UNPKG

@firebase/firestore

Version:

The Cloud Firestore component of the Firebase JS SDK.

1,216 lines (1,139 loc) • 246 kB
/** * Firestore Lite * * @remarks Firestore Lite is a small online-only SDK that allows read * and write access to your Firestore database. All operations connect * directly to the backend, and `onSnapshot()` APIs are not supported. * @packageDocumentation */ import { DocumentData as DocumentData_2 } from '@firebase/firestore-types'; import { EmulatorMockTokenOptions } from '@firebase/util'; import { FirebaseApp } from '@firebase/app'; import { FirebaseError } from '@firebase/util'; import { LogLevelString as LogLevel } from '@firebase/logger'; import { SetOptions as SetOptions_2 } from '@firebase/firestore-types'; /* Excluded from this release type: AbstractUserDataWriter */ /** * Describes a map whose keys are active target ids. We do not care about the type of the * values. */ declare type ActiveTargets = SortedMap<TargetId, unknown>; /** * Add a new document to specified `CollectionReference` with the given data, * assigning it a document ID automatically. * * The result of this write will only be reflected in document reads that occur * after the returned promise resolves. If the client is offline, the * write fails. If you would like to see local modifications or buffer writes * until the client is online, use the full Firestore SDK. * * @param reference - A reference to the collection to add this document to. * @param data - An Object containing the data for the new document. * @throws Error - If the provided input is not a valid Firestore document. * @returns A `Promise` resolved with a `DocumentReference` pointing to the * newly created document after it has been written to the backend. */ 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> { readonly _internalFieldPath?: FieldPath_2 | undefined; /** A type string to uniquely identify instances of this class. */ readonly type = "AggregateField"; /** Indicates the aggregation operation of this AggregateField. */ readonly aggregateType: AggregateType; /* Excluded from this release type: __constructor */ } /** * 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> { private readonly _userDataWriter; private readonly _data; /** 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>; /** @hideconstructor */ constructor(query: Query<AppModelType, DbModelType>, _userDataWriter: AbstractUserDataWriter, _data: ApiClientObjectMap<Value>); /** * 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; declare interface ApiClientObjectMap<T> { [k: string]: T; } /** * An `AppliableConstraint` is an abstraction of a constraint that can be applied * to a Firestore query. */ declare abstract class AppliableConstraint { /** * Takes the provided {@link Query} and returns a copy of the {@link Query} with this * {@link AppliableConstraint} applied. */ abstract _apply<AppModelType, DbModelType extends DocumentData>(query: Query<AppModelType, DbModelType>): Query<AppModelType, DbModelType>; } /** * 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; declare interface AsyncQueue { readonly isShuttingDown: boolean; /** * Adds a new operation to the queue without waiting for it to complete (i.e. * we ignore the Promise result). */ enqueueAndForget<T extends unknown>(op: () => Promise<T>): void; /** * Regardless if the queue has initialized shutdown, adds a new operation to the * queue without waiting for it to complete (i.e. we ignore the Promise result). */ enqueueAndForgetEvenWhileRestricted<T extends unknown>(op: () => Promise<T>): void; /** * Initialize the shutdown of this queue. Once this method is called, the * only possible way to request running an operation is through * `enqueueEvenWhileRestricted()`. * * @param purgeExistingTasks Whether already enqueued tasked should be * rejected (unless enqueued with `enqueueEvenWhileRestricted()`). Defaults * to false. */ enterRestrictedMode(purgeExistingTasks?: boolean): void; /** * Adds a new operation to the queue. Returns a promise that will be resolved * when the promise returned by the new operation is (with its value). */ enqueue<T extends unknown>(op: () => Promise<T>): Promise<T>; /** * Enqueue a retryable operation. * * A retryable operation is rescheduled with backoff if it fails with a * IndexedDbTransactionError (the error type used by SimpleDb). All * retryable operations are executed in order and only run if all prior * operations were retried successfully. */ enqueueRetryable(op: () => Promise<void>): void; /** * Schedules an operation to be queued on the AsyncQueue once the specified * `delayMs` has elapsed. The returned DelayedOperation can be used to cancel * or fast-forward the operation prior to its running. */ enqueueAfterDelay<T extends unknown>(timerId: TimerId, delayMs: number, op: () => Promise<T>): DelayedOperation<T>; /** * Verifies there's an operation currently in-progress on the AsyncQueue. * Unfortunately we can't verify that the running code is in the promise chain * of that operation, so this isn't a foolproof check, but it should be enough * to catch some bugs. */ verifyOperationInProgress(): void; } /* Excluded from this release type: AuthTokenFactory */ /** * 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>; /** * Path represents an ordered sequence of string segments. */ declare abstract class BasePath<B extends BasePath<B>> { private segments; private offset; private len; constructor(segments: string[], offset?: number, length?: number); /** * Abstract constructor method to construct an instance of B with the given * parameters. */ protected abstract construct(segments: string[], offset?: number, length?: number): B; /** * Returns a String representation. * * Implementing classes are required to provide deterministic implementations as * the String representation is used to obtain canonical Query IDs. */ abstract toString(): string; get length(): number; isEqual(other: B): boolean; child(nameOrPath: string | B): B; /** The index of one past the last segment of the path. */ private limit; popFirst(size?: number): B; popLast(): B; firstSegment(): string; lastSegment(): string; get(index: number): string; isEmpty(): boolean; isPrefixOf(other: this): boolean; isImmediateParentOf(potentialChild: this): boolean; forEach(fn: (segment: string) => void): void; toArray(): string[]; /** * Compare 2 paths segment by segment, prioritizing numeric IDs * (e.g., "__id123__") in numeric ascending order, followed by string * segments in lexicographical order. */ static comparator<T extends BasePath<T>>(p1: BasePath<T>, p2: BasePath<T>): number; private static compareSegments; private static isNumericId; private static extractNumericId; } /** * @license * Copyright 2017 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. */ /** * BatchID is a locally assigned ID for a batch of mutations that have been * applied. */ declare type BatchId = number; /** * Represents a bound of a query. * * The bound is specified with the given components representing a position and * whether it's just before or just after the position (relative to whatever the * query order is). * * The position represents a logical index position for a query. It's a prefix * of values for the (potentially implicit) order by clauses of a query. * * Bound provides a function to determine whether a document comes before or * after a bound. This is influenced by whether the position is just before or * just after the provided values. */ declare class Bound { readonly position: Value[]; readonly inclusive: boolean; constructor(position: Value[], inclusive: boolean); } /** * Provides interfaces to save and read Firestore bundles. */ declare interface BundleCache { /** * Gets the saved `BundleMetadata` for a given `bundleId`, returns undefined * if no bundle metadata is found under the given id. */ getBundleMetadata(transaction: PersistenceTransaction, bundleId: string): PersistencePromise<BundleMetadata | undefined>; /** * Saves a `BundleMetadata` from a bundle into local storage, using its id as * the persistent key. */ saveBundleMetadata(transaction: PersistenceTransaction, metadata: BundleMetadata_2): PersistencePromise<void>; /** * Gets a saved `NamedQuery` for the given query name. Returns undefined if * no queries are found under the given name. */ getNamedQuery(transaction: PersistenceTransaction, queryName: string): PersistencePromise<NamedQuery | undefined>; /** * Saves a `NamedQuery` from a bundle, using its name as the persistent key. */ saveNamedQuery(transaction: PersistenceTransaction, query: NamedQuery_2): PersistencePromise<void>; } /** Properties of a BundledQuery. */ declare interface BundledQuery { /** BundledQuery parent */ parent?: string | null; /** BundledQuery structuredQuery */ structuredQuery?: StructuredQuery | null; /** BundledQuery limitType */ limitType?: LimitType_2 | null; } /** * Represents a Firestore bundle saved by the SDK in its local storage. */ declare interface BundleMetadata { /** * Id of the bundle. It is used together with `createTime` to determine if a * bundle has been loaded by the SDK. */ readonly id: string; /** Schema version of the bundle. */ readonly version: number; /** * Set to the snapshot version of the bundle if created by the Server SDKs. * Otherwise set to SnapshotVersion.MIN. */ readonly createTime: SnapshotVersion; } /** Properties of a BundleMetadata. */ declare interface BundleMetadata_2 { /** BundleMetadata id */ id?: string | null; /** BundleMetadata createTime */ createTime?: Timestamp_2 | null; /** BundleMetadata version */ version?: number | null; /** BundleMetadata totalDocuments */ totalDocuments?: number | null; /** BundleMetadata totalBytes */ totalBytes?: number | null; } /** * An immutable object representing an array of bytes. */ export declare class Bytes { _byteString: ByteString; /** @hideconstructor */ constructor(byteString: ByteString); /** * 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 */ declare const enum ChangeType { Added = 0, Removed = 1, Modified = 2, Metadata = 3 } /** * 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; /** * A randomly-generated key assigned to each Firestore instance at startup. */ declare type ClientId = string; /** * 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> { readonly _path: ResourcePath; /** The type of this Firestore reference. */ readonly type = "collection"; /** @hideconstructor */ constructor(firestore: Firestore, converter: FirestoreDataConverter<AppModelType, DbModelType> | null, _path: ResourcePath); /** 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>; } /** * @license * Copyright 2017 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. */ declare type Comparator<K> = (key1: K, key2: K) => number; declare interface ComponentConfiguration { asyncQueue: AsyncQueue; databaseInfo: DatabaseInfo; authCredentials: CredentialsProvider<User>; appCheckCredentials: CredentialsProvider<string>; clientId: ClientId; initialUser: User; maxConcurrentLimboResolutions: number; } declare type CompositeFilterOp = 'OPERATOR_UNSPECIFIED' | 'AND' | 'OR'; declare const enum CompositeOperator { OR = "or", AND = "and" } /** * 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>; /** * A Listener for credential change events. The listener should fetch a new * token and may need to invalidate other state if the current user has also * changed. */ declare type CredentialChangeListener<T> = (credential: T) => Promise<void>; /** * Provides methods for getting the uid and token for the current user and * listening for changes. */ declare interface CredentialsProvider<T> { /** * Starts the credentials provider and specifies a listener to be notified of * credential changes (sign-in / sign-out, token changes). It is immediately * called once with the initial user. * * The change listener is invoked on the provided AsyncQueue. */ start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener<T>): void; /** Requests a token for the current user. */ getToken(): Promise<Token | null>; /** * Marks the last retrieved token as invalid, making the next GetToken request * force-refresh the token. */ invalidateToken(): void; shutdown(): void; } /** Settings for private credentials */ declare type CredentialsSettings = FirstPartyCredentialsSettings | ProviderCredentialsSettings; /* Excluded from this release type: DatabaseId */ /** * @license * Copyright 2017 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. */ declare class DatabaseInfo { readonly databaseId: DatabaseId; readonly appId: string; readonly persistenceKey: string; readonly host: string; readonly ssl: boolean; readonly forceLongPolling: boolean; readonly autoDetectLongPolling: boolean; readonly longPollingOptions: ExperimentalLongPollingOptions; readonly useFetchStreams: boolean; readonly isUsingEmulator: boolean; /** * Constructs a DatabaseInfo using the provided host, databaseId and * persistenceKey. * * @param databaseId - The database to use. * @param appId - The Firebase App Id. * @param persistenceKey - A unique identifier for this Firestore's local * storage (used in conjunction with the databaseId). * @param host - The Firestore backend host to connect to. * @param ssl - Whether to use SSL when connecting. * @param forceLongPolling - Whether to use the forceLongPolling option * when using WebChannel as the network transport. * @param autoDetectLongPolling - Whether to use the detectBufferingProxy * option when using WebChannel as the network transport. * @param longPollingOptions Options that configure long-polling. * @param useFetchStreams Whether to use the Fetch API instead of * XMLHTTPRequest */ constructor(databaseId: DatabaseId, appId: string, persistenceKey: string, host: string, ssl: boolean, forceLongPolling: boolean, autoDetectLongPolling: boolean, longPollingOptions: ExperimentalLongPollingOptions, useFetchStreams: boolean, isUsingEmulator: boolean); } /** * Datastore and its related methods are a wrapper around the external Google * Cloud Datastore grpc API, which provides an interface that is more convenient * for the rest of the client SDK architecture to consume. */ declare abstract class Datastore { abstract terminate(): void; abstract serializer: JsonProtoSerializer; } /** * Represents an operation scheduled to be run in the future on an AsyncQueue. * * It is created via DelayedOperation.createAndSchedule(). * * Supports cancellation (via cancel()) and early execution (via skipDelay()). * * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type * in newer versions of TypeScript defines `finally`, which is not available in * IE. */ declare class DelayedOperation<T extends unknown> implements PromiseLike<T> { private readonly asyncQueue; readonly timerId: TimerId; readonly targetTimeMs: number; private readonly op; private readonly removalCallback; private timerHandle; private readonly deferred; private constructor(); get promise(): Promise<T>; /** * Creates and returns a DelayedOperation that has been scheduled to be * executed on the provided asyncQueue after the provided delayMs. * * @param asyncQueue - The queue to schedule the operation on. * @param id - A Timer ID identifying the type of operation this is. * @param delayMs - The delay (ms) before the operation should be scheduled. * @param op - The operation to run. * @param removalCallback - A callback to be called synchronously once the * operation is executed or canceled, notifying the AsyncQueue to remove it * from its delayedOperations list. * PORTING NOTE: This exists to prevent making removeDelayedOperation() and * the DelayedOperation class public. */ static createAndSchedule<R extends unknown>(asyncQueue: AsyncQueue, timerId: TimerId, delayMs: number, op: () => Promise<R>, removalCallback: (op: DelayedOperation<R>) => void): DelayedOperation<R>; /** * Starts the timer. This is called immediately after construction by * createAndSchedule(). */ private start; /** * Queues the operation to run immediately (if it hasn't already been run or * canceled). */ skipDelay(): void; /** * Cancels the operation if it hasn't already been executed or canceled. The * promise will be rejected. * * As long as the operation has not yet been run, calling cancel() provides a * guarantee that the operation will not be run. */ cancel(reason?: string): void; then: <TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined) => Promise<TResult1 | TResult2>; private handleDelayElapsed; private clearTimeout; } /** * Deletes the document referred to by the specified `DocumentReference`. * * The deletion will only be reflected in document reads that occur after the * returned promise resolves. If the client is offline, the * delete fails. If you would like to see local modifications or buffer writes * until the client is online, use the full Firestore SDK. * * @param reference - A reference to the document to delete. * @returns A `Promise` resolved once the document has been successfully * deleted from the backend. */ 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; /** * The direction of sorting in an order by. */ declare const enum Direction { ASCENDING = "asc", DESCENDING = "desc" } /** * 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>; /** * Represents a document in Firestore with a key, version, data and whether the * data has local mutations applied to it. */ declare interface Document_2 { /** The key for this document */ readonly key: DocumentKey; /** * The version of this document if it exists or a version at which this * document was guaranteed to not exist. */ readonly version: SnapshotVersion; /** * The timestamp at which this document was read from the remote server. Uses * `SnapshotVersion.min()` for documents created by the user. */ readonly readTime: SnapshotVersion; /** * The timestamp at which the document was created. This value increases * monotonically when a document is deleted then recreated. It can also be * compared to `createTime` of other documents and the `readTime` of a query. */ readonly createTime: SnapshotVersion; /** The underlying data of this document or an empty value if no data exists. */ readonly data: ObjectValue; /** Returns whether local mutations were applied via the mutation queue. */ readonly hasLocalMutations: boolean; /** Returns whether mutations were applied based on a write acknowledgment. */ readonly hasCommittedMutations: boolean; /** * Whether this document had a local mutation applied that has not yet been * acknowledged by Watch. */ readonly hasPendingWrites: boolean; /** * Returns whether this document is valid (i.e. it is an entry in the * RemoteDocumentCache, was created by a mutation or read from the backend). */ isValidDocument(): boolean; /** * Returns whether the document exists and its data is known at the current * version. */ isFoundDocument(): boolean; /** * Returns whether the document is known to not exist at the current version. */ isNoDocument(): boolean; /** * Returns whether the document exists and its data is unknown at the current * version. */ isUnknownDocument(): boolean; isEqual(other: Document_2 | null | undefined): boolean; /** Creates a mutable copy of this document. */ mutableCopy(): MutableDocument; toString(): string; } declare type DocumentComparator = (doc1: Document_2, doc2: Document_2) => number; /** * 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; /* Excluded from this release type: DocumentKey */ declare type DocumentKeyMap<T> = ObjectMap<DocumentKey, T>; declare type DocumentKeySet = SortedSet<DocumentKey>; declare type DocumentMap = SortedMap<DocumentKey, Document_2>; /** * Provides methods to read and write document overlays. * * An overlay is a saved mutation, that gives a local view of a document when * applied to the remote version of the document. * * Each overlay stores the largest batch ID that is included in the overlay, * which allows us to remove the overlay once all batches leading up to it have * been acknowledged. */ declare interface DocumentOverlayCache { /** * Gets the saved overlay mutation for the given document key. * Returns null if there is no overlay for that key. */ getOverlay(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise<Overlay | null>; /** * Gets the saved overlay mutation for the given document keys. Skips keys for * which there are no overlays. */ getOverlays(transaction: PersistenceTransaction, keys: DocumentKey[]): PersistencePromise<OverlayMap>; /** * Saves the given document mutation map to persistence as overlays. * All overlays will have their largest batch id set to `largestBatchId`. */ saveOverlays(transaction: PersistenceTransaction, largestBatchId: number, overlays: MutationMap): PersistencePromise<void>; /** Removes overlays for the given document keys and batch ID. */ removeOverlaysForBatchId(transaction: PersistenceTransaction, documentKeys: DocumentKeySet, batchId: number): PersistencePromise<void>; /** * Returns all saved overlays for the given collection. * * @param transaction - The persistence transaction to use for this operation. * @param collection - The collection path to get the overlays for. * @param sinceBatchId - The minimum batch ID to filter by (exclusive). * Only overlays that contain a change past `sinceBatchId` are returned. * @returns Mapping of each document key in the collection to its overlay. */ getOverlaysForCollection(transaction: PersistenceTransaction, collection: ResourcePath, sinceBatchId: number): PersistencePromise<OverlayMap>; /** * Returns `count` overlays with a batch ID higher than `sinceBatchId` for the * provided collection group, processed by ascending batch ID. The method * always returns all overlays for a batch even if the last batch contains * more documents than the remaining limit. * * @param transaction - The persistence transaction used for this operation. * @param collectionGroup - The collection group to get the overlays for. * @param sinceBatchId - The minimum batch ID to filter by (exclusive). * Only overlays that contain a change past `sinceBatchId` are returned. * @param count - The number of overlays to return. Can be exceeded if the last * batch contains more entries. * @return Mapping of each document key in the collection group to its overlay. */ getOverlaysForCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, sinceBatchId: number, count: number): PersistencePromise<OverlayMap>; } /** * 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; readonly _key: DocumentKey; /** 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; /** @hideconstructor */ constructor(firestore: Firestore, /** * If provided, the `FirestoreDataConverter` associated with this instance. */ converter: FirestoreDataConverter<AppModelType, DbModelType> | null, _key: DocumentKey); get _path(): ResourcePath; /** * 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>; } /** * DocumentSet is an immutable (copy-on-write) collection that holds documents * in order specified by the provided comparator. We always add a document key * comparator on top of what is provided to guarantee document equality based on * the key. */ declare class DocumentSet { /** * Returns an empty copy of the existing DocumentSet, using the same * comparator. */ static emptySet(oldSet: DocumentSet): DocumentSet; private comparator; private keyedMap; private sortedSet; /** The default ordering is by key if the comparator is omitted */ constructor(comp?: DocumentComparator); has(key: DocumentKey): boolean; get(key: DocumentKey): Document_2 | null; first(): Document_2 | null; last(): Document_2 | null; isEmpty(): boolean; /** * Returns the index of the provided key in the document set, or -1 if the * document key is not present in the set; */ indexOf(key: DocumentKey): number; get size(): number; /** Iterates documents in order defined by "comparator" */ forEach(cb: (doc: Document_2) => void): void; /** Inserts or updates a document with the same key */ add(doc: Document_2): DocumentSet; /** Deletes a document with a given key */ delete(key: DocumentKey): DocumentSet; isEqual(other: DocumentSet | null | undefined): boolean; toString(): string; private copy; } /** * 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> { _firestore: Firestore; _userDataWriter: AbstractUserDataWriter; _key: DocumentKey; _document: Document_2 | null; _converter: UntypedFirestoreDataConverter<AppModelType, DbModelType> | null; /** @hideconstructor protected */ constructor(_firestore: Firestore, _userDataWriter: AbstractUserDataWriter, _key: DocumentKey, _document: Document_2 | null, _converter: UntypedFirestoreDataConverter<AppModelType, DbModelType> | null); /** 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>; /** * Signals whether or not the document at the snapshot's location exists. * * @returns 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. * * @returns An `Object` containing all fields in the document or `undefined` * if the document doesn't exist. */ data(): AppModelType | undefined; /** * Retrieves the field specified by `fieldPath`. Returns `undefined` if the * document or field doesn't exist. * * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific * field. * @returns The data at the specified field location or undefined if no such * field exists in the document. */ get(fieldPath: string | FieldPath): any; } declare type DocumentVersionMap = SortedMap<DocumentKey, SnapshotVersion>; declare interface DocumentViewChange { type: ChangeType; doc: Document_2; } export { EmulatorMockTokenOptions } /** * 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; declare interface Entry<K, V> { key: K; value: V; } /** * EventManager is responsible for mapping queries to query event emitters. * It handles "fan-out". -- Identical queries will re-use the same watch on the * backend. * * PORTING NOTE: On Web, EventManager `onListen` and `onUnlisten` need to be * assigned to SyncEngine's `listen()` and `unlisten()` API before usage. This * allows users to tree-shake the Watch logic. */ declare interface EventManager { onListen?: (query: Query_2, enableRemoteListen: boolean) => Promise<ViewSnaps