diff --git a/common/api-review/firestore-lite.api.md b/common/api-review/firestore-lite.api.md index 5804553b2fe..2fc68ea071d 100644 --- a/common/api-review/firestore-lite.api.md +++ b/common/api-review/firestore-lite.api.md @@ -4,15 +4,13 @@ ```ts -import { DocumentData as DocumentData_2 } from '@firebase/firestore-types'; -import { FieldPath as FieldPath_4 } from '@firebase/firestore-types'; import { FirebaseApp } from '@firebase/app-types'; import { FirebaseAuthInternalName } from '@firebase/auth-interop-types'; import { _FirebaseService } from '@firebase/app-types'; +import * as firestore from '@firebase/firestore-types'; import { LogLevel } from '@firebase/logger'; import { LogLevelString } from '@firebase/logger'; import { Provider } from '@firebase/component'; -import { SetOptions } from '@firebase/firestore-types'; // @public (undocumented) export function addDoc(reference: CollectionReference, data: T): Promise>; @@ -330,7 +328,7 @@ export function setDoc(reference: DocumentReference, data: T): Promise(reference: DocumentReference, data: Partial, options: SetOptions_2): Promise; +export function setDoc(reference: DocumentReference, data: Partial, options: SetOptions): Promise; // @public (undocumented) export function setLogLevel(newLevel: LogLevelString | LogLevel): void; @@ -402,7 +400,7 @@ export class Transaction { // (undocumented) set(documentRef: DocumentReference, value: T): this; // (undocumented) - set(documentRef: DocumentReference, value: Partial, options: SetOptions_2): this; + set(documentRef: DocumentReference, value: Partial, options: SetOptions): this; // (undocumented) update(documentRef: DocumentReference, value: UpdateData): this; // (undocumented) @@ -438,7 +436,7 @@ export class WriteBatch implements WriteBatch { // (undocumented) set(documentRef: DocumentReference, value: T): WriteBatch; // (undocumented) - set(documentRef: DocumentReference, value: Partial, options: SetOptions_2): WriteBatch; + set(documentRef: DocumentReference, value: Partial, options: SetOptions): WriteBatch; // (undocumented) update(documentRef: DocumentReference, value: UpdateData): WriteBatch; // (undocumented) diff --git a/package.json b/package.json index de289310bab..a3d95421adb 100644 --- a/package.json +++ b/package.json @@ -66,7 +66,7 @@ "@changesets/changelog-github": "0.2.6", "@changesets/cli": "2.9.2", "@microsoft/api-documenter": "7.8.21", - "@microsoft/api-extractor": "7.9.2", + "@microsoft/api-extractor": "7.8.2-pr1796.0", "@types/chai": "4.2.12", "@types/chai-as-promised": "7.1.3", "@types/child-process-promise": "2.2.1", diff --git a/packages/firestore/package.json b/packages/firestore/package.json index 100f14c4664..b1b368005e9 100644 --- a/packages/firestore/package.json +++ b/packages/firestore/package.json @@ -15,7 +15,7 @@ "build:deps": "lerna run --scope @firebase/'{app,firestore}' --include-dependencies build", "build:console": "node tools/console.build.js", "build:exp": "rollup -c rollup.config.exp.js", - "build:lite": "rollup -c rollup.config.lite.js && api-report:lite", + "build:lite": "rollup -c rollup.config.lite.js && yarn api-report:lite", "build:exp:release": "yarn build:exp && yarn build:lite", "predev": "yarn prebuild", "dev": "rollup -c -w", diff --git a/packages/firestore/src/api/database.ts b/packages/firestore/src/api/database.ts index 519ee56c380..7f06223b94a 100644 --- a/packages/firestore/src/api/database.ts +++ b/packages/firestore/src/api/database.ts @@ -15,33 +15,9 @@ * limitations under the License. */ -import { Value as ProtoValue } from '../protos/firestore_proto_api'; -import { - CollectionReference as PublicCollectionReference, - DocumentChange as PublicDocumentChange, - DocumentChangeType, - DocumentData, - DocumentReference as PublicDocumentReference, - DocumentSnapshot as PublicDocumentSnapshot, - FirebaseFirestore as PublicFirestore, - FirestoreDataConverter, - GetOptions, - LogLevel as PublicLogLevel, - OrderByDirection, - PersistenceSettings as PublicPersistenceSettings, - Query as PublicQuery, - QueryDocumentSnapshot as PublicQueryDocumentSnapshot, - QuerySnapshot as PublicQuerySnapshot, - SetOptions, - Settings as PublicSettings, - SnapshotListenOptions, - SnapshotMetadata as PublicSnapshotMetadata, - SnapshotOptions as PublicSnapshotOptions, - Transaction as PublicTransaction, - UpdateData, - WhereFilterOp, - WriteBatch as PublicWriteBatch -} from '@firebase/firestore-types'; +import * as firestore from '@firebase/firestore-types'; + +import * as api from '../protos/firestore_proto_api'; import { FirebaseApp } from '@firebase/app-types'; import { _FirebaseApp, FirebaseService } from '@firebase/app-types/private'; @@ -154,7 +130,7 @@ export const CACHE_SIZE_UNLIMITED = LruParams.COLLECTION_DISABLED; const DEFAULT_SYNCHRONIZE_TABS = false; /** Undocumented, private additional settings not exposed in our public API. */ -interface PrivateSettings extends PublicSettings { +interface PrivateSettings extends firestore.Settings { // Can be a google-auth-library or gapi client. credentials?: CredentialsSettings; } @@ -307,7 +283,7 @@ class FirestoreSettings { /** * The root reference to the database. */ -export class Firestore implements PublicFirestore, FirebaseService { +export class Firestore implements firestore.FirebaseFirestore, FirebaseService { // The objects that are a part of this API are exposed to third-parties as // compiled javascript so we want to flag our private members with a leading // underscore to discourage their use. @@ -381,7 +357,7 @@ export class Firestore implements PublicFirestore, FirebaseService { return this._userDataReader; } - settings(settingsLiteral: PublicSettings): void { + settings(settingsLiteral: firestore.Settings): void { validateExactNumberOfArgs('Firestore.settings', arguments, 1); validateArgType('Firestore.settings', 'object', 1, settingsLiteral); @@ -411,7 +387,7 @@ export class Firestore implements PublicFirestore, FirebaseService { return this._firestoreClient!.disableNetwork(); } - enablePersistence(settings?: PublicPersistenceSettings): Promise { + enablePersistence(settings?: firestore.PersistenceSettings): Promise { if (this._firestoreClient) { throw new FirestoreError( Code.FAILED_PRECONDITION, @@ -606,7 +582,7 @@ export class Firestore implements PublicFirestore, FirebaseService { } }; - collection(pathString: string): PublicCollectionReference { + collection(pathString: string): firestore.CollectionReference { validateExactNumberOfArgs('Firestore.collection', arguments, 1); validateArgType('Firestore.collection', 'non-empty string', 1, pathString); this.ensureClientConfigured(); @@ -617,7 +593,7 @@ export class Firestore implements PublicFirestore, FirebaseService { ); } - doc(pathString: string): PublicDocumentReference { + doc(pathString: string): firestore.DocumentReference { validateExactNumberOfArgs('Firestore.doc', arguments, 1); validateArgType('Firestore.doc', 'non-empty string', 1, pathString); this.ensureClientConfigured(); @@ -628,7 +604,7 @@ export class Firestore implements PublicFirestore, FirebaseService { ); } - collectionGroup(collectionId: string): PublicQuery { + collectionGroup(collectionId: string): firestore.Query { validateExactNumberOfArgs('Firestore.collectionGroup', arguments, 1); validateArgType( 'Firestore.collectionGroup', @@ -652,7 +628,7 @@ export class Firestore implements PublicFirestore, FirebaseService { } runTransaction( - updateFunction: (transaction: PublicTransaction) => Promise + updateFunction: (transaction: firestore.Transaction) => Promise ): Promise { validateExactNumberOfArgs('Firestore.runTransaction', arguments, 1); validateArgType('Firestore.runTransaction', 'function', 1, updateFunction); @@ -663,13 +639,13 @@ export class Firestore implements PublicFirestore, FirebaseService { ); } - batch(): PublicWriteBatch { + batch(): firestore.WriteBatch { this.ensureClientConfigured(); return new WriteBatch(this); } - static get logLevel(): PublicLogLevel { + static get logLevel(): firestore.LogLevel { switch (getLogLevel()) { case LogLevel.DEBUG: return 'debug'; @@ -689,7 +665,7 @@ export class Firestore implements PublicFirestore, FirebaseService { } } - static setLogLevel(level: PublicLogLevel): void { + static setLogLevel(level: firestore.LogLevel): void { validateExactNumberOfArgs('Firestore.setLogLevel', arguments, 1); validateStringEnum( 'setLogLevel', @@ -710,15 +686,15 @@ export class Firestore implements PublicFirestore, FirebaseService { /** * A reference to a transaction. */ -export class Transaction implements PublicTransaction { +export class Transaction implements firestore.Transaction { constructor( private _firestore: Firestore, private _transaction: InternalTransaction ) {} get( - documentRef: PublicDocumentReference - ): Promise> { + documentRef: firestore.DocumentReference + ): Promise> { validateExactNumberOfArgs('Transaction.get', arguments, 1); const ref = validateReference( 'Transaction.get', @@ -761,13 +737,13 @@ export class Transaction implements PublicTransaction { set( documentRef: DocumentReference, data: Partial, - options: SetOptions + options: firestore.SetOptions ): Transaction; set(documentRef: DocumentReference, data: T): Transaction; set( - documentRef: PublicDocumentReference, + documentRef: firestore.DocumentReference, value: T | Partial, - options?: SetOptions + options?: firestore.SetOptions ): Transaction { validateBetweenNumberOfArgs('Transaction.set', arguments, 2, 3); const ref = validateReference( @@ -794,18 +770,18 @@ export class Transaction implements PublicTransaction { } update( - documentRef: PublicDocumentReference, - value: UpdateData + documentRef: firestore.DocumentReference, + value: firestore.UpdateData ): Transaction; update( - documentRef: PublicDocumentReference, + documentRef: firestore.DocumentReference, field: string | ExternalFieldPath, value: unknown, ...moreFieldsAndValues: unknown[] ): Transaction; update( - documentRef: PublicDocumentReference, - fieldOrUpdateData: string | ExternalFieldPath | UpdateData, + documentRef: firestore.DocumentReference, + fieldOrUpdateData: string | ExternalFieldPath | firestore.UpdateData, value?: unknown, ...moreFieldsAndValues: unknown[] ): Transaction { @@ -849,7 +825,7 @@ export class Transaction implements PublicTransaction { return this; } - delete(documentRef: PublicDocumentReference): Transaction { + delete(documentRef: firestore.DocumentReference): Transaction { validateExactNumberOfArgs('Transaction.delete', arguments, 1); const ref = validateReference( 'Transaction.delete', @@ -861,7 +837,7 @@ export class Transaction implements PublicTransaction { } } -export class WriteBatch implements PublicWriteBatch { +export class WriteBatch implements firestore.WriteBatch { private _mutations = [] as Mutation[]; private _committed = false; @@ -870,13 +846,13 @@ export class WriteBatch implements PublicWriteBatch { set( documentRef: DocumentReference, data: Partial, - options: SetOptions + options: firestore.SetOptions ): WriteBatch; set(documentRef: DocumentReference, data: T): WriteBatch; set( - documentRef: PublicDocumentReference, + documentRef: firestore.DocumentReference, value: T | Partial, - options?: SetOptions + options?: firestore.SetOptions ): WriteBatch { validateBetweenNumberOfArgs('WriteBatch.set', arguments, 2, 3); this.verifyNotCommitted(); @@ -906,18 +882,18 @@ export class WriteBatch implements PublicWriteBatch { } update( - documentRef: PublicDocumentReference, - value: UpdateData + documentRef: firestore.DocumentReference, + value: firestore.UpdateData ): WriteBatch; update( - documentRef: PublicDocumentReference, + documentRef: firestore.DocumentReference, field: string | ExternalFieldPath, value: unknown, ...moreFieldsAndValues: unknown[] ): WriteBatch; update( - documentRef: PublicDocumentReference, - fieldOrUpdateData: string | ExternalFieldPath | UpdateData, + documentRef: firestore.DocumentReference, + fieldOrUpdateData: string | ExternalFieldPath | firestore.UpdateData, value?: unknown, ...moreFieldsAndValues: unknown[] ): WriteBatch { @@ -965,7 +941,7 @@ export class WriteBatch implements PublicWriteBatch { return this; } - delete(documentRef: PublicDocumentReference): WriteBatch { + delete(documentRef: firestore.DocumentReference): WriteBatch { validateExactNumberOfArgs('WriteBatch.delete', arguments, 1); this.verifyNotCommitted(); const ref = validateReference( @@ -1003,14 +979,15 @@ export class WriteBatch implements PublicWriteBatch { /** * A reference to a particular document in a collection in the database. */ -export class DocumentReference extends DocumentKeyReference - implements PublicDocumentReference { +export class DocumentReference + extends DocumentKeyReference + implements firestore.DocumentReference { private _firestoreClient: FirestoreClient; constructor( public _key: DocumentKey, readonly firestore: Firestore, - readonly _converter: FirestoreDataConverter | null + readonly _converter: firestore.FirestoreDataConverter | null ) { super(firestore._databaseId, _key, _converter); this._firestoreClient = this.firestore.ensureClientConfigured(); @@ -1019,7 +996,7 @@ export class DocumentReference extends DocumentKeyReference static forPath( path: ResourcePath, firestore: Firestore, - converter: FirestoreDataConverter | null + converter: firestore.FirestoreDataConverter | null ): DocumentReference { if (path.length % 2 !== 0) { throw new FirestoreError( @@ -1036,7 +1013,7 @@ export class DocumentReference extends DocumentKeyReference return this._key.path.lastSegment(); } - get parent(): PublicCollectionReference { + get parent(): firestore.CollectionReference { return new CollectionReference( this._key.path.popLast(), this.firestore, @@ -1048,7 +1025,9 @@ export class DocumentReference extends DocumentKeyReference return this._key.path.canonicalString(); } - collection(pathString: string): PublicCollectionReference { + collection( + pathString: string + ): firestore.CollectionReference { validateExactNumberOfArgs('DocumentReference.collection', arguments, 1); validateArgType( 'DocumentReference.collection', @@ -1070,7 +1049,7 @@ export class DocumentReference extends DocumentKeyReference ); } - isEqual(other: PublicDocumentReference): boolean { + isEqual(other: firestore.DocumentReference): boolean { if (!(other instanceof DocumentReference)) { throw invalidClassError('isEqual', 'DocumentReference', 1, other); } @@ -1081,9 +1060,9 @@ export class DocumentReference extends DocumentKeyReference ); } - set(value: Partial, options: SetOptions): Promise; + set(value: Partial, options: firestore.SetOptions): Promise; set(value: T): Promise; - set(value: T | Partial, options?: SetOptions): Promise { + set(value: T | Partial, options?: firestore.SetOptions): Promise { validateBetweenNumberOfArgs('DocumentReference.set', arguments, 1, 2); options = validateSetOptions('DocumentReference.set', options); const convertedValue = applyFirestoreDataConverter( @@ -1104,14 +1083,14 @@ export class DocumentReference extends DocumentKeyReference ); } - update(value: UpdateData): Promise; + update(value: firestore.UpdateData): Promise; update( field: string | ExternalFieldPath, value: unknown, ...moreFieldsAndValues: unknown[] ): Promise; update( - fieldOrUpdateData: string | ExternalFieldPath | UpdateData, + fieldOrUpdateData: string | ExternalFieldPath | firestore.UpdateData, value?: unknown, ...moreFieldsAndValues: unknown[] ): Promise { @@ -1152,19 +1131,21 @@ export class DocumentReference extends DocumentKeyReference ]); } - onSnapshot(observer: PartialObserver>): Unsubscribe; onSnapshot( - options: SnapshotListenOptions, - observer: PartialObserver> + observer: PartialObserver> + ): Unsubscribe; + onSnapshot( + options: firestore.SnapshotListenOptions, + observer: PartialObserver> ): Unsubscribe; onSnapshot( - onNext: NextFn>, + onNext: NextFn>, onError?: ErrorFn, onCompletion?: CompleteFn ): Unsubscribe; onSnapshot( - options: SnapshotListenOptions, - onNext: NextFn>, + options: firestore.SnapshotListenOptions, + onNext: NextFn>, onError?: ErrorFn, onCompletion?: CompleteFn ): Unsubscribe; @@ -1184,7 +1165,7 @@ export class DocumentReference extends DocumentKeyReference typeof args[currArg] === 'object' && !isPartialObserver(args[currArg]) ) { - options = args[currArg] as SnapshotListenOptions; + options = args[currArg] as firestore.SnapshotListenOptions; validateOptionNames('DocumentReference.onSnapshot', options, [ 'includeMetadataChanges' ]); @@ -1203,7 +1184,7 @@ export class DocumentReference extends DocumentKeyReference if (isPartialObserver(args[currArg])) { const userObserver = args[currArg] as PartialObserver< - PublicDocumentSnapshot + firestore.DocumentSnapshot >; args[currArg] = userObserver.next?.bind(userObserver); args[currArg + 1] = userObserver.error?.bind(userObserver); @@ -1232,7 +1213,7 @@ export class DocumentReference extends DocumentKeyReference const observer: PartialObserver = { next: snapshot => { if (args[currArg]) { - (args[currArg] as NextFn>)( + (args[currArg] as NextFn>)( this._convertToDocSnapshot(snapshot) ); } @@ -1248,7 +1229,7 @@ export class DocumentReference extends DocumentKeyReference ); } - get(options?: GetOptions): Promise> { + get(options?: firestore.GetOptions): Promise> { validateBetweenNumberOfArgs('DocumentReference.get', arguments, 0, 1); validateGetOptions('DocumentReference.get', options); @@ -1275,8 +1256,8 @@ export class DocumentReference extends DocumentKeyReference } withConverter( - converter: FirestoreDataConverter - ): PublicDocumentReference { + converter: firestore.FirestoreDataConverter + ): firestore.DocumentReference { return new DocumentReference(this._key, this.firestore, converter); } @@ -1302,13 +1283,13 @@ export class DocumentReference extends DocumentKeyReference } } -export class SnapshotMetadata implements PublicSnapshotMetadata { +export class SnapshotMetadata implements firestore.SnapshotMetadata { constructor( readonly hasPendingWrites: boolean, readonly fromCache: boolean ) {} - isEqual(other: PublicSnapshotMetadata): boolean { + isEqual(other: firestore.SnapshotMetadata): boolean { return ( this.hasPendingWrites === other.hasPendingWrites && this.fromCache === other.fromCache @@ -1320,20 +1301,20 @@ export class SnapshotMetadata implements PublicSnapshotMetadata { * Options interface that can be provided to configure the deserialization of * DocumentSnapshots. */ -export interface SnapshotOptions extends PublicSnapshotOptions {} +export interface SnapshotOptions extends firestore.SnapshotOptions {} -export class DocumentSnapshot - implements PublicDocumentSnapshot { +export class DocumentSnapshot + implements firestore.DocumentSnapshot { constructor( private _firestore: Firestore, private _key: DocumentKey, public _document: Document | null, private _fromCache: boolean, private _hasPendingWrites: boolean, - private readonly _converter: FirestoreDataConverter | null + private readonly _converter: firestore.FirestoreDataConverter | null ) {} - data(options?: PublicSnapshotOptions): T | undefined { + data(options?: firestore.SnapshotOptions): T | undefined { validateBetweenNumberOfArgs('DocumentSnapshot.data', arguments, 0, 1); options = validateSnapshotOptions('DocumentSnapshot.data', options); if (!this._document) { @@ -1366,7 +1347,7 @@ export class DocumentSnapshot get( fieldPath: string | ExternalFieldPath, - options?: PublicSnapshotOptions + options?: firestore.SnapshotOptions ): unknown { validateBetweenNumberOfArgs('DocumentSnapshot.get', arguments, 1, 2); options = validateSnapshotOptions('DocumentSnapshot.get', options); @@ -1393,7 +1374,7 @@ export class DocumentSnapshot return this._key.path.lastSegment(); } - get ref(): PublicDocumentReference { + get ref(): firestore.DocumentReference { return new DocumentReference( this._key, this._firestore, @@ -1405,11 +1386,11 @@ export class DocumentSnapshot return this._document !== null; } - get metadata(): PublicSnapshotMetadata { + get metadata(): firestore.SnapshotMetadata { return new SnapshotMetadata(this._hasPendingWrites, this._fromCache); } - isEqual(other: PublicDocumentSnapshot): boolean { + isEqual(other: firestore.DocumentSnapshot): boolean { if (!(other instanceof DocumentSnapshot)) { throw invalidClassError('isEqual', 'DocumentSnapshot', 1, other); } @@ -1425,8 +1406,9 @@ export class DocumentSnapshot } } -export class QueryDocumentSnapshot extends DocumentSnapshot - implements PublicQueryDocumentSnapshot { +export class QueryDocumentSnapshot + extends DocumentSnapshot + implements firestore.QueryDocumentSnapshot { data(options?: SnapshotOptions): T { const data = super.data(options); debugAssert( @@ -1446,7 +1428,7 @@ export function newQueryFilter( op: Operator, value: unknown ): FieldFilter { - let fieldValue: ProtoValue; + let fieldValue: api.Value; if (fieldPath.isKeyField()) { if (op === Operator.ARRAY_CONTAINS || op === Operator.ARRAY_CONTAINS_ANY) { throw new FirestoreError( @@ -1456,8 +1438,8 @@ export function newQueryFilter( ); } else if (op === Operator.IN || op === Operator.NOT_IN) { validateDisjunctiveFilterElements(value, op); - const referenceList: ProtoValue[] = []; - for (const arrayValue of value as ProtoValue[]) { + const referenceList: api.Value[] = []; + for (const arrayValue of value as api.Value[]) { referenceList.push(parseDocumentIdValue(databaseId, query, arrayValue)); } fieldValue = { arrayValue: { values: referenceList } }; @@ -1534,7 +1516,7 @@ export function newQueryBoundFromDocument( ); } - const components: ProtoValue[] = []; + const components: api.Value[] = []; // Because people expect to continue/end a query at the exact document // provided, we need to use the implicit sort order rather than the explicit @@ -1595,7 +1577,7 @@ export function newQueryBoundFromFields( ); } - const components: ProtoValue[] = []; + const components: api.Value[] = []; for (let i = 0; i < values.length; i++) { const rawValue = values[i]; const orderByComponent = orderBy[i]; @@ -1645,7 +1627,7 @@ function parseDocumentIdValue( databaseId: DatabaseId, query: InternalQuery, documentIdValue: unknown -): ProtoValue { +): api.Value { if (typeof documentIdValue === 'string') { if (documentIdValue === '') { throw new FirestoreError( @@ -1846,18 +1828,18 @@ export function validateHasExplicitOrderByForLimitToLast( } } -export class Query implements PublicQuery { +export class Query implements firestore.Query { constructor( public _query: InternalQuery, readonly firestore: Firestore, - protected readonly _converter: FirestoreDataConverter | null + protected readonly _converter: firestore.FirestoreDataConverter | null ) {} where( field: string | ExternalFieldPath, - opStr: WhereFilterOp, + opStr: firestore.WhereFilterOp, value: unknown - ): PublicQuery { + ): firestore.Query { validateExactNumberOfArgs('Query.where', arguments, 3); validateDefined('Query.where', 3, value); @@ -1899,8 +1881,8 @@ export class Query implements PublicQuery { orderBy( field: string | ExternalFieldPath, - directionStr?: OrderByDirection - ): PublicQuery { + directionStr?: firestore.OrderByDirection + ): firestore.Query { validateBetweenNumberOfArgs('Query.orderBy', arguments, 1, 2); validateOptionalArgType( 'Query.orderBy', @@ -1929,7 +1911,7 @@ export class Query implements PublicQuery { ); } - limit(n: number): PublicQuery { + limit(n: number): firestore.Query { validateExactNumberOfArgs('Query.limit', arguments, 1); validateArgType('Query.limit', 'number', 1, n); validatePositiveNumber('Query.limit', 1, n); @@ -1940,7 +1922,7 @@ export class Query implements PublicQuery { ); } - limitToLast(n: number): PublicQuery { + limitToLast(n: number): firestore.Query { validateExactNumberOfArgs('Query.limitToLast', arguments, 1); validateArgType('Query.limitToLast', 'number', 1, n); validatePositiveNumber('Query.limitToLast', 1, n); @@ -1952,9 +1934,9 @@ export class Query implements PublicQuery { } startAt( - docOrField: unknown | PublicDocumentSnapshot, + docOrField: unknown | firestore.DocumentSnapshot, ...fields: unknown[] - ): PublicQuery { + ): firestore.Query { validateAtLeastNumberOfArgs('Query.startAt', arguments, 1); const bound = this.boundFromDocOrFields( 'Query.startAt', @@ -1970,9 +1952,9 @@ export class Query implements PublicQuery { } startAfter( - docOrField: unknown | PublicDocumentSnapshot, + docOrField: unknown | firestore.DocumentSnapshot, ...fields: unknown[] - ): PublicQuery { + ): firestore.Query { validateAtLeastNumberOfArgs('Query.startAfter', arguments, 1); const bound = this.boundFromDocOrFields( 'Query.startAfter', @@ -1988,9 +1970,9 @@ export class Query implements PublicQuery { } endBefore( - docOrField: unknown | PublicDocumentSnapshot, + docOrField: unknown | firestore.DocumentSnapshot, ...fields: unknown[] - ): PublicQuery { + ): firestore.Query { validateAtLeastNumberOfArgs('Query.endBefore', arguments, 1); const bound = this.boundFromDocOrFields( 'Query.endBefore', @@ -2006,9 +1988,9 @@ export class Query implements PublicQuery { } endAt( - docOrField: unknown | PublicDocumentSnapshot, + docOrField: unknown | firestore.DocumentSnapshot, ...fields: unknown[] - ): PublicQuery { + ): firestore.Query { validateAtLeastNumberOfArgs('Query.endAt', arguments, 1); const bound = this.boundFromDocOrFields( 'Query.endAt', @@ -2023,7 +2005,7 @@ export class Query implements PublicQuery { ); } - isEqual(other: PublicQuery): boolean { + isEqual(other: firestore.Query): boolean { if (!(other instanceof Query)) { throw invalidClassError('isEqual', 'Query', 1, other); } @@ -2034,14 +2016,16 @@ export class Query implements PublicQuery { ); } - withConverter(converter: FirestoreDataConverter): PublicQuery { + withConverter( + converter: firestore.FirestoreDataConverter + ): firestore.Query { return new Query(this._query, this.firestore, converter); } /** Helper function to create a bound from a document or fields */ private boundFromDocOrFields( methodName: string, - docOrField: unknown | PublicDocumentSnapshot, + docOrField: unknown | firestore.DocumentSnapshot, fields: unknown[], before: boolean ): Bound { @@ -2068,19 +2052,21 @@ export class Query implements PublicQuery { } } - onSnapshot(observer: PartialObserver>): Unsubscribe; onSnapshot( - options: SnapshotListenOptions, - observer: PartialObserver> + observer: PartialObserver> + ): Unsubscribe; + onSnapshot( + options: firestore.SnapshotListenOptions, + observer: PartialObserver> ): Unsubscribe; onSnapshot( - onNext: NextFn>, + onNext: NextFn>, onError?: ErrorFn, onCompletion?: CompleteFn ): Unsubscribe; onSnapshot( - options: SnapshotListenOptions, - onNext: NextFn>, + options: firestore.SnapshotListenOptions, + onNext: NextFn>, onError?: ErrorFn, onCompletion?: CompleteFn ): Unsubscribe; @@ -2093,7 +2079,7 @@ export class Query implements PublicQuery { typeof args[currArg] === 'object' && !isPartialObserver(args[currArg]) ) { - options = args[currArg] as SnapshotListenOptions; + options = args[currArg] as firestore.SnapshotListenOptions; validateOptionNames('Query.onSnapshot', options, [ 'includeMetadataChanges' ]); @@ -2108,7 +2094,7 @@ export class Query implements PublicQuery { if (isPartialObserver(args[currArg])) { const userObserver = args[currArg] as PartialObserver< - PublicQuerySnapshot + firestore.QuerySnapshot >; args[currArg] = userObserver.next?.bind(userObserver); args[currArg + 1] = userObserver.error?.bind(userObserver); @@ -2132,7 +2118,7 @@ export class Query implements PublicQuery { const observer: PartialObserver = { next: snapshot => { if (args[currArg]) { - (args[currArg] as NextFn>)( + (args[currArg] as NextFn>)( new QuerySnapshot( this.firestore, this._query, @@ -2151,7 +2137,7 @@ export class Query implements PublicQuery { return firestoreClient.listen(this._query, options, observer); } - get(options?: GetOptions): Promise> { + get(options?: firestore.GetOptions): Promise> { validateBetweenNumberOfArgs('Query.get', arguments, 0, 1); validateGetOptions('Query.get', options); validateHasExplicitOrderByForLimitToLast(this._query); @@ -2167,17 +2153,18 @@ export class Query implements PublicQuery { } } -export class QuerySnapshot implements PublicQuerySnapshot { - private _cachedChanges: Array> | null = null; +export class QuerySnapshot + implements firestore.QuerySnapshot { + private _cachedChanges: Array> | null = null; private _cachedChangesIncludeMetadataChanges: boolean | null = null; - readonly metadata: PublicSnapshotMetadata; + readonly metadata: firestore.SnapshotMetadata; constructor( private readonly _firestore: Firestore, private readonly _originalQuery: InternalQuery, private readonly _snapshot: ViewSnapshot, - private readonly _converter: FirestoreDataConverter | null + private readonly _converter: firestore.FirestoreDataConverter | null ) { this.metadata = new SnapshotMetadata( _snapshot.hasPendingWrites, @@ -2185,8 +2172,8 @@ export class QuerySnapshot implements PublicQuerySnapshot { ); } - get docs(): Array> { - const result: Array> = []; + get docs(): Array> { + const result: Array> = []; this.forEach(doc => result.push(doc)); return result; } @@ -2200,7 +2187,7 @@ export class QuerySnapshot implements PublicQuerySnapshot { } forEach( - callback: (result: PublicQueryDocumentSnapshot) => void, + callback: (result: firestore.QueryDocumentSnapshot) => void, thisArg?: unknown ): void { validateBetweenNumberOfArgs('QuerySnapshot.forEach', arguments, 1, 2); @@ -2217,11 +2204,13 @@ export class QuerySnapshot implements PublicQuerySnapshot { }); } - get query(): PublicQuery { + get query(): firestore.Query { return new Query(this._originalQuery, this._firestore, this._converter); } - docChanges(options?: SnapshotListenOptions): Array> { + docChanges( + options?: firestore.SnapshotListenOptions + ): Array> { if (options) { validateOptionNames('QuerySnapshot.docChanges', options, [ 'includeMetadataChanges' @@ -2262,7 +2251,7 @@ export class QuerySnapshot implements PublicQuerySnapshot { } /** Check the equality. The call can be very expensive. */ - isEqual(other: PublicQuerySnapshot): boolean { + isEqual(other: firestore.QuerySnapshot): boolean { if (!(other instanceof QuerySnapshot)) { throw invalidClassError('isEqual', 'QuerySnapshot', 1, other); } @@ -2291,12 +2280,12 @@ export class QuerySnapshot implements PublicQuerySnapshot { } } -export class CollectionReference extends Query - implements PublicCollectionReference { +export class CollectionReference extends Query + implements firestore.CollectionReference { constructor( readonly _path: ResourcePath, firestore: Firestore, - _converter: FirestoreDataConverter | null + _converter: firestore.FirestoreDataConverter | null ) { super(newQueryForPath(_path), firestore, _converter); if (_path.length % 2 !== 1) { @@ -2313,12 +2302,12 @@ export class CollectionReference extends Query return this._query.path.lastSegment(); } - get parent(): PublicDocumentReference | null { + get parent(): firestore.DocumentReference | null { const parentPath = this._query.path.popLast(); if (parentPath.isEmpty()) { return null; } else { - return new DocumentReference( + return new DocumentReference( new DocumentKey(parentPath), this.firestore, /* converter= */ null @@ -2330,7 +2319,7 @@ export class CollectionReference extends Query return this._query.path.canonicalString(); } - doc(pathString?: string): PublicDocumentReference { + doc(pathString?: string): firestore.DocumentReference { validateBetweenNumberOfArgs('CollectionReference.doc', arguments, 0, 1); // We allow omission of 'pathString' but explicitly prohibit passing in both // 'undefined' and 'null'. @@ -2351,7 +2340,7 @@ export class CollectionReference extends Query ); } - add(value: T): Promise> { + add(value: T): Promise> { validateExactNumberOfArgs('CollectionReference.add', arguments, 1); const convertedValue = this._converter ? this._converter.toFirestore(value) @@ -2362,16 +2351,16 @@ export class CollectionReference extends Query } withConverter( - converter: FirestoreDataConverter - ): PublicCollectionReference { + converter: firestore.FirestoreDataConverter + ): firestore.CollectionReference { return new CollectionReference(this._path, this.firestore, converter); } } function validateSetOptions( methodName: string, - options: SetOptions | undefined -): SetOptions { + options: firestore.SetOptions | undefined +): firestore.SetOptions { if (options === undefined) { return { merge: false @@ -2402,8 +2391,8 @@ function validateSetOptions( function validateSnapshotOptions( methodName: string, - options: PublicSnapshotOptions | undefined -): PublicSnapshotOptions { + options: firestore.SnapshotOptions | undefined +): firestore.SnapshotOptions { if (options === undefined) { return {}; } @@ -2421,7 +2410,7 @@ function validateSnapshotOptions( function validateGetOptions( methodName: string, - options: GetOptions | undefined + options: firestore.GetOptions | undefined ): void { validateOptionalArgType(methodName, 'object', 1, options); if (options) { @@ -2438,7 +2427,7 @@ function validateGetOptions( function validateReference( methodName: string, - documentRef: PublicDocumentReference, + documentRef: firestore.DocumentReference, firestore: Firestore ): DocumentKeyReference { if (!(documentRef instanceof DocumentKeyReference)) { @@ -2454,14 +2443,14 @@ function validateReference( } /** - * Calculates the array of PublicDocumentChange's for a given ViewSnapshot. + * Calculates the array of firestore.DocumentChange's for a given ViewSnapshot. * * Exported for testing. * * @param snapshot The ViewSnapshot that represents the expected state. * @param includeMetadataChanges Whether to include metadata changes. * @param converter A factory function that returns a QueryDocumentSnapshot. - * @return An objecyt that matches the PublicDocumentChange API. + * @return An objecyt that matches the firestore.DocumentChange API. */ export function changesFromSnapshot( snapshot: ViewSnapshot, @@ -2472,7 +2461,7 @@ export function changesFromSnapshot( hasPendingWrite: boolean ) => DocSnap ): Array<{ - type: DocumentChangeType; + type: firestore.DocumentChangeType; doc: DocSnap; oldIndex: number; newIndex: number; @@ -2498,7 +2487,7 @@ export function changesFromSnapshot( ); lastDoc = change.doc; return { - type: 'added' as DocumentChangeType, + type: 'added' as firestore.DocumentChangeType, doc, oldIndex: -1, newIndex: index++ @@ -2534,7 +2523,7 @@ export function changesFromSnapshot( } } -function resultChangeType(type: ChangeType): DocumentChangeType { +function resultChangeType(type: ChangeType): firestore.DocumentChangeType { switch (type) { case ChangeType.Added: return 'added'; @@ -2560,8 +2549,8 @@ function resultChangeType(type: ChangeType): DocumentChangeType { export function applyFirestoreDataConverter( converter: UntypedFirestoreDataConverter | null, value: T, - options?: SetOptions -): DocumentData { + options?: firestore.SetOptions +): firestore.DocumentData { let convertedValue; if (converter) { if (options && (options.merge || options.mergeFields)) { @@ -2573,7 +2562,7 @@ export function applyFirestoreDataConverter( convertedValue = converter.toFirestore(value); } } else { - convertedValue = value as DocumentData; + convertedValue = value as firestore.DocumentData; } return convertedValue; } diff --git a/packages/firestore/src/api/field_path.ts b/packages/firestore/src/api/field_path.ts index eb2ec67d416..7d6797db01f 100644 --- a/packages/firestore/src/api/field_path.ts +++ b/packages/firestore/src/api/field_path.ts @@ -15,7 +15,7 @@ * limitations under the License. */ -import { FieldPath as PublicFieldPath } from '@firebase/firestore-types'; +import * as firestore from '@firebase/firestore-types'; import { FieldPath as InternalFieldPath } from '../model/path'; import { Code, FirestoreError } from '../util/error'; @@ -65,7 +65,7 @@ export abstract class BaseFieldPath { * 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). */ -export class FieldPath extends BaseFieldPath implements PublicFieldPath { +export class FieldPath extends BaseFieldPath implements firestore.FieldPath { /** * Creates a FieldPath from the provided field names. If more than one field * name is provided, the path will point to a nested field in a document. @@ -86,7 +86,7 @@ export class FieldPath extends BaseFieldPath implements PublicFieldPath { return new FieldPath(InternalFieldPath.keyField().canonicalString()); } - isEqual(other: PublicFieldPath): boolean { + isEqual(other: firestore.FieldPath): boolean { if (!(other instanceof FieldPath)) { throw invalidClassError('isEqual', 'FieldPath', 1, other); } diff --git a/packages/firestore/src/api/field_value.ts b/packages/firestore/src/api/field_value.ts index b37c92a8d3f..de96ac54cab 100644 --- a/packages/firestore/src/api/field_value.ts +++ b/packages/firestore/src/api/field_value.ts @@ -15,7 +15,7 @@ * limitations under the License. */ -import { FieldValue as PublicFieldValue } from '@firebase/firestore-types'; +import * as firestore from '@firebase/firestore-types'; import { validateArgType, validateAtLeastNumberOfArgs, @@ -204,26 +204,26 @@ export class NumericIncrementFieldValueImpl extends SerializableFieldValue { /** The public FieldValue class of the lite API. */ export abstract class FieldValue extends SerializableFieldValue - implements PublicFieldValue { + implements firestore.FieldValue { protected constructor() { super(); } - static delete(): PublicFieldValue { + static delete(): firestore.FieldValue { validateNoArgs('FieldValue.delete', arguments); return new FieldValueDelegate( new DeleteFieldValueImpl('FieldValue.delete') ); } - static serverTimestamp(): PublicFieldValue { + static serverTimestamp(): firestore.FieldValue { validateNoArgs('FieldValue.serverTimestamp', arguments); return new FieldValueDelegate( new ServerTimestampFieldValueImpl('FieldValue.serverTimestamp') ); } - static arrayUnion(...elements: unknown[]): PublicFieldValue { + static arrayUnion(...elements: unknown[]): firestore.FieldValue { validateAtLeastNumberOfArgs('FieldValue.arrayUnion', arguments, 1); // NOTE: We don't actually parse the data until it's used in set() or // update() since we'd need the Firestore instance to do this. @@ -232,7 +232,7 @@ export abstract class FieldValue extends SerializableFieldValue ); } - static arrayRemove(...elements: unknown[]): PublicFieldValue { + static arrayRemove(...elements: unknown[]): firestore.FieldValue { validateAtLeastNumberOfArgs('FieldValue.arrayRemove', arguments, 1); // NOTE: We don't actually parse the data until it's used in set() or // update() since we'd need the Firestore instance to do this. @@ -241,7 +241,7 @@ export abstract class FieldValue extends SerializableFieldValue ); } - static increment(n: number): PublicFieldValue { + static increment(n: number): firestore.FieldValue { validateArgType('FieldValue.increment', 'number', 1, n); validateExactNumberOfArgs('FieldValue.increment', arguments, 1); return new FieldValueDelegate( @@ -259,7 +259,7 @@ export abstract class FieldValue extends SerializableFieldValue * implementations as the base FieldValue class differs between the lite, full * and legacy SDK. */ -class FieldValueDelegate extends FieldValue implements PublicFieldValue { +class FieldValueDelegate extends FieldValue implements firestore.FieldValue { readonly _methodName: string; constructor(readonly _delegate: SerializableFieldValue) { @@ -271,7 +271,7 @@ class FieldValueDelegate extends FieldValue implements PublicFieldValue { return this._delegate._toFieldTransform(context); } - isEqual(other: PublicFieldValue): boolean { + isEqual(other: firestore.FieldValue): boolean { if (!(other instanceof FieldValueDelegate)) { return false; } diff --git a/packages/firestore/src/api/user_data_reader.ts b/packages/firestore/src/api/user_data_reader.ts index 51668f5d088..03b864ddc98 100644 --- a/packages/firestore/src/api/user_data_reader.ts +++ b/packages/firestore/src/api/user_data_reader.ts @@ -15,12 +15,9 @@ * limitations under the License. */ -import { DocumentData, SetOptions } from '@firebase/firestore-types'; +import * as firestore from '@firebase/firestore-types'; -import { - Value as ProtoValue, - MapValue as ProtoMapValue -} from '../protos/firestore_proto_api'; +import * as api from '../protos/firestore_proto_api'; import { Timestamp } from './timestamp'; import { DatabaseId } from '../core/database_info'; @@ -60,8 +57,11 @@ const RESERVED_FIELD_REGEX = /^__.*__$/; * lite, full and legacy SDK. */ export interface UntypedFirestoreDataConverter { - toFirestore(modelObject: T): DocumentData; - toFirestore(modelObject: Partial, options: SetOptions): DocumentData; + toFirestore(modelObject: T): firestore.DocumentData; + toFirestore( + modelObject: Partial, + options: firestore.SetOptions + ): firestore.DocumentData; fromFirestore(snapshot: unknown, options?: unknown): T; } @@ -349,7 +349,7 @@ export function parseSetData( targetDoc: DocumentKey, input: unknown, hasConverter: boolean, - options: SetOptions = {} + options: firestore.SetOptions = {} ): ParsedSetData { const context = userDataReader.createContext( options.merge || options.mergeFields @@ -538,7 +538,7 @@ export function parseQueryValue( methodName: string, input: unknown, allowArrays = false -): ProtoValue { +): api.Value { const context = userDataReader.createContext( allowArrays ? UserDataSource.ArrayArgument : UserDataSource.Argument, methodName @@ -564,7 +564,7 @@ export function parseQueryValue( export function parseData( input: unknown, context: ParseContext -): ProtoValue | null { +): api.Value | null { if (looksLikeJsonObject(input)) { validatePlainObject('Unsupported field value:', context, input); return parseObject(input, context); @@ -606,8 +606,8 @@ export function parseData( function parseObject( obj: Dict, context: ParseContext -): { mapValue: ProtoMapValue } { - const fields: Dict = {}; +): { mapValue: api.MapValue } { + const fields: Dict = {}; if (isEmpty(obj)) { // If we encounter an empty object, we explicitly add it to the update @@ -627,8 +627,8 @@ function parseObject( return { mapValue: { fields } }; } -function parseArray(array: unknown[], context: ParseContext): ProtoValue { - const values: ProtoValue[] = []; +function parseArray(array: unknown[], context: ParseContext): api.Value { + const values: api.Value[] = []; let entryIndex = 0; for (const entry of array) { let parsedEntry = parseData( @@ -680,7 +680,7 @@ function parseSentinelFieldValue( function parseScalarValue( value: unknown, context: ParseContext -): ProtoValue | null { +): api.Value | null { if (value === null) { return { nullValue: 'NULL_VALUE' }; } else if (typeof value === 'number') { diff --git a/packages/firestore/src/api/user_data_writer.ts b/packages/firestore/src/api/user_data_writer.ts index 614f1a01f9f..caa0bc8e312 100644 --- a/packages/firestore/src/api/user_data_writer.ts +++ b/packages/firestore/src/api/user_data_writer.ts @@ -15,14 +15,9 @@ * limitations under the License. */ -import { DocumentData } from '@firebase/firestore-types'; -import { - Value as ProtoValue, - MapValue as ProtoMapValue, - ArrayValue as ProtoArrayValue, - LatLng as ProtoLatLng, - Timestamp as ProtoTimestamp -} from '../protos/firestore_proto_api'; +import * as firestore from '@firebase/firestore-types'; + +import * as api from '../protos/firestore_proto_api'; import { DocumentKeyReference } from './user_data_reader'; import { Blob } from './blob'; @@ -60,10 +55,10 @@ export class UserDataWriter { private readonly serverTimestampBehavior: ServerTimestampBehavior, private readonly referenceFactory: ( key: DocumentKey - ) => DocumentKeyReference + ) => DocumentKeyReference ) {} - convertValue(value: ProtoValue): unknown { + convertValue(value: api.Value): unknown { switch (typeOrder(value)) { case TypeOrder.NullValue: return null; @@ -92,26 +87,26 @@ export class UserDataWriter { } } - private convertObject(mapValue: ProtoMapValue): DocumentData { - const result: DocumentData = {}; + private convertObject(mapValue: api.MapValue): firestore.DocumentData { + const result: firestore.DocumentData = {}; forEach(mapValue.fields || {}, (key, value) => { result[key] = this.convertValue(value); }); return result; } - private convertGeoPoint(value: ProtoLatLng): GeoPoint { + private convertGeoPoint(value: api.LatLng): GeoPoint { return new GeoPoint( normalizeNumber(value.latitude), normalizeNumber(value.longitude) ); } - private convertArray(arrayValue: ProtoArrayValue): unknown[] { + private convertArray(arrayValue: api.ArrayValue): unknown[] { return (arrayValue.values || []).map(value => this.convertValue(value)); } - private convertServerTimestamp(value: ProtoValue): unknown { + private convertServerTimestamp(value: api.Value): unknown { switch (this.serverTimestampBehavior) { case 'previous': const previousValue = getPreviousValue(value); @@ -126,7 +121,7 @@ export class UserDataWriter { } } - private convertTimestamp(value: ProtoTimestamp): Timestamp | Date { + private convertTimestamp(value: api.Timestamp): Timestamp | Date { const normalizedValue = normalizeTimestamp(value); const timestamp = new Timestamp( normalizedValue.seconds, @@ -139,7 +134,9 @@ export class UserDataWriter { } } - private convertReference(name: string): DocumentKeyReference { + private convertReference( + name: string + ): DocumentKeyReference { const resourcePath = ResourcePath.fromString(name); hardAssert( isValidResourceName(resourcePath), diff --git a/packages/firestore/src/core/query.ts b/packages/firestore/src/core/query.ts index 7aadf24e2d5..44455d954aa 100644 --- a/packages/firestore/src/core/query.ts +++ b/packages/firestore/src/core/query.ts @@ -15,7 +15,7 @@ * limitations under the License. */ -import { Value as PublicValue } from '../protos/firestore_proto_api'; +import * as api from '../protos/firestore_proto_api'; import { compareDocumentsByField, Document } from '../model/document'; import { DocumentKey } from '../model/document_key'; @@ -579,7 +579,7 @@ export class FieldFilter extends Filter { protected constructor( public field: FieldPath, public op: Operator, - public value: PublicValue + public value: api.Value ) { super(); } @@ -587,11 +587,7 @@ export class FieldFilter extends Filter { /** * Creates a filter based on the provided arguments. */ - static create( - field: FieldPath, - op: Operator, - value: PublicValue - ): FieldFilter { + static create(field: FieldPath, op: Operator, value: api.Value): FieldFilter { if (field.isKeyField()) { if (op === Operator.IN || op === Operator.NOT_IN) { return this.createKeyFieldInFilter(field, op, value); @@ -652,7 +648,7 @@ export class FieldFilter extends Filter { private static createKeyFieldInFilter( field: FieldPath, op: Operator.IN | Operator.NOT_IN, - value: PublicValue + value: api.Value ): FieldFilter { debugAssert( isArray(value), @@ -763,7 +759,7 @@ export function stringifyFilter(filter: Filter): string { export class KeyFieldFilter extends FieldFilter { private readonly key: DocumentKey; - constructor(field: FieldPath, op: Operator, value: PublicValue) { + constructor(field: FieldPath, op: Operator, value: api.Value) { super(field, op, value); debugAssert( isReferenceValue(value), @@ -782,7 +778,7 @@ export class KeyFieldFilter extends FieldFilter { export class KeyFieldInFilter extends FieldFilter { private readonly keys: DocumentKey[]; - constructor(field: FieldPath, value: PublicValue) { + constructor(field: FieldPath, value: api.Value) { super(field, Operator.IN, value); this.keys = extractDocumentKeysFromArrayValue(Operator.IN, value); } @@ -796,7 +792,7 @@ export class KeyFieldInFilter extends FieldFilter { export class KeyFieldNotInFilter extends FieldFilter { private readonly keys: DocumentKey[]; - constructor(field: FieldPath, value: PublicValue) { + constructor(field: FieldPath, value: api.Value) { super(field, Operator.NOT_IN, value); this.keys = extractDocumentKeysFromArrayValue(Operator.NOT_IN, value); } @@ -808,7 +804,7 @@ export class KeyFieldNotInFilter extends FieldFilter { function extractDocumentKeysFromArrayValue( op: Operator.IN | Operator.NOT_IN, - value: PublicValue + value: api.Value ): DocumentKey[] { debugAssert( isArray(value), @@ -826,7 +822,7 @@ function extractDocumentKeysFromArrayValue( /** A Filter that implements the array-contains operator. */ export class ArrayContainsFilter extends FieldFilter { - constructor(field: FieldPath, value: PublicValue) { + constructor(field: FieldPath, value: api.Value) { super(field, Operator.ARRAY_CONTAINS, value); } @@ -838,7 +834,7 @@ export class ArrayContainsFilter extends FieldFilter { /** A Filter that implements the IN operator. */ export class InFilter extends FieldFilter { - constructor(field: FieldPath, value: PublicValue) { + constructor(field: FieldPath, value: api.Value) { super(field, Operator.IN, value); debugAssert(isArray(value), 'InFilter expects an ArrayValue'); } @@ -851,7 +847,7 @@ export class InFilter extends FieldFilter { /** A Filter that implements the not-in operator. */ export class NotInFilter extends FieldFilter { - constructor(field: FieldPath, value: PublicValue) { + constructor(field: FieldPath, value: api.Value) { super(field, Operator.NOT_IN, value); debugAssert(isArray(value), 'NotInFilter expects an ArrayValue'); } @@ -864,7 +860,7 @@ export class NotInFilter extends FieldFilter { /** A Filter that implements the array-contains-any operator. */ export class ArrayContainsAnyFilter extends FieldFilter { - constructor(field: FieldPath, value: PublicValue) { + constructor(field: FieldPath, value: api.Value) { super(field, Operator.ARRAY_CONTAINS_ANY, value); debugAssert(isArray(value), 'ArrayContainsAnyFilter expects an ArrayValue'); } @@ -903,7 +899,7 @@ export const enum Direction { * just after the provided values. */ export class Bound { - constructor(readonly position: PublicValue[], readonly before: boolean) {} + constructor(readonly position: api.Value[], readonly before: boolean) {} } export function canonifyBound(bound: Bound): string { diff --git a/packages/firestore/src/local/indexeddb_schema.ts b/packages/firestore/src/local/indexeddb_schema.ts index 5a9f3c7b87a..0f8d9ade4e7 100644 --- a/packages/firestore/src/local/indexeddb_schema.ts +++ b/packages/firestore/src/local/indexeddb_schema.ts @@ -17,12 +17,7 @@ import { BatchId, ListenSequenceNumber, TargetId } from '../core/types'; import { ResourcePath } from '../model/path'; -import { - Write as ProtoWrite, - Document as ProtoDocument, - QueryTarget as ProtoQueryTarget, - DocumentsTarget as ProtoDocumentsTarget -} from '../protos/firestore_proto_api'; +import * as api from '../protos/firestore_proto_api'; import { debugAssert, hardAssert } from '../util/assert'; import { SnapshotVersion } from '../core/snapshot_version'; @@ -489,13 +484,13 @@ export class DbMutationBatch { * * These mutations are never sent to the backend. */ - public baseMutations: ProtoWrite[] | undefined, + public baseMutations: api.Write[] | undefined, /** * A list of mutations to apply. All mutations will be applied atomically. * * Mutations are serialized via toMutation(). */ - public mutations: ProtoWrite[] + public mutations: api.Write[] ) {} } @@ -696,7 +691,7 @@ export class DbRemoteDocument { * Set to an instance of a Document if there's a cached version of the * document. */ - public document: ProtoDocument | null, + public document: api.Document | null, /** * Documents that were written to the remote document store based on * a write acknowledgment are marked with `hasCommittedMutations`. These @@ -750,7 +745,7 @@ export type DbTargetKey = TargetId; * IndexedDb. We use the proto definitions for these two kinds of queries in * order to avoid writing extra serialization logic. */ -export type DbQuery = ProtoQueryTarget | ProtoDocumentsTarget; +export type DbQuery = api.QueryTarget | api.DocumentsTarget; /** * An object to be stored in the 'targets' store in IndexedDb. diff --git a/packages/firestore/src/local/local_serializer.ts b/packages/firestore/src/local/local_serializer.ts index 69662f585e0..1d90066dc48 100644 --- a/packages/firestore/src/local/local_serializer.ts +++ b/packages/firestore/src/local/local_serializer.ts @@ -25,7 +25,7 @@ import { } from '../model/document'; import { DocumentKey } from '../model/document_key'; import { MutationBatch } from '../model/mutation_batch'; -import { DocumentsTarget as PublicDocumentsTarget } from '../protos/firestore_proto_api'; +import * as api from '../protos/firestore_proto_api'; import { fromDocument, fromDocumentsTarget, @@ -268,6 +268,6 @@ export function toDbTarget( /** * A helper function for figuring out what kind of query has been stored. */ -function isDocumentQuery(dbQuery: DbQuery): dbQuery is PublicDocumentsTarget { - return (dbQuery as PublicDocumentsTarget).documents !== undefined; +function isDocumentQuery(dbQuery: DbQuery): dbQuery is api.DocumentsTarget { + return (dbQuery as api.DocumentsTarget).documents !== undefined; } diff --git a/packages/firestore/src/model/document.ts b/packages/firestore/src/model/document.ts index 74047ba0843..64a43b5a06c 100644 --- a/packages/firestore/src/model/document.ts +++ b/packages/firestore/src/model/document.ts @@ -15,10 +15,7 @@ * limitations under the License. */ -import { - Value as ProtoValue, - MapValue as ProtoMapValue -} from '../protos/firestore_proto_api'; +import * as api from '../protos/firestore_proto_api'; import { SnapshotVersion } from '../core/snapshot_version'; import { fail } from '../util/assert'; @@ -70,7 +67,7 @@ export class Document extends MaybeDocument { this.hasCommittedMutations = !!options.hasCommittedMutations; } - field(path: FieldPath): ProtoValue | null { + field(path: FieldPath): api.Value | null { return this.objectValue.field(path); } @@ -78,7 +75,7 @@ export class Document extends MaybeDocument { return this.objectValue; } - toProto(): { mapValue: ProtoMapValue } { + toProto(): { mapValue: api.MapValue } { return this.objectValue.proto; } diff --git a/packages/firestore/src/model/mutation.ts b/packages/firestore/src/model/mutation.ts index 547495ac695..7c585225d93 100644 --- a/packages/firestore/src/model/mutation.ts +++ b/packages/firestore/src/model/mutation.ts @@ -15,7 +15,7 @@ * limitations under the License. */ -import { Value as ProtoValue } from '../protos/firestore_proto_api'; +import * as api from '../protos/firestore_proto_api'; import { Timestamp } from '../api/timestamp'; import { SnapshotVersion } from '../core/snapshot_version'; @@ -120,7 +120,7 @@ export class MutationResult { * * Will be null if the mutation was not a TransformMutation. */ - readonly transformResults: Array | null + readonly transformResults: Array | null ) {} } @@ -725,9 +725,9 @@ function requireDocument( function serverTransformResults( fieldTransforms: FieldTransform[], baseDoc: MaybeDocument | null, - serverTransformResults: Array -): ProtoValue[] { - const transformResults: ProtoValue[] = []; + serverTransformResults: Array +): api.Value[] { + const transformResults: api.Value[] = []; hardAssert( fieldTransforms.length === serverTransformResults.length, `server transform result count (${serverTransformResults.length}) ` + @@ -737,7 +737,7 @@ function serverTransformResults( for (let i = 0; i < serverTransformResults.length; i++) { const fieldTransform = fieldTransforms[i]; const transform = fieldTransform.transform; - let previousValue: ProtoValue | null = null; + let previousValue: api.Value | null = null; if (baseDoc instanceof Document) { previousValue = baseDoc.field(fieldTransform.field); } @@ -770,12 +770,12 @@ function localTransformResults( localWriteTime: Timestamp, maybeDoc: MaybeDocument | null, baseDoc: MaybeDocument | null -): ProtoValue[] { - const transformResults: ProtoValue[] = []; +): api.Value[] { + const transformResults: api.Value[] = []; for (const fieldTransform of fieldTransforms) { const transform = fieldTransform.transform; - let previousValue: ProtoValue | null = null; + let previousValue: api.Value | null = null; if (maybeDoc instanceof Document) { previousValue = maybeDoc.field(fieldTransform.field); } @@ -802,7 +802,7 @@ function localTransformResults( function transformObject( mutation: TransformMutation, data: ObjectValue, - transformResults: ProtoValue[] + transformResults: api.Value[] ): ObjectValue { debugAssert( transformResults.length === mutation.fieldTransforms.length, diff --git a/packages/firestore/src/model/object_value.ts b/packages/firestore/src/model/object_value.ts index 24d1667ceaf..4e511872188 100644 --- a/packages/firestore/src/model/object_value.ts +++ b/packages/firestore/src/model/object_value.ts @@ -15,10 +15,7 @@ * limitations under the License. */ -import { - Value as ProtoValue, - MapValue as ProtoMapValue -} from '../protos/firestore_proto_api'; +import * as api from '../protos/firestore_proto_api'; import { debugAssert } from '../util/assert'; import { FieldMask } from './mutation'; @@ -52,7 +49,7 @@ export const enum TypeOrder { * ability to add and remove fields (via the ObjectValueBuilder). */ export class ObjectValue { - constructor(readonly proto: { mapValue: ProtoMapValue }) { + constructor(readonly proto: { mapValue: api.MapValue }) { debugAssert( !isServerTimestamp(proto), 'ServerTimestamps should be converted to ServerTimestampValue' @@ -69,11 +66,11 @@ export class ObjectValue { * @param path the path to search * @return The value at the path or if there it doesn't exist. */ - field(path: FieldPath): ProtoValue | null { + field(path: FieldPath): api.Value | null { if (path.isEmpty()) { return this.proto; } else { - let value: ProtoValue = this.proto; + let value: api.Value = this.proto; for (let i = 0; i < path.length - 1; ++i) { if (!value.mapValue!.fields) { return null; @@ -99,7 +96,7 @@ export class ObjectValue { * map of Overlay values (to represent additional nesting at the given key) or * `null` (to represent field deletes). */ -type Overlay = Map | ProtoValue | null; +type Overlay = Map | api.Value | null; /** * An ObjectValueBuilder provides APIs to set and delete fields from an @@ -121,7 +118,7 @@ export class ObjectValueBuilder { * @param value The value to set. * @return The current Builder instance. */ - set(path: FieldPath, value: ProtoValue): ObjectValueBuilder { + set(path: FieldPath, value: api.Value): ObjectValueBuilder { debugAssert( !path.isEmpty(), 'Cannot set field for empty path on ObjectValue' @@ -150,7 +147,7 @@ export class ObjectValueBuilder { * Adds `value` to the overlay map at `path`. Creates nested map entries if * needed. */ - private setOverlay(path: FieldPath, value: ProtoValue | null): void { + private setOverlay(path: FieldPath, value: api.Value | null): void { let currentLevel = this.overlayMap; for (let i = 0; i < path.length - 1; ++i) { @@ -209,7 +206,7 @@ export class ObjectValueBuilder { private applyOverlay( currentPath: FieldPath, currentOverlays: Map - ): { mapValue: ProtoMapValue } | null { + ): { mapValue: api.MapValue } | null { let modified = false; const existingValue = this.baseObject.field(currentPath); @@ -242,7 +239,7 @@ export class ObjectValueBuilder { /** * Returns a FieldMask built from all fields in a MapValue. */ -export function extractFieldMask(value: ProtoMapValue): FieldMask { +export function extractFieldMask(value: api.MapValue): FieldMask { const fields: FieldPath[] = []; forEach(value!.fields || {}, (key, value) => { const currentPath = new FieldPath([key]); diff --git a/packages/firestore/src/model/server_timestamps.ts b/packages/firestore/src/model/server_timestamps.ts index ebb86c5ddd4..97327bfaaf8 100644 --- a/packages/firestore/src/model/server_timestamps.ts +++ b/packages/firestore/src/model/server_timestamps.ts @@ -15,10 +15,7 @@ * limitations under the License. */ -import { - Value as ProtoValue, - MapValue as ProtoMapValue -} from '../protos/firestore_proto_api'; +import * as api from '../protos/firestore_proto_api'; import { Timestamp } from '../api/timestamp'; import { normalizeTimestamp } from './values'; @@ -47,7 +44,7 @@ const TYPE_KEY = '__type__'; const PREVIOUS_VALUE_KEY = '__previous_value__'; const LOCAL_WRITE_TIME_KEY = '__local_write_time__'; -export function isServerTimestamp(value: ProtoValue | null): boolean { +export function isServerTimestamp(value: api.Value | null): boolean { const type = (value?.mapValue?.fields || {})[TYPE_KEY]?.stringValue; return type === SERVER_TIMESTAMP_SENTINEL; } @@ -57,9 +54,9 @@ export function isServerTimestamp(value: ProtoValue | null): boolean { */ export function serverTimestamp( localWriteTime: Timestamp, - previousValue: ProtoValue | null -): ProtoValue { - const mapValue: ProtoMapValue = { + previousValue: api.Value | null +): api.Value { + const mapValue: api.MapValue = { fields: { [TYPE_KEY]: { stringValue: SERVER_TIMESTAMP_SENTINEL @@ -86,7 +83,7 @@ export function serverTimestamp( * Preserving the previous values allows the user to display the last resoled * value until the backend responds with the timestamp. */ -export function getPreviousValue(value: ProtoValue): ProtoValue | null { +export function getPreviousValue(value: api.Value): api.Value | null { const previousValue = value.mapValue!.fields![PREVIOUS_VALUE_KEY]; if (isServerTimestamp(previousValue)) { @@ -98,7 +95,7 @@ export function getPreviousValue(value: ProtoValue): ProtoValue | null { /** * Returns the local time at which this timestamp was first set. */ -export function getLocalWriteTime(value: ProtoValue): Timestamp { +export function getLocalWriteTime(value: api.Value): Timestamp { const localWriteTime = normalizeTimestamp( value.mapValue!.fields![LOCAL_WRITE_TIME_KEY].timestampValue! ); diff --git a/packages/firestore/src/model/transform_operation.ts b/packages/firestore/src/model/transform_operation.ts index 542a27a3603..86c69c7dde9 100644 --- a/packages/firestore/src/model/transform_operation.ts +++ b/packages/firestore/src/model/transform_operation.ts @@ -15,7 +15,7 @@ * limitations under the License. */ -import { Value as PublicValue } from '../protos/firestore_proto_api'; +import * as api from '../protos/firestore_proto_api'; import { Timestamp } from '../api/timestamp'; import { debugAssert } from '../util/assert'; @@ -43,9 +43,9 @@ export class TransformOperation { */ export function applyTransformOperationToLocalView( transform: TransformOperation, - previousValue: PublicValue | null, + previousValue: api.Value | null, localWriteTime: Timestamp -): PublicValue { +): api.Value { if (transform instanceof ServerTimestampTransform) { return serverTimestamp(localWriteTime, previousValue); } else if (transform instanceof ArrayUnionTransformOperation) { @@ -70,9 +70,9 @@ export function applyTransformOperationToLocalView( */ export function applyTransformOperationToRemoteDocument( transform: TransformOperation, - previousValue: PublicValue | null, - transformResult: PublicValue | null -): PublicValue { + previousValue: api.Value | null, + transformResult: api.Value | null +): api.Value { // The server just sends null as the transform result for array operations, // so we have to calculate a result the same as we do for local // applications. @@ -106,8 +106,8 @@ export function applyTransformOperationToRemoteDocument( */ export function computeTransformOperationBaseValue( transform: TransformOperation, - previousValue: PublicValue | null -): PublicValue | null { + previousValue: api.Value | null +): api.Value | null { if (transform instanceof NumericIncrementTransformOperation) { return isNumber(previousValue) ? previousValue! : { integerValue: 0 }; } @@ -146,15 +146,15 @@ export class ServerTimestampTransform extends TransformOperation {} /** Transforms an array value via a union operation. */ export class ArrayUnionTransformOperation extends TransformOperation { - constructor(readonly elements: PublicValue[]) { + constructor(readonly elements: api.Value[]) { super(); } } function applyArrayUnionTransformOperation( transform: ArrayUnionTransformOperation, - previousValue: PublicValue | null -): PublicValue { + previousValue: api.Value | null +): api.Value { const values = coercedFieldValuesArray(previousValue); for (const toUnion of transform.elements) { if (!values.some(element => valueEquals(element, toUnion))) { @@ -166,15 +166,15 @@ function applyArrayUnionTransformOperation( /** Transforms an array value via a remove operation. */ export class ArrayRemoveTransformOperation extends TransformOperation { - constructor(readonly elements: PublicValue[]) { + constructor(readonly elements: api.Value[]) { super(); } } function applyArrayRemoveTransformOperation( transform: ArrayRemoveTransformOperation, - previousValue: PublicValue | null -): PublicValue { + previousValue: api.Value | null +): api.Value { let values = coercedFieldValuesArray(previousValue); for (const toRemove of transform.elements) { values = values.filter(element => !valueEquals(element, toRemove)); @@ -191,7 +191,7 @@ function applyArrayRemoveTransformOperation( export class NumericIncrementTransformOperation extends TransformOperation { constructor( readonly serializer: JsonProtoSerializer, - readonly operand: PublicValue + readonly operand: api.Value ) { super(); debugAssert( @@ -203,8 +203,8 @@ export class NumericIncrementTransformOperation extends TransformOperation { export function applyNumericIncrementTransformOperationToLocalView( transform: NumericIncrementTransformOperation, - previousValue: PublicValue | null -): PublicValue { + previousValue: api.Value | null +): api.Value { // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit // precision and resolves overflows by reducing precision, we do not // manually cap overflows at 2^63. @@ -220,11 +220,11 @@ export function applyNumericIncrementTransformOperationToLocalView( } } -function asNumber(value: PublicValue): number { +function asNumber(value: api.Value): number { return normalizeNumber(value.integerValue || value.doubleValue); } -function coercedFieldValuesArray(value: PublicValue | null): PublicValue[] { +function coercedFieldValuesArray(value: api.Value | null): api.Value[] { return isArray(value) && value.arrayValue.values ? value.arrayValue.values.slice() : []; diff --git a/packages/firestore/src/model/values.ts b/packages/firestore/src/model/values.ts index 2bb206c6391..654e089d2aa 100644 --- a/packages/firestore/src/model/values.ts +++ b/packages/firestore/src/model/values.ts @@ -15,11 +15,7 @@ * limitations under the License. */ -import { - firestoreV1ApiClientInterfaces, - Timestamp, - MapValue -} from '../protos/firestore_proto_api'; +import * as api from '../protos/firestore_proto_api'; import { TypeOrder } from './object_value'; import { fail, hardAssert } from '../util/assert'; @@ -34,9 +30,6 @@ import { getPreviousValue, isServerTimestamp } from './server_timestamps'; -import Value = firestoreV1ApiClientInterfaces.Value; -import ArrayValue = firestoreV1ApiClientInterfaces.ArrayValue; -import LatLng = firestoreV1ApiClientInterfaces.LatLng; // A RegExp matching ISO 8601 UTC timestamps with optional fraction. const ISO_TIMESTAMP_REG_EXP = new RegExp( @@ -44,7 +37,7 @@ const ISO_TIMESTAMP_REG_EXP = new RegExp( ); /** Extracts the backend's type order for the provided value. */ -export function typeOrder(value: Value): TypeOrder { +export function typeOrder(value: api.Value): TypeOrder { if ('nullValue' in value) { return TypeOrder.NullValue; } else if ('booleanValue' in value) { @@ -74,7 +67,7 @@ export function typeOrder(value: Value): TypeOrder { } /** Tests `left` and `right` for equality based on the backend semantics. */ -export function valueEquals(left: Value, right: Value): boolean { +export function valueEquals(left: api.Value, right: api.Value): boolean { const leftType = typeOrder(left); const rightType = typeOrder(right); if (leftType !== rightType) { @@ -113,7 +106,7 @@ export function valueEquals(left: Value, right: Value): boolean { } } -function timestampEquals(left: Value, right: Value): boolean { +function timestampEquals(left: api.Value, right: api.Value): boolean { if ( typeof left.timestampValue === 'string' && typeof right.timestampValue === 'string' && @@ -131,7 +124,7 @@ function timestampEquals(left: Value, right: Value): boolean { ); } -function geoPointEquals(left: Value, right: Value): boolean { +function geoPointEquals(left: api.Value, right: api.Value): boolean { return ( normalizeNumber(left.geoPointValue!.latitude) === normalizeNumber(right.geoPointValue!.latitude) && @@ -140,13 +133,13 @@ function geoPointEquals(left: Value, right: Value): boolean { ); } -function blobEquals(left: Value, right: Value): boolean { +function blobEquals(left: api.Value, right: api.Value): boolean { return normalizeByteString(left.bytesValue!).isEqual( normalizeByteString(right.bytesValue!) ); } -export function numberEquals(left: Value, right: Value): boolean { +export function numberEquals(left: api.Value, right: api.Value): boolean { if ('integerValue' in left && 'integerValue' in right) { return ( normalizeNumber(left.integerValue) === normalizeNumber(right.integerValue) @@ -165,7 +158,7 @@ export function numberEquals(left: Value, right: Value): boolean { return false; } -function objectEquals(left: Value, right: Value): boolean { +function objectEquals(left: api.Value, right: api.Value): boolean { const leftMap = left.mapValue!.fields || {}; const rightMap = right.mapValue!.fields || {}; @@ -188,15 +181,15 @@ function objectEquals(left: Value, right: Value): boolean { /** Returns true if the ArrayValue contains the specified element. */ export function arrayValueContains( - haystack: ArrayValue, - needle: Value + haystack: api.ArrayValue, + needle: api.Value ): boolean { return ( (haystack.values || []).find(v => valueEquals(v, needle)) !== undefined ); } -export function valueCompare(left: Value, right: Value): number { +export function valueCompare(left: api.Value, right: api.Value): number { const leftType = typeOrder(left); const rightType = typeOrder(right); @@ -235,7 +228,7 @@ export function valueCompare(left: Value, right: Value): number { } } -function compareNumbers(left: Value, right: Value): number { +function compareNumbers(left: api.Value, right: api.Value): number { const leftNumber = normalizeNumber(left.integerValue || left.doubleValue); const rightNumber = normalizeNumber(right.integerValue || right.doubleValue); @@ -255,7 +248,7 @@ function compareNumbers(left: Value, right: Value): number { } } -function compareTimestamps(left: Timestamp, right: Timestamp): number { +function compareTimestamps(left: api.Timestamp, right: api.Timestamp): number { if ( typeof left === 'string' && typeof right === 'string' && @@ -289,7 +282,7 @@ function compareReferences(leftPath: string, rightPath: string): number { return primitiveComparator(leftSegments.length, rightSegments.length); } -function compareGeoPoints(left: LatLng, right: LatLng): number { +function compareGeoPoints(left: api.LatLng, right: api.LatLng): number { const comparison = primitiveComparator( normalizeNumber(left.latitude), normalizeNumber(right.latitude) @@ -312,7 +305,7 @@ function compareBlobs( return leftBytes.compareTo(rightBytes); } -function compareArrays(left: ArrayValue, right: ArrayValue): number { +function compareArrays(left: api.ArrayValue, right: api.ArrayValue): number { const leftArray = left.values || []; const rightArray = right.values || []; @@ -325,7 +318,7 @@ function compareArrays(left: ArrayValue, right: ArrayValue): number { return primitiveComparator(leftArray.length, rightArray.length); } -function compareMaps(left: MapValue, right: MapValue): number { +function compareMaps(left: api.MapValue, right: api.MapValue): number { const leftMap = left.fields || {}; const leftKeys = Object.keys(leftMap); const rightMap = right.fields || {}; @@ -356,11 +349,11 @@ function compareMaps(left: MapValue, right: MapValue): number { * Generates the canonical ID for the provided field value (as used in Target * serialization). */ -export function canonicalId(value: Value): string { +export function canonicalId(value: api.Value): string { return canonifyValue(value); } -function canonifyValue(value: Value): string { +function canonifyValue(value: api.Value): string { if ('nullValue' in value) { return 'null'; } else if ('booleanValue' in value) { @@ -392,12 +385,12 @@ function canonifyByteString(byteString: string | Uint8Array): string { return normalizeByteString(byteString).toBase64(); } -function canonifyTimestamp(timestamp: Timestamp): string { +function canonifyTimestamp(timestamp: api.Timestamp): string { const normalizedTimestamp = normalizeTimestamp(timestamp); return `time(${normalizedTimestamp.seconds},${normalizedTimestamp.nanos})`; } -function canonifyGeoPoint(geoPoint: LatLng): string { +function canonifyGeoPoint(geoPoint: api.LatLng): string { return `geo(${geoPoint.latitude},${geoPoint.longitude})`; } @@ -405,7 +398,7 @@ function canonifyReference(referenceValue: string): string { return DocumentKey.fromName(referenceValue).toString(); } -function canonifyMap(mapValue: MapValue): string { +function canonifyMap(mapValue: api.MapValue): string { // Iteration order in JavaScript is not guaranteed. To ensure that we generate // matching canonical IDs for identical maps, we need to sort the keys. const sortedKeys = Object.keys(mapValue.fields || {}).sort(); @@ -423,7 +416,7 @@ function canonifyMap(mapValue: MapValue): string { return result + '}'; } -function canonifyArray(arrayValue: ArrayValue): string { +function canonifyArray(arrayValue: api.ArrayValue): string { let result = '['; let first = true; for (const value of arrayValue.values || []) { @@ -444,7 +437,7 @@ function canonifyArray(arrayValue: ArrayValue): string { * The memory size takes into account only the actual user data as it resides * in memory and ignores object overhead. */ -export function estimateByteSize(value: Value): number { +export function estimateByteSize(value: api.Value): number { switch (typeOrder(value)) { case TypeOrder.NullValue: return 4; @@ -479,7 +472,7 @@ export function estimateByteSize(value: Value): number { } } -function estimateMapByteSize(mapValue: MapValue): number { +function estimateMapByteSize(mapValue: api.MapValue): number { let size = 0; forEach(mapValue.fields || {}, (key, val) => { size += key.length + estimateByteSize(val); @@ -487,7 +480,7 @@ function estimateMapByteSize(mapValue: MapValue): number { return size; } -function estimateArrayByteSize(arrayValue: ArrayValue): number { +function estimateArrayByteSize(arrayValue: api.ArrayValue): number { return (arrayValue.values || []).reduce( (previousSize, value) => previousSize + estimateByteSize(value), 0 @@ -499,7 +492,7 @@ function estimateArrayByteSize(arrayValue: ArrayValue): number { * nanos" representation. */ export function normalizeTimestamp( - date: Timestamp + date: api.Timestamp ): { seconds: number; nanos: number } { hardAssert(!!date, 'Cannot normalize null or undefined timestamp.'); @@ -561,7 +554,7 @@ export function normalizeByteString(blob: string | Uint8Array): ByteString { } /** Returns a reference value for the provided database and key. */ -export function refValue(databaseId: DatabaseId, key: DocumentKey): Value { +export function refValue(databaseId: DatabaseId, key: DocumentKey): api.Value { return { referenceValue: `projects/${databaseId.projectId}/databases/${ databaseId.database @@ -571,54 +564,54 @@ export function refValue(databaseId: DatabaseId, key: DocumentKey): Value { /** Returns true if `value` is an IntegerValue . */ export function isInteger( - value?: Value | null + value?: api.Value | null ): value is { integerValue: string | number } { return !!value && 'integerValue' in value; } /** Returns true if `value` is a DoubleValue. */ export function isDouble( - value?: Value | null + value?: api.Value | null ): value is { doubleValue: string | number } { return !!value && 'doubleValue' in value; } /** Returns true if `value` is either an IntegerValue or a DoubleValue. */ -export function isNumber(value?: Value | null): boolean { +export function isNumber(value?: api.Value | null): boolean { return isInteger(value) || isDouble(value); } /** Returns true if `value` is an ArrayValue. */ export function isArray( - value?: Value | null -): value is { arrayValue: ArrayValue } { + value?: api.Value | null +): value is { arrayValue: api.ArrayValue } { return !!value && 'arrayValue' in value; } /** Returns true if `value` is a ReferenceValue. */ export function isReferenceValue( - value?: Value | null + value?: api.Value | null ): value is { referenceValue: string } { return !!value && 'referenceValue' in value; } /** Returns true if `value` is a NullValue. */ export function isNullValue( - value?: Value | null + value?: api.Value | null ): value is { nullValue: 'NULL_VALUE' } { return !!value && 'nullValue' in value; } /** Returns true if `value` is NaN. */ export function isNanValue( - value?: Value | null + value?: api.Value | null ): value is { doubleValue: 'NaN' | number } { return !!value && 'doubleValue' in value && isNaN(Number(value.doubleValue)); } /** Returns true if `value` is a MapValue. */ export function isMapValue( - value?: Value | null -): value is { mapValue: MapValue } { + value?: api.Value | null +): value is { mapValue: api.MapValue } { return !!value && 'mapValue' in value; } diff --git a/packages/firestore/src/platform/node/grpc_connection.ts b/packages/firestore/src/platform/node/grpc_connection.ts index 47e3decb72b..46855192be1 100644 --- a/packages/firestore/src/platform/node/grpc_connection.ts +++ b/packages/firestore/src/platform/node/grpc_connection.ts @@ -21,11 +21,13 @@ import { credentials as GrpcCredentials, ServiceError } from '@grpc/grpc-js'; -import { version as grpcVersion } from '@grpc/grpc-js/package.json'; +import * as grpcPkgJson from '@grpc/grpc-js/package.json'; import firebase from '@firebase/app'; const SDK_VERSION = firebase.SDK_VERSION; +const grpcVersion = grpcPkgJson.version; + import { Token } from '../../api/credentials'; import { DatabaseInfo } from '../../core/database_info'; import { Connection, Stream } from '../../remote/connection'; diff --git a/packages/firestore/src/remote/datastore.ts b/packages/firestore/src/remote/datastore.ts index a674873e961..d866bdc6bc9 100644 --- a/packages/firestore/src/remote/datastore.ts +++ b/packages/firestore/src/remote/datastore.ts @@ -19,12 +19,7 @@ import { CredentialsProvider } from '../api/credentials'; import { Document, MaybeDocument } from '../model/document'; import { DocumentKey } from '../model/document_key'; import { Mutation } from '../model/mutation'; -import { - RunQueryRequest as ProtoRunQueryRequest, - RunQueryResponse as ProtoRunQueryResponse, - BatchGetDocumentsRequest as ProtoBatchGetDocumentsRequest, - BatchGetDocumentsResponse as ProtoBatchGetDocumentsResponse -} from '../protos/firestore_proto_api'; +import * as api from '../protos/firestore_proto_api'; import { debugAssert, debugCast, hardAssert } from '../util/assert'; import { Code, FirestoreError } from '../util/error'; import { Connection } from './connection'; @@ -167,8 +162,8 @@ export async function invokeBatchGetDocumentsRpc( documents: keys.map(k => toName(datastoreImpl.serializer, k)) }; const response = await datastoreImpl.invokeStreamingRPC< - ProtoBatchGetDocumentsRequest, - ProtoBatchGetDocumentsResponse + api.BatchGetDocumentsRequest, + api.BatchGetDocumentsResponse >('BatchGetDocuments', path, request); const docs = new Map(); @@ -192,8 +187,8 @@ export async function invokeRunQueryRpc( const datastoreImpl = debugCast(datastore, DatastoreImpl); const request = toQueryTarget(datastoreImpl.serializer, queryToTarget(query)); const response = await datastoreImpl.invokeStreamingRPC< - ProtoRunQueryRequest, - ProtoRunQueryResponse + api.RunQueryRequest, + api.RunQueryResponse >('RunQuery', request.parent!, { structuredQuery: request.structuredQuery }); return ( response diff --git a/packages/firestore/src/remote/persistent_stream.ts b/packages/firestore/src/remote/persistent_stream.ts index b38a90db9c9..e4f32eabb69 100644 --- a/packages/firestore/src/remote/persistent_stream.ts +++ b/packages/firestore/src/remote/persistent_stream.ts @@ -20,12 +20,7 @@ import { SnapshotVersion } from '../core/snapshot_version'; import { TargetId } from '../core/types'; import { TargetData } from '../local/target_data'; import { Mutation, MutationResult } from '../model/mutation'; -import { - ListenRequest as PublicListenRequest, - ListenResponse as PublicListenResponse, - WriteRequest as PublicWriteRequest, - WriteResponse as PublicWriteResponse -} from '../protos/firestore_proto_api'; +import * as api from '../protos/firestore_proto_api'; import { debugAssert, hardAssert } from '../util/assert'; import { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue'; import { Code, FirestoreError } from '../util/error'; @@ -52,10 +47,10 @@ const LOG_TAG = 'PersistentStream'; // The generated proto interfaces for these class are missing the database // field. So we add it here. // TODO(b/36015800): Remove this once the api generator is fixed. -interface ListenRequest extends PublicListenRequest { +interface ListenRequest extends api.ListenRequest { database?: string; } -export interface WriteRequest extends PublicWriteRequest { +export interface WriteRequest extends api.WriteRequest { database?: string; } /** @@ -544,8 +539,8 @@ export interface WatchStreamListener extends PersistentStreamListener { * sent from the server for ListenResponses. */ export class PersistentListenStream extends PersistentStream< - PublicListenRequest, - PublicListenResponse, + api.ListenRequest, + api.ListenResponse, WatchStreamListener > { constructor( @@ -567,14 +562,14 @@ export class PersistentListenStream extends PersistentStream< protected startRpc( token: Token | null - ): Stream { - return this.connection.openStream< - PublicListenRequest, - PublicListenResponse - >('Listen', token); + ): Stream { + return this.connection.openStream( + 'Listen', + token + ); } - protected onMessage(watchChangeProto: PublicListenResponse): Promise { + protected onMessage(watchChangeProto: api.ListenResponse): Promise { // A successful response means the stream is healthy this.backoff.reset(); @@ -650,8 +645,8 @@ export interface WriteStreamListener extends PersistentStreamListener { * TODO(b/33271235): Use proto types */ export class PersistentWriteStream extends PersistentStream< - PublicWriteRequest, - PublicWriteResponse, + api.WriteRequest, + api.WriteResponse, WriteStreamListener > { private handshakeComplete_ = false; @@ -706,14 +701,14 @@ export class PersistentWriteStream extends PersistentStream< protected startRpc( token: Token | null - ): Stream { - return this.connection.openStream( + ): Stream { + return this.connection.openStream( 'Write', token ); } - protected onMessage(responseProto: PublicWriteResponse): Promise { + protected onMessage(responseProto: api.WriteResponse): Promise { // Always capture the last stream token. hardAssert( !!responseProto.streamToken, diff --git a/packages/firestore/src/remote/serializer.ts b/packages/firestore/src/remote/serializer.ts index f4c1088d324..6095e13e760 100644 --- a/packages/firestore/src/remote/serializer.ts +++ b/packages/firestore/src/remote/serializer.ts @@ -50,28 +50,7 @@ import { VerifyMutation } from '../model/mutation'; import { FieldPath, ResourcePath } from '../model/path'; -import { - DocumentMask as ProtoDocumentMask, - Target as ProtoTarget, - FieldReference as ProtoFieldReference, - ApiClientObjectMap as ProtoApiClientObjectMap, - FieldTransform as ProtoFieldTransform, - Precondition as ProtoPrecondition, - Filter as ProtoFilter, - ListenResponse as ProtoListenResponse, - BatchGetDocumentsResponse as ProtoBatchGetDocumentsResponse, - OrderDirection as ProtoOrderDirection, - Order as ProtoOrder, - DocumentsTarget as ProtoDocumentsTarget, - QueryTarget as ProtoQueryTarget, - FieldFilterOp as ProtoFieldFilterOp, - Status as ProtoStatus, - Value as ProtoValue, - Timestamp as ProtoTimestamp, - Document as ProtoDocument, - Write as ProtoWrite, - Cursor as ProtoCursor -} from '../protos/firestore_proto_api'; +import * as api from '../protos/firestore_proto_api'; import { debugAssert, fail, hardAssert } from '../util/assert'; import { Code, FirestoreError } from '../util/error'; import { ByteString } from '../util/byte_string'; @@ -103,14 +82,14 @@ import { } from '../protos/firestore_proto_api'; const DIRECTIONS = (() => { - const dirs: { [dir: string]: ProtoOrderDirection } = {}; + const dirs: { [dir: string]: api.OrderDirection } = {}; dirs[Direction.ASCENDING] = 'ASCENDING'; dirs[Direction.DESCENDING] = 'DESCENDING'; return dirs; })(); const OPERATORS = (() => { - const ops: { [op: string]: ProtoFieldFilterOp } = {}; + const ops: { [op: string]: api.FieldFilterOp } = {}; ops[Operator.LESS_THAN] = 'LESS_THAN'; ops[Operator.LESS_THAN_OR_EQUAL] = 'LESS_THAN_OR_EQUAL'; ops[Operator.GREATER_THAN] = 'GREATER_THAN'; @@ -130,7 +109,7 @@ function assertPresent(value: unknown, description: string): asserts value { /** * This class generates JsonObject values for the Datastore API suitable for - * sending to either GRPC stub methods or via the JSON/HTTP REST Proto + * sending to either GRPC stub methods or via the JSON/HTTP REST API. * * The serializer supports both Protobuf.js and Proto3 JSON formats. By * setting `useProto3Json` to true, the serializer will use the Proto3 JSON @@ -149,7 +128,7 @@ export class JsonProtoSerializer { ) {} } -function fromRpcStatus(status: ProtoStatus): FirestoreError { +function fromRpcStatus(status: api.Status): FirestoreError { const code = status.code === undefined ? Code.UNKNOWN : mapCodeFromRpcCode(status.code); return new FirestoreError(code, status.message || ''); @@ -192,7 +171,7 @@ function fromInt32Proto( /** * Returns an IntegerValue for `value`. */ -export function toInteger(value: number): ProtoValue { +export function toInteger(value: number): api.Value { return { integerValue: '' + value }; } @@ -203,7 +182,7 @@ export function toInteger(value: number): ProtoValue { export function toDouble( serializer: JsonProtoSerializer, value: number -): ProtoValue { +): api.Value { if (serializer.useProto3Json) { if (isNaN(value)) { return { doubleValue: 'NaN' }; @@ -224,7 +203,7 @@ export function toDouble( export function toNumber( serializer: JsonProtoSerializer, value: number -): ProtoValue { +): api.Value { return isSafeInteger(value) ? toInteger(value) : toDouble(serializer, value); } @@ -234,7 +213,7 @@ export function toNumber( export function toTimestamp( serializer: JsonProtoSerializer, timestamp: Timestamp -): ProtoTimestamp { +): api.Timestamp { if (serializer.useProto3Json) { // Serialize to ISO-8601 date format, but with full nano resolution. // Since JS Date has only millis, let's only use it for the seconds and @@ -255,7 +234,7 @@ export function toTimestamp( } } -function fromTimestamp(date: ProtoTimestamp): Timestamp { +function fromTimestamp(date: api.Timestamp): Timestamp { const timestamp = normalizeTimestamp(date); return new Timestamp(timestamp.seconds, timestamp.nanos); } @@ -301,11 +280,11 @@ export function fromBytes( export function toVersion( serializer: JsonProtoSerializer, version: SnapshotVersion -): ProtoTimestamp { +): api.Timestamp { return toTimestamp(serializer, version.toTimestamp()); } -export function fromVersion(version: ProtoTimestamp): SnapshotVersion { +export function fromVersion(version: api.Timestamp): SnapshotVersion { hardAssert(!!version, "Trying to deserialize version that isn't set"); return SnapshotVersion.fromTimestamp(fromTimestamp(version)); } @@ -407,12 +386,12 @@ function extractLocalPathFromResourceName( return resourceName.popFirst(5); } -/** Creates an ProtoDocument from key and fields (but no create/update time) */ +/** Creates an api.Document from key and fields (but no create/update time) */ export function toMutationDocument( serializer: JsonProtoSerializer, key: DocumentKey, fields: ObjectValue -): ProtoDocument { +): api.Document { return { name: toName(serializer, key), fields: fields.proto.mapValue.fields @@ -422,7 +401,7 @@ export function toMutationDocument( export function toDocument( serializer: JsonProtoSerializer, document: Document -): ProtoDocument { +): api.Document { debugAssert( !document.hasLocalMutations, "Can't serialize documents with mutations." @@ -436,7 +415,7 @@ export function toDocument( export function fromDocument( serializer: JsonProtoSerializer, - document: ProtoDocument, + document: api.Document, hasCommittedMutations?: boolean ): Document { const key = fromName(serializer, document.name!); @@ -449,7 +428,7 @@ export function fromDocument( function fromFound( serializer: JsonProtoSerializer, - doc: ProtoBatchGetDocumentsResponse + doc: api.BatchGetDocumentsResponse ): Document { hardAssert( !!doc.found, @@ -465,7 +444,7 @@ function fromFound( function fromMissing( serializer: JsonProtoSerializer, - result: ProtoBatchGetDocumentsResponse + result: api.BatchGetDocumentsResponse ): NoDocument { hardAssert( !!result.missing, @@ -482,7 +461,7 @@ function fromMissing( export function fromMaybeDocument( serializer: JsonProtoSerializer, - result: ProtoBatchGetDocumentsResponse + result: api.BatchGetDocumentsResponse ): MaybeDocument { if ('found' in result) { return fromFound(serializer, result); @@ -494,7 +473,7 @@ export function fromMaybeDocument( export function fromWatchChange( serializer: JsonProtoSerializer, - change: ProtoListenResponse + change: api.ListenResponse ): WatchChange { let watchChange: WatchChange; if ('targetChange' in change) { @@ -590,7 +569,7 @@ function fromWatchTargetChangeState( } export function versionFromListenResponse( - change: ProtoListenResponse + change: api.ListenResponse ): SnapshotVersion { // We have only reached a consistent snapshot for the entire stream if there // is a read_time set and it applies to all targets (i.e. the list of @@ -611,8 +590,8 @@ export function versionFromListenResponse( export function toMutation( serializer: JsonProtoSerializer, mutation: Mutation -): ProtoWrite { - let result: ProtoWrite; +): api.Write { + let result: api.Write; if (mutation instanceof SetMutation) { result = { update: toMutationDocument(serializer, mutation.key, mutation.value) @@ -650,7 +629,7 @@ export function toMutation( export function fromMutation( serializer: JsonProtoSerializer, - proto: ProtoWrite + proto: api.Write ): Mutation { const precondition = proto.currentDocument ? fromPrecondition(proto.currentDocument) @@ -692,7 +671,7 @@ export function fromMutation( function toPrecondition( serializer: JsonProtoSerializer, precondition: Precondition -): ProtoPrecondition { +): api.Precondition { debugAssert(!precondition.isNone, "Can't serialize an empty precondition"); if (precondition.updateTime !== undefined) { return { @@ -705,7 +684,7 @@ function toPrecondition( } } -function fromPrecondition(precondition: ProtoPrecondition): Precondition { +function fromPrecondition(precondition: api.Precondition): Precondition { if (precondition.updateTime !== undefined) { return Precondition.updateTime(fromVersion(precondition.updateTime)); } else if (precondition.exists !== undefined) { @@ -717,7 +696,7 @@ function fromPrecondition(precondition: ProtoPrecondition): Precondition { function fromWriteResult( proto: WriteResult, - commitTime: ProtoTimestamp + commitTime: api.Timestamp ): MutationResult { // NOTE: Deletes don't have an updateTime. let version = proto.updateTime @@ -733,7 +712,7 @@ function fromWriteResult( version = fromVersion(commitTime); } - let transformResults: ProtoValue[] | null = null; + let transformResults: api.Value[] | null = null; if (proto.transformResults && proto.transformResults.length > 0) { transformResults = proto.transformResults; } @@ -742,7 +721,7 @@ function fromWriteResult( export function fromWriteResults( protos: WriteResult[] | undefined, - commitTime?: ProtoTimestamp + commitTime?: api.Timestamp ): MutationResult[] { if (protos && protos.length > 0) { hardAssert( @@ -758,7 +737,7 @@ export function fromWriteResults( function toFieldTransform( serializer: JsonProtoSerializer, fieldTransform: FieldTransform -): ProtoFieldTransform { +): api.FieldTransform { const transform = fieldTransform.transform; if (transform instanceof ServerTimestampTransform) { return { @@ -791,7 +770,7 @@ function toFieldTransform( function fromFieldTransform( serializer: JsonProtoSerializer, - proto: ProtoFieldTransform + proto: api.FieldTransform ): FieldTransform { let transform: TransformOperation | null = null; if ('setToServerValue' in proto) { @@ -821,12 +800,12 @@ function fromFieldTransform( export function toDocumentsTarget( serializer: JsonProtoSerializer, target: Target -): ProtoDocumentsTarget { +): api.DocumentsTarget { return { documents: [toQueryPath(serializer, target.path)] }; } export function fromDocumentsTarget( - documentsTarget: ProtoDocumentsTarget + documentsTarget: api.DocumentsTarget ): Target { const count = documentsTarget.documents!.length; hardAssert( @@ -840,9 +819,9 @@ export function fromDocumentsTarget( export function toQueryTarget( serializer: JsonProtoSerializer, target: Target -): ProtoQueryTarget { +): api.QueryTarget { // Dissect the path into parent, collectionId, and optional key filter. - const result: ProtoQueryTarget = { structuredQuery: {} }; + const result: api.QueryTarget = { structuredQuery: {} }; const path = target.path; if (target.collectionGroup !== null) { debugAssert( @@ -890,7 +869,7 @@ export function toQueryTarget( return result; } -export function fromQueryTarget(target: ProtoQueryTarget): Target { +export function fromQueryTarget(target: api.QueryTarget): Target { let path = fromQueryPath(target.parent!); const query = target.structuredQuery!; @@ -951,7 +930,7 @@ export function fromQueryTarget(target: ProtoQueryTarget): Target { export function toListenRequestLabels( serializer: JsonProtoSerializer, targetData: TargetData -): ProtoApiClientObjectMap | null { +): api.ApiClientObjectMap | null { const value = toLabel(serializer, targetData.purpose); if (value == null) { return null; @@ -981,8 +960,8 @@ function toLabel( export function toTarget( serializer: JsonProtoSerializer, targetData: TargetData -): ProtoTarget { - let result: ProtoTarget; +): api.Target { + let result: api.Target; const target = targetData.target; if (isDocumentTarget(target)) { @@ -1000,7 +979,7 @@ export function toTarget( return result; } -function toFilter(filters: Filter[]): ProtoFilter | undefined { +function toFilter(filters: Filter[]): api.Filter | undefined { if (filters.length === 0) { return; } @@ -1017,7 +996,7 @@ function toFilter(filters: Filter[]): ProtoFilter | undefined { return { compositeFilter: { op: 'AND', filters: protos } }; } -function fromFilter(filter: ProtoFilter | undefined): Filter[] { +function fromFilter(filter: api.Filter | undefined): Filter[] { if (!filter) { return []; } else if (filter.unaryFilter !== undefined) { @@ -1033,38 +1012,38 @@ function fromFilter(filter: ProtoFilter | undefined): Filter[] { } } -function toOrder(orderBys: OrderBy[]): ProtoOrder[] | undefined { +function toOrder(orderBys: OrderBy[]): api.Order[] | undefined { if (orderBys.length === 0) { return; } return orderBys.map(order => toPropertyOrder(order)); } -function fromOrder(orderBys: ProtoOrder[]): OrderBy[] { +function fromOrder(orderBys: api.Order[]): OrderBy[] { return orderBys.map(order => fromPropertyOrder(order)); } -function toCursor(cursor: Bound): ProtoCursor { +function toCursor(cursor: Bound): api.Cursor { return { before: cursor.before, values: cursor.position }; } -function fromCursor(cursor: ProtoCursor): Bound { +function fromCursor(cursor: api.Cursor): Bound { const before = !!cursor.before; const position = cursor.values || []; return new Bound(position, before); } // visible for testing -export function toDirection(dir: Direction): ProtoOrderDirection { +export function toDirection(dir: Direction): api.OrderDirection { return DIRECTIONS[dir]; } // visible for testing export function fromDirection( - dir: ProtoOrderDirection | undefined + dir: api.OrderDirection | undefined ): Direction | undefined { switch (dir) { case 'ASCENDING': @@ -1077,11 +1056,11 @@ export function fromDirection( } // visible for testing -export function toOperatorName(op: Operator): ProtoFieldFilterOp { +export function toOperatorName(op: Operator): api.FieldFilterOp { return OPERATORS[op]; } -export function fromOperatorName(op: ProtoFieldFilterOp): Operator { +export function fromOperatorName(op: api.FieldFilterOp): Operator { switch (op) { case 'EQUAL': return Operator.EQUAL; @@ -1110,32 +1089,32 @@ export function fromOperatorName(op: ProtoFieldFilterOp): Operator { } } -export function toFieldPathReference(path: FieldPath): ProtoFieldReference { +export function toFieldPathReference(path: FieldPath): api.FieldReference { return { fieldPath: path.canonicalString() }; } export function fromFieldPathReference( - fieldReference: ProtoFieldReference + fieldReference: api.FieldReference ): FieldPath { return FieldPath.fromServerFormat(fieldReference.fieldPath!); } // visible for testing -export function toPropertyOrder(orderBy: OrderBy): ProtoOrder { +export function toPropertyOrder(orderBy: OrderBy): api.Order { return { field: toFieldPathReference(orderBy.field), direction: toDirection(orderBy.dir) }; } -export function fromPropertyOrder(orderBy: ProtoOrder): OrderBy { +export function fromPropertyOrder(orderBy: api.Order): OrderBy { return new OrderBy( fromFieldPathReference(orderBy.field!), fromDirection(orderBy.direction) ); } -export function fromFieldFilter(filter: ProtoFilter): Filter { +export function fromFieldFilter(filter: api.Filter): Filter { return FieldFilter.create( fromFieldPathReference(filter.fieldFilter!.field!), fromOperatorName(filter.fieldFilter!.op!), @@ -1144,7 +1123,7 @@ export function fromFieldFilter(filter: ProtoFilter): Filter { } // visible for testing -export function toUnaryOrFieldFilter(filter: FieldFilter): ProtoFilter { +export function toUnaryOrFieldFilter(filter: FieldFilter): api.Filter { if (filter.op === Operator.EQUAL) { if (isNanValue(filter.value)) { return { @@ -1187,7 +1166,7 @@ export function toUnaryOrFieldFilter(filter: FieldFilter): ProtoFilter { }; } -export function fromUnaryFilter(filter: ProtoFilter): Filter { +export function fromUnaryFilter(filter: api.Filter): Filter { switch (filter.unaryFilter!.op!) { case 'IS_NAN': const nanField = fromFieldPathReference(filter.unaryFilter!.field!); @@ -1216,7 +1195,7 @@ export function fromUnaryFilter(filter: ProtoFilter): Filter { } } -export function toDocumentMask(fieldMask: FieldMask): ProtoDocumentMask { +export function toDocumentMask(fieldMask: FieldMask): api.DocumentMask { const canonicalFields: string[] = []; fieldMask.fields.forEach(field => canonicalFields.push(field.canonicalString()) @@ -1226,7 +1205,7 @@ export function toDocumentMask(fieldMask: FieldMask): ProtoDocumentMask { }; } -export function fromDocumentMask(proto: ProtoDocumentMask): FieldMask { +export function fromDocumentMask(proto: api.DocumentMask): FieldMask { const paths = proto.fieldPaths || []; return new FieldMask(paths.map(path => FieldPath.fromServerFormat(path))); } diff --git a/packages/firestore/src/util/error.ts b/packages/firestore/src/util/error.ts index 7fb11dc46a2..ac031e5b51b 100644 --- a/packages/firestore/src/util/error.ts +++ b/packages/firestore/src/util/error.ts @@ -15,16 +15,13 @@ * limitations under the License. */ -import { - FirestoreError as PublicFirestoreError, - FirestoreErrorCode as PublicFirestoreErrorCode -} from '@firebase/firestore-types'; +import * as firestore from '@firebase/firestore-types'; /** * Error Codes describing the different ways Firestore can fail. These come * directly from GRPC. */ -export type Code = PublicFirestoreErrorCode; +export type Code = firestore.FirestoreErrorCode; export const Code = { // Causes are copied from: @@ -161,7 +158,7 @@ export const Code = { * so we define our own compatible error class (with a `name` of 'FirebaseError' * and compatible `code` and `message` fields.) */ -export class FirestoreError extends Error implements PublicFirestoreError { +export class FirestoreError extends Error implements firestore.FirestoreError { name = 'FirebaseError'; stack?: string; diff --git a/yarn.lock b/yarn.lock index 40a70e075f0..6b1eb4c85b3 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2097,6 +2097,14 @@ js-yaml "~3.13.1" resolve "~1.17.0" +"@microsoft/api-extractor-model@7.8.0": + version "7.8.0" + resolved "https://registry.npmjs.org/@microsoft/api-extractor-model/-/api-extractor-model-7.8.0.tgz#5f532998f01109f23d57b422803bbdf5ad655d80" + integrity sha512-rk3n2GJ2DyKsmKmSK0VYN92ZAWPgc5+zBLbGASpty3pBZBuByJ0ioZdkxbtm5gaeurJzsG9DFTPCmpg/+Mt/nw== + dependencies: + "@microsoft/tsdoc" "0.12.19" + "@rushstack/node-core-library" "3.19.7" + "@microsoft/api-extractor-model@7.8.12": version "7.8.12" resolved "https://registry.npmjs.org/@microsoft/api-extractor-model/-/api-extractor-model-7.8.12.tgz#d089193ef29275b8b20802498c6bdfab80dcef59" @@ -2105,21 +2113,20 @@ "@microsoft/tsdoc" "0.12.19" "@rushstack/node-core-library" "3.25.0" -"@microsoft/api-extractor@7.9.2": - version "7.9.2" - resolved "https://registry.npmjs.org/@microsoft/api-extractor/-/api-extractor-7.9.2.tgz#3bb8c93f4280fcb94171e4214d714e1639f4fbd4" - integrity sha512-R4b3zXlYdicoS8bRLXEChTKLPyhUHrG1cb0GDtOX0zdoxlovU1p0JaPt97A/vC7N3Gm2E8gd2qsDWElKU3/wKQ== +"@microsoft/api-extractor@7.8.2-pr1796.0": + version "7.8.2-pr1796.0" + resolved "https://registry.npmjs.org/@microsoft/api-extractor/-/api-extractor-7.8.2-pr1796.0.tgz#1a174168c7a9a07d9c1790508fc71331ee36a8fe" + integrity sha512-Yc22e1j3TTJezL805KCSiuegjCdi24AXaEjGDSox2kF2X4VIGdrwRnCv5LPOVp0SbEDq13aPTVwby9y+A+OMCg== dependencies: - "@microsoft/api-extractor-model" "7.8.12" + "@microsoft/api-extractor-model" "7.8.0" "@microsoft/tsdoc" "0.12.19" - "@rushstack/node-core-library" "3.25.0" - "@rushstack/ts-command-line" "4.4.6" + "@rushstack/node-core-library" "3.19.7" + "@rushstack/ts-command-line" "4.4.0" colors "~1.2.1" lodash "~4.17.15" - resolve "~1.17.0" - semver "~7.3.0" + resolve "1.8.1" source-map "~0.6.1" - typescript "~3.9.5" + typescript "~3.7.2" "@microsoft/tsdoc@0.12.19": version "0.12.19" @@ -2338,6 +2345,19 @@ estree-walker "^1.0.1" picomatch "^2.2.2" +"@rushstack/node-core-library@3.19.7": + version "3.19.7" + resolved "https://registry.npmjs.org/@rushstack/node-core-library/-/node-core-library-3.19.7.tgz#8d8a193fd6f99536c92dd797ab50fd5fcb7630ea" + integrity sha512-gKE/OXH5GAj8yJ1kEyRW68UekJernilZ3QTRgmQ0MUHBCQmtZ9Q6T5PQ1sVbcL4teH8BMdpZeFy1DKnHs8h3PA== + dependencies: + "@types/node" "10.17.13" + colors "~1.2.1" + fs-extra "~7.0.1" + jju "~1.4.0" + semver "~5.3.0" + timsort "~0.3.0" + z-schema "~3.18.3" + "@rushstack/node-core-library@3.25.0": version "3.25.0" resolved "https://registry.npmjs.org/@rushstack/node-core-library/-/node-core-library-3.25.0.tgz#ba40bc1b188ab5d31f5705999cd2b3b56b8a32cf" @@ -2351,6 +2371,15 @@ timsort "~0.3.0" z-schema "~3.18.3" +"@rushstack/ts-command-line@4.4.0": + version "4.4.0" + resolved "https://registry.npmjs.org/@rushstack/ts-command-line/-/ts-command-line-4.4.0.tgz#796f24681fdcbd01d463278c9e80a51ea5f73b2b" + integrity sha512-AYRICJg9Cwz+IBo1+leG0MtHx2uVScEs5P5ZNW3oocKekN6oLZvM1SNxghB7EXJzmYHnEMvCGhQx0Ll4oEkIyQ== + dependencies: + "@types/argparse" "1.0.38" + argparse "~1.0.9" + colors "~1.2.1" + "@rushstack/ts-command-line@4.4.6": version "4.4.6" resolved "https://registry.npmjs.org/@rushstack/ts-command-line/-/ts-command-line-4.4.6.tgz#7818f19e444274e68564a756ef62a2b4e0ced0f8" @@ -12289,7 +12318,7 @@ path-key@^3.0.0, path-key@^3.1.0: resolved "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz#581f6ade658cbba65a0d3380de7753295054f375" integrity sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q== -path-parse@^1.0.6: +path-parse@^1.0.5, path-parse@^1.0.6: version "1.0.6" resolved "https://registry.npmjs.org/path-parse/-/path-parse-1.0.6.tgz#d62dbb5679405d72c4737ec58600e9ddcf06d24c" integrity sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw== @@ -13340,6 +13369,13 @@ resolve@1.15.1: dependencies: path-parse "^1.0.6" +resolve@1.8.1: + version "1.8.1" + resolved "https://registry.npmjs.org/resolve/-/resolve-1.8.1.tgz#82f1ec19a423ac1fbd080b0bab06ba36e84a7a26" + integrity sha512-AicPrAC7Qu1JxPCZ9ZgCZlY35QgFnNqc+0LtbRNxnVw4TXvjQ72wnuL9JQcEBgXkI9JM8MsT9kaQoHcpCRJOYA== + dependencies: + path-parse "^1.0.5" + resolve@^1.1.4, resolve@^1.1.6, resolve@^1.1.7, resolve@^1.10.0, resolve@^1.11.0, resolve@^1.11.1, resolve@^1.13.1, resolve@^1.17.0, resolve@^1.3.2, resolve@^1.3.3, resolve@^1.4.0, resolve@~1.17.0: version "1.17.0" resolved "https://registry.npmjs.org/resolve/-/resolve-1.17.0.tgz#b25941b54968231cc2d1bb76a79cb7f2c0bf8444" @@ -13769,6 +13805,11 @@ semver@^6.0.0, semver@^6.2.0, semver@^6.3.0: resolved "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz#ee0a64c8af5e8ceea67687b133761e1becbd1d3d" integrity sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw== +semver@~5.3.0: + version "5.3.0" + resolved "https://registry.npmjs.org/semver/-/semver-5.3.0.tgz#9b2ce5d3de02d17c6012ad326aa6b4d0cf54f94f" + integrity sha1-myzl094C0XxgEq0yaqa00M9U+U8= + send@0.17.1: version "0.17.1" resolved "https://registry.npmjs.org/send/-/send-0.17.1.tgz#c1d8b059f7900f7466dd4938bdc44e11ddb376c8" @@ -15388,12 +15429,12 @@ typedoc@0.16.11: typedoc-default-themes "^0.7.2" typescript "3.7.x" -typescript@3.7.x: +typescript@3.7.x, typescript@~3.7.2: version "3.7.5" resolved "https://registry.npmjs.org/typescript/-/typescript-3.7.5.tgz#0692e21f65fd4108b9330238aac11dd2e177a1ae" integrity sha512-/P5lkRXkWHNAbcJIiHPfRoKqyd7bsyCma1hZNUGfn20qm64T6ZBlrzprymeu918H+mB/0rIg2gGK/BXkhhYgBw== -typescript@3.9.7, typescript@~3.9.5: +typescript@3.9.7: version "3.9.7" resolved "https://registry.npmjs.org/typescript/-/typescript-3.9.7.tgz#98d600a5ebdc38f40cb277522f12dc800e9e25fa" integrity sha512-BLbiRkiBzAwsjut4x/dsibSTB6yWpwT5qWmC2OfuCg3GgVQCSgMs4vEctYPhsaGtd0AeuuHMkjZ2h2WG8MSzRw==