@tanstack/db
Version:
A reactive client store for building super fast apps on sync
1 lines • 109 kB
Source Map (JSON)
{"version":3,"file":"index.cjs","sources":["../../../../src/query/compiler/index.ts"],"sourcesContent":["import {\n concat as concatOperator,\n distinct,\n filter,\n join as joinOperator,\n map,\n reduce,\n serializeValue,\n tap,\n} from '@tanstack/db-ivm'\nimport { optimizeQuery } from '../optimizer.js'\nimport {\n CollectionInputNotFoundError,\n DistinctRequiresSelectError,\n DuplicateAliasInSubqueryError,\n FnSelectWithGroupByError,\n HavingRequiresGroupByError,\n LimitOffsetRequireOrderByError,\n UnsupportedFromTypeError,\n} from '../../errors.js'\nimport { VIRTUAL_PROP_NAMES } from '../../virtual-props.js'\nimport {\n ConditionalSelect,\n IncludesSubquery,\n PropRef,\n Value as ValClass,\n collectCollectionSources,\n getWhereExpression,\n isExpressionLike,\n} from '../ir.js'\nimport { ensureIndexForField } from '../../indexes/auto-index.js'\nimport { deepEquals } from '../../utils.js'\nimport {\n compileExpression,\n isCaseWhenConditionTrue,\n toBooleanPredicate,\n} from './evaluators.js'\nimport { processJoins, registerLazyDemandPlan } from './joins.js'\nimport { containsAggregate, processGroupBy } from './group-by.js'\nimport { getLazyLoadTargets } from './lazy-targets.js'\nimport { processOrderBy } from './order-by.js'\nimport { processSelect } from './select.js'\nimport type { CollectionSubscription } from '../../collection/subscription.js'\nimport type { OrderByOptimizationInfo } from './order-by.js'\nimport type {\n BasicExpression,\n CollectionRef,\n IncludesMaterialization,\n QueryIR,\n QueryRef,\n UnionAll,\n UnionFrom,\n} from '../ir.js'\nimport type { LazyCollectionCallbacks } from './joins.js'\nimport type { Collection } from '../../collection/index.js'\nimport type {\n KeyedStream,\n NamespacedAndKeyedStream,\n NamespacedRow,\n ResultStream,\n} from '../../types.js'\nimport type { QueryCache, QueryMapping, WindowOptions } from './types.js'\n\nexport type { WindowOptions } from './types.js'\n\n/** Symbol used to tag parent $selected with routing metadata for includes */\nexport const INCLUDES_ROUTING = Symbol(`includesRouting`)\nexport const INCLUDES_PUBLIC_KEY = Symbol(`includesPublicKey`)\nexport const FN_SELECT_STATE = Symbol(`fnSelectState`)\nconst SKIP_INCLUDE = Symbol(`skipInclude`)\n\ntype ConditionalSelectGuard = {\n condition: BasicExpression\n expected: boolean\n}\n\ntype SourceInclude = {\n sourceAlias: string\n include: IncludesCompilationResult\n}\n\ntype ProjectedSourceIncludePath = {\n path: Array<string>\n guards: Array<ConditionalSelectGuard>\n}\n\n/**\n * Result of compiling an includes subquery, including the child pipeline\n * and metadata needed to route child results to parent-scoped Collections.\n */\nexport interface IncludesCompilationResult {\n /** Filtered child pipeline (post inner-join with parent keys) */\n pipeline: ResultStream\n /** Result field name on parent (e.g., \"issues\") */\n fieldName: string\n /** Path where the included value is written in the parent result */\n resultPath: Array<string>\n /** Parent-side correlation ref (e.g., project.id) */\n correlationField: PropRef\n /** Child-side correlation ref (e.g., issue.projectId) */\n childCorrelationField: PropRef\n /** Whether the child query has an ORDER BY clause */\n hasOrderBy: boolean\n /** Full compilation result for the child query (for nested includes + alias tracking) */\n childCompilationResult: CompilationResult\n /** Parent-side projection refs for parent-referencing filters */\n parentProjection?: Array<PropRef>\n /** How the output layer materializes the child result on the parent row */\n materialization: IncludesMaterialization\n /** Internal field used to unwrap scalar child selects */\n scalarField?: string\n}\n\n/**\n * Result of query compilation including both the pipeline and source-specific WHERE clauses\n */\nexport interface CompilationResult {\n /** The ID of the main collection */\n collectionId: string\n\n /** The compiled query pipeline (D2 stream) */\n pipeline: ResultStream\n\n /** Map of opaque source IDs to their WHERE clauses for index optimization */\n sourceWhereClauses: Map<string, BasicExpression<boolean>>\n\n /**\n * Maps each source alias to its collection ID. Enables per-alias subscriptions for self-joins.\n * Example: `{ employee: 'employees-col-id', manager: 'employees-col-id' }`\n */\n aliasToCollectionId: Record<string, string>\n\n /**\n * Flattened mapping from outer alias to innermost alias for subqueries.\n * Always provides one-hop lookups, never recursive chains.\n *\n * Example: `{ activeUser: 'user' }` when `.from({ activeUser: subquery })`\n * where the subquery uses `.from({ user: collection })`.\n *\n * For deeply nested subqueries, the mapping goes directly to the innermost alias:\n * `{ author: 'user' }` (not `{ author: 'activeUser' }`), so `aliasRemapping[alias]`\n * always resolves in a single lookup.\n *\n * Used to resolve subscriptions during lazy loading when join aliases differ from\n * the inner aliases where collection subscriptions were created.\n */\n aliasRemapping: Record<string, string>\n\n /** Child pipelines for includes subqueries */\n includes?: Array<IncludesCompilationResult>\n}\n\n/**\n * Compiles a query IR into a D2 pipeline\n * @param rawQuery The query IR to compile\n * @param inputs Mapping of source aliases to input streams (e.g., `{ employee: input1, manager: input2 }`)\n * @param collections Mapping of collection IDs to Collection instances\n * @param subscriptions Mapping of source aliases to CollectionSubscription instances\n * @param callbacks Mapping of source aliases to lazy loading callbacks\n * @param lazySources Set of source identities that should load data lazily\n * @param optimizableOrderByCollections Map of source IDs to order-by optimization info\n * @param cache Optional cache for compiled subqueries (used internally for recursion)\n * @param queryMapping Optional mapping from optimized queries to original queries\n * @returns A CompilationResult with the pipeline, source WHERE clauses, and alias metadata\n */\nexport function compileQuery(\n rawQuery: QueryIR,\n inputs: Record<string, KeyedStream>,\n collections: Record<string, Collection<any, any, any, any, any>>,\n subscriptions: Record<string, CollectionSubscription>,\n callbacks: Record<string, LazyCollectionCallbacks>,\n lazySources: Set<string>,\n optimizableOrderByCollections: Record<string, OrderByOptimizationInfo>,\n setWindowFn: (windowFn: (options: WindowOptions) => void) => void,\n cache: QueryCache = new WeakMap(),\n queryMapping: QueryMapping = new WeakMap(),\n // For includes: parent key stream to inner-join with this query's FROM\n parentKeyStream?: KeyedStream,\n childCorrelationField?: PropRef,\n): CompilationResult {\n // Check if the original raw query has already been compiled\n const cachedResult =\n parentKeyStream === undefined ? cache.get(rawQuery) : undefined\n if (cachedResult) {\n return cachedResult\n }\n\n // Validate the raw query BEFORE optimization to check user's original structure.\n // This must happen before optimization because the optimizer may create internal\n // subqueries (e.g., for predicate pushdown) that reuse aliases, which is fine.\n validateQueryStructure(rawQuery)\n\n // Optimize the query before compilation\n const { optimizedQuery, sourceWhereClauses } = optimizeQuery(rawQuery)\n // Use a mutable binding so we can shallow-clone select before includes mutation\n let query = optimizedQuery\n\n // Create mapping from optimized query to original for caching\n queryMapping.set(query, rawQuery)\n mapNestedQueries(query, rawQuery, queryMapping)\n\n // Create a copy of the inputs map to avoid modifying the original\n const allInputs = { ...inputs }\n bindSourceInputs(rawQuery, allInputs)\n\n // Track alias to collection id relationships discovered during compilation.\n // This includes all user-declared aliases plus inner aliases from subqueries.\n const aliasToCollectionId: Record<string, string> = {}\n\n // Track alias remapping for subqueries (outer alias → inner alias)\n // e.g., when .join({ activeUser: subquery }) where subquery uses .from({ user: collection })\n // we store: aliasRemapping['activeUser'] = 'user'\n const aliasRemapping: Record<string, string> = {}\n\n // Create a map of source aliases to input streams.\n // Inputs MUST be keyed by alias (e.g., `{ employee: input1, manager: input2 }`),\n // not by collection ID. This enables per-alias subscriptions where different aliases\n // of the same collection (e.g., self-joins) maintain independent filtered streams.\n const sources: Record<string, KeyedStream> = {}\n\n // Process the FROM clause to get the source stream.\n const {\n alias: mainSource,\n collectionId: mainCollectionId,\n pipeline: initialPipeline,\n sources: fromSources,\n sourceIncludes,\n directIncludes,\n isUnionFrom,\n } = processFromClause(\n query.from,\n allInputs,\n collections,\n subscriptions,\n callbacks,\n lazySources,\n optimizableOrderByCollections,\n setWindowFn,\n cache,\n queryMapping,\n aliasToCollectionId,\n aliasRemapping,\n sourceWhereClauses,\n )\n Object.assign(sources, fromSources)\n\n // If this is an includes child query, inner-join the raw input with parent keys.\n // This filters the child collection to only rows matching parents in the result set.\n // The inner join happens BEFORE namespace wrapping / WHERE / SELECT / ORDER BY,\n // so the child pipeline only processes rows that match parents.\n let pipeline: NamespacedAndKeyedStream = initialPipeline\n const childCorrelationAlias = childCorrelationField?.path[0]\n const joinsParentAfterJoins =\n !isUnionFrom &&\n parentKeyStream !== undefined &&\n childCorrelationField !== undefined &&\n childCorrelationAlias !== mainSource\n if (\n !isUnionFrom &&\n parentKeyStream &&\n childCorrelationField &&\n !joinsParentAfterJoins\n ) {\n const mainInput = sources[mainSource]!\n let filteredMainInput = mainInput\n // Re-key child input by correlation field: [correlationValue, [childKey, childRow]]\n const childFieldPath = childCorrelationField.path.slice(1) // remove alias prefix\n const childRekeyed = mainInput.pipe(\n map(([key, row]: [unknown, any]) => {\n const correlationValue = getNestedValue(row, childFieldPath)\n return [correlationValue, [key, row]] as [unknown, [unknown, any]]\n }),\n )\n\n // Inner join: only children whose correlation key exists in parent keys pass through\n const joined = childRekeyed.pipe(joinOperator(parentKeyStream, `inner`))\n\n // Extract: [correlationValue, [[childKey, childRow], parentContext]] → [childKey, childRow]\n // Tag the row with __correlationKey for output routing\n // If parentSide is non-null (parent context projected), attach as __parentContext\n filteredMainInput = joined.pipe(\n filter(([_correlationValue, [childSide]]: any) => {\n return childSide != null\n }),\n map(([correlationValue, [childSide, parentSide]]: any) => {\n const [childKey, childRow] = childSide\n const tagged: any = {\n ...childRow,\n __correlationKey: correlationValue,\n [INCLUDES_PUBLIC_KEY]: childKey,\n }\n if (parentSide != null) {\n tagged.__parentContext = parentSide\n }\n const effectiveKey =\n parentSide != null ? serializeValue([childKey, parentSide]) : childKey\n return [effectiveKey, tagged]\n }),\n )\n\n // Update sources so the rest of the pipeline uses the filtered input\n sources[mainSource] = filteredMainInput\n\n pipeline = wrapInputWithAlias(filteredMainInput, mainSource)\n }\n\n // Process JOIN clauses if they exist\n if (query.join && query.join.length > 0) {\n pipeline = processJoins(\n pipeline,\n query.join,\n sources,\n mainCollectionId,\n mainSource,\n allInputs,\n cache,\n queryMapping,\n collections,\n subscriptions,\n callbacks,\n lazySources,\n optimizableOrderByCollections,\n setWindowFn,\n rawQuery,\n compileQuery,\n aliasToCollectionId,\n aliasRemapping,\n sourceWhereClauses,\n parentKeyStream !== undefined && !joinsParentAfterJoins,\n )\n }\n\n // A correlation field owned by a joined source does not exist on the main\n // input. Join the fully namespaced child relation with its parent routes\n // here, after the source join has made that field available.\n if (joinsParentAfterJoins) {\n const compiledChildCorrelation = compileExpression(childCorrelationField)\n pipeline = pipeline.pipe(\n map(\n ([key, row]) =>\n [compiledChildCorrelation(row), [key, row]] as [\n unknown,\n [unknown, typeof row],\n ],\n ),\n joinOperator(parentKeyStream, `inner`),\n filter(([_correlationValue, [childSide]]) => childSide != null),\n map(([correlationValue, [childSide, parentSide]]) => {\n const [childKey, row] = childSide as [unknown, NamespacedRow]\n const namespaced = { ...row } as Record<string, any>\n namespaced[mainSource] = {\n ...namespaced[mainSource],\n __correlationKey: correlationValue,\n [INCLUDES_PUBLIC_KEY]: childKey,\n }\n if (parentSide != null) {\n Object.assign(namespaced, parentSide)\n namespaced.__parentContext = parentSide\n }\n const effectiveKey =\n parentSide != null ? serializeValue([childKey, parentSide]) : childKey\n return [effectiveKey, namespaced]\n }),\n ) as NamespacedAndKeyedStream\n }\n\n // Process the WHERE clause if it exists\n if (query.where && query.where.length > 0) {\n // Apply each WHERE condition as a filter (they are ANDed together)\n for (const where of query.where) {\n const whereExpression = getWhereExpression(where)\n const compiledWhere = compileExpression(whereExpression)\n pipeline = pipeline.pipe(\n filter(([_key, namespacedRow]) => {\n return toBooleanPredicate(compiledWhere(namespacedRow))\n }),\n )\n }\n }\n\n // Process functional WHERE clauses if they exist\n if (query.fnWhere && query.fnWhere.length > 0) {\n for (const fnWhere of query.fnWhere) {\n pipeline = pipeline.pipe(\n filter(([_key, namespacedRow]) => {\n return toBooleanPredicate(fnWhere(namespacedRow))\n }),\n )\n }\n }\n\n // Extract includes from SELECT, compile child pipelines, and replace with placeholders.\n // This must happen AFTER WHERE (so parent pipeline is filtered) but BEFORE processSelect\n // (so IncludesSubquery nodes are stripped before select compilation).\n const includesResults: Array<IncludesCompilationResult> = !query.select\n ? [...directIncludes]\n : []\n const includesRoutingFns: Array<{\n fieldName: string\n getRouting: (nsRow: any) => {\n active: boolean\n correlationKey: unknown\n parentContext: Record<string, any> | null\n }\n }> = []\n for (const { sourceAlias, include } of sourceIncludes) {\n const projectedPaths =\n query.select != null\n ? findProjectedSourceIncludePaths(\n query.select,\n sourceAlias,\n include.resultPath,\n )\n : query.fnSelect\n ? []\n : [\n {\n path: [sourceAlias, ...include.resultPath],\n guards: [],\n },\n ]\n\n if (projectedPaths.length === 0) {\n continue\n }\n\n for (const { path: resultPath, guards } of projectedPaths) {\n const fieldName = getUniqueIncludesRoutingKey(\n `${sourceAlias}.${resultPath.join(`.`)}`,\n includesRoutingFns,\n )\n const compiledGuards = guards.map((guard) => ({\n condition: compileExpression(guard.condition),\n expected: guard.expected,\n }))\n includesResults.push({\n ...include,\n fieldName,\n resultPath,\n })\n\n includesRoutingFns.push({\n fieldName,\n getRouting: (nsRow: any) => {\n if (!matchesConditionalSelectGuards(compiledGuards, nsRow)) {\n return { active: false, correlationKey: null, parentContext: null }\n }\n return (\n nsRow[sourceAlias]?.[INCLUDES_ROUTING]?.[include.fieldName] ?? {\n active: false,\n correlationKey: null,\n parentContext: null,\n }\n )\n },\n })\n }\n }\n if (query.select && directIncludes.length > 0) {\n for (const include of directIncludes) {\n const projectedPaths = findProjectedResultIncludePaths(\n query.select,\n include.resultPath,\n )\n\n for (const { path: resultPath, guards } of projectedPaths) {\n const fieldName = getUniqueIncludesRoutingKey(\n resultPath.join(`.`),\n includesRoutingFns,\n )\n const compiledGuards = guards.map((guard) => ({\n condition: compileExpression(guard.condition),\n expected: guard.expected,\n }))\n\n includesResults.push({\n ...include,\n fieldName,\n resultPath,\n })\n\n includesRoutingFns.push({\n fieldName,\n getRouting: (nsRow: any) => {\n if (!matchesConditionalSelectGuards(compiledGuards, nsRow)) {\n return {\n active: false,\n correlationKey: null,\n parentContext: null,\n }\n }\n return (\n nsRow[INCLUDES_ROUTING]?.[include.fieldName] ?? {\n active: false,\n correlationKey: null,\n parentContext: null,\n }\n )\n },\n })\n }\n }\n }\n if (query.select) {\n const includesEntries = extractIncludesFromSelect(query.select)\n if (includesEntries.length > 0) {\n query = { ...query, select: { ...query.select } }\n }\n for (const { key, path, subquery, guards } of includesEntries) {\n const fieldName = getUniqueIncludesRoutingKey(key, includesRoutingFns)\n // Branch parent pipeline: map to [correlationValue, parentContext]\n // When parentProjection exists, project referenced parent fields; otherwise null (zero overhead)\n const compiledCorrelation = compileExpression(subquery.correlationField)\n const compiledGuards = guards.map((guard) => ({\n condition: compileExpression(guard.condition),\n expected: guard.expected,\n }))\n let parentKeys: any\n if (subquery.parentProjection && subquery.parentProjection.length > 0) {\n const compiledProjections = subquery.parentProjection.map((ref) => ({\n alias: ref.path[0]!,\n field: ref.path.slice(1),\n compiled: compileExpression(ref),\n }))\n parentKeys = pipeline.pipe(\n map(([_key, nsRow]: any) => {\n if (!matchesConditionalSelectGuards(compiledGuards, nsRow)) {\n return [SKIP_INCLUDE, null] as any\n }\n const parentContext: Record<string, Record<string, any>> = {}\n for (const proj of compiledProjections) {\n if (!parentContext[proj.alias]) {\n parentContext[proj.alias] = {}\n }\n const value = proj.compiled(nsRow)\n // Set nested field in the alias namespace\n let target = parentContext[proj.alias]!\n for (let i = 0; i < proj.field.length - 1; i++) {\n if (!target[proj.field[i]!]) {\n target[proj.field[i]!] = {}\n }\n target = target[proj.field[i]!]\n }\n target[proj.field[proj.field.length - 1]!] = value\n }\n return [compiledCorrelation(nsRow), parentContext] as any\n }),\n )\n } else {\n parentKeys = pipeline.pipe(\n map(([_key, nsRow]: any) => {\n if (!matchesConditionalSelectGuards(compiledGuards, nsRow)) {\n return [SKIP_INCLUDE, null] as any\n }\n return [compiledCorrelation(nsRow), null] as any\n }),\n )\n }\n parentKeys = parentKeys.pipe(\n filter(([correlationValue]: any) => correlationValue !== SKIP_INCLUDE),\n )\n\n // Deduplicate: when multiple parents share the same correlation key (and\n // parentContext), clamp multiplicity to 1 so the inner join doesn't\n // produce duplicate child entries that cause incorrect deletions.\n parentKeys = parentKeys.pipe(\n reduce((values: Array<[any, number]>) =>\n values.map(([v, mult]) => [v, mult > 0 ? 1 : 0] as [any, number]),\n ),\n )\n\n // --- Includes lazy loading (mirrors join lazy loading in joins.ts) ---\n // Resolve the child correlation field to concrete collection targets so\n // subquery and union child sources can load by branch when it is safe.\n const childSourceAlias = subquery.childCorrelationField.path[0]!\n const directChildCollection =\n subquery.query.from.type === `collectionRef`\n ? subquery.query.from.collection\n : undefined\n const lazyTargets = getLazyLoadTargets(\n subquery.query,\n subquery.query.from,\n childSourceAlias,\n subquery.childCorrelationField,\n directChildCollection,\n aliasRemapping,\n )\n\n if (lazyTargets.length > 0) {\n // 1. Mark child source as lazy so CollectionSubscriber skips initial full load\n for (const target of lazyTargets) {\n lazySources.add(target.sourceId)\n }\n\n // 2. Ensure an index on the correlation field for efficient lookups\n for (const target of lazyTargets) {\n const targetFieldName = target.path[0]\n if (targetFieldName) {\n ensureIndexForField(targetFieldName, target.path, target.collection)\n }\n }\n\n const initialKeys = getStaticDemandKeys(\n rawQuery,\n subquery.correlationField,\n )\n const demandPlans = lazyTargets.map((target) =>\n registerLazyDemandPlan(callbacks, target, initialKeys),\n )\n const demandWeights = new Map<\n string,\n { key: unknown; weight: number }\n >()\n\n // Keep the async demand adapter in sync with the current parent-key\n // relation. Retired keys stop participating in readiness immediately.\n parentKeys = parentKeys.pipe(\n tap((data: any) => {\n for (const [[correlationValue], weight] of data.getInner()) {\n if (correlationValue == null) continue\n const encoded = serializeValue(correlationValue)\n const previous = demandWeights.get(encoded)\n const nextWeight = (previous?.weight ?? 0) + weight\n if (nextWeight === 0) {\n demandWeights.delete(encoded)\n } else {\n demandWeights.set(encoded, {\n key: correlationValue,\n weight: nextWeight,\n })\n }\n }\n\n const keys = new Set(\n [...demandWeights.values()]\n .filter(({ weight }) => weight > 0)\n .map(({ key: demandedKey }) => demandedKey),\n )\n for (let index = 0; index < lazyTargets.length; index++) {\n const target = lazyTargets[index]!\n const plan = demandPlans[index]!\n callbacks[target.sourceId]?.setDemand?.(plan, keys)\n }\n }),\n )\n }\n\n // If parent filters exist, append them to the child query's WHERE\n const childQuery =\n subquery.parentFilters && subquery.parentFilters.length > 0\n ? {\n ...subquery.query,\n where: [\n ...(subquery.query.where || []),\n ...subquery.parentFilters,\n ],\n }\n : subquery.query\n\n // Recursively compile child query WITH the parent key stream\n const childResult = compileQuery(\n childQuery,\n allInputs,\n collections,\n subscriptions,\n callbacks,\n lazySources,\n optimizableOrderByCollections,\n setWindowFn,\n cache,\n queryMapping,\n parentKeys,\n subquery.childCorrelationField,\n )\n\n // Merge child's alias metadata into parent's\n Object.assign(aliasToCollectionId, childResult.aliasToCollectionId)\n Object.assign(aliasRemapping, childResult.aliasRemapping)\n for (const [alias, whereClause] of childResult.sourceWhereClauses) {\n sourceWhereClauses.set(alias, whereClause)\n }\n\n includesResults.push({\n pipeline: childResult.pipeline,\n fieldName,\n resultPath: path,\n correlationField: subquery.correlationField,\n childCorrelationField: subquery.childCorrelationField,\n hasOrderBy: !!(\n subquery.query.orderBy && subquery.query.orderBy.length > 0\n ),\n childCompilationResult: childResult,\n parentProjection: subquery.parentProjection,\n materialization: subquery.materialization,\n scalarField: subquery.scalarField,\n })\n\n // Capture routing function for INCLUDES_ROUTING tagging\n if (subquery.parentProjection && subquery.parentProjection.length > 0) {\n const compiledProjs = subquery.parentProjection.map((ref) => ({\n alias: ref.path[0]!,\n field: ref.path.slice(1),\n compiled: compileExpression(ref),\n }))\n const compiledCorr = compiledCorrelation\n const compiledRoutingGuards = compiledGuards\n includesRoutingFns.push({\n fieldName,\n getRouting: (nsRow: any) => {\n if (!matchesConditionalSelectGuards(compiledRoutingGuards, nsRow)) {\n return {\n active: false,\n correlationKey: null,\n parentContext: null,\n }\n }\n const parentContext: Record<string, Record<string, any>> = {}\n for (const proj of compiledProjs) {\n if (!parentContext[proj.alias]) {\n parentContext[proj.alias] = {}\n }\n const value = proj.compiled(nsRow)\n let target = parentContext[proj.alias]!\n for (let i = 0; i < proj.field.length - 1; i++) {\n if (!target[proj.field[i]!]) {\n target[proj.field[i]!] = {}\n }\n target = target[proj.field[i]!]\n }\n target[proj.field[proj.field.length - 1]!] = value\n }\n return {\n active: true,\n correlationKey: compiledCorr(nsRow),\n parentContext,\n }\n },\n })\n } else {\n const compiledRoutingGuards = compiledGuards\n includesRoutingFns.push({\n fieldName,\n getRouting: (nsRow: any) => {\n if (!matchesConditionalSelectGuards(compiledRoutingGuards, nsRow)) {\n return {\n active: false,\n correlationKey: null,\n parentContext: null,\n }\n }\n return {\n active: true,\n correlationKey: compiledCorrelation(nsRow),\n parentContext: null,\n }\n },\n })\n }\n\n // Replace includes entry in select with a null placeholder\n query = {\n ...query,\n select: replaceIncludesInSelect(query.select!, path),\n }\n }\n }\n\n if (\n query.distinct &&\n !query.fnSelect &&\n !query.select &&\n query.from.type !== `unionAll`\n ) {\n throw new DistinctRequiresSelectError()\n }\n\n if (query.fnSelect && query.groupBy && query.groupBy.length > 0) {\n throw new FnSelectWithGroupByError()\n }\n\n // Process the SELECT clause early - always create $selected\n // This eliminates duplication and allows for DISTINCT implementation\n if (query.fnSelect) {\n // Handle functional select - apply the function to transform the row\n pipeline = pipeline.pipe(\n map(([key, namespacedRow]) => {\n const selectResults = query.fnSelect!(namespacedRow)\n let selected = selectResults\n if (selectResults && typeof selectResults === `object`) {\n selected = Array.isArray(selectResults)\n ? [...selectResults]\n : { ...selectResults }\n const routing = (namespacedRow as any)[INCLUDES_ROUTING]\n if (routing) {\n selected[INCLUDES_ROUTING] = routing\n }\n if (directIncludes.length > 0) {\n Object.defineProperty(selected, FN_SELECT_STATE, {\n value: {\n sourceRow: namespacedRow,\n fnSelect: query.fnSelect!,\n },\n enumerable: true,\n configurable: true,\n })\n }\n }\n return [\n key,\n {\n ...namespacedRow,\n $selected: selected,\n },\n ] as [string, typeof namespacedRow & { $selected: any }]\n }),\n )\n } else if (query.select) {\n pipeline = processSelect(pipeline, query.select, allInputs)\n } else {\n // If no SELECT clause, create $selected with the main table data\n pipeline = pipeline.pipe(\n map(([key, namespacedRow]) => {\n const selectResults =\n !isUnionFrom && !query.join && !query.groupBy\n ? namespacedRow[mainSource]\n : namespacedRow\n\n return [\n key,\n {\n ...namespacedRow,\n $selected: selectResults,\n },\n ] as [string, typeof namespacedRow & { $selected: any }]\n }),\n )\n }\n\n // Tag $selected with routing metadata so the materialization graph can route\n // children without depending on the user's projection.\n if (includesRoutingFns.length > 0) {\n pipeline = pipeline.pipe(\n map(([key, namespacedRow]: any) => {\n const routing: Record<\n string,\n {\n active: boolean\n correlationKey: unknown\n parentContext: Record<string, any> | null\n }\n > = {}\n for (const { fieldName, getRouting } of includesRoutingFns) {\n routing[fieldName] = getRouting(namespacedRow)\n }\n const selected = Array.isArray(namespacedRow.$selected)\n ? [...namespacedRow.$selected]\n : { ...namespacedRow.$selected }\n selected[INCLUDES_ROUTING] = routing\n return [key, { ...namespacedRow, $selected: selected }]\n }),\n )\n }\n\n // Process the GROUP BY clause if it exists.\n // When in includes mode (parentKeyStream), pass mainSource so that groupBy\n // preserves __correlationKey for per-parent aggregation.\n const groupByMainSource = parentKeyStream ? mainSource : undefined\n if (query.groupBy && query.groupBy.length > 0) {\n pipeline = processGroupBy(\n pipeline,\n query.groupBy,\n query.having,\n query.select,\n query.fnHaving,\n mainCollectionId,\n groupByMainSource,\n )\n } else if (query.select) {\n // Check if SELECT contains aggregates but no GROUP BY (implicit single-group aggregation)\n const hasAggregates = Object.values(query.select).some(\n (expr) => expr.type === `agg` || containsAggregate(expr),\n )\n if (hasAggregates) {\n // Handle implicit single-group aggregation\n pipeline = processGroupBy(\n pipeline,\n [], // Empty group by means single group\n query.having,\n query.select,\n query.fnHaving,\n mainCollectionId,\n groupByMainSource,\n )\n }\n }\n\n // Process the HAVING clause if it exists (only applies after GROUP BY)\n if (query.having && (!query.groupBy || query.groupBy.length === 0)) {\n // Check if we have aggregates in SELECT that would trigger implicit grouping\n const hasAggregates = query.select\n ? Object.values(query.select).some((expr) => expr.type === `agg`)\n : false\n\n if (!hasAggregates) {\n throw new HavingRequiresGroupByError()\n }\n }\n\n // Process functional HAVING clauses outside of GROUP BY (treat as additional WHERE filters)\n if (\n query.fnHaving &&\n query.fnHaving.length > 0 &&\n (!query.groupBy || query.groupBy.length === 0)\n ) {\n // If there's no GROUP BY but there are fnHaving clauses, apply them as filters\n for (const fnHaving of query.fnHaving) {\n pipeline = pipeline.pipe(\n filter(([_key, namespacedRow]) => {\n return fnHaving(namespacedRow)\n }),\n )\n }\n }\n\n // Normalize every logical row before DISTINCT and ordering. Those operators\n // track visibility by row key, so an insert-before-delete replacement with\n // the same key would otherwise keep the old value and hide route or order\n // changes. Joined contributors may differ in unselected namespaces; only\n // the public value and its route/order inputs must be congruent.\n if (!query.select || !containsAggregate(query.select)) {\n pipeline = canonicalizeSelectedRows(\n pipeline,\n query,\n mainSource,\n parentKeyStream !== undefined,\n )\n }\n\n const keyedSourceWhereClauses = keyWhereClausesBySource(\n rawQuery,\n sourceWhereClauses,\n aliasRemapping,\n )\n\n // Process the DISTINCT clause if it exists\n if (query.distinct) {\n pipeline = pipeline.pipe(distinct(([_key, row]) => row.$selected))\n }\n\n // Process orderBy parameter if it exists\n if (query.orderBy && query.orderBy.length > 0) {\n // When in includes mode with limit/offset, use grouped ordering so that\n // the limit is applied per parent (per correlation key), not globally.\n const includesGroupKeyFn =\n parentKeyStream &&\n (query.limit !== undefined || query.offset !== undefined)\n ? (_key: unknown, row: unknown) => {\n const correlationKey =\n (row as any)?.[mainSource]?.__correlationKey ??\n (row as any)?.__correlationKey\n const parentContext = (row as any)?.__parentContext\n if (parentContext != null) {\n return serializeValue([correlationKey, parentContext])\n }\n return correlationKey\n }\n : undefined\n\n const orderedPipeline = processOrderBy(\n rawQuery,\n pipeline,\n query.orderBy,\n query.select || {},\n collections[mainCollectionId]!,\n optimizableOrderByCollections,\n setWindowFn,\n query.limit,\n query.offset,\n includesGroupKeyFn,\n )\n\n // Final step: extract the $selected and include orderBy index\n const resultPipeline: ResultStream = orderedPipeline.pipe(\n map(([key, [row, orderByIndex]]) => {\n // Extract the final results from $selected and include orderBy index\n const raw = (row as any).$selected\n const finalResults = attachVirtualPropsToSelected(\n unwrapValue(raw),\n row as Record<string, any>,\n )\n // When in includes mode, embed the correlation key and parentContext\n if (parentKeyStream) {\n const correlationKey =\n (row as any)[mainSource]?.__correlationKey ??\n (row as any).__correlationKey\n const parentContext = (row as any).__parentContext ?? null\n const publicKey = getIncludesPublicKey(row, mainSource, key)\n const routedResults = stripInternalCorrelation(finalResults)\n return [\n key,\n [\n routedResults,\n orderByIndex,\n correlationKey,\n parentContext,\n publicKey,\n ],\n ] as any\n }\n return [key, [finalResults, orderByIndex]] as [unknown, [any, string]]\n }),\n ) as ResultStream\n\n // Cache the result before returning (use original query as key)\n const compilationResult: CompilationResult = {\n collectionId: mainCollectionId,\n pipeline: resultPipeline,\n sourceWhereClauses: keyedSourceWhereClauses,\n aliasToCollectionId,\n aliasRemapping,\n includes: includesResults.length > 0 ? includesResults : undefined,\n }\n if (parentKeyStream === undefined) cache.set(rawQuery, compilationResult)\n\n return compilationResult\n } else if (query.limit !== undefined || query.offset !== undefined) {\n // If there's a limit or offset without orderBy, throw an error\n throw new LimitOffsetRequireOrderByError()\n }\n\n // Final step: extract the $selected and return tuple format (no orderBy)\n const resultPipeline: ResultStream = pipeline.pipe(\n map(([key, row]) => {\n // Extract the final results from $selected and return [key, [results, undefined]]\n const raw = (row as any).$selected\n const finalResults = attachVirtualPropsToSelected(\n unwrapValue(raw),\n row as Record<string, any>,\n )\n // When in includes mode, embed the correlation key and parentContext\n if (parentKeyStream) {\n const correlationKey =\n (row as any)[mainSource]?.__correlationKey ??\n (row as any).__correlationKey\n const parentContext = (row as any).__parentContext ?? null\n const publicKey = getIncludesPublicKey(row, mainSource, key)\n const routedResults = stripInternalCorrelation(finalResults)\n return [\n key,\n [routedResults, undefined, correlationKey, parentContext, publicKey],\n ] as any\n }\n return [key, [finalResults, undefined]] as [\n unknown,\n [any, string | undefined],\n ]\n }),\n )\n\n // Cache the result before returning (use original query as key)\n const compilationResult: CompilationResult = {\n collectionId: mainCollectionId,\n pipeline: resultPipeline,\n sourceWhereClauses: keyedSourceWhereClauses,\n aliasToCollectionId,\n aliasRemapping,\n includes: includesResults.length > 0 ? includesResults : undefined,\n }\n if (parentKeyStream === undefined) cache.set(rawQuery, compilationResult)\n\n return compilationResult\n}\n\nfunction keyWhereClausesBySource(\n query: QueryIR,\n clauses: Map<string, BasicExpression<boolean>>,\n aliasRemapping: Record<string, string>,\n): Map<string, BasicExpression<boolean>> {\n const sources = collectCollectionSources(query)\n const sourceIds = new Set(sources.map(({ sourceId }) => sourceId))\n const result = new Map<string, BasicExpression<boolean>>()\n for (const [key, clause] of clauses) {\n if (sourceIds.has(key)) {\n result.set(key, clause)\n continue\n }\n\n const alias = aliasRemapping[key] ?? key\n for (const source of sources) {\n if (source.alias === alias) result.set(source.sourceId, clause)\n }\n }\n return result\n}\n\nfunction bindSourceInputs(\n query: QueryIR,\n inputs: Record<string, KeyedStream>,\n): void {\n for (const source of collectCollectionSources(query)) {\n const input = inputs[source.sourceId] ?? inputs[source.alias]\n if (!input) continue\n inputs[source.sourceId] = input\n inputs[source.alias] = input\n }\n}\n\nfunction canonicalizeSelectedRows(\n pipeline: NamespacedAndKeyedStream,\n query: QueryIR,\n mainSource: string,\n isIncludedRelation: boolean,\n): NamespacedAndKeyedStream {\n const compiledOrder = (query.orderBy ?? []).map(({ expression }) =>\n compileExpression(expression),\n )\n const signature = (row: any) => ({\n value: row.$selected,\n routing: row.$selected?.[INCLUDES_ROUTING],\n outerCorrelation: isIncludedRelation\n ? row[mainSource]?.__correlationKey\n : undefined,\n parentContext: isIncludedRelation\n ? (row.__parentContext ?? row[mainSource]?.__parentContext ?? null)\n : undefined,\n order: compiledOrder.map((evaluate) => evaluate(row)),\n })\n\n return pipeline.pipe(\n reduce((values: Array<[any, number]>) => {\n const totalMultiplicity = values.reduce(\n (total, [, multiplicity]) => total + multiplicity,\n 0,\n )\n if (totalMultiplicity === 0) return []\n if (totalMultiplicity < 0) {\n throw new Error(`Query row has negative multiplicity`)\n }\n\n const visible = values.find(([, multiplicity]) => multiplicity > 0)?.[0]\n if (!visible) throw new Error(`Query row has no positive contributor`)\n const visibleSignature = signature(visible)\n\n for (const [candidate, multiplicity] of values) {\n if (\n multiplicity > 0 &&\n !deepEquals(visibleSignature, signature(candidate))\n ) {\n throw new Error(\n `Query contributors with the same row key are not congruent`,\n )\n }\n }\n\n return [[visible, 1]]\n }),\n ) as NamespacedAndKeyedStream\n}\n\n/**\n * Collects aliases used for DIRECT collection references (not subqueries).\n * Used to validate that subqueries don't reuse parent query collection aliases.\n * Only direct CollectionRef aliases matter - QueryRef aliases don't cause conflicts.\n */\nfunction collectDirectCollectionAliases(query: QueryIR): Set<string> {\n const aliases = new Set<string>()\n\n // Collect FROM alias only if it's a direct collection reference\n for (const source of getFromSources(query.from)) {\n if (source.type === `collectionRef`) {\n aliases.add(source.alias)\n }\n }\n\n // Collect JOIN aliases only for direct collection references\n if (query.join) {\n for (const joinClause of query.join) {\n if (joinClause.from.type === `collectionRef`) {\n aliases.add(joinClause.from.alias)\n }\n }\n }\n\n return aliases\n}\n\n/**\n * Validates the structure of a query and its subqueries.\n * Checks that subqueries don't reuse collection aliases from parent queries.\n * This must be called on the RAW query before optimization.\n */\nfunction validateQueryStructure(\n query: QueryIR,\n parentCollectionAliases: Set<string> = new Set(),\n): void {\n // Collect direct collection aliases from this query level\n const currentLevelAliases = collectDirectCollectionAliases(query)\n\n // Check if any current alias conflicts with parent aliases\n for (const alias of currentLevelAliases) {\n if (parentCollectionAliases.has(alias)) {\n throw new DuplicateAliasInSubqueryError(\n alias,\n Array.from(parentCollectionAliases),\n )\n }\n }\n\n // Combine parent and current aliases for checking nested subqueries\n const combinedAliases = new Set([\n ...parentCollectionAliases,\n ...currentLevelAliases,\n ])\n\n // Recursively validate FROM subqueries\n if (query.from.type === `unionAll`) {\n for (const branch of query.from.queries) {\n validateQueryStructure(branch, combinedAliases)\n }\n } else {\n for (const source of getFromSources(query.from)) {\n if (source.type === `queryRef`) {\n validateQueryStructure(source.query, combinedAliases)\n }\n }\n }\n\n // Recursively validate JOIN subqueries\n if (query.join) {\n for (const joinClause of query.join) {\n if (joinClause.from.type === `queryRef`) {\n validateQueryStructure(joinClause.from.query, combinedAliases)\n }\n }\n }\n\n if (query.select) {\n for (const { subquery } of extractIncludesFromSelect(query.select)) {\n validateQueryStructure(subquery.query, combinedAliases)\n }\n }\n}\n\n/**\n * Processes the FROM clause, handling direct collection references and subqueries.\n * Populates `aliasToCollectionId` and `aliasRemapping` for per-alias subscription tracking.\n */\nfunction processFromClause(\n from: CollectionRef | QueryRef | UnionFrom | UnionAll,\n allInputs: Record<string, KeyedStream>,\n collections: Record<string, Collection>,\n subscriptions: Record<string, CollectionSubscription>,\n callbacks: Record<string, LazyCollectionCallbacks>,\n lazySources: Set<string>,\n optimizableOrderByCollections: Record<string, OrderByOptimizationInfo>,\n setWindowFn: (windowFn: (options: WindowOptions) => void) => void,\n cache: QueryCache,\n queryMapping: QueryMapping,\n aliasToCollectionId: Record<string, string>,\n aliasRemapping: Record<string, string>,\n sourceWhereClauses: Map<string, BasicExpression<boolean>>,\n): {\n alias: string\n pipeline: NamespacedAndKeyedStream\n collectionId: string\n sources: Record<string, KeyedStream>\n sourceIncludes: Array<SourceInclude>\n directIncludes: Array<IncludesCompilationResult>\n isUnionFrom: boolean\n} {\n if (from.type === `unionAll`) {\n return processUnionAll(\n from,\n allInputs,\n collections,\n subscriptions,\n callbacks,\n lazySources,\n optimizableOrderByCollections,\n setWindowFn,\n cache,\n queryMapping,\n aliasToCollectionId,\n aliasRemapping,\n sourceWhereClauses,\n )\n }\n\n if (from.type !== `unionFrom`) {\n const { alias, input, collectionId, sourceIncludes } = processFrom(\n from,\n allInputs,\n collections,\n subscriptions,\n callbacks,\n lazySources,\n optimizableOrderByCollections,\n setWindowFn,\n cache,\n queryMapping,\n aliasToCollectionId,\n aliasRemapping,\n sourceWhereClauses,\n )\n\n return {\n alias,\n pipeline: wrapInputWithAlias(input, alias),\n collectionId,\n sources: { [alias]: input },\n sourceIncludes,\n directIncludes: [],\n isUnionFrom: false,\n }\n }\n\n if (from.sources.length === 0) {\n throw new UnsupportedFromTypeError(`empty unionFrom`)\n }\n\n const sources: Record<string, KeyedStream> = {}\n const sourceIncludes: Array<SourceInclude> = []\n let pipeline: NamespacedAndKeyedStream | undefined\n let mainAlias = ``\n let mainCollectionId = ``\n\n for (const source of from.sources) {\n const {\n alias,\n input,\n collectionId,\n sourceIncludes: childSourceIncludes,\n } = processFrom(\n source,\n allInputs,\n collections,\n subscriptions,\n callbacks,\n lazySources,\n optimizableOrderByCollections,\n setWindowFn,\n cache,\n queryMapping,\n aliasToCollectionId,\n aliasRemapping,\n sourceWhereClauses,\n )\n\n if (!mainAlias) {\n mainAlias = alias\n mainCollectionId = collectionId\n }\n sources[alias] = input\n sourceIncludes.push(...childSourceIncludes)\n\n const branch = wrapInputWithAlias(input, alias).pipe(\n map(([key, row]) => {\n return [`${alias}:${encodeKeyForUnionBranch(key)}`, row] as [\n string,\n typeof row,\n ]\n }),\n )\n\n pipeline = pipeline ? pipeline.pipe(concatOperator(branch)) : branch\n }\n\n return {\n alias: mainAlias,\n pipeline: pipeline!,\n collectionId: mainCollectionId,\n sources,\n sourceIncludes,\n directIncludes: [],\n isUnionFrom: true,\n }\n}\n\nfunction processUnionAll(\n from: UnionAll,\n allInputs: Record<string, KeyedStream>,\n collections: Record<string, Collection>,\n subscriptions: Record<string, CollectionSubscription>,\n callbacks: Record<string, LazyCollectionCallbacks>,\n lazySources: Set<string>,\n optimizableOrderByCollections: Record<string, OrderByOptimizationInfo>,\n setWindowFn: (windowFn: (options: WindowOptions) => void) => void,\n cache: QueryCache,\n queryMapping: QueryMapping,\n aliasToCollectionId: Record<string, string>,\n aliasRemapping: Record<string, string>,\n sourceWhereClauses: Map<string, BasicExpression<boolean>>,\n): {\n alias: string\n pipeline: NamespacedAndKeyedStream\n collectionId: string\n sources: Record<string, KeyedStream>\n sourceIncludes: Array<SourceInclude>\n directIncludes: Array<IncludesCompilationResult>\n isUnionFrom: boolean\n} {\n if (from.queries.length === 0) {\n throw new UnsupportedFromTypeError(`empty unionAll`)\n }\n\n const sources: Record<string, KeyedStream> = {}\n const sourceIncludes: Array<SourceInclude> = []\n const directIncludes: Array<IncludesCompilationResult> = []\n let pipeline: NamespacedAndKeyedStream | undefined\n let mainCollectionId = ``\n const branchAliases = new Set<string>()\n\n for (let index = 0; index < from.queries.length; index++) {\n const branch = from.queries[index]!\n for (const source of getAllSources(branch)) {\n if (branchAliases.has(source.alias)) {\n throw new Error(\n `Duplicate source alias \"${source.alias}\" in unionAll query branches. ` +\n `Use distinct aliases in each branch before passing them to unionAll().`,\n )\n }\n branchAliases.add(source.alias)\n }\n const branchResult = compileQuery(\n branch,\n allInputs,\n collections,\n subscriptions,\n callbacks,\n lazySources,\n optimizableOrderByCollections,\n setWindowFn,\n cache,\n queryMapping,\n )\n\n if (!mainCollectionId) {\n mainCollectionId = branchResult.collectionId\n }\n Object.assign(aliasToCollectionId, branchResult.aliasToCollectionId)\n Object.assign(aliasRemapping, branchResult.aliasRemapping)\n directIncludes.push(...(branchResult.includes ?? []))\n Object.assign(sources, allInputs)\n for (const [alias, where] of branchResult.sourceWhereClauses) {\n sourceWhereClauses.set(alias, where)\n }\n\n const branchPipeline = branchResult.pipeline.pipe(\n map(([key, [row]]) => {\n return [`${index}:${encodeKeyForUnionBranch(key)}`, row] as [\n string,\n Record<string, any>,\n ]\n }),\n )\n\n pipeline = pipeline\n ? pipeline.pipe(concatOperator(branchPipeline))\n : branchPipeline\n }\n\n return {\n alias: ``,\n pipeline: pipeline!,\n collectionId: mainCollectionId,\n sources,\n sourceIncludes,\n directIncludes,\n isUnionFrom: true,\n }\n}\n\nfunction wrapInputWithAlias(\n input: KeyedStream,\n alias: string,\n): NamespacedAndKeyedStream {\n return input.pipe(\n map(([key, row]) => {\n // Initialize the record with a nested structure.\n // If __parentContext exists (from parent-referencing includes), merge parent\n // aliases into the namespaced row so WHERE can resolve parent refs.\n const { __parentContext, ...cleanRow } = row as any\n const nsRow: Record<string, any> = { [alias]: cleanRow }\n if (__parentContext) {\n Object.assign(nsRow, __parentContext)\n ;(nsRow as any).__parentContext = __parentContext\n }\n return [key, nsRow] as [unknown, Record<string, typeof row>]\n }),\n )\n}\n\nfunction encodeKeyForUnionBranch(key: unknown): string {\n if (typeof key === `string`) {\n return `string:${key}`\n }\n if (typeof key === `number`) {\n return `number:${String(key)}`\n }\n if (typeof key === `bigint`) {\n return `bigint:${String(key)}`\n }\n return `${typeof key}:${JSON.stringify(key)}`\n}\n\nfunction processFrom(\n from: CollectionRef | QueryRef,\n allInputs: Record<string, KeyedStream>,\n collections: Record<string, Collection>,\n subscriptions: Record<string, CollectionSubscription>,\n callbacks: Record<string, LazyCollectionCallbacks>,\n lazySources: Set<string>,\n optimizableOrderByCollections: Record<string, OrderByOptimizationInfo>,\n setWindowFn: (windowFn: (options: WindowOptions) => void) => void,\n cache: QueryCache,\n queryMapping: QueryMapping,\n aliasToCollectionId: Record<string, string>,\n aliasRemapping: Record<string, string>,\n sourceWhereClauses: Map<string, BasicExpression<boolean>>,\n): {\n alias: string\n input: KeyedStream\n collectionId: string\n sourceIncludes: Array<SourceInclude>\n} {\n switch (from.type) {\n case `collectionRef`: {\n const input = allInputs[from.sourceId] ?? allInputs[from.alias]\n if (!input) {\n throw new CollectionInputNotFoundError(\n from.alias,\n from.collection.id,\n Object.keys(allInputs),\n )\n }\n aliasToCollectionId[from.alias] = from.collection.id\n return {\n alias: from.alias,\n input,\n collectionId: from.collection.id,\n sourceIncludes: [],\n }\n }\n case `queryRef`: {\n // Find the original query for caching purposes\n const originalQuery = queryMapping.get(from.query) || from.query\n\n // Recursively compile the sub-query with cache\n const subQueryResult = compileQuery(\n originalQuery,\n allInputs,\n collections,\n subscriptions,\n callbacks,\n lazySources,\n optimizableOrderByCollections,\n setWindowFn,\n cache,\n queryMapping,\n )\n\n // Pull up alias mappings from subquery to parent scope.\n // This includes both the innermost alias-to-collection mappings AND\n // any existing remappings from nested subquery levels.\n Object.assign(aliasToCollectionId, subQueryResult.aliasToCollectionId)\n Object.assign(aliasRemapping, subQueryResult.aliasRemapping)\n\n // Pull up source WHERE clauses from subquery to parent scope.\n // This enables loadSubset to receive the correct where clauses for subquery collections.\n //\n // IMPORTANT: Skip pull-up for optimizer-created subqueries. These are detected when:\n // 1. The outer alias (from.alias) matches the inner alias (from.query.from.alias)\n // 2. The subquery was found in queryMapping (it's a user-defined subquery, not optimizer-created)\n //\n // For optimizer-created subqueries, the parent already has the sourceWhereClauses\n // extracted from the original raw query, so pulling up would be redundant.\n // More importantly, pulling up for optimizer-created subqueries can cause issues\n // when the optimizer has restructured the query.\n const isUserDefinedSubquery = queryMapping.has(from.query)\n const subqueryFromAlias = getFirstFromAlias(from.query.from)\n const isOptimizerCreated =\n !isUserDefinedSubquery && from.alias === subqueryFromAlias\n\n if (!isOptimizerCreated) {\n for (const [alias, whereClause] of subQueryResult.sourceWhereClauses) {\n sourceWhereClauses.set(alias, whereClause)\n }\n }\n\n // Create a FLATTENED remapping from outer alias to innermost alias.\n // For nested subqueries, this ensures one-hop lookups (not recursive chains).\n //\n // Example with 3-level nesting:\n // Inner: .from({ user: usersCollection })\n // Middle: .from({ activeUser: innerSubquery }) → creates: activeUser → user\n // Outer: .from({ author: middleSubquery }) → creates: author → user (not author → activeUser)\n //\n // The key insight: We search through the PULLED-UP aliasToCollectionId (which contains\n // the innermost 'user' alias), so we always map directly to the deepest level.\n // This means aliasRemapping[alias] is always a single lookup, never recursive.\n // Needed for subscription resolution during lazy loading.\n const innerAlias = Object.keys(subQueryResult.aliasToCollectionId).find(\n (alias) =>\n subQueryResult.aliasToCollectionId[alias] ===\n subQueryResult.collectionId,\n )\n if (innerAlias && innerAlias !== from.alias) {\n aliasRemapping[from.alias] = innerAlias\n }\n\n // Extract the pipeline from the compilation result\n const subQueryInput = subQueryResult.pipeline\n\n // Subqueries may return [key, [value, orderByIndex]] (with ORDER BY) or [key, value] (without ORDER BY)\n // We need to extract just the value for use in parent queries\n const extractedInput = subQueryInput.pipe(\n map((data: any) => {\n const [key, [value, _orderByIndex]] = data\n // Unwrap Value expressions that might have leaked through as the entire row\n const unwrapped = unwrapValue(value)\n return [key, unwrapped] as [unknown, any]\n }),\n )\n\n return {\n alias: from.alias,\n input: extractedInput,\n collectionId: subQueryResult.collectionId,\n sourceIncludes:\n subQueryResult.includes?.map((include) => ({\n sourceAlias: from.alias,\n include,\n })) ?? [],\n }\n }\n default:\n throw new UnsupportedFromTypeError((from as any).type)\n }\n}\n\n// Helper to check if a value is a Value expression\nfunction isValue(raw: any): boolean {\n return (\n raw instanceof ValClass ||\n (raw && typeof raw === `object` && `type` in raw && raw.type === `val`)\n )\n}\n\n// Helper to unwrap a Value expression or return the value itself\nfunction unwrapValue(value: any): any {\n return isValue(value) ? value.value : value\n}\n\nfunction attachVirtualPropsToSelected(\n selected: any,\n row: Record<string, any>,\n): any {\n if (!selected || typeof selected !== `object`) {\n return selected\n }\n\n let needsMerge = false\n for (const prop of VIRTUAL_PROP_NAMES) {\n if (selected[prop] == null && prop in row) {\n needsMerge = true\n break\n }\n }\n\n if (!needsMerge) {\n return selected\n }\n\n const result = Array.isArray(selected) ? [...selected] : { ...selected }\n for (const prop of VIRTUAL_PROP_NAMES) {\n if (selected[prop] == null && prop in row) {\n result[prop] = row[prop]\n }\n }\n\n return result\n}\n\nfunction stripInternalCorrelation(selected: any): any {\n if (\n !selected ||\n typeof selected !== `object` ||\n (!(`__correlationKey` in selected) &&\n !(`__parentContext` in selected) &&\n !(INCLUDES_PUBLIC_KEY in selected))\n ) {\n return selected\n }\n\n const result = Array.isArray(selected) ? [...selected] : { ...selected }\n delete result.__correlationKey\n delete result.__parentContext\n delete result[INCLUDES_PUBLIC_KEY]\n return result\n}\n\nfunction getIncludesPublicKey(\n row: Record<string, any>,\n mainSource: string,\n fallback: unknown,\n): unknown {\n return row[mainSource]?.[INCLUDES_PUBLIC_KEY] ?? fallback\n}\n\n/**\n * Recursively maps optimized subqueries to their original queries for proper caching.\n * This ensures that when we encounter the same QueryRef object in different contexts,\n * we can find the original query to check the cache.\n */\nfunction mapNestedQueries(\n optimizedQuery: QueryIR,\n originalQuery: QueryIR,\n queryMapping: QueryMapping,\n): void {\n mapNestedFromQueries(optimizedQuery.from, originalQuery.from, queryMapping)\n\n // Map JOIN clauses if they exist\n if (optimizedQuery.join && originalQuery.join) {\n for (\n let i = 0;\n i < optimizedQuery.join.length && i < originalQuery.join.length;\n i++\n ) {\n const optimizedJoin = optimizedQuery.join[i]!\n const originalJoin = originalQuery.join[i]!\n\n if (\n optimizedJoin.from.type === `queryRef` &&\n originalJoin.from.type === `queryRef`\n ) {\n queryMapping.set(optimizedJoin.from.query, originalJoin.from.query)\n // Recursively map nested queries in joins\n mapNestedQueries(\n optimizedJoin.from.query,\n originalJoin.from.query,\n queryMapping,\n )\n }\n }\n }\n}\n\nfunction getRefFromAlias(\n query: QueryIR,\n alias: string,\n): CollectionRef | QueryRef | void {\n for (const source of getFromSources(query.from)) {\n if (source.alias === alias) {\n return source\n }\n }\n\n for (const join of query.join || []) {\n if (join.from.alias === alias) {\n return join.from\n }\n }\n}\n\nfunction getFromSources(\n from: QueryIR[`from`],\n): Array<CollectionRef | QueryRef> {\n if (from.type === `unionFrom`) {\n return from.sources\n }\n if (from.type === `unionAll`) {\n return []\n }\n return [from]\n}\n\nfunction getAllSources(query: QueryIR): Array<CollectionRef | QueryRef> {\n return [\n ...getFromSources(query.from),\n ...(query.join?.map((join) => join.from) ?? []),\n ]\n}\n\nfunction getFirstFromAlias(from: QueryIR[`from`]): string {\n return getFromSources(from)[0]?.alias ?? ``\n}\n\nfunction findProjectedSourceIncludePaths(\n select: Record<string, any>,\n sourceAlias: string,\n sourcePath: Array<string>,\n): Array<ProjectedSourceIncludePath> {\n const targetPath = [sourceAlias, ...sourcePath]\n return findProjectedIncludePaths(select, targetPath)\n}\n\nfunction findProjectedResultIncludePaths(\n select: Record<string, any>,\n resultPath: Array<string>,\n): Array<ProjectedSourceIncludePath> {\n return findProjectedIncludePaths(select, resultPath)\n}\n\nfunction findProjectedIncludePaths(\n select: Record<string, any>,\n targetPath: Array<string>,\n): Array<ProjectedSourceIncludePath> {\n const resultPaths: Array<ProjectedSourceIncludePath> = []\n\n const visitSelectObject = (\n obj: Record<string, any>,\n prefix: Array<string>,\n guards: Array<ConditionalSelectGuard>,\n ) => {\n for (const [key, value] of Object.entries(obj)) {\n if (key.startsWith(`__SPREAD_SENTINEL__`)) {\n visitSpreadSentinel(key, value, prefix, guards)\n continue\n }\n visitSelectValue(value, [...prefix, key], guards)\n }\n }\n\n const visitSpreadSentinel = (\n key: string,\n value: any,\n path: Array<string>,\n guards: Array<ConditionalSelectGuard>,\n ) => {\n const rest = key.slice(`__SPREAD_SENTINEL__`.length)\n const splitIndex = rest.lastIndexOf(`__`)\n const pathStr = splitIndex >= 0 ? rest.slice(0, splitIndex) : rest\n const isRefExpr =\n value &&\n typeof value === `object` &&\n `type` in value &&\n value.type === `ref`\n const sourcePath = isRefExpr\n ? (value as PropRef).path\n : pathStr.split(`.`).filter(Boolean)\n\n if (pathStartsWith(targetPath, sourcePath)) {\n resultPaths.push({\n path: [...path, ...targetPath.slice(sourcePath.length)],\n guards,\n })\n }\n }\n\n const visitSelectValue = (\n value: any,\n path: Array<string>,\n guards: Array<ConditionalSelectGuard>,\n ) => {\n if (value instanceof PropRef && pathStartsWith(targetPath, value.path)) {\n resultPaths.push({\n path: [...path, ...targetPath.slice(value.path.length)],\n guards,\n })\n return\n }\n\n if (value instanceof ConditionalSelect) {\n const previousBranchGuards: Array<ConditionalSelectGuard> = []\n for (const branch of value.branches) {\n visitSelectValue(branch.value, path, [\n ...guards,\n ...previousBranchGuards,\n { condition: branch.condition, expected: true },\n ])\n previousBranchGuards.push({\n condition: branch.condition,\n expected: false,\n })\n }\n if (value.defaultValue !== undefined) {\n visitSelectValue(value.defaultValue, path, [\n ...guards,\n ...previousBranchGuards,\n ])\n }\n return\n }\n\n if (isNestedSelectObject(value)) {\n visitSelectObject(value, path, guards)\n }\n }\n\n visitSelectObject(select, [], [])\n return resultPaths\n}\n\nfunction pathStartsWith(path: Array<string>, prefix: Array<string>): boolean {\n return (\n prefix.length <= path.length && prefix.every((part, i) => path[i] === part)\n )\n}\n\nfunction mapNestedFromQueries(\n optimizedFrom: QueryIR[`from`],\n originalFrom: QueryIR[`from`],\n queryMapping: QueryMapping,\n): void {\n if (optimizedFrom.type === `unionAll` && originalFrom.type === `unionAll`) {\n for (\n let i = 0;\n i < optimizedFrom.queries.length && i < originalFrom.queries.length;\n i++\n ) {\n const optimizedBranch = optimizedFrom.queries[i]!\n const originalBranch = originalFrom.queries[i]!\n queryMapping.set(optimizedBranch, originalBranch)\n mapNestedQueries(optimizedBranch, originalBranch, queryMapping)\n }\n return\n }\n\n const optimizedSources = getFromSources(optimizedFrom)\n const originalSources = getFromSources(originalFrom)\n\n for (\n let i = 0;\n i < optimizedSources.length && i < originalSources.length;\n i++\n ) {\n const optimizedSource = optimizedSources[i]!\n const originalSource = originalSources[i]!\n if (\n optimizedSource.type === `queryRef` &&\n originalSource.type === `queryRef`\n ) {\n queryMapping.set(optimizedSource.query, originalSource.query)\n mapNestedQueries(\n optimizedSource.query,\n originalSource.query,\n queryMapping,\n )\n }\n }\n}\n\n/**\n * Follows the given reference in a query\n * until its finds the root field the reference points to.\n * @returns The collection, its alias, and the path to the root field in this collection\n */\nexport function followRef(\n query: QueryIR,\n ref: PropRef<any>,\n collection: Collection,\n): { collection: Collection; path: Array<string> } | void {\n if (ref.path.length === 0) {\n return\n }\n\n if (ref.path.length === 1) {\n // This field should be part of this collection\n const field = ref.path[0]!\n // is it part of the select clause?\n if (query.select) {\n const selectedField = query.select[field]\n if (selectedField && selectedField.type === `ref`) {\n return followRef(query, selectedField, collection)\n }\n }\n\n // Either this field is not part of the select clause\n // and thus it must be part of the collection itself\n // or it is part of the select but is not a reference\n // so we can stop here and don't have to follow it\n return { collection, path: [field] }\n }\n\n if (ref.path.length > 1) {\n // This is a nested field\n const [alias, ...rest] = ref.path\n const aliasRef = getRefFromAlias(query, alias!)\n if (!aliasRef) {\n return\n }\n\n if (aliasRef.type === `queryRef`) {\n return followRef(aliasRef.query, new PropRef(rest), collection)\n } else {\n // This is a reference to a collection\n // we can't follow it further\n // so the field must be on the collection itself\n return { collection: aliasRef.collection, path: rest }\n }\n }\n}\n\n/**\n * Walks a Select object to find IncludesSubquery entries.\n * Plain nested objects still reject includes, but ConditionalSelect branches can\n * contain guarded nested includes that are only materialized when the branch\n * condition is true.\n */\nfunction extractIncludesFromSelect(select: Record<string, any>): Array<{\n key: string\n path: Array<string>\n subquery: IncludesSubquery\n guards: Array<ConditionalSelectGuard>\n}> {\n const results: Array<{\n key: string\n path: Array<string>\n subquery: IncludesSubquery\n guards: Array<ConditionalSelectGuard>\n }> = []\n for (const [key, value] of Object.entries(select)) {\n if (key.startsWith(`__SPREAD_SENTINEL__`)) continue\n if (value instanceof IncludesSubquery) {\n results.push({\n key: getIncludesRoutingKey([key], results),\n path: [key],\n subquery: value,\n guards: [],\n })\n } else if (value instanceof ConditionalSelect) {\n collectIncludesFromConditionalSelect(value, [key], [], results)\n } else if (isNestedSelectObject(value)) {\n // Check nested objects for IncludesSubquery — not supported yet\n assertNoNestedIncludes(value, key)\n }\n }\n return results\n}\n\nfunction collectIncludesFromConditionalSelect(\n conditional: ConditionalSelect,\n prefixPath: Array<string>,\n guards: Array<ConditionalSelectGuard>,\n results: Array<{\n key: string\n path: Array<string>\n subquery: IncludesSubquery\n guards: Array<ConditionalSelectGuard>\n }>,\n): void {\n const previousBranchGuards: Array<ConditionalSelectGuard> = []\n for (const branch of conditional.branches) {\n collectIncludesFromSelectValue(\n branch.value,\n prefixPath,\n [\n ...guards,\n ...previousBranchGuards,\n { condition: branch.condition, expected: true },\n ],\n results,\n )\n previousBranchGuards.push({\n condition: branch.condition,\n expected: false,\n })\n }\n\n if (conditional.defaultValue !== undefined) {\n collectIncludesFromSelectValue(\n conditional.defaultValue,\n prefixPath,\n [...guards, ...previousBranchGuards],\n results,\n )\n }\n}\n\nfunction collectIncludesFromSelectValue(\n value: any,\n prefixPath: Array<string>,\n guards: Array<ConditionalSelectGuard>,\n results: Array<{\n key: string\n path: Array<string>\n subquery: IncludesSubquery\n guards: Array<ConditionalSelectGuard>\n }>,\n): void {\n if (value instanceof IncludesSubquery) {\n const key = getIncludesRoutingKey(prefixPath, results)\n results.push({ key, path: prefixPath, subquery: value, guards })\n return\n }\n\n if (value instanceof ConditionalSelect) {\n collectIncludesFromConditionalSelect(value, prefixPath, guards, results)\n return\n }\n\n if (!isNestedSelectObject(value)) {\n return\n }\n\n for (const [key, child] of Object.entries(value)) {\n if (key.startsWith(`__SPREAD_SENTINEL__`)) continue\n collectIncludesFromSelectValue(child, [...prefixPath, key], guards, results)\n }\n}\n\nfunction getIncludesRoutingKey(\n path: Array<string>,\n entries: Array<{ key: string }>,\n): string {\n return getUniqueIncludesRoutingKey(path.join(`.`), entries)\n}\n\nfunction getUniqueIncludesRoutingKey(\n baseKey: string,\n entries: Array<{ key?: string; fieldName?: string }>,\n): string {\n const hasKey = (key: string) =>\n entries.some((entry) => (entry.key ?? entry.fieldName) === key)\n\n if (!hasKey(baseKey)) {\n return baseKey\n }\n\n let suffix = entries.length\n let key = `${baseKey}#${suffix}`\n while (hasKey(key)) {\n suffix++\n key = `${baseKey}#${suffix}`\n }\n return key\n}\n\n/** Check if a value is a nested plain object in a select (not an IR expression node) */\nfunction isNestedSelectObject(value: any): value is Record<string, any> {\n return (\n value != null &&\n typeof value === `object` &&\n !Array.isArray(value) &&\n !isExpressionLike(value) &&\n value.__refProxy !== true\n )\n}\n\nfunction assertNoNestedIncludes(\n obj: Record<string, any>,\n parentPath: string,\n): void {\n for (const [key, value] of Object.entries(obj)) {\n if (key.startsWith(`__SPREAD_SENTINEL__`)) continue\n if (value instanceof IncludesSubquery) {\n throw new Error(\n `Includes subqueries must be at the top level of select(). ` +\n `Found nested includes at \"${parentPath}.${key}\".`,\n )\n }\n if (isNestedSelectObject(value)) {\n assertNoNestedIncludes(value, `${parentPath}.${key}`)\n }\n }\n}\n\n/**\n * Replaces an IncludesSubquery entry in the select object with a null Value placeholder.\n * This ensures processSelect() doesn't encounter it.\n */\nfunction replaceIncludesInSelect(\n select: Record<string, any>,\n path: Array<string>,\n): Record<string, any> {\n return replaceIncludesInSelectValue(select, path, new ValClass(null)).value\n}\n\nfunction replaceIncludesInSelectValue(\n value: any,\n path: Array<string>,\n replacement: ValClass,\n): { value: any; replaced: boolean } {\n if (path.length === 0) {\n return replaceIncludesValue(value, replacement)\n }\n\n if (value instanceof ConditionalSelect) {\n return replaceIncludesInConditionalSelect(value, path, replacement)\n }\n\n if (!isNestedSelectObject(value)) {\n return { value, replaced: false }\n }\n\n if (path.length === 1) {\n const field = path[0]!\n const result = replaceIncludesValue(value[field], replacement)\n if (!result.replaced) {\n return { value, replaced: false }\n }\n return {\n value: {\n ...value,\n [field]: result.value,\n },\n replaced: true,\n }\n }\n\n const [head, ...rest] = path\n const result = replaceIncludesInSelectValue(value[head!], rest, replacement)\n if (!result.replaced) {\n return { value, replaced: false }\n }\n return {\n value: {\n ...value,\n [head!]: result.value,\n },\n replaced: true,\n }\n}\n\nfunction replaceIncludesValue(\n value: any,\n replacement: ValClass,\n): { value: any; replaced: boolean } {\n if (value instanceof IncludesSubquery) {\n return { value: replacement, replaced: true }\n }\n\n if (value instanceof ConditionalSelect) {\n return replaceIncludesInConditionalSelect(value, [], replacement)\n }\n\n return { value, replaced: false }\n}\n\nfunction replaceIncludesInConditionalSelect(\n conditional: ConditionalSelect,\n path: Array<string>,\n replacement: ValClass,\n): { value: ConditionalSelect; replaced: boolean } {\n let replaced = false\n const branches = conditional.branches.map((branch) => {\n const result =\n path.length === 0\n ? replaceIncludesValue(branch.value, replacement)\n : replaceIncludesInSelectValue(branch.value, path, replacement)\n if (!result.replaced) {\n return branch\n }\n replaced = true\n return { ...branch, value: result.value }\n })\n\n let defaultValue = conditional.defaultValue\n if (conditional.defaultValue !== undefined) {\n const result =\n path.length === 0\n ? replaceIncludesValue(conditional.defaultValue, replacement)\n : replaceIncludesInSelectValue(\n conditional.defaultValue,\n path,\n replacement,\n )\n if (result.replaced) {\n replaced = true\n defaultValue = result.value\n }\n }\n\n if (!replaced) {\n return { value: conditional, replaced: false }\n }\n\n return {\n value: new ConditionalSelect(branches, defaultValue),\n replaced: true,\n }\n}\n\n/**\n * Gets a nested value from an object by path segments.\n * For v1 with single-level correlation fields (e.g., `projectId`), it's just `obj[path[0]]`.\n */\nfunction getNestedValue(obj: any, path: Array<string>): any {\n let value = obj\n for (const segment of path) {\n if (value == null) return value\n value = value[segment]\n }\n return value\n}\n\nfunction matchesConditionalSelectGuards(\n guards: Array<{\n condition: (row: any) => any\n expected: boolean\n }>,\n row: any,\n): boolean {\n return guards.every(\n (guard) => isCaseWhenConditionTrue(guard.condition(row)) === guard.expected,\n )\n}\n\nexport type CompileQueryFn = typeof compileQuery\n\nfunction getStaticDemandKeys(query: QueryIR, ref: PropRef): Set<unknown> {\n const constraints: Array<Set<unknown>> = []\n const visit = (expression: BasicExpression): void => {\n if (expression.type !== `func`) return\n if (expression.name === `and`) {\n expression.args.forEach(visit)\n return\n }\n if (expression.name !== `eq` && expression.name !== `in`) return\n\n const [left, right] = expression.args\n const value =\n left?.type === `ref` &&\n pathsEqual(left.path, ref.path) &&\n right instanceof ValClass\n ? right.value\n : right?.type === `ref` &&\n pathsEqual(right.path, ref.path) &&\n left instanceof ValClass\n ? left.value\n : undefined\n if (value === undefined) return\n constraints.push(new Set(Array.isArray(value) ? value : [value]))\n }\n\n query.where?.forEach((where) => visit(getWhereExpression(where)))\n if (constraints.length === 0) return new Set()\n return new Set(\n [...constraints[0]!].filter((value) =>\n constraints.slice(1).every((constraint) => constraint.has(value)),\n ),\n )\n}\n\nfunction pathsEqual(left: Array<string>, right: Array<string>): boolean {\n return (\n left.length === right.length &&\n left.every((segment, index) => segment === right[index])\n )\n}\n"],"names":["optimizeQuery","map","joinOperator","filter","serializeValue","processJoins","compileExpression","getWhereExpression","toBooleanPredicate","reduce","lazyTargets","getLazyLoadTargets","ensureIndexForField","registerLazyDemandPlan","tap","DistinctRequiresSelectError","FnSelectWithGroupByError","processSelect","processGroupBy","containsAggregate","HavingRequiresGroupByError","distinct","processOrderBy","resultPipeline","compilationResult","LimitOffsetRequireOrderByError","collectCollectionSources","deepEquals","DuplicateAliasInSubqueryError","sourceIncludes","UnsupportedFromTypeError","concatOperator","CollectionInputNotFoundError","ValClass","VIRTUAL_PROP_NAMES","select","PropRef","ConditionalSelect","IncludesSubquery","key","isExpressionLike","result","isCaseWhenConditionTrue"],"mappings":";;;;;;;;;;;;;;;AAkEO,MAAM,0CAA0B,iBAAiB;AACjD,MAAM,6CAA6B,mBAAmB;AACtD,MAAM,yCAAyB,eAAe;AACrD,MAAM,sCAAsB,aAAa;AAgGlC,SAAS,aACd,UACA,QACA,aACA,eACA,WACA,aACA,+BACA,aACA,QAAoB,oBAAI,WACxB,mCAAiC,QAAA,GAEjC,iBACA,uBACmB;AAEnB,QAAM,eACJ,oBAAoB,SAAY,MAAM,IAAI,QAAQ,IAAI;AACxD,MAAI,cAAc;AAChB,WAAO;AAAA,EACT;AAKA,yBAAuB,QAAQ;AAG/B,QAAM,EAAE,gBAAgB,uBAAuBA,UAAAA,cAAc,QAAQ;AAErE,MAAI,QAAQ;AAGZ,eAAa,IAAI,OAAO,QAAQ;AAChC,mBAAiB,OAAO,UAAU,YAAY;AAG9C,QAAM,YAAY,EAAE,GAAG,OAAA;AACvB,mBAAiB,UAAU,SAAS;AAIpC,QAAM,sBAA8C,CAAA;AAKpD,QAAM,iBAAyC,CAAA;AAM/C,QAAM,UAAuC,CAAA;AAG7C,QAAM;AAAA,IACJ,OAAO;AAAA,IACP,cAAc;AAAA,IACd,UAAU;AAAA,IACV,SAAS;AAAA,IACT;AAAA,IACA;AAAA,IACA;AAAA,EAAA,IACE;AAAA,IACF,MAAM;AAAA,IACN;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