import { ID, type HookDataFor, type StagingTarget, type WriteGroup } from './FirestoreRepository.js'; import type { HookEvent, HookExecution } from './Hooks.js'; import { FirestoreDocument } from './DocumentId.js'; import { UpdateInput } from './Validation.js'; import { type DetailedQuerySnapshot, type WithMetadata } from './SnapshotMetadata.js'; import { DeepPartial, FieldPaths, NumericFieldPaths, OmitId, KeysOf, ValueAtKey } from '../utils/pathTypes.js'; import { CollectionReference, DocumentReference, DocumentSnapshot, FieldPath, Filter, Firestore, Query, QueryDocumentSnapshot, WhereFilterOp } from 'firebase-admin/firestore'; type FirestoreWriteBatch = (groups: WriteGroup[], operation: string) => Promise; /** * Event-correlated bound signature matching {@link FirestoreRepository}'s dispatcher (review N1). * Payload type comes from {@link HookDataFor} so a wrong shape at a query emit site fails to compile * the same way a wrong repository emit payload does. */ type RunHook = (event: E, data: HookDataFor, execution?: HookExecution) => Promise; type ValidateUpdate = (data: UpdateInput) => UpdateInput; /** * Bound repository guard refusing a query write terminal while a **read-capable** write interceptor * is registered: a transaction cannot be chunked, so these paths have no boundary to host one. * * Called as the first statement of `update()` / `delete()`, ahead of the query read and the * `beforeBulk*` hooks, so a refused call performs no I/O and fires no hooks. This is the *only* place * these paths refuse — `commitInChunks` no longer carries that check. */ type AssertBatchWritesAllowed = (operation: string) => void; /** * Bound repository collector for the write-interceptor writes that must land in the same batch as * each query-terminal domain write (ADR-0040). * * Narrower than the repository's own `InterceptedWrite` union by design: a query write terminal is * only ever an update or a delete, never a create, so this signature never needs the repository's * `WO` (create-output) parameter. Contravariance makes the repository's wider method assignable. * * The query terminals are **batch-only** — {@link AssertBatchWritesAllowed} has already refused a * read-capable interceptor by the time this runs — so there is no read phase to thread through and no * `reads` argument. */ type CollectInterceptorWrites = (write: { readonly kind: 'update'; readonly id: ID; readonly data: UpdateInput; } | { readonly kind: 'delete'; readonly id: ID; readonly document: FirestoreDocument; }) => ((target: StagingTarget) => void)[]; export type PaginatedResult = { items: FirestoreDocument[]; nextCursor: string | null; hasMore: boolean; }; /** * Options for {@link FirestoreQueryBuilderBase.explain}, derived from the Admin SDK * `Query.explain` signature. firebase-admin's public allowlist does not re-export `ExplainOptions` * by name (ADR-0031 / D9) — importing that name from `firebase-admin/firestore` fails TS2305. */ type ExplainOptions = NonNullable[0]>; /** * Metrics object returned by Admin SDK Query Explain, derived from `Query.explain`'s return type. * Not re-exported as a public name — consumers use {@link QueryExplainResult}. */ type ExplainMetrics = Awaited>['metrics']; /** * Result of {@link FirestoreQueryBuilderBase.explain}. * * `metrics` is the Admin SDK explain-metrics object (plan summary, and execution stats when the * query was analyzed). `documents` is the ORM-mapped page of results when `analyze: true`, or * `null` when the query was plan-only (`analyze` false/omitted) and the SDK returned no snapshot. * * An analyzed query that matches nothing yields `documents: []` — not `null`. Do not collapse the * two; callers use `null` vs `[]` to distinguish “did not execute” from “executed, empty.” */ export type QueryExplainResult = { readonly metrics: ExplainMetrics; readonly documents: R[] | null; }; /** * One chunk from {@link FirestoreQueryBuilderBase.explainStream}. * * Document chunks are builder-mapped `R` (collection `{…data, id}` or group * `{…data, id, path, parentPath}`). Terminal diagnostics chunks carry Admin SDK `metrics`. * Fields are optional because the SDK emits document and metrics chunks separately — a chunk may * have only `document`, only `metrics`, or (in theory) both. Do not assume both are always present. */ export type QueryExplainStreamResult = { readonly document?: R; readonly metrics?: ExplainMetrics; }; /** * One entry in an {@link AggregationSpec}. `count` takes no field; `sum` and `average` take a * numeric stored field path (top-level, nested/dotted, or a `FieldPath`). * * `field?: never` on the count variant is load-bearing: excess-property checking against a union * admits any property present in ANY member, so without it `{ kind: 'count', field: 'total' }` * type-checks and the stray field is silently dropped. */ export type CountAggregation = { kind: 'count'; field?: never; }; export type SumAggregation = { kind: 'sum'; field: NumericFieldPaths | FieldPath; }; export type AverageAggregation = { kind: 'average'; field: NumericFieldPaths | FieldPath; }; export type AggregationSpecEntry = CountAggregation | SumAggregation | AverageAggregation; /** A caller-supplied multi-aggregation spec: result alias -> aggregation descriptor. */ export type AggregationSpec = Record>; /** * The result of {@link FirestoreQueryBuilderBase.aggregate} — the spec's own aliases, each carrying * the type its aggregation produces: `count`/`sum` -> `number`, `average` -> `number | null` * (ADR-0020 null fidelity). * * The three branches are deliberate. A literal spec narrows precisely; a spec whose entries are only * known as the union (one built from runtime configuration) matches neither of the first two * branches and falls through to the SAFE `number | null`, rather than falsely promising `number` for * an average it might contain. */ export type AggregationResult> = { [K in keyof Spec]: Spec[K] extends { kind: 'average'; } ? number | null : Spec[K] extends { kind: 'count' | 'sum'; } ? number : number | null; }; /** * The source-agnostic half of the composite-filter factories: field conditions and the `and`/`or` * groups, shared by {@link QueryFilterFactory} (single collection) and `CollectionGroupFilterFactory` * (collection group). The two differ only in their document-name helper, because a collection * matches on the leaf id and a collection group matches on the full document path. * * Not re-exported from the package root — consumers name the concrete factory their builder hands * them. * * @template S - the repository's **stored** data shape (without the synthetic `id`). Declared * **invariant** (`in out`) deliberately. `S` appears only inside the deferred conditional type * `FieldPaths`, and TypeScript cannot measure variance through that, so with no annotation it * falls back to accepting BOTH directions: a predicate annotated with an unrelated repository's * shape — or one that kept `id` in the shape and could then query the synthetic `id` as a stored * field path — was silently accepted, defeating the typo protection this type exists to provide. * (Verified: property syntax is bivariant here too, so this is not the usual method-parameter * bivariance; a control factory parameterized by a plain string union IS measured contravariantly.) * Invariance requires the annotated shape to match the repository's stored shape exactly, so use * `StoredDataOf` (or `OmitId`) rather than the raw model. Do **not** * substitute built-in `Omit`: that spelling flattens an explicit-`id` + string-index * intersection and drops declared siblings from typed paths (issue #82). {@link OmitId} omits * declared `id` from the path-facing key set while reconstructing original index signatures, so * value-position dynamic access survives. Variance annotations require TypeScript 4.7+; the * documented floor is 5.5+ (ADR-0016). */ export interface QueryFilterFactoryBase { /** * A single field condition — the composite-filter counterpart of * {@link FirestoreQueryBuilder.where}. `field` is a typed stored field path (or a `FieldPath`); * `value` stays `unknown` because a `readConverter` can make the stored representation differ from * the read model. */ where(field: FieldPaths | FieldPath, op: WhereFilterOp, value: unknown): Filter; /** Conjunction — every given filter must match. Requires at least one filter. */ and(...filters: Filter[]): Filter; /** Disjunction — at least one given filter must match. Requires at least one filter. */ or(...filters: Filter[]): Filter; } /** Comparison operators for a single document-id operand on `whereId`. */ type WhereIdComparisonOperator = '<' | '<=' | '==' | '!=' | '>=' | '>'; /** Membership operators for a document-id list operand on `whereId`. */ type WhereIdMembershipOperator = 'in' | 'not-in'; /** * Schema-aware factory for composite query filters, handed to the callback of * {@link FirestoreQueryBuilder.whereFilter}. Mirrors the Admin SDK's `Filter` statics, but the field * paths are typed against the repository's **stored** shape (so a typo is a compile error) and * `whereId` runs the same validated document-id boundary as {@link FirestoreQueryBuilder.whereId}. * * The factory is stateless and its methods return plain SDK `Filter` values, so a group can be * extracted into a reusable predicate. Name the shape with `StoredDataOf` — it already * resolves to the repository's stored data without the synthetic `id`: * * @example * const publishedOrMine = * (uid: string) => (f: QueryFilterFactory>) => * f.or(f.where('status', '==', 'published'), f.where('authorId', '==', uid)); * * await postRepo.query().whereFilter(publishedOrMine(uid)).get(); * * @template S - see {@link QueryFilterFactoryBase} for why this is invariant (`in out`). */ export interface QueryFilterFactory extends QueryFilterFactoryBase { /** * A document-name condition via `FieldPath.documentId()` — the composite-filter counterpart of * {@link FirestoreQueryBuilder.whereId}, with the same `InvalidDocumentIdError` boundary and the * same operator restrictions (array-contains operators are intentionally excluded). */ whereId(op: WhereIdComparisonOperator, value: string): Filter; whereId(op: WhereIdMembershipOperator, value: readonly string[]): Filter; } /** * Source-specific wording used by `FirestoreQueryBuilderBase.applyCompositeFilter` diagnostics. A * dropped-whole filter widens a collection query to one collection but a group query to **every** * collection with that id at any depth, so the two messages must not be interchangeable. * * Package-internal by convention — exported because it appears in a protected member's signature * (and so survives `stripInternal` in the emitted `.d.ts`), but not re-exported from the package * root. */ export type CompositeFilterHints = { /** The factory methods to name in the "callback must return a filter" error. */ readonly factoryMethods: string; /** What an empty filter would widen the query to, e.g. `'the collection'`. */ readonly scope: string; }; /** * True only for `FieldPath.documentId()` — the document-NAME sentinel. A string field path is never * the document name (a stored field literally called `id` is ordinary data), so only the `FieldPath` * form can address it. */ export declare function isDocumentIdPath(field: unknown): field is FieldPath; /** * Builds the `where` / `and` / `or` members every filter factory shares, bound to one source's * document-name filter and wording. The concrete factories add their own document-name helper * (`whereId` for a collection, `wherePath` for a collection group). * * Package-internal; not re-exported from the package root. * * @param nameFilter - The source's validated `FieldPath.documentId()` filter builder. * @param scope - What an empty group would widen the query to, for the rejection message. */ export declare function createFilterFactoryCore(nameFilter: (op: WhereFilterOp, value: unknown, references: 'allow' | 'reject') => Filter, scope: string): QueryFilterFactoryBase; /** * @template T - **read data** (no `id`); terminal reads return {@link FirestoreDocument}``. * @template W - **write model** (for `update`). * @template S - **stored data** — the source of query FIELD PATHS (`where` / `orderBy` / `select` / * aggregations). Defaults to `T`. Query operand VALUES stay `unknown` in v3 (typed operands are * deferred — see ADR-0018); document-name queries use `whereId` / `orderById`. * @template R - the current result shape of terminal reads. Defaults to `FirestoreDocument`; * `select(...)` narrows it to `FirestoreDocument>` (nested map properties optional * too) so fields projected away — at any depth — become compile errors when accessed. */ /** * The source-agnostic **read** surface shared by every ORM query builder. * * Everything here works identically whether the underlying `Query` came from a single * `CollectionReference` or from `Firestore.collectionGroup(id)`. The four things that genuinely * differ are abstract: how a result snapshot becomes the result shape ({@link toResult}), what * "belongs to this query's source" means for a pagination cursor * ({@link assertCursorBelongsToSource}), how a `FieldPath.documentId()` operand is validated * ({@link documentNameFilter} — a leaf id for a collection, a full document path for a group), and * the wording hints for composite-filter diagnostics ({@link compositeFilterHints}). * * The split exists so that {@link FirestoreQueryBuilder}'s destructive terminals (`update` / * `delete`) are **absent from the type** of a collection-group builder rather than present and * throwing: their bulk hooks are keyed by `id`, which is not unique across a collection group. * See `FirestoreCollectionGroupQueryBuilder` and ADR-0024. * * Not re-exported from the package root — consumers name the concrete subclasses. * * @template T - **read data** (no `id`). * @template S - **stored data** — the source of query FIELD PATHS. * @template R - the current result shape of terminal reads. */ export declare abstract class FirestoreQueryBuilderBase { protected readonly baseQuery: Query; protected readonly db: Firestore; protected readonly allowLegacyDatastoreIds: boolean; protected query: Query; protected hasOrderBy: boolean; /** * True once `limitToLast()` has been applied more recently than `limit()`. * * The Admin SDK treats `limit` / `limitToLast` as last-wins: a later `limit()` replaces an earlier * `limitToLast()` on the underlying query (and vice versa). This flag tracks that so * `stream()` / `explainStream()` / `paginate()` / `offsetPaginate()` reject only while the builder * is actually in a `limitToLast` state — not after a subsequent `limit()` cleared it. */ protected hasLimitToLast: boolean; /** * True once `offset()` has been applied on this builder. * * Opaque `paginate()` leaves any caller offset on the query (it only adds a cursor + limit), so a * prior `offset(n)` re-applies *after* each page cursor and can silently drop documents while * still reporting `hasMore: true`. `offsetPaginate()` replaces the offset slot with its own page * math while `count()` still observes the caller's offset, desyncing `total` from `items`. Track * the flag so both terminals can reject the combination locally. */ protected hasOffset: boolean; protected hasSelect: boolean; protected constructor(baseQuery: Query, db: Firestore, allowLegacyDatastoreIds: boolean); /** * Maps one result snapshot to this builder's result shape, overlaying repository-owned identity * over the document's own data. The single place every terminal read materializes a row. */ protected abstract toResult(doc: QueryDocumentSnapshot): R; /** * {@link toResult} paired with the snapshot's provenance metadata — the mapper every * `{ withMetadata: true }` terminal uses. Kept beside {@link toResult} so a subclass that * overrides the result shape (e.g. the collection-group builder's `path`/`parentPath` overlay) * gets the metadata variant for free. */ protected toResultWithMetadata(doc: QueryDocumentSnapshot): WithMetadata; /** * Map a page of snapshots to the shape the caller's `withMetadata` flag selected. One place, so a * new terminal cannot forget the branch. */ private mapDocs; /** * Rejects a decoded pagination cursor whose document does not belong to this query's source. * * A forged or foreign opaque `paginate` cursor must never be dereferenced: without this, pagination * could probe arbitrary documents in the same database and disclose their existence. On the * current emulator, a typed `startAfter(foreignSnapshot)` on a **single collection** throws, and * on a **collection group** is accepted using the snap's `orderBy` field values as the cursor * (empty or a suffix depending on those values) — but opaque path tokens still re-fetch by path, * so this membership check remains the forged-cursor gate for `paginate` / `paginateWithCount`. */ protected abstract assertCursorBelongsToSource(docRef: DocumentReference): void; /** * Builds the validated document-NAME (`FieldPath.documentId()`) filter for this source. A * collection compares against the leaf document id; a collection group compares against the full * document path. */ protected abstract documentNameFilter(op: WhereFilterOp, value: unknown, references: 'allow' | 'reject'): Filter; /** Source-specific wording for {@link applyCompositeFilter} diagnostics. */ protected abstract get compositeFilterHints(): CompositeFilterHints; /** * Applies a composite filter produced by a `whereFilter(...)` callback, with the two guards that * cannot be expressed in the type system. Shared by every builder; the public `whereFilter` on * each subclass differs only in which factory it hands the callback. */ protected applyCompositeFilter(filter: unknown): this; /** * Encodes a query document into an opaque cursor string. * The cursor stores the full Firestore document path so pagination * is resilient across collections and subcollections. * * @param doc - The Firestore document snapshot to encode * @returns Base64url-encoded cursor payload */ private encodeCursor; /** * Decodes a cursor into a Firestore document snapshot for startAfter(). * Throws when the encoded document no longer exists to avoid silently * restarting pagination from the beginning. * * @param cursor - Base64url-encoded cursor payload * @returns Document snapshot represented by the cursor */ private decodeCursor; /** * Validates a pagination input is a positive, finite integer, rejecting `0`, negatives, * non-integers, `NaN`, and `Infinity` up front (which would otherwise produce nonsensical offsets * / page counts or fail later in less predictable ways). */ private assertPositiveInt; /** * Validates a non-negative finite integer (including 0). Used by `offset()` and `limitToLast()` * where zero is a legal SDK input (no skip / empty last-page) but negatives and non-integers are * not — those would otherwise surface as opaque gRPC `INVALID_ARGUMENT` failures. */ private assertNonNegativeInt; /** * Rejects a zero-argument cursor bound call before it reaches the Admin SDK. * * The SDK throws for empty args too; we fail locally with a method-specific message so callers * see which bound was misused without reading an opaque SDK stack. */ private assertBoundArgs; /** * Add a where clause to filter documents. * Supports various operators based on field type. * * The `field` is a schema-aware field path (typo-checked), but `value` is intentionally typed as * `unknown` rather than the field's type: a `readConverter` can make the application model (`T`) * differ from the value actually stored in Firestore, so the stored comparison value cannot be * derived from `T` in general. Callers are responsible for passing a value matching the STORED * representation. * * @param field - The field path to filter on (typed) or a `FieldPath` * @param op - The comparison operator * @param value - The value to compare against (matches the stored representation) * * @example * // Basic equality * await userRepo.query() * .where('status', '==', 'active') * .get(); * * @example * // Comparison operators * await productRepo.query() * .where('price', '>', 100) * .where('stock', '>=', 10) * .get(); * * @example * // Array operations * await postRepo.query() * .where('tags', 'array-contains', 'javascript') * .get(); * * @example * // In/Not-in queries * await orderRepo.query() * .where('status', 'in', ['pending', 'processing']) * .get(); * * @returns The query builder instance */ where(field: FieldPaths> | FieldPath, op: WhereFilterOp, value: unknown): this; /** * Order query results by a specific field. * Can be chained for multi-field sorting. * * @param field - The field to sort by * @param direction - Sort direction: 'asc' (default) or 'desc' * * @example * // Sort users by creation date, newest first * const recentUsers = await userRepo.query() * .orderBy('createdAt', 'desc') * .limit(10) * .get(); * * @example * // Multi-field sorting * const products = await productRepo.query() * .orderBy('category', 'asc') * .orderBy('price', 'desc') * .get(); * * @returns The query builder instance */ orderBy(field: FieldPaths> | FieldPath, direction?: 'asc' | 'desc'): this; /** * Limit the number of documents returned. * Useful for pagination and performance optimization. * * When chained after `limitToLast()`, this call **replaces** `limitToLast` (Admin SDK last-wins): * the builder is no longer treated as a `limitToLast` query for `stream()` / `paginate()` guards. * * @param n - Maximum number of documents to return * * @example * // Get top 5 products by price * const topProducts = await productRepo.query() * .orderBy('price', 'desc') * .limit(5) * .get(); * * @example * // First page of results * const firstPage = await userRepo.query() * .orderBy('createdAt', 'desc') * .limit(20) * .get(); * * @returns The query builder instance */ limit(n: number): this; /** * Start the result set at the given cursor position (**inclusive**). * * Overloads match the Admin SDK: pass a `DocumentSnapshot` whose data includes every `orderBy` / * inequality field, **or** pass field values in the same order as the query's `orderBy` clauses. * Field values are typed `unknown` (stored-shape rule — same as `where`). * * A snapshot bound without a prior `orderBy()` is legal in the SDK and implies document-id order; * field-value bounds require `orderBy()`. Prefer an explicit `orderBy` / `orderById` either way. * * Pass a `DocumentReference` only if you intend it as a *field value* (almost never correct for a * field `orderBy` — it can yield an empty result with no throw). Prefer snapshots or scalar values. * * Bound methods forward to the Admin SDK immediately and may throw **raw SDK errors** synchronously * (for example a single-collection foreign `DocumentSnapshot` is rejected at the call site, not * wrapped by `parseFirestoreError` — same voice as `where` / `orderBy`). * * @example * await repo.query().orderBy('score').startAt(20).endAt(40).get(); * await repo.query().orderBy('score').startAt(await db.doc('…').get()).get(); */ startAt(snapshot: DocumentSnapshot): this; startAt(...fieldValues: unknown[]): this; /** * Start after the cursor (**exclusive**). See {@link startAt} for overload and typing rules. */ startAfter(snapshot: DocumentSnapshot): this; startAfter(...fieldValues: unknown[]): this; /** * End at the cursor (**inclusive**). See {@link startAt} for overload and typing rules. */ endAt(snapshot: DocumentSnapshot): this; endAt(...fieldValues: unknown[]): this; /** * End before the cursor (**exclusive**). See {@link startAt} for overload and typing rules. */ endBefore(snapshot: DocumentSnapshot): this; endBefore(...fieldValues: unknown[]): this; /** * Skip the first `n` matching documents. `n` must be a non-negative integer (`0` is allowed). * * Prefer cursor bounds or opaque `paginate()` for large offsets — Firestore still scans skipped * documents, so large offsets are costly. Opaque `paginate()` / `offsetPaginate()` reject a prior * `offset()`: the terminals own the offset/limit slots and composing them silently desyncs pages * or totals. * * @param n - Number of matching documents to skip (including `0`) * @returns The query builder instance * @throws {@link TypeError} when `n` is negative, non-integral, or non-finite */ offset(n: number): this; /** * Return the last `n` documents of the ordered result set (results still in `orderBy` order). * * Requires at least one prior `orderBy()` / `orderById()` / `orderByPath()` (local guard). * Cannot be combined with native `stream()` — call `get()` instead. Real-time `onSnapshot()` * **is** supported. `getOne()` / `exists()` also compose: they skip an internal `.limit(1)` that * would otherwise last-wins overwrite this window. If both `limit` and `limitToLast` are chained, * the **last** call wins (SDK). * * Reverse pagination pattern: `orderBy(...).endAt(cursor).limitToLast(pageSize).get()`. * Do not use opaque `paginate()` for reverse pages — it is forward-only and rejects * `limitToLast`. Opaque `paginate` / `offsetPaginate` also reject a prior `offset()`. * * @param n - Number of trailing documents to return (`0` yields an empty page) * @returns The query builder instance * @throws {@link TypeError} when `n` is negative, non-integral, or non-finite */ limitToLast(n: number): this; /** * Count documents matching the query. * More efficient than fetching all documents when you only need the count. * * @returns Number of documents matching the query * * @example * // Count active users * const activeCount = await userRepo.query() * .where('status', '==', 'active') * .count(); * * @example * // Count orders in date range * const orderCount = await orderRepo.query() * .where('createdAt', '>=', startDate) * .where('createdAt', '<=', endDate) * .count(); */ count(): Promise; /** * Paginate through query results using cursor-based pagination. * More efficient than offset pagination for large datasets. * * Pass `{ withMetadata: true }` as the third argument to receive each row as `{ doc, metadata }` * instead — the same mapped document under `doc`, plus its Firestore provenance. When the third * argument is used, pass `null` (or a cursor) explicitly for the middle parameter. * * @param pageSize - Number of items per page * @param cursor - Opaque cursor string returned by the previous page * @param options - Optional `{ withMetadata }` opt-in * @returns Object with items, next cursor, and hasMore flag * @throws {@link TypeError} when `pageSize` is not a positive finite integer * @throws {@link InvalidPaginationCursorError} when `cursor` is malformed, belongs to another * query source, or points to a deleted document * * @example * // First page * const firstPage = await productRepo.query() * .where('category', '==', 'electronics') * .orderBy('price', 'desc') * .paginate(20); * * @example * // Next page * const nextPage = await productRepo.query() * .where('category', '==', 'electronics') * .orderBy('price', 'desc') * .paginate(20, firstPage.nextCursor); */ paginate(pageSize: number, cursor: string | null | undefined, options: { withMetadata: true; }): Promise<{ items: WithMetadata[]; nextCursor: string | null; hasMore: boolean; }>; paginate(pageSize: number, cursor?: string | null, options?: { withMetadata?: false; }): Promise<{ items: R[]; nextCursor: string | null; hasMore: boolean; }>; /** * Paginate using offset/limit (traditional pagination). * Less efficient than cursor pagination for large datasets. * * @param page - Page number (1-based) * @param pageSize - Number of items per page * @returns Paginated results with metadata * @throws {@link TypeError} when `page` or `pageSize` is not a positive finite integer * * @example * // Get page 2 with 20 items per page * const results = await userRepo.query() * .where('role', '==', 'customer') * .orderBy('createdAt', 'desc') * .offsetPaginate(2, 20); * * console.log(`Page ${results.page} of ${results.totalPages}`); * console.log(`Showing ${results.items.length} of ${results.total} total`); */ offsetPaginate(page: number, pageSize: number, options: { withMetadata: true; }): Promise<{ items: WithMetadata[]; page: number; pageSize: number; total: number; totalPages: number; }>; offsetPaginate(page: number, pageSize: number, options?: { withMetadata?: false; }): Promise<{ items: R[]; page: number; pageSize: number; total: number; totalPages: number; }>; /** * Get a single document matching the query. * Returns null if no documents match. * * @returns The first matching document or null * * @example * // Find user by email * const user = await userRepo.query() * .where('email', '==', 'john@example.com') * .getOne(); * * @example * // Get the cheapest product in category * const cheapest = await productRepo.query() * .where('category', '==', 'books') * .orderBy('price', 'asc') * .getOne(); */ getOne(options: { withMetadata: true; }): Promise | null>; getOne(options?: { withMetadata?: false; }): Promise; /** * Check if any documents match the query. * More efficient than count() when you only need to know if results exist. * * @returns True if at least one document matches * * @example * // Check if email is already taken * const emailExists = await userRepo.query() * .where('email', '==', newEmail) * .exists(); * * @example * // Check if user has any orders * const hasOrders = await orderRepo.query() * .where('userId', '==', userId) * .exists(); */ exists(): Promise; /** * Calculate the sum for a numeric field using Firestore's native aggregation query. * This executes on the Firestore backend and returns only the aggregate result. * * Not combinable with a prior {@link select}: Firestore rejects property masks when aggregation * fields are present. Use an unprojected query, or {@link aggregate} with a count-only spec after * `select()`. * * @param field - The numeric field to sum * @returns The summed value for matching documents * * @example * // Calculate total revenue for completed orders * const totalRevenue = await orderRepo.query() * .where('status', '==', 'completed') * .sum('total'); */ sum(field: NumericFieldPaths> | FieldPath): Promise; /** * Calculate the average for a numeric field using Firestore's native aggregation query. * This executes on the Firestore backend and returns only the aggregate result. * * Not combinable with a prior {@link select}: Firestore rejects property masks when aggregation * fields are present. Use an unprojected query, or {@link aggregate} with a count-only spec after * `select()`. * * @param field - The numeric field to average * @returns The average value for matching documents, or `null` when there are no numeric values * to average (an empty match set). This is distinct from an average that genuinely computes to * `0` — callers must handle `null` explicitly. * * @example * // Calculate average product rating * const avgRating = await reviewRepo.query() * .where('productId', '==', productId) * .average('rating'); // number | null */ average(field: NumericFieldPaths> | FieldPath): Promise; /** * Run multiple aliased aggregations in a **single** Firestore aggregate request — the dashboard * case: count + total + average (or any mix) without three round trips. * * Spec shape is a plain descriptor object (not a callback factory): each key is the result alias, * each value is `{ kind: 'count' }` or `{ kind: 'sum' | 'average', field }`. Field paths keep the * same {@link NumericFieldPaths} typing as {@link sum} / {@link average}. Result aliases map to * `number` for `count`/`sum` and `number | null` for `average` (ADR-0020 null fidelity). A * runtime-built (widened) spec degrades safely to `number | null` per alias. * * **Sparse-field intersection (emulator-observed; production UNVERIFIED):** when the spec * includes a `sum`/`average` over a field that only some matching documents carry, the document * set for the **entire** request collapses to documents that have that field — so a sibling * `count` can return less than `count()` alone. Prefer aggregating required schema fields; when * you need an unconditioned count alongside a sparse-field sum, issue `count()` as a separate * call. See ADR-0027. * * Other semantics: * - Backend max is **5** aggregations per request (not capped locally — the server message is * actionable if Google raises the limit). * - Non-numeric values are skipped by `sum`/`average` but still counted by `count`, so * `average !== sum / count` when non-numerics are present. * - `sum` of int64 values beyond 2^53 loses JavaScript number precision. * - `where` / `orderBy` / `limit` / `limitToLast` / cursors / `offset` all apply; `orderBy(field)` * itself excludes documents missing that field. * - Aggregation queries need the same indexes the underlying query needs. * - `select()` + a count-only spec is legal; `select()` + any `sum`/`average` is rejected locally. * - The alias `'__proto__'` is rejected before any SDK call (SDK alias-map crash). * - Unknown / missing `kind` values are rejected locally (runtime-built specs via `JSON.parse` * are the sanctioned untyped path — silently treating them as `average` would be wrong). * * @param spec - Alias → aggregation descriptor map (at least one entry; max 5 enforced by backend) * @returns An object whose own keys are the spec aliases and whose values match each kind's type * * @example * const stats = await orderRepo * .query() * .where('status', '==', 'completed') * .aggregate({ * orders: { kind: 'count' }, * revenue: { kind: 'sum', field: 'total' }, * avgOrder: { kind: 'average', field: 'total' }, * }); * // stats.orders: number; stats.revenue: number; stats.avgOrder: number | null */ aggregate>>(spec: Spec): Promise>; /** * Local misuse guards for {@link aggregate}: empty spec, `__proto__` alias, unknown kinds, and * `select()` combined with field aggregations. Kept outside the SDK try/catch so they stay * ordinary `Error`s (not `parseFirestoreError`-rewritten), matching paginate()/distinctValues(). */ private assertAggregateSpec; /** * Maps a validated {@link AggregationSpec} onto the Admin SDK AggregateSpec. * * Uses `safeAssign` so caller-controlled alias keys never invoke inherited setters. */ private toSdkAggregateSpec; /** * Rebuilds the aggregation result in the caller's alias order. * * Sum uses `?? 0`; average keeps null so "no values" stays distinct from 0 (ADR-0020). */ private decodeAggregateResult; /** * Local guard shared by {@link sum}, {@link average}, and (kind-aware) {@link aggregate}: * Firestore rejects a field mask combined with any field-referencing aggregation. Count-only * aggregations after select() remain legal and are not routed through this helper. * * @param methodName - Public method name for the error message (`sum()` / `average()`) */ protected assertNoSelectWithFieldAggregation(methodName: string): void; /** * Get all distinct values for a specific field. * Useful for generating filter options or analyzing data distribution. * * **Client-side, with Firestore-aware semantic equality.** This terminal downloads every matching * document and dedupes in process — Firestore Core has no server-side `DISTINCT` (the Enterprise * Pipeline model that does is out of scope; see issue #41). Deduplication is *not* reference * identity: maps and arrays compare structurally and map key order is irrelevant, and `Timestamp`, * `GeoPoint`, `DocumentReference` (by path), `Bytes` and `VectorValue` compare by value. Values a * `readConverter` produced that are not Firestore values — a `Map`, a `Set`, a custom class — fall * back to per-instance identity and are never merged. See {@link distinctFirestoreValues}. * * **Reads the document's own field, never a repository identity overlay** (review M1). Unlike the * terminals that materialize whole rows, this reads `doc.data()[field]` directly, so on a * collection-group query `distinctValues('path')` returns the distinct values of a *stored* field * literally named `path` — not the document paths that `get()` reports as `row.path`. That is * deliberate: it is the only surface that can still read a field the identity overlay shadows, so * restricting the key space would close the sole escape hatch for exactly the data users would be * trying to recover. Identity-named keys are only reachable here when the model declares them, * which `collectionGroup()` rejects for schema-validated repositories. * * @param field - The (top-level) field to get distinct values from * @returns Array of unique values * * @example * // Get all product categories * const categories = await productRepo.query() * .distinctValues('category'); * * @example * // Get all order statuses in use * const statuses = await orderRepo.query() * .where('createdAt', '>', lastMonth) * .distinctValues('status'); */ distinctValues>, string>>(field: K): Promise[]>; /** * Stream query results as an async generator. * Memory efficient for processing large datasets. * * @yields Documents one at a time * * @example * // Process all users without loading into memory * for await (const user of userRepo.query().stream()) { * await sendEmail(user.email); * console.log(`Processed user ${user.id}`); * } * * @example * // Export data to CSV * const csvStream = createWriteStream('users.csv'); * for await (const user of userRepo.query() * .where('subscribed', '==', true) * .stream()) { * csvStream.write(`${user.name},${user.email}\n`); * } */ stream(options: { withMetadata: true; }): AsyncGenerator>; stream(options?: { withMetadata?: false; }): AsyncGenerator; /** * Subscribe to real-time updates for documents matching the query. * Callback is triggered whenever matching documents are added, modified, or removed. * * @param callback - Function called with updated results * @param onError - Optional error handler * @returns Unsubscribe function to stop listening * * @example * // Monitor active orders in real-time * const unsubscribe = await orderRepo.query() * .where('status', '==', 'active') * .onSnapshot( * (orders) => { * console.log(`Active orders: ${orders.length}`); * updateDashboard(orders); * }, * (error) => console.error('Snapshot error:', error) * ); * * // Later: stop listening * unsubscribe(); */ onSnapshot(callback: (items: R[]) => void, onError?: (error: Error) => void): Promise<() => void>; /** * Subscribe to real-time updates **with the incremental change set**, rather than only the full * result array. * * Each emission delivers the complete mapped result set (`docs`) *and* what changed since the * previous one (`changes`) — the Admin SDK's `docChanges()`, mapped through this builder's result * shape and paired with per-document metadata. The first emission reports every matching document * as an `'added'` change with `oldIndex: -1`. * * Use {@link onSnapshot} when you only need the current array; this method exists for consumers * that maintain their own list and want to apply deltas. * * ⚠️ A `'removed'` change carries the document **as it last was** (`doc` and `metadata` are * populated, and the underlying snapshot reports `exists: true`). Branch on `change.type`, never * on the document. `readTime` is the emission's read time — Firestore reports no deletion time. * * Like {@link onSnapshot}, this cannot be combined with `select()`: Firestore does not allow a * real-time listener on a field-masked query. * * @param callback - Function called with each detailed emission * @param onError - Optional error handler * @returns Unsubscribe function to stop listening * * @example * const unsubscribe = await orderRepo.query() * .where('status', '==', 'active') * .onSnapshotDetailed(snapshot => { * for (const change of snapshot.changes) { * if (change.type === 'added') addRow(change.newIndex, change.doc); * else if (change.type === 'removed') removeRow(change.oldIndex); * else moveRow(change.oldIndex, change.newIndex, change.doc); * } * }); * * // Later: stop listening * unsubscribe(); */ onSnapshotDetailed(callback: (snapshot: DetailedQuerySnapshot) => void, onError?: (error: Error) => void): Promise<() => void>; /** * Paginate with total count included. * Combines paginate() and count() in a single method. * * @param pageSize - Number of items per page * @param cursor - Opaque cursor string returned by the previous page * @param options - Optional `{ withMetadata }` opt-in (forwarded to {@link paginate}) * @returns Paginated results with total count * @throws {@link TypeError} when `pageSize` is not a positive finite integer * @throws {@link InvalidPaginationCursorError} under the same cursor conditions as * {@link paginate} * * @example * // Get paginated results with progress info * const { items, nextCursor, hasMore, total } = await productRepo.query() * .where('inStock', '==', true) * .paginateWithCount(20, lastCursor); * * console.log(`Showing ${items.length} of ${total} products`); */ paginateWithCount(pageSize: number, cursor: string | null | undefined, options: { withMetadata: true; }): Promise<{ items: WithMetadata[]; nextCursor: string | null; hasMore: boolean; total: number; }>; paginateWithCount(pageSize: number, cursor?: string | null, options?: { withMetadata?: false; }): Promise<{ items: R[]; nextCursor: string | null; hasMore: boolean; total: number; }>; /** * Execute the query and return all matching documents. * This is the main method to retrieve query results. * * Pass `{ withMetadata: true }` to receive each row as `{ doc, metadata }` instead — the same * mapped document under `doc`, plus its Firestore `ref` / `path` / `parentPath` / `createTime` / * `updateTime` / `readTime`. The default return shape is unchanged. * * @param options - Optional `{ withMetadata }` opt-in * @returns Array of documents matching the query * * @example * // Simple query * const activeUsers = await userRepo.query() * .where('status', '==', 'active') * .get(); * * @example * // Complex query with multiple conditions * const results = await orderRepo.query() * .where('status', '==', 'pending') * .where('total', '>', 100) * .where('createdAt', '>=', startOfDay) * .orderBy('createdAt', 'desc') * .limit(50) * .get(); * * @example * // With snapshot metadata * const rows = await userRepo.query().where('status', '==', 'active').get({ withMetadata: true }); * console.log(rows[0].doc.name, rows[0].metadata.updateTime.toDate()); */ get(options: { withMetadata: true; }): Promise[]>; get(options?: { withMetadata?: false; }): Promise; /** * Plans this query and optionally executes it (Admin SDK Query Explain). * * Pass `{ analyze: true }` to execute the query and receive execution statistics plus the * matching documents mapped through this builder's result shape (`R`). Omit `analyze` (or pass * `false`) for a plan-only request: `documents` is `null` and `metrics.executionStats` is null. * * Returns `{ metrics, documents }` — SDK diagnostics plus ORM-mapped rows — not a raw * `ExplainResults` / `QuerySnapshot`. Use {@link get} when you only need documents. * * Composes with `limitToLast` the same way `get()` does (SDK reverses the page for * `LimitType.Last`); there is no local `hasLimitToLast` reject. * * ⚠️ The Firestore **emulator does not return explain metrics** today; the Admin SDK then throws * `Error: No explain results`. Real plan/execution stats require production Firestore. * * Requires a Firestore SDK that exposes `Query.explain` (`@google-cloud/firestore` >= 7.4). * * @example * const plan = await userRepo.query().where('status', '==', 'active').explain(); * console.log(plan.metrics.planSummary.indexesUsed); * * const analyzed = await userRepo.query().where('status', '==', 'active').explain({ analyze: true }); * // analyzed.documents: User[] (possibly empty); analyzed.metrics.executionStats is non-null */ explain(options?: ExplainOptions): Promise>; /** * Streams Admin SDK Query Explain chunks for this Core query (collection or collection-group). * * Inherited by {@link FirestoreQueryBuilder} and {@link FirestoreCollectionGroupQueryBuilder}. * There is no vector/Aggregate equivalent — `VectorQuery.explainStream` is absent at runtime. * * Pass `{ analyze: true }` to execute the query while streaming: document chunks are mapped * through this builder's result shape (`R`); a terminal chunk may carry `metrics`. Document and * metrics arrive as **separate** chunks (fields are optional on {@link QueryExplainStreamResult}). * * Locally rejects `limitToLast` before opening the native stream (Firestore cannot stream * `LimitType.Last` queries — use {@link explain} instead). Unlike {@link explain}, which * composes with `limitToLast` like `get()`. * * ⚠️ The Firestore **emulator streams document chunks without metrics** today — do not treat an * emulator stream as proof of production diagnostics. Real plan/execution stats need production * Firestore (or unit mocks that supply a metrics chunk). * * Requires a Firestore SDK that exposes `Query.explainStream` (`@google-cloud/firestore` >= 7.4; * firebase-admin 12 only when the resolved `@google-cloud/firestore` is new enough; * firebase-admin >= 13 typically bundles it). * * @example * for await (const chunk of userRepo * .query() * .where('status', '==', 'active') * .explainStream({ analyze: true })) { * if (chunk.document) { * console.log(chunk.document.id, chunk.document.name); * } * if (chunk.metrics) { * console.log(chunk.metrics.planSummary.indexesUsed); * } * } */ explainStream(options?: ExplainOptions): AsyncGenerator>; } /** * Query builder for a single **collection** (or subcollection) — the builder returned by * `FirestoreRepository.query()`. * * Adds the collection-only surface on top of {@link FirestoreQueryBuilderBase}: document-name * queries by leaf id (`whereId` / `orderById`), the whole-collection `collectionCount()`, and the * destructive `update()` / `delete()` terminals with their bulk hooks. * * @template T - **read data** (no `id`); terminal reads return {@link FirestoreDocument}``. * @template W - **write model** (for `update`). * @template S - **stored data** — the source of query FIELD PATHS (`where` / `orderBy` / `select` / * aggregations). Defaults to `T`. Query operand VALUES stay `unknown` in v3 (typed operands are * deferred — see ADR-0018); document-name queries use `whereId` / `orderById`. * @template R - the current result shape of terminal reads. Defaults to `FirestoreDocument`; * `select(...)` narrows it to `FirestoreDocument>` (nested map properties optional * too) so fields projected away — at any depth — become compile errors when accessed. */ export declare class FirestoreQueryBuilder> extends FirestoreQueryBuilderBase { private readonly collectionRef; private readonly commitInChunks; private readonly runHooks; private readonly validateUpdate?; private readonly collectInterceptorWrites?; private readonly assertBatchWritesAllowed?; constructor(baseQuery: Query, collectionRef: CollectionReference, db: Firestore, commitInChunks: FirestoreWriteBatch, runHooks: RunHook, validateUpdate?: ValidateUpdate | undefined, allowLegacyDatastoreIds?: boolean, collectInterceptorWrites?: CollectInterceptorWrites | undefined, assertBatchWritesAllowed?: AssertBatchWritesAllowed | undefined); /** A collection read result is the document data plus the authoritative leaf document id. */ protected toResult(doc: QueryDocumentSnapshot): R; /** * Binds a cursor to THIS collection: a forged/foreign cursor pointing at a document in another * collection must not be dereferenced. */ protected assertCursorBelongsToSource(docRef: DocumentReference): void; /** In a single collection, the document name is the leaf id. */ protected documentNameFilter(op: WhereFilterOp, value: unknown, references: 'allow' | 'reject'): Filter; protected get compositeFilterHints(): CompositeFilterHints; /** * Removes top-level undefined keys from update payloads. * This keeps update behavior consistent with repository update semantics. */ private sanitizeUpdateData; /** * Rejects an empty update payload, matching the repository update surfaces so every update path * shares one policy. */ private assertNonEmptyUpdatePayload; /** * Add a **composite** filter — nested `AND` / `OR` boolean expressions, which chained `where()` * calls (an implicit top-level AND) cannot express. * * The callback receives a schema-aware {@link QueryFilterFactory}: `f.where(...)` takes the same * typed stored field paths as {@link where} at every nesting depth, and `f.whereId(...)` applies * the same validated document-id boundary as {@link whereId}. A prebuilt Admin SDK `Filter` may be * returned directly (`f => myFilter`) as an escape hatch — it is applied verbatim, without the * typed-path or id validation the factory provides. * * Composes with everything else on the builder: a `whereFilter()` is AND-ed with any chained * `where()` clauses, and works with `orderBy`/`limit`, `select`, the aggregations, pagination, * `stream()`, `onSnapshot()`, the `update()`/`delete()` terminals, and vector prefilters. * * ⚠️ **An inequality inside an `or()` branch drops documents that are MISSING that field — even * documents matched by a DIFFERENT branch.** Firestore adds an implicit `orderBy` for every * inequality field (`<`, `<=`, `>`, `>=`, `!=`) collected across the *flattened* filter tree, and a * document without an ordered field cannot appear. (`not-in` is an inequality too, but it can never * appear inside an `OR` — Firestore rejects that combination outright.) So an OR query can return * **fewer** rows than one of its own disjuncts, and `count()` agrees — it is not a read-path artifact: * * ``` * where('kind', '==', 'x') → 4 docs * whereFilter(f => f.or(f.where('score', '>', 5), * f.where('kind', '==', 'x'))) → 3 docs ← a `kind: 'x'` doc has no `score` * ``` * * This also affects the destructive `update()` / `delete()` terminals, which would silently skip * those documents. Safe shapes inside `or()`: equality, `in`, and `array-contains` / * `array-contains-any`; and `f.whereId(...)` with a comparison operator, which is exempt because * Firestore skips `documentId()` when adding implicit orders and a document name always exists. * If you need an inequality branch, ensure the field is always written (e.g. a default at create * time), or run the branches as separate queries and merge by `id`. * * Firestore enforces its own limits on the **server** and the ORM does not duplicate them (a local * copy would risk rejecting a query the backend accepts, and the counts multiply across clauses the * callback cannot see). Non-exhaustively: at most 30 disjunctions after normalization (an ANDed pair * of 6-value `in` filters is already 36), `in` accepts at most 30 values, at most one * `array-contains` **per disjunction**, and one `!=` / `not-in` **per query** — which also counts * `!= null` / `!= NaN`. A `not-in` anywhere in the query is incompatible with any `OR`, including a * `not-in` from a chained `where()` outside this callback. All surface as `INVALID_ARGUMENT`. A * composite query may also require a composite index. * * @param build - Callback that composes and returns the filter * * @example * // status == 'published' OR (authorId == me AND visibility == 'private') * const posts = await postRepo.query() * .whereFilter(f => * f.or( * f.where('status', '==', 'published'), * f.and(f.where('authorId', '==', uid), f.where('visibility', '==', 'private')), * ), * ) * .orderBy('createdAt', 'desc') * .get(); * * @example * // Combined with a chained where(): deleted == false AND (a OR b) * await postRepo.query() * .where('deleted', '==', false) * .whereFilter(f => f.or(f.where('pinned', '==', true), f.whereId('in', featuredIds))) * .get(); * * @returns The query builder instance */ whereFilter(build: (f: QueryFilterFactory>) => Filter): this; /** * Select specific fields to reduce bandwidth and improve performance. * Returns partial documents with only the specified fields. * * @param fields - Fields to include in the result * * @example * // Get only name and email for users * const users = await userRepo.query() * .select('name', 'email') * .get(); * * @example * // Combine with where clause * const activeUserEmails = await userRepo.query() * .where('status', '==', 'active') * .select('email') * .get(); * * @returns The query builder instance */ select(...fields: (FieldPaths> | FieldPath)[]): FirestoreQueryBuilder>>; /** * Filter by the native Firestore **document id** (the document name), via `FieldPath.documentId()`. * * This is the correct way to query by id — distinct from `where('id', ...)`, which would query a * *stored* field named `id` (not a valid field path, since `id` is repository metadata). Operands * are validated with the same `InvalidDocumentIdError` boundary as CRUD ids (review A7); only the * document-id-meaningful operators are accepted (comparison for a single id, `in`/`not-in` for an * id array — array-contains operators are intentionally excluded). * * @example * await userRepo.query().whereId('==', 'user-123').getOne(); * await userRepo.query().whereId('in', ['a', 'b', 'c']).get(); */ whereId(op: WhereIdComparisonOperator, value: string): this; whereId(op: WhereIdMembershipOperator, value: readonly string[]): this; /** * Order by the native Firestore **document id** (the document name), via `FieldPath.documentId()` — * the id-aware counterpart to `orderBy(...)`. Useful as a stable tiebreaker for cursor pagination. * * ⚠️ `'desc'` cannot be a query's ONLY ordering: Firestore rejects a bare descending document-name * scan with `FAILED_PRECONDITION: Firestore does not support descending key scans`. Add any * equality `where(...)` clause or a preceding `orderBy(...)` and it works. Ascending is * unrestricted. * * @example * await userRepo.query().orderById().paginate(20); * * @example * // Descending needs a companion clause. * await userRepo.query().where('status', '==', 'active').orderById('desc').get(); */ orderById(direction?: 'asc' | 'desc'): this; /** * Count every document in the collection, ignoring the builder's `where` clauses. * * Named `collectionCount()` (not `totalCount()`) precisely because it counts the whole * collection and disregards any filters chained onto this builder — use {@link QueryBuilder.count} * for a query-aware count that honors the `where`/`orderBy` chain. * * @returns Total number of documents in the collection * * @example * // Get total user count (ignores any where clauses) * const total = await userRepo.query().collectionCount(); */ collectionCount(): Promise; /** * Update all documents matching the query. * Supports dot notation for nested field updates. * * @param data - Partial document data (supports dot notation) * @returns Number of documents updated * * @example * // Regular update * await ordersRepo.query() * .where('status', '==', 'pending') * .update({ status: 'shipped' }); * * @example * // Dot notation for nested fields * await usersRepo.query() * .where('role', '==', 'admin') * .update({ * 'settings.notifications': true, * 'profile.verified': true * }); * * @example * // Mixed updates * await ordersRepo.query() * .where('category', '==', 'electronics') * .update({ * discount: 0.1, * 'metadata.updated': new Date().toISOString() * }); */ update(data: UpdateInput): Promise; /** * Permanently delete all documents matching the query. * This is a hard delete - documents cannot be recovered. * * @returns Number of documents deleted * * @example * // Delete all cancelled orders older than 30 days * const deletedCount = await orderRepo.query() * .where('status', '==', 'cancelled') * .where('createdAt', '<', thirtyDaysAgo) * .delete(); * * @example * // Delete all test users * await userRepo.query() * .where('email', 'array-contains', '@test.com') * .delete(); */ delete(): Promise; } /** * The chainable clause members of {@link FirestoreQueryBuilder} — every member whose declared return * type is `this`, plus `select`, which returns a re-parameterized builder. This is exactly the set * {@link ReadOnlyQuery} must re-declare: an `Omit` keeps the member but leaves its return type * pointing at the full builder, which is the leak ADR-0041 exists to close. * * Do NOT replace this with a conditional type that derives the set from `keyof`. The list is short, * `src/tests/types/read-only-query.type-test.ts` checks it from both sides, and a derived version * reads as clever while catching nothing extra. * * Do NOT mark this helper for stripInternal (the TypeScript JSDoc tag that removes declarations from * `.d.ts` emit — trap T5). `tsconfig` sets `stripInternal: true`; applying that tag here would strip * this declaration and leave a dangling reference in the published `.d.ts`. The packed-consumer check * names `ReadOnlyQuery` and asserts write keys stay absent so that regression fails CI. * * (Avoid writing the stripInternal tag name with a leading "@" anywhere in this block — TypeScript * parses it as the tag and would strip this helper the same way.) */ type ReadOnlyQueryClauseKeys = 'where' | 'whereFilter' | 'whereId' | 'orderBy' | 'orderById' | 'limit' | 'limitToLast' | 'offset' | 'startAt' | 'startAfter' | 'endAt' | 'endBefore' | 'select'; /** * A **read-only view** of {@link FirestoreQueryBuilder}: the entire read surface — filtering, * composite filters, document-name queries, ordering, projection, bounds, aggregation, pagination, * streaming, listeners, explain — with `update()` and `delete()` absent **at every chain depth** * (ADR-0041). * * Hand this out from a facade that owns its own write paths. `repository.query()` is assignable with * **no cast** — annotate the return type and you are done. There is no wrapper object and no runtime * cost; this type erases completely. * * @example * class OrderService { * constructor(private readonly orders: typeof orderRepo) {} * query(): ReadOnlyQuery { * return this.orders.query(); // structural — no cast * } * } * * await svc.query().where('status', '==', 'pending').orderBy('updatedAt').get(); // ✓ * await svc.query().where('status', '==', 'pending').update({ status: 'shipped' }); // ✗ TS2339 * * @remarks * **Why not `Omit, 'update' | 'delete'>`?** TypeScript resolves a `this` * return type against the *declared* type of the receiver. The `Omit` blocks the immediate call and * then hands the full builder back from the first `.where(...)`, so the narrowing survives exactly * one expression. Every clause member below returns `ReadOnlyQuery` instead, so it survives * transitively. Never "simplify" this back to an `Omit`: that reintroduces the leak *silently*, * because the blocked immediate call still looks like proof. * * **Type-level only.** A deliberate cast back to `FirestoreQueryBuilder` still reaches `update()`. * The purpose is compile-time enforcement of an application's own boundary (ADR-0041, decision 5). * * @template T - **read data** (no `id`) — same meaning as on {@link FirestoreQueryBuilder}. * @template W - **write model.** Accepted for positional parity with * {@link FirestoreQueryBuilder}``, so a signature can be copied across without * silently re-binding `S` / `R`. No read member references it, so it does not affect assignability. * @template S - **stored data** — the source of query FIELD PATHS. * @template R - the current result shape of terminal reads; `select(...)` narrows it exactly as on * the concrete builder. */ export interface ReadOnlyQuery> extends Omit, 'update' | 'delete' | ReadOnlyQueryClauseKeys> { where(...a: Parameters['where']>): ReadOnlyQuery; whereFilter(...a: Parameters['whereFilter']>): ReadOnlyQuery; whereId(op: WhereIdComparisonOperator, value: string): ReadOnlyQuery; whereId(op: WhereIdMembershipOperator, value: readonly string[]): ReadOnlyQuery; orderBy(...a: Parameters['orderBy']>): ReadOnlyQuery; orderById(...a: Parameters['orderById']>): ReadOnlyQuery; limit(...a: Parameters['limit']>): ReadOnlyQuery; limitToLast(...a: Parameters['limitToLast']>): ReadOnlyQuery; offset(...a: Parameters['offset']>): ReadOnlyQuery; startAt(...a: Parameters['startAt']>): ReadOnlyQuery; startAfter(...a: Parameters['startAfter']>): ReadOnlyQuery; endAt(...a: Parameters['endAt']>): ReadOnlyQuery; endBefore(...a: Parameters['endBefore']>): ReadOnlyQuery; select(...a: Parameters['select']>): ReadOnlyQuery>>; } /** * Returns the underlying Firestore Query for package-internal composition. * Used by the vector search extension (`flintfire/vector`). */ export declare function getQueryRef(builder: FirestoreQueryBuilder): Query; export {};