@firebase/firestore
Version:
The Cloud Firestore component of the Firebase JS SDK.
1,290 lines (1,235 loc) • 106 kB
TypeScript
/**
* 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-exp';
import { FirebaseAuthInternalName } from '@firebase/auth-interop-types';
import { _FirebaseService } from '@firebase/app-exp';
import { LogLevelString as LogLevel } from '@firebase/logger';
import { Provider } from '@firebase/component';
import { SetOptions as SetOptions_2 } from '@firebase/firestore-types';
/**
* Converts Firestore's internal types to the JavaScript types that we expose
* to the user.
*
* @internal
*/
declare abstract class AbstractUserDataWriter {
convertValue(value: Value, serverTimestampBehavior?: ServerTimestampBehavior): unknown;
private convertObject;
private convertGeoPoint;
private convertArray;
private convertServerTimestamp;
private convertTimestamp;
protected convertDocumentKey(name: string, expectedDatabaseId: DatabaseId): DocumentKey;
protected abstract convertReference(name: string): unknown;
protected abstract convertBytes(bytes: ByteString): 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.
* @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<T>(reference: CollectionReference<T>, data: T): Promise<DocumentReference<T>>;
declare interface ApiClientObjectMap<T> {
[k: string]: T;
}
/**
* 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()`.
*/
enterRestrictedMode(): 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;
}
/**
* 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[];
static comparator<T extends BasePath<T>>(p1: BasePath<T>, p2: BasePath<T>): 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 before: boolean;
constructor(position: Value[], before: boolean);
}
/**
* 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;
}
/**
* @license
* Copyright 2020 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.
*/
/**
* Immutable class that represents a "proto" byte string.
*
* Proto byte strings can either be Base64-encoded strings or Uint8Arrays when
* sent on the wire. This class abstracts away this differentiation by holding
* the proto byte string in a common class that must be converted into a string
* before being sent as a proto.
*/
declare class ByteString {
private readonly binaryString;
static readonly EMPTY_BYTE_STRING: ByteString;
private constructor();
static fromBase64String(base64: string): ByteString;
static fromUint8Array(array: Uint8Array): ByteString;
toBase64(): string;
toUint8Array(): Uint8Array;
approximateByteSize(): number;
compareTo(other: ByteString): number;
isEqual(other: ByteString): boolean;
}
/**
* 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: FirebaseFirestore, path: string, ...pathSegments: string[]): CollectionReference<DocumentData>;
/**
* Gets a `CollectionReference` instance that refers to a subcollection of
* `reference` at the 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(reference: CollectionReference<unknown>, path: string, ...pathSegments: string[]): CollectionReference<DocumentData>;
/**
* Gets a `CollectionReference` instance that refers to a subcollection of
* `reference` at the 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(reference: DocumentReference, path: string, ...pathSegments: string[]): CollectionReference<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: FirebaseFirestore, collectionId: string): Query<DocumentData>;
/**
* A `CollectionReference` object can be used for adding documents, getting
* document references, and querying for documents (using {@link query}).
*/
export declare class CollectionReference<T = DocumentData> extends Query<T> {
readonly _path: ResourcePath;
/** The type of this Firestore reference. */
readonly type = "collection";
/** @hideconstructor */
constructor(firestore: FirebaseFirestore, converter: FirestoreDataConverter<T> | 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> | 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 and your custom type `U`.
*
* @param converter - Converts objects to and from Firestore.
* @returns A `CollectionReference<U>` that uses the provided converter.
*/
withConverter<U>(converter: FirestoreDataConverter<U>): CollectionReference<U>;
/**
* Removes the current converter.
*
* @param converter - `null` removes the current converter.
* @returns A `CollectionReference<DocumentData>` that does not use a
* converter.
*/
withConverter(converter: null): CollectionReference<DocumentData>;
}
declare type CompositeFilterOp = 'OPERATOR_UNSPECIFIED' | 'AND';
/**
* 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 = (user: User) => Promise<void>;
/**
* Provides methods for getting the uid and token for the current user and
* listening for changes.
*/
declare interface CredentialsProvider {
/** 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;
/**
* 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.
*/
setChangeListener(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void;
/** Removes the previously-set change listener. */
removeChangeListener(): void;
}
/** Settings for private credentials */
declare type CredentialsSettings = FirstPartyCredentialsSettings | ProviderCredentialsSettings;
/** Represents the database ID a Firestore client is associated with. */
declare class DatabaseId {
readonly projectId: string;
readonly database: string;
constructor(projectId: string, database?: string);
get isDefaultDatabase(): boolean;
isEqual(other: {}): 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;
}
/**
* 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();
/**
* 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(reference: DocumentReference<unknown>): 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 abosulute 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: FirebaseFirestore, path: string, ...pathSegments: string[]): DocumentReference<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-genrated 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<T>(reference: CollectionReference<T>, path?: string, ...pathSegments: string[]): DocumentReference<T>;
/**
* 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(reference: DocumentReference<unknown>, path: string, ...pathSegments: string[]): DocumentReference<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 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;
toString(): string;
}
/**
* 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;
declare class DocumentKey {
readonly path: ResourcePath;
constructor(path: ResourcePath);
static fromPath(path: string): DocumentKey;
static fromName(name: string): DocumentKey;
/** Returns true if the document is in the specified collectionId. */
hasCollectionId(collectionId: string): boolean;
isEqual(other: DocumentKey | null): boolean;
toString(): string;
static comparator(k1: DocumentKey, k2: DocumentKey): number;
static isDocumentKey(path: ResourcePath): boolean;
/**
* Creates and returns a new document key with the given segments.
*
* @param segments - The segments of the path to the document
* @returns A new instance of DocumentKey
*/
static fromSegments(segments: string[]): DocumentKey;
}
/**
* 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<T = DocumentData> {
/**
* If provided, the `FirestoreDataConverter` associated with this instance.
*/
readonly converter: FirestoreDataConverter<T> | null;
readonly _key: DocumentKey;
/** The type of this Firestore reference. */
readonly type = "document";
/**
* The {@link FirebaseFirestore} the document is in.
* This is useful for performing transactions, for example.
*/
readonly firestore: FirebaseFirestore;
/** @hideconstructor */
constructor(firestore: FirebaseFirestore,
/**
* If provided, the `FirestoreDataConverter` associated with this instance.
*/
converter: FirestoreDataConverter<T> | 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<T>;
/**
* 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 and
* your custom type `U`.
*
* @param converter - Converts objects to and from Firestore.
* @returns A `DocumentReference<U>` that uses the provided converter.
*/
withConverter<U>(converter: FirestoreDataConverter<U>): DocumentReference<U>;
/**
* Removes the current converter.
*
* @param converter - `null` removes the current converter.
* @returns A `DocumentReference<DocumentData>` that does not use a converter.
*/
withConverter(converter: null): DocumentReference<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<T = DocumentData> {
_firestore: FirebaseFirestore;
_userDataWriter: AbstractUserDataWriter;
_key: DocumentKey;
_document: Document_2 | null;
_converter: UntypedFirestoreDataConverter<T> | null;
/** @hideconstructor protected */
constructor(_firestore: FirebaseFirestore, _userDataWriter: AbstractUserDataWriter, _key: DocumentKey, _document: Document_2 | null, _converter: UntypedFirestoreDataConverter<T> | 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<T>;
/**
* Signals whether or not the document at the snapshot's location exists.
*
* @returns true if the document exists.
*/
exists(): this is QueryDocumentSnapshot<T>;
/**
* 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(): T | 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;
}
/**
* Creates a `QueryConstraint` 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 `QueryConstraint` to pass to `query()`
*/
export declare function endAt(snapshot: DocumentSnapshot<unknown>): QueryConstraint;
/**
* Creates a `QueryConstraint` 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 `QueryConstraint` to pass to `query()`
*/
export declare function endAt(...fieldValues: unknown[]): QueryConstraint;
/**
* Creates a `QueryConstraint` 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 `QueryConstraint` to pass to `query()`
*/
export declare function endBefore(snapshot: DocumentSnapshot<unknown>): QueryConstraint;
/**
* Creates a `QueryConstraint` 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 `QueryConstraint` to pass to `query()`
*/
export declare function endBefore(...fieldValues: unknown[]): QueryConstraint;
declare type FieldFilterOp = 'OPERATOR_UNSPECIFIED' | 'LESS_THAN' | 'LESS_THAN_OR_EQUAL' | 'GREATER_THAN' | 'GREATER_THAN_OR_EQUAL' | 'EQUAL' | 'NOT_EQUAL' | 'ARRAY_CONTAINS' | 'IN' | 'ARRAY_CONTAINS_ANY' | 'NOT_IN';
/**
* Provides a set of fields that can be used to partially patch a document.
* FieldMask is used in conjunction with ObjectValue.
* Examples:
* foo - Overwrites foo entirely with the provided value. If foo is not
* present in the companion ObjectValue, the field is deleted.
* foo.bar - Overwrites only the field bar of the object foo.
* If foo is not an object, foo is replaced with an object
* containing foo
*/
declare class FieldMask {
readonly fields: FieldPath_2[];
constructor(fields: FieldPath_2[]);
/**
* Verifies that `fieldPath` is included by at least one field in this field
* mask.
*
* This is an O(n) operation, where `n` is the size of the field mask.
*/
covers(fieldPath: FieldPath_2): boolean;
isEqual(other: FieldMask): boolean;
}
/**
* 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 {
/** Internal representation of a Firestore field path. */
readonly _internalPath: FieldPath_2;
/**
* 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;
}
/** A dot-separated path for navigating sub-objects within a document. */
declare class FieldPath_2 extends BasePath<FieldPath_2> {
protected construct(segments: string[], offset?: number, length?: number): FieldPath_2;
/**
* Returns true if the string could be used as a segment in a field path
* without escaping.
*/
private static isValidIdentifier;
canonicalString(): string;
toString(): string;
/**
* Returns true if this field references the key of a document.
*/
isKeyField(): boolean;
/**
* The field designating the key of a document.
*/
static keyField(): FieldPath_2;
/**
* Parses a field string from the given server-formatted string.
*
* - Splitting the empty string is not allowed (for now at least).
* - Empty segments within the string (e.g. if there are two consecutive
* separators) are not allowed.
*
* TODO(b/37244157): we should make this more strict. Right now, it allows
* non-identifier path components, even if they aren't escaped.
*/
static fromServerFormat(path: string): FieldPath_2;
static emptyPath(): FieldPath_2;
}
/** A field path and the TransformOperation to perform upon it. */
declare class FieldTransform {
readonly field: FieldPath_2;
readonly transform: TransformOperation;
constructor(field: FieldPath_2, transform: TransformOperation);
}
declare type FieldTransformSetToServerValue = 'SERVER_VALUE_UNSPECIFIED' | 'REQUEST_TIME';
/**
* Sentinel values that can be used when writing document fields with `set()`
* or `update()`.
*/
export declare abstract class FieldValue {
_methodName: string;
/**
* @param _methodName - The public API endpoint that returns this class.
* @hideconstructor
*/
constructor(_methodName: string);
/** Compares `FieldValue`s for equality. */
abstract isEqual(other: FieldValue): boolean;
abstract _toFieldTransform(context: ParseContext): FieldTransform | null;
}
declare abstract class Filter {
abstract matches(doc: Document_2): boolean;
}
/**
* The Cloud Firestore service interface.
*
* Do not call this constructor directly. Instead, use {@link getFirestore}.
*/
export declare class FirebaseFirestore implements FirestoreService {
type: 'firestore-lite' | 'firestore';
readonly _databaseId: DatabaseId;
readonly _persistenceKey: string;
_credentials: CredentialsProvider;
private _settings;
private _settingsFrozen;
private _terminateTask?;
_app?: FirebaseApp;
/** @hideconstructor */
constructor(databaseIdOrApp: DatabaseId | FirebaseApp, authProvider: Provider<FirebaseAuthInternalName>);
/**
* The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service
* instance.
*/
get app(): FirebaseApp;
get _initialized(): boolean;
get _terminated(): boolean;
_setSettings(settings: PrivateSettings): void;
_getSettings(): FirestoreSettings;
_freezeSettings(): FirestoreSettings;
_delete(): Promise<void>;
/** Returns a JSON-serializable representation of this Firestore instance. */
toJSON(): object;
/**
* Terminates all components used by this client. Subclasses can override
* this method to clean up their own dependencies, but must also call this
* method.
*
* Only ever called once.
*/
protected _terminate(): Promise<void>;
}
/**
* Converter used by `withConverter()` to transform user objects of type `T`
* into Firestore data.
*
* Using the converter allows you to specify generic type arguments when
* storing and retrieving objects from Firestore.
*
* @example
* ```typescript
* class Post {
* constructor(readonly title: string, readonly author: string) {}
*
* toString(): string {
* return this.title + ', by ' + this.author;
* }
* }
*
* const postConverter = {
* toFirestore(post: Post): firebase.firestore.DocumentData {
* return {title: post.title, author: post.author};
* },
* fromFirestore(snapshot: firebase.firestore.QueryDocumentSnapshot): Post {
* const data = snapshot.data(options)!;
* return new Post(data.title, data.author);
* }
* };
*
* const postSnap = await firebase.firestore()
* .collection('posts')
* .withConverter(postConverter)
* .doc().get();
* const post = postSnap.data();
* if (post !== undefined) {
* post.title; // string
* post.toString(); // Should be defined
* post.someNonExistentProperty; // TS error
* }
* ```
*/
export declare interface FirestoreDataConverter<T> {
/**
* Called by the Firestore SDK to convert a custom model object of type `T`
* into a plain Javascript object (suitable for writing directly to the
* Firestore database). Used with {@link @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#(WriteBatch.set:1)}
* and {@link @firebase/firestore/lite#(Transaction.set:1)}.
*/
toFirestore(modelObject: T): DocumentData;
/**
* Called by the Firestore SDK to convert a custom model object of type `T`
* into a plain Javascript object (suitable for writing directly to the
* Firestore database). Used with {@link @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#(WriteBatch.set:1)}
* and {@link @firebase/firestore/lite#(Transaction.set:1)} with `merge:true` or `mergeFields`.
*/
toFirestore(modelObject: Partial<T>, options: SetOptions): DocumentData;
/**
* Called by the Firestore SDK to convert Firestore data into an object of
* type T. You can access your data by calling: `snapshot.data()`.
*
* @param snapshot - A `QueryDocumentSnapshot` containing your data and
* metadata.
*/
fromFirestore(snapshot: QueryDocumentSnapshot<DocumentData>): T;
}
/** An error returned by a Firestore operation. */
export declare class FirestoreError extends Error {
/**
* The backend error code associated with this error.
*/
readonly code: FirestoreErrorCode;
/**
* A custom error description.
*/
readonly message: string;
/** The custom name for all FirestoreErrors. */
readonly name: string;
/** The stack of the error. */
readonly stack?: string;
/** @hideconstructor */
constructor(
/**
* The backend error code associated with this error.
*/
code: FirestoreErrorCode,
/**
* A custom error description.
*/
message: string);
}
/**
* @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.
*/
/**
* 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';
/**
* An interface implemented by FirebaseFirestore that provides compatibility
* with the usage in this file.
*
* This interface mainly exists to remove a cyclic dependency.
*/
declare interface FirestoreService extends _FirebaseService {
_credentials: CredentialsProvider;
_persistenceKey: string;
_databaseId: DatabaseId;
_terminated: boolean;
_freezeSettings(): FirestoreSettings;
}
/**
* A concrete type describing all the values that can be applied via a
* user-supplied firestore.Settings object. This is a separate type so that
* defaults can be supplied and the value can be checked for equality.
*/
declare class FirestoreSettings {
/** The hostname to connect to. */
readonly host: string;
/** Whether to use SSL when connecting. */
readonly ssl: boolean;
readonly cacheSizeBytes: number;
readonly experimentalForceLongPolling: boolean;
readonly experimentalAutoDetectLongPolling: boolean;
readonly ignoreUndefinedProperties: boolean;
readonly useFetchStreams: boolean;
credentials?: any;
constructor(settings: PrivateSettings);
isEqual(other: FirestoreSettings): boolean;
}
declare namespace firestoreV1ApiClientInterfaces {
interface ArrayValue {
values?: Value[];
}
interface BatchGetDocumentsRequest {
database?: string;
documents?: string[];
mask?: DocumentMask;
transaction?: string;
newTransaction?: TransactionOptions;
readTime?: string;
}
interface BatchGetDocumentsResponse {
found?: Document;
missing?: string;
transaction?: string;
readTime?: string;
}
interface BeginTransactionRequest {
options?: TransactionOptions;
}
interface BeginTransactionResponse {
transaction?: string;
}
interface CollectionSelector {
collectionId?: string;
allDescendants?: boolean;
}
interface CommitRequest {
database?: string;
writes?: Write[];
transaction?: string;
}
interface CommitResponse {
writeResults?: WriteResult[];
commitTime?: string;
}
interface CompositeFilter {
op?: CompositeFilterOp;
filters?: Filter[];
}
interface Cursor {
values?: Value[];
before?: boolean;
}
interface Document {
name?: string;
fields?: ApiClientObjectMap<Value>;
createTime?: Timestamp_2;
updateTime?: Timestamp_2;
}
interface DocumentChange {
document?: Document;
targetIds?: number[];
removedTargetIds?: number[];
}
interface DocumentDelete {
document?: string;
removedTargetIds?: number[];
readTime?: Timestamp_2;
}
interface DocumentMask {
fieldPaths?: string[];
}
interface DocumentRemove {
document?: string;
removedTargetIds?: number[];
readTime?: string;
}
interface DocumentTransform {
document?: string;
fieldTransforms?: FieldTransform[];
}
interface DocumentsTarget {
documents?: string[];
}
interface Empty {
}
interface ExistenceFilter {
targetId?: number;
count?: number;
}
interface FieldFilter {
field?: FieldReference;
op?: FieldFilterOp;
value?: Value;
}
interface FieldReference {
fieldPath?: string;
}
interface FieldTransform {
fieldPath?: string;
setToServerValue?: FieldTransformSetToServerValue;
appendMissingElements?: ArrayValue;
removeAllFromArray?: ArrayValue;
increment?: Value;
}
interface Filter {
compositeFilter?: CompositeFilter;
fieldFilter?: FieldFilter;
unaryFilter?: UnaryFilter;
}
interface Index {
name?: string;
collectionId?: string;
fields?: IndexField[];
state?: IndexState;
}
interface IndexField {
fieldPath?: string;
mode?: IndexFieldMode;
}
interface LatLng {
latitude?: number;
longitude?: number;
}
interface ListCollectionIdsRequest {
pageSize?: number;
pageToken?: string;
}
interface ListCollectionIdsResponse {
collectionIds?: string[];
nextPageToken?: string;
}
interface ListDocumentsResponse {
documents?: Document[];
nextPageToken?: string;
}
interface ListIndexesResponse {
indexes?: Index[];
nextPageToken?: string;
}
interface ListenRequest {
addTarget?: Target;
removeTarget?: number;
labels?: ApiClientObjectMap<string>;
}
interface ListenResponse {
targetChange?: TargetChange;
documentChange?: DocumentChange;
documentDelete?: DocumentDelete;
documentRemove?: DocumentRemove;
filter?: ExistenceFilter;
}
interface MapValue {
fields?: ApiClientObjectMap<Value>;
}
interface Operation {
name?: string;
metadata?: ApiClientObjectMap<any>;
done?: boolean;
error?: Status;
response?: ApiClientObjectMap<any>;
}
interface Order {
field?: FieldReference;
direction?: OrderDirection;
}
interface Precondition {
exists?: boolean;
updateTime?: Timestamp_2;
}
interface Projection {
fields?: FieldReference[];
}
interface QueryTarget {
parent?: string;
structuredQuery?: StructuredQuery;
}
interface ReadOnly {