← All packages

@searsuite/sear-domain-formula-engine

Parse expressions

This package defines the values and service interfaces consumed by formula features. IFormulaParser describes parsing, IFormulaEvaluator describes evaluation, IDependencyGraph describes recalculation dependencies, and IFunctionRegistry describes function lookup. The TypeScript implementations live in @searsuite/sear-domain-formula-engine-ts and are selected through dependency injection.

Use these interfaces when building a plugin or host that must work with a different formula implementation. Use the TypeScript package when you need its concrete parser, evaluator, or built-in functions.

interfaceIFormulaParser
interface IFormulaParser IFormulaParser: unknown
methodextractDependencies(ast: FormulaAST): Dependency[]

Extracts all dependencies from an AST.

Traverses all cell and range nodes in the AST and returns a Dependency list. Returned dependencies stay range-level and are not expanded per cell.

Example
// =SUM(A1:C100) + D5
extractDependencies(ast) → [
  { kind: FormulaNodeKind.Range, start: [0,0], end: [99,2] },
  { kind: FormulaNodeKind.Cell, row: 4, col: 3 }
]
methodparse(formula: string): FormulaAST

Parses a formula string into an AST.

Input is a formula string with a leading '=', such as "=A1+B1". Uses recursive-descent parsing and supports the full operator precedence.

ReturnsParsed AST.

ThrowsWhen parsing fails because syntax is invalid.

formula

Formula string including the leading '='.

methodshiftReferences(ast: FormulaAST, changes: StructureChange[]): FormulaAST

Shifts references.

Rewrites row/column references inside an AST after structural changes such as row/column insertions and deletions. Uses immutable updates: creates a new AST and never mutates the original AST.

Rules:

  • Absolute references ($A$1) are unaffected.
  • Relative references shift according to insertion/deletion position.
  • Deleted referenced rows/columns produce an AST carrying #REF!.
