import { DataContainer, DcuplInitOptions, ViewDefinition, ListItem, ModelDefinition, RawItem, ChangeDetector, DependencyGraph, AttributeDependencyGraph } from '@dcupl/common'; import { DcuplModel } from './model/model.js'; import { QualityController } from '../quality/quality.controller.js'; import { ChangeTracker } from './change-tracker.js'; import { PartialUpdateMetrics } from './partial-update-metrics.js'; import { DcuplApi } from '../dcupl/dcupl-api.js'; type ModelParserCalculationTimingEntry = { modelName: string; step: string; value: number; }; export declare class ModelParser { cdRef: ChangeDetector; qualityController: QualityController; dcuplInstance: DcuplApi; unprocessedModelDescriptions: Map; protected unprocessedData: DataContainer[]; private keyedContainers; private replacedRowKeys; private definitionChanges; private modelDrops; private droppedModels; dependencyGraph: DependencyGraph; attributeDependencyGraph: AttributeDependencyGraph; changeTracker: ChangeTracker; partialUpdateMetrics: PartialUpdateMetrics; views: Map; models: Map; initOptions: DcuplInitOptions; private calculationTimings; private log; private _sealed; /** True after seal(): the staged log is gone, every write is rejected (#332). Read-only; seal() sets it (#454). */ get sealed(): boolean; constructor(cdRef: ChangeDetector, qualityController: QualityController, dcuplInstance: DcuplApi); /** * Drops the staged raw rows and the change tracker. The built models, indices and quality * errors stay. After this, addData/addModel/reprocessData/init/update throw DcuplSealedError. * The preconditions are checked by DcuplApi.seal(): init() completed, no apply in flight, no pending * loader resource, no unapplied staged changes (rows or model definitions). */ seal(): void; private assertNotSealed; init(): Promise; private prepareModels; /** * Stages dropping `modelKey` (#415): the next `init()` or `update()`, which takes the full path, * removes its definition, its data and the model, as in an instance that never had it: the global * API (`query.*`, `fn.*`) throws for the key, and lists created on it serve no rows. Registering * the key again with `addModel` before that cancels the drop; registering it after rebuilds the * model in the same instance, so those lists follow it. The app loader uses it when a model left * the loader config. */ dropModel(modelKey: string): void; /** Whether the next init or full update drops `modelKey` (see dropModel). */ hasModelDrop(modelKey: string): boolean; private applyModelDrops; /** * Unregisters a model (#420): its stored definition, its instance and its queued data containers, * so the next init does not bring it back. Counts as a definition change, so the next `update()` * rebuilds everything and references to the model resolve as to a missing model. */ removeModel(modelKey: string): void; /** Unregisters a view; takes effect at once (#420). */ removeView(viewKey: string): void; /** * Records that `models.set`/`models.update` changed the definition of `modelKey` (#408): the next * `update()` rebuilds everything, like `init()`. */ markDefinitionChanged(modelKey: string): void; /** The models whose definition changed since the last init (#408). */ getDefinitionChanges(): string[]; private validateModels; /** * initDependencyGraph * The dependencies are only affected by references. Derived properties/references do not count since they * are only possible if references are already present to derive from. Same goes for resolved references. */ private initDependencyGraph; /** * buildAttributeDependencyGraph * Analyzes all models and their attributes to build attribute-level dependencies. * This enables partial updates by tracking which attributes depend on others. */ private buildAttributeDependencyGraph; /** * The processing step of an attribute, as the full path computes it: 1 basic * properties and references, 2 query and resolved references, 3 derived and * grouped references and derived and expression properties, 4 derived * properties and references on a resolved reference (#400). */ private getAttributeProcessingStep; /** * Validates that all expected attributes are present in the attribute dependency graph. * Logs warnings for any missing attributes that might indicate parsing failures. */ private validateAttributeDependencyGraph; /** * Process expression property dependencies * Expression properties depend on all attributes referenced in the template */ private processExpressionProperty; /** * Splits an expression variable path into its segments; bracket indices become segments of * their own: "tags[0].name" -> ["tags", "0", "name"]. */ private getExpressionPathSegments; /** * Process derived property dependencies * Derived properties depend on a local reference and the remote property */ private processDerivedProperty; /** * Process query reference dependencies * Query references depend on properties used in the query template */ private processQueryReference; /** * Process resolved reference dependencies * Resolved references depend on the inverse reference from the remote model */ private processResolvedReference; /** * Process derived reference dependencies * Derived references depend on a local reference */ private processDerivedReference; /** * Process grouped reference dependencies * Grouped references depend on a source reference */ private processGroupedReference; /** * Applies the pending changes, on the partial path when it is possible and worth it, otherwise * as a full rebuild (`init()`). * * @returns The path taken: `'partial'` or `'full'` (dcupl.update() reports it as * `isPartialUpdate` on `dcupl_partial_update`, #383) */ update(): Promise<'partial' | 'full'>; /** * Determines if a partial update is possible and beneficial * @returns object with decision and reason */ private shouldUsePartialUpdate; /** * Query references are computed on the full path only: the partial path has * no step that re-runs their queries (#367). Returns the first query * reference (`Model.reference`) whose result the pending changes can alter, * so that update() takes the full path instead: * - its owner model changed — the owner's rows fill the query templates; * - its target model, or a model the target reaches through its references, * changed — deep query paths and derived/resolved attributes read those. * Recomputing just the affected query references on the partial path is a * performance follow-up. */ private findQueryReferenceAffectedByChanges; /** * The model itself plus every model it reaches through its references of * any kind, transitively. */ private getModelsReachableFrom; /** * Performs a partial update by only reprocessing changed attributes and their dependents */ private partialUpdate; reprocessData(): Promise; protected getSortedCalculationTimings(): ModelParserCalculationTimingEntry[]; /** * Registers a model definition, merged into an earlier one with the same key (`models.update`; * `models.set` drops the earlier one first). The parser keeps its own copy, so later changes to * `model` do not reach this instance, and init does not write into it (#314). Inline `data` is not * part of the stored definition: it is queued through `addData`, like `dcupl.data.set`, so * `models.get` does not return it. */ addModel(model: ModelDefinition): void; private mergeModels; addData(container: DataContainer): void; /** Registers a view definition. The parser keeps its own copy (#314). */ addView(view: ViewDefinition): void; /** * Sets a validation error for a model. * Requires both global quality controller AND model-specific quality to be enabled. * This implements the two-tier validation system. */ private setError; /** * Folds each model's queued containers into the one `set` container that is * processed. A lone `set` container whose rows have unique keys is processed * as is. Every other group goes through mergeContainers(), which applies the * containers in order and dedupes the rows by key: a lone `update`/`remove` * on a model without data changes nothing (#365), and duplicate keys in a * `set` payload keep only the last row (#369). */ private getMergedContainers; /** * Keys of the rows that a later row with the same key replaced in the `set` * payload behind `container`, one entry per replaced row (#369). Empty for * containers without duplicate keys. */ getReplacedRowKeys(container: DataContainer): readonly string[]; /** * A lone container needs no merge when it is a `set` whose rows have unique * keys. A lone `update`/`upsert`/`remove` is merged onto an empty dataset, * so an update or remove on a model without data changes nothing (#365). */ private isProcessableAsIs; /** * Collapse the accumulated container history into the already-merged per-model * result so `unprocessedData` stays bounded (≈ one container per model) instead * of growing with every data mutation — the merged result is identical to * re-merging the full history, so this is behavior-preserving and only affects * how much is re-merged on the next cycle. Runs after processing completes. * * - Only the containers the apply merged (`consumedContainers`) are collapsed. * Every other container stays queued after the merged result, keeping its * relative order: pending (unresolved) placeholders, and placeholders * resolved or containers staged while the apply ran — it yields to the * event loop, and dropping those lost their data. A placeholder that was * already pending therefore folds after containers this apply merged, even * ones staged after it (as before). * - Merged containers are registered as already-keyed so a subsequent * handleAlternativeKey pass does not re-apply a composite keyProperty (#182). */ private consolidateUnprocessedData; /** * Re-records the containers still queued on top of the merged result after * an apply cleared the change tracker. They were staged (or their * placeholder resolved) while the apply ran and are not processed yet: the * next apply must still see them, or its partial path skips their data. * Left out: pending placeholders, which carry no data yet (as before), and * internal `$` models, whose containers the apply stages and builds itself * (quality initData stages the error-tracking models, built at once or on * first read). */ private retrackUnprocessedData; /** * Applies a model's containers in order and returns one `set` container * with one row per key. Keys are compared as strings, the same identity the * model stores, and rows without a key are passed through for the model to * drop as `MissingKey`. * * - `set`: replaces the rows. Rows with the same key are deduped: the last * row wins as a whole and keeps the first row's position; the keys of the * replaced rows are kept for the model's NonUniqueKey errors (#369). * - `upsert`: merges a row into the stored row with the same key (see * mergeRow) or inserts it. * - `update`: merges a row into the stored row with the same key and ignores * unknown keys, also when the model has no rows yet (#365). * - `remove`: deletes the rows with the given keys; unknown keys are ignored. * * The result carries the key settings of the `set` container that supplied * the rows (without one: of the last container that has them), so the * model's errors name the same key attribute. */ private mergeContainers; /** * Folds an update/upsert payload row into the stored row. Every attribute * the payload carries replaces the stored value wholesale: arrays * (Array<…> properties, multi-valued references) and objects (json/any * properties) are never merged element-wise or recursively — change * tracking and the partial path work per attribute, too. Attributes absent * from the payload, or `undefined` in it, keep their stored value (send * `null` to clear one). Returns a new row and mutates neither input: rows * can be caller-owned, and json values are stored by reference. */ private mergeRow; /** * Mirrors mergeContainers() for the loader source-metadata side channel: when * several resources feed one model, their per-resource coercion metadata must * be combined onto the merged container, otherwise the CSV aggregation path in * QualityController loses its side channel (dcupl#197). 'set'/default resets the * effective metadata (the dataset is replaced); 'upsert'/'update' accumulate * columns and failure counts; 'remove' leaves the effective metadata unchanged * (an approximation — removed rows' failures may be over-counted). */ private mergeContainerSourceMetadata; private cloneCoercionSamples; private connectDataWithModels; /** * Performs partial data processing by only reprocessing changed attributes and their dependents * @param containers - Data containers to process */ private connectDataWithModelsPartial; /** * The merged rows of the items the pending changes touch, per model: rows of * existing items and rows the update inserts (no stored item yet). Rows * without a key are left out — init() reported them already (MissingKey). */ private splitChangedRows; /** * The items, per model, whose basic reference points at an item that this * update inserts or removes (#368). Records those references as changed, so * they and their dependents are processed again. Matches the raw reference * value (any separator part, array element or object key) and the stored * one, so strict references that dropped a missing key are found too. * References within one model count too: they resolve against every row of * the model, whatever its position (#411). */ private getItemsReferencingChangedItems; /** Whether a raw or stored reference value names one of `keys` (a superset match). */ private referencesAnyKey; /** * Scopes step 1 of a partial update to the rows that changed (#368): the * other rows' raw values did not change, so reprocessing them only recorded * their errors again. Rows the update inserts are processed for every basic * attribute, as init() does. With error tracking on, it removes the error * records the update re-derives (QualityController.prepareErrorsForPartialUpdate); * the attributes whose errors need every row are reprocessed for all rows. */ private getPartialRowScopes; /** * Step 1 of the partial path for one model (#368): the changed attributes of * the changed rows, every basic attribute of the inserted rows, and the * attributes of `scope.allRowsAttributes` for every row. */ private addBasicAttributesPartial; /** `container` limited to `rows`, keeping its source metadata (the error `origin`). */ private getContainerWithRows; /** * Computes the processing order for resolved references in step 2 * Resolved references that depend on basic references should be processed before * resolved references that depend on other resolved references * @param processingPlan - The full processing plan * @returns Array of model keys in the correct processing order */ private getResolvedReferenceProcessingOrder; /** * Processes specific attributes for a given step across all affected models * @param step - Processing step (1-4) * @param processingPlan - Map of modelKey → Map of step → Set of attributeKeys * @param containers - Data containers being processed */ private processAttributesForStep; handleAlternativeKey(containers: DataContainer[]): DataContainer[]; private handleDataContainer; /** * The processing of handleDataContainer without yielding to the event loop, for callers that * cannot wait: the error-tracking models are built on first read, inside a synchronous read (#444). * It emits the same `dcupl_handle_datacontainer` message, when the containers are processed. */ processDataContainersSync(containers: DataContainer[]): void; /** * Steps 1-4 of the data processing. Yields where the async caller gives the event loop a turn * (performance.containerBatchSize decides where, as before). */ private processDataContainers; /** * Called before a read of `modelKey`'s rows from outside the parser: the error-tracking models * are built on first read (#444). */ prepareModelForRead(modelKey: string | undefined): void; _getModelKeys(): string[]; _getViewKeys(options?: { modelKey: string; }): string[]; /** * Gets the total number of items across all models * @returns Total count of items */ getTotalItemCount(): number; } export {};