@firebase/firestore
Version:
The Cloud Firestore component of the Firebase JS SDK.
1,612 lines (1,493 loc) • 849 kB
TypeScript
/**
* @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.
*/
interface VersionService {
library: string;
version: string;
}
interface PlatformLoggerService {
getPlatformInfoString(): string;
}
interface HeartbeatService {
/**
* Called to report a heartbeat. The function will generate
* a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it
* to IndexedDB.
* Note that we only store one heartbeat per day. So if a heartbeat for today is
* already logged, subsequent calls to this function in the same day will be ignored.
*/
triggerHeartbeat(): Promise<void>;
/**
* Returns a base64 encoded string which can be attached to the heartbeat-specific header directly.
* It also clears all heartbeats from memory as well as in IndexedDB.
*/
getHeartbeatsHeader(): Promise<string>;
}
/**
* @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.
*/
/**
* A {@link @firebase/app#FirebaseApp} holds the initialization information for a collection of
* services.
*
* Do not call this constructor directly. Instead, use
* {@link (initializeApp:1) | initializeApp()} to create an app.
*
* @public
*/
interface FirebaseApp {
/**
* The (read-only) name for this app.
*
* The default app's name is `"[DEFAULT]"`.
*
* @example
* ```javascript
* // The default app's name is "[DEFAULT]"
* const app = initializeApp(defaultAppConfig);
* console.log(app.name); // "[DEFAULT]"
* ```
*
* @example
* ```javascript
* // A named app's name is what you provide to initializeApp()
* const otherApp = initializeApp(otherAppConfig, "other");
* console.log(otherApp.name); // "other"
* ```
*/
readonly name: string;
/**
* The (read-only) configuration options for this app. These are the original
* parameters given in {@link (initializeApp:1) | initializeApp()}.
*
* @example
* ```javascript
* const app = initializeApp(config);
* console.log(app.options.databaseURL === config.databaseURL); // true
* ```
*/
readonly options: FirebaseOptions;
/**
* The settable config flag for GDPR opt-in/opt-out
*/
automaticDataCollectionEnabled: boolean;
}
/**
* @public
*
* Firebase configuration object. Contains a set of parameters required by
* services in order to successfully communicate with Firebase server APIs
* and to associate client data with your Firebase project and
* Firebase application. Typically this object is populated by the Firebase
* console at project setup. See also:
* {@link https://firebase.google.com/docs/web/setup#config-object | Learn about the Firebase config object}.
*/
interface FirebaseOptions {
/**
* An encrypted string used when calling certain APIs that don't need to
* access private user data
* (example value: `AIzaSyDOCAbC123dEf456GhI789jKl012-MnO`).
*/
apiKey?: string;
/**
* Auth domain for the project ID.
*/
authDomain?: string;
/**
* Default Realtime Database URL.
*/
databaseURL?: string;
/**
* The unique identifier for the project across all of Firebase and
* Google Cloud.
*/
projectId?: string;
/**
* The default Cloud Storage bucket name.
*/
storageBucket?: string;
/**
* Unique numerical value used to identify each sender that can send
* Firebase Cloud Messaging messages to client apps.
*/
messagingSenderId?: string;
/**
* Unique identifier for the app.
*/
appId?: string;
/**
* An ID automatically created when you enable Analytics in your
* Firebase project and register a web app. In versions 7.20.0
* and higher, this parameter is optional.
*/
measurementId?: string;
}
/**
* @internal
*/
interface _FirebaseService {
app: FirebaseApp;
/**
* Delete the service and free it's resources - called from
* {@link @firebase/app#deleteApp | deleteApp()}
*/
_delete(): Promise<void>;
}
declare module '@firebase/component' {
interface NameServiceMapping {
'app': FirebaseApp;
'app-version': VersionService;
'heartbeat': HeartbeatService;
'platform-logger': PlatformLoggerService;
}
}
/**
* @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.
*/
type LogLevelString = 'debug' | 'verbose' | 'info' | 'warn' | 'error' | 'silent';
/**
* An object that can be injected into the environment as __FIREBASE_DEFAULTS__,
* either as a property of globalThis, a shell environment variable, or a
* cookie.
*
* This object can be used to automatically configure and initialize
* a Firebase app as well as any emulators.
*
* @public
*/
interface FirebaseDefaults {
config?: Record<string, string>;
emulatorHosts?: Record<string, string>;
_authTokenSyncURL?: string;
_authIdTokenMaxAge?: number;
/**
* Override Firebase's runtime environment detection and
* force the SDK to act as if it were in the specified environment.
*/
forceEnvironment?: 'browser' | 'node';
[key: string]: unknown;
}
declare global {
var __FIREBASE_DEFAULTS__: FirebaseDefaults | undefined;
}
/**
* @license
* Copyright 2021 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.
*/
type FirebaseSignInProvider = 'custom' | 'email' | 'password' | 'phone' | 'anonymous' | 'google.com' | 'facebook.com' | 'github.com' | 'twitter.com' | 'microsoft.com' | 'apple.com';
interface FirebaseIdToken {
iss: string;
aud: string;
sub: string;
iat: number;
exp: number;
user_id: string;
auth_time: number;
provider_id?: 'anonymous';
email?: string;
email_verified?: boolean;
phone_number?: string;
name?: string;
picture?: string;
firebase: {
sign_in_provider: FirebaseSignInProvider;
identities?: {
[provider in FirebaseSignInProvider]?: string[];
};
};
[claim: string]: unknown;
uid?: never;
}
type EmulatorMockTokenOptions = ({
user_id: string;
} | {
sub: string;
}) & Partial<FirebaseIdToken>;
declare class FirebaseError extends Error {
/** The error code for this error. */
readonly code: string;
/** Custom data for this error. */
customData?: Record<string, unknown> | undefined;
/** The custom name for all FirebaseErrors. */
readonly name: string;
constructor(
/** The error code for this error. */
code: string, message: string,
/** Custom data for this error. */
customData?: Record<string, unknown> | undefined);
}
/**
* @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`.
*/
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;
}
/**
* @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;
readonly apiKey: string | undefined;
/**
* 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, apiKey: string | undefined);
}
/**
* Represents the database ID a Firestore client is associated with.
* @internal
*/
declare class DatabaseId {
readonly projectId: string;
readonly database: string;
constructor(projectId: string, database?: string);
static empty(): DatabaseId;
get isDefaultDatabase(): boolean;
isEqual(other: {}): boolean;
}
/**
* @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.
*/
type DocumentData$1 = { [field: string]: any };
type UpdateData$1 = { [fieldPath: string]: any };
interface Settings {
host?: string;
ssl?: boolean;
cacheSizeBytes?: number;
experimentalForceLongPolling?: boolean;
experimentalAutoDetectLongPolling?: boolean;
ignoreUndefinedProperties?: boolean;
merge?: boolean;
}
interface PersistenceSettings$1 {
synchronizeTabs?: boolean;
experimentalTabSynchronization?: boolean;
experimentalForceOwningTab?: boolean;
}
interface FirestoreDataConverter$2<T> {
toFirestore(modelObject: T): DocumentData$1;
toFirestore(modelObject: Partial<T>, options: SetOptions$1): DocumentData$1;
fromFirestore(snapshot: QueryDocumentSnapshot$2, options: SnapshotOptions$1): T;
}
declare class FirebaseFirestore {
private constructor();
settings(settings: Settings): void;
useEmulator(
host: string,
port: number,
options?: {
mockUserToken?: EmulatorMockTokenOptions | string;
}
): void;
enablePersistence(settings?: PersistenceSettings$1): Promise<void>;
collection(collectionPath: string): CollectionReference$1<DocumentData$1>;
doc(documentPath: string): DocumentReference$1<DocumentData$1>;
collectionGroup(collectionId: string): Query$2<DocumentData$1>;
runTransaction<T>(
updateFunction: (transaction: Transaction$3) => Promise<T>
): Promise<T>;
batch(): WriteBatch$1;
app: any;
clearPersistence(): Promise<void>;
enableNetwork(): Promise<void>;
disableNetwork(): Promise<void>;
waitForPendingWrites(): Promise<void>;
onSnapshotsInSync(observer: {
next?: (value: void) => void;
error?: (error: FirestoreError$1) => void;
complete?: () => void;
}): () => void;
onSnapshotsInSync(onSync: () => void): () => void;
terminate(): Promise<void>;
loadBundle(
bundleData: ArrayBuffer | ReadableStream<Uint8Array> | string
): LoadBundleTask$1;
namedQuery(name: string): Promise<Query$2<DocumentData$1> | null>;
INTERNAL: { delete: () => Promise<void> };
}
interface LoadBundleTask$1 extends PromiseLike<LoadBundleTaskProgress$1> {
onProgress(
next?: (progress: LoadBundleTaskProgress$1) => any,
error?: (error: Error) => any,
complete?: () => void
): void;
then<T, R>(
onFulfilled?: (a: LoadBundleTaskProgress$1) => T | PromiseLike<T>,
onRejected?: (a: Error) => R | PromiseLike<R>
): Promise<T | R>;
catch<R>(
onRejected: (a: Error) => R | PromiseLike<R>
): Promise<R | LoadBundleTaskProgress$1>;
}
interface LoadBundleTaskProgress$1 {
documentsLoaded: number;
totalDocuments: number;
bytesLoaded: number;
totalBytes: number;
taskState: TaskState$1;
}
type TaskState$1 = 'Error' | 'Running' | 'Success';
declare class Transaction$3 {
private constructor();
get<T>(documentRef: DocumentReference$1<T>): Promise<DocumentSnapshot$2<T>>;
set<T>(
documentRef: DocumentReference$1<T>,
data: Partial<T>,
options: SetOptions$1
): Transaction$3;
set<T>(documentRef: DocumentReference$1<T>, data: T): Transaction$3;
update(documentRef: DocumentReference$1<any>, data: UpdateData$1): Transaction$3;
update(
documentRef: DocumentReference$1<any>,
field: string | FieldPath$2,
value: any,
...moreFieldsAndValues: any[]
): Transaction$3;
delete(documentRef: DocumentReference$1<any>): Transaction$3;
}
declare class WriteBatch$1 {
private constructor();
set<T>(
documentRef: DocumentReference$1<T>,
data: Partial<T>,
options: SetOptions$1
): WriteBatch$1;
set<T>(documentRef: DocumentReference$1<T>, data: T): WriteBatch$1;
update(documentRef: DocumentReference$1<any>, data: UpdateData$1): WriteBatch$1;
update(
documentRef: DocumentReference$1<any>,
field: string | FieldPath$2,
value: any,
...moreFieldsAndValues: any[]
): WriteBatch$1;
delete(documentRef: DocumentReference$1<any>): WriteBatch$1;
commit(): Promise<void>;
}
interface SnapshotListenOptions$1 {
readonly includeMetadataChanges?: boolean;
}
interface SetOptions$1 {
readonly merge?: boolean;
readonly mergeFields?: (string | FieldPath$2)[];
}
interface GetOptions {
readonly source?: 'default' | 'server' | 'cache';
}
declare class DocumentReference$1<
T = DocumentData$1,
T2 extends DocumentData$1 = DocumentData$1
> {
private constructor();
readonly id: string;
readonly firestore: FirebaseFirestore;
readonly parent: CollectionReference$1<T>;
readonly path: string;
collection(collectionPath: string): CollectionReference$1<DocumentData$1>;
isEqual(other: DocumentReference$1<T>): boolean;
set(data: Partial<T>, options: SetOptions$1): Promise<void>;
set(data: T): Promise<void>;
update(data: UpdateData$1): Promise<void>;
update(
field: string | FieldPath$2,
value: any,
...moreFieldsAndValues: any[]
): Promise<void>;
delete(): Promise<void>;
get(options?: GetOptions): Promise<DocumentSnapshot$2<T>>;
onSnapshot(observer: {
next?: (snapshot: DocumentSnapshot$2<T>) => void;
error?: (error: FirestoreError$1) => void;
complete?: () => void;
}): () => void;
onSnapshot(
options: SnapshotListenOptions$1,
observer: {
next?: (snapshot: DocumentSnapshot$2<T>) => void;
error?: (error: FirestoreError$1) => void;
complete?: () => void;
}
): () => void;
onSnapshot(
onNext: (snapshot: DocumentSnapshot$2<T>) => void,
onError?: (error: FirestoreError$1) => void,
onCompletion?: () => void
): () => void;
onSnapshot(
options: SnapshotListenOptions$1,
onNext: (snapshot: DocumentSnapshot$2<T>) => void,
onError?: (error: FirestoreError$1) => void,
onCompletion?: () => void
): () => void;
withConverter(converter: null): DocumentReference$1<DocumentData$1>;
withConverter<U>(converter: FirestoreDataConverter$2<U>): DocumentReference$1<U>;
}
interface SnapshotOptions$1 {
readonly serverTimestamps?: 'estimate' | 'previous' | 'none';
}
interface SnapshotMetadata$1 {
readonly hasPendingWrites: boolean;
readonly fromCache: boolean;
isEqual(other: SnapshotMetadata$1): boolean;
}
declare class DocumentSnapshot$2<
T = DocumentData$1,
T2 extends DocumentData$1 = DocumentData$1
> {
protected constructor();
readonly exists: boolean;
readonly ref: DocumentReference$1<T>;
readonly id: string;
readonly metadata: SnapshotMetadata$1;
data(options?: SnapshotOptions$1): T | undefined;
get(fieldPath: string | FieldPath$2, options?: SnapshotOptions$1): any;
isEqual(other: DocumentSnapshot$2<T>): boolean;
}
declare class QueryDocumentSnapshot$2<
T = DocumentData$1,
T2 extends DocumentData$1 = DocumentData$1
> extends DocumentSnapshot$2<T, T2> {
private constructor();
data(options?: SnapshotOptions$1): T;
}
type OrderByDirection$1 = 'desc' | 'asc';
type WhereFilterOp$1 =
| '<'
| '<='
| '=='
| '!='
| '>='
| '>'
| 'array-contains'
| 'in'
| 'array-contains-any'
| 'not-in';
declare class Query$2<T = DocumentData$1, T2 extends DocumentData$1 = DocumentData$1> {
protected constructor();
readonly firestore: FirebaseFirestore;
where(
fieldPath: string | FieldPath$2,
opStr: WhereFilterOp$1,
value: any
): Query$2<T>;
orderBy(
fieldPath: string | FieldPath$2,
directionStr?: OrderByDirection$1
): Query$2<T>;
limit(limit: number): Query$2<T>;
limitToLast(limit: number): Query$2<T>;
startAt(snapshot: DocumentSnapshot$2<any>): Query$2<T>;
startAt(...fieldValues: any[]): Query$2<T>;
startAfter(snapshot: DocumentSnapshot$2<any>): Query$2<T>;
startAfter(...fieldValues: any[]): Query$2<T>;
endBefore(snapshot: DocumentSnapshot$2<any>): Query$2<T>;
endBefore(...fieldValues: any[]): Query$2<T>;
endAt(snapshot: DocumentSnapshot$2<any>): Query$2<T>;
endAt(...fieldValues: any[]): Query$2<T>;
isEqual(other: Query$2<T>): boolean;
get(options?: GetOptions): Promise<QuerySnapshot$1<T>>;
onSnapshot(observer: {
next?: (snapshot: QuerySnapshot$1<T>) => void;
error?: (error: FirestoreError$1) => void;
complete?: () => void;
}): () => void;
onSnapshot(
options: SnapshotListenOptions$1,
observer: {
next?: (snapshot: QuerySnapshot$1<T>) => void;
error?: (error: FirestoreError$1) => void;
complete?: () => void;
}
): () => void;
onSnapshot(
onNext: (snapshot: QuerySnapshot$1<T>) => void,
onError?: (error: FirestoreError$1) => void,
onCompletion?: () => void
): () => void;
onSnapshot(
options: SnapshotListenOptions$1,
onNext: (snapshot: QuerySnapshot$1<T>) => void,
onError?: (error: FirestoreError$1) => void,
onCompletion?: () => void
): () => void;
withConverter(converter: null): Query$2<DocumentData$1>;
withConverter<U>(converter: FirestoreDataConverter$2<U>): Query$2<U>;
}
declare class QuerySnapshot$1<
T = DocumentData$1,
T2 extends DocumentData$1 = DocumentData$1
> {
private constructor();
readonly query: Query$2<T>;
readonly metadata: SnapshotMetadata$1;
readonly docs: Array<QueryDocumentSnapshot$2<T>>;
readonly size: number;
readonly empty: boolean;
docChanges(options?: SnapshotListenOptions$1): Array<DocumentChange$1<T>>;
forEach(
callback: (result: QueryDocumentSnapshot$2<T>) => void,
thisArg?: any
): void;
isEqual(other: QuerySnapshot$1<T>): boolean;
}
type DocumentChangeType$1 = 'added' | 'removed' | 'modified';
interface DocumentChange$1<
T = DocumentData$1,
T2 extends DocumentData$1 = DocumentData$1
> {
readonly type: DocumentChangeType$1;
readonly doc: QueryDocumentSnapshot$2<T>;
readonly oldIndex: number;
readonly newIndex: number;
}
declare class CollectionReference$1<
T = DocumentData$1,
T2 extends DocumentData$1 = DocumentData$1
> extends Query$2<T, T2> {
private constructor();
readonly id: string;
readonly parent: DocumentReference$1<DocumentData$1> | null;
readonly path: string;
doc(documentPath?: string): DocumentReference$1<T>;
add(data: T): Promise<DocumentReference$1<T>>;
isEqual(other: CollectionReference$1<T>): boolean;
withConverter(converter: null): CollectionReference$1<DocumentData$1>;
withConverter<U>(
converter: FirestoreDataConverter$2<U>
): CollectionReference$1<U>;
}
declare class FieldPath$2 {
constructor(...fieldNames: string[]);
static documentId(): FieldPath$2;
isEqual(other: FieldPath$2): boolean;
}
type FirestoreErrorCode$1 =
| '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';
interface FirestoreError$1 {
code: FirestoreErrorCode$1;
message: string;
name: string;
stack?: string;
}
declare module '@firebase/component' {
interface NameServiceMapping {
'firestore-compat': FirebaseFirestore;
}
}
/**
* 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;
}
/**
* A slash-separated path for navigating resources (documents and collections)
* within Firestore.
*
* @internal
*/
declare class ResourcePath extends BasePath<ResourcePath> {
protected construct(segments: string[], offset?: number, length?: number): ResourcePath;
canonicalString(): string;
toString(): string;
/**
* Returns a string representation of this path
* where each path segment has been encoded with
* `encodeURIComponent`.
*/
toUriEncodedString(): string;
/**
* Creates a resource path from the given slash-delimited string. If multiple
* arguments are provided, all components are combined. Leading and trailing
* slashes from all components are ignored.
*/
static fromString(...pathComponents: string[]): ResourcePath;
static emptyPath(): ResourcePath;
}
/**
* A dot-separated path for navigating sub-objects within a document.
* @internal
*/
declare class FieldPath$1 extends BasePath<FieldPath$1> {
protected construct(segments: string[], offset?: number, length?: number): FieldPath$1;
/**
* 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$1;
/**
* 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$1;
static emptyPath(): FieldPath$1;
}
/**
* @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.
*/
/**
* @internal
*/
declare class DocumentKey {
readonly path: ResourcePath;
constructor(path: ResourcePath);
static fromPath(path: string): DocumentKey;
static fromName(name: string): DocumentKey;
static empty(): DocumentKey;
get collectionGroup(): string;
/** Returns true if the document is in the specified collectionId. */
hasCollectionId(collectionId: string): boolean;
/** Returns the collection group (i.e. the name of the parent collection) for this key. */
getCollectionGroup(): string;
/** Returns the fully qualified path to the parent collection. */
getCollectionPath(): ResourcePath;
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;
}
/**
* @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.
*/
/**
* 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$1[];
constructor(fields: FieldPath$1[]);
static empty(): FieldMask;
/**
* Returns a new FieldMask object that is the result of adding all the given
* fields paths to this field mask.
*/
unionWith(extraFields: FieldPath$1[]): FieldMask;
/**
* 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$1): boolean;
isEqual(other: FieldMask): boolean;
}
/**
* @license
* Copyright 2025 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.
*/
/**
* A list of data types Firestore objects may serialize in their toJSON implemenetations.
* @private
* @internal
*/
type JsonTypeDesc = 'object' | 'string' | 'number' | 'boolean' | 'null' | 'undefined';
/**
* An association of JsonTypeDesc values to their native types.
* @private
* @internal
*/
type TSType<T extends JsonTypeDesc> = T extends 'object' ? object : T extends 'string' ? string : T extends 'number' ? number : T extends 'boolean' ? boolean : T extends 'null' ? null : T extends 'undefined' ? undefined : never;
/**
* The representation of a JSON object property name and its type value.
* @private
* @internal
*/
interface Property<T extends JsonTypeDesc> {
value?: TSType<T>;
typeString: JsonTypeDesc;
}
/**
* @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.
*/
/**
* A `Timestamp` represents a point in time independent of any time zone or
* calendar, represented as seconds and fractions of seconds at nanosecond
* resolution in UTC Epoch time.
*
* It is encoded using the Proleptic Gregorian Calendar which extends the
* Gregorian calendar backwards to year one. It is encoded assuming all minutes
* are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second
* table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to
* 9999-12-31T23:59:59.999999999Z.
*
* For examples and further specifications, refer to the
* {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.
*/
declare class Timestamp$1 {
/**
* The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
*/
readonly seconds: number;
/**
* The fractions of a second at nanosecond resolution.*
*/
readonly nanoseconds: number;
/**
* Creates a new timestamp with the current date, with millisecond precision.
*
* @returns a new timestamp representing the current date.
*/
static now(): Timestamp$1;
/**
* Creates a new timestamp from the given date.
*
* @param date - The date to initialize the `Timestamp` from.
* @returns A new `Timestamp` representing the same point in time as the given
* date.
*/
static fromDate(date: Date): Timestamp$1;
/**
* Creates a new timestamp from the given number of milliseconds.
*
* @param milliseconds - Number of milliseconds since Unix epoch
* 1970-01-01T00:00:00Z.
* @returns A new `Timestamp` representing the same point in time as the given
* number of milliseconds.
*/
static fromMillis(milliseconds: number): Timestamp$1;
/**
* Creates a new timestamp.
*
* @param seconds - The number of seconds of UTC time since Unix epoch
* 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
* 9999-12-31T23:59:59Z inclusive.
* @param nanoseconds - The non-negative fractions of a second at nanosecond
* resolution. Negative second values with fractions must still have
* non-negative nanoseconds values that count forward in time. Must be
* from 0 to 999,999,999 inclusive.
*/
constructor(
/**
* The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
*/
seconds: number,
/**
* The fractions of a second at nanosecond resolution.*
*/
nanoseconds: number);
/**
* Converts a `Timestamp` to a JavaScript `Date` object. This conversion
* causes a loss of precision since `Date` objects only support millisecond
* precision.
*
* @returns JavaScript `Date` object representing the same point in time as
* this `Timestamp`, with millisecond precision.
*/
toDate(): Date;
/**
* Converts a `Timestamp` to a numeric timestamp (in milliseconds since
* epoch). This operation causes a loss of precision.
*
* @returns The point in time corresponding to this timestamp, represented as
* the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.
*/
toMillis(): number;
_compareTo(other: Timestamp$1): number;
/**
* Returns true if this `Timestamp` is equal to the provided one.
*
* @param other - The `Timestamp` to compare against.
* @returns true if this `Timestamp` is equal to the provided one.
*/
isEqual(other: Timestamp$1): boolean;
/** Returns a textual representation of this `Timestamp`. */
toString(): string;
static _jsonSchemaVersion: string;
static _jsonSchema: {
type: Property<"string">;
seconds: Property<"number">;
nanoseconds: Property<"number">;
};
/**
* Returns a JSON-serializable representation of this `Timestamp`.
*/
toJSON(): {
seconds: number;
nanoseconds: number;
type: string;
};
/**
* Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}.
*/
static fromJSON(json: object): Timestamp$1;
/**
* Converts this object to a primitive string, which allows `Timestamp` objects
* to be compared using the `>`, `<=`, `>=` and `>` operators.
*/
valueOf(): 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.
*/
/**
* A version of a document in Firestore. This corresponds to the version
* timestamp, such as update_time or read_time.
*/
declare class SnapshotVersion {
private timestamp;
static fromTimestamp(value: Timestamp$1): SnapshotVersion;
static min(): SnapshotVersion;
static max(): SnapshotVersion;
private constructor();
compareTo(other: SnapshotVersion): number;
isEqual(other: SnapshotVersion): boolean;
/** Returns a number representation of the version for use in spec tests. */
toMicroseconds(): number;
toString(): string;
toTimestamp(): Timestamp$1;
}
interface ApiClientObjectMap<T> {
[k: string]: T;
}
declare type Timestamp = string | {
seconds?: string | number;
nanos?: number;
};
declare type CompositeFilterOp = 'OPERATOR_UNSPECIFIED' | 'AND' | 'OR';
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';
declare type FieldTransformSetToServerValue = 'SERVER_VALUE_UNSPECIFIED' | 'REQUEST_TIME';
declare type IndexFieldMode = 'MODE_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING';
declare type IndexState$1 = 'STATE_UNSPECIFIED' | 'CREATING' | 'READY' | 'ERROR';
declare type OrderDirection = 'DIRECTION_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING';
declare type TargetChangeTargetChangeType = 'NO_CHANGE' | 'ADD' | 'REMOVE' | 'CURRENT' | 'RESET';
declare type UnaryFilterOp = 'OPERATOR_UNSPECIFIED' | 'IS_NAN' | 'IS_NULL' | 'IS_NOT_NAN' | 'IS_NOT_NULL';
declare type ValueNullValue = 'NULL_VALUE';
declare namespace firestoreV1ApiClientInterfaces {
interface Aggregation {
count?: Count;
sum?: Sum;
avg?: Avg;
alias?: string;
}
interface AggregationResult {
aggregateFields?: ApiClientObjectMap<Value>;
}
interface ArrayValue {
values?: Value[];
}
interface Avg {
field?: FieldReference;
}
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 BitSequence {
bitmap?: string | Uint8Array;
padding?: number;
}
interface BloomFilter {
bits?: BitSequence;
hashCount?: number;
}
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 Count {
upTo?: number;
}
interface Cursor {
values?: Value[];
before?: boolean;
}
interface Document {
name?: string;
fields?: ApiClientObjectMap<Value>;
createTime?: Timestamp;
updateTime?: Timestamp;
}
interface DocumentChange {
document?: Document;
targetIds?: number[];
removedTargetIds?: number[];
}
interface DocumentDelete {
document?: string;
removedTargetIds?: number[];
readTime?: Timestamp;
}
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 ExecutePipelineRequest {
database?: string;
structuredPipeline?: StructuredPipeline;
transaction?: string;
newTransaction?: TransactionOptions;
readTime?: string;
}
interface ExecutePipelineResponse {
transaction?: string;
results?: Document[];
executionTime?: string;
}
interface ExistenceFilter {
targetId?: number;
count?: number;
unchangedNames?: BloomFilter;
}
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 Function {
name?: string;
args?: Value[];
options?: ApiClientObjectMap<Value>;
}
interface Index {
name?: string;
collectionId?: string;
fields?: IndexField[];
state?: IndexState$1;
}
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 Pipeline {
stages?: Stage[];
}
interface Precondition {
exists?: boolean;
updateTime?: Timestamp;
}
interface Projection {
fields?: FieldReference[];
}
interface QueryTarget {
parent?: string;
structuredQuery?: StructuredQuery;
}
interface ReadOnly {
readTime?: string;
}
interface ReadWrite {
retryTransaction?: string;
}
interface RollbackRequest {
transaction?: string;
}
interface RunQueryRequest {
parent?: string;
structuredQuery?: StructuredQuery;
transaction?: string;
newTransaction?: TransactionOptions;
readTime?: string;
}
interface RunQueryResponse {
transaction?: string;
document?: Document;
readTime?: string;
skippedResults?: number;
}
interface RunAggregationQueryRequest {
parent?: string;
structuredAggregationQuery?: StructuredAggregationQuery;
transaction?: string;
newTransaction?: TransactionOptions;
readTime?: string;
}
interface RunAggregationQueryResponse {
result?: AggregationResult;
transaction?: string;
readTime?: string;
}
interface StructuredAggregationQuery {
structuredQuery?: StructuredQuery;
aggregations?: Aggregation[];
}
interface Stage {
name?: string;
args?: Value[];
options?: ApiClientObjectMap<Value>;
}
interface Status {
code?: number;
message?: string;
details?: Array<ApiClientObjectMap<any>>;
}
interface StructuredPipeline {
pipeline?: Pipeline;
options?: ApiClientObjectMap<Value>;
}
interface StructuredQuery {
select?: Projection;
from?: CollectionSelector[];
where?: Filter;
orderBy?: Order[];
startAt?: Cursor;
endAt?: Cursor;
offset?: number;
limit?: number | {
value: number;
};
}
interface Sum {
field?: FieldReference;
}
interface Target {
query?: QueryTarget;
documents?: DocumentsTarget;
resumeToken?: string | Uint8Array;
readTime?: Timestamp;
targetId?: number;
once?: boolean;
expectedCount?: number | {
value: number;
};
}
interface TargetChange {
targetChangeType?: TargetChangeTargetChangeType;
targetIds?: number[];
cause?: Status;
resumeToken?: string | Uint8Array;
readTime?: Timestamp;
}
interface TransactionOptions {
readOnly?: ReadOnly;
readWrite?: ReadWrite;
}
interface UnaryFilter {
op?: UnaryFilterOp;
field?: FieldReference;
}
interface Value {
nullValue?: ValueNullValue;
booleanValue?: boolean;
integerValue?: string | number;
doubleValue?: string | number;
timestampValue?: Timestamp;
stringValue?: string;
bytesValue?: string | Uint8Array;
referenceValue?: string;
geoPointValue?: LatLng;
arrayValue?: ArrayValue;
mapValue?: MapValue;
fieldReferenceValue?: string;
variableReferenceValue?: string;
functionValue?: Function;
pipelineValue?: Pipeline;
}
interface Write {
update?: Document;
delete?: string;
verify?: string;
transform?: DocumentTransform;
updateMask?: DocumentMask;
updateTransforms?: FieldTransform[];
currentDocument?: Precondition;
}
interface WriteRequest {
streamId?: string;
writes?: Write[];
streamToken?: string | Uint8Array;
labels?: ApiClientObjectMap<string>;
}
interface WriteResponse {
streamId?: string;
streamToken?: string | Uint8Array;
writeResults?: WriteResult[];
commitTime?: Timestamp;
}
interface WriteResult {
updateTime?: Timestamp;
transformResults?: Value[];
}
}
declare type MapValue = firestoreV1ApiClientInterfaces.MapValue;
declare type Pipeline$2 = firestoreV1ApiClientInterfaces.Pipeline;
declare type Stage$1 =