{"version":3,"file":"catalog.cjs","sources":["../../src/libs/catalog/filter/filter.ts","../../../../node_modules/lodash-es/_arrayIncludes.js","../../../../node_modules/lodash-es/_isFlattenable.js","../../../../node_modules/lodash-es/_baseFlatten.js","../../../../node_modules/lodash-es/_baseDifference.js","../../../../node_modules/lodash-es/difference.js","../../src/libs/catalog/item/item.ts","../../src/libs/catalog/catalog-api.ts","../../src/libs/catalog/catalog.ts"],"sourcesContent":["import {\n  Aggregation,\n  AggregationOptions,\n  CatalogApiOptions,\n  ChangeDetector,\n  DcuplFacetCalculationOptions,\n  DcuplFilterOptions,\n  DcuplFiltersOptions,\n  DcuplGroupByOptions,\n  DcuplItemsOptions,\n  DcuplQueryBuilder,\n  FilterComparisonType,\n  FilterItem,\n  FilterItemDateRangeValue,\n  FilterItemEntry,\n  FilterItemNumberRangeValue,\n  FilterItemType,\n  FilterStringArray,\n  FilterStringSingle,\n  getFacets,\n  InverseIndexValuesMap,\n  ListItem,\n  PropertyFilterItem,\n  PropertyType,\n  ReferenceFilterItem,\n  SectionItem,\n  SortingProjection,\n  TextFilterItem,\n  getAggregation,\n  IndicesController,\n  IndexContext,\n  CacheController,\n  resolveCacheMaxSize,\n  resolveProjectionCacheMaxSize,\n  GroupByResponse,\n  QueryManager,\n  perf,\n  deepQueryService,\n  getDeepPathValues,\n  QueryAttributeEntry,\n  Projection,\n  estimateCachedValueSize,\n} from '@dcupl/common';\n\nimport { DcuplModel, ModelParser } from '../../model-parser';\nimport { ItemService } from '../item/item';\n\n/** How many rows of a projected map are sampled to size it, see {@link estimateProjectionSize}. */\nconst PROJECTION_SAMPLE_ROWS = 8;\n\n/**\n * Estimated bytes of a projected map, the `sizeHint` of its cache entry. The entry owns one new\n * object per row (nested projected remote objects included), which the cache's constant-time\n * estimate does not walk, so the map is sized from a sample: `32 + rows × (24 + the largest\n * estimate of a sampled row)`.\n *\n * Up to {@link PROJECTION_SAMPLE_ROWS} rows are sampled, evenly spaced (the rows at index\n * floor(i × rows / n)), and the largest estimate is used, so that a row without the reference does\n * not under-count the whole map (a list whose row 0 has no `product` was counted 3.5 times too\n * small from that row alone). Remaining limits: `estimateCachedValueSize(row, 2)` does not walk\n * arrays (multi-valued nested projections count per slot) and stops at depth 2, so multi-valued or\n * 3+-hop paths can still be under-counted.\n */\nfunction estimateProjectionSize(projectedData: Map<string, unknown>): number {\n  const rows = projectedData.size;\n  const sampleCount = Math.min(PROJECTION_SAMPLE_ROWS, rows);\n  let largestRow = 0;\n  let sampled = 0;\n  let index = 0;\n  for (const row of projectedData.values()) {\n    if (index === Math.floor((sampled * rows) / sampleCount)) {\n      largestRow = Math.max(largestRow, estimateCachedValueSize(row, 2));\n      if (++sampled === sampleCount) break;\n    }\n    index++;\n  }\n  return 32 + rows * (24 + largestRow);\n}\n\nexport class Filter<ListType extends ListItem = ListItem> {\n  public initialData!: Map<string, ListType>;\n  private _filteredData!: Map<string, ListType>;\n  /** Set when caches were dropped without an eager recompute — the next\n   *  filteredData read recomputes from initialData (#245). */\n  private filteredDataStale = false;\n  public model!: DcuplModel<ListType>;\n\n  public get filteredData(): Map<string, ListType> {\n    if (this.filteredDataStale) {\n      this.filteredDataStale = false;\n      this._filteredData = this.getFilteredData(this.initialData, false);\n    }\n    return this._filteredData;\n  }\n\n  public set filteredData(value: Map<string, ListType>) {\n    this._filteredData = value;\n    this.filteredDataStale = false;\n  }\n  public filterItems: Map<string, FilterItem> = new Map();\n  public queryBuilder!: DcuplQueryBuilder;\n\n  public cacheCtrl!: CacheController;\n\n  /**\n   * The projected copies deep facets and deep filters build (#443), in their own controller so that\n   * results (`cacheCtrl`, `performance.cache.maxSize`) and projections\n   * (`performance.cache.maxProjectionSize`) do not evict each other: a projection holds a new object\n   * per row and is far larger than a cached result.\n   */\n  public projectionCacheCtrl!: CacheController;\n\n  /**\n   * The other models this list's current results were read through: every\n   * model on a dotted path (`memberships.user.daysInactive` on `project` reads\n   * `membership` and `user`) that a query, facet, aggregate, groupBy, pivot or\n   * suggestion resolved since the caches were last dropped. dcupl.update()\n   * treats the list as affected when any of them changes (#284). Cleared\n   * together with the caches: after that nothing cached can be stale, and the\n   * next read registers the paths it resolves again.\n   */\n  private dependencyModels: Set<string> = new Set();\n\n  constructor(\n    public modelParser: ModelParser,\n    public cdRef: ChangeDetector,\n    public item: ItemService,\n    public indicesController: IndicesController,\n    public queryManager: QueryManager,\n  ) {\n    const cacheOptions = this.cdRef.dcuplInitOptions.performance?.cache;\n    this.cacheCtrl = new CacheController(!!cacheOptions?.enabled, resolveCacheMaxSize(cacheOptions));\n    this.projectionCacheCtrl = new CacheController(\n      !!cacheOptions?.enabled,\n      resolveProjectionCacheMaxSize(cacheOptions),\n    );\n  }\n\n  public init(model: DcuplModel<ListType>, data: Map<string, ListType>): void {\n    this.model = model;\n    this.initialData = data;\n    this.filteredData = this.initialData;\n\n    this.queryBuilder = new DcuplQueryBuilder();\n    this.queryBuilder.init({ modelKey: model.key });\n\n    this.initFilterItems({ skipProcessing: true });\n  }\n\n  /**\n   * Unified cache invalidation - Single source of truth for clearing all caches\n   * This prevents accidentally missing a cache when invalidating. Drops every\n   * deep index too: another model on its path can have changed. The indices of\n   * this list's own model that a partial update made stale are dropped by the\n   * model (DcuplModel.resetIndicesForChangedAttributes).\n   */\n  private invalidateAllCaches(): void {\n    // Clear every cached result and every cached projection (they live in their own controller)\n    this.cacheCtrl.clear();\n    this.projectionCacheCtrl.clear();\n    this.dependencyModels.clear();\n\n    // Debug logging if enabled\n    const debug = this.cdRef.dcuplInitOptions.logging?.level === 'debug';\n    const deepIndicesReset = debug ? this.indicesController.getIndexCount().deep : 0;\n    this.indicesController.resetAllDeepIndices();\n\n    if (debug) {\n      const indexCount = this.indicesController.getIndexCount();\n      console.debug('[Filter] Caches invalidated', {\n        deepIndicesReset,\n        shallowIndicesPreserved: indexCount.shallow,\n        totalIndices: indexCount.total,\n      });\n    }\n  }\n\n  public update(model: DcuplModel<ListType>, data: Map<string, ListType>, indicesController: IndicesController): void {\n    this.model = model;\n    this.initialData = data;\n    this.indicesController = indicesController;\n\n    // Single invalidation point - prevents missing caches\n    this.invalidateAllCaches();\n\n    this.filteredData = this.getFilteredData(this.initialData, false);\n    this.initFilterItems({ skipProcessing: true });\n  }\n\n  public resetCache(): void {\n    this.invalidateAllCaches();\n    // filteredData was computed before the caches were dropped — recompute it\n    // lazily on the next read so no caller can serve a pre-drop result, and\n    // lists nobody reads between updates pay nothing (#245).\n    this.filteredDataStale = true;\n  }\n\n  /**\n   * Extract all deep query attributes from the query\n   */\n  private getDeepQueryAttributes(query: any): string[] {\n    const attributes = new Set<string>();\n    if (!query || !query.queries) return [];\n\n    for (const group of query.queries) {\n      if (!group.queries) continue;\n      for (const q of group.queries) {\n        if (q.attribute) {\n          const parsed = deepQueryService.parse(q.attribute);\n          if (parsed.isDeepQuery) {\n            attributes.add(q.attribute);\n          }\n        }\n      }\n    }\n    return Array.from(attributes);\n  }\n\n  /**\n   * Create projection for query's deep attributes\n   */\n  private getProjectionForQuery(query: any): any {\n    const deepAttributes = this.getDeepQueryAttributes(query);\n    if (deepAttributes.length === 0) return null;\n\n    const entries = deepAttributes.map((attr) => deepQueryService.parse(attr));\n    return this.projectionFor(entries);\n  }\n\n  /**\n   * Builds the projection that resolves `entries` on this list's items and\n   * records the models it reads through in {@link dependencyModels}. Every\n   * deep-path read of this list goes through here, so the set is complete.\n   */\n  public projectionFor(entries: QueryAttributeEntry[]): Record<string, boolean | Record<string, boolean>> {\n    const projection = this.queryBuilder.getProjectionForAttributeEntries(entries);\n    this.item.getProjectionModels(projection, this.model, this.dependencyModels);\n    return projection;\n  }\n\n  /** The models a path to `attribute` reads through (not this list's own). */\n  private pathModels(attribute: string): Set<string> {\n    const entry = deepQueryService.parse(attribute);\n    if (!entry.isDeepQuery) {\n      return new Set();\n    }\n    return this.item.getProjectionModels(this.projectionFor([entry]), this.model);\n  }\n\n  /**\n   * The models other than this list's own that its cached results depend on\n   * (see {@link dependencyModels}).\n   * @internal\n   */\n  public getDependencyModels(): ReadonlySet<string> {\n    return this.dependencyModels;\n  }\n\n  /**\n   * Generate cache key from deep query attributes\n   */\n  private getProjectionCacheKey(query: any): string {\n    const deepAttributes = this.getDeepQueryAttributes(query);\n    if (deepAttributes.length === 0) return '';\n\n    // Sort attributes for consistent cache keys\n    return deepAttributes.sort().join('|');\n  }\n\n  /**\n   * Projects `data` for `projection` and caches the projected map in the list's projection cache\n   * (`projectionCacheCtrl`) under `'projection'` (#443): it is bounded by\n   * `performance.cache.maxProjectionSize` and evicted, least recently used first, with the list's\n   * other projections; queries and facet results (`cacheCtrl`, `maxSize`) never evict it. It is\n   * dropped in `invalidateAllCaches` (`projectionCacheCtrl.clear()`), together with the results,\n   * which runs when a model on the list's `dependencyModels` changes (#284); the tag it carries\n   * mirrors the `'data'` entry's, so `invalidateByDependencies` can drop it granularly. A\n   * projection larger than the budget is built and returned but not kept.\n   */\n  private getProjectedData(data: Map<string, ListType>, projection: any, cacheKey: string): Map<string, ListType> {\n    const context = cacheKey ? this.projectionCacheCtrl.generateContext({ projection: cacheKey }) : undefined;\n    if (context) {\n      const cached = this.projectionCacheCtrl.get('projection', context);\n      if (cached) return cached;\n    }\n\n    const projectedData = new Map<string, ListType>();\n    for (const [key, item] of data) {\n      projectedData.set(key, this.item.getProjectedData(projection, this.model, item) as ListType);\n    }\n\n    if (context) {\n      const pathModels = this.item.getProjectionModels(projection, this.model);\n      this.projectionCacheCtrl.set(\n        'projection',\n        context,\n        projectedData,\n        { models: new Set([this.model.key, ...pathModels]), modelAttributes: new Map() },\n        estimateProjectionSize(projectedData),\n      );\n    }\n    return projectedData;\n  }\n\n  /**\n   * The list's unfiltered data in the shape {@link getFilteredData} evaluates the current query\n   * on: projected for the query's deep attributes, or the stored rows when it has none. Facets on\n   * a dotted path count from this (minus the excluded group) rather than from `filteredData`,\n   * which is already narrowed by the full query (#276). The facet attribute itself is not\n   * projected: its index is read from the stored rows (#448). So a facet adds no projected copy;\n   * a deep query shares the one entry `query.execute` keeps in the list's projection cache,\n   * bounded by `performance.cache.maxProjectionSize` and dropped on every data update.\n   */\n  public getQueryProjectedInitialData(): Map<string, ListType> {\n    const query = this.queryBuilder.getQuery();\n    const projection = this.getProjectionForQuery(query);\n    if (!projection) {\n      return this.initialData;\n    }\n    return this.getProjectedData(this.initialData, projection, this.getProjectionCacheKey(query));\n  }\n\n  /**\n   * The values the dotted `attributeKey` resolves to on `item`, as a projection of `item` would\n   * answer them. A path without brackets is read from the stored rows of the models on it\n   * (`segments`, no projected copy, #448); a bracket path (`items[*].color`) is projected.\n   */\n  private getDeepAttributeValues(\n    item: ListType,\n    attributeKey: string,\n    segments: readonly string[] | undefined,\n    projection: Projection<ListType>,\n  ): any[] {\n    const projected = (): any[] =>\n      getDeepPathValues(this.item.getProjectedData(projection, this.model, item), attributeKey);\n    return segments ? this.item.getDeepPathValuesOf(this.model, item, segments, projected) : projected();\n  }\n\n  private initFilterItems(options?: DcuplFiltersOptions): void {\n    const attributes = [...this.model.properties.values(), ...this.model.references.values()];\n\n    attributes.forEach((attribute) => {\n      if (attribute.filter) {\n        if (Array.isArray(options?.filterKeys)) {\n          if (options?.filterKeys.includes(attribute.key)) {\n            this.updateFilterItem(attribute.key, options);\n          }\n        } else {\n          this.updateFilterItem(attribute.key, options);\n        }\n      }\n    });\n  }\n\n  /**\n   * @param indexCoversData - `indexMap` was built from exactly `relevantData`, so `distinct` can\n   *   count the index without checking every key against the data (dcupl#500).\n   */\n  public getAggregate(\n    options: AggregationOptions,\n    relevantData: Map<string, ListType>,\n    indexMap: InverseIndexValuesMap,\n    indexCoversData = false,\n  ): Aggregation {\n    this.queryManager.validateDateGroupBounds(this.model.key, options);\n\n    // Check if this is a deep query attribute\n    const attributeEntry = deepQueryService.parse(options.attribute);\n\n    if (attributeEntry.isDeepQuery) {\n      // For deep queries, data is already projected by catalog-api\n      // Use the full path with projected data\n      return getAggregation(options, relevantData, indexMap, options.attribute, indexCoversData);\n    } else {\n      // For shallow attributes, get from model as before\n      const attribute = this.model.getAttribute(options.attribute);\n\n      if (!attribute) {\n        throw new Error('Attribute not found');\n      }\n\n      return getAggregation(options, relevantData, indexMap, attribute.key, indexCoversData);\n    }\n  }\n\n  public getSections(options: DcuplGroupByOptions<any>): GroupByResponse {\n    // before any section is built: a set without sections must refuse a bad bound as well (#514)\n    options.aggregates?.forEach((aggregate) => this.queryManager.validateDateGroupBounds(this.model.key, aggregate));\n\n    const response: GroupByResponse = {\n      _meta: {\n        currentSize: 0,\n        initialSize: 0,\n      },\n      items: [],\n    };\n\n    // Check if this is a deep query attribute\n    const attributeEntry = deepQueryService.parse(options.attribute);\n    const isDeepQuery = attributeEntry.isDeepQuery;\n\n    let attribute;\n    if (!isDeepQuery) {\n      attribute = this.model.getAttribute(options.attribute);\n      if (!attribute) {\n        throw new Error('Attribute not found');\n      }\n    }\n\n    let sectionItems: Map<string, SectionItem> = new Map();\n\n    let remoteModel: DcuplModel | undefined;\n\n    // Only get remote model for non-deep queries with references\n    if (!isDeepQuery && attribute && (attribute.type === 'singleValued' || attribute.type === 'multiValued')) {\n      remoteModel = this.modelParser.models.get(attribute.model)!;\n    }\n\n    const childLevelOptions: DcuplItemsOptions<any> = {};\n\n    // Validate the sort once per groupBy: a malformed sort warns once and falls back to the\n    // unsorted order instead of throwing on `sort.attributes` (#465).\n    const validSort = this.item.checkSortProjection(options.sort) ? options.sort : undefined;\n\n    const childLevelSorting: SortingProjection<any> = this.getSortingProjectionForModel(validSort, this.model);\n    childLevelOptions.sort = childLevelSorting;\n\n    // 1) PREPARE INITIAL DATA\n    // get the filteredData only SORTED\n\n    let relevantData = this.item.getItemsAsMap(this.filteredData, this.model, childLevelOptions) as Map<\n      string,\n      ListType\n    >;\n\n    // For deep queries, project the data before creating indices\n    if (isDeepQuery) {\n      const projection = this.projectionFor([attributeEntry]);\n      const projectedData = new Map<string, ListType>();\n\n      for (const [key, item] of relevantData) {\n        const projectedItem = this.item.getProjectedData(projection, this.model, item);\n        projectedData.set(key, projectedItem as ListType);\n      }\n\n      relevantData = projectedData;\n    }\n\n    // The groupBy index and every section's aggregate index share this context. It is serialized\n    // once per call rather than once per section, and a long one is stored once (#356). It names the\n    // groupBy attribute: the section key alone mixed up sections of two groupBy attributes that\n    // share a value, so a section's aggregates could come from the other attribute's section.\n    const query = this.queryBuilder.getQuery();\n    const sectionContext = IndexContext.of({\n      groupBy: options.attribute,\n      childLevelSorting,\n      query,\n    });\n    // The query selected these items, the groupBy attribute splits them into sections and the sort\n    // orders them: a change of any of these attributes makes the groupBy index and every section's\n    // aggregate index stale, not only a change of the indexed attribute (#359).\n    const sectionAttributes = [\n      options.attribute,\n      ...childLevelSorting.attributes.map(String),\n      ...this.queryBuilder.getQueryAttributes(query),\n    ];\n    const indexMap = this.indicesController.getOrCreateIndex(\n      `${options.attribute}`,\n      relevantData,\n      sectionContext,\n      sectionAttributes,\n    );\n\n    // 2) get the distinct values for the attribute\n\n    // todo distinctoptions\n    const agg = this.getAggregate(\n      { attribute: options.attribute, types: ['distinct'], excludeUndefineds: true },\n      relevantData,\n      indexMap,\n      true,\n    );\n\n    if (agg.distinct) {\n      for (const distinctAggValue of agg.distinct) {\n        let item: ListItem = { key: distinctAggValue.value, value: distinctAggValue.value };\n\n        const values = distinctAggValue.keys!.filter((key) => relevantData.has(key));\n\n        if (remoteModel) {\n          const remoteItem = remoteModel['data'].get(distinctAggValue.value);\n          if (remoteItem) {\n            item = remoteItem;\n          }\n        }\n        const sectionItem: SectionItem = {\n          ...item,\n          key: distinctAggValue.value,\n          _items: [],\n          _aggregates: [],\n          _meta: {\n            size: values.length,\n          },\n        };\n\n        sectionItems.set(distinctAggValue.value, sectionItem);\n      }\n    }\n\n    // // 3) Page, Sort and project the section data\n    const topLevelOptions: DcuplItemsOptions<any> = {\n      count: options.count,\n      start: options.start,\n      projection: options.projection,\n    };\n    if (remoteModel) {\n      const topLevelSorting: SortingProjection<any> = this.getSortingProjectionForModel(validSort, remoteModel);\n      topLevelOptions.sort = topLevelSorting;\n    }\n\n    response._meta.currentSize = sectionItems.size;\n    response._meta.initialSize = agg.distinct!.length;\n\n    sectionItems = this.item.getItemsAsMap(sectionItems, remoteModel, topLevelOptions) as Map<string, SectionItem>;\n\n    if (Array.isArray(options?.aggregates)) {\n      // An aggregate on a dotted attribute reads the items projected along its path, where the\n      // references are resolved; the raw items hold only the reference keys (#401).\n      const deepAggregateEntries = options.aggregates\n        .map((aggOption) => deepQueryService.parse(aggOption.attribute))\n        .filter((entry) => entry.isDeepQuery);\n      let deepAggregateData: Map<string, ListType> | undefined;\n      if (deepAggregateEntries.length > 0) {\n        const projection = this.projectionFor(deepAggregateEntries);\n        deepAggregateData = new Map();\n        for (const [key, item] of this.filteredData) {\n          deepAggregateData.set(key, this.item.getProjectedData(projection, this.model, item) as ListType);\n        }\n      }\n\n      sectionItems.forEach((sectionItem) => {\n        const initialAggregate = agg.distinct!.find((d) => d.value === sectionItem.key);\n        const filteredData = this.getDataByKeys(relevantData, initialAggregate!.keys!);\n        const deepFilteredData = deepAggregateData && this.getDataByKeys(deepAggregateData, initialAggregate!.keys!);\n        sectionItem._aggregates = options.aggregates!.map((aggOption) => {\n          const sectionData =\n            deepFilteredData && deepQueryService.parse(aggOption.attribute).isDeepQuery\n              ? deepFilteredData\n              : filteredData;\n          // Build an index for the aggregate's OWN attribute over this section's\n          // items. Reusing the groupBy attribute's index (indexMap) made `distinct`\n          // aggregates return the groupBy values instead of the requested ones (#220).\n          // The section key keeps each section's index distinct in the controller cache.\n          const aggregateIndex = this.indicesController.getOrCreateIndex(\n            `${aggOption.attribute}`,\n            sectionData,\n            sectionContext.with(sectionItem.key),\n            sectionAttributes,\n          );\n          return this.getAggregate(aggOption, sectionData, aggregateIndex, true);\n        });\n      });\n    }\n\n    if (options?.items) {\n      const wildCardItem = options.items?.find((i) => i.key === '*');\n\n      if (wildCardItem) {\n        // The wildcard applies to every section: validate its sort once here so a malformed sort\n        // warns once per query, not once per section (#465).\n        const wildCardOptions = {\n          ...wildCardItem,\n          sort: this.item.sanitizeSort(wildCardItem.sort as SortingProjection<any> | undefined),\n        } as DcuplItemsOptions<any>;\n        sectionItems.forEach((sectionItem) => {\n          const initialAggregate = agg.distinct!.find((d) => d.value === sectionItem.key);\n          const filteredData = this.getDataByKeys(relevantData, initialAggregate!.keys!);\n          const items = this.item.getItems(filteredData, this.model, wildCardOptions);\n          sectionItem._items = items;\n        });\n      } else {\n        sectionItems.forEach((sectionItem) => {\n          const optionItem = options.items?.find((i) => i.key === sectionItem.key);\n          if (optionItem) {\n            const initialAggregate = agg.distinct!.find((d) => d.value === sectionItem.key);\n            const filteredData = this.getDataByKeys(relevantData, initialAggregate!.keys!);\n            const items = this.item.getItems(filteredData, this.model, optionItem as DcuplItemsOptions<any>);\n            sectionItem._items = items;\n          }\n        });\n      }\n    }\n\n    response.items = Array.from(sectionItems.values());\n    return response;\n  }\n\n  /** `sort` must already be validated (`ItemService.checkSortProjection`) or undefined. */\n  private getSortingProjectionForModel(\n    sort: SortingProjection<any> | undefined,\n    model: DcuplModel<ListItem>,\n  ): SortingProjection<any> {\n    const topLevelSorting: SortingProjection<any> = {\n      attributes: [],\n      order: [],\n    };\n\n    sort?.attributes.forEach((attribute, idx) => {\n      if (model.properties.has(attribute as string)) {\n        topLevelSorting.attributes.push(attribute);\n        topLevelSorting.order.push(sort.order[idx]!);\n      }\n    });\n    return topLevelSorting;\n  }\n\n  public getReferenceKeyForFilterKey(filterKey: string): string {\n    const filterItem = this.filterItems.get(filterKey);\n    return filterItem?.attributeKey || filterItem?.key || filterKey;\n  }\n\n  public updateFilterItem(filterKey: string, options: DcuplFilterOptions = {}): void {\n    const defaultOptions: DcuplFilterOptions = {\n      calculateFacets: false,\n      excludeZeros: true,\n      excludeUndefineds: true,\n      excludeUnresolved: true,\n      skipProcessing: false,\n    };\n\n    const referenceKey = this.getReferenceKeyForFilterKey(filterKey);\n\n    if (!referenceKey) {\n      return;\n    }\n\n    const reference = this.model.references.get(referenceKey);\n\n    let relevantOptions: DcuplFilterOptions = {};\n    if (typeof reference?.filter === 'object') {\n      relevantOptions = Object.assign(defaultOptions, reference.filter, options);\n    } else {\n      relevantOptions = Object.assign(defaultOptions, options);\n    }\n\n    if (reference) {\n      this.updateFilterItemReference(reference.key, reference.key, relevantOptions);\n      return;\n    }\n\n    const property = this.model.properties.get(referenceKey);\n\n    if (property) {\n      if (Array.isArray(property.filter)) {\n        property.filter.forEach((filter) => {\n          const comparisonType = (filter as FilterStringArray)?.comparisonType || 'containsIgnoreCase';\n          this.updateFilterItemProperty(filter.key, property.key, property.type, comparisonType, relevantOptions);\n        });\n        return;\n      } else {\n        const comparisonType = (property.filter as FilterStringSingle)?.comparisonType || 'containsIgnoreCase';\n        this.updateFilterItemProperty(property.key, property.key, property.type, comparisonType, relevantOptions);\n        return;\n      }\n    }\n\n    if (filterKey === 'key') {\n      const comparisonType = 'containsIgnoreCase';\n      this.updateFilterItemProperty('key', 'key', 'string', comparisonType, relevantOptions);\n      return;\n    }\n  }\n\n  private updateFilterItemReference(filterKey: string, attributeKey: string, options: DcuplFilterOptions): void {\n    let entries: FilterItemEntry[] = [];\n    const reference = this.model.references.get(attributeKey);\n    if (reference && !options.skipProcessing) {\n      const remoteModel = this.modelParser.models.get(reference.model);\n      entries = this.getFacets(reference.key, remoteModel, this.withoutSkipKeys(options));\n    }\n    const filterItem = {\n      key: filterKey,\n      attributeKey: attributeKey,\n      enabled: !!entries.find((entry) => entry.enabled),\n      selected: !!entries.find((entry) => entry.selected),\n      type: 'reference',\n      entries: entries,\n    } as ReferenceFilterItem;\n\n    this.filterItems.set(filterItem.key, filterItem);\n  }\n\n  private updateFilterItemProperty(\n    filterKey: string,\n    attributeKey: string,\n    type: PropertyType,\n    comparisonType: FilterComparisonType,\n    options: DcuplFilterOptions,\n  ): void {\n    const filterType = this.getFilterTypeForPropertyType(type);\n\n    // Depth-aware: also finds a group keyed by the filter inside a keyless wrapper group, a\n    // top-level match first (#303); range items' relatedQuery uses the same lookup.\n    const hasFilterEntry = this.queryBuilder.hasQueryGroup(filterKey);\n\n    const filterItem = {\n      key: filterKey,\n      attributeKey: attributeKey,\n      enabled: true,\n      selected: !!hasFilterEntry,\n      type: filterType,\n    } as PropertyFilterItem;\n\n    if (filterItem.type === 'text') {\n      (filterItem as TextFilterItem).comparisonType = comparisonType;\n    }\n\n    if (filterItem.type === 'boolean') {\n      const entries = this.getFacets(filterItem.attributeKey, undefined, this.withoutSkipKeys(options));\n      filterItem.entries = entries;\n    }\n\n    if (!options.skipProcessing) {\n      if (filterItem.type === 'number') {\n        filterItem.range = this.getNumberRangesForFilterItem(filterItem);\n      }\n      if (filterItem.type === 'date') {\n        filterItem.range = this.getDateRangesForFilterItem(filterItem);\n      }\n    }\n    this.filterItems.set(filterItem.key, filterItem);\n  }\n\n  public getNumberRange(propertyKey: string, filterKey = propertyKey): FilterItemNumberRangeValue {\n    // #124 Performance optimization: Single-pass algorithm for min/max calculation\n    // Instead of 11 passes (Array.from, map, filter, flat, min, max × 2), do 2 single passes\n    let filteredMin = Infinity;\n    let filteredMax = -Infinity;\n\n    for (const item of this.filteredData.values()) {\n      const value = item[propertyKey];\n      if (typeof value === 'undefined' || value === null) continue;\n\n      // Handle both single values and arrays\n      if (Array.isArray(value)) {\n        for (const v of value) {\n          if (typeof v === 'number') {\n            if (v < filteredMin) filteredMin = v;\n            if (v > filteredMax) filteredMax = v;\n          }\n        }\n      } else if (typeof value === 'number') {\n        if (value < filteredMin) filteredMin = value;\n        if (value > filteredMax) filteredMax = value;\n      }\n    }\n\n    let initialMin = Infinity;\n    let initialMax = -Infinity;\n\n    for (const item of this.initialData.values()) {\n      const value = item[propertyKey];\n      if (typeof value === 'undefined' || value === null) continue;\n\n      // Handle both single values and arrays\n      if (Array.isArray(value)) {\n        for (const v of value) {\n          if (typeof v === 'number') {\n            if (v < initialMin) initialMin = v;\n            if (v > initialMax) initialMax = v;\n          }\n        }\n      } else if (typeof value === 'number') {\n        if (value < initialMin) initialMin = value;\n        if (value > initialMax) initialMax = value;\n      }\n    }\n\n    // Handle case where no valid values were found\n    if (filteredMin === Infinity) filteredMin = 0;\n    if (filteredMax === -Infinity) filteredMax = 0;\n    if (initialMin === Infinity) initialMin = 0;\n    if (initialMax === -Infinity) initialMax = 0;\n\n    const ranges: FilterItemNumberRangeValue = {\n      available: {\n        min: filteredMin,\n        max: filteredMax,\n      },\n      initial: {\n        min: initialMin,\n        max: initialMax,\n      },\n      relatedQuery: this.queryBuilder.getQueryGroup(filterKey),\n    };\n\n    return ranges;\n  }\n\n  private getNumberRangesForFilterItem(filterItem: FilterItem): FilterItemNumberRangeValue {\n    const ranges = this.getNumberRange(filterItem.attributeKey, filterItem.key);\n    return ranges;\n  }\n\n  private getDateRangesForFilterItem(filterItem: FilterItem): FilterItemDateRangeValue {\n    const ranges: FilterItemDateRangeValue = this.getDateRange(filterItem.attributeKey, filterItem.key);\n    return ranges;\n  }\n\n  public getDateRange(propertyKey: string, filterKey = propertyKey): FilterItemDateRangeValue {\n    // #124 Performance optimization: Single-pass algorithm for date min/max calculation\n    // Instead of 11 passes (Array.from, map, filter, flat, min, max × 2), do 2 single passes\n    let filteredMin: Date | null = null;\n    let filteredMax: Date | null = null;\n\n    for (const item of this.filteredData.values()) {\n      const value = item[propertyKey];\n      if (typeof value === 'undefined' || value === null) continue;\n\n      // Handle both single values and arrays\n      const dates = Array.isArray(value) ? value : [value];\n      for (const d of dates) {\n        if (d instanceof Date) {\n          if (!filteredMin || d < filteredMin) filteredMin = d;\n          if (!filteredMax || d > filteredMax) filteredMax = d;\n        }\n      }\n    }\n\n    let initialMin: Date | null = null;\n    let initialMax: Date | null = null;\n\n    for (const item of this.initialData.values()) {\n      const value = item[propertyKey];\n      if (typeof value === 'undefined' || value === null) continue;\n\n      // Handle both single values and arrays\n      const dates = Array.isArray(value) ? value : [value];\n      for (const d of dates) {\n        if (d instanceof Date) {\n          if (!initialMin || d < initialMin) initialMin = d;\n          if (!initialMax || d > initialMax) initialMax = d;\n        }\n      }\n    }\n\n    // Use current date as fallback if no valid dates found\n    const now = new Date();\n    if (!filteredMin) filteredMin = now;\n    if (!filteredMax) filteredMax = now;\n    if (!initialMin) initialMin = now;\n    if (!initialMax) initialMax = now;\n\n    const ranges: FilterItemDateRangeValue = {\n      available: {\n        min: filteredMin,\n        max: filteredMax,\n      },\n      initial: {\n        min: initialMin,\n        max: initialMax,\n      },\n      relatedQuery: this.queryBuilder.getQueryGroup(filterKey),\n    };\n\n    return ranges;\n  }\n\n  /**\n   * `skipKeys` is an `fn.facets` option only: the entries of a filter item always list their\n   * `resultKeys`, also when an untyped caller passes it to `filters.get`.\n   */\n  private withoutSkipKeys(options: DcuplFilterOptions): DcuplFilterOptions {\n    const { skipKeys: _skipKeys, ...filterOptions } = options as DcuplFacetCalculationOptions;\n    return filterOptions;\n  }\n\n  public getFacets(\n    attributeKey: string,\n    remoteModel: DcuplModel | undefined,\n    options: DcuplFacetCalculationOptions,\n  ): FilterItemEntry[] {\n    let indexMap: InverseIndexValuesMap;\n\n    const cacheContext = this.cacheCtrl.generateContext({ attributeKey, query: this.queryBuilder.getQuery(), options });\n\n    const cachedValue = this.cacheCtrl.get('facets', cacheContext);\n\n    if (cachedValue) {\n      return cachedValue;\n    }\n\n    let remoteData: Map<string, ListItem> = new Map();\n\n    indexMap = this.indicesController.getIndex(attributeKey)!;\n\n    if (remoteModel) {\n      remoteData = remoteModel.getData();\n    } else {\n      remoteData = this.indicesController.getData(attributeKey)!;\n    }\n\n    const attributeEntry = deepQueryService.parse(attributeKey);\n    const isDeepQuery = attributeEntry.isDeepQuery;\n    // A dotted facet counts over the data in the shape the list's query is evaluated on\n    // (see getQueryProjectedInitialData); the facet path itself is never projected (#448).\n    const relevantData = isDeepQuery ? this.getQueryProjectedInitialData() : this.initialData;\n\n    // Autogenerate index if not present\n    if (!indexMap || !remoteData) {\n      this.indicesController.reset(attributeKey);\n\n      // The path's projection records the models it reads through (#284); it only projects an item\n      // for a bracket path, which getDeepPathValuesOf leaves to the projection walk.\n      const pathProjection = isDeepQuery ? (this.projectionFor([attributeEntry]) as Projection<ListType>) : undefined;\n      const pathSegments = attributeKey.includes('[') ? undefined : attributeKey.split('.');\n\n      this.initialData.forEach((entry) => {\n        let attributeValues: any[];\n        if (isDeepQuery) {\n          // read from the stored rows, so reference segments resolve without a projected copy\n          attributeValues = this.getDeepAttributeValues(entry, attributeKey, pathSegments, pathProjection!);\n          // Preserve undefined facet behavior when path yields no matches\n          if (attributeValues.length === 0) {\n            attributeValues = [undefined];\n          }\n        } else {\n          attributeValues = [entry[attributeKey]];\n        }\n        this.indicesController.fillInverseIndex(attributeKey, entry.key, attributeValues);\n        this.indicesController.fillDataMap(attributeKey, attributeValues);\n      });\n\n      indexMap = this.indicesController.getIndex(attributeKey)!;\n      // A remote model's data is independent of this model's index — re-reading it from the\n      // just-filled data map would clobber it (empty model ⇒ empty data map ⇒ remote facet\n      // keys vanish). Only non-reference attributes source their facet keys from the data map.\n      if (!remoteModel) {\n        remoteData = this.indicesController.getData(attributeKey)!;\n      }\n    }\n\n    const relevantModelData = relevantData;\n\n    const facets = getFacets(\n      relevantModelData,\n      remoteData,\n      options,\n      this.queryBuilder.getQuery(),\n      attributeKey,\n      this.indicesController['indexMap'],\n      this.queryManager,\n    );\n\n    // Store facets with explicit dependencies for granular invalidation. A\n    // dotted attribute also depends on every model on its path (#284).\n    this.cacheCtrl.set('facets', cacheContext, facets, {\n      models: new Set([this.model.key, ...this.pathModels(attributeKey)]),\n      modelAttributes: new Map([[this.model.key, new Set([attributeKey])]]),\n    });\n\n    return facets;\n  }\n\n  public getDataByKeys(data: Map<string, ListType>, itemKeys: string[]): Map<string, ListType> {\n    if (itemKeys) {\n      const filteredData = new Map();\n      itemKeys.forEach((key) => {\n        const entry = data.get(key);\n        if (entry) {\n          filteredData.set(entry.key, entry);\n        }\n      });\n      return filteredData;\n    }\n    return data;\n  }\n\n  private getFilterTypeForPropertyType(type: PropertyType): FilterItemType {\n    switch (type) {\n      case 'string':\n        return 'text';\n      case 'int':\n        return 'number';\n      case 'float':\n        return 'number';\n      case 'date':\n        return 'date';\n      case 'boolean':\n        return 'boolean';\n      case 'json':\n        return 'text';\n      case 'any':\n        return 'text';\n      case 'Array<string>':\n        return 'text';\n      case 'Array<int>':\n        return 'number';\n      case 'Array<float>':\n        return 'number';\n      case 'Array<date>':\n        return 'date';\n    }\n  }\n\n  public updateFilteredData(options?: CatalogApiOptions): void {\n    const start = perf.now();\n    if (!options?.skipProcessing) {\n      this.filteredData = this.getFilteredData(this.initialData, false);\n      this.emitResultUpdated(start);\n    }\n  }\n\n  /**\n   * Announces that this list's result can have changed. Emitted when a query\n   * change recomputes the result (updateFilteredData) and, via\n   * DcuplList.emitResultUpdated, once per affected list after\n   * dcupl.update() (#278). Read-only calls never emit it.\n   */\n  public emitResultUpdated(start: number = perf.now()): void {\n    this.cdRef.trigger({\n      scope: 'list',\n      type: 'result_updated',\n      action: 'update',\n      connectMessage: true,\n      listKey: this.cdRef.key,\n      modelKey: this.model.key,\n      start,\n    });\n  }\n\n  public getFilteredData(initialData: Map<string, ListType>, earlyReturn: boolean): Map<string, ListType> {\n    const cacheContext = this.cacheCtrl.generateContext({ query: this.queryBuilder.getQuery(), earlyReturn });\n\n    const cachedValue = this.cacheCtrl.get('data', cacheContext);\n\n    if (cachedValue) {\n      return cachedValue;\n    }\n\n    const query = this.queryBuilder.getQuery();\n\n    // Check if query has deep query attributes\n    const projection = this.getProjectionForQuery(query);\n\n    let value: Map<string, ListType>;\n\n    if (projection) {\n      // Generate cache key for projection\n      const cacheKey = this.getProjectionCacheKey(query);\n\n      // Project data to resolve deep query references (with caching)\n      const projectedData = this.getProjectedData(initialData, projection, cacheKey);\n\n      // Filter using projected data\n      const filteredProjected = this.queryManager.queryData(\n        projectedData,\n        query,\n        earlyReturn,\n        this.indicesController['indexMap'],\n      );\n\n      // Map filtered keys back to original data\n      value = new Map<string, ListType>();\n      for (const key of filteredProjected.keys()) {\n        if (initialData.has(key)) {\n          value.set(key, initialData.get(key)!);\n        }\n      }\n    } else {\n      // No deep queries, filter normally\n      value = this.queryManager.queryData(initialData, query, earlyReturn, this.indicesController['indexMap']);\n    }\n\n    // Store filtered data with dependencies. This cache depends on the entire\n    // model as we're caching query results — and on every model the query's\n    // dotted paths read through (#284).\n    const pathModels = projection ? this.item.getProjectionModels(projection, this.model) : new Set<string>();\n    this.cacheCtrl.set('data', cacheContext, value, {\n      models: new Set([this.model.key, ...pathModels]),\n      modelAttributes: new Map(), // Query may reference many attributes, track at model level\n    });\n\n    return value;\n  }\n\n  public getFilterItems(options?: DcuplFiltersOptions): FilterItem[] {\n    if (Array.isArray(options?.filterKeys)) {\n      const items: FilterItem[] = [];\n      options?.filterKeys.forEach((filterKey) => {\n        const item = this.getFilterItem(filterKey, options);\n        if (item) {\n          items.push(item);\n        }\n      });\n      return items;\n    } else {\n      if (!options?.skipProcessing) {\n        this.initFilterItems(options);\n      }\n      return Array.from(this.filterItems.values());\n    }\n  }\n\n  public getFilterItem(filterItemId: string, options?: DcuplFilterOptions): FilterItem | undefined {\n    if (this.filterItems.has(filterItemId)) {\n      if (!options?.skipProcessing) {\n        this.updateFilterItem(filterItemId, options);\n      }\n    }\n\n    return this.filterItems.get(filterItemId);\n  }\n}\n","import baseIndexOf from './_baseIndexOf.js';\n\n/**\n * A specialized version of `_.includes` for arrays without support for\n * specifying an index to search from.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\nfunction arrayIncludes(array, value) {\n  var length = array == null ? 0 : array.length;\n  return !!length && baseIndexOf(array, value, 0) > -1;\n}\n\nexport default arrayIncludes;\n","import Symbol from './_Symbol.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\n\n/** Built-in value references. */\nvar spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined;\n\n/**\n * Checks if `value` is a flattenable `arguments` object or array.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.\n */\nfunction isFlattenable(value) {\n  return isArray(value) || isArguments(value) ||\n    !!(spreadableSymbol && value && value[spreadableSymbol]);\n}\n\nexport default isFlattenable;\n","import arrayPush from './_arrayPush.js';\nimport isFlattenable from './_isFlattenable.js';\n\n/**\n * The base implementation of `_.flatten` with support for restricting flattening.\n *\n * @private\n * @param {Array} array The array to flatten.\n * @param {number} depth The maximum recursion depth.\n * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.\n * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.\n * @param {Array} [result=[]] The initial result value.\n * @returns {Array} Returns the new flattened array.\n */\nfunction baseFlatten(array, depth, predicate, isStrict, result) {\n  var index = -1,\n      length = array.length;\n\n  predicate || (predicate = isFlattenable);\n  result || (result = []);\n\n  while (++index < length) {\n    var value = array[index];\n    if (depth > 0 && predicate(value)) {\n      if (depth > 1) {\n        // Recursively flatten arrays (susceptible to call stack limits).\n        baseFlatten(value, depth - 1, predicate, isStrict, result);\n      } else {\n        arrayPush(result, value);\n      }\n    } else if (!isStrict) {\n      result[result.length] = value;\n    }\n  }\n  return result;\n}\n\nexport default baseFlatten;\n","import SetCache from './_SetCache.js';\nimport arrayIncludes from './_arrayIncludes.js';\nimport arrayIncludesWith from './_arrayIncludesWith.js';\nimport arrayMap from './_arrayMap.js';\nimport baseUnary from './_baseUnary.js';\nimport cacheHas from './_cacheHas.js';\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * The base implementation of methods like `_.difference` without support\n * for excluding multiple arrays or iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Array} values The values to exclude.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n */\nfunction baseDifference(array, values, iteratee, comparator) {\n  var index = -1,\n      includes = arrayIncludes,\n      isCommon = true,\n      length = array.length,\n      result = [],\n      valuesLength = values.length;\n\n  if (!length) {\n    return result;\n  }\n  if (iteratee) {\n    values = arrayMap(values, baseUnary(iteratee));\n  }\n  if (comparator) {\n    includes = arrayIncludesWith;\n    isCommon = false;\n  }\n  else if (values.length >= LARGE_ARRAY_SIZE) {\n    includes = cacheHas;\n    isCommon = false;\n    values = new SetCache(values);\n  }\n  outer:\n  while (++index < length) {\n    var value = array[index],\n        computed = iteratee == null ? value : iteratee(value);\n\n    value = (comparator || value !== 0) ? value : 0;\n    if (isCommon && computed === computed) {\n      var valuesIndex = valuesLength;\n      while (valuesIndex--) {\n        if (values[valuesIndex] === computed) {\n          continue outer;\n        }\n      }\n      result.push(value);\n    }\n    else if (!includes(values, computed, comparator)) {\n      result.push(value);\n    }\n  }\n  return result;\n}\n\nexport default baseDifference;\n","import baseDifference from './_baseDifference.js';\nimport baseFlatten from './_baseFlatten.js';\nimport baseRest from './_baseRest.js';\nimport isArrayLikeObject from './isArrayLikeObject.js';\n\n/**\n * Creates an array of `array` values not included in the other given arrays\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons. The order and references of result values are\n * determined by the first array.\n *\n * **Note:** Unlike `_.pullAll`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...Array} [values] The values to exclude.\n * @returns {Array} Returns the new array of filtered values.\n * @see _.without, _.xor\n * @example\n *\n * _.difference([2, 1], [2, 3]);\n * // => [1]\n */\nvar difference = baseRest(function(array, values) {\n  return isArrayLikeObject(array)\n    ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true))\n    : [];\n});\n\nexport default difference;\n","import {\n  ListItem,\n  DcuplItemsOptions,\n  Projection,\n  SortingProjection,\n  SortDirection,\n  ScriptController,\n  logger,\n} from '@dcupl/common';\nimport { difference, orderBy } from 'lodash-es';\n\nimport { DcuplModel, ModelParser } from '../../model-parser';\n\n/** The shape a `sort` option must have; named in the warning for a malformed sort (#465). */\nconst EXPECTED_SORT_SHAPE = \"{ attributes: string[], order: ('ASC' | 'DESC')[] }\";\n\nexport class ItemService<ListType extends ListItem = ListItem> {\n  private log = logger.child({ prefix: 'ItemService' });\n\n  constructor(\n    public modelParser: ModelParser,\n    private scriptController: ScriptController,\n  ) {}\n\n  public getItem(\n    itemId: string,\n    dataAsMap: Map<string, ListType>,\n    model: DcuplModel<ListType>,\n    options?: DcuplItemsOptions<ListType>,\n  ): ListType | null {\n    const projection: Projection<ListType> = options?.projection || { $: true };\n    const dataEntry = dataAsMap.get(itemId);\n\n    if (!dataEntry) {\n      return null;\n    }\n\n    const objToReturn = this.getProjectedData(projection, model, dataEntry);\n\n    return objToReturn;\n  }\n\n  public getManyItems(\n    itemKeys: string[],\n    dataAsMap: Map<string, ListType>,\n    model: DcuplModel<ListType>,\n    options?: DcuplItemsOptions<ListType>,\n  ): ListType[] {\n    const items: ListType[] = [];\n\n    for (const key of itemKeys) {\n      const projection: Projection<ListType> = options?.projection || { $: true };\n      const dataEntry = dataAsMap.get(key);\n\n      if (!dataEntry) {\n        continue;\n      }\n\n      const objToReturn = this.getProjectedData(projection, model, dataEntry);\n\n      items.push(objToReturn);\n    }\n    return items;\n  }\n\n  public getItems(\n    dataAsMap: Map<string, ListType>,\n    model: DcuplModel<ListType>,\n    options?: DcuplItemsOptions<ListType>,\n  ): ListType[] {\n    const result = this.getItemsAsMap(dataAsMap, model, options);\n\n    return Array.from(result.values());\n  }\n\n  public getItemsAsMap(\n    dataAsMap: Map<string, ListType>,\n    model?: DcuplModel<ListType>,\n    options?: DcuplItemsOptions<ListType>,\n  ): Map<string, ListType> {\n    const start = options?.start || 0;\n    // Use ?? so an explicit count of 0 is honored (return no items) rather than\n    // being coerced to \"no limit\". undefined still means \"all items\".\n    const count = options?.count ?? dataAsMap.size;\n    const projection: Projection<ListType> = options?.projection || { $: true };\n\n    if (this.checkSortProjection(options?.sort)) {\n      dataAsMap = this.getSortedItems(dataAsMap, options, model);\n    }\n\n    if (this.checkSortScript(options?.sort)) {\n      dataAsMap = this.getSortedItemsBasedOnScript(dataAsMap, options);\n    }\n\n    const result = this.getPagedData(dataAsMap, start, count, projection, model);\n\n    return result;\n  }\n\n  protected getSortedItemsBasedOnScript(\n    data: Map<string, ListType>,\n    options?: DcuplItemsOptions<ListType>,\n  ): Map<string, ListType> {\n    const dataAsArray = Array.from(data.values());\n    const scriptName = options?.sort?.script?.key || '';\n    const sortOptions = options?.sort?.script?.options || undefined;\n    if (!this.scriptController.hasScript(scriptName)) {\n      return data;\n    }\n\n    const sortedArray: ListType[] = this.scriptController.executeScript(scriptName, 'sort', {\n      options: sortOptions,\n      items: dataAsArray,\n    });\n\n    return new Map(\n      sortedArray.map((object) => {\n        return [object.key, object];\n      }),\n    );\n  }\n  protected getSortedItems(\n    data: Map<string, ListType>,\n    options?: DcuplItemsOptions<ListType>,\n    model?: DcuplModel<ListType>,\n  ): Map<string, ListType> {\n    const attributes = [...options!.sort!.attributes];\n\n    const dataAsArray = Array.from(data.values());\n\n    const dataTransformer = (listItem: ListType, attr: string, undefinedValue: any): any => {\n      const value = listItem[attr];\n      if (typeof value === 'undefined' || value === null) {\n        return undefinedValue;\n      }\n      if (typeof value === 'string') {\n        return value.toLowerCase();\n      }\n\n      if (typeof value === 'object') {\n        if (typeof value?.key === 'string') {\n          return value.key.toLowerCase();\n        }\n      }\n\n      return value;\n    };\n\n    const transformerFn = attributes.map((attribute: any, index: number) => (entry: any): any => {\n      const relevantOrder = options!.sort!.order.at(index) as SortDirection;\n\n      const undefinedValue = this.getUndefinedValueForSorting(attribute, relevantOrder, model);\n      return dataTransformer(entry, attribute, undefinedValue);\n    });\n    const order = [...options!.sort!.order].map((o) => o.toLowerCase()) as Array<'asc' | 'desc'>;\n    const sortedArray: ListType[] = orderBy(dataAsArray, [...transformerFn], order);\n\n    return new Map(\n      sortedArray.map((object) => {\n        return [object.key, object];\n      }),\n    );\n  }\n\n  private getUndefinedValueForSorting(attribute: string, direction: SortDirection, model?: DcuplModel<ListType>): any {\n    const property = model?.properties.get(attribute);\n\n    if (property) {\n      if (property.type === 'string') {\n        if (direction == 'ASC') {\n          return undefined;\n        }\n        if (direction == 'DESC') {\n          return '';\n        }\n      }\n      if (\n        property.type === 'int' ||\n        property.type === 'float' ||\n        property.type === 'date' ||\n        property.type === 'boolean'\n      ) {\n        if (direction == 'ASC') {\n          return Infinity;\n        }\n        if (direction == 'DESC') {\n          return -Infinity;\n        }\n      }\n    }\n  }\n\n  public isValidProjection(projection?: Projection<ListType>): boolean {\n    if (!projection) {\n      return false;\n    }\n\n    if (projection.$ === true && Object.keys(projection).length === 1) {\n      return false;\n    }\n    return true;\n  }\n\n  public getPagedData(\n    data: Map<string, any>,\n    start: number,\n    count: number,\n    projection?: Projection<ListType>,\n    model?: DcuplModel<ListType>,\n  ): Map<string, any> {\n    const it = data.entries();\n    const pagedData = new Map();\n\n    // fast return - if we want to return the full default-projected dataset\n    if (start === 0 && count === data.size && projection?.$ === true && Object.keys(projection).length === 1) {\n      return data;\n    }\n\n    for (let i = 0; i < start + count; i++) {\n      if (i < start) {\n        it.next();\n        continue;\n      }\n      if (i > start + count) {\n        break;\n      }\n\n      const item = it.next().value;\n      if (item) {\n        if (model && projection && this.isValidProjection(projection)) {\n          const objToReturn = this.getProjectedData(projection, model, item[1] as ListType);\n          pagedData.set(item[0], objToReturn);\n        } else {\n          pagedData.set(item[0], item[1]);\n        }\n      }\n    }\n\n    return pagedData;\n  }\n\n  /**\n   * Whether `sort.script` names a registered script. Runs once per call, never per item. An\n   * unregistered key logs one warning naming the key and is ignored, so the result keeps its\n   * order (#473), the same contract as a malformed attribute sort (#465): no throw. A sort\n   * without a `script` does not warn.\n   */\n  public checkSortScript(sort: SortingProjection<any> | undefined): boolean {\n    if (!sort || typeof sort !== 'object' || !sort.script) {\n      return false;\n    }\n    const key = sort.script.key;\n    if (typeof key === 'string' && this.scriptController.hasScript(key)) {\n      return true;\n    }\n    this.log.warn(`Ignoring the sort script \"${String(key)}\": no script is registered under that key`, {\n      sort: this.describeSort(sort),\n    });\n    return false;\n  }\n\n  private hasRegisteredScript(sort: SortingProjection<any>): boolean {\n    const key = sort.script?.key;\n    return typeof key === 'string' && this.scriptController.hasScript(key);\n  }\n\n  /**\n   * Whether `sort` can be applied as an attribute sort. Runs once per call, never per item.\n   * A present but malformed sort (wrong shape, lowercase order, attributes and order of\n   * different length) logs one warning naming the expected shape and is ignored, so the\n   * result keeps its unsorted order (#465). When the sort also carries a `script`, the\n   * warning says only the attribute sort is ignored: the script sort still runs.\n   * A missing sort, an empty one (`{}` or `{ attributes: [], order: [] }`) and a\n   * script-only sort (`{ script }`) do not warn.\n   */\n  public checkSortProjection(sort: SortingProjection<any> | undefined): boolean {\n    if (this.isValidSortProjection(sort)) {\n      return true;\n    }\n    if (sort === undefined || sort === null || this.isEmptyOrScriptOnlySort(sort)) {\n      return false;\n    }\n    // Only a registered script \"still runs\"; an unregistered key gets its own warning (#473).\n    const hasScript = typeof sort === 'object' && this.hasRegisteredScript(sort);\n    const message = hasScript\n      ? `Ignoring the invalid attribute sort, the script sort still runs; expected ${EXPECTED_SORT_SHAPE} with one order per attribute`\n      : `Ignoring an invalid sort; expected ${EXPECTED_SORT_SHAPE} with one order per attribute`;\n    this.log.warn(message, { sort: this.describeSort(sort) });\n    return false;\n  }\n\n  /**\n   * The part of `sort` that can run, validated once: the sort itself when its attribute sort is\n   * valid and its script (if any) is registered, only the valid part when the other is malformed\n   * or unregistered (one warning each), else undefined. For callers that apply the same sort many\n   * times (groupBy sections), so a malformed sort warns once per query instead of once per call\n   * (#465, #473).\n   */\n  public sanitizeSort(sort: SortingProjection<any> | undefined): SortingProjection<any> | undefined {\n    const attributeSortValid = this.checkSortProjection(sort);\n    const scriptValid = this.checkSortScript(sort);\n    if (attributeSortValid && scriptValid) {\n      return sort;\n    }\n    if (attributeSortValid) {\n      return { attributes: sort!.attributes, order: sort!.order };\n    }\n    if (scriptValid) {\n      return { attributes: [], order: [], script: sort!.script };\n    }\n    return undefined;\n  }\n\n  private isEmptyOrScriptOnlySort(sort: SortingProjection<any>): boolean {\n    if (typeof sort !== 'object') {\n      return false;\n    }\n    const setKeys = Object.keys(sort).filter((key) => (sort as Record<string, unknown>)[key] !== undefined);\n    if (setKeys.length === 0) {\n      return true;\n    }\n    const { attributes, order } = sort as Partial<SortingProjection<any>>;\n    if (attributes === undefined && order === undefined) {\n      return setKeys.length === 1 && !!sort.script;\n    }\n    return (\n      Array.isArray(attributes) &&\n      attributes.length === 0 &&\n      (order === undefined || (Array.isArray(order) && order.length === 0))\n    );\n  }\n\n  private describeSort(sort: unknown): string {\n    try {\n      return JSON.stringify(sort) ?? String(sort);\n    } catch {\n      return String(sort);\n    }\n  }\n\n  protected isValidSortProjection(sort: SortingProjection<any> | undefined): boolean {\n    const validOrderValues: SortDirection[] = ['ASC', 'DESC'];\n\n    if (\n      !sort ||\n      !Array.isArray(sort.attributes) ||\n      sort.attributes.length === 0 ||\n      !Array.isArray(sort.order) ||\n      sort.attributes.length !== sort.order.length\n    ) {\n      return false;\n    }\n\n    if (difference(sort.order, validOrderValues).length > 0) {\n      return false;\n    }\n\n    return true;\n  }\n\n  public getProjectedData(\n    projection: Projection<ListType>,\n    model: DcuplModel<ListType>,\n    dataEntry: ListType,\n  ): ListType {\n    let objToReturn = { key: dataEntry.key } as ListType;\n\n    if (projection.$ === true) {\n      objToReturn = Object.assign({}, dataEntry);\n    }\n\n    if (projection.$$ === true) {\n      objToReturn = Object.assign({}, dataEntry);\n      model.references.forEach((ref) => {\n        if (!projection[ref.key as keyof Projection<ListType>]) {\n          (projection as Record<string, any>)[ref.key] = { $: true };\n        }\n      });\n    }\n\n    const keys: Array<keyof ListType> = Object.keys(projection);\n\n    keys\n      .filter((key) => key !== '$' && key !== '$$')\n      .forEach((key) => {\n        const projectionValue = (projection as ListType)[key];\n        if (projectionValue === false) {\n          delete objToReturn[key];\n          return;\n        }\n\n        if (projectionValue === true) {\n          objToReturn[key] = dataEntry[key];\n          return;\n        }\n\n        if (typeof projectionValue === 'object') {\n          const reference = model.references.get(key as string);\n          if (reference) {\n            const remoteModel = this.modelParser.models.get(reference.model) as DcuplModel<any> | undefined;\n            if (remoteModel) {\n              if (reference.type === 'multiValued') {\n                const value: ListType[] = dataEntry[key] || [];\n\n                objToReturn[key] = value\n                  .map((entryKey: ListType) => {\n                    // Handle both string references ('c1') and object references ({ key: 'c1' })\n                    const refKey = typeof entryKey === 'string' ? entryKey : (entryKey as ListItem).key;\n                    const entry = remoteModel.getEntry(refKey);\n                    if (entry) {\n                      return this.getProjectedData(projectionValue, remoteModel, entry);\n                    }\n\n                    if (this.modelParser.initOptions.referenceMetadata?.enabled) {\n                      return { key: refKey, _dcupl_ref_: 'miss' };\n                    } else {\n                      return null;\n                    }\n                  })\n                  .filter(Boolean) as ListType[keyof ListType];\n              } else if (reference.type === 'singleValued') {\n                const value: ListType = dataEntry[key];\n                if (value) {\n                  // Handle both string references ('c1') and object references ({ key: 'c1' })\n                  const refKey = typeof value === 'string' ? value : (value as ListItem).key;\n                  const entry = remoteModel?.getEntry(refKey);\n                  if (entry) {\n                    objToReturn[key] = this.getProjectedData(\n                      projectionValue,\n                      remoteModel,\n                      entry,\n                    ) as ListType[keyof ListType];\n                  } else {\n                    if (this.modelParser.initOptions.referenceMetadata?.enabled) {\n                      objToReturn[key] = { key: refKey, _dcupl_ref_: 'miss' } as ListType[keyof ListType];\n                    } else {\n                      delete objToReturn[key];\n                    }\n                  }\n                }\n              }\n            }\n          }\n        }\n      });\n\n    return objToReturn;\n  }\n\n  /**\n   * The values the dotted path `segments` (a path without brackets, split at its dots) resolves to\n   * on `dataEntry`, read from the stored rows: each reference on the path is looked up by key in\n   * its model instead of building a projected copy of the item (#448). Answers what\n   * `getDeepPathValues(getProjectedData(projection, model, dataEntry), path)` answers for the\n   * path's projection, in the same order, with the same multi-valued unwinding, missing-reference\n   * markers (`referenceMetadata`) and dropped misses. A multi-valued reference that holds no list\n   * is answered by `projectedValues`, the projection walk (which fails on it as it always did).\n   */\n  public getDeepPathValuesOf(\n    model: DcuplModel<any>,\n    dataEntry: ListItem,\n    segments: readonly string[],\n    projectedValues: () => any[],\n  ): any[] {\n    const withMetadata = !!this.modelParser.initOptions.referenceMetadata?.enabled;\n    const last = segments.length - 1;\n    const values: any[] = [];\n    let needsProjection = false;\n\n    // Depth first; getDeepPathValues walks level by level, which visits the leaves in the same order.\n    const visit = (node: any, nodeModel: DcuplModel<any> | undefined, i: number): void => {\n      if (i > last) {\n        // like getDeepPathValues: a list at the leaf (a multi-valued key list) unwinds one level\n        if (Array.isArray(node)) {\n          for (const element of node) if (element !== undefined) values.push(element);\n        } else {\n          values.push(node);\n        }\n        return;\n      }\n      if (node === undefined || node === null) return;\n      if (Array.isArray(node)) {\n        for (const element of node) {\n          if (element !== undefined && element !== null) step(element, nodeModel, i);\n        }\n      } else {\n        step(node, nodeModel, i);\n      }\n    };\n\n    const step = (element: any, elementModel: DcuplModel<any> | undefined, i: number): void => {\n      const segment = segments[i]!;\n      const value = element[segment];\n      // the projection resolves a reference only where the path continues past it\n      const reference = i < last ? elementModel?.references.get(segment) : undefined;\n      const remoteModel = reference\n        ? (this.modelParser.models.get(reference.model) as DcuplModel<any> | undefined)\n        : undefined;\n      if (!reference || !remoteModel) {\n        if (value !== undefined) visit(value, undefined, i + 1);\n        return;\n      }\n      if (reference.type === 'multiValued') {\n        const keys = value || [];\n        if (!Array.isArray(keys)) {\n          needsProjection = true;\n          return;\n        }\n        // the projected list holds the found rows and, with referenceMetadata, a marker per miss\n        for (const entryKey of keys) {\n          const refKey = typeof entryKey === 'string' ? entryKey : (entryKey as ListItem).key;\n          const entry = remoteModel.getEntry(refKey);\n          if (entry) step(entry, remoteModel, i + 1);\n          else if (withMetadata) step({ key: refKey, _dcupl_ref_: 'miss' }, remoteModel, i + 1);\n          if (needsProjection) return;\n        }\n      } else if (reference.type === 'singleValued') {\n        if (!value) {\n          // a falsy reference value is kept as stored\n          if (value !== undefined) visit(value, undefined, i + 1);\n          return;\n        }\n        const refKey = typeof value === 'string' ? value : (value as ListItem).key;\n        const entry = remoteModel.getEntry(refKey);\n        if (entry) visit(entry, remoteModel, i + 1);\n        else if (withMetadata) visit({ key: refKey, _dcupl_ref_: 'miss' }, undefined, i + 1);\n      } else if (value !== undefined) {\n        visit(value, undefined, i + 1);\n      }\n    };\n\n    visit(dataEntry, model, 0);\n    return needsProjection ? projectedValues() : values;\n  }\n\n  /**\n   * The models a projection reads through: for every nested projection key\n   * that is a reference of `model`, the referenced model, recursively (the\n   * same walk {@link getProjectedData} takes). A list that projects\n   * `{ memberships: { user: { daysInactive: true } } }` on `project` reads\n   * `membership` and `user`, so a change on either can change its result\n   * (#284). Keys that are no reference (properties, `$`/`$$`, array indices)\n   * contribute nothing; the root model itself is not included.\n   */\n  public getProjectionModels(\n    projection: Projection<any>,\n    model: DcuplModel<any>,\n    collected: Set<string> = new Set(),\n  ): Set<string> {\n    if (!projection || typeof projection !== 'object') {\n      return collected;\n    }\n\n    for (const [key, projectionValue] of Object.entries(projection)) {\n      if (key === '$' || key === '$$' || typeof projectionValue !== 'object' || projectionValue === null) {\n        continue;\n      }\n      const reference = model.references.get(key);\n      if (!reference) {\n        continue;\n      }\n      collected.add(reference.model);\n      const remoteModel = this.modelParser.models.get(reference.model) as DcuplModel<any> | undefined;\n      if (remoteModel) {\n        // a projection object is finite, so the walk terminates without a cycle guard\n        this.getProjectionModels(projectionValue as Projection<any>, remoteModel, collected);\n      }\n    }\n\n    return collected;\n  }\n}\n","import {\n  DcuplFiltersOptions,\n  DcuplItemOptions,\n  DcuplItemsOptions,\n  DcuplGroupByOptions,\n  FilterItem,\n  ListItem,\n  ListMetadata,\n  GroupByResponse,\n  trigger,\n  ViewDefinition,\n  ModelAttribute,\n  DcuplFacetOptions,\n  DcuplGlobalQueryOptions,\n  DcuplQueryGroup,\n  DcuplQuery,\n  DcuplFilterOptions,\n  ChangeDetector,\n  DcuplListQueryOptions,\n  AggregationOptions,\n  deepQueryService,\n  parseRegexLiteral,\n  Aggregation,\n  DcuplManyItemsOptions,\n  SuggestionOptions,\n  Suggestion,\n  computeSuggestions,\n  PivotOptions,\n  PivotResponse,\n  pivot,\n  IndicesController,\n  DcuplFacet,\n  DcuplQueryBuilder,\n  logger,\n} from '@dcupl/common';\n\nimport { DcuplModel } from '../model-parser';\nimport { Filter } from './filter/filter';\nimport { ItemService } from './item/item';\nimport { DcuplApi } from '../dcupl/dcupl-api';\n\nexport class CatalogApi<ListType extends ListItem = ListItem> {\n  protected metadata!: ListMetadata;\n  protected model!: DcuplModel<ListType>;\n  protected filter!: Filter<ListType>;\n  private itemService!: ItemService<ListType>;\n  private log = logger.child({ prefix: 'Catalog' });\n\n  constructor(\n    protected dcuplApi: DcuplApi,\n    protected cdRef: ChangeDetector,\n    protected indicesController: IndicesController,\n  ) {\n    this.itemService = new ItemService<ListType & ListItem>(\n      this.dcuplApi['modelParser'],\n      this.dcuplApi['scriptController'],\n    );\n    this.filter = new Filter<ListType>(\n      this.dcuplApi['modelParser'],\n      this.cdRef,\n      this.itemService,\n      this.indicesController,\n      this.dcuplApi['queryManager'],\n    );\n  }\n\n  protected initListeners(): void {\n    this.initListMetadata();\n  }\n\n  private initListMetadata(): void {\n    this.metadata = {\n      key: this.model.key,\n      currentSize: this.filter.filteredData.size,\n      initialSize: this.filter.initialData.size,\n      attributes: this.getModelAttributes(),\n      views: this.getViews(),\n      appliedQuery: this.filter.queryBuilder.getQuery(),\n    };\n  }\n\n  private getModelAttributes(): ModelAttribute[] {\n    const attributes: ModelAttribute[] = [...this.model.references.values(), ...this.model.properties.values()];\n    return attributes;\n  }\n\n  public query = {\n    apply: (\n      query: DcuplQueryGroup | DcuplQuery | DcuplQuery[] | DcuplQueryGroup[],\n      options?: { mode?: 'set' | 'add'; skipProcessing?: boolean },\n    ): DcuplGlobalQueryOptions<any> => {\n      return this.applyQuery(query, options);\n    },\n    applyOptions: (\n      itemOptions: DcuplItemsOptions<ListType>,\n      options?: { mode?: 'set' | 'update'; skipProcessing?: boolean },\n    ): DcuplGlobalQueryOptions<any> => {\n      return this.applyOptions(itemOptions, options);\n    },\n    remove: (options?: Partial<DcuplQueryGroup> | DcuplQuery): DcuplGlobalQueryOptions<any> => {\n      return this.removeQuery(options);\n    },\n    reset: (\n      options: { skipProcessing?: boolean } = {\n        skipProcessing: false,\n      },\n    ): DcuplGlobalQueryOptions<any> => {\n      return this.resetQuery(options);\n    },\n    execute: <ItemType extends ListType = ListType>(query?: DcuplListQueryOptions<NoInfer<ItemType>>): ItemType[] => {\n      return this.executeQuery(query);\n    },\n    /** The item with `itemKey` among the list's current items, or `null` when there is none. */\n    one: (options: DcuplItemOptions<ListType>): ListType | null => {\n      return this._getItem(options);\n    },\n    many: (options: DcuplManyItemsOptions<ListType>): ListType[] => {\n      return this._getManyItems(options);\n    },\n    get: (): DcuplGlobalQueryOptions<any> => {\n      return this.getQuery();\n    },\n    has: (options: { groupKey: string; queryKey?: string }): boolean => {\n      return this.hasGroupOrQueryKey(options);\n    },\n\n    // ============================================================================\n    // Semantic Aliases - Clearer naming for improved developer experience\n    // ============================================================================\n\n    /**\n     * Add query condition(s) to the current query.\n     * Accepts single condition or array of conditions.\n     * Each condition is added to the group whose groupKey equals its attribute, found at any\n     * nesting depth with a top-level match first (#302), or to a new top-level `'or'` group\n     * if there is none. To combine conditions in an unkeyed\n     * group, use `addGroup` — unkeyed groups are always appended, never merged.\n     * Clearer alternative to `apply(condition, { mode: 'add' })`.\n     *\n     * @param condition - Single query condition or array of conditions to add\n     * @param options - Optional processing options\n     * @returns Updated query\n     *\n     * @example\n     * ```typescript\n     * // Add single condition\n     * list.catalog.query.addCondition({ operator: 'eq', attribute: 'status', value: 'active' });\n     *\n     * // Add multiple conditions\n     * list.catalog.query.addCondition([\n     *   { operator: 'eq', attribute: 'status', value: 'active' },\n     *   { operator: 'gte', attribute: 'price', value: 100 }\n     * ]);\n     * ```\n     */\n    addCondition: (\n      condition: DcuplQuery | DcuplQuery[],\n      options?: { skipProcessing?: boolean },\n    ): DcuplGlobalQueryOptions<any> => {\n      return this.applyQuery(condition, { mode: 'add', skipProcessing: options?.skipProcessing });\n    },\n\n    /**\n     * Replace the conditions of an attribute group with new condition(s).\n     * Accepts single condition or array of conditions. Each condition replaces the\n     * conditions of the group keyed by its attribute; other groups are kept. The attribute\n     * group is found at any nesting depth, a top-level match first (#302).\n     * Clearer alternative to `apply(condition, { mode: 'set' })`.\n     *\n     * @param condition - Single query condition or array of conditions to set\n     * @param options - Optional processing options\n     * @returns Updated query\n     *\n     * @example\n     * ```typescript\n     * // Replace with single condition\n     * list.catalog.query.setCondition({ operator: 'eq', attribute: 'status', value: 'active' });\n     *\n     * // Replace with multiple conditions\n     * list.catalog.query.setCondition([\n     *   { operator: 'eq', attribute: 'status', value: 'active' },\n     *   { operator: 'gte', attribute: 'price', value: 100 }\n     * ]);\n     * ```\n     */\n    setCondition: (\n      condition: DcuplQuery | DcuplQuery[],\n      options?: { skipProcessing?: boolean },\n    ): DcuplGlobalQueryOptions<any> => {\n      return this.applyQuery(condition, { mode: 'set', skipProcessing: options?.skipProcessing });\n    },\n\n    /**\n     * Add a query group to the filter.\n     * - Keyed group (`groupKey` set): if a group with the same groupKey exists, its queries\n     *   are extended and its groupType is replaced by the given one (if set); otherwise a new\n     *   group is created. The existing group is found at any nesting depth, a top-level match\n     *   first, so a group nested in a keyless wrapper is extended where it is (#302).\n     * - Unkeyed group (no `groupKey`): always appended as a new group; it is never merged\n     *   into another group, so each unkeyed group keeps its own groupType.\n     *\n     * A newly created group without `groupType` is stored as `'or'`.\n     *\n     * @param group - Query group to add\n     * @param options - Optional processing options\n     * @returns Updated query\n     *\n     * @example\n     * ```typescript\n     * list.catalog.query.addGroup({\n     *   groupKey: 'priceRange',\n     *   groupType: 'and',\n     *   queries: [\n     *     { operator: 'gte', attribute: 'price', value: 50 },\n     *     { operator: 'lte', attribute: 'price', value: 100 }\n     *   ]\n     * });\n     * ```\n     */\n    addGroup: (group: DcuplQueryGroup, options?: { skipProcessing?: boolean }): DcuplGlobalQueryOptions<any> => {\n      return this.applyQuery(group, { mode: 'add', skipProcessing: options?.skipProcessing });\n    },\n\n    /**\n     * Replace one query group by key (per-group `set`).\n     * The group with the same `groupKey` is replaced; other groups and the query options\n     * are kept. Only `apply({ groupKey: 'root', ... }, { mode: 'set' })` replaces the whole\n     * query. A keyed group passed inside a keyless wrapper group stays nested there and is\n     * still found by `groupKey` by `removeGroup`, `has`, `filters.get` and `fn.facets`\n     * (#294). A later `setGroup` with that key replaces the nested group in place instead of\n     * appending a second top-level group; a top-level match wins over a nested one (#302).\n     *\n     * A group without `groupType` is stored as `'or'`, also when it replaces an existing group\n     * (#362), so setting the same group twice stores the same query.\n     *\n     * @param group - Query group to set\n     * @param options - Optional processing options\n     * @returns Updated query\n     *\n     * @example\n     * ```typescript\n     * list.catalog.query.setGroup({\n     *   groupKey: 'priceRange',\n     *   groupType: 'and',\n     *   queries: [\n     *     { operator: 'gte', attribute: 'price', value: 50 },\n     *     { operator: 'lte', attribute: 'price', value: 100 }\n     *   ]\n     * });\n     * ```\n     */\n    setGroup: (group: DcuplQueryGroup, options?: { skipProcessing?: boolean }): DcuplGlobalQueryOptions<any> => {\n      return this.applyQuery(group, { mode: 'set', skipProcessing: options?.skipProcessing });\n    },\n\n    /**\n     * Remove query condition(s).\n     * Accepts single condition or array of conditions.\n     * Clearer alias for {@link remove}.\n     *\n     * @param condition - Single query condition or array of conditions to remove\n     * @param options - Optional processing options\n     * @returns Updated query\n     *\n     * @example\n     * ```typescript\n     * // Remove single condition\n     * list.catalog.query.removeCondition({ attribute: 'status', value: 'active' });\n     *\n     * // Remove multiple conditions\n     * list.catalog.query.removeCondition([\n     *   { attribute: 'status' },\n     *   { attribute: 'price' }\n     * ]);\n     * ```\n     */\n    removeCondition: (\n      condition: DcuplQuery | DcuplQuery[],\n      options?: { skipProcessing?: boolean },\n    ): DcuplGlobalQueryOptions<any> => {\n      if (Array.isArray(condition)) {\n        for (const c of condition) {\n          this.removeQuery(c, options);\n        }\n        return this.getQuery();\n      }\n      return this.removeQuery(condition, options);\n    },\n\n    /**\n     * Remove a query group by its key.\n     *\n     * @param groupKey - Key of the group to remove\n     * @param options - Optional processing options\n     * @returns Updated query\n     *\n     * @example\n     * ```typescript\n     * list.catalog.query.removeGroup('priceRange');\n     * ```\n     */\n    removeGroup: (groupKey: string, options?: { skipProcessing?: boolean }): DcuplGlobalQueryOptions<any> => {\n      return this.removeQuery({ groupKey }, options);\n    },\n\n    /**\n     * Clear all filters and reset to initial state.\n     * Clearer alias for {@link reset}.\n     *\n     * @param options - Optional processing options\n     * @returns Empty query\n     *\n     * @example\n     * ```typescript\n     * list.catalog.query.clear();\n     * ```\n     */\n    clear: (options?: { skipProcessing?: boolean }): DcuplGlobalQueryOptions<any> => {\n      return this.resetQuery(options);\n    },\n\n    /**\n     * Get the current query state.\n     * Clearer alias for {@link get}.\n     *\n     * @returns Current query\n     *\n     * @example\n     * ```typescript\n     * const query = list.catalog.query.current();\n     * ```\n     */\n    current: (): DcuplGlobalQueryOptions<any> => {\n      return this.getQuery();\n    },\n\n    /**\n     * Check if the query has any filter conditions.\n     *\n     * @returns true if query has no conditions, false otherwise\n     *\n     * @example\n     * ```typescript\n     * if (list.catalog.query.isEmpty()) {\n     *   console.log('No filters applied');\n     * }\n     * ```\n     */\n    isEmpty: (): boolean => {\n      const query = this.getQuery();\n      return query.queries.length === 0;\n    },\n\n    // ============================================================================\n    // Convenience Methods for Results\n    // ============================================================================\n\n    /**\n     * Get all matching items.\n     * Clearer alias for {@link execute} - more intuitive than \"all()\" which might suggest returning all queries.\n     *\n     * @param options - Optional query options\n     * @returns Array of matching items\n     *\n     * @example\n     * ```typescript\n     * const items = list.catalog.query.items();\n     * const limited = list.catalog.query.items({ count: 10 });\n     * const byPrice = list.catalog.query.items({ sort: { attributes: ['price'], order: ['DESC'] } });\n     * ```\n     */\n    items: <ItemType extends ListType = ListType>(query?: DcuplListQueryOptions<NoInfer<ItemType>>): ItemType[] => {\n      return this.executeQuery(query);\n    },\n\n    /**\n     * Get the first matching result.\n     *\n     * @param options - Optional query options\n     * @returns First matching item or undefined\n     *\n     * @example\n     * ```typescript\n     * const firstItem = list.catalog.query.first();\n     * const firstActive = list.catalog.query.first({\n     *   queries: [{ operator: 'eq', attribute: 'status', value: 'active' }]\n     * });\n     * ```\n     */\n    first: <ItemType extends ListType = ListType>(\n      query?: DcuplListQueryOptions<NoInfer<ItemType>>,\n    ): ItemType | undefined => {\n      const queryOptions = query ? { ...query, count: 1 } : { count: 1 };\n      const results = this.executeQuery(queryOptions);\n      return results[0];\n    },\n\n    /**\n     * Check if any results exist for the current query.\n     *\n     * @param options - Optional query options\n     * @returns true if at least one result exists\n     *\n     * @example\n     * ```typescript\n     * if (list.catalog.query.any()) {\n     *   console.log('Results found');\n     * }\n     *\n     * const hasActive = list.catalog.query.any({\n     *   queries: [{ operator: 'eq', attribute: 'status', value: 'active' }]\n     * });\n     * ```\n     */\n    any: <ItemType extends ListType = ListType>(query?: DcuplListQueryOptions<NoInfer<ItemType>>): boolean => {\n      const queryOptions = query ? { ...query, count: 1 } : { count: 1 };\n      const results = this.executeQuery(queryOptions);\n      return results.length > 0;\n    },\n\n    /**\n     * Count matching items for the current query.\n     *\n     * @param options - Optional query options\n     * @returns Number of matching items\n     *\n     * @example\n     * ```typescript\n     * const total = list.catalog.query.count();\n     * const activeCount = list.catalog.query.count({\n     *   queries: [{ operator: 'eq', attribute: 'status', value: 'active' }]\n     * });\n     * ```\n     */\n    count: <ItemType extends ListType = ListType>(query?: DcuplListQueryOptions<NoInfer<ItemType>>): number => {\n      const results = this.executeQuery(query);\n      return results.length;\n    },\n  };\n\n  public filters = {\n    get: (options: DcuplFilterOptions & { filterKey: string }): FilterItem | undefined => {\n      return this.getFilter(options);\n    },\n    getAll: (options?: DcuplFiltersOptions): FilterItem[] => {\n      return this.getFilters(options);\n    },\n  };\n\n  public fn = {\n    pivot: (options: PivotOptions): PivotResponse => {\n      return this._getPivot(options);\n    },\n    aggregate: (options: AggregationOptions): Aggregation => {\n      return this.getAggregate(options);\n    },\n    suggest: (options: SuggestionOptions): Suggestion[] => {\n      return this._getSuggestions(options);\n    },\n    groupBy: (options: DcuplGroupByOptions<ListType>): GroupByResponse => {\n      return this._getSections(options);\n    },\n    facets: (options: DcuplFacetOptions): DcuplFacet[] => {\n      return this._getFacets(options);\n    },\n    metadata: (): ListMetadata => {\n      return this._getMetadata();\n    },\n  };\n\n  private getViews(): ViewDefinition[] {\n    const views: ViewDefinition[] = [];\n    this.filter.modelParser.views.forEach((view) => {\n      if (view.model === this.model.key) {\n        views.push(view);\n      }\n    });\n    return views;\n  }\n\n  @trigger({\n    scope: 'list',\n    type: 'fn_metadata',\n    cloneResult: true,\n    connectMessage: true,\n    connectMessageResult: true,\n  })\n  private _getMetadata(): ListMetadata {\n    this.initListMetadata();\n    return this.metadata;\n  }\n\n  private getFilters(options?: DcuplFiltersOptions): FilterItem[] {\n    return this._getFilters(options);\n  }\n\n  @trigger({\n    scope: 'list',\n    type: 'filter_many',\n    cloneResult: true,\n    connectMessage: true,\n    connectMessageResult: true,\n  })\n  private _getFilters(options?: DcuplFiltersOptions): FilterItem[] {\n    const result = this.filter.getFilterItems(options);\n\n    if (options?.filterKeys) {\n      return options.filterKeys\n        .map((key) => {\n          const filter = result.find((filter) => filter.key === key);\n          if (!filter) {\n            this.log.error('Filter not found', undefined, { filterKey: key, model: this.model.key });\n          }\n          return filter;\n        })\n        .filter(Boolean) as FilterItem[];\n    }\n\n    return result;\n  }\n\n  private getFilter(options: DcuplFilterOptions & { filterKey: string }): FilterItem | undefined {\n    return this._getFilter(options);\n  }\n\n  @trigger({\n    scope: 'list',\n    type: 'filter_one',\n    cloneResult: true,\n    connectMessage: true,\n    connectMessageResult: true,\n  })\n  private _getFilter(options: DcuplFilterOptions & { filterKey: string }): FilterItem | undefined {\n    const result = this.filter.getFilterItem(options.filterKey, options);\n    return result;\n  }\n\n  @trigger({\n    scope: 'list',\n    type: 'query_get',\n    cloneResult: true,\n  })\n  private getQuery(): DcuplGlobalQueryOptions<ListType> {\n    return this.filter.queryBuilder.getQuery();\n  }\n\n  @trigger({\n    scope: 'list',\n    type: 'query_has',\n  })\n  private hasGroupOrQueryKey(options: { groupKey: string; queryKey?: string }): boolean {\n    return this.filter.queryBuilder.has(options);\n  }\n\n  @trigger({\n    scope: 'list',\n    type: 'query_apply',\n    cloneResult: true,\n    connectMessage: true,\n    connectMessageResult: true,\n  })\n  private applyQuery(\n    queryToApply: DcuplQueryGroup | DcuplQuery | DcuplQuery[] | DcuplQueryGroup[],\n    options?: { mode?: 'set' | 'add'; skipProcessing?: boolean },\n  ): DcuplGlobalQueryOptions<any> {\n    this.assertValidQueryToApply(queryToApply);\n\n    const query = this.filter.queryBuilder.applyQuery(queryToApply, options);\n\n    this.filter.updateFilteredData({ skipProcessing: options?.skipProcessing });\n\n    return query;\n  }\n\n  /**\n   * Rejects a condition or group the query engine cannot evaluate (e.g. `in` with a non-array\n   * value) BEFORE it is stored (#383). It used to be stored first and then fail while computing\n   * the result, so it stayed in the list's query and every later read of the list threw the same\n   * error. Only what `applyQuery` stores is checked, with the same rules (and messages) as a read.\n   */\n  private assertValidQueryToApply(queryToApply: DcuplQueryGroup | DcuplQuery | DcuplQuery[] | DcuplQueryGroup[]): void {\n    if (Array.isArray(queryToApply)) {\n      for (const query of queryToApply) {\n        this.assertValidQueryToApply(query);\n      }\n      return;\n    }\n\n    const queryBuilder = this.filter.queryBuilder;\n    if (queryBuilder.isQuery(queryToApply) || queryBuilder.isQueryGroup(queryToApply)) {\n      this.dcuplApi['queryManager'].validateQuery(queryToApply, this.model.key);\n    }\n  }\n\n  @trigger({\n    scope: 'list',\n    type: 'query_apply_options',\n    cloneResult: true,\n    connectMessage: true,\n    connectMessageResult: true,\n  })\n  private applyOptions(\n    itemOptions: DcuplItemsOptions<ListType>,\n    options?: { mode?: 'set' | 'update'; skipProcessing?: boolean },\n  ): DcuplGlobalQueryOptions<any> {\n    const query = this.filter.queryBuilder.applyOptions(itemOptions, options?.mode);\n\n    this.filter.updateFilteredData({ skipProcessing: options?.skipProcessing });\n\n    return query;\n  }\n\n  @trigger({\n    scope: 'list',\n    type: 'query_remove',\n    cloneResult: true,\n    connectMessage: true,\n    connectMessageResult: true,\n  })\n  private removeQuery(\n    queryToRemove?: Partial<DcuplQueryGroup> | DcuplQuery,\n    options?: { skipProcessing?: boolean },\n  ): DcuplGlobalQueryOptions<any> {\n    let query: DcuplGlobalQueryOptions<any>;\n    if (queryToRemove) {\n      query = this.filter.queryBuilder.removeQuery(queryToRemove);\n    } else {\n      query = this.filter.queryBuilder.removeAllQueries();\n    }\n\n    this.filter.updateFilteredData({ skipProcessing: options?.skipProcessing });\n\n    return query;\n  }\n\n  @trigger({\n    scope: 'list',\n    type: 'query_reset',\n    cloneResult: true,\n    connectMessage: true,\n    connectMessageResult: true,\n  })\n  private resetQuery(options?: { skipProcessing?: boolean }): DcuplGlobalQueryOptions<any> {\n    const query = this.filter.queryBuilder.reset();\n\n    this.filter.updateFilteredData({ skipProcessing: options?.skipProcessing });\n\n    return query;\n  }\n\n  @trigger({\n    scope: 'list',\n    type: 'query_execute',\n    cloneResult: true,\n    connectMessage: true,\n    connectMessageResult: true,\n  })\n  private executeQuery<ItemType extends ListType = ListType>(options?: DcuplListQueryOptions<ItemType>): ItemType[] {\n    // What the caller passed: with the live query, it determines the options used below, so the\n    // cache context holds the live query once instead of again inside the merged options (#356).\n    const requestedOptions = options;\n    if (!options) {\n      options = this.filter.queryBuilder.getQuery();\n    } else if (!options.queries) {\n      // If options provided without queries, merge with current query state\n      const currentQuery = this.filter.queryBuilder.getQuery();\n      options = Object.assign({}, currentQuery, options);\n    }\n\n    // The result is computed on `filter.filteredData`, which follows the\n    // live query, so the live query must be part of the cache context — like\n    // every other reader (facets, aggregation, sections, suggestions). An\n    // options-shaped read that carried its own `queries` used to be keyed by\n    // the options alone and served the pre-mutation result after the query\n    // changed (#210).\n    const cacheContext = this.filter.cacheCtrl.generateContext({\n      options: requestedOptions,\n      query: this.filter.queryBuilder.getQuery(),\n    });\n    const hasCache = this.filter.cacheCtrl.has('query', cacheContext);\n    if (hasCache) {\n      return this.filter.cacheCtrl.get('query', cacheContext);\n    }\n\n    // `options.queries` is always set here (the live query, or merged with it\n    // above); `?? []` only narrows the type, whose `queries` is optional (#283).\n    const fullOptions: DcuplGlobalQueryOptions<ItemType> = Object.assign({}, options, {\n      queries: options.queries ?? [],\n      modelKey: this.model.key,\n    });\n\n    const queriedData = this.dcuplApi['queryManager'].queryData(\n      this.filter.filteredData,\n      fullOptions,\n      false,\n      this.filter.indicesController['indexMap'],\n    );\n\n    const items = this.itemService.getItems(queriedData, this.model, options as DcuplItemsOptions<ListType>);\n    this.filter.cacheCtrl.set('query', cacheContext, items);\n\n    return items as ItemType[];\n  }\n\n  @trigger({\n    scope: 'list',\n    type: 'fn_groupBy',\n    cloneResult: true,\n    connectMessage: true,\n    connectMessageResult: true,\n  })\n  private _getSections(options: DcuplGroupByOptions<any>): GroupByResponse {\n    const cacheContext = this.filter.cacheCtrl.generateContext({\n      options,\n      query: this.filter.queryBuilder.getQuery(),\n    });\n    const hasCache = this.filter.cacheCtrl.has('sections', cacheContext);\n    if (hasCache) {\n      return this.filter.cacheCtrl.get('sections', cacheContext);\n    }\n\n    const response = this.filter.getSections(options);\n\n    this.filter.cacheCtrl.set('sections', cacheContext, response);\n\n    return response;\n  }\n\n  @trigger({\n    scope: 'list',\n    type: 'query_one',\n    cloneResult: true,\n    connectMessage: true,\n    connectMessageResult: true,\n  })\n  private _getItem<ItemType = ListType>(options: DcuplItemOptions<ItemType>): ItemType | null {\n    const item = this.itemService.getItem(\n      options.itemKey,\n      this.filter.filteredData,\n      this.model,\n      options as DcuplItemOptions<ListType>,\n    );\n    return item as ItemType | null;\n  }\n\n  @trigger({\n    scope: 'list',\n    type: 'query_many',\n    cloneResult: true,\n    connectMessage: true,\n    connectMessageResult: true,\n  })\n  private _getManyItems<ItemType = ListType>(options: DcuplManyItemsOptions<ItemType>): ItemType[] {\n    const items = this.itemService.getManyItems(options.itemKeys, this.filter.filteredData, this.model, options);\n    return items as unknown as ItemType[];\n  }\n\n  @trigger({\n    scope: 'list',\n    type: 'fn_suggest',\n    cloneResult: true,\n    connectMessage: true,\n    connectMessageResult: true,\n  })\n  private _getSuggestions(options: SuggestionOptions): Suggestion[] {\n    // set defaults\n    if (typeof options.excludeUndefineds === 'undefined') {\n      options.excludeUndefineds = true;\n    }\n    if (typeof options.excludeNulls === 'undefined') {\n      options.excludeNulls = true;\n    }\n    if (typeof options.calculateResultKeys === 'undefined') {\n      options.calculateResultKeys = true;\n    }\n\n    // check cache\n    const cacheContext = this.filter.cacheCtrl.generateContext({\n      options,\n      query: this.filter.queryBuilder.getQuery(),\n    });\n    const hasCache = this.filter.cacheCtrl.has('suggestions', cacheContext);\n    if (hasCache) {\n      return this.filter.cacheCtrl.get('suggestions', cacheContext);\n    }\n\n    // check if attribute exists (skip for deep queries)\n    const isDeepQuery = deepQueryService.parse(options.attribute).isDeepQuery;\n    if (!isDeepQuery) {\n      const attribute = this.model.getAttribute(options.attribute);\n      if (!attribute) {\n        throw new Error(`Attribute ${options.attribute} does not exist`);\n      }\n    }\n\n    const regexLiteral = parseRegexLiteral(options.value, options.regexFlags);\n    if (regexLiteral) {\n      try {\n        new RegExp(regexLiteral.pattern, regexLiteral.flags);\n      } catch (_err) {\n        return [];\n      }\n    }\n\n    let relevantData: Map<string, ListType>;\n    let relevantQuery: DcuplGlobalQueryOptions<any> | undefined = undefined;\n    if (options.relevantData === 'all') {\n      relevantData = this.filter.initialData;\n      relevantQuery = { modelKey: this.model.key, queries: [] };\n    } else if (options.relevantData === 'filtered') {\n      relevantData = this.filter.filteredData;\n      relevantQuery = this.filter.queryBuilder.getQuery();\n    } else if (options.relevantData === 'excludeQuery' && options.excludeQuery) {\n      const qb = new DcuplQueryBuilder();\n      // A group matcher combined with `operator` would match no group and exclude nothing (#536).\n      if (!qb.isQuery(options.excludeQuery) && qb.isQueryGroup(options.excludeQuery)) {\n        this.dcuplApi['queryManager'].assertGroupCombinator(options.excludeQuery);\n      }\n      qb.init(this.filter.queryBuilder.getQuery());\n      // Note: init() now handles full query initialization, no need to apply again\n      qb.removeQuery(options.excludeQuery);\n      relevantQuery = qb.getQuery();\n      const filteredDataWithExcludedQuery = this.dcuplApi['queryManager'].queryData(\n        this.filter.initialData,\n        relevantQuery,\n        false,\n        this.filter.indicesController['indexMap'],\n      );\n      relevantData = filteredDataWithExcludedQuery;\n    } else {\n      // default - use filtered data\n      relevantData = this.filter.filteredData;\n      relevantQuery = this.filter.queryBuilder.getQuery();\n    }\n\n    // For deep queries, project the data before creating indices\n    let dataForIndexing = relevantData;\n    if (isDeepQuery) {\n      const attributeEntry = deepQueryService.parse(options.attribute);\n      const projection = this.filter.projectionFor([attributeEntry]);\n      const projectedData = new Map<string, ListType>();\n\n      for (const [key, item] of relevantData) {\n        const projectedItem = this.filter.item.getProjectedData(projection, this.model, item);\n        projectedData.set(key, projectedItem as ListType);\n      }\n\n      dataForIndexing = projectedData;\n    }\n\n    // The index covers the items relevantQuery selected, so a change of its attributes makes it\n    // stale as well (#359).\n    const indexMap = this.filter.indicesController.getOrCreateIndex(\n      options.attribute,\n      dataForIndexing,\n      { query: relevantQuery },\n      relevantQuery ? this.filter.queryBuilder.getQueryAttributes(relevantQuery) : [],\n    );\n\n    const suggestions = computeSuggestions(dataForIndexing, indexMap, options, this.dcuplApi['queryManager']);\n\n    this.filter.cacheCtrl.set('suggestions', cacheContext, suggestions);\n\n    return suggestions;\n  }\n\n  @trigger({\n    scope: 'list',\n    type: 'fn_facets',\n    cloneResult: true,\n    connectMessage: true,\n    connectMessageResult: true,\n  })\n  private _getFacets(options: DcuplFacetOptions): DcuplFacet[] {\n    this.assertFacetAttribute(options);\n    const cacheContext = this.filter.cacheCtrl.generateContext({\n      options,\n      query: this.filter.queryBuilder.getQuery(),\n    });\n    const hasCache = this.filter.cacheCtrl.has('facets', cacheContext);\n    if (hasCache) {\n      return this.filter.cacheCtrl.get('facets', cacheContext);\n    }\n\n    // Check if this is a deep query\n    const isDeepQuery = deepQueryService.parse(options.attribute).isDeepQuery;\n\n    let remoteModel: DcuplModel<ListItem> | undefined;\n\n    // Deep queries facet on the leaf attribute values (e.g. countries), not the\n    // remote model's primary keys. Leaving remoteModel set would make filter.getFacets\n    // pull `remoteModel.getData()` into the facet-key space on cache-miss re-runs,\n    // mismatching the dotted-path index and returning [].\n    if (!isDeepQuery) {\n      const reference = this.model.references.get(options.attribute);\n      if (reference) {\n        remoteModel = this.filter.modelParser.models.get(reference.model);\n      }\n    }\n\n    // A dotted facet counts over the list's unfiltered data (not filteredData): getFacets applies\n    // the query minus the excluded group itself, so starting from already-filtered data would make\n    // dotted-path facets non-disjunctive and build the facet index from a subset of the items\n    // (#276). filter.getFacets reads the path's values from the stored rows, without projecting the\n    // items for it (#448).\n    return this.computeFacetsInternal(options, remoteModel, cacheContext);\n  }\n\n  /**\n   * A facet needs `options.attribute`, an attribute of the model (#558): without options the SDK threw\n   * a TypeError, and an unknown attribute answered `[]`. A dotted or bracket path is checked on its\n   * first segment only (a key that contains a dot passes as a whole); the later segments are #191.\n   */\n  private assertFacetAttribute(options: DcuplFacetOptions | undefined): void {\n    const attribute: unknown = options?.attribute;\n    if (typeof attribute !== 'string' || attribute === '') {\n      throw new Error(`facets: options.attribute is required (model \"${this.model.key}\")`);\n    }\n    if (this.model.getAttribute(attribute)) {\n      return;\n    }\n    const firstSegment = deepQueryService.parse(attribute).isDeepQuery ? attribute.split(/[.[]/)[0] : attribute;\n    if (!firstSegment || !this.model.getAttribute(firstSegment)) {\n      throw new Error(`facets: attribute \"${attribute}\" does not exist on model \"${this.model.key}\"`);\n    }\n  }\n\n  private computeFacetsInternal(\n    options: DcuplFacetOptions,\n    remoteModel: DcuplModel<ListItem> | undefined,\n    cacheContext: any,\n  ): DcuplFacet[] {\n    if (typeof options.excludeZeros === 'undefined') {\n      options.excludeZeros = true;\n    }\n\n    if (typeof options.excludeUndefineds === 'undefined') {\n      options.excludeUndefineds = true;\n    }\n\n    if (typeof options.excludeUnresolved === 'undefined') {\n      options.excludeUnresolved = true;\n    }\n\n    if (typeof options.calculateResults === 'undefined') {\n      options.calculateResults = true;\n    }\n\n    const entries: DcuplFacet[] = this.filter.getFacets(options.attribute, remoteModel, {\n      calculateFacets: options.calculateResults,\n      skipKeys: options.skipKeys,\n      count: options.count,\n      excludeZeros: options.excludeZeros,\n      excludeUndefineds: options.excludeUndefineds,\n      excludeUnresolved: options.excludeUnresolved,\n      sort: options.sort,\n      excludeGroup: options.excludeGroup,\n      skipProcessing: false,\n    });\n\n    this.filter.cacheCtrl.set('facets', cacheContext, entries);\n\n    return entries;\n  }\n\n  @trigger({\n    scope: 'list',\n    type: 'fn_aggregate',\n    cloneResult: true,\n    connectMessage: true,\n    connectMessageResult: true,\n  })\n  private getAggregate(options: AggregationOptions): Aggregation {\n    const cacheContext = this.filter.cacheCtrl.generateContext({\n      options,\n      query: this.filter.queryBuilder.getQuery(),\n    });\n    const hasCache = this.filter.cacheCtrl.has('aggregation', cacheContext);\n    if (hasCache) {\n      return this.filter.cacheCtrl.get('aggregation', cacheContext);\n    }\n\n    // Check if this is a deep query and project data if needed\n    const attributeEntry = deepQueryService.parse(options.attribute);\n    let dataForAggregation = this.filter.filteredData;\n\n    if (attributeEntry.isDeepQuery) {\n      // Project the data to resolve references for deep queries\n      const projection = this.filter.projectionFor([attributeEntry]);\n      const projectedData = new Map();\n\n      for (const [key, item] of this.filter.filteredData) {\n        const projectedItem = this.filter.item.getProjectedData(projection, this.model, item);\n        projectedData.set(key, projectedItem);\n      }\n\n      dataForAggregation = projectedData;\n    }\n\n    // The index covers the items the list's query selected, so a change of a query attribute makes\n    // it stale as well (#359).\n    const query = this.filter.queryBuilder.getQuery();\n    const aggregate = this.filter.getAggregate(\n      options,\n      dataForAggregation,\n      this.filter.indicesController.getOrCreateIndex(\n        options.attribute,\n        dataForAggregation,\n        query,\n        this.filter.queryBuilder.getQueryAttributes(query),\n      ),\n      true,\n    );\n    this.filter.cacheCtrl.set('aggregation', cacheContext, aggregate);\n    return aggregate;\n  }\n\n  @trigger({\n    scope: 'list',\n    type: 'fn_pivot',\n    cloneResult: true,\n    connectMessage: true,\n    connectMessageResult: true,\n  })\n  private _getPivot(options: PivotOptions): PivotResponse {\n    // A one-dimensional pivot leaves out the other dimension, which is [] (#558), as in the wire contract.\n    // Only then a copy: the options object the caller passes is left as it is.\n    if (\n      options &&\n      ((Array.isArray(options.rows) && options.columns === undefined) ||\n        (Array.isArray(options.columns) && options.rows === undefined))\n    ) {\n      options = { ...options, rows: options.rows ?? [], columns: options.columns ?? [] };\n    }\n    if (\n      !options ||\n      !Array.isArray(options.columns) ||\n      !Array.isArray(options.rows) ||\n      !options.values ||\n      !options.values.length\n    ) {\n      this.log.error('Invalid pivot options', undefined, { model: this.model.key });\n      return { key: 'invalid_options' };\n    }\n    for (const value of options.values) {\n      this.dcuplApi['queryManager'].validateDateGroupBounds(this.model.key, value);\n    }\n\n    const cacheContext = this.filter.cacheCtrl.generateContext({\n      options,\n      query: this.filter.queryBuilder.getQuery(),\n    });\n    const hasCache = this.filter.cacheCtrl.has('pivot', cacheContext);\n    if (hasCache) {\n      return this.filter.cacheCtrl.get('pivot', cacheContext);\n    }\n\n    /**\n     * TODO: Check for possible Improvement\n     * We are passing a new indicesController every time we call pivot\n     * We should probably pass a valid context depending on the current pivoting operation\n     * After the last pivoting operation there are more fine tuned indices that can be reused\n     * Check if those child indices (current query + current pivot depth) can be reused...\n     */\n    let indicesCtrl: IndicesController = new IndicesController();\n\n    if (this.filter.filteredData.size === this.filter.initialData.size) {\n      indicesCtrl = this.filter.indicesController;\n    }\n\n    // Check if any attributes are deep queries and project data if needed\n    const allAttributes = [\n      ...options.rows.map((r) => r.attribute),\n      ...options.columns.map((c) => c.attribute),\n      ...options.values.map((v) => v.attribute),\n    ];\n    const deepQueryAttributes = allAttributes\n      .map((attr) => deepQueryService.parse(attr))\n      .filter((entry) => entry.isDeepQuery);\n\n    let projectedData: Map<string, any> | undefined;\n    if (deepQueryAttributes.length > 0) {\n      // Build projection for all deep query attributes\n      const projection = this.filter.projectionFor(deepQueryAttributes);\n      projectedData = new Map();\n      for (const [key, item] of this.filter.filteredData) {\n        const projectedItem = this.filter.item.getProjectedData(projection, this.model, item);\n        projectedData.set(key, projectedItem);\n      }\n    }\n\n    const result = pivot(this.filter.filteredData, options, { key: 'root' }, 'root', indicesCtrl, projectedData);\n\n    this.filter.cacheCtrl.set('pivot', cacheContext, result);\n\n    return result;\n  }\n}\n","import { ChangeDetector, IndicesController, ListItem } from '@dcupl/common';\n\nimport { DcuplModel } from '../model-parser';\n\nimport { CatalogApi } from './catalog-api';\n\nimport { DcuplApi } from '../dcupl/dcupl-api';\n\nexport class Catalog<ListType extends ListItem = ListItem> extends CatalogApi<ListType> {\n  protected listKey!: string;\n  constructor(\n    protected dcuplApi: DcuplApi,\n    protected cdRef: ChangeDetector,\n    protected indicesController: IndicesController,\n  ) {\n    super(dcuplApi, cdRef, indicesController);\n  }\n\n  protected init(listKey: string, model: DcuplModel<ListType>, data: Map<string, ListType>): void {\n    this.listKey = listKey;\n    this.model = model;\n    this.filter.init(model, data);\n    super.initListeners();\n  }\n\n  protected update(\n    model: DcuplModel<ListType>,\n    data: Map<string, ListType>,\n    indicesController: IndicesController,\n  ): void {\n    this.model = model;\n    this.filter.update(model, data, indicesController);\n  }\n}\n"],"names":["PROJECTION_SAMPLE_ROWS","estimateProjectionSize","projectedData","rows","sampleCount","largestRow","sampled","index","row","estimateCachedValueSize","Filter","modelParser","cdRef","item","indicesController","queryManager","cacheOptions","CacheController","resolveCacheMaxSize","resolveProjectionCacheMaxSize","value","model","data","DcuplQueryBuilder","debug","deepIndicesReset","indexCount","query","attributes","group","q","deepQueryService","deepAttributes","entries","attr","projection","attribute","entry","cacheKey","context","cached","key","pathModels","attributeKey","segments","projected","getDeepPathValues","options","relevantData","indexMap","indexCoversData","getAggregation","aggregate","response","attributeEntry","isDeepQuery","sectionItems","remoteModel","childLevelOptions","validSort","childLevelSorting","projectedItem","sectionContext","IndexContext","sectionAttributes","agg","distinctAggValue","values","remoteItem","sectionItem","topLevelOptions","topLevelSorting","deepAggregateEntries","aggOption","deepAggregateData","initialAggregate","d","filteredData","deepFilteredData","sectionData","aggregateIndex","wildCardItem","i","wildCardOptions","items","optionItem","sort","idx","filterKey","filterItem","defaultOptions","referenceKey","reference","relevantOptions","property","filter","comparisonType","type","filterType","hasFilterEntry","propertyKey","filteredMin","filteredMax","v","initialMin","initialMax","dates","now","_skipKeys","filterOptions","cacheContext","cachedValue","remoteData","pathProjection","pathSegments","attributeValues","relevantModelData","facets","getFacets","itemKeys","start","perf","initialData","earlyReturn","filteredProjected","filterItemId","arrayIncludes","array","length","baseIndexOf","spreadableSymbol","Symbol","isFlattenable","isArray","isArguments","baseFlatten","depth","predicate","isStrict","result","arrayPush","LARGE_ARRAY_SIZE","baseDifference","iteratee","comparator","includes","isCommon","valuesLength","cacheHas","SetCache","outer","computed","valuesIndex","difference","baseRest","isArrayLikeObject","EXPECTED_SORT_SHAPE","ItemService","scriptController","logger","itemId","dataAsMap","dataEntry","objToReturn","count","dataAsArray","scriptName","sortOptions","sortedArray","object","dataTransformer","listItem","undefinedValue","transformerFn","relevantOrder","order","orderBy","direction","it","pagedData","message","attributeSortValid","scriptValid","setKeys","validOrderValues","ref","projectionValue","entryKey","refKey","projectedValues","withMetadata","last","needsProjection","visit","node","nodeModel","element","step","elementModel","segment","keys","collected","CatalogApi","dcuplApi","itemOptions","condition","c","groupKey","queryOptions","views","view","queryToApply","queryBuilder","queryToRemove","requestedOptions","currentQuery","fullOptions","queriedData","regexLiteral","parseRegexLiteral","relevantQuery","qb","dataForIndexing","suggestions","computeSuggestions","firstSegment","dataForAggregation","indicesCtrl","IndicesController","deepQueryAttributes","r","pivot","__decorateClass","trigger","Catalog","listKey"],"mappings":"2HAgDMA,EAAyB,EAe/B,SAASC,EAA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