@ricsam/formula-engine 0.2.8 → 0.2.10

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.
Files changed (130) hide show
  1. package/README.md +41 -3
  2. package/dist/cjs/core/engine.cjs +551 -166
  3. package/dist/cjs/core/engine.cjs.map +3 -3
  4. package/dist/cjs/core/managers/dependency-manager.cjs +151 -67
  5. package/dist/cjs/core/managers/dependency-manager.cjs.map +3 -3
  6. package/dist/cjs/core/managers/evaluation-manager.cjs.map +1 -1
  7. package/dist/cjs/core/managers/workbook-manager.cjs +197 -1
  8. package/dist/cjs/core/managers/workbook-manager.cjs.map +3 -3
  9. package/dist/cjs/core/mutation-invalidation.cjs +241 -0
  10. package/dist/cjs/core/mutation-invalidation.cjs.map +10 -0
  11. package/dist/cjs/core/types.cjs.map +2 -2
  12. package/dist/cjs/core/workbook-renamer.cjs.map +1 -1
  13. package/dist/cjs/evaluator/formula-evaluator.cjs +22 -48
  14. package/dist/cjs/evaluator/formula-evaluator.cjs.map +3 -3
  15. package/dist/cjs/functions/math/sum/summation-utils.cjs +2 -2
  16. package/dist/cjs/functions/math/sum/summation-utils.cjs.map +2 -2
  17. package/dist/cjs/lib.cjs +2 -13
  18. package/dist/cjs/lib.cjs.map +3 -3
  19. package/dist/cjs/package.json +1 -1
  20. package/dist/cjs/parser/formatter.cjs +3 -4
  21. package/dist/cjs/parser/formatter.cjs.map +3 -3
  22. package/dist/cjs/parser/parser.cjs +24 -216
  23. package/dist/cjs/parser/parser.cjs.map +3 -3
  24. package/dist/mjs/core/engine.mjs +565 -207
  25. package/dist/mjs/core/engine.mjs.map +3 -3
  26. package/dist/mjs/core/managers/dependency-manager.mjs +151 -67
  27. package/dist/mjs/core/managers/dependency-manager.mjs.map +3 -3
  28. package/dist/mjs/core/managers/evaluation-manager.mjs.map +1 -1
  29. package/dist/mjs/core/managers/workbook-manager.mjs +197 -1
  30. package/dist/mjs/core/managers/workbook-manager.mjs.map +3 -3
  31. package/dist/mjs/core/mutation-invalidation.mjs +201 -0
  32. package/dist/mjs/core/mutation-invalidation.mjs.map +10 -0
  33. package/dist/mjs/core/types.mjs.map +2 -2
  34. package/dist/mjs/core/workbook-renamer.mjs.map +1 -1
  35. package/dist/mjs/evaluator/formula-evaluator.mjs +22 -48
  36. package/dist/mjs/evaluator/formula-evaluator.mjs.map +3 -3
  37. package/dist/mjs/functions/math/sum/summation-utils.mjs +2 -2
  38. package/dist/mjs/functions/math/sum/summation-utils.mjs.map +2 -2
  39. package/dist/mjs/lib.mjs +2 -13
  40. package/dist/mjs/lib.mjs.map +3 -3
  41. package/dist/mjs/package.json +1 -1
  42. package/dist/mjs/parser/formatter.mjs +3 -4
  43. package/dist/mjs/parser/formatter.mjs.map +3 -3
  44. package/dist/mjs/parser/parser.mjs +24 -216
  45. package/dist/mjs/parser/parser.mjs.map +3 -3
  46. package/dist/types/core/engine.d.ts +31 -135
  47. package/dist/types/core/managers/dependency-manager.d.ts +5 -1
  48. package/dist/types/core/managers/evaluation-manager.d.ts +1 -1
  49. package/dist/types/core/managers/workbook-manager.d.ts +23 -1
  50. package/dist/types/core/mutation-invalidation.d.ts +46 -0
  51. package/dist/types/core/types.d.ts +35 -0
  52. package/dist/types/lib.d.ts +0 -8
  53. package/dist/types/parser/parser.d.ts +4 -6
  54. package/package.json +1 -1
  55. package/dist/cjs/core/commands/command-executor.cjs +0 -149
  56. package/dist/cjs/core/commands/command-executor.cjs.map +0 -10
  57. package/dist/cjs/core/commands/content-commands.cjs +0 -857
  58. package/dist/cjs/core/commands/content-commands.cjs.map +0 -10
  59. package/dist/cjs/core/commands/metadata-commands.cjs +0 -160
  60. package/dist/cjs/core/commands/metadata-commands.cjs.map +0 -10
  61. package/dist/cjs/core/commands/named-expression-commands.cjs +0 -363
  62. package/dist/cjs/core/commands/named-expression-commands.cjs.map +0 -10
  63. package/dist/cjs/core/commands/structure-commands.cjs +0 -696
  64. package/dist/cjs/core/commands/structure-commands.cjs.map +0 -10
  65. package/dist/cjs/core/commands/style-commands.cjs +0 -229
  66. package/dist/cjs/core/commands/style-commands.cjs.map +0 -10
  67. package/dist/cjs/core/commands/table-commands.cjs +0 -495
  68. package/dist/cjs/core/commands/table-commands.cjs.map +0 -10
  69. package/dist/cjs/core/commands/types.cjs +0 -99
  70. package/dist/cjs/core/commands/types.cjs.map +0 -10
  71. package/dist/cjs/core/managers/schema-manager.cjs +0 -374
  72. package/dist/cjs/core/managers/schema-manager.cjs.map +0 -10
  73. package/dist/cjs/core/schema/cell-orm.cjs +0 -76
  74. package/dist/cjs/core/schema/cell-orm.cjs.map +0 -10
  75. package/dist/cjs/core/schema/grid-orm.cjs +0 -125
  76. package/dist/cjs/core/schema/grid-orm.cjs.map +0 -10
  77. package/dist/cjs/core/schema/schema-builder.cjs +0 -74
  78. package/dist/cjs/core/schema/schema-builder.cjs.map +0 -10
  79. package/dist/cjs/core/schema/schema-helpers.cjs +0 -200
  80. package/dist/cjs/core/schema/schema-helpers.cjs.map +0 -10
  81. package/dist/cjs/core/schema/schema.cjs +0 -91
  82. package/dist/cjs/core/schema/schema.cjs.map +0 -10
  83. package/dist/cjs/core/schema/table-orm.cjs +0 -189
  84. package/dist/cjs/core/schema/table-orm.cjs.map +0 -10
  85. package/dist/mjs/core/commands/command-executor.mjs +0 -109
  86. package/dist/mjs/core/commands/command-executor.mjs.map +0 -10
  87. package/dist/mjs/core/commands/content-commands.mjs +0 -821
  88. package/dist/mjs/core/commands/content-commands.mjs.map +0 -10
  89. package/dist/mjs/core/commands/metadata-commands.mjs +0 -120
  90. package/dist/mjs/core/commands/metadata-commands.mjs.map +0 -10
  91. package/dist/mjs/core/commands/named-expression-commands.mjs +0 -323
  92. package/dist/mjs/core/commands/named-expression-commands.mjs.map +0 -10
  93. package/dist/mjs/core/commands/structure-commands.mjs +0 -661
  94. package/dist/mjs/core/commands/structure-commands.mjs.map +0 -10
  95. package/dist/mjs/core/commands/style-commands.mjs +0 -189
  96. package/dist/mjs/core/commands/style-commands.mjs.map +0 -10
  97. package/dist/mjs/core/commands/table-commands.mjs +0 -459
  98. package/dist/mjs/core/commands/table-commands.mjs.map +0 -10
  99. package/dist/mjs/core/commands/types.mjs +0 -59
  100. package/dist/mjs/core/commands/types.mjs.map +0 -10
  101. package/dist/mjs/core/managers/schema-manager.mjs +0 -334
  102. package/dist/mjs/core/managers/schema-manager.mjs.map +0 -10
  103. package/dist/mjs/core/schema/cell-orm.mjs +0 -35
  104. package/dist/mjs/core/schema/cell-orm.mjs.map +0 -10
  105. package/dist/mjs/core/schema/grid-orm.mjs +0 -84
  106. package/dist/mjs/core/schema/grid-orm.mjs.map +0 -10
  107. package/dist/mjs/core/schema/schema-builder.mjs +0 -34
  108. package/dist/mjs/core/schema/schema-builder.mjs.map +0 -10
  109. package/dist/mjs/core/schema/schema-helpers.mjs +0 -160
  110. package/dist/mjs/core/schema/schema-helpers.mjs.map +0 -10
  111. package/dist/mjs/core/schema/schema.mjs +0 -51
  112. package/dist/mjs/core/schema/schema.mjs.map +0 -10
  113. package/dist/mjs/core/schema/table-orm.mjs +0 -156
  114. package/dist/mjs/core/schema/table-orm.mjs.map +0 -10
  115. package/dist/types/core/commands/command-executor.d.ts +0 -81
  116. package/dist/types/core/commands/content-commands.d.ts +0 -172
  117. package/dist/types/core/commands/metadata-commands.d.ts +0 -55
  118. package/dist/types/core/commands/named-expression-commands.d.ts +0 -130
  119. package/dist/types/core/commands/structure-commands.d.ts +0 -155
  120. package/dist/types/core/commands/style-commands.d.ts +0 -76
  121. package/dist/types/core/commands/table-commands.d.ts +0 -119
  122. package/dist/types/core/commands/types.d.ts +0 -143
  123. package/dist/types/core/managers/schema-manager.d.ts +0 -142
  124. package/dist/types/core/schema/cell-orm.d.ts +0 -33
  125. package/dist/types/core/schema/grid-orm.d.ts +0 -63
  126. package/dist/types/core/schema/schema-builder.d.ts +0 -16
  127. package/dist/types/core/schema/schema-helpers.d.ts +0 -49
  128. package/dist/types/core/schema/schema.d.ts +0 -167
  129. package/dist/types/core/schema/schema.type-test.d.ts +0 -1
  130. package/dist/types/core/schema/table-orm.d.ts +0 -46
