UNPKG

@firebase/firestore

Version:

The Cloud Firestore component of the Firebase JS SDK.

1,078 lines (1,077 loc) 139 kB
/** * Cloud Firestore * * @packageDocumentation */ import { FirebaseApp } from '@firebase/app'; import { LogLevelString as LogLevel } from '@firebase/logger'; import { EmulatorMockTokenOptions } from '@firebase/util'; import { FirebaseError } from '@firebase/util'; /** * Add a new document to specified `CollectionReference` with the given data, * assigning it a document ID automatically. * * @param reference - A reference to the collection to add this document to. * @param data - An Object containing the data for the new document. * @returns A `Promise` resolved with a `DocumentReference` pointing to the * newly created document after it has been written to the backend (Note that it * won't resolve while you're offline). */ export declare function addDoc<AppModelType, DbModelType extends DocumentData>(reference: CollectionReference<AppModelType, DbModelType>, data: WithFieldValue<AppModelType>): Promise<DocumentReference<AppModelType, DbModelType>>; /** * Returns a new map where every key is prefixed with the outer key appended * to a dot. */ export declare type AddPrefixToKeys<Prefix extends string, T extends Record<string, unknown>> = { [K in keyof T & string as `${Prefix}.${K}`]+?: string extends K ? any : T[K]; }; /** * Represents an aggregation that can be performed by Firestore. */ export declare class AggregateField<T> { /** A type string to uniquely identify instances of this class. */ readonly type = "AggregateField"; /** Indicates the aggregation operation of this AggregateField. */ readonly aggregateType: AggregateType; } /** * Compares two 'AggregateField` instances for equality. * * @param left Compare this AggregateField to the `right`. * @param right Compare this AggregateField to the `left`. */ export declare function aggregateFieldEqual(left: AggregateField<unknown>, right: AggregateField<unknown>): boolean; /** * The union of all `AggregateField` types that are supported by Firestore. */ export declare type AggregateFieldType = ReturnType<typeof sum> | ReturnType<typeof average> | ReturnType<typeof count>; /** * The results of executing an aggregation query. */ export declare class AggregateQuerySnapshot<AggregateSpecType extends AggregateSpec, AppModelType = DocumentData, DbModelType extends DocumentData = DocumentData> { /** A type string to uniquely identify instances of this class. */ readonly type = "AggregateQuerySnapshot"; /** * The underlying query over which the aggregations recorded in this * `AggregateQuerySnapshot` were performed. */ readonly query: Query<AppModelType, DbModelType>; private constructor(); /** * Returns the results of the aggregations performed over the underlying * query. * * The keys of the returned object will be the same as those of the * `AggregateSpec` object specified to the aggregation method, and the values * will be the corresponding aggregation result. * * @returns The results of the aggregations performed over the underlying * query. */ data(): AggregateSpecData<AggregateSpecType>; } /** * Compares two `AggregateQuerySnapshot` instances for equality. * * Two `AggregateQuerySnapshot` instances are considered "equal" if they have * underlying queries that compare equal, and the same data. * * @param left - The first `AggregateQuerySnapshot` to compare. * @param right - The second `AggregateQuerySnapshot` to compare. * * @returns `true` if the objects are "equal", as defined above, or `false` * otherwise. */ export declare function aggregateQuerySnapshotEqual<AggregateSpecType extends AggregateSpec, AppModelType, DbModelType extends DocumentData>(left: AggregateQuerySnapshot<AggregateSpecType, AppModelType, DbModelType>, right: AggregateQuerySnapshot<AggregateSpecType, AppModelType, DbModelType>): boolean; /** * Specifies a set of aggregations and their aliases. */ export declare interface AggregateSpec { [field: string]: AggregateFieldType; } /** * A type whose keys are taken from an `AggregateSpec`, and whose values are the * result of the aggregation performed by the corresponding `AggregateField` * from the input `AggregateSpec`. */ export declare type AggregateSpecData<T extends AggregateSpec> = { [P in keyof T]: T[P] extends AggregateField<infer U> ? U : never; }; /** * Union type representing the aggregate type to be performed. */ export declare type AggregateType = 'count' | 'avg' | 'sum'; /** * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of * the given filter constraints. A conjunction filter includes a document if it * satisfies all of the given filters. * * @param queryConstraints - Optional. The list of * {@link QueryFilterConstraint}s to perform a conjunction for. These must be * created with calls to {@link where}, {@link or}, or {@link and}. * @returns The newly created {@link QueryCompositeFilterConstraint}. */ export declare function and(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; /** * Returns a special value that can be used with {@link (setDoc:1)} or {@link * updateDoc:1} that tells the server to remove the given elements from any * array value that already exists on the server. All instances of each element * specified will be removed from the array. If the field being modified is not * already an array it will be overwritten with an empty array. * * @param elements - The elements to remove from the array. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or * `updateDoc()` */ export declare function arrayRemove(...elements: unknown[]): FieldValue; /** * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array * value that already exists on the server. Each specified element that doesn't * already exist in the array will be added to the end. If the field being * modified is not already an array it will be overwritten with an array * containing exactly the specified elements. * * @param elements - The elements to union into the array. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or * `updateDoc()`. */ export declare function arrayUnion(...elements: unknown[]): FieldValue; /* Excluded from this release type: AuthTokenFactory */ /* Excluded from this release type: _AutoId */ /** * Create an AggregateField object that can be used to compute the average of * a specified field over a range of documents in the result set of a query. * @param field Specifies the field to average across the result set. */ export declare function average(field: string | FieldPath): AggregateField<number | null>; /** * An immutable object representing an array of bytes. */ export declare class Bytes { private constructor(); /** * Creates a new `Bytes` object from the given Base64 string, converting it to * bytes. * * @param base64 - The Base64 string used to create the `Bytes` object. */ static fromBase64String(base64: string): Bytes; /** * Creates a new `Bytes` object from the given Uint8Array. * * @param array - The Uint8Array used to create the `Bytes` object. */ static fromUint8Array(array: Uint8Array): Bytes; /** * Returns the underlying bytes as a Base64-encoded string. * * @returns The Base64-encoded string created from the `Bytes` object. */ toBase64(): string; /** * Returns the underlying bytes in a new `Uint8Array`. * * @returns The Uint8Array created from the `Bytes` object. */ toUint8Array(): Uint8Array; /** * Returns a string representation of the `Bytes` object. * * @returns A string representation of the `Bytes` object. */ toString(): string; /** * Returns true if this `Bytes` object is equal to the provided one. * * @param other - The `Bytes` object to compare against. * @returns true if this `Bytes` object is equal to the provided one. */ isEqual(other: Bytes): boolean; } /* Excluded from this release type: _ByteString */ /** * Constant used to indicate the LRU garbage collection should be disabled. * Set this value as the `cacheSizeBytes` on the settings passed to the * {@link Firestore} instance. */ export declare const CACHE_SIZE_UNLIMITED = -1; /** * Helper for calculating the nested fields for a given type T1. This is needed * to distribute union types such as `undefined | {...}` (happens for optional * props) or `{a: A} | {b: B}`. * * In this use case, `V` is used to distribute the union types of `T[K]` on * `Record`, since `T[K]` is evaluated as an expression and not distributed. * * See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types */ export declare type ChildUpdateFields<K extends string, V> = V extends Record<string, unknown> ? AddPrefixToKeys<K, UpdateData<V>> : never; /** * Clears the persistent storage. This includes pending writes and cached * documents. * * Must be called while the {@link Firestore} instance is not started (after the app is * terminated or when the app is first initialized). On startup, this function * must be called before other functions (other than {@link * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore} * instance is still running, the promise will be rejected with the error code * of `failed-precondition`. * * Note: `clearIndexedDbPersistence()` is primarily intended to help write * reliable tests that use Cloud Firestore. It uses an efficient mechanism for * dropping existing data but does not attempt to securely overwrite or * otherwise make cached data unrecoverable. For applications that are sensitive * to the disclosure of cached data in between user sessions, we strongly * recommend not enabling persistence at all. * * @param firestore - The {@link Firestore} instance to clear persistence for. * @returns A `Promise` that is resolved when the persistent storage is * cleared. Otherwise, the promise is rejected with an error. */ export declare function clearIndexedDbPersistence(firestore: Firestore): Promise<void>; /** * Gets a `CollectionReference` instance that refers to the collection at * the specified absolute path. * * @param firestore - A reference to the root `Firestore` instance. * @param path - A slash-separated path to a collection. * @param pathSegments - Additional path segments to apply relative to the first * argument. * @throws If the final path has an even number of segments and does not point * to a collection. * @returns The `CollectionReference` instance. */ export declare function collection(firestore: Firestore, path: string, ...pathSegments: string[]): CollectionReference<DocumentData, DocumentData>; /** * Gets a `CollectionReference` instance that refers to a subcollection of * `reference` at the specified relative path. * * @param reference - A reference to a collection. * @param path - A slash-separated path to a collection. * @param pathSegments - Additional path segments to apply relative to the first * argument. * @throws If the final path has an even number of segments and does not point * to a collection. * @returns The `CollectionReference` instance. */ export declare function collection<AppModelType, DbModelType extends DocumentData>(reference: CollectionReference<AppModelType, DbModelType>, path: string, ...pathSegments: string[]): CollectionReference<DocumentData, DocumentData>; /** * Gets a `CollectionReference` instance that refers to a subcollection of * `reference` at the specified relative path. * * @param reference - A reference to a Firestore document. * @param path - A slash-separated path to a collection. * @param pathSegments - Additional path segments that will be applied relative * to the first argument. * @throws If the final path has an even number of segments and does not point * to a collection. * @returns The `CollectionReference` instance. */ export declare function collection<AppModelType, DbModelType extends DocumentData>(reference: DocumentReference<AppModelType, DbModelType>, path: string, ...pathSegments: string[]): CollectionReference<DocumentData, DocumentData>; /** * Creates and returns a new `Query` instance that includes all documents in the * database that are contained in a collection or subcollection with the * given `collectionId`. * * @param firestore - A reference to the root `Firestore` instance. * @param collectionId - Identifies the collections to query over. Every * collection or subcollection with this ID as the last segment of its path * will be included. Cannot contain a slash. * @returns The created `Query`. */ export declare function collectionGroup(firestore: Firestore, collectionId: string): Query<DocumentData, DocumentData>; /** * A `CollectionReference` object can be used for adding documents, getting * document references, and querying for documents (using {@link (query:1)}). */ export declare class CollectionReference<AppModelType = DocumentData, DbModelType extends DocumentData = DocumentData> extends Query<AppModelType, DbModelType> { /** The type of this Firestore reference. */ readonly type = "collection"; private constructor(); /** The collection's identifier. */ get id(): string; /** * A string representing the path of the referenced collection (relative * to the root of the database). */ get path(): string; /** * A reference to the containing `DocumentReference` if this is a * subcollection. If this isn't a subcollection, the reference is null. */ get parent(): DocumentReference<DocumentData, DocumentData> | null; /** * Applies a custom data converter to this `CollectionReference`, allowing you * to use your own custom model objects with Firestore. When you call {@link * addDoc} with the returned `CollectionReference` instance, the provided * converter will convert between Firestore data of type `NewDbModelType` and * your custom type `NewAppModelType`. * * @param converter - Converts objects to and from Firestore. * @returns A `CollectionReference` that uses the provided converter. */ withConverter<NewAppModelType, NewDbModelType extends DocumentData = DocumentData>(converter: FirestoreDataConverter<NewAppModelType, NewDbModelType>): CollectionReference<NewAppModelType, NewDbModelType>; /** * Removes the current converter. * * @param converter - `null` removes the current converter. * @returns A `CollectionReference<DocumentData, DocumentData>` that does not * use a converter. */ withConverter(converter: null): CollectionReference<DocumentData, DocumentData>; } /** * Modify this instance to communicate with the Cloud Firestore emulator. * * Note: This must be called before this instance has been used to do any * operations. * * @param firestore - The `Firestore` instance to configure to connect to the * emulator. * @param host - the emulator host (ex: localhost). * @param port - the emulator port (ex: 9000). * @param options.mockUserToken - the mock auth token to use for unit testing * Security Rules. */ export declare function connectFirestoreEmulator(firestore: Firestore, host: string, port: number, options?: { mockUserToken?: EmulatorMockTokenOptions | string; }): void; /** * Create an AggregateField object that can be used to compute the count of * documents in the result set of a query. */ export declare function count(): AggregateField<number>; /** * Removes all persistent cache indexes. * * Please note this function will also deletes indexes generated by * `setIndexConfiguration()`, which is deprecated. */ export declare function deleteAllPersistentCacheIndexes(indexManager: PersistentCacheIndexManager): void; /** * Deletes the document referred to by the specified `DocumentReference`. * * @param reference - A reference to the document to delete. * @returns A Promise resolved once the document has been successfully * deleted from the backend (note that it won't resolve while you're offline). */ export declare function deleteDoc<AppModelType, DbModelType extends DocumentData>(reference: DocumentReference<AppModelType, DbModelType>): Promise<void>; /** * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. */ export declare function deleteField(): FieldValue; /** * Disables network usage for this instance. It can be re-enabled via {@link * enableNetwork}. While the network is disabled, any snapshot listeners, * `getDoc()` or `getDocs()` calls will return results from cache, and any write * operations will be queued until the network is restored. * * @returns A `Promise` that is resolved once the network has been disabled. */ export declare function disableNetwork(firestore: Firestore): Promise<void>; /** * Stops creating persistent cache indexes automatically for local query * execution. The indexes which have been created by calling * `enablePersistentCacheIndexAutoCreation()` still take effect. */ export declare function disablePersistentCacheIndexAutoCreation(indexManager: PersistentCacheIndexManager): void; /** * Gets a `DocumentReference` instance that refers to the document at the * specified absolute path. * * @param firestore - A reference to the root `Firestore` instance. * @param path - A slash-separated path to a document. * @param pathSegments - Additional path segments that will be applied relative * to the first argument. * @throws If the final path has an odd number of segments and does not point to * a document. * @returns The `DocumentReference` instance. */ export declare function doc(firestore: Firestore, path: string, ...pathSegments: string[]): DocumentReference<DocumentData, DocumentData>; /** * Gets a `DocumentReference` instance that refers to a document within * `reference` at the specified relative path. If no path is specified, an * automatically-generated unique ID will be used for the returned * `DocumentReference`. * * @param reference - A reference to a collection. * @param path - A slash-separated path to a document. Has to be omitted to use * auto-generated IDs. * @param pathSegments - Additional path segments that will be applied relative * to the first argument. * @throws If the final path has an odd number of segments and does not point to * a document. * @returns The `DocumentReference` instance. */ export declare function doc<AppModelType, DbModelType extends DocumentData>(reference: CollectionReference<AppModelType, DbModelType>, path?: string, ...pathSegments: string[]): DocumentReference<AppModelType, DbModelType>; /** * Gets a `DocumentReference` instance that refers to a document within * `reference` at the specified relative path. * * @param reference - A reference to a Firestore document. * @param path - A slash-separated path to a document. * @param pathSegments - Additional path segments that will be applied relative * to the first argument. * @throws If the final path has an odd number of segments and does not point to * a document. * @returns The `DocumentReference` instance. */ export declare function doc<AppModelType, DbModelType extends DocumentData>(reference: DocumentReference<AppModelType, DbModelType>, path: string, ...pathSegments: string[]): DocumentReference<DocumentData, DocumentData>; /** * A `DocumentChange` represents a change to the documents matching a query. * It contains the document affected and the type of change that occurred. */ export declare interface DocumentChange<AppModelType = DocumentData, DbModelType extends DocumentData = DocumentData> { /** The type of change ('added', 'modified', or 'removed'). */ readonly type: DocumentChangeType; /** The document affected by this change. */ readonly doc: QueryDocumentSnapshot<AppModelType, DbModelType>; /** * The index of the changed document in the result set immediately prior to * this `DocumentChange` (i.e. supposing that all prior `DocumentChange` objects * have been applied). Is `-1` for 'added' events. */ readonly oldIndex: number; /** * The index of the changed document in the result set immediately after * this `DocumentChange` (i.e. supposing that all prior `DocumentChange` * objects and the current `DocumentChange` object have been applied). * Is -1 for 'removed' events. */ readonly newIndex: number; } /** * The type of a `DocumentChange` may be 'added', 'removed', or 'modified'. */ export declare type DocumentChangeType = 'added' | 'removed' | 'modified'; /** * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to * values. */ export declare interface DocumentData { /** A mapping between a field and its value. */ [field: string]: any; } /** * Returns a special sentinel `FieldPath` to refer to the ID of a document. * It can be used in queries to sort or filter by the document ID. */ export declare function documentId(): FieldPath; /** * A `DocumentReference` refers to a document location in a Firestore database * and can be used to write, read, or listen to the location. The document at * the referenced location may or may not exist. */ export declare class DocumentReference<AppModelType = DocumentData, DbModelType extends DocumentData = DocumentData> { /** * If provided, the `FirestoreDataConverter` associated with this instance. */ readonly converter: FirestoreDataConverter<AppModelType, DbModelType> | null; /** The type of this Firestore reference. */ readonly type = "document"; /** * The {@link Firestore} instance the document is in. * This is useful for performing transactions, for example. */ readonly firestore: Firestore; private constructor(); /** * The document's identifier within its collection. */ get id(): string; /** * A string representing the path of the referenced document (relative * to the root of the database). */ get path(): string; /** * The collection this `DocumentReference` belongs to. */ get parent(): CollectionReference<AppModelType, DbModelType>; /** * Applies a custom data converter to this `DocumentReference`, allowing you * to use your own custom model objects with Firestore. When you call {@link * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference` * instance, the provided converter will convert between Firestore data of * type `NewDbModelType` and your custom type `NewAppModelType`. * * @param converter - Converts objects to and from Firestore. * @returns A `DocumentReference` that uses the provided converter. */ withConverter<NewAppModelType, NewDbModelType extends DocumentData = DocumentData>(converter: FirestoreDataConverter<NewAppModelType, NewDbModelType>): DocumentReference<NewAppModelType, NewDbModelType>; /** * Removes the current converter. * * @param converter - `null` removes the current converter. * @returns A `DocumentReference<DocumentData, DocumentData>` that does not * use a converter. */ withConverter(converter: null): DocumentReference<DocumentData, DocumentData>; } /** * A `DocumentSnapshot` contains data read from a document in your Firestore * database. The data can be extracted with `.data()` or `.get(<field>)` to * get a specific field. * * For a `DocumentSnapshot` that points to a non-existing document, any data * access will return 'undefined'. You can use the `exists()` method to * explicitly verify a document's existence. */ export declare class DocumentSnapshot<AppModelType = DocumentData, DbModelType extends DocumentData = DocumentData> { /** * Metadata about the `DocumentSnapshot`, including information about its * source and local modifications. */ readonly metadata: SnapshotMetadata; protected constructor(); /** * Returns whether or not the data exists. True if the document exists. */ exists(): this is QueryDocumentSnapshot<AppModelType, DbModelType>; /** * Retrieves all fields in the document as an `Object`. Returns `undefined` if * the document doesn't exist. * * By default, `serverTimestamp()` values that have not yet been * set to their final value will be returned as `null`. You can override * this by passing an options object. * * @param options - An options object to configure how data is retrieved from * the snapshot (for example the desired behavior for server timestamps that * have not yet been set to their final value). * @returns An `Object` containing all fields in the document or `undefined` if * the document doesn't exist. */ data(options?: SnapshotOptions): AppModelType | undefined; /** * Retrieves the field specified by `fieldPath`. Returns `undefined` if the * document or field doesn't exist. * * By default, a `serverTimestamp()` that has not yet been set to * its final value will be returned as `null`. You can override this by * passing an options object. * * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific * field. * @param options - An options object to configure how the field is retrieved * from the snapshot (for example the desired behavior for server timestamps * that have not yet been set to their final value). * @returns The data at the specified field location or undefined if no such * field exists in the document. */ get(fieldPath: string | FieldPath, options?: SnapshotOptions): any; /** * Property of the `DocumentSnapshot` that provides the document's ID. */ get id(): string; /** * The `DocumentReference` for the document included in the `DocumentSnapshot`. */ get ref(): DocumentReference<AppModelType, DbModelType>; } /* Excluded from this release type: _EmptyAppCheckTokenProvider */ /* Excluded from this release type: _EmptyAuthCredentialsProvider */ export { EmulatorMockTokenOptions }; /** * Attempts to enable persistent storage, if possible. * * On failure, `enableIndexedDbPersistence()` will reject the promise or * throw an exception. There are several reasons why this can fail, which can be * identified by the `code` on the error. * * * failed-precondition: The app is already open in another browser tab. * * unimplemented: The browser is incompatible with the offline persistence * implementation. * * Note that even after a failure, the {@link Firestore} instance will remain * usable, however offline persistence will be disabled. * * Note: `enableIndexedDbPersistence()` must be called before any other functions * (other than {@link initializeFirestore}, {@link (getFirestore:1)} or * {@link clearIndexedDbPersistence}. * * Persistence cannot be used in a Node.js environment. * * @param firestore - The {@link Firestore} instance to enable persistence for. * @param persistenceSettings - Optional settings object to configure * persistence. * @returns A `Promise` that represents successfully enabling persistent storage. * @deprecated This function will be removed in a future major release. Instead, set * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to * turn on IndexedDb cache. Calling this function when `FirestoreSettings.localCache` * is already specified will throw an exception. */ export declare function enableIndexedDbPersistence(firestore: Firestore, persistenceSettings?: PersistenceSettings): Promise<void>; /** * Attempts to enable multi-tab persistent storage, if possible. If enabled * across all tabs, all operations share access to local persistence, including * shared execution of queries and latency-compensated local document updates * across all connected instances. * * On failure, `enableMultiTabIndexedDbPersistence()` will reject the promise or * throw an exception. There are several reasons why this can fail, which can be * identified by the `code` on the error. * * * failed-precondition: The app is already open in another browser tab and * multi-tab is not enabled. * * unimplemented: The browser is incompatible with the offline persistence * implementation. * * Note that even after a failure, the {@link Firestore} instance will remain * usable, however offline persistence will be disabled. * * @param firestore - The {@link Firestore} instance to enable persistence for. * @returns A `Promise` that represents successfully enabling persistent * storage. * @deprecated This function will be removed in a future major release. Instead, set * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to * turn on indexeddb cache. Calling this function when `FirestoreSettings.localCache` * is already specified will throw an exception. */ export declare function enableMultiTabIndexedDbPersistence(firestore: Firestore): Promise<void>; /** * Re-enables use of the network for this {@link Firestore} instance after a prior * call to {@link disableNetwork}. * * @returns A `Promise` that is resolved once the network has been enabled. */ export declare function enableNetwork(firestore: Firestore): Promise<void>; /** * Enables the SDK to create persistent cache indexes automatically for local * query execution when the SDK believes cache indexes can help improve * performance. * * This feature is disabled by default. */ export declare function enablePersistentCacheIndexAutoCreation(indexManager: PersistentCacheIndexManager): void; /** * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at * the provided document (inclusive). The end position is relative to the order * of the query. The document must contain all of the fields provided in the * orderBy of the query. * * @param snapshot - The snapshot of the document to end at. * @returns A {@link QueryEndAtConstraint} to pass to `query()` */ export declare function endAt<AppModelType, DbModelType extends DocumentData>(snapshot: DocumentSnapshot<AppModelType, DbModelType>): QueryEndAtConstraint; /** * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at * the provided fields relative to the order of the query. The order of the field * values must match the order of the order by clauses of the query. * * @param fieldValues - The field values to end this query at, in order * of the query's order by. * @returns A {@link QueryEndAtConstraint} to pass to `query()` */ export declare function endAt(...fieldValues: unknown[]): QueryEndAtConstraint; /** * Creates a {@link QueryEndAtConstraint} that modifies the result set to end * before the provided document (exclusive). The end position is relative to the * order of the query. The document must contain all of the fields provided in * the orderBy of the query. * * @param snapshot - The snapshot of the document to end before. * @returns A {@link QueryEndAtConstraint} to pass to `query()` */ export declare function endBefore<AppModelType, DbModelType extends DocumentData>(snapshot: DocumentSnapshot<AppModelType, DbModelType>): QueryEndAtConstraint; /** * Creates a {@link QueryEndAtConstraint} that modifies the result set to end * before the provided fields relative to the order of the query. The order of * the field values must match the order of the order by clauses of the query. * * @param fieldValues - The field values to end this query before, in order * of the query's order by. * @returns A {@link QueryEndAtConstraint} to pass to `query()` */ export declare function endBefore(...fieldValues: unknown[]): QueryEndAtConstraint; /* Excluded from this release type: executeWrite */ /** * @license * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Options that configure the SDK’s underlying network transport (WebChannel) * when long-polling is used. * * Note: This interface is "experimental" and is subject to change. * * See `FirestoreSettings.experimentalAutoDetectLongPolling`, * `FirestoreSettings.experimentalForceLongPolling`, and * `FirestoreSettings.experimentalLongPollingOptions`. */ export declare interface ExperimentalLongPollingOptions { /** * The desired maximum timeout interval, in seconds, to complete a * long-polling GET response. Valid values are between 5 and 30, inclusive. * Floating point values are allowed and will be rounded to the nearest * millisecond. * * By default, when long-polling is used the "hanging GET" request sent by * the client times out after 30 seconds. To request a different timeout * from the server, set this setting with the desired timeout. * * Changing the default timeout may be useful, for example, if the buffering * proxy that necessitated enabling long-polling in the first place has a * shorter timeout for hanging GET requests, in which case setting the * long-polling timeout to a shorter value, such as 25 seconds, may fix * prematurely-closed hanging GET requests. * For example, see https://github.com/firebase/firebase-js-sdk/issues/6987. */ timeoutSeconds?: number; } /** * A `FieldPath` refers to a field in a document. The path may consist of a * single field name (referring to a top-level field in the document), or a * list of field names (referring to a nested field in the document). * * Create a `FieldPath` by providing field names. If more than one field * name is provided, the path will point to a nested field in a document. */ export declare class FieldPath { /** * Creates a `FieldPath` from the provided field names. If more than one field * name is provided, the path will point to a nested field in a document. * * @param fieldNames - A list of field names. */ constructor(...fieldNames: string[]); /** * Returns true if this `FieldPath` is equal to the provided one. * * @param other - The `FieldPath` to compare against. * @returns true if this `FieldPath` is equal to the provided one. */ isEqual(other: FieldPath): boolean; } /** * Sentinel values that can be used when writing document fields with `set()` * or `update()`. */ export declare abstract class FieldValue { private constructor(); /** Compares `FieldValue`s for equality. */ abstract isEqual(other: FieldValue): boolean; } /* Excluded from this release type: _FirebaseService */ /** * The Cloud Firestore service interface. * * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. */ export declare class Firestore { /** * Whether it's a {@link Firestore} or Firestore Lite instance. */ type: 'firestore-lite' | 'firestore'; private constructor(); /** * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service * instance. */ get app(): FirebaseApp; /** * Returns a JSON-serializable representation of this `Firestore` instance. */ toJSON(): object; } /** * Converter used by `withConverter()` to transform user objects of type * `AppModelType` into Firestore data of type `DbModelType`. * * Using the converter allows you to specify generic type arguments when * storing and retrieving objects from Firestore. * * In this context, an "AppModel" is a class that is used in an application to * package together related information and functionality. Such a class could, * for example, have properties with complex, nested data types, properties used * for memoization, properties of types not supported by Firestore (such as * `symbol` and `bigint`), and helper functions that perform compound * operations. Such classes are not suitable and/or possible to store into a * Firestore database. Instead, instances of such classes need to be converted * to "plain old JavaScript objects" (POJOs) with exclusively primitive * properties, potentially nested inside other POJOs or arrays of POJOs. In this * context, this type is referred to as the "DbModel" and would be an object * suitable for persisting into Firestore. For convenience, applications can * implement `FirestoreDataConverter` and register the converter with Firestore * objects, such as `DocumentReference` or `Query`, to automatically convert * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel` * to `AppModel` when retrieving from Firestore. * * @example * * Simple Example * * ```typescript * const numberConverter = { * toFirestore(value: WithFieldValue<number>) { * return { value }; * }, * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) { * return snapshot.data(options).value as number; * } * }; * * async function simpleDemo(db: Firestore): Promise<void> { * const documentRef = doc(db, 'values/value123').withConverter(numberConverter); * * // converters are used with `setDoc`, `addDoc`, and `getDoc` * await setDoc(documentRef, 42); * const snapshot1 = await getDoc(documentRef); * assertEqual(snapshot1.data(), 42); * * // converters are not used when writing data with `updateDoc` * await updateDoc(documentRef, { value: 999 }); * const snapshot2 = await getDoc(documentRef); * assertEqual(snapshot2.data(), 999); * } * ``` * * Advanced Example * * ```typescript * // The Post class is a model that is used by our application. * // This class may have properties and methods that are specific * // to our application execution, which do not need to be persisted * // to Firestore. * class Post { * constructor( * readonly title: string, * readonly author: string, * readonly lastUpdatedMillis: number * ) {} * toString(): string { * return `${this.title} by ${this.author}`; * } * } * * // The PostDbModel represents how we want our posts to be stored * // in Firestore. This DbModel has different properties (`ttl`, * // `aut`, and `lut`) from the Post class we use in our application. * interface PostDbModel { * ttl: string; * aut: { firstName: string; lastName: string }; * lut: Timestamp; * } * * // The `PostConverter` implements `FirestoreDataConverter` and specifies * // how the Firestore SDK can convert `Post` objects to `PostDbModel` * // objects and vice versa. * class PostConverter implements FirestoreDataConverter<Post, PostDbModel> { * toFirestore(post: WithFieldValue<Post>): WithFieldValue<PostDbModel> { * return { * ttl: post.title, * aut: this._autFromAuthor(post.author), * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis) * }; * } * * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post { * const data = snapshot.data(options) as PostDbModel; * const author = `${data.aut.firstName} ${data.aut.lastName}`; * return new Post(data.ttl, author, data.lut.toMillis()); * } * * _autFromAuthor( * author: string | FieldValue * ): { firstName: string; lastName: string } | FieldValue { * if (typeof author !== 'string') { * // `author` is a FieldValue, so just return it. * return author; * } * const [firstName, lastName] = author.split(' '); * return {firstName, lastName}; * } * * _lutFromLastUpdatedMillis( * lastUpdatedMillis: number | FieldValue * ): Timestamp | FieldValue { * if (typeof lastUpdatedMillis !== 'number') { * // `lastUpdatedMillis` must be a FieldValue, so just return it. * return lastUpdatedMillis; * } * return Timestamp.fromMillis(lastUpdatedMillis); * } * } * * async function advancedDemo(db: Firestore): Promise<void> { * // Create a `DocumentReference` with a `FirestoreDataConverter`. * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter()); * * // The `data` argument specified to `setDoc()` is type checked by the * // TypeScript compiler to be compatible with `Post`. Since the `data` * // argument is typed as `WithFieldValue<Post>` rather than just `Post`, * // this allows properties of the `data` argument to also be special * // Firestore values that perform server-side mutations, such as * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`. * await setDoc(documentRef, { * title: 'My Life', * author: 'Foo Bar', * lastUpdatedMillis: serverTimestamp() * }); * * // The TypeScript compiler will fail to compile if the `data` argument to * // `setDoc()` is _not_ compatible with `WithFieldValue<Post>`. This * // type checking prevents the caller from specifying objects with incorrect * // properties or property values. * // @ts-expect-error "Argument of type { ttl: string; } is not assignable * // to parameter of type WithFieldValue<Post>" * await setDoc(documentRef, { ttl: 'The Title' }); * * // When retrieving a document with `getDoc()` the `DocumentSnapshot` * // object's `data()` method returns a `Post`, rather than a generic object, * // which would have been returned if the `DocumentReference` did _not_ have a * // `FirestoreDataConverter` attached to it. * const snapshot1: DocumentSnapshot<Post> = await getDoc(documentRef); * const post1: Post = snapshot1.data()!; * if (post1) { * assertEqual(post1.title, 'My Life'); * assertEqual(post1.author, 'Foo Bar'); * } * * // The `data` argument specified to `updateDoc()` is type checked by the * // TypeScript compiler to be compatible with `PostDbModel`. Note that * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`, * // the `data` argument to `updateDoc()` must be compatible with * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed * // as `WithFieldValue<PostDbModel>` rather than just `PostDbModel`, this * // allows properties of the `data` argument to also be those special * // Firestore values, like `arrayRemove()`, `deleteField()`, and * // `serverTimestamp()`. * await updateDoc(documentRef, { * 'aut.firstName': 'NewFirstName', * lut: serverTimestamp() * }); * * // The TypeScript compiler will fail to compile if the `data` argument to * // `updateDoc()` is _not_ compatible with `WithFieldValue<PostDbModel>`. * // This type checking prevents the caller from specifying objects with * // incorrect properties or property values. * // @ts-expect-error "Argument of type { title: string; } is not assignable * // to parameter of type WithFieldValue<PostDbModel>" * await updateDoc(documentRef, { title: 'New Title' }); * const snapshot2: DocumentSnapshot<Post> = await getDoc(documentRef); * const post2: Post = snapshot2.data()!; * if (post2) { * assertEqual(post2.title, 'My Life'); * assertEqual(post2.author, 'NewFirstName Bar'); * } * } * ``` */ export declare interface FirestoreDataConverter<AppModelType, DbModelType extends DocumentData = DocumentData> { /** * Called by the Firestore SDK to convert a custom model object of type * `AppModelType` into a plain JavaScript object (suitable for writing * directly to the Firestore database) of type `DbModelType`. To use `set()` * with `merge` and `mergeFields`, `toFirestore()` must be defined with * `PartialWithFieldValue<AppModelType>`. * * The `WithFieldValue<T>` type extends `T` to also allow FieldValues such as * {@link (deleteField:1)} to be used as property values. */ toFirestore(modelObject: WithFieldValue<AppModelType>): WithFieldValue<DbModelType>; /** * Called by the Firestore SDK to convert a custom model object of type * `AppModelType` into a plain JavaScript object (suitable for writing * directly to the Firestore database) of type `DbModelType`. Used with * {@link (setDoc:1)}, {@link (WriteBatch.set:1)} and * {@link (Transaction.set:1)} with `merge:true` or `mergeFields`. * * The `PartialWithFieldValue<T>` type extends `Partial<T>` to allow * FieldValues such as {@link (arrayUnion:1)} to be used as property values. * It also supports nested `Partial` by allowing nested fields to be * omitted. */ toFirestore(modelObject: PartialWithFieldValue<AppModelType>, options: SetOptions): PartialWithFieldValue<DbModelType>; /** * Called by the Firestore SDK to convert Firestore data into an object of * type `AppModelType`. You can access your data by calling: * `snapshot.data(options)`. * * Generally, the data returned from `snapshot.data()` can be cast to * `DbModelType`; however, this is not guaranteed because Firestore does not * enforce a schema on the database. For example, writes from a previous * version of the application or writes from another client that did not use a * type converter could have written data with different properties and/or * property types. The implementation will need to choose whether to * gracefully recover from non-conforming data or throw an error. * * To override this method, see {@link (FirestoreDataConverter.fromFirestore:1)}. * * @param snapshot - A `QueryDocumentSnapshot` containing your data and metadata. * @param options - The `SnapshotOptions` from the initial call to `data()`. */ fromFirestore(snapshot: QueryDocumentSnapshot<DocumentData, DocumentData>, options?: SnapshotOptions): AppModelType; } /** An error returned by a Firestore operation. */ export declare class FirestoreError extends FirebaseError { /** * The backend error code associated with this error. */ readonly code: FirestoreErrorCode; /** * A custom error description. */ readonly message: string; /** The stack of the error. */ readonly stack?: string; private constructor(); } /** * The set of Firestore status codes. The codes are the same at the ones * exposed by gRPC here: * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md * * Possible values: * - 'cancelled': The operation was cancelled (typically by the caller). * - 'unknown': Unknown error or an error from a different error domain. * - 'invalid-argument': Client specified an invalid argument. Note that this * differs from 'failed-precondition'. 'invalid-argument' indicates * arguments that are problematic regardless of the state of the system * (e.g. an invalid field name). * - 'deadline-exceeded': Deadline expired before operation could complete. * For operations that change the state of the system, this error may be * returned even if the operation has completed successfully. For example, * a successful response from a server could have been delayed long enough * for the deadline to expire. * - 'not-found': Some requested document was not found. * - 'already-exists': Some document that we attempted to create already * exists. * - 'permission-denied': The caller does not have permission to execute the * specified operation. * - 'resource-exhausted': Some resource has been exhausted, perhaps a * per-user quota, or perhaps the entire file system is out of space. * - 'failed-precondition': Operation was rejected because the system is not * in a state required for the operation's execution. * - 'aborted': The operation was aborted, typically due to a concurrency * issue like transaction aborts, etc. * - 'out-of-range': Operation was attempted past the valid range. * - 'unimplemented': Operation is not implemented or not supported/enabled. * - 'internal': Internal errors. Means some invariants expected by * underlying system has been broken. If you see one of these errors, * something is very broken. * - 'unavailable': The service is currently unavailable. This is most likely * a transient condition and may be corrected by retrying with a backoff. * - 'data-loss': Unrecoverable data loss or corruption. * - 'unauthenticated': The request does not have valid authentication * credentials for the operation. */ export declare type FirestoreErrorCode = 'cancelled' | 'unknown' | 'invalid-argument' | 'deadline-exceeded' | 'not-found' | 'already-exists' | 'permission-denied' | 'resource-exhausted' | 'failed-precondition' | 'aborted' | 'out-of-range' | 'unimplemented' | 'internal' | 'unavailable' | 'data-loss' | 'unauthenticated'; /** * Union type from all supported SDK cache layer. */ export declare type FirestoreLocal