Example
A formula =B3 in A2, after inserting one row below row 1, becomes =B4.
A formula =SUM(A1:A3) in A4, after deleting row 2, becomes =SUM(A1:#REF!).
variablesymbol
symbol: typeof symbol
typeBinaryOp
type BinaryOp = "+" | "-" | "*" | "/" | "^" | "&" | "=" | "<>" | "<" | ">" | "<=" | ">="

Supported binary formula operators.

typeFormulaAST
type FormulaAST = { kind: typeof FormulaNodeKind.Number; value: number } | { kind: typeof FormulaNodeKind.String; value: string } | { kind: typeof FormulaNodeKind.Boolean; value: boolean } | { code: FormulaErrorCode; kind: typeof FormulaNodeKind.Error } | { kind: typeof FormulaNodeKind.Name; name: string } | { items: FormulaAST[]; kind: typeof FormulaNodeKind.Tuple } | { kind: typeof FormulaNodeKind.Intersection; left: FormulaAST; right: FormulaAST } | { kind: typeof FormulaNodeKind.Array; rows: FormulaAST[][] } | { kind: typeof FormulaNodeKind.Missing } | { absCol: boolean; absRow: boolean; col: number; kind: typeof FormulaNodeKind.Cell; row: number } | { absEndCol: boolean; absEndRow: boolean; absStartCol: boolean; absStartRow: boolean; end: [number, number]; kind: typeof FormulaNodeKind.Range; start: [number, number] } | { absCol: boolean; absRow: boolean; col: number; kind: typeof FormulaNodeKind.WorkbookCell; row: number; sheetName: string } | { absEndCol: boolean; absEndRow: boolean; absStartCol: boolean; absStartRow: boolean; end: [number, number]; kind: typeof FormulaNodeKind.WorkbookRange; sheetName: string; start: [number, number] } | { absEndCol: boolean; absStartCol: boolean; endCol: number; kind: typeof FormulaNodeKind.ColumnRange; startCol: number } | { absEndRow: boolean; absStartRow: boolean; endRow: number; kind: typeof FormulaNodeKind.RowRange; startRow: number } | { args: FormulaAST[]; kind: typeof FormulaNodeKind.Call; name: string } | { args: FormulaAST[]; callee: FormulaAST; kind: typeof FormulaNodeKind.Invoke } | { kind: typeof FormulaNodeKind.Binary; left: FormulaAST; op: BinaryOp; right: FormulaAST } | { kind: typeof FormulaNodeKind.Unary; op: UnaryOp; operand: FormulaAST }

Serializable formula abstract syntax tree.

typeFormulaNodeKind
type FormulaNodeKind = typeof FormulaNodeKind[keyof typeof FormulaNodeKind] FormulaNodeKind: { Array: "array"; Binary: "binary"; Boolean: "boolean"; Call: "call"; Cell: "cell"; ColumnRange: "columnRange"; Error: "error"; Intersection: "intersection"; … }

Type contract carried by the canonical FormulaNodeKind value.

typeFormulaReferenceNode
type FormulaReferenceNode = Extract<FormulaAST, { kind: typeof FormulaNodeKind.Cell | typeof FormulaNodeKind.Range | typeof FormulaNodeKind.WorkbookCell | typeof FormulaNodeKind.WorkbookRange | typeof FormulaNodeKind.RowRange | typeof FormulaNodeKind.ColumnRange }>

Reference leaves shared by immutable formula transformations.

typeUnaryOp
type UnaryOp = "-" | "+" | "%" | "NOT"

Supported unary formula operators.

Resolve references

interfaceFormulaCellPosition

Position of the formula currently being evaluated.

interfaceFormulaMetadataCellReference

Platform-neutral identity of one cell visible to formula evaluation.

interfaceFormulaReferenceArgument

A function argument that intentionally retains reference identity.

interfaceFormulaReferenceResolutionOptions

Options used when resolving text, names, or dynamic references.

interfaceFormulaReferenceValue

Reference identity returned by reference-preserving functions.

interfaceFormulaSheetMetadata

Stable workbook sheet identity and one-based display position.

interfaceFormulaWorkbookMetadata

Read-only workbook facts consumed by information formulas.

interfaceResolvedFormulaRange

Concrete finite range resolved against sheet bounds.

typeCellKey
type CellKey = number

Numeric key encoding one cell coordinate.

typeFormulaRangeSource
type FormulaRangeSource = { kind: typeof FormulaRangeSourceKind.CurrentSheet } | { kind: typeof FormulaRangeSourceKind.WorkbookSheet; sheetName: string }

Source owner for a resolved formula range.

typeFormulaRangeSourceKind
type FormulaRangeSourceKind = typeof FormulaRangeSourceKind[keyof typeof FormulaRangeSourceKind] FormulaRangeSourceKind: { CurrentSheet: "currentSheet"; WorkbookSheet: "workbookSheet" }

Type contract carried by the canonical FormulaRangeSourceKind value.

typeFormulaReferenceStyle
type FormulaReferenceStyle = "A1" | "R1C1"

Reference notation accepted by a reference resolver.

functionmapFormulaReferenceNodes
mapFormulaReferenceNodes(ast: FormulaAST, map: (node: FormulaReferenceNode): FormulaAST): FormulaAST

Traverses expression containers while preserving unchanged node identities.

Track structural changes

interfaceIDependencyGraph
interface IDependencyGraph IDependencyGraph: unknown
propertyreadonly pendingCount: number

Number of dirty formulas still waiting for evaluation.

propertyreadonly size: number

Total number of formula cells currently in the graph.

methodclear(): void

Clears all graph data.

methodenforceCommandBoundary(isCommandExecuting: (): boolean): void

Binds mutations to the owning editor command dispatch after initialization.

methodgetDependencies(formulaKey: number): readonly Dependency[]

Gets the range-level dependencies owned by one formula cell.

Returned dependencies are defensive copies and must not expose mutable graph internals. Non-formula cells return an empty array.

ReturnsRange-level Dependency list used by the formula.

formulaKey

CellKey for the formula cell.

methodgetDependents(key: number): number[]

Gets every formula that depends on one cell.

Uses three reverse-lookup indexes:

  1. Per-cell reverse dependencies (cellRevDeps) — O(1)
  2. Column-grouped interval lookup (columnRanges) — O(log N + K)
  3. Overflow-list linear scan (overflowRanges) — O(M)

ReturnsCellKeys for all formulas that depend on that cell.

key

CellKey for the referenced cell.

methodgetFormulaKeys(): readonly number[]

Gets formula cells currently registered in the graph.

The returned array is a stable snapshot for diagnostics and host status views. Mutating it must not affect graph internals.

ReturnsCellKeys for every formula cell with registered dependencies.

methodgetLastCycleKeys(): number[]

Cycle nodes detected by the last markDirty call.

Formulas in a cycle should display the #REF! error. markDirty detects cycles by topological elimination: repeatedly remove ready nodes; the remaining nodes are part of cycles.

methodgetNextReadyBatch(viewport: Set<number>, maxCount: number): number[]

Gets currently dirty formulas that can be evaluated immediately.

"Ready" means all dependencies for the formula are clean and there are no dirty dependencies. Viewport formulas are returned first so visible results update before off-screen ones.

ReturnsCellKeys for formulas that can be evaluated immediately.

viewport

CellKeys currently inside the viewport.

maxCount

Maximum number of formulas to return.

methodisDirty(key: number): boolean

Reports whether one formula cell is currently dirty.

Non-formula cells and clean formula cells return false.

ReturnsTrue when the formula is waiting for recalculation.

key

CellKey for the formula to inspect.

methodmarkClean(key: number): void

Marks one formula clean after evaluation completes.

Unlocks downstream dependencies by decrementing dirtyDepCount for each dirty formula that depends on key. When dirtyDepCount reaches 0, that formula becomes ready and can be returned by getNextReadyBatch.

key

CellKey for the formula that has finished evaluating.

methodmarkDirty(changedKeys: number[]): void

Marks all affected formulas dirty.

Starts from changedKeys and propagates dirty marks along reverse-dependency edges using BFS. Complexity is O(affected formulas + edges), with no topological sort.

Cycle detection records nodes inside the cycle in lastCycleKeys, which can be read through getLastCycleKeys().

changedKeys

CellKeys for cells whose values changed.

methodonStructureChanged(changes: StructureChange[]): void

Notifies the graph about structural changes.

Called for row/column insertions and deletions, and updates range coordinates in spatial indexes. Large change sets may choose lazy rebuilds by clearing indexes and rebuilding on the next query.

changes

Structural change list.

methodremoveCell(formulaKey: number): void

Removes one formula cell.

Clears the formula's:

  • forward dependencies (deps Map)
  • reverse indexes (cellRevDeps + columnRanges + overflowRanges)
  • dirty state (dirtySet + dirtyDepCount)
methodupdateCell(formulaKey: number, deps: Dependency[]): void

Registers or updates dependencies for one formula cell.

deps is a range-level Dependency list and is not expanded per cell. Existing formula-cell dependencies are removed before the new set is registered.

formulaKey

CellKey for the formula cell.

deps

Range-level Dependency list used by the formula.

variablesymbol
symbol: typeof symbol
interfaceFormulaRangeMove

Inclusive source bounds and displacement for reference-preserving cell movement.

propertyreadonly columnOffset: number
propertyreadonly end: readonly [number, number]
propertyreadonly includeUnqualified?: boolean

False when inspecting qualified references from a different sheet.

propertyreadonly rowOffset: number
propertyreadonly sheetName?: string

When supplied, qualified references to this sheet also follow the move.

propertyreadonly start: readonly [number, number]
interfaceFormulaStructureMoveOptions

Selects the reference namespace rewritten by a structure permutation.

interfaceShiftedStructureCoordinate

Result of shifting one coordinate through structure changes.

interfaceStructureMoveChange

Formula-aware row or column move.

typeDependency
type Dependency = { col: number; kind: typeof FormulaNodeKind.Cell; row: number } | { end: [number, number]; kind: typeof FormulaNodeKind.Range; start: [number, number] } | { col: number; kind: typeof FormulaNodeKind.WorkbookCell; row: number; sheetName: string } | { end: [number, number]; kind: typeof FormulaNodeKind.WorkbookRange; sheetName: string; start: [number, number] } | { endCol: number; kind: typeof FormulaNodeKind.ColumnRange; startCol: number } | { endRow: number; kind: typeof FormulaNodeKind.RowRange; startRow: number }

Formula dependency preserving cell and range reference semantics.

typeFormulaDynamicDependencyRegistrar
type FormulaDynamicDependencyRegistrar = (reference: ResolvedFormulaRange): void

Callback used to publish dynamic formula dependency edges.

typeStructureChange
type StructureChange = StructureInsertDeleteChange | StructureMoveChange
typeStructureChangeAxis
type StructureChangeAxis = typeof StructureChangeAxis[keyof typeof StructureChangeAxis] StructureChangeAxis: { Col: "col"; Row: "row" }

Type contract carried by StructureChangeAxis.

typeStructureChangeKind
type StructureChangeKind = typeof StructureChangeKind[keyof typeof StructureChangeKind] StructureChangeKind: { Delete: "delete"; Insert: "insert"; Move: "move" }

Type contract carried by StructureChangeKind.

typeStructureChangeType
type StructureChangeType = MatrixOTActionName.RowInsert | MatrixOTActionName.RowDelete | MatrixOTActionName.RowMove | MatrixOTActionName.ColInsert | MatrixOTActionName.ColDelete | MatrixOTActionName.ColMove

Matrix structure action understood by formula reference transforms.

variableFormulaStructureChangeActionNames
FormulaStructureChangeActionNames: readonly StructureChangeType[]

Matrix OT action names that participate in formula reference rebasing.

functionassertSupportedStructureChange
assertSupportedStructureChange(change: StructureChange): void

Validates indices on a formula structure change before rebasing.

functiongetStructureChangeAxis
getStructureChangeAxis(change: StructureChange): StructureChangeAxis | undefined

Returns the axis affected by one structure change.

functiongetStructureChangeKind
getStructureChangeKind(change: StructureChange): StructureChangeKind | undefined

Returns whether one structure change inserts, deletes, or moves coordinates.

functionmatrixOperationsToStructureChanges
matrixOperationsToStructureChanges(operations: readonly OTOperation[]): StructureChange[]

Converts Matrix OT operations into formula structure changes.

functionmatrixOperationToStructureChange
matrixOperationToStructureChange(operation: OTOperation): StructureChange | null

Converts one Matrix OT structure operation into a formula structure change.

functionmoveFormulaReferences
moveFormulaReferences(ast: FormulaAST, move: FormulaRangeMove): FormulaAST

Moves referenced identities, including absolute references, without rebasing unrelated references.

functionreorderFormulaReferences
reorderFormulaReferences(ast: FormulaAST, changes: readonly StructureMoveChange[], options?: FormulaStructureMoveOptions): FormulaAST

Reorders reference identities (including absolute references) through the entire permutation.

functionshiftStructureCoordinate
shiftStructureCoordinate(input: { absolute?: boolean; axis: StructureChangeAxis; changes: readonly StructureChange[]; coordinate: number }): ShiftedStructureCoordinate

Shifts one coordinate through formula structure changes.

Evaluate formulas

interfaceIFormulaEvaluator
interface IFormulaEvaluator IFormulaEvaluator: unknown
methodevaluate(ast: FormulaAST, context: EvalContext): FormulaValue

Evaluates one AST.

Recursively traverses the AST, performs operations, and handles error propagation:

  • Any FormulaError operand -> result is that error.
  • Division by zero -> #DIV/0!.
  • Type mismatch -> #VALUE!.
  • Unknown function name -> #NAME?.

ReturnsCalculated result.

ast

Parsed formula AST.

context

Evaluation context that provides cell-value reads.

methodevaluateBatch(asts: { ast: FormulaAST; key: number }[], context: EvalContext): EvalResult[]

Batch evaluation.

The TS implementation can call evaluate one by one. A WASM implementation can process all ASTs on the Rust side in one pass, avoiding 100K JS <-> WASM boundary crossings.

ReturnsEvaluation result list.

asts

AST list to evaluate; each item contains a CellKey and its AST.

context

Evaluation context.

methodregisterFunction(fn: FormulaFunction): void

Registers a custom function.

After registration, formulas can call the function by name. For example, registering AVERAGE allows =AVERAGE(A1:A10).

variablesymbol
symbol: typeof symbol
interfaceIFunctionRegistry
interface IFunctionRegistry IFunctionRegistry: unknown
methodenforceCommandBoundary(isCommandExecuting: (): boolean, dispatchRemoval: (id: number): void): void

Requires post-initialization writes to occur during the owning editor's command dispatch.

methodget(name: string): FormulaFunction | undefined

Gets a function definition by name.

ReturnsFunction definition, or undefined when it is not registered.

name

Function name, case-insensitive.

methodhas(name: string): boolean

Checks whether a function has been registered.

name

Function name, case-insensitive.

methodlist(): string[]

Lists all registered function names.

ReturnsFunction names in uppercase.

methodregister(fn: FormulaFunction): (): void

Registers a formula function.

fn

Function definition; name is stored in uppercase automatically.

methodregisterMany(functions: readonly FormulaFunction[]): (): void

Registers a group of formula functions and publishes one combined change notification.

functions

Function definitions in registration precedence order.

methodsubscribe(listener: (functionNames: readonly string[]): void): (): void

Subscribes to registrations and removals that can change formula results.

methodunregisterRegistration(id: number): void

Removes one tokenized registration; disposal may dispatch an owner command.

variablesymbol
symbol: typeof symbol
interfaceIAggregationCache
interface IAggregationCache IAggregationCache: unknown
methodclear(): void

Clears all caches.

methodenforceCommandBoundary(isCommandExecuting: (): boolean): void

Binds cache writes to the owning editor command dispatch after initialization.

methodgetCount(startRow: number, startCol: number, endRow: number, endCol: number): number

Gets the COUNT for a range, meaning the number of numeric cells.

Uses the same cache and incremental strategy as getSum.

methodgetSum(startRow: number, startCol: number, endRow: number, endCol: number): number

Gets the SUM for a range.

Cache hit returns directly in O(1). Cache miss requires a full O(N) scan on the first call.

Called by FormulaEvaluator while evaluating SUM, not exposed directly to users.

startRow

Start row (0-based).

startCol

Start column (0-based).

endRow

End row (0-based).

endCol

End column (0-based).

methodonCellChanged(row: number, col: number, oldVal: FormulaValue, newVal: FormulaValue): void

Notifies the cache that one cell value changed.

Finds every cached range covering the cell and updates incrementally:

  • newSum = oldSum - oldVal + newVal
  • FormulaError oldVal/newVal values are treated as non-numeric and do not affect sum.
row

Changed row (0-based).

col

Changed column (0-based).

oldVal

Previous value.

newVal

New value.

methodonStructureChanged(): void

Notifies the cache that rows or columns were inserted or deleted.

Structural changes invalidate all range caches because range coordinates have changed, so the cache must be cleared.

methodsetCount(startRow: number, startCol: number, endRow: number, endCol: number, count: number): void

Stores a successfully calculated COUNT for a rectangular range.

methodsetSum(startRow: number, startCol: number, endRow: number, endCol: number, sum: number): void

Stores a successfully calculated SUM for a rectangular range.

variablesymbol
symbol: typeof symbol
interfaceIFormulaCalculationTraceProvider
interface IFormulaCalculationTraceProvider IFormulaCalculationTraceProvider: unknown

Read-only subscription provider for formula calculation trace events.

Hosts should subscribe through the command surface, while plugins can inject this provider directly during the editor lifecycle. Events are local runtime trace and do not participate in OT or persistence.

methodsubscribeFormulaCalculationTrace(listener: FormulaCalculationTraceListener): (): void

Subscribes to formula calculation trace events for one editor instance.

ReturnsFunction that removes the listener; calling it more than once is safe.

listener

Callback invoked for future calculation trace events.

variablesymbol
symbol: typeof symbol

DI token for resolving IFormulaCalculationTraceProvider.

interfaceIFormulaIterationSettingsProvider
interface IFormulaIterationSettingsProvider IFormulaIterationSettingsProvider: unknown

Optional editor-local provider for circular formula calculation.

methodgetSettings(): FormulaIterationSettings
variablesymbol
symbol: typeof symbol
classFormulaFunctionArguments

Public coercion and argument-reading SDK for built-in and third-party formula functions.

constructorFormulaFunctionArguments(args: readonly FormulaArg[], context: EvalContext): FormulaFunctionArguments
methodboolean(index: number, fallback?: boolean): boolean | FormulaError

Reads a boolean argument from booleans, numbers, or TRUE/FALSE text.

methodinteger(index: number, fallback?: number): number | FormulaError

Reads a truncated integer argument.

methodisMissing(index: number): boolean

Returns whether an argument was omitted.

methodnumber(index: number, fallback?: number): number | FormulaError

Reads and coerces one argument to a finite number.

methodreference(index: number): FormulaError | ResolvedFormulaRange

Reads a reference argument without materializing it.

methodtext(index: number, fallback?: string): string | FormulaError

Reads and coerces one argument to text using spreadsheet-compatible scalar rules.

methodvalue(index: number): FormulaValue

Reads one scalar argument while preserving formula errors.

interfaceEvalContext

Host-provided services and data readers used during formula evaluation.

propertyaggregationCache?: IAggregationCache
propertyarrayFormulaMode?: "dynamic" | "legacy"
propertybudget?: FormulaEvaluationBudget
propertycurrentCell?: FormulaCellPosition
propertydateSystem?: FormulaDateSystem
propertydateTimeLocale?: FormulaDateTimeLocale
propertyexternalServices?: FormulaExternalServiceReader
propertyformulaSource?: IFormulaSourceProvider
propertylanguageService?: FormulaLanguageService
propertymetadata?: FormulaMetadataReader
propertyphoneticReader?: FormulaPhoneticReader
propertyreferenceResolver?: FormulaReferenceResolver
propertyregisterDynamicDependency?: FormulaDynamicDependencyRegistrar
propertyscope?: FormulaEvaluationScope
propertytextLocale?: FormulaTextLocale
propertyxmlXPath?: XmlXPathEvaluator
methodcurrentDateTime(): number
methodevaluateArrayFormula(ast: FormulaAST, scope?: FormulaEvaluationScope): FormulaValue
methodevaluateFormula(ast: FormulaAST, scope?: FormulaEvaluationScope): FormulaValue
methodforFormulaCell(cell: FormulaCellPosition): EvalContext
methodgetCellValue(row: number, col: number): FormulaValue
methodgetSheetShape(): [rowCount: number, colCount: number]
methodgetWorkbookCellValue(sheetName: string, row: number, col: number): FormulaValue
methodisCellInBounds(row: number, col: number): boolean
methodisCellOccupied(row: number, col: number): boolean
methoditerateRange(startRow: number, startCol: number, endRow: number, endCol: number): Iterable<FormulaValue>
methoditerateRangeCells(startRow: number, startCol: number, endRow: number, endCol: number): Iterable<FormulaRangeCell>
methoditerateWorkbookRange(sheetName: string, startRow: number, startCol: number, endRow: number, endCol: number): Iterable<FormulaValue>
methoditerateWorkbookRangeCells(sheetName: string, startRow: number, startCol: number, endRow: number, endCol: number): Iterable<FormulaRangeCell>
methodrandom(): number
methodreadReference(reference: ResolvedFormulaRange): FormulaValue
interfaceEvalResult

One result produced during formula batch evaluation.

interfaceFormulaCalculationTraceEventBase

Shared metadata attached to every calculation trace event.

interfaceFormulaEvaluationBudget

Host-neutral execution budget for formula evaluation.

interfaceFormulaFunctionDescriptor

Versioned presentation-neutral formula function metadata.

propertyreadonly category: string
propertyreadonly example: string
propertyreadonly externalServices?: readonly string[]
propertyreadonly maxArguments?: number

Authoritative upper argument bound. Omit for variadic or illustrative signatures.

propertyreadonly minArguments?: number

Authoritative lower argument bound. Omit when a signature is illustrative only.

propertyreadonly parameters: readonly FormulaFunctionParameterDescriptor[]
propertyreadonly returnKind?: "array" | "scalar" | "scalar-or-array"
propertyreadonly summary: string
propertyreadonly version: 1
interfaceFormulaIterationSettings

Per-editor calculation policy for circular formula dependencies.

typeFormulaCalculationTraceEvent
type FormulaCalculationTraceEvent = FormulaBatchFlushedEvent | FormulaRecalculationCompletedEvent | FormulaErrorChangedEvent | FormulaDependenciesChangedEvent

Formula calculation trace event union.

typeFormulaCalculationTraceEventPayload
type FormulaCalculationTraceEventPayload = conditional

Trace event payload before the provider assigns its sequence number.

typeFormulaCalculationTraceListener
type FormulaCalculationTraceListener = (event: FormulaCalculationTraceEvent): void

Listener invoked synchronously for calculation trace events.

typeFormulaFunctionArgumentKind
type FormulaFunctionArgumentKind = "any" | "number" | "text" | "boolean" | "cell" | "range" | "array" | "reference" | "function" | "rich"

Coarse argument kinds stable across formula-engine implementations.

variableFormulaCalculationTraceEventType
FormulaCalculationTraceEventType: { BatchFlushed: "formula.batchFlushed"; DependenciesChanged: "formula.dependenciesChanged"; ErrorChanged: "formula.errorChanged"; RecalculationCompleted: "formula.recalculationCompleted" }

Stable formula calculation trace event ids.

Formula values and errors

FormulaAST is the parsed expression. FormulaValue is the result a function or evaluator can return; FormulaArg represents an argument passed to a function. References and ranges use the FormulaReference* and FormulaRange* contracts, so a function can read cells without owning the Sheet document.

If you are implementing a function, start with FormulaFunction and EvalContext. If you are integrating an evaluator, start with IFormulaEvaluator and the reference-resolution contracts.

interfaceCellChange

Value transition for one formula-visible cell.

interfaceFormulaError

Serializable formula error value.

interfaceFormulaText

Text value carrying an explicit numeric coercion policy.

interfaceFormulaTupleValue

Tuple expression preserving the identity of its items.

typeErrorCode
type ErrorCode = FormulaErrorCode

Standard Excel-compatible error code.

typeFormulaArg
type FormulaArg = { kind: "value"; sourceAst?: FormulaAST; sourceKind?: FormulaNodeKind; value: FormulaValue } | { ast: FormulaAST; kind: "expression" } | { kind: "missing" } | { col: number; kind: typeof FormulaNodeKind.Cell; row: number } | { end: [number, number]; kind: typeof FormulaNodeKind.Range; start: [number, number] } | { col: number; kind: typeof FormulaNodeKind.WorkbookCell; row: number; sheetName: string } | { end: [number, number]; kind: typeof FormulaNodeKind.WorkbookRange; sheetName: string; start: [number, number] } | { endCol: number; kind: typeof FormulaNodeKind.ColumnRange; startCol: number } | { endRow: number; kind: typeof FormulaNodeKind.RowRange; startRow: number } | FormulaReferenceArgument

Function argument preserving lazy reference and expression semantics.

typeFormulaArray
type FormulaArray = FormulaValue[][]

Rectangular two-dimensional formula result represented as nested rows.

typeFormulaErrorCode
type FormulaErrorCode = typeof FormulaErrorCode[keyof typeof FormulaErrorCode] FormulaErrorCode: { DivisionByZero: "#DIV/0!"; Name: "#NAME?"; NotAvailable: "#N/A"; NullIntersection: "#NULL!"; Number: "#NUM!"; Reference: "#REF!"; Spill: "#SPILL!"; Value: "#VALUE!" }

Type contract carried by the canonical FormulaErrorCode value.

typeFormulaRichResult
type FormulaRichResult = FormulaHyperlinkResult | FormulaImageResult

Host-neutral result projected by a formula cell renderer.

typeFormulaValue
type FormulaValue = null | number | string | boolean | FormulaText | FormulaError | FormulaReferenceValue | FormulaTupleValue | FormulaCubeMemberValue | FormulaCubeSetValue | FormulaValue[]

Scalar, collection, error, or reference result produced by formulas.

functioncreateFormulaError
createFormulaError<T>(code: T): FormulaError & { code: T }

Creates a validated serializable formula error value.

functionisFormulaArgumentKind
isFormulaArgumentKind<K>(arg: FormulaArgumentLike | null | undefined, ...kinds: readonly K[]): arg

Narrows a formula argument to one or more discriminant kinds.

functionisFormulaError
isFormulaError(value: unknown): value

Returns whether a formula value is an error value.

functionisFormulaErrorCode
isFormulaErrorCode(code: unknown): code

Reports whether a runtime value is a canonical formula error code.

Results and status

interfaceIFormulaResultProvider
interface IFormulaResultProvider IFormulaResultProvider: unknown

Read-only provider for calculated formula results.

Rendering and other consumers use this interface to read per-client derived formula values without depending on a concrete formula plugin implementation.

methodforEachFormulaResultInRange(startRow: number, startColumn: number, endRow: number, endColumn: number, visit: (row: number, column: number): void): void

Visits calculated result coordinates in an inclusive range. Providers that project results into cells without persisted data must implement this so range consumers can discover those cells without probing empty positions.

methodgetFormulaResult(row: number, col: number): FormulaValue | undefined

Gets the calculated result for a formula anchor or one of its dynamic-array spill cells.

ReturnsFormulaValue, or undefined when not calculated or not a formula cell.

row

Row index (0-based).

col

Column index (0-based).

variablesymbol
symbol: typeof symbol

DI token for resolving IFormulaResultProvider.

interfaceIFormulaRichResultProvider
interface IFormulaRichResultProvider IFormulaRichResultProvider: unknown

Read-only provider for non-text visual results produced by formula cells.

interfaceIFormulaSourceProvider
interface IFormulaSourceProvider IFormulaSourceProvider: unknown

Read-only provider for the formula source text shown while editing.

methodgetFormulaSource(row: number, col: number): string | undefined

Gets the formula source that should be presented to the user for one cell.

Providers may return undefined when they do not own the queried cell. The default sheet formula provider returns the persisted formula text, while workbook-aware providers can return display text formatted from stable workbook bindings and the current sheet names.

variablesymbol
symbol: typeof symbol

DI token for resolving IFormulaSourceProvider.

interfaceIFormulaStatusProvider
interface IFormulaStatusProvider IFormulaStatusProvider: unknown

Read-only provider for formula result, source, dependency, and dirty status.

Hosts should prefer the command surface that delegates to this provider, while plugins can inject the provider directly when they run inside the editor lifecycle.

methodgetFormulaCellStatus(row: number, col: number): FormulaCellStatus

Gets a stable formula status snapshot for one sheet cell.

ReturnsFormula status with defensive copies of dependency arrays.

row

Row index (0-based).

col

Column index (0-based).

variablesymbol
symbol: typeof symbol

DI token for resolving IFormulaStatusProvider.

interfaceFormulaBatchFlushedEvent
interface FormulaBatchFlushedEvent extends FormulaCalculationTraceEventBase

Event emitted when one batch of derived results is flushed.

Inherited members 1

Inherited from FormulaCalculationTraceEventBase.

interfaceFormulaDependenciesChangedEvent
interface FormulaDependenciesChangedEvent extends FormulaCalculationTraceEventBase

Event emitted when one formula cell's dependency edges change.

Inherited members 1

Inherited from FormulaCalculationTraceEventBase.

interfaceFormulaErrorChangedEvent
interface FormulaErrorChangedEvent extends FormulaCalculationTraceEventBase

Event emitted when one formula cell's error code changes.

Inherited members 1

Inherited from FormulaCalculationTraceEventBase.

interfaceFormulaRecalculationCompletedEvent
interface FormulaRecalculationCompletedEvent extends FormulaCalculationTraceEventBase

Event emitted when one recalculation generation completes.

Inherited members 1

Inherited from FormulaCalculationTraceEventBase.

typeFormulaCellSource
type FormulaCellSource = "empty" | "value" | "formula"

Origin of a persisted cell, kept distinct from its calculated value.

variableFormulaBatchFlushedEventType
FormulaBatchFlushedEventType: "formula.batchFlushed"

Stable event id for a formula batch flush.

variableFormulaDependenciesChangedEventType
FormulaDependenciesChangedEventType: "formula.dependenciesChanged"

Stable event id for a formula dependency transition.

variableFormulaErrorChangedEventType
FormulaErrorChangedEventType: "formula.errorChanged"

Stable event id for a formula error transition.

variableFormulaRecalculationCompletedEventType
FormulaRecalculationCompletedEventType: "formula.recalculationCompleted"

Stable event id for formula recalculation completion.

Dates and locales

interfaceIFormulaDateSystemProvider
interface IFormulaDateSystemProvider IFormulaDateSystemProvider: unknown

Editor-local source for the workbook date serial system.

methodgetDateSystem(): FormulaDateSystem
variablesymbol
symbol: typeof symbol
interfaceIFormulaLocaleProvider
interface IFormulaLocaleProvider IFormulaLocaleProvider: unknown

Editor-local locale provider consumed by formula evaluation hosts.

methodgetDateTimeLocale(): FormulaDateTimeLocale

Returns the current date/time locale strategy for formula functions.

methodgetTextLocale(): FormulaTextLocale

Returns the current text byte/width locale strategy for formula functions.

variablesymbol
symbol: typeof symbol

DI token for resolving IFormulaLocaleProvider.

interfaceIFormulaTextServiceProvider
interface IFormulaTextServiceProvider IFormulaTextServiceProvider: unknown

Optional editor-local providers for metadata- and service-backed text formulas.

interfaceFormulaDateTimeMeridiemSymbol

Locale-specific AM/PM token.

interfaceFormulaDateTimeMonthSymbol

Locale-specific month-name token.

interfaceFormulaDateTimeParseOptions

Options passed to locale-aware formula date/time parsers.

interfaceFormulaDateTimeParseResult

Parsed Excel-compatible date/time serial and source components.

typeFormulaDateSystem
type FormulaDateSystem = typeof FormulaDateSystem[keyof typeof FormulaDateSystem] FormulaDateSystem: { Excel1900: 1900; Excel1904: 1904 }

Workbook date serial systems supported by formula evaluation.

typeFormulaLanguageServiceResult
type FormulaLanguageServiceResult = FormulaServiceCacheResult<string>

Synchronous result exposed by a host-managed language-service cache.

variableFormulaLanguageServiceDefinition
FormulaLanguageServiceDefinition: FormulaExternalServiceDefinition<FormulaLanguageService>

Canonical service identity used by cached language formulas and their hosts.

Add-ins and external services

interfaceFormulaAddInRegistrationRequest

Identifies one procedure exposed by a host-managed add-in.

interfaceFormulaAddInService

Host-owned native add-in boundary used by CALL and REGISTER.ID. Implementations must enforce authorization and isolation outside formula evaluation.

interfaceFormulaDirectAddInCall
interface FormulaDirectAddInCall extends FormulaAddInRegistrationRequest

Invokes a host-authorized procedure by module signature.

Inherited members 2

Inherited from FormulaAddInRegistrationRequest.

interfaceFormulaExternalServiceDefinition
interface FormulaExternalServiceDefinition<T>

Typed identity for one synchronous service view consumed by formulas.

interfaceFormulaExternalServiceReader

Read-only external-service view exposed during formula evaluation.

interfaceFormulaRegisteredAddInCall

Invokes a procedure previously resolved by REGISTER.ID.

typeFormulaAddInCall
type FormulaAddInCall = FormulaRegisteredAddInCall | FormulaDirectAddInCall

Supported host add-in invocation request.

typeFormulaAddInRegistrationId
type FormulaAddInRegistrationId = number

Stable numeric handle for one host-authorized add-in procedure.

typeFormulaServiceCacheResult
type FormulaServiceCacheResult = { status: typeof FormulaServiceCacheStatus.Ready; value: T } | { status: typeof FormulaServiceCacheStatus.Pending | typeof FormulaServiceCacheStatus.Unavailable }

Synchronous cache result; asynchronous work stays outside formula evaluation.

variableFormulaAddInServiceDefinition
FormulaAddInServiceDefinition: FormulaExternalServiceDefinition<FormulaAddInService>

Typed identity used to publish a host-specific add-in implementation.

variableFormulaServiceCacheStatus
FormulaServiceCacheStatus: { Pending: "pending"; Ready: "ready"; Unavailable: "unavailable" }

Canonical states of a host-managed formula service cache.

functiondefineFormulaExternalService
defineFormulaExternalService<T>(id: string, options?: Pick<FormulaExternalServiceDefinition<T>, "subscribeInvalidation">): FormulaExternalServiceDefinition<T>

Creates a stable external-service definition shared by hosts and plugins.

Cube and pivot services

interfaceFormulaCubeMemberValue

CUBE member or tuple identity with its display caption.

interfaceFormulaCubeSetValue

CUBE set identity with its display caption.

interfaceFormulaPivotDataService

Host service used by GETPIVOTDATA.

typeFormulaCubeKpiProperty
type FormulaCubeKpiProperty = typeof FormulaCubeKpiProperty[keyof typeof FormulaCubeKpiProperty] FormulaCubeKpiProperty: { KPICurrentTimeMember: 6; KPIGoal: 2; KPIStatus: 3; KPITrend: 4; KPIValue: 1; KPIWeight: 5 }

Type contract carried by the canonical FormulaCubeKpiProperty value.

typeFormulaCubeMemberExpression
type FormulaCubeMemberExpression = string | FormulaCubeMemberValue | readonly FormulaCubeMemberExpression[]

Serializable member or tuple expression accepted by CUBE services.

typeFormulaCubeQuery
type FormulaCubeQuery = { caption?: string; connection: string; kind: "kpi-member"; kpiName: string; property: FormulaCubeKpiProperty } | { caption?: string; connection: string; expression: FormulaCubeMemberExpression; kind: "member" } | { connection: string; kind: "member-property"; member: FormulaCubeMemberExpression; property: string } | { caption?: string; connection: string; kind: "ranked-member"; rank: number; set: string | FormulaCubeSetValue } | { caption?: string; connection: string; expression: string; kind: "set"; sortBy?: string; sortOrder?: number } | { kind: "set-count"; set: FormulaCubeSetValue } | { connection: string; kind: "value"; members: readonly FormulaCubeMemberExpression[] }

Serializable query handled by a host-owned CUBE service.

typeFormulaCubeResult
type FormulaCubeResult = FormulaValue | FormulaCubeMemberValue | FormulaCubeSetValue | FormulaError

Value returned from a host-owned CUBE service.

variableFormulaCubeServiceDefinition
FormulaCubeServiceDefinition: FormulaExternalServiceDefinition<FormulaCubeService>

Typed identity used to publish a host-specific CUBE implementation.

variableFormulaPivotDataServiceDefinition
FormulaPivotDataServiceDefinition: FormulaExternalServiceDefinition<FormulaPivotDataService>

Typed identity for the host pivot-data service.

variableFormulaCubeKpiPropertyValue
FormulaCubeKpiPropertyValue: { KPICurrentTimeMember: 6; KPIGoal: 2; KPIStatus: 3; KPITrend: 4; KPIValue: 1; KPIWeight: 5 }

Stable CUBE KPI property identifiers.

Web and data services

interfaceFormulaGoogleRequest

Serializable request used by host-backed Google-compatible formulas.

interfaceFormulaHyperlinkResult

Host-neutral hyperlink result projected by a formula renderer.

interfaceFormulaHyperlinkService

Host policy for validating and normalizing hyperlink targets.

interfaceFormulaImageResource

Host-neutral image resource returned by an image loader.

interfaceFormulaImageResult

Host-neutral image result projected by a formula renderer.

interfaceFormulaRtdKey

Stable key used to read one RTD subscription.

interfaceFormulaWebService

Synchronous view of HTTP response text loaded explicitly by the host.

variableFormulaGoogleServiceDefinition
FormulaGoogleServiceDefinition: FormulaExternalServiceDefinition<FormulaGoogleService>

Host-neutral service identity shared by Google-compatible cached formulas.

variableFormulaHyperlinkServiceDefinition
FormulaHyperlinkServiceDefinition: FormulaExternalServiceDefinition<FormulaHyperlinkService>

Typed identity for the host hyperlink service.

variableFormulaImageServiceDefinition
FormulaImageServiceDefinition: FormulaExternalServiceDefinition<FormulaImageService>

Typed identity for the host image service.

variableFormulaRtdServiceDefinition
FormulaRtdServiceDefinition: FormulaExternalServiceDefinition<FormulaRtdService>

Typed identity for the host RTD service.

variableFormulaStockHistoryServiceDefinition
FormulaStockHistoryServiceDefinition: FormulaExternalServiceDefinition<FormulaStockHistoryService>

Stable external-service identity used by STOCKHISTORY and host caches.

variableFormulaWebLimits
FormulaWebLimits: Readonly<{ textLength: 32767; urlLength: 2048 }>

Excel limits applied independently of the host's transport/security policy.

variableFormulaWebServiceDefinition
FormulaWebServiceDefinition: FormulaExternalServiceDefinition<FormulaWebService>

Shared identity for WEBSERVICE cache registration and recalculation.