@@ -2,7 +2,7 @@
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/core/managers/evaluation-manager.ts"],
4
4
  "sourcesContent": [
5
- "import { flags } from \"../../debug/flags.cjs\";\nimport { AstEvaluationNode } from \"../../evaluator/dependency-nodes/ast-evaluation-node.cjs\";\nimport { CellValueNode } from \"../../evaluator/dependency-nodes/cell-value-node.cjs\";\nimport { EvaluationContext } from \"../../evaluator/evaluation-context.cjs\";\nimport {\n EvaluationError,\n SheetNotFoundError,\n} from \"../../evaluator/evaluation-error.cjs\";\nimport { RangeEvaluationNode } from \"../../evaluator/range-evaluation-node.cjs\";\nimport { normalizeSerializedCellValue } from \"../../parser/formatter.cjs\";\nimport { FormulaEvaluator } from \"../../evaluator/formula-evaluator.cjs\";\nimport {\n FormulaError,\n type CellAddress,\n type CellInRangeResult,\n type CellValue,\n type ErrorEvaluationResult,\n type EvaluateAllCellsResult,\n type EvaluationOrder,\n type FunctionEvaluationResult,\n type SerializedCellValue,\n type SingleEvaluationResult,\n type SpreadsheetRange,\n type ValueEvaluationResult,\n} from \"../types.cjs\";\nimport {\n captureEvaluationErrors,\n getAbsoluteRange,\n cellAddressToKey,\n checkRangeIntersection,\n getCellReference,\n getRangeIntersection,\n getRelativeRange,\n isCellInRange,\n parseCellReference,\n rangeAddressToKey,\n} from \"../utils.cjs\";\nimport type { DependencyManager } from \"./dependency-manager.cjs\";\nimport type { WorkbookManager } from \"./workbook-manager.cjs\";\nimport { SpillMetaNode } from \"../../evaluator/dependency-nodes/spill-meta-node.cjs\";\nimport { EmptyCellEvaluationNode } from \"../../evaluator/dependency-nodes/empty-cell-evaluation-node.cjs\";\nimport type { TableManager } from \"./table-manager.cjs\";\nimport type { DependencyNode } from \"./dependency-node.cjs\";\nimport { VirtualCellValueNode } from \"../../evaluator/dependency-nodes/virtual-cell-value-node.cjs\";\nimport { ResourceDependencyNode } from \"../../evaluator/dependency-nodes/resource-dependency-node.cjs\";\nimport type {\n NodeSnapshotId,\n SerializedCellInRangeResultSnapshot,\n SerializedErrorEvaluationResultSnapshot,\n SerializedEvaluateAllCellsResultSnapshot,\n SerializedFunctionEvaluationResultSnapshot,\n SerializedSingleEvaluationResultSnapshot,\n SerializedSpillMetaEvaluationResultSnapshot,\n SerializedSpilledValuesEvaluationResultSnapshot,\n} from \"../engine-snapshot.cjs\";\nimport type { MutationInvalidation } from \"../commands/types.cjs\";\n\nexport class EvaluationManager {\n private isEvaluating = false;\n\n constructor(\n private workbookManager: WorkbookManager,\n private tableManager: TableManager,\n private formulaEvaluator: FormulaEvaluator,\n private dependencyManager: DependencyManager\n ) {}\n\n clearEvaluationCache(): void {\n this.dependencyManager.clearEvaluationCache();\n }\n\n private dependsOnNode(\n candidate: DependencyNode,\n target: DependencyNode,\n visited: Set<DependencyNode> = new Set()\n ): boolean {\n if (candidate === target) {\n return true;\n }\n\n if (visited.has(candidate)) {\n return false;\n }\n visited.add(candidate);\n\n for (const dep of candidate.getDependencies()) {\n if (this.dependsOnNode(dep, target, visited)) {\n return true;\n }\n }\n\n return false;\n }\n\n invalidateFromMutation(footprint: MutationInvalidation): void {\n this.dependencyManager.invalidateFromMutation(footprint);\n }\n\n evaluationResultToSerializedValue(\n evaluation: SingleEvaluationResult,\n cellAddress: CellAddress,\n debug?: boolean\n ): SerializedCellValue {\n if (\n evaluation.type !== \"error\" &&\n evaluation.type !== \"awaiting-evaluation\"\n ) {\n const value = evaluation.result;\n\n return value.type === \"infinity\"\n ? value.sign === \"positive\"\n ? \"INFINITY\"\n : \"-INFINITY\"\n : value.value;\n }\n\n if (evaluation.type === \"awaiting-evaluation\") {\n return (\n evaluation.errAddress.key +\n \" is awaiting evaluation of \" +\n evaluation.waitingFor.key\n );\n }\n\n if (debug) {\n const errAddress = evaluation.errAddress.key;\n if (errAddress === cellAddressToKey(cellAddress)) {\n return evaluation.err + \" \" + evaluation.message;\n }\n return (\n evaluation.err +\n \" in \" +\n evaluation.errAddress.key +\n \" \" +\n evaluation.message\n );\n }\n\n return evaluation.err;\n }\n\n private buildSnapshotOrigin(\n node: CellValueNode | SpillMetaNode | AstEvaluationNode\n ): CellAddress {\n if (\"cellAddress\" in node) {\n return node.cellAddress;\n }\n\n const contextDependency = node.getContextDependency();\n return {\n workbookName: contextDependency.workbookName ?? \"__snapshot__\",\n sheetName: contextDependency.sheetName ?? \"__snapshot__\",\n colIndex: contextDependency.colIndex ?? 0,\n rowIndex: contextDependency.rowIndex ?? 0,\n };\n }\n\n private serializeErrorEvaluationResultSnapshot(\n evaluation: Exclude<ErrorEvaluationResult, { type: \"awaiting-evaluation\" }>,\n getNodeSnapshotId: (node: DependencyNode) => NodeSnapshotId\n ): SerializedErrorEvaluationResultSnapshot {\n return {\n type: \"error\",\n err: evaluation.err,\n message: evaluation.message,\n errAddressId: getNodeSnapshotId(evaluation.errAddress),\n sourceCell: evaluation.sourceCell,\n };\n }\n\n serializeSingleEvaluationResultSnapshot(\n evaluation: SingleEvaluationResult,\n getNodeSnapshotId: (node: DependencyNode) => NodeSnapshotId\n ): SerializedSingleEvaluationResultSnapshot | undefined {\n if (evaluation.type === \"awaiting-evaluation\") {\n return undefined;\n }\n\n if (evaluation.type === \"error\") {\n return this.serializeErrorEvaluationResultSnapshot(\n evaluation,\n getNodeSnapshotId\n );\n }\n\n return {\n type: \"value\",\n result: evaluation.result,\n sourceCell: evaluation.sourceCell,\n };\n }\n\n deserializeSingleEvaluationResultSnapshot(\n evaluation: SerializedSingleEvaluationResultSnapshot,\n resolveNodeSnapshotId: (nodeId: NodeSnapshotId) => DependencyNode\n ): SingleEvaluationResult {\n if (evaluation.type === \"error\") {\n return {\n type: \"error\",\n err: evaluation.err,\n message: evaluation.message,\n errAddress: resolveNodeSnapshotId(evaluation.errAddressId),\n sourceCell: evaluation.sourceCell,\n };\n }\n\n return {\n type: \"value\",\n result: evaluation.result,\n sourceCell: evaluation.sourceCell,\n };\n }\n\n serializeEvaluateAllCellsResultSnapshot(\n evaluation: EvaluateAllCellsResult,\n getNodeSnapshotId: (node: DependencyNode) => NodeSnapshotId\n ): SerializedEvaluateAllCellsResultSnapshot | undefined {\n if (evaluation.type === \"awaiting-evaluation\") {\n return undefined;\n }\n\n if (evaluation.type === \"error\") {\n return this.serializeErrorEvaluationResultSnapshot(\n evaluation,\n getNodeSnapshotId\n );\n }\n\n const values: SerializedCellInRangeResultSnapshot[] = [];\n for (const value of evaluation.values) {\n const serialized = this.serializeSingleEvaluationResultSnapshot(\n value.result,\n getNodeSnapshotId\n );\n if (!serialized) {\n return undefined;\n }\n values.push({\n relativePos: value.relativePos,\n result: serialized,\n });\n }\n\n return {\n type: \"values\",\n values,\n };\n }\n\n deserializeEvaluateAllCellsResultSnapshot(\n evaluation: SerializedEvaluateAllCellsResultSnapshot,\n resolveNodeSnapshotId: (nodeId: NodeSnapshotId) => DependencyNode\n ): EvaluateAllCellsResult {\n if (evaluation.type === \"error\") {\n return this.deserializeSingleEvaluationResultSnapshot(\n evaluation,\n resolveNodeSnapshotId\n ) as ErrorEvaluationResult;\n }\n\n return {\n type: \"values\",\n values: evaluation.values.map((value) => ({\n relativePos: value.relativePos,\n result: this.deserializeSingleEvaluationResultSnapshot(\n value.result,\n resolveNodeSnapshotId\n ),\n })),\n };\n }\n\n serializeFunctionEvaluationResultSnapshot(\n evaluation: FunctionEvaluationResult,\n options: {\n sourceNode: CellValueNode | SpillMetaNode | AstEvaluationNode;\n getNodeSnapshotId: (node: DependencyNode) => NodeSnapshotId;\n }\n ): SerializedFunctionEvaluationResultSnapshot | undefined {\n if (evaluation.type !== \"spilled-values\") {\n return this.serializeSingleEvaluationResultSnapshot(\n evaluation,\n options.getNodeSnapshotId\n );\n }\n\n const origin = this.buildSnapshotOrigin(options.sourceNode);\n const spillArea = evaluation.spillArea(origin);\n const relativeSpillArea = getRelativeRange(spillArea, {\n colIndex: origin.colIndex,\n rowIndex: origin.rowIndex,\n });\n\n if (evaluation.sourceRange) {\n return {\n type: \"spilled-values\",\n spill: {\n kind: \"source-range\",\n relativeSpillArea,\n source: evaluation.source,\n sourceCell: evaluation.sourceCell,\n sourceRange: evaluation.sourceRange,\n },\n };\n }\n\n if (\n relativeSpillArea.width.type !== \"number\" ||\n relativeSpillArea.height.type !== \"number\"\n ) {\n return undefined;\n }\n\n const context = new EvaluationContext(\n this.tableManager,\n options.sourceNode,\n origin\n );\n const values: SerializedCellInRangeResultSnapshot[] = [];\n\n for (let y = 0; y < relativeSpillArea.height.value; y++) {\n for (let x = 0; x < relativeSpillArea.width.value; x++) {\n const result = captureEvaluationErrors(options.sourceNode, () =>\n evaluation.evaluate({ x, y }, context)\n );\n const serialized = this.serializeSingleEvaluationResultSnapshot(\n result,\n options.getNodeSnapshotId\n );\n if (!serialized) {\n return undefined;\n }\n values.push({\n relativePos: { x, y },\n result: serialized,\n });\n }\n }\n\n return {\n type: \"spilled-values\",\n spill: {\n kind: \"materialized\",\n relativeSpillArea,\n source: evaluation.source,\n sourceCell: evaluation.sourceCell,\n sourceRange: evaluation.sourceRange,\n values,\n },\n };\n }\n\n deserializeFunctionEvaluationResultSnapshot(\n evaluation: SerializedFunctionEvaluationResultSnapshot,\n resolveNodeSnapshotId: (nodeId: NodeSnapshotId) => DependencyNode\n ): FunctionEvaluationResult {\n if (evaluation.type !== \"spilled-values\") {\n return this.deserializeSingleEvaluationResultSnapshot(\n evaluation,\n resolveNodeSnapshotId\n );\n }\n\n const spillSnapshot = evaluation.spill;\n if (spillSnapshot.kind === \"materialized\") {\n const values = new Map(\n spillSnapshot.values.map((value) => [\n `${value.relativePos.x},${value.relativePos.y}`,\n this.deserializeSingleEvaluationResultSnapshot(\n value.result,\n resolveNodeSnapshotId\n ),\n ])\n );\n\n return {\n type: \"spilled-values\",\n source: spillSnapshot.source,\n sourceCell: spillSnapshot.sourceCell,\n sourceRange: spillSnapshot.sourceRange,\n spillArea: (origin) =>\n getAbsoluteRange(spillSnapshot.relativeSpillArea, {\n colIndex: origin.colIndex,\n rowIndex: origin.rowIndex,\n }),\n evaluate: (spillOffset) =>\n values.get(`${spillOffset.x},${spillOffset.y}`) ?? {\n type: \"value\",\n result: this.convertScalarValueToCellValue(\"\"),\n },\n evaluateAllCells: () => ({\n type: \"values\",\n values: spillSnapshot.values.map((value) => ({\n relativePos: value.relativePos,\n result: this.deserializeSingleEvaluationResultSnapshot(\n value.result,\n resolveNodeSnapshotId\n ),\n })),\n }),\n };\n }\n\n return {\n type: \"spilled-values\",\n source: spillSnapshot.source,\n sourceCell: spillSnapshot.sourceCell,\n sourceRange: spillSnapshot.sourceRange,\n spillArea: (origin) =>\n getAbsoluteRange(spillSnapshot.relativeSpillArea, {\n colIndex: origin.colIndex,\n rowIndex: origin.rowIndex,\n }),\n evaluate: (spillOffset, context) => {\n const cellAddress: CellAddress = {\n workbookName: spillSnapshot.sourceRange.workbookName,\n sheetName: spillSnapshot.sourceRange.sheetName,\n colIndex: spillSnapshot.sourceRange.range.start.col + spillOffset.x,\n rowIndex: spillSnapshot.sourceRange.range.start.row + spillOffset.y,\n };\n\n const evalNode = this.dependencyManager.getCellValueOrEmptyCellNode(\n cellAddressToKey(cellAddress)\n );\n context.dependencyNode.addDependency(evalNode);\n return evalNode.evaluationResult;\n },\n evaluateAllCells: ({ intersection, context, origin }) => {\n let range = spillSnapshot.sourceRange.range;\n if (intersection) {\n const relativeRange = getRelativeRange(intersection, origin);\n const projectedIntersection = getAbsoluteRange(relativeRange, {\n colIndex: spillSnapshot.sourceRange.range.start.col,\n rowIndex: spillSnapshot.sourceRange.range.start.row,\n });\n const nextRange = getRangeIntersection(\n spillSnapshot.sourceRange.range,\n projectedIntersection\n );\n if (nextRange) {\n range = nextRange;\n }\n }\n\n const rangeAddress = {\n workbookName: spillSnapshot.sourceRange.workbookName,\n sheetName: spillSnapshot.sourceRange.sheetName,\n range,\n };\n\n const rangeNode = this.dependencyManager.getRangeNode(\n rangeAddressToKey(rangeAddress)\n );\n context.dependencyNode.addDependency(rangeNode);\n return rangeNode.result;\n },\n };\n }\n\n serializeSpillMetaEvaluationResultSnapshot(\n evaluation: SpillMetaNode[\"evaluationResult\"],\n options: {\n sourceNode: CellValueNode | SpillMetaNode | AstEvaluationNode;\n getNodeSnapshotId: (node: DependencyNode) => NodeSnapshotId;\n }\n ): SerializedSpillMetaEvaluationResultSnapshot | undefined {\n if (evaluation.type === \"does-not-spill\") {\n return { type: \"does-not-spill\" };\n }\n\n if (evaluation.type === \"error\") {\n return this.serializeErrorEvaluationResultSnapshot(\n evaluation,\n options.getNodeSnapshotId\n );\n }\n\n const serialized = this.serializeFunctionEvaluationResultSnapshot(\n evaluation,\n options\n );\n if (!serialized || serialized.type !== \"spilled-values\") {\n return undefined;\n }\n\n return serialized;\n }\n\n deserializeSpillMetaEvaluationResultSnapshot(\n evaluation: SerializedSpillMetaEvaluationResultSnapshot,\n resolveNodeSnapshotId: (nodeId: NodeSnapshotId) => DependencyNode\n ): SpillMetaNode[\"evaluationResult\"] {\n if (evaluation.type === \"does-not-spill\") {\n return evaluation;\n }\n\n if (evaluation.type === \"error\") {\n return this.deserializeSingleEvaluationResultSnapshot(\n evaluation,\n resolveNodeSnapshotId\n ) as SpillMetaNode[\"evaluationResult\"];\n }\n\n return this.deserializeFunctionEvaluationResultSnapshot(\n evaluation,\n resolveNodeSnapshotId\n ) as SpillMetaNode[\"evaluationResult\"];\n }\n\n evaluateEmptyCell(node: EmptyCellEvaluationNode): void {\n if (node.resolved) {\n const result = node.evaluationResult;\n if (result && result.type !== \"awaiting-evaluation\") {\n return;\n }\n }\n\n this.dependencyManager.unregisterNode(node);\n node.resetDirectDepsUpdated();\n\n const ctx = new EvaluationContext(\n this.tableManager,\n node,\n node.cellAddress\n );\n const inSpilled = this.dependencyManager.getSpillValue(node.cellAddress);\n\n if (inSpilled) {\n // if we are spilling then we can just add the spill origin as a dependency and evaluate the spilled value\n const spillTarget = this.dependencyManager.getSpilledAddress(\n node.cellAddress,\n inSpilled\n );\n const spillOriginKey = cellAddressToKey(inSpilled.origin).replace(\n /^[^:]+:/,\n \"spill-meta:\"\n );\n const spillMetaNode =\n this.dependencyManager.getSpillMetaNode(spillOriginKey);\n node.addDependency(spillMetaNode);\n const result = spillMetaNode.evaluationResult;\n if (result.type === \"spilled-values\") {\n // let's evaluate the spilled value to extract dependencies\n const evaluation = captureEvaluationErrors(spillMetaNode, () => {\n return result.evaluate(spillTarget.spillOffset, ctx);\n });\n node.setEvaluationResult(evaluation);\n }\n } else {\n // upgrade any frontier dependencies that spill into the range\n node.upgradeFrontierDependencies();\n\n const evaluationResult: SingleEvaluationResult = {\n type: \"value\",\n result: this.convertScalarValueToCellValue(\"\"),\n };\n // for now let's just store the empty value, the next time the cell is evaluated isSpilled will be true and the spilled value will be evaluated\n node.setEvaluationResult(evaluationResult);\n }\n\n this.dependencyManager.registerNode(node);\n }\n\n evaluateRangeNode(node: RangeEvaluationNode): void {\n if (node.resolved) {\n return;\n }\n\n this.dependencyManager.unregisterNode(node);\n node.resetDirectDepsUpdated();\n\n const result = captureEvaluationErrors(node, (): EvaluateAllCellsResult => {\n node.upgradeFrontierDependencies();\n\n const evalOrder = node.getRangeEvalOrder();\n const circularEntryCache = new Map<DependencyNode, boolean>();\n const shouldSkipCircularEntry = (candidate: DependencyNode) => {\n const cached = circularEntryCache.get(candidate);\n if (cached !== undefined) {\n return cached;\n }\n\n // If a cell inside the range depends back on the range itself, including\n // its current value would count a circular result back into the same\n // aggregate on a later rerun.\n const isCircular = this.dependsOnNode(candidate, node);\n circularEntryCache.set(candidate, isCircular);\n return isCircular;\n };\n\n const results: CellInRangeResult[] = [];\n\n for (const entry of evalOrder) {\n if (entry.type === \"value\") {\n if (shouldSkipCircularEntry(entry.node)) {\n continue;\n }\n\n const entryAddress = entry.address;\n const result = entry.node.evaluationResult;\n\n const relativePos = {\n x: entryAddress.colIndex - node.address.range.start.col,\n y: entryAddress.rowIndex - node.address.range.start.row,\n };\n\n results.push({ result: result, relativePos });\n } else if (\n entry.type === \"empty_cell\" ||\n entry.type === \"empty_range\"\n ) {\n for (const candidateNode of entry.candidates) {\n if (shouldSkipCircularEntry(candidateNode)) {\n continue;\n }\n\n if (candidateNode.evaluationResult.type === \"spilled-values\") {\n const spillArea = candidateNode.evaluationResult.spillArea(\n candidateNode.cellAddress\n );\n if (entry.type === \"empty_range\") {\n const intersects = checkRangeIntersection(\n spillArea,\n entry.address.range\n );\n if (intersects) {\n // When a spilled range intersects with our target range, we need to evaluate\n // only the cells that fall within the intersection area.\n //\n // Example: If cell A10 contains a spilled range that covers A10:B11,\n // and our target range is B10:INFINITY, then we only want to evaluate\n // the intersection B10:B11 from the spilled range.\n //\n // The evaluateAllCells method expects the intersection to be passed\n // so it can limit evaluation to only the relevant cells.\n const ctx = new EvaluationContext(\n this.tableManager,\n node,\n candidateNode.cellAddress\n );\n const spilledResults =\n candidateNode.evaluationResult.evaluateAllCells.call(\n this.formulaEvaluator,\n {\n context: ctx,\n evaluate: candidateNode.evaluationResult.evaluate,\n intersection: entry.address.range,\n origin: candidateNode.cellAddress,\n lookupOrder: \"col-major\",\n }\n );\n\n if (spilledResults.type === \"values\") {\n results.push(...spilledResults.values);\n } else {\n return spilledResults;\n }\n }\n } else {\n const intersects = isCellInRange(entry.address, spillArea);\n if (intersects) {\n // When a spilled range intersects with our target range, we need to evaluate\n // only the cells that fall within the intersection area.\n //\n // Example: If cell A10 contains a spilled range that covers A10:B11,\n // and our target range is B10:INFINITY, then we only want to evaluate\n // the intersection B10:B11 from the spilled range.\n //\n // The evaluateAllCells method expects the intersection to be passed\n // so it can limit evaluation to only the relevant cells.\n\n const relativePos = {\n x:\n entry.address.colIndex -\n candidateNode.cellAddress.colIndex,\n y:\n entry.address.rowIndex -\n candidateNode.cellAddress.rowIndex,\n };\n const ctx = new EvaluationContext(\n this.tableManager,\n node,\n candidateNode.cellAddress\n );\n const spilledResult = candidateNode.evaluationResult.evaluate(\n relativePos,\n ctx\n );\n\n results.push({\n relativePos: {\n x: entry.address.colIndex - node.address.range.start.col,\n y: entry.address.rowIndex - node.address.range.start.row,\n },\n result: spilledResult,\n });\n }\n }\n }\n }\n }\n }\n\n return {\n type: \"values\",\n values: results,\n };\n });\n\n node.setResult(result);\n this.dependencyManager.registerNode(node);\n }\n\n evaluateCellNode(\n node: CellValueNode | SpillMetaNode | VirtualCellValueNode\n ): void {\n // Enable caching for resolved nodes\n if (node.resolved) {\n return;\n }\n\n const finalizePersistentNode = () => {\n if (node instanceof VirtualCellValueNode) {\n return;\n }\n\n this.dependencyManager.registerNode(node);\n };\n\n if (!(node instanceof VirtualCellValueNode)) {\n this.dependencyManager.unregisterNode(node);\n }\n node.resetDirectDepsUpdated();\n\n const ctx = new EvaluationContext(\n this.tableManager,\n node,\n node.cellAddress\n );\n\n if (node instanceof CellValueNode && node.spillMeta) {\n // we are evaluating a e.g. A1 in A1=SEQUENCE(10), where we want the value in the cell in A1, i.e. 1\n // As A1 is already pointing to a spill meta node, everything has been setup already,\n // we just need to evaluate the spill origin and assign the result to the currentDepNode\n const spillOrigin = node.spillMeta;\n if (spillOrigin.evaluationResult.type === \"spilled-values\") {\n const result = spillOrigin.evaluationResult.evaluate(\n { x: 0, y: 0 },\n ctx\n );\n node.setEvaluationResult(result);\n finalizePersistentNode();\n return;\n }\n }\n\n let content: SerializedCellValue;\n try {\n if (node instanceof VirtualCellValueNode) {\n content = node.cellValue;\n } else {\n content = this.workbookManager.getSerializedCellValue(node.cellAddress);\n }\n } catch (err) {\n const evaluationResult: ErrorEvaluationResult = {\n type: \"error\",\n err: FormulaError.ERROR,\n message: \"Syntax error\",\n errAddress: node,\n };\n node.setEvaluationResult(evaluationResult);\n if (!(node instanceof VirtualCellValueNode)) {\n this.dependencyManager.registerNode(node);\n }\n return;\n }\n\n if (typeof content !== \"string\" || !content.startsWith(\"=\")) {\n if (node instanceof SpillMetaNode) {\n node.setEvaluationResult({\n type: \"does-not-spill\",\n });\n finalizePersistentNode();\n return;\n }\n // Static value cells cannot have frontier dependencies\n const result: ValueEvaluationResult = {\n type: \"value\",\n result: this.convertScalarValueToCellValue(content),\n };\n node.setEvaluationResult(result);\n finalizePersistentNode();\n return;\n }\n\n let evaluation: FunctionEvaluationResult = captureEvaluationErrors(\n node,\n () => this.formulaEvaluator.evaluateFormula(content.slice(1), ctx)\n );\n\n // the evaluated cell IS A spilling formula, e.g. if dependencyKey points to A1, then the formula is e.g. A1=SEQUENCE(10), or A1=A3:B5\n if (evaluation.type === \"spilled-values\") {\n const spillArea = evaluation.spillArea(node.cellAddress);\n\n if (!this.canSpill(node.cellAddress, spillArea)) {\n // Override evaluation with SPILL error, but continue execution to set up nodes\n evaluation = {\n type: \"error\",\n err: FormulaError.SPILL,\n message: \"Cannot spill - area is blocked\",\n errAddress: node,\n };\n } else {\n // Spill succeeds - register it\n this.dependencyManager.setSpilledValue(node.key, {\n spillOnto: spillArea,\n origin: node.cellAddress,\n });\n }\n\n // Set up spill meta node and evaluation results (even if spill failed)\n if (node instanceof SpillMetaNode) {\n // we have already setup an origin/spill meta node relationship,\n // so we are just reevaluating the spill meta node here\n node.setEvaluationResult(evaluation);\n finalizePersistentNode();\n } else {\n const spillMetaNode = this.dependencyManager.getSpillMetaNode(\n node.key.replace(/^[^:]+:/, \"spill-meta:\")\n );\n\n node.addDependency(spillMetaNode);\n node.setSpillMetaNode(spillMetaNode);\n spillMetaNode.setEvaluationResult(evaluation);\n this.dependencyManager.registerNode(spillMetaNode);\n\n if (evaluation.type === \"spilled-values\") {\n const originResult = evaluation.evaluate({ x: 0, y: 0 }, ctx);\n node.setEvaluationResult(originResult);\n } else {\n // Spill failed - set error on origin cell\n node.setEvaluationResult(evaluation);\n }\n }\n finalizePersistentNode();\n return;\n }\n\n if (evaluation.type === \"value\") {\n if (node instanceof SpillMetaNode) {\n node.setEvaluationResult({\n type: \"does-not-spill\",\n });\n finalizePersistentNode();\n return;\n } else {\n node.setEvaluationResult(evaluation);\n finalizePersistentNode();\n return;\n }\n }\n\n node.setEvaluationResult(evaluation);\n finalizePersistentNode();\n }\n\n evaluateDependencyNode(dependency: DependencyNode): void {\n if (dependency instanceof EmptyCellEvaluationNode) {\n this.evaluateEmptyCell(dependency);\n return;\n }\n if (dependency instanceof RangeEvaluationNode) {\n this.evaluateRangeNode(dependency);\n return;\n }\n if (\n dependency instanceof CellValueNode ||\n dependency instanceof VirtualCellValueNode\n ) {\n this.evaluateCellNode(dependency);\n return;\n }\n if (dependency instanceof AstEvaluationNode) {\n return;\n }\n if (dependency instanceof ResourceDependencyNode) {\n return;\n }\n if (dependency instanceof SpillMetaNode) {\n this.evaluateCellNode(dependency);\n return;\n }\n throw new Error(\"Invalid dependency: \" + (dependency as any).key);\n }\n\n /**\n * User exposed method to evaluate a formula\n */\n evaluateFormula(\n /**\n * formula for example\n */\n cellValue: SerializedCellValue,\n cellAddress: CellAddress\n ): SerializedCellValue {\n if (this.isEvaluating) {\n throw new Error(\"Evaluation in progress\");\n }\n\n const node = this.dependencyManager.getVirtualCellValueNode(\n cellAddress,\n cellValue\n );\n\n if (node.evaluationResult.type === \"awaiting-evaluation\") {\n this.evaluateCell(node);\n }\n\n const result = node.evaluationResult;\n\n return this.evaluationResultToSerializedValue(result, cellAddress);\n }\n\n /**\n * Evaluates a cell by building the evaluation order and evaluating the dependencies in order\n */\n evaluateCell(\n node: CellValueNode | EmptyCellEvaluationNode | VirtualCellValueNode\n ): void {\n if (this.isEvaluating) {\n throw new Error(\"Evaluation in progress\");\n }\n this.isEvaluating = true;\n\n let precalculatedPlan: EvaluationOrder | undefined;\n\n let requiresReRun = true;\n while (requiresReRun) {\n requiresReRun = false;\n\n // Use DependencyManager to build evaluation order\n const evaluationPlan =\n precalculatedPlan ?? this.dependencyManager.buildEvaluationOrder(node);\n\n if (evaluationPlan.hasCycle) {\n const evaluationResult: ErrorEvaluationResult = {\n type: \"error\",\n err: FormulaError.CYCLE,\n message: Array.from(evaluationPlan.cycleNodes ?? [])\n .map((node) => node.key)\n .join(\" -> \"),\n errAddress: node,\n };\n // cycle detected\n if (evaluationPlan.cycleNodes) {\n for (const node of evaluationPlan.cycleNodes) {\n if (\n !(node instanceof RangeEvaluationNode) &&\n !(node instanceof ResourceDependencyNode)\n ) {\n node.setEvaluationResult(evaluationResult);\n }\n }\n }\n this.isEvaluating = false;\n }\n\n // Evaluate all dependencies in order\n const timeStart = performance.now();\n const durations: { duration: number; key: string }[] = [];\n let numResolved = 0;\n if (flags.isProfiling && evaluationPlan.evaluationOrder.size > -1) {\n // console.profile();\n }\n evaluationPlan.evaluationOrder.forEach((dependency) => {\n const start = performance.now();\n if (dependency.resolved) {\n numResolved++;\n }\n this.evaluateDependencyNode(dependency);\n\n const end = performance.now();\n if (flags.isProfiling && evaluationPlan.evaluationOrder.size > -1) {\n durations.push({ duration: end - start, key: dependency.key });\n }\n });\n if (flags.isProfiling && evaluationPlan.evaluationOrder.size > -1) {\n // console.profileEnd();\n }\n if (flags.isProfiling && evaluationPlan.evaluationOrder.size > -1) {\n const percentResolved = Math.round(\n (100 * numResolved) / evaluationPlan.evaluationOrder.size\n );\n const avgDuration =\n durations.reduce((a, b) => a + b.duration, 0) / durations.length || 0;\n console.log(\n `%c[Evaluation] %c${evaluationPlan.evaluationOrder.size} deps | %c${(\n performance.now() - timeStart\n ).toFixed(\n 1\n )}ms | %c${percentResolved}% resolved | %c${avgDuration.toFixed(\n 2\n )}ms avg`,\n \"color:#83aaff;font-weight:bold;\",\n \"color:#fff;font-weight:bold;\",\n \"color:#7fff9e\",\n \"color:#85baff\",\n \"color:#ffdfa3\"\n );\n }\n\n this.dependencyManager.markResolvedNodes(node);\n\n const nextEvaluationPlan =\n this.dependencyManager.buildEvaluationOrder(node);\n\n this.dependencyManager.updateResolvedSCCs(nextEvaluationPlan);\n\n precalculatedPlan = nextEvaluationPlan;\n\n // Check if new dependencies were discovered during evaluation\n if (nextEvaluationPlan.hash !== evaluationPlan.hash) {\n requiresReRun = true;\n } else {\n this.isEvaluating = false;\n return;\n }\n }\n this.isEvaluating = false;\n }\n\n convertScalarValueToCellValue(val: SerializedCellValue): CellValue {\n if (val === \"INFINITY\") {\n return { type: \"infinity\", sign: \"positive\" };\n }\n if (val === \"-INFINITY\") {\n return { type: \"infinity\", sign: \"negative\" };\n }\n if (typeof val === \"number\") {\n return { type: \"number\", value: val };\n }\n if (typeof val === \"boolean\") {\n return { type: \"boolean\", value: val };\n }\n if (typeof val === \"undefined\") {\n return { type: \"string\", value: \"\" };\n }\n return { type: \"string\", value: val };\n }\n\n // todo optimize using workbook manager\n canSpill(spillCandidate: CellAddress, spillArea: SpreadsheetRange): boolean {\n // Check if the spill origin cell is inside a table - spilling formulas cannot exist in tables\n if (this.tableManager.isCellInTable(spillCandidate)) {\n return false;\n }\n\n // Check if the spill area would intersect with any table - formulas cannot spill into tables\n if (\n this.tableManager.doesRangeIntersectTable(\n spillCandidate.workbookName,\n spillCandidate.sheetName,\n spillArea\n )\n ) {\n return false;\n }\n\n const sheet = this.workbookManager.getSheet(spillCandidate);\n if (!sheet) {\n throw new SheetNotFoundError(spillCandidate.sheetName);\n }\n const cellId = getCellReference(spillCandidate);\n const content = sheet.content.get(cellId);\n if (!content) {\n throw new EvaluationError(FormulaError.REF, `Cell not found: ${cellId}`);\n }\n for (const spilledValue of this.dependencyManager.spilledValues) {\n if (\n spilledValue.origin.workbookName !== spillCandidate.workbookName ||\n spilledValue.origin.sheetName !== spillCandidate.sheetName\n ) {\n continue;\n }\n if (\n spilledValue.origin.colIndex === spillCandidate.colIndex &&\n spilledValue.origin.rowIndex === spillCandidate.rowIndex\n ) {\n // we are already have a spill, this one will be replaced\n continue;\n }\n\n if (checkRangeIntersection(spillArea, spilledValue.spillOnto)) {\n return false;\n }\n }\n // let's just check the raw data if there is something in the range\n for (const key of sheet.content.keys()) {\n const cellAddress = parseCellReference(key);\n const endCol = spillArea.end.col;\n const endRow = spillArea.end.row;\n\n if (\n cellAddress.colIndex === spillCandidate.colIndex &&\n cellAddress.rowIndex === spillCandidate.rowIndex\n ) {\n continue;\n }\n\n if (endCol.type === \"number\" && endRow.type === \"number\") {\n if (\n cellAddress.colIndex >= spillArea.start.col &&\n cellAddress.colIndex <= endCol.value &&\n cellAddress.rowIndex >= spillArea.start.row &&\n cellAddress.rowIndex <= endRow.value\n ) {\n if (\n normalizeSerializedCellValue(sheet.content.get(key)) !== undefined\n ) {\n // there is something in the range, so we can't spill\n return false;\n }\n }\n }\n }\n\n return true;\n }\n\n getCellEvaluationResult(\n cellAddress: CellAddress\n ): SingleEvaluationResult | undefined {\n if (this.isEvaluating) {\n throw new Error(\"Evaluation in progress\");\n }\n\n const nodeKey = cellAddressToKey(cellAddress);\n const node = this.dependencyManager.getCellValueOrEmptyCellNode(nodeKey);\n\n const sheet = this.workbookManager.getSheet(cellAddress);\n if (!sheet) {\n throw new SheetNotFoundError(cellAddress.sheetName);\n }\n\n if (node.evaluationResult.type === \"awaiting-evaluation\") {\n // if (cellAddressToKey(cellAddress).includes(\"G10\")) {\n // console.group(\"Evaluation of G10\");\n // flags.isProfiling = true;\n // console.time(\"Evaluation of G10\");\n // console.profile(\"Evaluation of G10\");\n // }\n this.evaluateCell(node);\n // if (flags.isProfiling) {\n // flags.isProfiling = false;\n // console.timeEnd(\"Evaluation of G10\");\n // console.profileEnd(\"Evaluation of G10\");\n // console.groupEnd();\n // }\n }\n\n const result = node.evaluationResult;\n\n return result;\n }\n}\n"
5
+ "import { flags } from \"../../debug/flags.cjs\";\nimport { AstEvaluationNode } from \"../../evaluator/dependency-nodes/ast-evaluation-node.cjs\";\nimport { CellValueNode } from \"../../evaluator/dependency-nodes/cell-value-node.cjs\";\nimport { EvaluationContext } from \"../../evaluator/evaluation-context.cjs\";\nimport {\n EvaluationError,\n SheetNotFoundError,\n} from \"../../evaluator/evaluation-error.cjs\";\nimport { RangeEvaluationNode } from \"../../evaluator/range-evaluation-node.cjs\";\nimport { normalizeSerializedCellValue } from \"../../parser/formatter.cjs\";\nimport { FormulaEvaluator } from \"../../evaluator/formula-evaluator.cjs\";\nimport {\n FormulaError,\n type CellAddress,\n type CellInRangeResult,\n type CellValue,\n type ErrorEvaluationResult,\n type EvaluateAllCellsResult,\n type EvaluationOrder,\n type FunctionEvaluationResult,\n type SerializedCellValue,\n type SingleEvaluationResult,\n type SpreadsheetRange,\n type ValueEvaluationResult,\n} from \"../types.cjs\";\nimport {\n captureEvaluationErrors,\n getAbsoluteRange,\n cellAddressToKey,\n checkRangeIntersection,\n getCellReference,\n getRangeIntersection,\n getRelativeRange,\n isCellInRange,\n parseCellReference,\n rangeAddressToKey,\n} from \"../utils.cjs\";\nimport type { DependencyManager } from \"./dependency-manager.cjs\";\nimport type { WorkbookManager } from \"./workbook-manager.cjs\";\nimport { SpillMetaNode } from \"../../evaluator/dependency-nodes/spill-meta-node.cjs\";\nimport { EmptyCellEvaluationNode } from \"../../evaluator/dependency-nodes/empty-cell-evaluation-node.cjs\";\nimport type { TableManager } from \"./table-manager.cjs\";\nimport type { DependencyNode } from \"./dependency-node.cjs\";\nimport { VirtualCellValueNode } from \"../../evaluator/dependency-nodes/virtual-cell-value-node.cjs\";\nimport { ResourceDependencyNode } from \"../../evaluator/dependency-nodes/resource-dependency-node.cjs\";\nimport type {\n NodeSnapshotId,\n SerializedCellInRangeResultSnapshot,\n SerializedErrorEvaluationResultSnapshot,\n SerializedEvaluateAllCellsResultSnapshot,\n SerializedFunctionEvaluationResultSnapshot,\n SerializedSingleEvaluationResultSnapshot,\n SerializedSpillMetaEvaluationResultSnapshot,\n SerializedSpilledValuesEvaluationResultSnapshot,\n} from \"../engine-snapshot.cjs\";\nimport type { MutationInvalidation } from \"../mutation-invalidation.cjs\";\n\nexport class EvaluationManager {\n private isEvaluating = false;\n\n constructor(\n private workbookManager: WorkbookManager,\n private tableManager: TableManager,\n private formulaEvaluator: FormulaEvaluator,\n private dependencyManager: DependencyManager\n ) {}\n\n clearEvaluationCache(): void {\n this.dependencyManager.clearEvaluationCache();\n }\n\n private dependsOnNode(\n candidate: DependencyNode,\n target: DependencyNode,\n visited: Set<DependencyNode> = new Set()\n ): boolean {\n if (candidate === target) {\n return true;\n }\n\n if (visited.has(candidate)) {\n return false;\n }\n visited.add(candidate);\n\n for (const dep of candidate.getDependencies()) {\n if (this.dependsOnNode(dep, target, visited)) {\n return true;\n }\n }\n\n return false;\n }\n\n invalidateFromMutation(footprint: MutationInvalidation): void {\n this.dependencyManager.invalidateFromMutation(footprint);\n }\n\n evaluationResultToSerializedValue(\n evaluation: SingleEvaluationResult,\n cellAddress: CellAddress,\n debug?: boolean\n ): SerializedCellValue {\n if (\n evaluation.type !== \"error\" &&\n evaluation.type !== \"awaiting-evaluation\"\n ) {\n const value = evaluation.result;\n\n return value.type === \"infinity\"\n ? value.sign === \"positive\"\n ? \"INFINITY\"\n : \"-INFINITY\"\n : value.value;\n }\n\n if (evaluation.type === \"awaiting-evaluation\") {\n return (\n evaluation.errAddress.key +\n \" is awaiting evaluation of \" +\n evaluation.waitingFor.key\n );\n }\n\n if (debug) {\n const errAddress = evaluation.errAddress.key;\n if (errAddress === cellAddressToKey(cellAddress)) {\n return evaluation.err + \" \" + evaluation.message;\n }\n return (\n evaluation.err +\n \" in \" +\n evaluation.errAddress.key +\n \" \" +\n evaluation.message\n );\n }\n\n return evaluation.err;\n }\n\n private buildSnapshotOrigin(\n node: CellValueNode | SpillMetaNode | AstEvaluationNode\n ): CellAddress {\n if (\"cellAddress\" in node) {\n return node.cellAddress;\n }\n\n const contextDependency = node.getContextDependency();\n return {\n workbookName: contextDependency.workbookName ?? \"__snapshot__\",\n sheetName: contextDependency.sheetName ?? \"__snapshot__\",\n colIndex: contextDependency.colIndex ?? 0,\n rowIndex: contextDependency.rowIndex ?? 0,\n };\n }\n\n private serializeErrorEvaluationResultSnapshot(\n evaluation: Exclude<ErrorEvaluationResult, { type: \"awaiting-evaluation\" }>,\n getNodeSnapshotId: (node: DependencyNode) => NodeSnapshotId\n ): SerializedErrorEvaluationResultSnapshot {\n return {\n type: \"error\",\n err: evaluation.err,\n message: evaluation.message,\n errAddressId: getNodeSnapshotId(evaluation.errAddress),\n sourceCell: evaluation.sourceCell,\n };\n }\n\n serializeSingleEvaluationResultSnapshot(\n evaluation: SingleEvaluationResult,\n getNodeSnapshotId: (node: DependencyNode) => NodeSnapshotId\n ): SerializedSingleEvaluationResultSnapshot | undefined {\n if (evaluation.type === \"awaiting-evaluation\") {\n return undefined;\n }\n\n if (evaluation.type === \"error\") {\n return this.serializeErrorEvaluationResultSnapshot(\n evaluation,\n getNodeSnapshotId\n );\n }\n\n return {\n type: \"value\",\n result: evaluation.result,\n sourceCell: evaluation.sourceCell,\n };\n }\n\n deserializeSingleEvaluationResultSnapshot(\n evaluation: SerializedSingleEvaluationResultSnapshot,\n resolveNodeSnapshotId: (nodeId: NodeSnapshotId) => DependencyNode\n ): SingleEvaluationResult {\n if (evaluation.type === \"error\") {\n return {\n type: \"error\",\n err: evaluation.err,\n message: evaluation.message,\n errAddress: resolveNodeSnapshotId(evaluation.errAddressId),\n sourceCell: evaluation.sourceCell,\n };\n }\n\n return {\n type: \"value\",\n result: evaluation.result,\n sourceCell: evaluation.sourceCell,\n };\n }\n\n serializeEvaluateAllCellsResultSnapshot(\n evaluation: EvaluateAllCellsResult,\n getNodeSnapshotId: (node: DependencyNode) => NodeSnapshotId\n ): SerializedEvaluateAllCellsResultSnapshot | undefined {\n if (evaluation.type === \"awaiting-evaluation\") {\n return undefined;\n }\n\n if (evaluation.type === \"error\") {\n return this.serializeErrorEvaluationResultSnapshot(\n evaluation,\n getNodeSnapshotId\n );\n }\n\n const values: SerializedCellInRangeResultSnapshot[] = [];\n for (const value of evaluation.values) {\n const serialized = this.serializeSingleEvaluationResultSnapshot(\n value.result,\n getNodeSnapshotId\n );\n if (!serialized) {\n return undefined;\n }\n values.push({\n relativePos: value.relativePos,\n result: serialized,\n });\n }\n\n return {\n type: \"values\",\n values,\n };\n }\n\n deserializeEvaluateAllCellsResultSnapshot(\n evaluation: SerializedEvaluateAllCellsResultSnapshot,\n resolveNodeSnapshotId: (nodeId: NodeSnapshotId) => DependencyNode\n ): EvaluateAllCellsResult {\n if (evaluation.type === \"error\") {\n return this.deserializeSingleEvaluationResultSnapshot(\n evaluation,\n resolveNodeSnapshotId\n ) as ErrorEvaluationResult;\n }\n\n return {\n type: \"values\",\n values: evaluation.values.map((value) => ({\n relativePos: value.relativePos,\n result: this.deserializeSingleEvaluationResultSnapshot(\n value.result,\n resolveNodeSnapshotId\n ),\n })),\n };\n }\n\n serializeFunctionEvaluationResultSnapshot(\n evaluation: FunctionEvaluationResult,\n options: {\n sourceNode: CellValueNode | SpillMetaNode | AstEvaluationNode;\n getNodeSnapshotId: (node: DependencyNode) => NodeSnapshotId;\n }\n ): SerializedFunctionEvaluationResultSnapshot | undefined {\n if (evaluation.type !== \"spilled-values\") {\n return this.serializeSingleEvaluationResultSnapshot(\n evaluation,\n options.getNodeSnapshotId\n );\n }\n\n const origin = this.buildSnapshotOrigin(options.sourceNode);\n const spillArea = evaluation.spillArea(origin);\n const relativeSpillArea = getRelativeRange(spillArea, {\n colIndex: origin.colIndex,\n rowIndex: origin.rowIndex,\n });\n\n if (evaluation.sourceRange) {\n return {\n type: \"spilled-values\",\n spill: {\n kind: \"source-range\",\n relativeSpillArea,\n source: evaluation.source,\n sourceCell: evaluation.sourceCell,\n sourceRange: evaluation.sourceRange,\n },\n };\n }\n\n if (\n relativeSpillArea.width.type !== \"number\" ||\n relativeSpillArea.height.type !== \"number\"\n ) {\n return undefined;\n }\n\n const context = new EvaluationContext(\n this.tableManager,\n options.sourceNode,\n origin\n );\n const values: SerializedCellInRangeResultSnapshot[] = [];\n\n for (let y = 0; y < relativeSpillArea.height.value; y++) {\n for (let x = 0; x < relativeSpillArea.width.value; x++) {\n const result = captureEvaluationErrors(options.sourceNode, () =>\n evaluation.evaluate({ x, y }, context)\n );\n const serialized = this.serializeSingleEvaluationResultSnapshot(\n result,\n options.getNodeSnapshotId\n );\n if (!serialized) {\n return undefined;\n }\n values.push({\n relativePos: { x, y },\n result: serialized,\n });\n }\n }\n\n return {\n type: \"spilled-values\",\n spill: {\n kind: \"materialized\",\n relativeSpillArea,\n source: evaluation.source,\n sourceCell: evaluation.sourceCell,\n sourceRange: evaluation.sourceRange,\n values,\n },\n };\n }\n\n deserializeFunctionEvaluationResultSnapshot(\n evaluation: SerializedFunctionEvaluationResultSnapshot,\n resolveNodeSnapshotId: (nodeId: NodeSnapshotId) => DependencyNode\n ): FunctionEvaluationResult {\n if (evaluation.type !== \"spilled-values\") {\n return this.deserializeSingleEvaluationResultSnapshot(\n evaluation,\n resolveNodeSnapshotId\n );\n }\n\n const spillSnapshot = evaluation.spill;\n if (spillSnapshot.kind === \"materialized\") {\n const values = new Map(\n spillSnapshot.values.map((value) => [\n `${value.relativePos.x},${value.relativePos.y}`,\n this.deserializeSingleEvaluationResultSnapshot(\n value.result,\n resolveNodeSnapshotId\n ),\n ])\n );\n\n return {\n type: \"spilled-values\",\n source: spillSnapshot.source,\n sourceCell: spillSnapshot.sourceCell,\n sourceRange: spillSnapshot.sourceRange,\n spillArea: (origin) =>\n getAbsoluteRange(spillSnapshot.relativeSpillArea, {\n colIndex: origin.colIndex,\n rowIndex: origin.rowIndex,\n }),\n evaluate: (spillOffset) =>\n values.get(`${spillOffset.x},${spillOffset.y}`) ?? {\n type: \"value\",\n result: this.convertScalarValueToCellValue(\"\"),\n },\n evaluateAllCells: () => ({\n type: \"values\",\n values: spillSnapshot.values.map((value) => ({\n relativePos: value.relativePos,\n result: this.deserializeSingleEvaluationResultSnapshot(\n value.result,\n resolveNodeSnapshotId\n ),\n })),\n }),\n };\n }\n\n return {\n type: \"spilled-values\",\n source: spillSnapshot.source,\n sourceCell: spillSnapshot.sourceCell,\n sourceRange: spillSnapshot.sourceRange,\n spillArea: (origin) =>\n getAbsoluteRange(spillSnapshot.relativeSpillArea, {\n colIndex: origin.colIndex,\n rowIndex: origin.rowIndex,\n }),\n evaluate: (spillOffset, context) => {\n const cellAddress: CellAddress = {\n workbookName: spillSnapshot.sourceRange.workbookName,\n sheetName: spillSnapshot.sourceRange.sheetName,\n colIndex: spillSnapshot.sourceRange.range.start.col + spillOffset.x,\n rowIndex: spillSnapshot.sourceRange.range.start.row + spillOffset.y,\n };\n\n const evalNode = this.dependencyManager.getCellValueOrEmptyCellNode(\n cellAddressToKey(cellAddress)\n );\n context.dependencyNode.addDependency(evalNode);\n return evalNode.evaluationResult;\n },\n evaluateAllCells: ({ intersection, context, origin }) => {\n let range = spillSnapshot.sourceRange.range;\n if (intersection) {\n const relativeRange = getRelativeRange(intersection, origin);\n const projectedIntersection = getAbsoluteRange(relativeRange, {\n colIndex: spillSnapshot.sourceRange.range.start.col,\n rowIndex: spillSnapshot.sourceRange.range.start.row,\n });\n const nextRange = getRangeIntersection(\n spillSnapshot.sourceRange.range,\n projectedIntersection\n );\n if (nextRange) {\n range = nextRange;\n }\n }\n\n const rangeAddress = {\n workbookName: spillSnapshot.sourceRange.workbookName,\n sheetName: spillSnapshot.sourceRange.sheetName,\n range,\n };\n\n const rangeNode = this.dependencyManager.getRangeNode(\n rangeAddressToKey(rangeAddress)\n );\n context.dependencyNode.addDependency(rangeNode);\n return rangeNode.result;\n },\n };\n }\n\n serializeSpillMetaEvaluationResultSnapshot(\n evaluation: SpillMetaNode[\"evaluationResult\"],\n options: {\n sourceNode: CellValueNode | SpillMetaNode | AstEvaluationNode;\n getNodeSnapshotId: (node: DependencyNode) => NodeSnapshotId;\n }\n ): SerializedSpillMetaEvaluationResultSnapshot | undefined {\n if (evaluation.type === \"does-not-spill\") {\n return { type: \"does-not-spill\" };\n }\n\n if (evaluation.type === \"error\") {\n return this.serializeErrorEvaluationResultSnapshot(\n evaluation,\n options.getNodeSnapshotId\n );\n }\n\n const serialized = this.serializeFunctionEvaluationResultSnapshot(\n evaluation,\n options\n );\n if (!serialized || serialized.type !== \"spilled-values\") {\n return undefined;\n }\n\n return serialized;\n }\n\n deserializeSpillMetaEvaluationResultSnapshot(\n evaluation: SerializedSpillMetaEvaluationResultSnapshot,\n resolveNodeSnapshotId: (nodeId: NodeSnapshotId) => DependencyNode\n ): SpillMetaNode[\"evaluationResult\"] {\n if (evaluation.type === \"does-not-spill\") {\n return evaluation;\n }\n\n if (evaluation.type === \"error\") {\n return this.deserializeSingleEvaluationResultSnapshot(\n evaluation,\n resolveNodeSnapshotId\n ) as SpillMetaNode[\"evaluationResult\"];\n }\n\n return this.deserializeFunctionEvaluationResultSnapshot(\n evaluation,\n resolveNodeSnapshotId\n ) as SpillMetaNode[\"evaluationResult\"];\n }\n\n evaluateEmptyCell(node: EmptyCellEvaluationNode): void {\n if (node.resolved) {\n const result = node.evaluationResult;\n if (result && result.type !== \"awaiting-evaluation\") {\n return;\n }\n }\n\n this.dependencyManager.unregisterNode(node);\n node.resetDirectDepsUpdated();\n\n const ctx = new EvaluationContext(\n this.tableManager,\n node,\n node.cellAddress\n );\n const inSpilled = this.dependencyManager.getSpillValue(node.cellAddress);\n\n if (inSpilled) {\n // if we are spilling then we can just add the spill origin as a dependency and evaluate the spilled value\n const spillTarget = this.dependencyManager.getSpilledAddress(\n node.cellAddress,\n inSpilled\n );\n const spillOriginKey = cellAddressToKey(inSpilled.origin).replace(\n /^[^:]+:/,\n \"spill-meta:\"\n );\n const spillMetaNode =\n this.dependencyManager.getSpillMetaNode(spillOriginKey);\n node.addDependency(spillMetaNode);\n const result = spillMetaNode.evaluationResult;\n if (result.type === \"spilled-values\") {\n // let's evaluate the spilled value to extract dependencies\n const evaluation = captureEvaluationErrors(spillMetaNode, () => {\n return result.evaluate(spillTarget.spillOffset, ctx);\n });\n node.setEvaluationResult(evaluation);\n }\n } else {\n // upgrade any frontier dependencies that spill into the range\n node.upgradeFrontierDependencies();\n\n const evaluationResult: SingleEvaluationResult = {\n type: \"value\",\n result: this.convertScalarValueToCellValue(\"\"),\n };\n // for now let's just store the empty value, the next time the cell is evaluated isSpilled will be true and the spilled value will be evaluated\n node.setEvaluationResult(evaluationResult);\n }\n\n this.dependencyManager.registerNode(node);\n }\n\n evaluateRangeNode(node: RangeEvaluationNode): void {\n if (node.resolved) {\n return;\n }\n\n this.dependencyManager.unregisterNode(node);\n node.resetDirectDepsUpdated();\n\n const result = captureEvaluationErrors(node, (): EvaluateAllCellsResult => {\n node.upgradeFrontierDependencies();\n\n const evalOrder = node.getRangeEvalOrder();\n const circularEntryCache = new Map<DependencyNode, boolean>();\n const shouldSkipCircularEntry = (candidate: DependencyNode) => {\n const cached = circularEntryCache.get(candidate);\n if (cached !== undefined) {\n return cached;\n }\n\n // If a cell inside the range depends back on the range itself, including\n // its current value would count a circular result back into the same\n // aggregate on a later rerun.\n const isCircular = this.dependsOnNode(candidate, node);\n circularEntryCache.set(candidate, isCircular);\n return isCircular;\n };\n\n const results: CellInRangeResult[] = [];\n\n for (const entry of evalOrder) {\n if (entry.type === \"value\") {\n if (shouldSkipCircularEntry(entry.node)) {\n continue;\n }\n\n const entryAddress = entry.address;\n const result = entry.node.evaluationResult;\n\n const relativePos = {\n x: entryAddress.colIndex - node.address.range.start.col,\n y: entryAddress.rowIndex - node.address.range.start.row,\n };\n\n results.push({ result: result, relativePos });\n } else if (\n entry.type === \"empty_cell\" ||\n entry.type === \"empty_range\"\n ) {\n for (const candidateNode of entry.candidates) {\n if (shouldSkipCircularEntry(candidateNode)) {\n continue;\n }\n\n if (candidateNode.evaluationResult.type === \"spilled-values\") {\n const spillArea = candidateNode.evaluationResult.spillArea(\n candidateNode.cellAddress\n );\n if (entry.type === \"empty_range\") {\n const intersects = checkRangeIntersection(\n spillArea,\n entry.address.range\n );\n if (intersects) {\n // When a spilled range intersects with our target range, we need to evaluate\n // only the cells that fall within the intersection area.\n //\n // Example: If cell A10 contains a spilled range that covers A10:B11,\n // and our target range is B10:INFINITY, then we only want to evaluate\n // the intersection B10:B11 from the spilled range.\n //\n // The evaluateAllCells method expects the intersection to be passed\n // so it can limit evaluation to only the relevant cells.\n const ctx = new EvaluationContext(\n this.tableManager,\n node,\n candidateNode.cellAddress\n );\n const spilledResults =\n candidateNode.evaluationResult.evaluateAllCells.call(\n this.formulaEvaluator,\n {\n context: ctx,\n evaluate: candidateNode.evaluationResult.evaluate,\n intersection: entry.address.range,\n origin: candidateNode.cellAddress,\n lookupOrder: \"col-major\",\n }\n );\n\n if (spilledResults.type === \"values\") {\n results.push(...spilledResults.values);\n } else {\n return spilledResults;\n }\n }\n } else {\n const intersects = isCellInRange(entry.address, spillArea);\n if (intersects) {\n // When a spilled range intersects with our target range, we need to evaluate\n // only the cells that fall within the intersection area.\n //\n // Example: If cell A10 contains a spilled range that covers A10:B11,\n // and our target range is B10:INFINITY, then we only want to evaluate\n // the intersection B10:B11 from the spilled range.\n //\n // The evaluateAllCells method expects the intersection to be passed\n // so it can limit evaluation to only the relevant cells.\n\n const relativePos = {\n x:\n entry.address.colIndex -\n candidateNode.cellAddress.colIndex,\n y:\n entry.address.rowIndex -\n candidateNode.cellAddress.rowIndex,\n };\n const ctx = new EvaluationContext(\n this.tableManager,\n node,\n candidateNode.cellAddress\n );\n const spilledResult = candidateNode.evaluationResult.evaluate(\n relativePos,\n ctx\n );\n\n results.push({\n relativePos: {\n x: entry.address.colIndex - node.address.range.start.col,\n y: entry.address.rowIndex - node.address.range.start.row,\n },\n result: spilledResult,\n });\n }\n }\n }\n }\n }\n }\n\n return {\n type: \"values\",\n values: results,\n };\n });\n\n node.setResult(result);\n this.dependencyManager.registerNode(node);\n }\n\n evaluateCellNode(\n node: CellValueNode | SpillMetaNode | VirtualCellValueNode\n ): void {\n // Enable caching for resolved nodes\n if (node.resolved) {\n return;\n }\n\n const finalizePersistentNode = () => {\n if (node instanceof VirtualCellValueNode) {\n return;\n }\n\n this.dependencyManager.registerNode(node);\n };\n\n if (!(node instanceof VirtualCellValueNode)) {\n this.dependencyManager.unregisterNode(node);\n }\n node.resetDirectDepsUpdated();\n\n const ctx = new EvaluationContext(\n this.tableManager,\n node,\n node.cellAddress\n );\n\n if (node instanceof CellValueNode && node.spillMeta) {\n // we are evaluating a e.g. A1 in A1=SEQUENCE(10), where we want the value in the cell in A1, i.e. 1\n // As A1 is already pointing to a spill meta node, everything has been setup already,\n // we just need to evaluate the spill origin and assign the result to the currentDepNode\n const spillOrigin = node.spillMeta;\n if (spillOrigin.evaluationResult.type === \"spilled-values\") {\n const result = spillOrigin.evaluationResult.evaluate(\n { x: 0, y: 0 },\n ctx\n );\n node.setEvaluationResult(result);\n finalizePersistentNode();\n return;\n }\n }\n\n let content: SerializedCellValue;\n try {\n if (node instanceof VirtualCellValueNode) {\n content = node.cellValue;\n } else {\n content = this.workbookManager.getSerializedCellValue(node.cellAddress);\n }\n } catch (err) {\n const evaluationResult: ErrorEvaluationResult = {\n type: \"error\",\n err: FormulaError.ERROR,\n message: \"Syntax error\",\n errAddress: node,\n };\n node.setEvaluationResult(evaluationResult);\n if (!(node instanceof VirtualCellValueNode)) {\n this.dependencyManager.registerNode(node);\n }\n return;\n }\n\n if (typeof content !== \"string\" || !content.startsWith(\"=\")) {\n if (node instanceof SpillMetaNode) {\n node.setEvaluationResult({\n type: \"does-not-spill\",\n });\n finalizePersistentNode();\n return;\n }\n // Static value cells cannot have frontier dependencies\n const result: ValueEvaluationResult = {\n type: \"value\",\n result: this.convertScalarValueToCellValue(content),\n };\n node.setEvaluationResult(result);\n finalizePersistentNode();\n return;\n }\n\n let evaluation: FunctionEvaluationResult = captureEvaluationErrors(\n node,\n () => this.formulaEvaluator.evaluateFormula(content.slice(1), ctx)\n );\n\n // the evaluated cell IS A spilling formula, e.g. if dependencyKey points to A1, then the formula is e.g. A1=SEQUENCE(10), or A1=A3:B5\n if (evaluation.type === \"spilled-values\") {\n const spillArea = evaluation.spillArea(node.cellAddress);\n\n if (!this.canSpill(node.cellAddress, spillArea)) {\n // Override evaluation with SPILL error, but continue execution to set up nodes\n evaluation = {\n type: \"error\",\n err: FormulaError.SPILL,\n message: \"Cannot spill - area is blocked\",\n errAddress: node,\n };\n } else {\n // Spill succeeds - register it\n this.dependencyManager.setSpilledValue(node.key, {\n spillOnto: spillArea,\n origin: node.cellAddress,\n });\n }\n\n // Set up spill meta node and evaluation results (even if spill failed)\n if (node instanceof SpillMetaNode) {\n // we have already setup an origin/spill meta node relationship,\n // so we are just reevaluating the spill meta node here\n node.setEvaluationResult(evaluation);\n finalizePersistentNode();\n } else {\n const spillMetaNode = this.dependencyManager.getSpillMetaNode(\n node.key.replace(/^[^:]+:/, \"spill-meta:\")\n );\n\n node.addDependency(spillMetaNode);\n node.setSpillMetaNode(spillMetaNode);\n spillMetaNode.setEvaluationResult(evaluation);\n this.dependencyManager.registerNode(spillMetaNode);\n\n if (evaluation.type === \"spilled-values\") {\n const originResult = evaluation.evaluate({ x: 0, y: 0 }, ctx);\n node.setEvaluationResult(originResult);\n } else {\n // Spill failed - set error on origin cell\n node.setEvaluationResult(evaluation);\n }\n }\n finalizePersistentNode();\n return;\n }\n\n if (evaluation.type === \"value\") {\n if (node instanceof SpillMetaNode) {\n node.setEvaluationResult({\n type: \"does-not-spill\",\n });\n finalizePersistentNode();\n return;\n } else {\n node.setEvaluationResult(evaluation);\n finalizePersistentNode();\n return;\n }\n }\n\n node.setEvaluationResult(evaluation);\n finalizePersistentNode();\n }\n\n evaluateDependencyNode(dependency: DependencyNode): void {\n if (dependency instanceof EmptyCellEvaluationNode) {\n this.evaluateEmptyCell(dependency);\n return;\n }\n if (dependency instanceof RangeEvaluationNode) {\n this.evaluateRangeNode(dependency);\n return;\n }\n if (\n dependency instanceof CellValueNode ||\n dependency instanceof VirtualCellValueNode\n ) {\n this.evaluateCellNode(dependency);\n return;\n }\n if (dependency instanceof AstEvaluationNode) {\n return;\n }\n if (dependency instanceof ResourceDependencyNode) {\n return;\n }\n if (dependency instanceof SpillMetaNode) {\n this.evaluateCellNode(dependency);\n return;\n }\n throw new Error(\"Invalid dependency: \" + (dependency as any).key);\n }\n\n /**\n * User exposed method to evaluate a formula\n */\n evaluateFormula(\n /**\n * formula for example\n */\n cellValue: SerializedCellValue,\n cellAddress: CellAddress\n ): SerializedCellValue {\n if (this.isEvaluating) {\n throw new Error(\"Evaluation in progress\");\n }\n\n const node = this.dependencyManager.getVirtualCellValueNode(\n cellAddress,\n cellValue\n );\n\n if (node.evaluationResult.type === \"awaiting-evaluation\") {\n this.evaluateCell(node);\n }\n\n const result = node.evaluationResult;\n\n return this.evaluationResultToSerializedValue(result, cellAddress);\n }\n\n /**\n * Evaluates a cell by building the evaluation order and evaluating the dependencies in order\n */\n evaluateCell(\n node: CellValueNode | EmptyCellEvaluationNode | VirtualCellValueNode\n ): void {\n if (this.isEvaluating) {\n throw new Error(\"Evaluation in progress\");\n }\n this.isEvaluating = true;\n\n let precalculatedPlan: EvaluationOrder | undefined;\n\n let requiresReRun = true;\n while (requiresReRun) {\n requiresReRun = false;\n\n // Use DependencyManager to build evaluation order\n const evaluationPlan =\n precalculatedPlan ?? this.dependencyManager.buildEvaluationOrder(node);\n\n if (evaluationPlan.hasCycle) {\n const evaluationResult: ErrorEvaluationResult = {\n type: \"error\",\n err: FormulaError.CYCLE,\n message: Array.from(evaluationPlan.cycleNodes ?? [])\n .map((node) => node.key)\n .join(\" -> \"),\n errAddress: node,\n };\n // cycle detected\n if (evaluationPlan.cycleNodes) {\n for (const node of evaluationPlan.cycleNodes) {\n if (\n !(node instanceof RangeEvaluationNode) &&\n !(node instanceof ResourceDependencyNode)\n ) {\n node.setEvaluationResult(evaluationResult);\n }\n }\n }\n this.isEvaluating = false;\n }\n\n // Evaluate all dependencies in order\n const timeStart = performance.now();\n const durations: { duration: number; key: string }[] = [];\n let numResolved = 0;\n if (flags.isProfiling && evaluationPlan.evaluationOrder.size > -1) {\n // console.profile();\n }\n evaluationPlan.evaluationOrder.forEach((dependency) => {\n const start = performance.now();\n if (dependency.resolved) {\n numResolved++;\n }\n this.evaluateDependencyNode(dependency);\n\n const end = performance.now();\n if (flags.isProfiling && evaluationPlan.evaluationOrder.size > -1) {\n durations.push({ duration: end - start, key: dependency.key });\n }\n });\n if (flags.isProfiling && evaluationPlan.evaluationOrder.size > -1) {\n // console.profileEnd();\n }\n if (flags.isProfiling && evaluationPlan.evaluationOrder.size > -1) {\n const percentResolved = Math.round(\n (100 * numResolved) / evaluationPlan.evaluationOrder.size\n );\n const avgDuration =\n durations.reduce((a, b) => a + b.duration, 0) / durations.length || 0;\n console.log(\n `%c[Evaluation] %c${evaluationPlan.evaluationOrder.size} deps | %c${(\n performance.now() - timeStart\n ).toFixed(\n 1\n )}ms | %c${percentResolved}% resolved | %c${avgDuration.toFixed(\n 2\n )}ms avg`,\n \"color:#83aaff;font-weight:bold;\",\n \"color:#fff;font-weight:bold;\",\n \"color:#7fff9e\",\n \"color:#85baff\",\n \"color:#ffdfa3\"\n );\n }\n\n this.dependencyManager.markResolvedNodes(node);\n\n const nextEvaluationPlan =\n this.dependencyManager.buildEvaluationOrder(node);\n\n this.dependencyManager.updateResolvedSCCs(nextEvaluationPlan);\n\n precalculatedPlan = nextEvaluationPlan;\n\n // Check if new dependencies were discovered during evaluation\n if (nextEvaluationPlan.hash !== evaluationPlan.hash) {\n requiresReRun = true;\n } else {\n this.isEvaluating = false;\n return;\n }\n }\n this.isEvaluating = false;\n }\n\n convertScalarValueToCellValue(val: SerializedCellValue): CellValue {\n if (val === \"INFINITY\") {\n return { type: \"infinity\", sign: \"positive\" };\n }\n if (val === \"-INFINITY\") {\n return { type: \"infinity\", sign: \"negative\" };\n }\n if (typeof val === \"number\") {\n return { type: \"number\", value: val };\n }\n if (typeof val === \"boolean\") {\n return { type: \"boolean\", value: val };\n }\n if (typeof val === \"undefined\") {\n return { type: \"string\", value: \"\" };\n }\n return { type: \"string\", value: val };\n }\n\n // todo optimize using workbook manager\n canSpill(spillCandidate: CellAddress, spillArea: SpreadsheetRange): boolean {\n // Check if the spill origin cell is inside a table - spilling formulas cannot exist in tables\n if (this.tableManager.isCellInTable(spillCandidate)) {\n return false;\n }\n\n // Check if the spill area would intersect with any table - formulas cannot spill into tables\n if (\n this.tableManager.doesRangeIntersectTable(\n spillCandidate.workbookName,\n spillCandidate.sheetName,\n spillArea\n )\n ) {\n return false;\n }\n\n const sheet = this.workbookManager.getSheet(spillCandidate);\n if (!sheet) {\n throw new SheetNotFoundError(spillCandidate.sheetName);\n }\n const cellId = getCellReference(spillCandidate);\n const content = sheet.content.get(cellId);\n if (!content) {\n throw new EvaluationError(FormulaError.REF, `Cell not found: ${cellId}`);\n }\n for (const spilledValue of this.dependencyManager.spilledValues) {\n if (\n spilledValue.origin.workbookName !== spillCandidate.workbookName ||\n spilledValue.origin.sheetName !== spillCandidate.sheetName\n ) {\n continue;\n }\n if (\n spilledValue.origin.colIndex === spillCandidate.colIndex &&\n spilledValue.origin.rowIndex === spillCandidate.rowIndex\n ) {\n // we are already have a spill, this one will be replaced\n continue;\n }\n\n if (checkRangeIntersection(spillArea, spilledValue.spillOnto)) {\n return false;\n }\n }\n // let's just check the raw data if there is something in the range\n for (const key of sheet.content.keys()) {\n const cellAddress = parseCellReference(key);\n const endCol = spillArea.end.col;\n const endRow = spillArea.end.row;\n\n if (\n cellAddress.colIndex === spillCandidate.colIndex &&\n cellAddress.rowIndex === spillCandidate.rowIndex\n ) {\n continue;\n }\n\n if (endCol.type === \"number\" && endRow.type === \"number\") {\n if (\n cellAddress.colIndex >= spillArea.start.col &&\n cellAddress.colIndex <= endCol.value &&\n cellAddress.rowIndex >= spillArea.start.row &&\n cellAddress.rowIndex <= endRow.value\n ) {\n if (\n normalizeSerializedCellValue(sheet.content.get(key)) !== undefined\n ) {\n // there is something in the range, so we can't spill\n return false;\n }\n }\n }\n }\n\n return true;\n }\n\n getCellEvaluationResult(\n cellAddress: CellAddress\n ): SingleEvaluationResult | undefined {\n if (this.isEvaluating) {\n throw new Error(\"Evaluation in progress\");\n }\n\n const nodeKey = cellAddressToKey(cellAddress);\n const node = this.dependencyManager.getCellValueOrEmptyCellNode(nodeKey);\n\n const sheet = this.workbookManager.getSheet(cellAddress);\n if (!sheet) {\n throw new SheetNotFoundError(cellAddress.sheetName);\n }\n\n if (node.evaluationResult.type === \"awaiting-evaluation\") {\n // if (cellAddressToKey(cellAddress).includes(\"G10\")) {\n // console.group(\"Evaluation of G10\");\n // flags.isProfiling = true;\n // console.time(\"Evaluation of G10\");\n // console.profile(\"Evaluation of G10\");\n // }\n this.evaluateCell(node);\n // if (flags.isProfiling) {\n // flags.isProfiling = false;\n // console.timeEnd(\"Evaluation of G10\");\n // console.profileEnd(\"Evaluation of G10\");\n // console.groupEnd();\n // }\n }\n\n const result = node.evaluationResult;\n\n return result;\n }\n}\n"
6
6
  ],
7
7
  "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAsB,IAAtB;AACkC,IAAlC;AAC8B,IAA9B;AACkC,IAAlC;AAIO,IAHP;AAIoC,IAApC;AAC6C,IAA7C;AAeO,IAbP;AAyBO,IAXP;AAc8B,IAA9B;AACwC,IAAxC;AAGqC,IAArC;AACuC,IAAvC;AAAA;AAaO,MAAM,kBAAkB;AAAA,EAInB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EANF,eAAe;AAAA,EAEvB,WAAW,CACD,iBACA,cACA,kBACA,mBACR;AAAA,IAJQ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA;AAAA,EAGV,oBAAoB,GAAS;AAAA,IAC3B,KAAK,kBAAkB,qBAAqB;AAAA;AAAA,EAGtC,aAAa,CACnB,WACA,QACA,UAA+B,IAAI,KAC1B;AAAA,IACT,IAAI,cAAc,QAAQ;AAAA,MACxB,OAAO;AAAA,IACT;AAAA,IAEA,IAAI,QAAQ,IAAI,SAAS,GAAG;AAAA,MAC1B,OAAO;AAAA,IACT;AAAA,IACA,QAAQ,IAAI,SAAS;AAAA,IAErB,WAAW,OAAO,UAAU,gBAAgB,GAAG;AAAA,MAC7C,IAAI,KAAK,cAAc,KAAK,QAAQ,OAAO,GAAG;AAAA,QAC5C,OAAO;AAAA,MACT;AAAA,IACF;AAAA,IAEA,OAAO;AAAA;AAAA,EAGT,sBAAsB,CAAC,WAAuC;AAAA,IAC5D,KAAK,kBAAkB,uB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IAC1C;AAAA,IAEA,MAAM,UAAU,8BAAiB,WAAW;AAAA,IAC5C,MAAM,OAAO,KAAK,kBAAkB,4BAA4B,OAAO;AAAA,IAEvE,MAAM,QAAQ,KAAK,gBAAgB,SAAS,WAAW;AAAA,IACvD,IAAI,CAAC,OAAO;AAAA,MACV,MAAM,IAAI,2CAAmB,YAAY,SAAS;AAAA,IACpD;AAAA,IAEA,IAAI,KAAK,iBAAiB,SAAS,uBAAuB;AAAA,MAOxD,KAAK,aAAa,IAAI;AAAA,IAOxB;AAAA,IAEA,MAAM,SAAS,KAAK;AAAA,IAEpB,OAAO;AAAA;AAEX;",
8
8
  "debugId": "82AA595E9C9D067964756E2164756E21",
@@ -389,6 +389,202 @@ class WorkbookManager {
389
389
  }
390
390
  return sheet.content;
391
391
  }
392
+ resolveSearchScope(options) {
393
+ if (options?.sheetName && !options.workbookName) {
394
+ throw new Error("workbookName is required when sheetName is provided");
395
+ }
396
+ if (!options?.workbookName) {
397
+ const scopedSheets = [];
398
+ for (const workbookName2 of this.workbooks.keys()) {
399
+ for (const sheet2 of this.getOrderedSheets(workbookName2)) {
400
+ scopedSheets.push({ workbookName: workbookName2, sheet: sheet2 });
401
+ }
402
+ }
403
+ return scopedSheets;
404
+ }
405
+ const workbookName = options.workbookName;
406
+ if (!this.workbooks.has(workbookName)) {
407
+ throw new import_evaluation_error.WorkbookNotFoundError(workbookName);
408
+ }
409
+ if (!options.sheetName) {
410
+ return this.getOrderedSheets(workbookName).map((sheet2) => ({
411
+ workbookName,
412
+ sheet: sheet2
413
+ }));
414
+ }
415
+ const sheet = this.getSheet({
416
+ workbookName,
417
+ sheetName: options.sheetName
418
+ });
419
+ if (!sheet) {
420
+ throw new import_evaluation_error.SheetNotFoundError(options.sheetName);
421
+ }
422
+ return [{ workbookName, sheet }];
423
+ }
424
+ getStringContentKind(cellContent) {
425
+ return cellContent.startsWith("=") ? "formula" : "text";
426
+ }
427
+ findMatchesInString(cellContent, query, caseSensitive) {
428
+ if (query.length === 0) {
429
+ return [];
430
+ }
431
+ const normalizedContent = caseSensitive ? cellContent : cellContent.toLowerCase();
432
+ const normalizedQuery = caseSensitive ? query : query.toLowerCase();
433
+ const matches = [];
434
+ let searchFromIndex = 0;
435
+ while (searchFromIndex <= normalizedContent.length - normalizedQuery.length) {
436
+ const startIndex = normalizedContent.indexOf(normalizedQuery, searchFromIndex);
437
+ if (startIndex === -1) {
438
+ break;
439
+ }
440
+ const endIndexExclusive = startIndex + normalizedQuery.length;
441
+ matches.push({
442
+ occurrenceIndex: matches.length,
443
+ startIndex,
444
+ endIndexExclusive,
445
+ matchedText: cellContent.slice(startIndex, endIndexExclusive)
446
+ });
447
+ searchFromIndex = endIndexExclusive;
448
+ }
449
+ return matches;
450
+ }
451
+ buildSearchMatchesInScope(query, scopedSheets, caseSensitive) {
452
+ const results = [];
453
+ for (const { workbookName, sheet } of scopedSheets) {
454
+ const sheetMatches = [];
455
+ for (const [cellReference, value] of sheet.content.entries()) {
456
+ if (typeof value !== "string") {
457
+ continue;
458
+ }
459
+ const matches = this.findMatchesInString(value, query, caseSensitive);
460
+ if (matches.length === 0) {
461
+ continue;
462
+ }
463
+ const { rowIndex, colIndex } = import_utils.parseCellReference(cellReference);
464
+ const contentKind = this.getStringContentKind(value);
465
+ sheetMatches.push(...matches.map((match) => ({
466
+ workbookName,
467
+ sheetName: sheet.name,
468
+ cellReference,
469
+ cellContent: value,
470
+ contentKind,
471
+ occurrenceIndex: match.occurrenceIndex,
472
+ startIndex: match.startIndex,
473
+ endIndexExclusive: match.endIndexExclusive,
474
+ matchedText: match.matchedText,
475
+ rowIndex,
476
+ colIndex
477
+ })));
478
+ }
479
+ sheetMatches.sort((left, right) => left.rowIndex - right.rowIndex || left.colIndex - right.colIndex || left.occurrenceIndex - right.occurrenceIndex);
480
+ results.push(...sheetMatches.map(({ rowIndex: _rowIndex, colIndex: _colIndex, ...match }) => match));
481
+ }
482
+ return results;
483
+ }
484
+ search(query, options) {
485
+ const scopedSheets = this.resolveSearchScope(options);
486
+ if (query.length === 0) {
487
+ return [];
488
+ }
489
+ return this.buildSearchMatchesInScope(query, scopedSheets, options?.caseSensitive === true);
490
+ }
491
+ buildReplacedContent(beforeContent, matches, replacement) {
492
+ let cursor = 0;
493
+ let replacedContent = "";
494
+ for (const match of matches) {
495
+ replacedContent += beforeContent.slice(cursor, match.startIndex);
496
+ replacedContent += replacement;
497
+ cursor = match.endIndexExclusive;
498
+ }
499
+ replacedContent += beforeContent.slice(cursor);
500
+ return replacedContent;
501
+ }
502
+ prepareReplace(query, replacement, target, options) {
503
+ if (query.length === 0) {
504
+ throw new Error("replace requires a non-empty query");
505
+ }
506
+ const address = {
507
+ workbookName: target.workbookName,
508
+ sheetName: target.sheetName,
509
+ ...import_utils.parseCellReference(target.cellReference)
510
+ };
511
+ const beforeContent = this.getCellContent(address);
512
+ if (typeof beforeContent !== "string") {
513
+ throw new Error(`replace requires target cell ${target.cellReference} to contain a string`);
514
+ }
515
+ const matches = this.findMatchesInString(beforeContent, query, options?.caseSensitive === true);
516
+ const match = matches[target.occurrenceIndex];
517
+ if (!match) {
518
+ throw new Error(`Occurrence ${target.occurrenceIndex} not found in cell ${target.cellReference}`);
519
+ }
520
+ const afterContent = this.buildReplacedContent(beforeContent, [match], replacement);
521
+ const contentKind = this.getStringContentKind(beforeContent);
522
+ return {
523
+ address,
524
+ beforeContent,
525
+ afterContent,
526
+ change: {
527
+ workbookName: target.workbookName,
528
+ sheetName: target.sheetName,
529
+ cellReference: target.cellReference,
530
+ contentKind,
531
+ occurrenceIndex: match.occurrenceIndex,
532
+ startIndex: match.startIndex,
533
+ endIndexExclusive: match.endIndexExclusive,
534
+ matchedText: match.matchedText,
535
+ replacementText: replacement,
536
+ beforeContent,
537
+ afterContent
538
+ }
539
+ };
540
+ }
541
+ prepareReplaceAll(query, replacement, options) {
542
+ const scopedSheets = this.resolveSearchScope(options);
543
+ if (query.length === 0) {
544
+ throw new Error("replaceAll requires a non-empty query");
545
+ }
546
+ const matches = this.buildSearchMatchesInScope(query, scopedSheets, options?.caseSensitive === true);
547
+ const matchesByCell = new Map;
548
+ for (const match of matches) {
549
+ const cellKey = `${match.workbookName}:${match.sheetName}:${match.cellReference}`;
550
+ const existing = matchesByCell.get(cellKey);
551
+ if (existing) {
552
+ existing.push(match);
553
+ } else {
554
+ matchesByCell.set(cellKey, [match]);
555
+ }
556
+ }
557
+ return Array.from(matchesByCell.values()).map((cellMatches) => {
558
+ const [firstMatch] = cellMatches;
559
+ if (!firstMatch) {
560
+ throw new Error("Expected at least one match per cell");
561
+ }
562
+ const address = {
563
+ workbookName: firstMatch.workbookName,
564
+ sheetName: firstMatch.sheetName,
565
+ ...import_utils.parseCellReference(firstMatch.cellReference)
566
+ };
567
+ const afterContent = this.buildReplacedContent(firstMatch.cellContent, cellMatches, replacement);
568
+ return {
569
+ address,
570
+ beforeContent: firstMatch.cellContent,
571
+ afterContent,
572
+ changes: cellMatches.map((match) => ({
573
+ workbookName: match.workbookName,
574
+ sheetName: match.sheetName,
575
+ cellReference: match.cellReference,
576
+ contentKind: match.contentKind,
577
+ occurrenceIndex: match.occurrenceIndex,
578
+ startIndex: match.startIndex,
579
+ endIndexExclusive: match.endIndexExclusive,
580
+ matchedText: match.matchedText,
581
+ replacementText: replacement,
582
+ beforeContent: firstMatch.cellContent,
583
+ afterContent
584
+ }))
585
+ };
586
+ });
587
+ }
392
588
  addCellToGroups(indexes, rowIndex, colIndex, key) {
393
589
  let rowGroup = indexes.rowGroups.get(rowIndex);
394
590
  if (!rowGroup) {
@@ -641,4 +837,4 @@ class WorkbookManager {
641
837
  }
642
838
  }
643
839
 
644
- //# debugId=8594DB95F85838CE64756E2164756E21
840
+ //# debugId=483CA8B52CB4833564756E2164756E21