{"version":3,"sources":["webpack:///firebase-firestore.js","webpack:///./firestore/index.js","webpack:///../firestore/dist/esm/src/util/log.js","webpack:///../firestore/dist/esm/src/util/assert.js","webpack:///../firestore/dist/esm/src/platform/platform.js","webpack:///../firestore/dist/esm/src/util/api.js","webpack:///../firestore/dist/esm/src/util/obj.js","webpack:///../firestore/dist/esm/src/util/input_validation.js","webpack:///../firestore/dist/esm/src/util/misc.js","webpack:///../firestore/dist/esm/src/api/blob.js","webpack:///../firestore/dist/esm/src/model/field_value.js","webpack:///../firestore/dist/esm/src/util/types.js","webpack:///../firestore/dist/esm/src/core/query.js","webpack:///../firestore/dist/esm/src/remote/rpc_error.js","webpack:///../firestore/dist/esm/src/model/collections.js","webpack:///../firestore/dist/esm/src/remote/watch_change.js","webpack:///../firestore/dist/esm/src/remote/serializer.js","webpack:///../firestore/dist/esm/src/api/field_path.js","webpack:///../firestore/dist/esm/src/core/view.js","webpack:///../firestore/dist/esm/src/local/encoded_resource_path.js","webpack:///../firestore/dist/esm/src/local/indexeddb_schema.js","webpack:///../firestore/dist/esm/src/local/simple_db.js","webpack:///../firestore/dist/esm/src/local/indexeddb_mutation_queue.js","webpack:///../firestore/dist/esm/src/local/indexeddb_query_cache.js","webpack:///../firestore/dist/esm/src/local/indexeddb_remote_document_cache.js","webpack:///../firestore/dist/esm/src/local/local_serializer.js","webpack:///../firestore/dist/esm/src/api/credentials.js","webpack:///../firestore/dist/esm/src/api/observer.js","webpack:///../firestore/dist/esm/src/api/user_data_converter.js","webpack:///../firestore/dist/esm/src/api/database.js","webpack:///../firestore/dist/esm/src/platform/config.js","webpack:///../firestore/dist/esm/index.js","webpack:///../firestore/dist/esm/src/core/version.js","webpack:///../firestore/dist/esm/src/util/error.js","webpack:///../firestore/dist/esm/src/api/geo_point.js","webpack:///../firestore/dist/esm/src/core/database_info.js","webpack:///../firestore/dist/esm/src/model/path.js","webpack:///../firestore/dist/esm/src/model/document_key.js","webpack:///../firestore/dist/esm/src/model/document.js","webpack:///../firestore/dist/esm/src/util/sorted_map.js","webpack:///../firestore/dist/esm/src/local/query_data.js","webpack:///../firestore/dist/esm/src/core/timestamp.js","webpack:///../firestore/dist/esm/src/core/snapshot_version.js","webpack:///../firestore/dist/esm/src/model/mutation.js","webpack:///../firestore/dist/esm/src/remote/existence_filter.js","webpack:///../firestore/dist/esm/src/util/sorted_set.js","webpack:///../firestore/dist/esm/src/remote/remote_event.js","webpack:///../firestore/dist/esm/src/remote/stream_bridge.js","webpack:///../firestore/dist/esm/src/platform_browser/webchannel_connection.js","webpack:///../firestore/dist/esm/src/platform_browser/browser_platform.js","webpack:///../firestore/dist/esm/src/platform_browser/browser_init.js","webpack:///../firestore/dist/esm/src/core/types.js","webpack:///../firestore/dist/esm/src/core/view_snapshot.js","webpack:///../firestore/dist/esm/src/core/target_id_generator.js","webpack:///../firestore/dist/esm/src/model/document_set.js","webpack:///../firestore/dist/esm/src/util/obj_map.js","webpack:///../firestore/dist/esm/src/core/event_manager.js","webpack:///../firestore/dist/esm/src/local/persistence_promise.js","webpack:///../firestore/dist/esm/src/local/eager_garbage_collector.js","webpack:///../firestore/dist/esm/src/local/local_view_changes.js","webpack:///../firestore/dist/esm/src/local/reference_set.js","webpack:///../firestore/dist/esm/src/remote/persistent_stream.js","webpack:///../firestore/dist/esm/src/core/sync_engine.js","webpack:///../firestore/dist/esm/src/model/mutation_batch.js","webpack:///../firestore/dist/esm/src/local/indexeddb_persistence.js","webpack:///../firestore/dist/esm/src/local/local_documents_view.js","webpack:///../firestore/dist/esm/src/local/remote_document_change_buffer.js","webpack:///../firestore/dist/esm/src/local/local_store.js","webpack:///../firestore/dist/esm/src/local/memory_mutation_queue.js","webpack:///../firestore/dist/esm/src/local/memory_query_cache.js","webpack:///../firestore/dist/esm/src/local/memory_remote_document_cache.js","webpack:///../firestore/dist/esm/src/local/memory_persistence.js","webpack:///../firestore/dist/esm/src/local/no_op_garbage_collector.js","webpack:///../firestore/dist/esm/src/util/promise.js","webpack:///../firestore/dist/esm/src/remote/backoff.js","webpack:///../firestore/dist/esm/src/remote/datastore.js","webpack:///../firestore/dist/esm/src/core/transaction.js","webpack:///../firestore/dist/esm/src/remote/remote_store.js","webpack:///../firestore/dist/esm/src/core/firestore_client.js","webpack:///../firestore/dist/esm/src/util/async_observer.js","webpack:///../firestore/dist/esm/src/util/async_queue.js","webpack:///../firestore/dist/esm/src/auth/user.js","webpack:///../firestore/dist/esm/src/api/field_value.js","webpack:///../webchannel-wrapper/dist/index.js"],"names":["webpackJsonpFirebase","113","module","exports","__webpack_require__","114","__webpack_exports__","getLogLevel","logLevel","setLogLevel","newLevel","debug","tag","msg","obj","_i","arguments","length","LogLevel","DEBUG","time","Date","toISOString","args","map","argToString","console","log","apply","SDK_VERSION","concat","log_error","ERROR","error","platform","platform_PlatformSupport","getPlatform","formatJSON","e","fail","failure","message","Error","assert","assertion","emptyByteString","makeConstructorPrivate","cls","optionalMessage","PublicConstructor","FirestoreError","Code","INVALID_ARGUMENT","prototype","staticProperty","hasOwnProperty","contains","key","Object","call","defaulted","value","defaultValue","undefined","forEachNumber","fn","num","isNaN","forEach","isEmpty","shallowCopy","result","validateExactNumberOfArgs","functionName","numberOfArgs","formatPlural","validateAtLeastNumberOfArgs","minNumberOfArgs","validateBetweenNumberOfArgs","maxNumberOfArgs","validateNamedArrayAtLeastNumberOfElements","name","minNumberOfElements","Array","validateArgType","type","position","argument","validateType","ordinal","validateOptionalArgType","validateNamedType","optionName","validateNamedOptionalType","validateNamedPropertyEquals","inputName","input","expected","expectedDescription","expected_1","val","push","valueDescription","actualDescription","join","validateNamedOptionalPropertyEquals","isPlainObject","description","getPrototypeOf","substring","JSON","stringify","customObjectName","tryGetCustomObjectType","constructor","funcNameRegex","results","exec","validateDefined","validateOptionNames","options","optionNames","_","indexOf","invalidClassError","str","primitiveComparator","left","right","equals","isEqual","arrayEquals","i","immediatePredecessor","s","lastIndex","charAt","String","fromCharCode","charCodeAt","immediateSuccessor","assertUint8ArrayAvailable","Uint8Array","UNIMPLEMENTED","assertBase64Available","base64Available","numericComparator","numericEquals","isNullOrUndefined","isSafeInteger","isInteger","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","fieldFilter","field","op","NullValue","INSTANCE","query_RelationOp","EQUAL","NullFilter","DoubleValue","NAN","NanFilter","query_RelationFilter","isPermanentError","code","OK","CANCELLED","UNKNOWN","DEADLINE_EXCEEDED","RESOURCE_EXHAUSTED","INTERNAL","UNAVAILABLE","UNAUTHENTICATED","NOT_FOUND","ALREADY_EXISTS","PERMISSION_DENIED","FAILED_PRECONDITION","ABORTED","OUT_OF_RANGE","DATA_LOSS","mapCodeFromRpcStatus","status","RpcCode","mapCodeFromRpcCode","mapRpcCodeFromCode","mapCodeFromHttpStatus","maybeDocumentMap","EMPTY_MAYBE_DOCUMENT_MAP","documentMap","EMPTY_DOCUMENT_MAP","documentVersionMap","EMPTY_DOCUMENT_VERSION_MAP","documentKeySet","EMPTY_DOCUMENT_KEY_SET","applyResumeToken","change","resumeToken","assertPresent","parseInt64","hasTag","fromDotSeparatedString","path","search","RESERVED","field_path_FieldPath","bind","split","compareChangeType","c1","c2","order","ChangeType","Added","Modified","Metadata","Removed","encode","encodeSeparator","encodeSegment","get","segment","resultBuf","c","escapeChar","encodedNul","encodedEscape","encodedSeparatorChar","decode","path_ResourcePath","EMPTY_PATH","lastReasonableEscapeIndex","segments","segmentBuilder","start","end","currentPiece","createOrUpgradeDb","db","oldVersion","createObjectStore","DbMutationQueue","store","keyPath","DbMutationBatch","DbTargetDocument","createIndex","documentTargetsIndex","documentTargetsKeyPath","unique","DbTarget","queryTargetsIndexName","queryTargetsKeyPath","indexeddb_schema_DbDocumentMutation","DbRemoteDocument","DbOwner","DbTargetGlobal","wrapRequest","request","persistence_promise_PersistencePromise","resolve","reject","onsuccess","event","target","onerror","validateStreamToken","token","mutationsStore","txn","getStore","documentMutationsStore","mutationQueuesStore","simple_db_SimpleDbTransaction","targetsStore","indexeddb_query_cache_getStore","globalTargetStore","documentTargetStore","remoteDocumentsStore","dbKey","docKey","toArray","isDocumentQuery","dbQuery","documents","makeCredentialsProvider","credentials","credentials_EmptyCredentialsProvider","credentials_FirstPartyCredentialsProvider","client","sessionIndex","isPartialObserver","implementsAnyMethods","methods","object","methods_1","method","isWrite","dataSource","UserDataSource","Set","MergeSet","Update","QueryValue","looksLikeJsonObject","geo_point_GeoPoint","blob_Blob","DocumentKeyReference","FieldValueImpl","validatePlainObject","context","createError","fieldPathFromArgument","methodName","_internalPath","fieldPathFromDotSeparatedString","errorMessage","validateSetOptions","merge","validateSnapshotOptions","serverTimestamps","validateReference","documentRef","firestore","database_DocumentReference","changesFromSnapshot","snapshot","oldDocs","lastDoc_1","index_1","docChanges","doc","database_QueryDocumentSnapshot","fromCache","query","docComparator","oldIndex","newIndex","indexTracker_1","delete","add","resultChangeType","configureForFirebase","firebase","registerService","app","database_Firestore","firestoreNamespace","registerFirestore","instance","defineProperty","esm","PlatformSupport","setPlatform","__extends","this","extendStatics","setPrototypeOf","__proto__","d","b","p","__","create","_super","_this","toString","misc_AutoId","AutoId","newId","chars","autoId","Math","floor","random","Blob","binaryString","_binaryString","fromBase64String","base64","atob","fromUint8Array","array","char","toBase64","btoa","toUint8Array","buffer","other","_compareTo","PublicBlob","GeoPoint","latitude","longitude","isFinite","_lat","_long","enumerable","configurable","DatabaseInfo","databaseId","persistenceKey","host","ssl","DEFAULT_DATABASE_NAME","database_info_DatabaseId","DatabaseId","projectId","database","compareTo","path___extends","path_Path","Path","offset","init","len","construct","comparator","child","nameOrPath","slice","limit","popFirst","size","popLast","firstSegment","lastSegment","index","isPrefixOf","p1","p2","min","ResourcePath","canonicalString","fromString","filter","identifierRegExp","path_FieldPath","FieldPath","isValidIdentifier","test","replace","isKeyField","keyField","fromServerFormat","current","addCurrentSegment","inBackticks","next","document_key_DocumentKey","DocumentKey","isDocumentKey","k1","k2","fromSegments","fromPathString","EMPTY","document_Document","Document","version","data","hasLocalMutations","fieldValue","compareByKey","d1","d2","compareByField","v1","v2","document_NoDocument","NoDocument","sorted_map_SortedMap","SortedMap","root","sorted_map_LLRBNode","insert","copy","BLACK","remove","node","cmp","getPredecessorKey","rightParent","prunedNodes","minKey","maxKey","inorderTraversal","action","k","v","reverseTraversal","getIterator","sorted_map_SortedMapIterator","getIteratorFrom","getReverseIterator","getReverseIteratorFrom","SortedMapIterator","startKey","isReverse","nodeStack","getNext","pop","hasNext","peek","LLRBNode","color","RED","n","fixUp","removeMin","isRed","moveRedLeft","smallest","rotateRight","moveRedRight","rotateLeft","colorFlip","nl","nr","checkMaxDepth","blackDepth","check","pow","LLRBEmptyNode","TypeOrder","field_value___extends","ServerTimestampBehavior","QueryPurpose","field_value_FieldValueOptions","FieldValueOptions","serverTimestampBehavior","fromSnapshotOptions","Estimate","Previous","defaultOptions","Default","field_value_FieldValue","FieldValue","defaultCompareTo","typeOrder","internalValue","field_value_BooleanValue","BooleanValue","of","TRUE","FALSE","NumberValue","IntegerValue","NaN","POSITIVE_INFINITY","Infinity","NEGATIVE_INFINITY","field_value_StringValue","StringValue","TimestampValue","toDate","ServerTimestampValue","localWriteTime","previousValue","BlobValue","field_value_RefValue","RefValue","GeoPointValue","field_value_ObjectValue","ObjectValue","it1","it2","next1","next2","set","to","setChild","newChild","pathSegment","childName","field_value_ArrayValue","ArrayValue","minLength","NumberAsAny","Number","query_Query","Query","explicitOrderBy","filters","startAt","endAt","memoizedCanonicalId","memoizedOrderBy","assertValidBound","atPath","inequalityField","getInequalityFilterField","firstOrderByField","getFirstOrderByField","KEY_ORDERING_ASC","query_OrderBy","foundKeyOrdering","_a","orderBy","lastDirection","dir","Direction","ASCENDING","KEY_ORDERING_DESC","addFilter","isInequality","newFilters","addOrderBy","newOrderBy","withLimit","withStartAt","bound","withEndAt","canonicalId","_b","_c","comparedOnKeyField","comp","compare","matches","matchesAncestor","matchesOrderBy","matchesFilters","matchesBounds","hasLimit","docPath","sortsBeforeDocument","RelationOp","LESS_THAN","LESS_THAN_OR_EQUAL","GREATER_THAN_OR_EQUAL","GREATER_THAN","RelationFilter","refValue","comparison","matchesComparison","matchesValue","DESCENDING","query_Bound","Bound","before","component","orderByComponent","docValue","thisPosition","otherPosition","OrderBy","isKeyOrderBy","isoRegExp","RegExp","timestamp_Timestamp","Timestamp","seconds","nanos","now","fromEpochMilliseconds","fromDate","date","getTime","milliseconds","fromISOString","utc","fraction","nanoStr","substr","toEpochMilliseconds","snapshot_version_SnapshotVersion","SnapshotVersion","timestamp","fromMicroseconds","fromTimestamp","forDeletedDoc","MIN","toMicroseconds","toTimestamp","MutationType","query_data_QueryData","QueryData","targetId","purpose","snapshotVersion","update","updated","mutation___extends","mutation_FieldMask","FieldMask","fields","ServerTimestampTransform","FieldTransform","transform","MutationResult","transformResults","mutation_Precondition","Precondition","updateTime","exists","isValidFor","maybeDoc","isNone","NONE","mutation_Mutation","Mutation","verifyKeyMatches","getPostMutationVersion","mutation_SetMutation","SetMutation","precondition","applyToRemoteDocument","mutationResult","applyToLocalView","baseDoc","mutation_PatchMutation","PatchMutation","fieldMask","Patch","newData","patchDocument","patchObject","fieldPath","newValue","mutation_TransformMutation","TransformMutation","fieldTransforms","Transform","requireDocument","transformObject","localTransformResults","fieldTransform","mutation_DeleteMutation","DeleteMutation","Delete","ExistenceFilter","count","CurrentStatusUpdate","sorted_set_SortedSet","SortedSet","fromMapKeys","keys","has","elem","first","last","cb","forEachInRange","range","iter","forEachWhile","firstAfterOrEqual","unionWith","thisIt","otherIt","thisElem","otherElem","remote_event_RemoteEvent","RemoteEvent","targetChanges","documentUpdates","addDocumentUpdate","handleExistenceFilterMismatch","mapping","ResetMapping","currentStatusUpdate","MarkNotCurrent","WatchTargetChangeState","EMPTY_KEY_SET","docs","UpdateMapping","addedDocuments","removedDocuments","applyToKeySet","DocumentWatchChange","updatedTargetIds","removedTargetIds","newDoc","ExistenceFilterChange","existenceFilter","watch_change_WatchTargetChange","WatchTargetChange","state","targetIds","cause","watch_change_WatchChangeAggregator","WatchChangeAggregator","listenTargets","pendingTargetResponses","existenceFilters","frozen","watchChange","addDocumentChange","addTargetChange","addExistenceFilterChange","addChanges","watchChanges","createRemoteEvent","isActiveTarget","ensureTargetChange","None","docChange","relevant","targetChange","NoChange","recordTargetResponse","Current","MarkCurrent","Reset","newCount","DIRECTIONS","dirs","OPERATORS","ops","serializer_JsonProtoSerializer","JsonProtoSerializer","useProto3Json","unsafeCastProtoByteString","byteString","fromRpcStatus","toInt32Value","fromInt32Value","toBytes","bytes","fromBlob","blob","toVersion","fromVersion","toResourceName","fullyQualifiedPrefixPath","fromResourceName","resource","isValidResourceName","toName","fromName","extractLocalPathFromResourceName","toQueryPath","encodedDatabaseId","fromQueryPath","resourceName","toValue","nullValue","booleanValue","integerValue","doubleValue","stringValue","mapValue","toMapValue","arrayValue","toArrayValue","timestampValue","geoPointValue","bytesValue","referenceValue","fromValue","fromFields","values","dbId","toMutationDocument","toFields","toDocument","document","fromDocument","fromFound","found","fromMissing","missing","readTime","fromMaybeDocument","toWatchTargetChangeState","toTestWatchChange","documentChange","documentDelete","documentRemove","targetChangeType","fromWatchChange","fromWatchTargetChangeState","causeProto","entityChange","docDelete","docRemove","versionFromListenResponse","toMutation","mutation","updateMask","toDocumentMask","toFieldTransform","currentDocument","toPrecondition","fromMutation","proto","fromPrecondition","fromDocumentMask","fromFieldTransform","fromWriteResult","fromWriteResults","protos","setToServerValue","toDocumentsTarget","fromDocumentsTarget","documentsTarget","toQueryTarget","structuredQuery","parent","from","collectionId","where","toFilter","toOrder","toCursor","fromQueryTarget","fromCount","filterBy","fromFilter","fromOrder","fromCursor","toListenRequestLabels","queryData","toLabel","goog-listen-tags","Listen","ExistenceFilterMismatch","LimboResolution","toTarget","toRelationFilter","toUnaryFilter","compositeFilter","unaryFilter","fromUnaryFilter","fromRelationFilter","f","reduce","accum","orderBys","toPropertyOrder","fromPropertyOrder","cursor","toDirection","fromDirection","toOperatorName","fromOperatorName","toFieldPathReference","fromFieldPathReference","fieldReference","direction","nanField","nullField","fieldPaths","paths","dist","stream_bridge_StreamBridge","StreamBridge","sendFn","closeFn","onOpen","callback","wrappedOnOpen","onClose","wrappedOnClose","onMessage","wrappedOnMessage","close","send","callOnOpen","callOnClose","err","callOnMessage","LOG_TAG","RPC_NAME_REST_MAPPING","BatchGetDocuments","Commit","X_GOOG_API_CLIENT_VALUE","webchannel_connection_WebChannelConnection","WebChannelConnection","info","pool","baseUrl","modifyHeadersForRequest","headers","header","authHeaders","invokeRPC","rpcName","url","makeUrl","Promise","getObject","xhr","listenOnce","COMPLETE","getLastErrorCode","NO_ERROR","json","getResponseJson","TIMEOUT","HTTP_ERROR","status_1","getStatus","getResponseText","getStatusText","getLastError","releaseObject","requestString","Content-Type","invokeStreamingRPC","openStream","urlParts","webchannelTransport","backgroundChannelTest","httpSessionIdParam","initMessageHeaders","httpHeadersOverwriteParam","sendRawJson","supportsCrossDomainXhr","channel","createWebChannel","opened","closed","streamBridge","open","unguardedEventListen","listen","param","setTimeout","EventType","OPEN","CLOSE","MESSAGE","msgData","status_2","urlRpcName","browser_platform_BrowserPlatform","BrowserPlatform","loadConnection","databaseInfo","newSerializer","encoded","raw","OnlineState","fieldNames","documentId","_DOCUMENT_ID","SyncState","GeneratorIds","view_snapshot_DocumentChangeSet","DocumentChangeSet","changeMap","track","oldChange","getChanges","changes","ViewSnapshot","hasPendingWrites","syncStateChanged","otherChanges","document_set_DocumentSet","DocumentSet","keyedMap","sortedSet","emptySet","oldSet","prevDoc","thisDoc","otherDoc","docStrings","newSet","obj_map_ObjectMap","ObjectMap","mapKeyFn","inner","id","matches_1","otherKey","splice","entries","entries_1","QueryListenersInfo","listeners","event_manager_EventManager","EventManager","syncEngine","queries","q","onlineState","Unknown","subscribe","onChange","onError","listener","firstListen","queryInfo","applyOnlineStateChange","viewSnap","onViewSnapshot","then","unlisten","lastListen","viewSnaps","viewSnaps_1","event_manager_QueryListener","QueryListener","queryObserver","raisedInitialEvent","snap","includeDocumentMetadataChanges","shouldRaiseEvent","shouldRaiseInitialEvent","raiseInitialEvent","maybeOnline","Failed","waitForSyncWhenOnline","hasPendingWritesChanged","includeQueryMetadataChanges","getInitialViewChanges","PersistencePromise","nextCallback","catchCallback","isDone","callbackAttached","catch","nextFn","catchFn","wrapFailure","wrapSuccess","toPromise","wrapUserFunction","waitFor","all","promise","nextPromise","idx","initial","eager_garbage_collector_EagerGarbageCollector","EagerGarbageCollector","isEager","sources","potentialGarbage","addGarbageSource","garbageSource","setGarbageCollector","removeGarbageSource","addPotentialGarbageKey","collectGarbage","promises","garbageKeys","hasRefsPromise","documentHasAnyReferences","hasRefs","source","containsKey","local_view_changes_LocalViewChanges","LocalViewChanges","addedKeys","removedKeys","fromSnapshot","viewSnapshot","reference_set_ReferenceSet","ReferenceSet","refsByKey","reference_set_DocReference","refsByTarget","compareByTargetId","garbageCollector","addReference","ref","addReferences","removeReference","removeRef","removeReferences","removeReferencesForId","emptyKey","startRef","endRef","removeAllReferences","referencesForId","firstRef","DocReference","targetOrBatchId","RESERVED_BITS","PersistentStreamState","TargetIdGenerator","generatorId","initAfter","afterWithoutGenerator","afterGenerator","previousId","forLocalStore","LocalStore","forSyncEngine","SyncEngine","AddedLimboDocument","RemovedLimboDocument","view_View","View","syncedDocuments","syncState","limboDocuments","mutatedKeys","documentSet","computeDocChanges","previousChanges","changeSet","oldDocumentSet","newMutatedKeys","newDocumentSet","needsRefill","lastDocInLimit","newMaybeDoc","oldDoc","docsEqual","applyChanges","sort","limboChanges","applyTargetChange","synced","newSyncState","Synced","Local","shouldBeInLimbo","targetMapping","oldLimboDocuments","QueryView","view","sync_engine_SyncEngine","localStore","remoteStore","currentUser","viewHandler","errorHandler","queryViewsByQuery","queryViewsByTarget","limboTargetsByKey","limboKeysByTarget","limboDocumentRefs","limboCollector","mutationUserCallbacks","targetIdGenerator","assertSubscribed","allocateQuery","executeQuery","remoteDocumentKeys","remoteKeys","viewDocChanges","viewChange","queryView","releaseQuery","removeAndCleanupQuery","write","batch","userCallback","localWrite","addMutationCallback","batchId","emitNewSnapsAndNotifyLocalStore","fillWritePipeline","wrapUpdateFunctionError","runTransaction","updateFunction","retries","transaction","createTransaction","userPromise","commit","applyRemoteEvent","remoteEvent","limboKey","newViewSnapshots","rejectListen","docMap","event_1","queryView_1","applySuccessfulWrite","mutationBatchResult","processUserCallback","acknowledgeBatch","rejectFailedWrite","rejectBatch","newCallbacks","toKey","gcLimboDocuments","updateTrackedLimbos","limboChanges_1","limboChange","trackLimboChange","limboTargetId","currentLimboDocs","newSnaps","docChangesInAllViews","queriesProcessed","notifyLocalViewChanges","fnName","handleUserChange","user","BATCHID_UNKNOWN","mutation_batch_MutationBatch","MutationBatch","mutations","batchResult","mutationResults","keySet","isTombstone","toTombstone","mutation_batch_MutationBatchResult","MutationBatchResult","commitVersion","streamToken","docVersions","versionMap","DbTimestamp","ownerId","leaseTimestampMs","userId","lastAcknowledgedBatchId","lastStreamToken","localWriteTimeMs","DbDocumentMutation","prefixForUser","prefixForPath","PLACEHOLDER","DbNoDocument","noDocument","lastListenSequenceNumber","highestTargetId","highestListenSequenceNumber","lastRemoteSnapshotVersion","ALL_STORES","simple_db_SimpleDb","SimpleDb","openOrCreate","runUpgrade","isAvailable","window","indexedDB","onupgradeneeded","deleteDatabase","ua","navigator","userAgent","mode","objectStores","transactionFn","transactionFnResult","abort","completionPromise","IterationController","dbCursor","shouldStop","nextKey","done","skip","SimpleDbTransaction","objectStoresNames","aborted","onabort","oncomplete","storeName","objectStore","simple_db_SimpleDbStore","SimpleDbStore","put","keyOrValue","loadAll","indexOrRange","iterateCursor","deleteAll","keysOnly","control","iterate","optionsOrCallback","cursorRequest","controller","userResult","primaryKey","skipToKey","continue","indexName","reverse","openKeyCursor","openCursor","indexeddb_mutation_queue_IndexedDbMutationQueue","IndexedDbMutationQueue","serializer","forUser","uid","isUnauthenticated","loadNextBatchIdFromDb","nextBatchId","metadata","checkEmpty","empty","maxBatchId","nextUser","IDBKeyRange","keyForBatchId","getNextBatchId","getHighestAcknowledgedBatchId","getLastStreamToken","setLastStreamToken","addMutationBatch","dbBatch","toDbMutationBatch","mutations_1","indexKey","lookupMutationBatch","fromDbMutationBatch","getNextMutationBatchAfterBatchId","lowerBound","foundBatch","getAllMutationBatches","dbBatches","getAllMutationBatchesThroughBatchId","getAllMutationBatchesAffectingDocumentKey","documentKey","indexPrefix","indexStart","userID","encodedPath","batchID","mutationKey","getAllMutationBatchesAffectingQuery","queryPath","immediateChildrenLength","uniqueBatchIDs","removeMutationBatches","batches","indexTxn","this_1","batches_1","only","numDeleted","removePromise","performConsistencyCheck","startRange","danglingMutationReferences","gc","indexeddb_query_cache_IndexedDbQueryCache","IndexedDbQueryCache","lastSavedVersion","getHighestTargetId","getLastRemoteSnapshotVersion","setLastRemoteSnapshotVersion","addQueryData","addedQueryPromise","toDbTarget","removeQueryData","removeMatchingKeysForTargetId","getQueryData","fromDbTarget","addMatchingKeys","removeMatchingKeys","notifyGCForRemovedKeys","getMatchingKeysForTargetId","indexeddb_remote_document_cache_IndexedDbRemoteDocumentCache","IndexedDbRemoteDocumentCache","addEntry","maybeDocument","toDbRemoteDocument","removeEntry","getEntry","dbRemoteDoc","fromDbRemoteDocument","getDocumentsMatchingQuery","local_serializer_LocalSerializer","LocalSerializer","remoteSerializer","remoteDoc","serializedMutations","m","dbTarget","queryProto","dbTimestamp","EXISTING_OWNER_ERROR_MSG","indexeddb_persistence_IndexedDbPersistence","IndexedDbPersistence","prefix","generateOwnerId","dbName","MAIN_DATABASE","localStoragePrefix","started","simpleDb","tryAcquireOwnerLease","scheduleOwnerLeaseRefreshes","attachWindowUnloadHook","persistenceError","shutdown","detachWindowUnloadHook","stopOwnerLeaseRefreshes","releaseOwnerLease","getMutationQueue","getQueryCache","getRemoteDocumentCache","operation","ensureOwnerLease","buildStoragePrefix","isDefaultDatabase","dbOwner","validOwner","newDbOwner","minAcceptable","maxAcceptable","getZombiedOwnerId","ownerLeaseRefreshHandle","setInterval","reason","clearInterval","windowUnloadHandler","setZombiedOwnerId","addEventListener","removeEventListener","zombiedOwnerId","localStorage","getItem","zombiedOwnerLocalStorageKey","zombieOwnerId","removeItem","setItem","local_documents_view_LocalDocumentsView","LocalDocumentsView","remoteDocumentCache","mutationQueue","getDocument","computeLocalDocument","getDocuments","getDocumentsMatchingDocumentQuery","getDocumentsMatchingCollectionQuery","queryResults","computeLocalDocuments","promisedResults","matchingMutationBatches","matchingKeys","matchingMutationBatches_1","mutatedDoc","remote_document_change_buffer_RemoteDocumentChangeBuffer","RemoteDocumentChangeBuffer","assertChanges","bufferedEntry","local_store_LocalStore","persistence","initialUser","localViewReferences","heldBatchResults","remoteDocuments","queryCache","localDocuments","startMutationQueue","startQueryCache","oldBatches","promisedOldBatches","newBatches","changedKeys","_d","highestAck","ackedBatches","promisedBatch","changedDocuments","affected","shouldHoldBatchResult","documentBuffer_1","releaseBatchResults","promisedAffectedKeys","toReject","affectedKeys","promisedToReject","lastAcked","removeMutationBatch","documentBuffer","changedDocKeys","existingDoc","lastRemoteVersion","remoteVersion","releasedWriteKeys","releaseHeldBatchResults","promisedReleasedWriteKeys","viewChanges","viewChanges_1","nextMutationBatch","afterBatchId","readDocument","cached","documentBuffer_2","garbage","toRelease","isRemoteUpToVersion","batchResults","promiseChain","batchResults_1","applyWriteToRemoteDocuments","affectedDocs","batches_2","docKeys","ackVersion","memory_mutation_queue_MemoryMutationQueue","MemoryMutationQueue","highestAcknowledgedBatchId","batchesByDocumentKey","batchIndex","indexOfExistingBatchId","findMutationBatch","max","rawIndex","indexOfBatchId","getAllLiveMutationBatchesBeforeIndex","endIndex","immediateChildrenPathLength","startPath","rowKeyPath","batchCount","firstBatchId","queueCount","startIndex","queueIndex","length_1","references","memory_query_cache_MemoryQueryCache","MemoryQueryCache","memory_remote_document_cache_MemoryRemoteDocumentCache","MemoryRemoteDocumentCache","iterator","memory_persistence_MemoryPersistence","MemoryPersistence","mutationQueues","queue","MemoryPersistenceTransaction","no_op_garbage_collector_NoOpGarbageCollector","NoOpGarbageCollector","Deferred","backoff_ExponentialBackoff","ExponentialBackoff","initialDelayMs","backoffFactor","maxDelayMs","reset","currentBaseMs","resetToMax","backoffAndWait","def","delayWithJitterMs","jitterDelayMs","persistent_stream___extends","BACKOFF_INITIAL_DELAY_MS","BACKOFF_MAX_DELAY_MS","BACKOFF_FACTOR","persistent_stream_PersistentStream","PersistentStream","connection","credentialsProvider","initialBackoffDelay","idle","stream","backoff","Initial","isStarted","Backoff","Auth","Open","isOpen","performBackoff","auth","stop","Stopped","inhibitBackoff","markIdle","schedule","handleIdleCloseTimer","sendRequest","cancelIdleCheck","finalState","tearDown","getToken","startStream","rpcError","handleStreamClose","dispatchIfStillActive","currentStream_1","startRpc","PersistentListenStream","watchChangeProto","onWatchChange","watch","addTarget","labels","unwatch","removeTarget","persistent_stream_PersistentWriteStream","PersistentWriteStream","handshakeComplete_","writeMutations","responseProto","writeResults","commitTime","onMutationResult","onHandshakeComplete","writeHandshake","writes","datastore_Datastore","Datastore","newPersistentWriteStream","newPersistentWatchStream","params","response","lookup","transaction_Transaction","Transaction","datastore","readVersions","committed","recordVersion","docVersion","existingVersion","preconditionForUpdate","toMutations","unwritten","remote_store_RemoteStore","RemoteStore","onlineStateHandler","pendingWrites","lastBatchSeen","accumulatedWatchChanges","watchStream","writeStream","watchStreamOnlineState","watchStreamFailures","shouldWarnOffline","enableNetwork","updateOnlineState","newState","Healthy","updateOnlineStateAfterFailure","isNetworkEnabled","shouldStartWatchStream","startWatchStream","disableNetwork","disableNetworkInternal","cleanUpWatchStreamState","cleanUpWriteStreamState","sendWatchRequest","sendUnwatchRequest","recordPendingTargetRequest","onWatchStreamOpen","onWatchStreamClose","onWatchStreamChange","handleTargetError","handleWatchChangeBatch","aggregator","deletedDoc","trackedRemote","newQueryData","requestQueryData","canWriteMutations","outstandingWrites","shouldStartWriteStream","startWriteStream","handshakeComplete","onWriteStreamOpen","onWriteStreamClose","onWriteHandshakeComplete","shift","success","errorHandling","handleWriteError","handleHandshakeError","firestore_client_FirestoreClient","FirestoreClient","asyncQueue","usePersistence","initializationDone","persistenceResult","initialized","setUserChangeListener","initializePersistence","initializeRest","startIndexedDbPersistence","canFallback","warn","startMemoryPersistence","storagePrefix","onlineStateChangedHandler","eventMgr","verifyOperationInProgress","removeUserChangeListener","observer","deferred","AsyncObserver","muted","scheduleEvent","mute","eventHandler","async_queue_AsyncQueue","AsyncQueue","tail","delayedOperations","delayedOperationsCount","operationInProgress","delay","stack","delayedOp_1","handle","scheduleInternal","drain","executeDelayedTasks","entry","clearTimeout","User","otherUser","GOOGLE_CREDENTIALS","FIRST_PARTY","OAuthToken","Authorization","EmptyCredentialsProvider","userListener","forceRefresh","credentials_FirebaseCredentialsProvider","FirebaseCredentialsProvider","tokenListener","userCounter","newUser","getUser","addAuthTokenListener","initialUserCounter","tokenData","accessToken","removeAuthTokenListener","getUid","currentUid","credentials_FirstPartyToken","FirstPartyToken","gapi","X-Goog-AuthUser","FirstPartyCredentialsProvider","api_field_value___extends","DeleteFieldValueImpl","serverTimestamp","ServerTimestampFieldValueImpl","PublicFieldValue","RESERVED_FIELD_REGEX","user_data_converter_ParsedSetData","ParsedSetData","user_data_converter_ParsedUpdateData","ParsedUpdateData","user_data_converter_ParseContext","ParseContext","arrayElement","validatePath","childContextForField","childPath","validatePathSegment","childContextForFieldPath","childContextForArray","fieldDescription","user_data_converter_UserDataConverter","UserDataConverter","preConverter","parseSetData","updateData","parseData","parseMergeData","parseUpdateData","fieldMaskPaths","childContext","runPreConverter","parsedValue","mask","parseUpdateVarargs","moreFieldsAndValues","value_1","parseQueryValue","parsed","parseArray","parseObject","parseScalarValue","entryIndex","array_1","parsedEntry","database___extends","DEFAULT_HOST","DEFAULT_SSL","database_FirestoreSettings","FirestoreSettings","settings","FirestoreConfig","Firestore","databaseIdOrApp","_queue","_firestoreClient","drainAsyncQueue","config","firebaseApp","databaseIdFromApp","external_1","_config","_databaseId","settingsLiteral","newSettings","ensureClientConfigured","enablePersistence","configureClient","thisDb","otherDb","_key","_dataConverter","collection","pathString","database_CollectionReference","forPath","database_Transaction","database_WriteBatch","SILENT","level","_firestore","_transaction","database_DocumentSnapshot","fieldOrUpdateData","WriteBatch","_mutations","_committed","verifyNotCommitted","DocumentReference","onSnapshot","includeMetadataChanges","currArg","internalOptions","complete","onSnapshotInternal","errHandler","asyncObserver","internalListener","SnapshotMetadata","DocumentSnapshot","_document","_fromCache","convertObject","convertValue","convertArray","QueryDocumentSnapshot","database_Query","_query","opStr","validateNewFilter","directionStr","validateNewOrderBy","docOrField","boundFromDocOrFields","startAfter","endBefore","boundFromDocument","allFields","boundFromFields","components","rawValue","wrapped","database_QuerySnapshot","firestoreClient","existingField","validateOrderByAndInequalityMatch","inequality","QuerySnapshot","_originalQuery","_snapshot","_cachedChanges","thisArg","convertToDocumentImpl","CollectionReference","parentPath","docRef","PublicFirestore","PublicTransaction","PublicWriteBatch","PublicDocumentReference","PublicDocumentSnapshot","PublicQueryDocumentSnapshot","PublicQuery","PublicQuerySnapshot","PublicCollectionReference","115","global","l","a","aa","ba","propertyIsEnumerable","ca","da","fa","ha","unshift","r","Function","ia","u","H","Cb","ja","captureStackTrace","ka","ma","na","oa","w","qa","ra","ea","va","wa","xa","ya","y","x","Ba","Ca","Da","Ea","Ga","Fa","Ha","Ia","Ja","Oa","documentMode","Ta","la","Pa","h","parseInt","A","$a","relatedTarget","button","screenY","screenX","clientY","clientX","metaKey","shiftKey","altKey","ctrlKey","pointerId","pointerType","changedTouches","srcElement","Ma","nodeName","fromElement","toElement","pageX","pageY","ab","defaultPrevented","bb","eb","src","capture","ga","Y","fb","gb","ib","sa","jb","hb","nb","once","ob","pb","qb","rb","kb","sb","Za","attachEvent","tb","addListener","removeListener","mb","ub","Xa","vb","wb","detachEvent","lb","xb","yb","keyCode","returnValue","parentNode","zb","handleEvent","B","P","K","Ab","Bb","eval","Db","Eb","Fb","Boolean","Gb","valueOf","Ib","Hb","Jb","Kb","Ob","Pb","Lb","Qb","Sb","MessageChannel","postMessage","createElement","style","display","documentElement","appendChild","contentWindow","location","protocol","origin","port1","onmessage","port2","za","onreadystatechange","removeChild","Ub","Tb","Vb","setImmediate","Window","Rb","Nb","Wb","Xb","g","t","Yb","$","L","Zb","$b","ac","X","C","cc","dc","fc","D","lc","oc","nc","mc","jc","lastIndexOf","E","hc","pc","ic","F","kc","qc","rc","G","Z","Mb","sc","tc","uc","vc","I","wc","xc","parse","zc","Ac","yc","dispatchEvent","Bc","J","Cc","Dc","Ec","Hc","Ic","Jc","Lc","Mc","ActiveXObject","XMLHttpRequest","T","N","S","Nc","Oc","j","U","o","M","Pc","Sc","Tc","Uc","Vc","Wc","Xc","Qa","Yc","W","Ka","V","Zc","$c","ad","bd","cd","dd","ed","Rc","Qc","fd","gd","hd","ta","O","jd","kd","md","decodeURIComponent","nd","od","pd","qd","rd","match","ld","sd","td","zd","ud","Ad","Q","Bd","abs","Cd","Dd","decodeURI","encodeURI","Ed","R","Gd","Fd","Hd","toLowerCase","Id","Kd","Jd","Ld","Md","Od","Pd","Qd","Rd","Sd","Td","Vd","Wd","Xd","Yd","Zd","pa","$d","ae","be","ce","de","ee","fe","ge","he","ie","encodeURIComponent","je","Image","onload","ke","ontimeout","le","qe","z","timeout","oe","re","se","te","goog","La","self","me","pe","readyState","ue","ve","we","Ua","concurrentRequestLimit","fastHandshake","xe","ye","ze","sendBeacon","Ae","cancel","Be","Ce","De","Ee","Fe","He","Ge","round","Va","Ie","Na","Je","Ke","Ud","Aa","Le","hostname","port","Me","Ne","Oe","testUrl","messageUrlParams","messageHeaders","clientProtocolHeaderRequired","X-Client-Protocol","messageContentType","X-WebChannel-Content-Type","Pe","Qe","__sm__","Re","Te","Ue","Ve","We","Xe","Ye","Ze","$e","af","trim","Ra","Sa","parseFloat","compatMode","Wa","freeze","Ya","2","3","4","preventDefault","\"","\\","/","\b","\f","\n","\r","\t","\u000b","bc","ec","Fc","Gc","Kc","vd","wd","xd","yd","Nd","getResponseHeader","ne","toUpperCase","FormData","setRequestHeader","responseType","withCredentials","statusText","responseText","__data__","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iC,EAAA/+D,UAAAk4D,GAAkC2E,EAAA78D,UAAAk6B,UAAA2iC,EAAA78D,UAAAy5D,GAAqCoD,EAAA78D,UAAAi7B,cAAA4hC,EAAA78D,UAAAg9D,GAAyCqI,EAAArlE,UAAAo6B,WAAAirC,EAAArlE,UAAAs6D,GAAsC+K,EAAArlE,UAAAg7B,aAAAqqC,EAAArlE,UAAAs8D,GAAwC+I,EAAArlE,UAAAs6B,iBAAA+qC,EAAArlE,UAAAq6D,GAC32BgL,EAAArlE,UAAA66B,UAAAwqC,EAAArlE,UAAAumE,EAAoClB,EAAArlE,UAAA+6B,cAAAsqC,EAAArlE,UAAAo6D,GAAyCiL,EAAArlE,UAAAy6B,gBAAA4qC,EAAArlE,UAAAgwE,GAA2C3K,EAAArlE,UAAA86B,gBAAAuqC,EAAArlE,UAAAymE,EAA0CpB,EAAArlE,UAAA86B,gBAAAuqC,EAAArlE,UAAAymE,EAA0CpB,EAAArlE,UAAA04B,KAAA2sC,EAAArlE,UAAAu4D,GAAgC17D,OAAAC,SAAgBq1E,0BAAAD,GAAAE,UAAApB,GAAAx0C,UAAAy0C,GAAAoB,WAAA5I,GAAA6I,UAAAzV,KAAmFv8D,SAAA,KAAAy3D,cAAA,mBAAAiU,WAAA,mBAAAr8B,qBnFiihBlTrvC,KAAKxD,QAASC,oBAAoB,QAI5D,MACO,MAAM6B,GACN,KAAUS,OACR","file":"firebase-firestore.js","sourcesContent":["/*!\n * @license Firebase v4.9.0\n * Build: rev-a586a7f\n * Terms: https://firebase.google.com/terms/\n */\ntry {\n webpackJsonpFirebase([1],{\n\n/***/ 113:\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n__webpack_require__(114);\n\n\n/***/ }),\n\n/***/ 114:\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nObject.defineProperty(__webpack_exports__, \"__esModule\", { value: true });\n\n// EXTERNAL MODULE: ../app/dist/esm/index.js + 1 modules\nvar esm = __webpack_require__(6);\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/version.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The semver (www.semver.org) version of the SDK. */\nvar SDK_VERSION = esm[\"default\"].SDK_VERSION;\n\n//# sourceMappingURL=version.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/log.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/* tslint:disable:no-console */\n\n\nvar LogLevel;\n(function (LogLevel) {\n LogLevel[LogLevel[\"DEBUG\"] = 0] = \"DEBUG\";\n LogLevel[LogLevel[\"ERROR\"] = 1] = \"ERROR\";\n LogLevel[LogLevel[\"SILENT\"] = 2] = \"SILENT\";\n})(LogLevel || (LogLevel = {}));\nvar logLevel = LogLevel.ERROR;\n// Helper methods are needed because variables can't be exported as read/write\nfunction getLogLevel() {\n return logLevel;\n}\nfunction setLogLevel(newLevel) {\n logLevel = newLevel;\n}\nfunction debug(tag, msg) {\n var obj = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n obj[_i - 2] = arguments[_i];\n }\n if (logLevel <= LogLevel.DEBUG) {\n var time = new Date().toISOString();\n var args = obj.map(argToString);\n console.log.apply(console, [\"Firestore (\" + SDK_VERSION + \") \" + time + \" [\" + tag + \"]: \" + msg].concat(args));\n }\n}\nfunction log_error(msg) {\n var obj = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n obj[_i - 1] = arguments[_i];\n }\n if (logLevel <= LogLevel.ERROR) {\n var time = new Date().toISOString();\n var args = obj.map(argToString);\n console.error.apply(console, [\"Firestore (\" + SDK_VERSION + \") \" + time + \": \" + msg].concat(args));\n }\n}\n/**\n * Converts an additional log parameter to a string representation.\n */\nfunction argToString(obj) {\n if (typeof obj === 'string') {\n return obj;\n }\n else {\n var platform = platform_PlatformSupport.getPlatform();\n try {\n return platform.formatJSON(obj);\n }\n catch (e) {\n // Converting to JSON failed, just log the object directly\n return obj;\n }\n }\n}\n\n//# sourceMappingURL=log.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/assert.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n/**\n * Unconditionally fails, throwing an Error with the given message.\n *\n * Returns any so it can be used in expressions:\n * @example\n * let futureVar = fail('not implemented yet');\n */\nfunction fail(failure) {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n var message = \"FIRESTORE (\" + SDK_VERSION + \") INTERNAL ASSERTION FAILED: \" + failure;\n log_error(message);\n // NOTE: We don't use FirestoreError here because these are internal failures\n // that cannot be handled by the user. (Also it would create a circular\n // dependency between the error and assert modules which doesn't work.)\n throw new Error(message);\n}\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n */\nfunction assert(assertion, message) {\n if (!assertion) {\n fail(message);\n }\n}\n\n//# sourceMappingURL=assert.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/platform/platform.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Provides singleton helpers where setup code can inject a platform at runtime.\n * setPlatform needs to be set before Firestore is used and must be set exactly\n * once.\n */\nvar platform_PlatformSupport = /** @class */ (function () {\n function PlatformSupport() {\n }\n PlatformSupport.setPlatform = function (platform) {\n if (PlatformSupport.platform) {\n fail('Platform already defined');\n }\n PlatformSupport.platform = platform;\n };\n PlatformSupport.getPlatform = function () {\n if (!PlatformSupport.platform) {\n fail('Platform not set');\n }\n return PlatformSupport.platform;\n };\n return PlatformSupport;\n}());\n\n/**\n * Returns the representation of an empty \"proto\" byte string for the\n * platform.\n */\nfunction emptyByteString() {\n return platform_PlatformSupport.getPlatform().emptyByteString;\n}\n\n//# sourceMappingURL=platform.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/error.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n// TODO(mcg): Change to a string enum once we've upgraded to typescript 2.4.\n// tslint:disable-next-line:variable-name Intended to look like a TS 2.4 enum\nvar Code = {\n // Causes are copied from:\n // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n /** Not an error; returned on success. */\n OK: 'ok',\n /** The operation was cancelled (typically by the caller). */\n CANCELLED: 'cancelled',\n /** Unknown error or an error from a different error domain. */\n UNKNOWN: 'unknown',\n /**\n * Client specified an invalid argument. Note that this differs from\n * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are\n * problematic regardless of the state of the system (e.g., a malformed file\n * name).\n */\n INVALID_ARGUMENT: 'invalid-argument',\n /**\n * Deadline expired before operation could complete. For operations that\n * change the state of the system, this error may be returned even if the\n * operation has completed successfully. For example, a successful response\n * from a server could have been delayed long enough for the deadline to\n * expire.\n */\n DEADLINE_EXCEEDED: 'deadline-exceeded',\n /** Some requested entity (e.g., file or directory) was not found. */\n NOT_FOUND: 'not-found',\n /**\n * Some entity that we attempted to create (e.g., file or directory) already\n * exists.\n */\n ALREADY_EXISTS: 'already-exists',\n /**\n * The caller does not have permission to execute the specified operation.\n * PERMISSION_DENIED must not be used for rejections caused by exhausting\n * some resource (use RESOURCE_EXHAUSTED instead for those errors).\n * PERMISSION_DENIED must not be used if the caller can not be identified\n * (use UNAUTHENTICATED instead for those errors).\n */\n PERMISSION_DENIED: 'permission-denied',\n /**\n * The request does not have valid authentication credentials for the\n * operation.\n */\n UNAUTHENTICATED: 'unauthenticated',\n /**\n * Some resource has been exhausted, perhaps a per-user quota, or perhaps the\n * entire file system is out of space.\n */\n RESOURCE_EXHAUSTED: 'resource-exhausted',\n /**\n * Operation was rejected because the system is not in a state required for\n * the operation's execution. For example, directory to be deleted may be\n * non-empty, an rmdir operation is applied to a non-directory, etc.\n *\n * A litmus test that may help a service implementor in deciding\n * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:\n * (a) Use UNAVAILABLE if the client can retry just the failing call.\n * (b) Use ABORTED if the client should retry at a higher-level\n * (e.g., restarting a read-modify-write sequence).\n * (c) Use FAILED_PRECONDITION if the client should not retry until\n * the system state has been explicitly fixed. E.g., if an \"rmdir\"\n * fails because the directory is non-empty, FAILED_PRECONDITION\n * should be returned since the client should not retry unless\n * they have first fixed up the directory by deleting files from it.\n * (d) Use FAILED_PRECONDITION if the client performs conditional\n * REST Get/Update/Delete on a resource and the resource on the\n * server does not match the condition. E.g., conflicting\n * read-modify-write on the same resource.\n */\n FAILED_PRECONDITION: 'failed-precondition',\n /**\n * The operation was aborted, typically due to a concurrency issue like\n * sequencer check failures, transaction aborts, etc.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n ABORTED: 'aborted',\n /**\n * Operation was attempted past the valid range. E.g., seeking or reading\n * past end of file.\n *\n * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed\n * if the system state changes. For example, a 32-bit file system will\n * generate INVALID_ARGUMENT if asked to read at an offset that is not in the\n * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from\n * an offset past the current file size.\n *\n * There is a fair bit of overlap between FAILED_PRECONDITION and\n * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)\n * when it applies so that callers who are iterating through a space can\n * easily look for an OUT_OF_RANGE error to detect when they are done.\n */\n OUT_OF_RANGE: 'out-of-range',\n /** Operation is not implemented or not supported/enabled in this service. */\n UNIMPLEMENTED: 'unimplemented',\n /**\n * Internal errors. Means some invariants expected by underlying System has\n * been broken. If you see one of these errors, Something is very broken.\n */\n INTERNAL: 'internal',\n /**\n * The service is currently unavailable. This is a most likely a transient\n * condition and may be corrected by retrying with a backoff.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n UNAVAILABLE: 'unavailable',\n /** Unrecoverable data loss or corruption. */\n DATA_LOSS: 'data-loss'\n};\n/**\n * An error class used for Firestore-generated errors. Ideally we should be\n * using FirebaseError, but integrating with it is overly arduous at the moment,\n * so we define our own compatible error class (with a `name` of 'FirebaseError'\n * and compatible `code` and `message` fields.)\n */\nvar FirestoreError = /** @class */ (function (_super) {\n __extends(FirestoreError, _super);\n function FirestoreError(code, message) {\n var _this = _super.call(this, message) || this;\n _this.code = code;\n _this.message = message;\n _this.name = 'FirebaseError';\n // HACK: We write a toString property directly because Error is not a real\n // class and so inheritance does not work correctly. We could alternatively\n // do the same \"back-door inheritance\" trick that FirebaseError does.\n _this.toString = function () { return _this.name + \": [code=\" + _this.code + \"]: \" + _this.message; };\n return _this;\n }\n return FirestoreError;\n}(Error));\n\n\n//# sourceMappingURL=error.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/api.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// We are doing some heavy reflective stuff, lots of any casting necessary\n/* tslint:disable:no-any */\n\n/**\n * Helper function to prevent instantiation through the constructor.\n *\n * This method creates a new constructor that throws when it's invoked.\n * The prototype of that constructor is then set to the prototype of the hidden\n * \"class\" to expose all the prototype methods and allow for instanceof\n * checks.\n *\n * To also make all the static methods available, all properties of the\n * original constructor are copied to the new constructor.\n */\nfunction makeConstructorPrivate(cls, optionalMessage) {\n function PublicConstructor() {\n var error = 'This constructor is private.';\n if (optionalMessage) {\n error += ' ';\n error += optionalMessage;\n }\n throw new FirestoreError(Code.INVALID_ARGUMENT, error);\n }\n // Make sure instanceof checks work and all methods are exposed on the public\n // constructor\n PublicConstructor.prototype = cls.prototype;\n // Copy any static methods/members\n for (var staticProperty in cls) {\n if (cls.hasOwnProperty(staticProperty)) {\n PublicConstructor[staticProperty] = cls[staticProperty];\n }\n }\n return PublicConstructor;\n}\n\n//# sourceMappingURL=api.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/obj.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nfunction contains(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\nfunction get(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key) ? obj[key] : null;\n}\nfunction obj_size(obj) {\n var count = 0;\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n count++;\n }\n }\n return count;\n}\n/** Returns the given value if it's defined or the defaultValue otherwise. */\nfunction defaulted(value, defaultValue) {\n return value !== undefined ? value : defaultValue;\n}\nfunction forEachNumber(obj, fn) {\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n var num = Number(key);\n if (!isNaN(num)) {\n fn(num, obj[key]);\n }\n }\n }\n}\nfunction forEach(obj, fn) {\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn(key, obj[key]);\n }\n }\n}\nfunction lookupOrInsert(obj, key, valFn) {\n if (!contains(obj, key)) {\n obj[key] = valFn();\n }\n return obj[key];\n}\nfunction isEmpty(obj) {\n assert(obj != null && typeof obj === 'object', 'isEmpty() expects object parameter.');\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return false;\n }\n }\n return true;\n}\nfunction shallowCopy(obj) {\n assert(obj && typeof obj === 'object', 'shallowCopy() expects object parameter.');\n var result = {};\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n result[key] = obj[key];\n }\n }\n return result;\n}\n\n//# sourceMappingURL=obj.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/input_validation.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n/**\n * Validates the invocation of functionName has the exact number of arguments.\n *\n * Forward the magic \"arguments\" variable as second parameter on which the\n * parameter validation is performed:\n * validateExactNumberOfArgs('myFunction', arguments, 2);\n */\nfunction validateExactNumberOfArgs(functionName, args, numberOfArgs) {\n if (args.length !== numberOfArgs) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires \" +\n formatPlural(numberOfArgs, 'argument') +\n ', but was called with ' +\n formatPlural(args.length, 'argument') +\n '.');\n }\n}\n/**\n * Validates the invocation of functionName has at least the provided number of\n * arguments (but can have many more).\n *\n * Forward the magic \"arguments\" variable as second parameter on which the\n * parameter validation is performed:\n * validateAtLeastNumberOfArgs('myFunction', arguments, 2);\n */\nfunction validateAtLeastNumberOfArgs(functionName, args, minNumberOfArgs) {\n if (args.length < minNumberOfArgs) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires at least \" +\n formatPlural(minNumberOfArgs, 'argument') +\n ', but was called with ' +\n formatPlural(args.length, 'argument') +\n '.');\n }\n}\n/**\n * Validates the invocation of functionName has number of arguments between\n * the values provided.\n *\n * Forward the magic \"arguments\" variable as second parameter on which the\n * parameter validation is performed:\n * validateBetweenNumberOfArgs('myFunction', arguments, 2, 3);\n */\nfunction validateBetweenNumberOfArgs(functionName, args, minNumberOfArgs, maxNumberOfArgs) {\n if (args.length < minNumberOfArgs || args.length > maxNumberOfArgs) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires between \" + minNumberOfArgs + \" and \" +\n (maxNumberOfArgs + \" arguments, but was called with \") +\n formatPlural(args.length, 'argument') +\n '.');\n }\n}\n/**\n * Validates the provided argument is an array and has as least the expected\n * number of elements.\n */\nfunction validateNamedArrayAtLeastNumberOfElements(functionName, value, name, minNumberOfElements) {\n if (!(value instanceof Array) || value.length < minNumberOfElements) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires its \" + name + \" argument to be an \" +\n 'array with at least ' +\n (formatPlural(minNumberOfElements, 'element') + \".\"));\n }\n}\n/**\n * Validates the provided positional argument has the native JavaScript type\n * using typeof checks.\n */\nfunction validateArgType(functionName, type, position, argument) {\n validateType(functionName, type, ordinal(position) + \" argument\", argument);\n}\n/**\n * Validates the provided argument has the native JavaScript type using\n * typeof checks or is undefined.\n */\nfunction validateOptionalArgType(functionName, type, position, argument) {\n if (argument !== undefined) {\n validateArgType(functionName, type, position, argument);\n }\n}\n/**\n * Validates the provided named option has the native JavaScript type using\n * typeof checks.\n */\nfunction validateNamedType(functionName, type, optionName, argument) {\n validateType(functionName, type, optionName + \" option\", argument);\n}\n/**\n * Validates the provided named option has the native JavaScript type using\n * typeof checks or is undefined.\n */\nfunction validateNamedOptionalType(functionName, type, optionName, argument) {\n if (argument !== undefined) {\n validateNamedType(functionName, type, optionName, argument);\n }\n}\n/**\n * Validates that the provided named option equals one of the expected values.\n */\nfunction validateNamedPropertyEquals(functionName, inputName, optionName, input, expected) {\n var expectedDescription = [];\n for (var _i = 0, expected_1 = expected; _i < expected_1.length; _i++) {\n var val = expected_1[_i];\n if (val === input) {\n return;\n }\n expectedDescription.push(valueDescription(val));\n }\n var actualDescription = valueDescription(input);\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid value \" + actualDescription + \" provided to function \" + functionName + \"() for option \\\"serverTimestamps\\\". Acceptable values: \" + expectedDescription.join(', '));\n}\n/**\n * Validates that the provided named option equals one of the expected values or\n * is undefined.\n */\nfunction validateNamedOptionalPropertyEquals(functionName, inputName, optionName, input, expected) {\n if (input !== undefined) {\n validateNamedPropertyEquals(functionName, inputName, optionName, input, expected);\n }\n}\n/** Helper to validate the type of a provided input. */\nfunction validateType(functionName, type, inputName, input) {\n if (typeof input !== type || (type === 'object' && !isPlainObject(input))) {\n var description = valueDescription(input);\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires its \" + inputName + \" \" +\n (\"to be of type \" + type + \", but it was: \" + description));\n }\n}\n/**\n * Returns true iff it's a non-null object without a custom prototype\n * (i.e. excludes Array, Date, etc.).\n */\nfunction isPlainObject(input) {\n return (typeof input === 'object' &&\n input !== null &&\n Object.getPrototypeOf(input) === Object.prototype);\n}\n/** Returns a string describing the type / value of the provided input. */\nfunction valueDescription(input) {\n if (input === undefined) {\n return 'undefined';\n }\n else if (input === null) {\n return 'null';\n }\n else if (typeof input === 'string') {\n if (input.length > 20) {\n input = input.substring(0, 20) + \"...\";\n }\n return JSON.stringify(input);\n }\n else if (typeof input === 'number' || typeof input === 'boolean') {\n return '' + input;\n }\n else if (typeof input === 'object') {\n if (input instanceof Array) {\n return 'an array';\n }\n else {\n var customObjectName = tryGetCustomObjectType(input);\n if (customObjectName) {\n return \"a custom \" + customObjectName + \" object\";\n }\n else {\n return 'an object';\n }\n }\n }\n else if (typeof input === 'function') {\n return 'a function';\n }\n else {\n return fail('Unknown wrong type: ' + typeof input);\n }\n}\n/** Hacky method to try to get the constructor name for an object. */\nfunction tryGetCustomObjectType(input) {\n if (input.constructor) {\n var funcNameRegex = /function\\s+([^\\s(]+)\\s*\\(/;\n var results = funcNameRegex.exec(input.constructor.toString());\n if (results && results.length > 1) {\n return results[1];\n }\n }\n return null;\n}\n/** Validates the provided argument is defined. */\nfunction validateDefined(functionName, position, argument) {\n if (argument === undefined) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires a valid \" + ordinal(position) + \" \" +\n \"argument, but it was undefined.\");\n }\n}\n/**\n * Validates the provided positional argument is an object, and its keys and\n * values match the expected keys and types provided in optionTypes.\n */\nfunction validateOptionNames(functionName, options, optionNames) {\n forEach(options, function (key, _) {\n if (optionNames.indexOf(key) < 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Unknown option '\" + key + \"' passed to function \" + functionName + \"(). \" +\n 'Available options: ' +\n optionNames.join(', '));\n }\n });\n}\n/**\n * Helper method to throw an error that the provided argument did not pass\n * an instanceof check.\n */\nfunction invalidClassError(functionName, type, position, argument) {\n var description = valueDescription(argument);\n return new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires its \" + ordinal(position) + \" \" +\n (\"argument to be a \" + type + \", but it was: \" + description));\n}\n/** Converts a number to its english word representation */\nfunction ordinal(num) {\n switch (num) {\n case 1:\n return 'first';\n case 2:\n return 'second';\n case 3:\n return 'third';\n default:\n return num + 'th';\n }\n}\n/**\n * Formats the given word as plural conditionally given the preceding number.\n */\nfunction formatPlural(num, str) {\n return num + \" \" + str + (num === 1 ? '' : 's');\n}\n\n//# sourceMappingURL=input_validation.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/misc.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// tslint:disable-next-line:class-as-namespace\nvar misc_AutoId = /** @class */ (function () {\n function AutoId() {\n }\n AutoId.newId = function () {\n // Alphanumeric characters\n var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n var autoId = '';\n for (var i = 0; i < 20; i++) {\n autoId += chars.charAt(Math.floor(Math.random() * chars.length));\n }\n assert(autoId.length === 20, 'Invalid auto ID: ' + autoId);\n return autoId;\n };\n return AutoId;\n}());\n\nfunction primitiveComparator(left, right) {\n if (left < right)\n return -1;\n if (left > right)\n return 1;\n return 0;\n}\n/** Helper to compare nullable (or undefined-able) objects using isEqual(). */\nfunction equals(left, right) {\n if (left !== null && left !== undefined) {\n return !!(right && left.isEqual(right));\n }\n else {\n // HACK: Explicitly cast since TypeScript's type narrowing apparently isn't\n // smart enough.\n return left === right;\n }\n}\n/** Helper to compare arrays using isEqual(). */\nfunction arrayEquals(left, right) {\n if (left.length !== right.length) {\n return false;\n }\n for (var i = 0; i < left.length; i++) {\n if (!left[i].isEqual(right[i])) {\n return false;\n }\n }\n return true;\n}\n/**\n * Returns the largest lexicographically smaller string of equal or smaller\n * length. Returns an empty string if there is no such predecessor (if the input\n * is empty).\n *\n * Strings returned from this method can be invalid UTF-16 but this is sufficent\n * in use for indexeddb because that depends on lexicographical ordering but\n * shouldn't be used elsewhere.\n */\nfunction immediatePredecessor(s) {\n // We can decrement the last character in the string and be done\n // unless that character is 0 (0x0000), in which case we have to erase the\n // last character.\n var lastIndex = s.length - 1;\n if (s.length === 0) {\n // Special case the empty string.\n return '';\n }\n else if (s.charAt(lastIndex) === '\\0') {\n return s.substring(0, lastIndex);\n }\n else {\n return (s.substring(0, lastIndex) +\n String.fromCharCode(s.charCodeAt(lastIndex) - 1));\n }\n}\n/**\n * Returns the immediate lexicographically-following string. This is useful to\n * construct an inclusive range for indexeddb iterators.\n */\nfunction immediateSuccessor(s) {\n // Return the input string, with an additional NUL byte appended.\n return s + '\\0';\n}\n\n//# sourceMappingURL=misc.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/api/blob.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n\n\n/** Helper function to assert Uint8Array is available at runtime. */\nfunction assertUint8ArrayAvailable() {\n if (typeof Uint8Array === 'undefined') {\n throw new FirestoreError(Code.UNIMPLEMENTED, 'Uint8Arrays are not available in this environment.');\n }\n}\n/** Helper function to assert Base64 functions are available at runtime. */\nfunction assertBase64Available() {\n if (!platform_PlatformSupport.getPlatform().base64Available) {\n throw new FirestoreError(Code.UNIMPLEMENTED, 'Blobs are unavailable in Firestore in this environment.');\n }\n}\n/**\n * Immutable class holding a blob (binary data).\n * This class is directly exposed in the public API.\n *\n * Note that while you can't hide the constructor in JavaScript code, we are\n * using the hack above to make sure no-one outside this module can call it.\n */\nvar blob_Blob = /** @class */ (function () {\n function Blob(binaryString) {\n assertBase64Available();\n this._binaryString = binaryString;\n }\n Blob.fromBase64String = function (base64) {\n validateExactNumberOfArgs('Blob.fromBase64String', arguments, 1);\n validateArgType('Blob.fromBase64String', 'string', 1, base64);\n assertBase64Available();\n try {\n var binaryString = platform_PlatformSupport.getPlatform().atob(base64);\n return new Blob(binaryString);\n }\n catch (e) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Failed to construct Blob from Base64 string: ' + e);\n }\n };\n Blob.fromUint8Array = function (array) {\n validateExactNumberOfArgs('Blob.fromUint8Array', arguments, 1);\n assertUint8ArrayAvailable();\n if (!(array instanceof Uint8Array)) {\n throw invalidClassError('Blob.fromUint8Array', 'Uint8Array', 1, array);\n }\n // We can't call array.map directly because it expects the return type to\n // be a Uint8Array, whereas we can convert it to a regular array by invoking\n // map on the Array prototype.\n var binaryString = Array.prototype.map\n .call(array, function (char) {\n return String.fromCharCode(char);\n })\n .join('');\n return new Blob(binaryString);\n };\n Blob.prototype.toBase64 = function () {\n validateExactNumberOfArgs('Blob.toBase64', arguments, 0);\n assertBase64Available();\n return platform_PlatformSupport.getPlatform().btoa(this._binaryString);\n };\n Blob.prototype.toUint8Array = function () {\n validateExactNumberOfArgs('Blob.toUint8Array', arguments, 0);\n assertUint8ArrayAvailable();\n var buffer = new Uint8Array(this._binaryString.length);\n for (var i = 0; i < this._binaryString.length; i++) {\n buffer[i] = this._binaryString.charCodeAt(i);\n }\n return buffer;\n };\n Blob.prototype.toString = function () {\n return 'Blob(base64: ' + this.toBase64() + ')';\n };\n Blob.prototype.isEqual = function (other) {\n return this._binaryString === other._binaryString;\n };\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */\n Blob.prototype._compareTo = function (other) {\n return primitiveComparator(this._binaryString, other._binaryString);\n };\n return Blob;\n}());\n\n// Public instance that disallows construction at runtime. This constructor is\n// used when exporting Blob on firebase.firestore.Blob and will be called Blob\n// publicly. Internally we still use Blob which has a type checked private\n// constructor. Note that Blob and PublicBlob can be used interchangeably in\n// instanceof checks.\n// For our internal TypeScript code PublicBlob doesn't exist as a type, and so\n// we need to use Blob as type and export it too.\n// tslint:disable-next-line:variable-name We're treating this as a class name.\nvar PublicBlob = makeConstructorPrivate(blob_Blob, 'Use Blob.fromUint8Array() or Blob.fromBase64String() instead.');\n\n//# sourceMappingURL=blob.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/api/geo_point.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n/**\n * Immutable class representing a geo point as latitude-longitude pair.\n * This class is directly exposed in the public API, including its constructor.\n */\nvar geo_point_GeoPoint = /** @class */ (function () {\n function GeoPoint(latitude, longitude) {\n validateExactNumberOfArgs('GeoPoint', arguments, 2);\n validateArgType('GeoPoint', 'number', 1, latitude);\n validateArgType('GeoPoint', 'number', 2, longitude);\n if (!isFinite(latitude) || latitude < -90 || latitude > 90) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Latitude must be a number between -90 and 90, but was: ' + latitude);\n }\n if (!isFinite(longitude) || longitude < -180 || longitude > 180) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Longitude must be a number between -180 and 180, but was: ' + longitude);\n }\n this._lat = latitude;\n this._long = longitude;\n }\n Object.defineProperty(GeoPoint.prototype, \"latitude\", {\n /**\n * Returns the latitude of this geo point, a number between -90 and 90.\n */\n get: function () {\n return this._lat;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GeoPoint.prototype, \"longitude\", {\n /**\n * Returns the longitude of this geo point, a number between -180 and 180.\n */\n get: function () {\n return this._long;\n },\n enumerable: true,\n configurable: true\n });\n GeoPoint.prototype.isEqual = function (other) {\n return this._lat === other._lat && this._long === other._long;\n };\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */\n GeoPoint.prototype._compareTo = function (other) {\n return (primitiveComparator(this._lat, other._lat) ||\n primitiveComparator(this._long, other._long));\n };\n return GeoPoint;\n}());\n\n\n//# sourceMappingURL=geo_point.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/database_info.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nvar DatabaseInfo = /** @class */ (function () {\n /**\n * Constructs a DatabaseInfo using the provided host, databaseId and\n * persistenceKey.\n *\n * @param databaseId The database to use.\n * @param persistenceKey A unique identifier for this Firestore's local\n * storage (used in conjunction with the databaseId).\n * @param host The Firestore backend host to connect to.\n * @param ssl Whether to use SSL when connecting.\n */\n function DatabaseInfo(databaseId, persistenceKey, host, ssl) {\n this.databaseId = databaseId;\n this.persistenceKey = persistenceKey;\n this.host = host;\n this.ssl = ssl;\n }\n return DatabaseInfo;\n}());\n\n/** The default database name for a project. */\nvar DEFAULT_DATABASE_NAME = '(default)';\n/** Represents the database ID a Firestore client is associated with. */\nvar database_info_DatabaseId = /** @class */ (function () {\n function DatabaseId(projectId, database) {\n this.projectId = projectId;\n this.database = database ? database : DEFAULT_DATABASE_NAME;\n }\n Object.defineProperty(DatabaseId.prototype, \"isDefaultDatabase\", {\n get: function () {\n return this.database === DEFAULT_DATABASE_NAME;\n },\n enumerable: true,\n configurable: true\n });\n DatabaseId.prototype.isEqual = function (other) {\n return (other instanceof DatabaseId &&\n other.projectId === this.projectId &&\n other.database === this.database);\n };\n DatabaseId.prototype.compareTo = function (other) {\n return (primitiveComparator(this.projectId, other.projectId) ||\n primitiveComparator(this.database, other.database));\n };\n return DatabaseId;\n}());\n\n\n//# sourceMappingURL=database_info.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/model/path.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar path___extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n\n\nvar DOCUMENT_KEY_NAME = '__name__';\n/**\n * Path represents an ordered sequence of string segments.\n */\nvar path_Path = /** @class */ (function () {\n function Path(segments, offset, length) {\n this.init(segments, offset, length);\n }\n /**\n * An initialization method that can be called from outside the constructor.\n * We need this so that we can have a non-static construct method that returns\n * the polymorphic `this` type.\n */\n Path.prototype.init = function (segments, offset, length) {\n if (offset === undefined) {\n offset = 0;\n }\n else if (offset > segments.length) {\n fail('offset ' + offset + ' out of range ' + segments.length);\n }\n if (length === undefined) {\n length = segments.length - offset;\n }\n else if (length > segments.length - offset) {\n fail('length ' + length + ' out of range ' + (segments.length - offset));\n }\n this.segments = segments;\n this.offset = offset;\n this.len = length;\n };\n /**\n * Constructs a new instance of Path using the same concrete type as `this`.\n * We need this instead of using the normal constructor, because polymorphic\n * `this` doesn't work on static methods.\n */\n Path.prototype.construct = function (segments, offset, length) {\n var path = Object.create(Object.getPrototypeOf(this));\n path.init(segments, offset, length);\n return path;\n };\n Object.defineProperty(Path.prototype, \"length\", {\n get: function () {\n return this.len;\n },\n enumerable: true,\n configurable: true\n });\n Path.prototype.isEqual = function (other) {\n return Path.comparator(this, other) === 0;\n };\n Path.prototype.child = function (nameOrPath) {\n var segments = this.segments.slice(this.offset, this.limit());\n if (nameOrPath instanceof Path) {\n nameOrPath.forEach(function (segment) {\n segments.push(segment);\n });\n }\n else if (typeof nameOrPath === 'string') {\n segments.push(nameOrPath);\n }\n else {\n fail('Unknown parameter type for Path.child(): ' + nameOrPath);\n }\n return this.construct(segments);\n };\n /** The index of one past the last segment of the path. */\n Path.prototype.limit = function () {\n return this.offset + this.length;\n };\n Path.prototype.popFirst = function (size) {\n size = size === undefined ? 1 : size;\n assert(this.length >= size, \"Can't call popFirst() with less segments\");\n return this.construct(this.segments, this.offset + size, this.length - size);\n };\n Path.prototype.popLast = function () {\n assert(!this.isEmpty(), \"Can't call popLast() on empty path\");\n return this.construct(this.segments, this.offset, this.length - 1);\n };\n Path.prototype.firstSegment = function () {\n assert(!this.isEmpty(), \"Can't call firstSegment() on empty path\");\n return this.segments[this.offset];\n };\n Path.prototype.lastSegment = function () {\n assert(!this.isEmpty(), \"Can't call lastSegment() on empty path\");\n return this.segments[this.limit() - 1];\n };\n Path.prototype.get = function (index) {\n assert(index < this.length, 'Index out of range');\n return this.segments[this.offset + index];\n };\n Path.prototype.isEmpty = function () {\n return this.length === 0;\n };\n Path.prototype.isPrefixOf = function (other) {\n if (other.length < this.length) {\n return false;\n }\n for (var i = 0; i < this.length; i++) {\n if (this.get(i) !== other.get(i)) {\n return false;\n }\n }\n return true;\n };\n Path.prototype.forEach = function (fn) {\n for (var i = this.offset, end = this.limit(); i < end; i++) {\n fn(this.segments[i]);\n }\n };\n Path.prototype.toArray = function () {\n return this.segments.slice(this.offset, this.limit());\n };\n Path.comparator = function (p1, p2) {\n var len = Math.min(p1.length, p2.length);\n for (var i = 0; i < len; i++) {\n var left = p1.get(i);\n var right = p2.get(i);\n if (left < right)\n return -1;\n if (left > right)\n return 1;\n }\n if (p1.length < p2.length)\n return -1;\n if (p1.length > p2.length)\n return 1;\n return 0;\n };\n return Path;\n}());\n\n/**\n * A slash-separated path for navigating resources (documents and collections)\n * within Firestore.\n */\nvar path_ResourcePath = /** @class */ (function (_super) {\n path___extends(ResourcePath, _super);\n function ResourcePath() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n ResourcePath.prototype.canonicalString = function () {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n return this.toArray().join('/');\n };\n ResourcePath.prototype.toString = function () {\n return this.canonicalString();\n };\n /**\n * Creates a resource path from the given slash-delimited string.\n */\n ResourcePath.fromString = function (path) {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n if (path.indexOf('//') >= 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid path (\" + path + \"). Paths must not contain // in them.\");\n }\n // We may still have an empty segment at the beginning or end if they had a\n // leading or trailing slash (which we allow).\n var segments = path.split('/').filter(function (segment) { return segment.length > 0; });\n return new ResourcePath(segments);\n };\n ResourcePath.EMPTY_PATH = new ResourcePath([]);\n return ResourcePath;\n}(path_Path));\n\nvar identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/;\n/** A dot-separated path for navigating sub-objects within a document. */\nvar path_FieldPath = /** @class */ (function (_super) {\n path___extends(FieldPath, _super);\n function FieldPath() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Returns true if the string could be used as a segment in a field path\n * without escaping.\n */\n FieldPath.isValidIdentifier = function (segment) {\n return identifierRegExp.test(segment);\n };\n FieldPath.prototype.canonicalString = function () {\n return this.toArray()\n .map(function (str) {\n str = str.replace('\\\\', '\\\\\\\\').replace('`', '\\\\`');\n if (!FieldPath.isValidIdentifier(str)) {\n str = '`' + str + '`';\n }\n return str;\n })\n .join('.');\n };\n FieldPath.prototype.toString = function () {\n return this.canonicalString();\n };\n /**\n * Returns true if this field references the key of a document.\n */\n FieldPath.prototype.isKeyField = function () {\n return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME;\n };\n /**\n * The field designating the key of a document.\n */\n FieldPath.keyField = function () {\n return new FieldPath([DOCUMENT_KEY_NAME]);\n };\n /**\n * Parses a field string from the given server-formatted string.\n *\n * - Splitting the empty string is not allowed (for now at least).\n * - Empty segments within the string (e.g. if there are two consecutive\n * separators) are not allowed.\n *\n * TODO(b/37244157): we should make this more strict. Right now, it allows\n * non-identifier path components, even if they aren't escaped.\n */\n FieldPath.fromServerFormat = function (path) {\n var segments = [];\n var current = '';\n var i = 0;\n var addCurrentSegment = function () {\n if (current.length === 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field path (\" + path + \"). Paths must not be empty, begin \" +\n \"with '.', end with '.', or contain '..'\");\n }\n segments.push(current);\n current = '';\n };\n var inBackticks = false;\n while (i < path.length) {\n var c = path[i];\n if (c === '\\\\') {\n if (i + 1 === path.length) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has trailing escape character: ' + path);\n }\n var next = path[i + 1];\n if (!(next === '\\\\' || next === '.' || next === '`')) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has invalid escape sequence: ' + path);\n }\n current += next;\n i += 2;\n }\n else if (c === '`') {\n inBackticks = !inBackticks;\n i++;\n }\n else if (c === '.' && !inBackticks) {\n addCurrentSegment();\n i++;\n }\n else {\n current += c;\n i++;\n }\n }\n addCurrentSegment();\n if (inBackticks) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Unterminated ` in path: ' + path);\n }\n return new FieldPath(segments);\n };\n FieldPath.EMPTY_PATH = new FieldPath([]);\n return FieldPath;\n}(path_Path));\n\n\n//# sourceMappingURL=path.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/model/document_key.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\nvar document_key_DocumentKey = /** @class */ (function () {\n function DocumentKey(path) {\n this.path = path;\n assert(DocumentKey.isDocumentKey(path), 'Invalid DocumentKey with an odd number of segments: ' +\n path.toArray().join('/'));\n }\n DocumentKey.prototype.isEqual = function (other) {\n return (other !== null && path_ResourcePath.comparator(this.path, other.path) === 0);\n };\n DocumentKey.prototype.toString = function () {\n return this.path.toString();\n };\n DocumentKey.comparator = function (k1, k2) {\n return path_ResourcePath.comparator(k1.path, k2.path);\n };\n DocumentKey.isDocumentKey = function (path) {\n return path.length % 2 === 0;\n };\n /**\n * Creates and returns a new document key with the given segments.\n *\n * @param path The segments of the path to the document\n * @return A new instance of DocumentKey\n */\n DocumentKey.fromSegments = function (segments) {\n return new DocumentKey(new path_ResourcePath(segments.slice()));\n };\n /**\n * Creates and returns a new document key using '/' to split the string into\n * segments.\n *\n * @param path The slash-separated path string to the document\n * @return A new instance of DocumentKey\n */\n DocumentKey.fromPathString = function (path) {\n return new DocumentKey(path_ResourcePath.fromString(path));\n };\n DocumentKey.EMPTY = new DocumentKey(new path_ResourcePath([]));\n return DocumentKey;\n}());\n\n\n//# sourceMappingURL=document_key.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/model/document.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\nvar document_Document = /** @class */ (function () {\n function Document(key, version, data, options) {\n this.key = key;\n this.version = version;\n this.data = data;\n this.hasLocalMutations = options.hasLocalMutations;\n }\n Document.prototype.field = function (path) {\n return this.data.field(path);\n };\n Document.prototype.fieldValue = function (path) {\n var field = this.field(path);\n return field ? field.value() : undefined;\n };\n Document.prototype.value = function () {\n return this.data.value();\n };\n Document.prototype.isEqual = function (other) {\n return (other instanceof Document &&\n this.key.isEqual(other.key) &&\n this.version.isEqual(other.version) &&\n this.data.isEqual(other.data) &&\n this.hasLocalMutations === other.hasLocalMutations);\n };\n Document.prototype.toString = function () {\n return (\"Document(\" + this.key + \", \" + this.version + \", \" + this.data.toString() + \", \" +\n (\"{hasLocalMutations: \" + this.hasLocalMutations + \"})\"));\n };\n Document.compareByKey = function (d1, d2) {\n return document_key_DocumentKey.comparator(d1.key, d2.key);\n };\n Document.compareByField = function (field, d1, d2) {\n var v1 = d1.field(field);\n var v2 = d2.field(field);\n if (v1 !== undefined && v2 !== undefined) {\n return v1.compareTo(v2);\n }\n else {\n return fail(\"Trying to compare documents on fields that don't exist\");\n }\n };\n return Document;\n}());\n\n/**\n * A class representing a deleted document.\n * Version is set to 0 if we don't point to any specific time, otherwise it\n * denotes time we know it didn't exist at.\n */\nvar document_NoDocument = /** @class */ (function () {\n function NoDocument(key, version) {\n this.key = key;\n this.version = version;\n }\n NoDocument.prototype.toString = function () {\n return \"NoDocument(\" + this.key + \", \" + this.version + \")\";\n };\n NoDocument.prototype.isEqual = function (other) {\n return (other &&\n other.version.isEqual(this.version) &&\n other.key.isEqual(this.key));\n };\n NoDocument.compareByKey = function (d1, d2) {\n return document_key_DocumentKey.comparator(d1.key, d2.key);\n };\n return NoDocument;\n}());\n\n\n//# sourceMappingURL=document.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/sorted_map.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// An immutable sorted map implementation, based on a Left-leaning Red-Black\n// tree.\nvar sorted_map_SortedMap = /** @class */ (function () {\n function SortedMap(comparator, root) {\n this.comparator = comparator;\n this.root = root ? root : sorted_map_LLRBNode.EMPTY;\n }\n // Returns a copy of the map, with the specified key/value added or replaced.\n SortedMap.prototype.insert = function (key, value) {\n return new SortedMap(this.comparator, this.root\n .insert(key, value, this.comparator)\n .copy(null, null, sorted_map_LLRBNode.BLACK, null, null));\n };\n // Returns a copy of the map, with the specified key removed.\n SortedMap.prototype.remove = function (key) {\n return new SortedMap(this.comparator, this.root\n .remove(key, this.comparator)\n .copy(null, null, sorted_map_LLRBNode.BLACK, null, null));\n };\n // Returns the value of the node with the given key, or null.\n SortedMap.prototype.get = function (key) {\n var node = this.root;\n while (!node.isEmpty()) {\n var cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return node.value;\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else if (cmp > 0) {\n node = node.right;\n }\n }\n return null;\n };\n // Returns the key of the item *before* the specified key, or null if key is\n // the first item.\n SortedMap.prototype.getPredecessorKey = function (key) {\n var node = this.root;\n var rightParent = null;\n while (!node.isEmpty()) {\n var cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n if (!node.left.isEmpty()) {\n node = node.left;\n while (!node.right.isEmpty())\n node = node.right;\n return node.key;\n }\n else if (rightParent) {\n return rightParent.key;\n }\n else {\n return null; // first item.\n }\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else if (cmp > 0) {\n rightParent = node;\n node = node.right;\n }\n }\n throw fail('Attempted to find predecessor key for a nonexistent key.' +\n ' What gives?');\n };\n // Returns the index of the element in this sorted map, or -1 if it doesn't\n // exist.\n SortedMap.prototype.indexOf = function (key) {\n // Number of nodes that were pruned when descending right\n var prunedNodes = 0;\n var node = this.root;\n while (!node.isEmpty()) {\n var cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return prunedNodes + node.left.size;\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else {\n // Count all nodes left of the node plus the node itself\n prunedNodes += node.left.size + 1;\n node = node.right;\n }\n }\n // Node not found\n return -1;\n };\n SortedMap.prototype.isEmpty = function () {\n return this.root.isEmpty();\n };\n Object.defineProperty(SortedMap.prototype, \"size\", {\n // Returns the total number of nodes in the map.\n get: function () {\n return this.root.size;\n },\n enumerable: true,\n configurable: true\n });\n // Returns the minimum key in the map.\n SortedMap.prototype.minKey = function () {\n return this.root.minKey();\n };\n // Returns the maximum key in the map.\n SortedMap.prototype.maxKey = function () {\n return this.root.maxKey();\n };\n // Traverses the map in key order and calls the specified action function\n // for each key/value pair. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n SortedMap.prototype.inorderTraversal = function (action) {\n return this.root.inorderTraversal(action);\n };\n SortedMap.prototype.forEach = function (fn) {\n this.inorderTraversal(function (k, v) {\n fn(k, v);\n return false;\n });\n };\n // Traverses the map in reverse key order and calls the specified action\n // function for each key/value pair. If action returns true, traversal is\n // aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n SortedMap.prototype.reverseTraversal = function (action) {\n return this.root.reverseTraversal(action);\n };\n // Returns an iterator over the SortedMap.\n SortedMap.prototype.getIterator = function () {\n return new sorted_map_SortedMapIterator(this.root, null, this.comparator, false);\n };\n SortedMap.prototype.getIteratorFrom = function (key) {\n return new sorted_map_SortedMapIterator(this.root, key, this.comparator, false);\n };\n SortedMap.prototype.getReverseIterator = function () {\n return new sorted_map_SortedMapIterator(this.root, null, this.comparator, true);\n };\n SortedMap.prototype.getReverseIteratorFrom = function (key) {\n return new sorted_map_SortedMapIterator(this.root, key, this.comparator, true);\n };\n return SortedMap;\n}()); // end SortedMap\n\n// An iterator over an LLRBNode.\nvar sorted_map_SortedMapIterator = /** @class */ (function () {\n function SortedMapIterator(node, startKey, comparator, isReverse) {\n this.isReverse = isReverse;\n this.nodeStack = [];\n var cmp = 1;\n while (!node.isEmpty()) {\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (isReverse)\n cmp *= -1;\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse) {\n node = node.left;\n }\n else {\n node = node.right;\n }\n }\n else if (cmp === 0) {\n // This node is exactly equal to our start key. Push it on the stack,\n // but stop iterating;\n this.nodeStack.push(node);\n break;\n }\n else {\n // This node is greater than our start key, add it to the stack and move\n // to the next one\n this.nodeStack.push(node);\n if (this.isReverse) {\n node = node.right;\n }\n else {\n node = node.left;\n }\n }\n }\n }\n SortedMapIterator.prototype.getNext = function () {\n assert(this.nodeStack.length > 0, 'getNext() called on iterator when hasNext() is false.');\n var node = this.nodeStack.pop();\n var result = { key: node.key, value: node.value };\n if (this.isReverse) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.right;\n }\n }\n else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.left;\n }\n }\n return result;\n };\n SortedMapIterator.prototype.hasNext = function () {\n return this.nodeStack.length > 0;\n };\n SortedMapIterator.prototype.peek = function () {\n if (this.nodeStack.length === 0)\n return null;\n var node = this.nodeStack[this.nodeStack.length - 1];\n return { key: node.key, value: node.value };\n };\n return SortedMapIterator;\n}()); // end SortedMapIterator\n\n// Represents a node in a Left-leaning Red-Black tree.\nvar sorted_map_LLRBNode = /** @class */ (function () {\n function LLRBNode(key, value, color, left, right) {\n this.key = key;\n this.value = value;\n this.color = color != null ? color : LLRBNode.RED;\n this.left = left != null ? left : LLRBNode.EMPTY;\n this.right = right != null ? right : LLRBNode.EMPTY;\n this.size = this.left.size + 1 + this.right.size;\n }\n // Returns a copy of the current node, optionally replacing pieces of it.\n LLRBNode.prototype.copy = function (key, value, color, left, right) {\n return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);\n };\n LLRBNode.prototype.isEmpty = function () {\n return false;\n };\n // Traverses the tree in key order and calls the specified action function\n // for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n LLRBNode.prototype.inorderTraversal = function (action) {\n return (this.left.inorderTraversal(action) ||\n action(this.key, this.value) ||\n this.right.inorderTraversal(action));\n };\n // Traverses the tree in reverse key order and calls the specified action\n // function for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n LLRBNode.prototype.reverseTraversal = function (action) {\n return (this.right.reverseTraversal(action) ||\n action(this.key, this.value) ||\n this.left.reverseTraversal(action));\n };\n // Returns the minimum node in the tree.\n LLRBNode.prototype.min = function () {\n if (this.left.isEmpty()) {\n return this;\n }\n else {\n return this.left.min();\n }\n };\n // Returns the maximum key in the tree.\n LLRBNode.prototype.minKey = function () {\n return this.min().key;\n };\n // Returns the maximum key in the tree.\n LLRBNode.prototype.maxKey = function () {\n if (this.right.isEmpty()) {\n return this.key;\n }\n else {\n return this.right.maxKey();\n }\n };\n // Returns new tree, with the key/value added.\n LLRBNode.prototype.insert = function (key, value, comparator) {\n var n = this;\n var cmp = comparator(key, n.key);\n if (cmp < 0) {\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n }\n else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n }\n else {\n n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));\n }\n return n.fixUp();\n };\n LLRBNode.prototype.removeMin = function () {\n if (this.left.isEmpty()) {\n return LLRBNode.EMPTY;\n }\n var n = this;\n if (!n.left.isRed() && !n.left.left.isRed())\n n = n.moveRedLeft();\n n = n.copy(null, null, null, n.left.removeMin(), null);\n return n.fixUp();\n };\n // Returns new tree, with the specified item removed.\n LLRBNode.prototype.remove = function (key, comparator) {\n var smallest;\n var n = this;\n if (comparator(key, n.key) < 0) {\n if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {\n n = n.moveRedLeft();\n }\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n }\n else {\n if (n.left.isRed())\n n = n.rotateRight();\n if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {\n n = n.moveRedRight();\n }\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return LLRBNode.EMPTY;\n }\n else {\n smallest = n.right.min();\n n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin());\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp();\n };\n LLRBNode.prototype.isRed = function () {\n return this.color;\n };\n // Returns new tree after performing any needed rotations.\n LLRBNode.prototype.fixUp = function () {\n var n = this;\n if (n.right.isRed() && !n.left.isRed())\n n = n.rotateLeft();\n if (n.left.isRed() && n.left.left.isRed())\n n = n.rotateRight();\n if (n.left.isRed() && n.right.isRed())\n n = n.colorFlip();\n return n;\n };\n LLRBNode.prototype.moveRedLeft = function () {\n var n = this.colorFlip();\n if (n.right.left.isRed()) {\n n = n.copy(null, null, null, null, n.right.rotateRight());\n n = n.rotateLeft();\n n = n.colorFlip();\n }\n return n;\n };\n LLRBNode.prototype.moveRedRight = function () {\n var n = this.colorFlip();\n if (n.left.left.isRed()) {\n n = n.rotateRight();\n n = n.colorFlip();\n }\n return n;\n };\n LLRBNode.prototype.rotateLeft = function () {\n var nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return this.right.copy(null, null, this.color, nl, null);\n };\n LLRBNode.prototype.rotateRight = function () {\n var nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return this.left.copy(null, null, this.color, null, nr);\n };\n LLRBNode.prototype.colorFlip = function () {\n var left = this.left.copy(null, null, !this.left.color, null, null);\n var right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n };\n // For testing.\n LLRBNode.prototype.checkMaxDepth = function () {\n var blackDepth = this.check();\n if (Math.pow(2.0, blackDepth) <= this.size + 1) {\n return true;\n }\n else {\n return false;\n }\n };\n // In a balanced RB tree, the black-depth (number of black nodes) from root to\n // leaves is equal on both sides. This function verifies that or asserts.\n LLRBNode.prototype.check = function () {\n if (this.isRed() && this.left.isRed()) {\n throw fail('Red node has red child(' + this.key + ',' + this.value + ')');\n }\n if (this.right.isRed()) {\n throw fail('Right child of (' + this.key + ',' + this.value + ') is red');\n }\n var blackDepth = this.left.check();\n if (blackDepth !== this.right.check()) {\n throw fail('Black depths differ');\n }\n else {\n return blackDepth + (this.isRed() ? 0 : 1);\n }\n };\n // tslint:disable-next-line:no-any Empty node is shared between all LLRB trees.\n LLRBNode.EMPTY = null;\n LLRBNode.RED = true;\n LLRBNode.BLACK = false;\n return LLRBNode;\n}()); // end LLRBNode\n\n// Represents an empty node (a leaf node in the Red-Black Tree).\nvar LLRBEmptyNode = /** @class */ (function () {\n function LLRBEmptyNode() {\n this.size = 0;\n }\n // Returns a copy of the current node.\n LLRBEmptyNode.prototype.copy = function (key, value, color, left, right) {\n return this;\n };\n // Returns a copy of the tree, with the specified key/value added.\n LLRBEmptyNode.prototype.insert = function (key, value, comparator) {\n return new sorted_map_LLRBNode(key, value);\n };\n // Returns a copy of the tree, with the specified key removed.\n LLRBEmptyNode.prototype.remove = function (key, comparator) {\n return this;\n };\n LLRBEmptyNode.prototype.isEmpty = function () {\n return true;\n };\n LLRBEmptyNode.prototype.inorderTraversal = function (action) {\n return false;\n };\n LLRBEmptyNode.prototype.reverseTraversal = function (action) {\n return false;\n };\n LLRBEmptyNode.prototype.minKey = function () {\n return null;\n };\n LLRBEmptyNode.prototype.maxKey = function () {\n return null;\n };\n LLRBEmptyNode.prototype.isRed = function () {\n return false;\n };\n // For testing.\n LLRBEmptyNode.prototype.checkMaxDepth = function () {\n return true;\n };\n LLRBEmptyNode.prototype.check = function () {\n return 0;\n };\n return LLRBEmptyNode;\n}()); // end LLRBEmptyNode\n\nsorted_map_LLRBNode.EMPTY = new LLRBEmptyNode();\n\n//# sourceMappingURL=sorted_map.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/model/field_value.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar field_value___extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n\n\n\n\nvar TypeOrder;\n(function (TypeOrder) {\n // This order is defined by the backend.\n TypeOrder[TypeOrder[\"NullValue\"] = 0] = \"NullValue\";\n TypeOrder[TypeOrder[\"BooleanValue\"] = 1] = \"BooleanValue\";\n TypeOrder[TypeOrder[\"NumberValue\"] = 2] = \"NumberValue\";\n TypeOrder[TypeOrder[\"TimestampValue\"] = 3] = \"TimestampValue\";\n TypeOrder[TypeOrder[\"StringValue\"] = 4] = \"StringValue\";\n TypeOrder[TypeOrder[\"BlobValue\"] = 5] = \"BlobValue\";\n TypeOrder[TypeOrder[\"RefValue\"] = 6] = \"RefValue\";\n TypeOrder[TypeOrder[\"GeoPointValue\"] = 7] = \"GeoPointValue\";\n TypeOrder[TypeOrder[\"ArrayValue\"] = 8] = \"ArrayValue\";\n TypeOrder[TypeOrder[\"ObjectValue\"] = 9] = \"ObjectValue\";\n})(TypeOrder || (TypeOrder = {}));\n/** Defines the return value for pending server timestamps. */\nvar ServerTimestampBehavior;\n(function (ServerTimestampBehavior) {\n ServerTimestampBehavior[ServerTimestampBehavior[\"Default\"] = 0] = \"Default\";\n ServerTimestampBehavior[ServerTimestampBehavior[\"Estimate\"] = 1] = \"Estimate\";\n ServerTimestampBehavior[ServerTimestampBehavior[\"Previous\"] = 2] = \"Previous\";\n})(ServerTimestampBehavior || (ServerTimestampBehavior = {}));\n/** Holds properties that define field value deserialization options. */\nvar field_value_FieldValueOptions = /** @class */ (function () {\n function FieldValueOptions(serverTimestampBehavior) {\n this.serverTimestampBehavior = serverTimestampBehavior;\n }\n FieldValueOptions.fromSnapshotOptions = function (options) {\n switch (options.serverTimestamps) {\n case 'estimate':\n return new FieldValueOptions(ServerTimestampBehavior.Estimate);\n case 'previous':\n return new FieldValueOptions(ServerTimestampBehavior.Previous);\n case 'none': // Fall-through intended.\n case undefined:\n return FieldValueOptions.defaultOptions;\n default:\n return fail('fromSnapshotOptions() called with invalid options.');\n }\n };\n FieldValueOptions.defaultOptions = new FieldValueOptions(ServerTimestampBehavior.Default);\n return FieldValueOptions;\n}());\n\n/**\n * A field value represents a datatype as stored by Firestore.\n */\nvar field_value_FieldValue = /** @class */ (function () {\n function FieldValue() {\n }\n FieldValue.prototype.toString = function () {\n var val = this.value();\n return val === null ? 'null' : val.toString();\n };\n FieldValue.prototype.defaultCompareTo = function (other) {\n assert(this.typeOrder !== other.typeOrder, 'Default compareTo should not be used for values of same type.');\n var cmp = primitiveComparator(this.typeOrder, other.typeOrder);\n return cmp;\n };\n return FieldValue;\n}());\n\nvar NullValue = /** @class */ (function (_super) {\n field_value___extends(NullValue, _super);\n function NullValue() {\n var _this = _super.call(this) || this;\n _this.typeOrder = TypeOrder.NullValue;\n // internalValue is unused but we add it to work around\n // https://github.com/Microsoft/TypeScript/issues/15585\n _this.internalValue = null;\n return _this;\n }\n NullValue.prototype.value = function (options) {\n return null;\n };\n NullValue.prototype.isEqual = function (other) {\n return other instanceof NullValue;\n };\n NullValue.prototype.compareTo = function (other) {\n if (other instanceof NullValue) {\n return 0;\n }\n return this.defaultCompareTo(other);\n };\n NullValue.INSTANCE = new NullValue();\n return NullValue;\n}(field_value_FieldValue));\n\nvar field_value_BooleanValue = /** @class */ (function (_super) {\n field_value___extends(BooleanValue, _super);\n function BooleanValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.BooleanValue;\n return _this;\n }\n BooleanValue.prototype.value = function (options) {\n return this.internalValue;\n };\n BooleanValue.prototype.isEqual = function (other) {\n return (other instanceof BooleanValue &&\n this.internalValue === other.internalValue);\n };\n BooleanValue.prototype.compareTo = function (other) {\n if (other instanceof BooleanValue) {\n return primitiveComparator(this, other);\n }\n return this.defaultCompareTo(other);\n };\n BooleanValue.of = function (value) {\n return value ? BooleanValue.TRUE : BooleanValue.FALSE;\n };\n BooleanValue.TRUE = new BooleanValue(true);\n BooleanValue.FALSE = new BooleanValue(false);\n return BooleanValue;\n}(field_value_FieldValue));\n\n/** Base class for IntegerValue and DoubleValue. */\nvar NumberValue = /** @class */ (function (_super) {\n field_value___extends(NumberValue, _super);\n function NumberValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.NumberValue;\n return _this;\n }\n NumberValue.prototype.value = function (options) {\n return this.internalValue;\n };\n NumberValue.prototype.compareTo = function (other) {\n if (other instanceof NumberValue) {\n return numericComparator(this.internalValue, other.internalValue);\n }\n return this.defaultCompareTo(other);\n };\n return NumberValue;\n}(field_value_FieldValue));\n\n/** Utility function to compare doubles (using Firestore semantics for NaN). */\nfunction numericComparator(left, right) {\n if (left < right) {\n return -1;\n }\n else if (left > right) {\n return 1;\n }\n else if (left === right) {\n return 0;\n }\n else {\n // one or both are NaN.\n if (isNaN(left)) {\n return isNaN(right) ? 0 : -1;\n }\n else {\n return 1;\n }\n }\n}\n/**\n * Utility function to check numbers for equality using Firestore semantics\n * (NaN === NaN, -0.0 !== 0.0).\n */\nfunction numericEquals(left, right) {\n // Implemented based on Object.is() polyfill from\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n if (left === right) {\n // +0 != -0\n return left !== 0 || 1 / left === 1 / right;\n }\n else {\n // NaN == NaN\n return left !== left && right !== right;\n }\n}\nvar IntegerValue = /** @class */ (function (_super) {\n field_value___extends(IntegerValue, _super);\n function IntegerValue(internalValue) {\n return _super.call(this, internalValue) || this;\n }\n IntegerValue.prototype.isEqual = function (other) {\n // NOTE: DoubleValue and IntegerValue instances may compareTo() the same,\n // but that doesn't make them equal via isEqual().\n if (other instanceof IntegerValue) {\n return numericEquals(this.internalValue, other.internalValue);\n }\n else {\n return false;\n }\n };\n return IntegerValue;\n}(NumberValue));\n\nvar DoubleValue = /** @class */ (function (_super) {\n field_value___extends(DoubleValue, _super);\n function DoubleValue(internalValue) {\n var _this = _super.call(this, internalValue) || this;\n _this.internalValue = internalValue;\n return _this;\n }\n DoubleValue.prototype.isEqual = function (other) {\n // NOTE: DoubleValue and IntegerValue instances may compareTo() the same,\n // but that doesn't make them equal via isEqual().\n if (other instanceof DoubleValue) {\n return numericEquals(this.internalValue, other.internalValue);\n }\n else {\n return false;\n }\n };\n DoubleValue.NAN = new DoubleValue(NaN);\n DoubleValue.POSITIVE_INFINITY = new DoubleValue(Infinity);\n DoubleValue.NEGATIVE_INFINITY = new DoubleValue(-Infinity);\n return DoubleValue;\n}(NumberValue));\n\n// TODO(b/37267885): Add truncation support\nvar field_value_StringValue = /** @class */ (function (_super) {\n field_value___extends(StringValue, _super);\n function StringValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.StringValue;\n return _this;\n }\n StringValue.prototype.value = function (options) {\n return this.internalValue;\n };\n StringValue.prototype.isEqual = function (other) {\n return (other instanceof StringValue && this.internalValue === other.internalValue);\n };\n StringValue.prototype.compareTo = function (other) {\n if (other instanceof StringValue) {\n return primitiveComparator(this.internalValue, other.internalValue);\n }\n return this.defaultCompareTo(other);\n };\n return StringValue;\n}(field_value_FieldValue));\n\nvar TimestampValue = /** @class */ (function (_super) {\n field_value___extends(TimestampValue, _super);\n function TimestampValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.TimestampValue;\n return _this;\n }\n TimestampValue.prototype.value = function (options) {\n return this.internalValue.toDate();\n };\n TimestampValue.prototype.isEqual = function (other) {\n return (other instanceof TimestampValue &&\n this.internalValue.isEqual(other.internalValue));\n };\n TimestampValue.prototype.compareTo = function (other) {\n if (other instanceof TimestampValue) {\n return this.internalValue.compareTo(other.internalValue);\n }\n else if (other instanceof ServerTimestampValue) {\n // Concrete timestamps come before server timestamps.\n return -1;\n }\n else {\n return this.defaultCompareTo(other);\n }\n };\n return TimestampValue;\n}(field_value_FieldValue));\n\n/**\n * Represents a locally-applied ServerTimestamp.\n *\n * Notes:\n * - ServerTimestampValue instances are created as the result of applying a\n * TransformMutation (see TransformMutation.applyTo()). They can only exist in\n * the local view of a document. Therefore they do not need to be parsed or\n * serialized.\n * - When evaluated locally (e.g. for snapshot.data()), they by default\n * evaluate to `null`. This behavior can be configured by passing custom\n * FieldValueOptions to value().\n * - With respect to other ServerTimestampValues, they sort by their\n * localWriteTime.\n */\nvar ServerTimestampValue = /** @class */ (function (_super) {\n field_value___extends(ServerTimestampValue, _super);\n function ServerTimestampValue(localWriteTime, previousValue) {\n var _this = _super.call(this) || this;\n _this.localWriteTime = localWriteTime;\n _this.previousValue = previousValue;\n _this.typeOrder = TypeOrder.TimestampValue;\n return _this;\n }\n ServerTimestampValue.prototype.value = function (options) {\n if (options &&\n options.serverTimestampBehavior === ServerTimestampBehavior.Estimate) {\n return this.localWriteTime.toDate();\n }\n else if (options &&\n options.serverTimestampBehavior === ServerTimestampBehavior.Previous) {\n return this.previousValue ? this.previousValue.value(options) : null;\n }\n else {\n return null;\n }\n };\n ServerTimestampValue.prototype.isEqual = function (other) {\n return (other instanceof ServerTimestampValue &&\n this.localWriteTime.isEqual(other.localWriteTime));\n };\n ServerTimestampValue.prototype.compareTo = function (other) {\n if (other instanceof ServerTimestampValue) {\n return this.localWriteTime.compareTo(other.localWriteTime);\n }\n else if (other instanceof TimestampValue) {\n // Server timestamps come after all concrete timestamps.\n return 1;\n }\n else {\n return this.defaultCompareTo(other);\n }\n };\n ServerTimestampValue.prototype.toString = function () {\n return '';\n };\n return ServerTimestampValue;\n}(field_value_FieldValue));\n\nvar BlobValue = /** @class */ (function (_super) {\n field_value___extends(BlobValue, _super);\n function BlobValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.BlobValue;\n return _this;\n }\n BlobValue.prototype.value = function (options) {\n return this.internalValue;\n };\n BlobValue.prototype.isEqual = function (other) {\n return (other instanceof BlobValue &&\n this.internalValue.isEqual(other.internalValue));\n };\n BlobValue.prototype.compareTo = function (other) {\n if (other instanceof BlobValue) {\n return this.internalValue._compareTo(other.internalValue);\n }\n return this.defaultCompareTo(other);\n };\n return BlobValue;\n}(field_value_FieldValue));\n\nvar field_value_RefValue = /** @class */ (function (_super) {\n field_value___extends(RefValue, _super);\n function RefValue(databaseId, key) {\n var _this = _super.call(this) || this;\n _this.databaseId = databaseId;\n _this.key = key;\n _this.typeOrder = TypeOrder.RefValue;\n return _this;\n }\n RefValue.prototype.value = function (options) {\n return this.key;\n };\n RefValue.prototype.isEqual = function (other) {\n if (other instanceof RefValue) {\n return (this.key.isEqual(other.key) && this.databaseId.isEqual(other.databaseId));\n }\n else {\n return false;\n }\n };\n RefValue.prototype.compareTo = function (other) {\n if (other instanceof RefValue) {\n var cmp = this.databaseId.compareTo(other.databaseId);\n return cmp !== 0 ? cmp : document_key_DocumentKey.comparator(this.key, other.key);\n }\n return this.defaultCompareTo(other);\n };\n return RefValue;\n}(field_value_FieldValue));\n\nvar GeoPointValue = /** @class */ (function (_super) {\n field_value___extends(GeoPointValue, _super);\n function GeoPointValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.GeoPointValue;\n return _this;\n }\n GeoPointValue.prototype.value = function (options) {\n return this.internalValue;\n };\n GeoPointValue.prototype.isEqual = function (other) {\n return (other instanceof GeoPointValue &&\n this.internalValue.isEqual(other.internalValue));\n };\n GeoPointValue.prototype.compareTo = function (other) {\n if (other instanceof GeoPointValue) {\n return this.internalValue._compareTo(other.internalValue);\n }\n return this.defaultCompareTo(other);\n };\n return GeoPointValue;\n}(field_value_FieldValue));\n\nvar field_value_ObjectValue = /** @class */ (function (_super) {\n field_value___extends(ObjectValue, _super);\n function ObjectValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.ObjectValue;\n return _this;\n }\n ObjectValue.prototype.value = function (options) {\n var result = {};\n this.internalValue.inorderTraversal(function (key, val) {\n result[key] = val.value(options);\n });\n return result;\n };\n ObjectValue.prototype.forEach = function (action) {\n this.internalValue.inorderTraversal(action);\n };\n ObjectValue.prototype.isEqual = function (other) {\n if (other instanceof ObjectValue) {\n var it1 = this.internalValue.getIterator();\n var it2 = other.internalValue.getIterator();\n while (it1.hasNext() && it2.hasNext()) {\n var next1 = it1.getNext();\n var next2 = it2.getNext();\n if (next1.key !== next2.key || !next1.value.isEqual(next2.value)) {\n return false;\n }\n }\n return !it1.hasNext() && !it2.hasNext();\n }\n return false;\n };\n ObjectValue.prototype.compareTo = function (other) {\n if (other instanceof ObjectValue) {\n var it1 = this.internalValue.getIterator();\n var it2 = other.internalValue.getIterator();\n while (it1.hasNext() && it2.hasNext()) {\n var next1 = it1.getNext();\n var next2 = it2.getNext();\n var cmp = primitiveComparator(next1.key, next2.key) ||\n next1.value.compareTo(next2.value);\n if (cmp) {\n return cmp;\n }\n }\n // Only equal if both iterators are exhausted\n return primitiveComparator(it1.hasNext(), it2.hasNext());\n }\n else {\n return this.defaultCompareTo(other);\n }\n };\n ObjectValue.prototype.set = function (path, to) {\n assert(!path.isEmpty(), 'Cannot set field for empty path on ObjectValue');\n if (path.length === 1) {\n return this.setChild(path.firstSegment(), to);\n }\n else {\n var child = this.child(path.firstSegment());\n if (!(child instanceof ObjectValue)) {\n child = ObjectValue.EMPTY;\n }\n var newChild = child.set(path.popFirst(), to);\n return this.setChild(path.firstSegment(), newChild);\n }\n };\n ObjectValue.prototype.delete = function (path) {\n assert(!path.isEmpty(), 'Cannot delete field for empty path on ObjectValue');\n if (path.length === 1) {\n return new ObjectValue(this.internalValue.remove(path.firstSegment()));\n }\n else {\n // nested field\n var child = this.child(path.firstSegment());\n if (child instanceof ObjectValue) {\n var newChild = child.delete(path.popFirst());\n return new ObjectValue(this.internalValue.insert(path.firstSegment(), newChild));\n }\n else {\n // Don't actually change a primitive value to an object for a delete\n return this;\n }\n }\n };\n ObjectValue.prototype.contains = function (path) {\n return this.field(path) !== undefined;\n };\n ObjectValue.prototype.field = function (path) {\n assert(!path.isEmpty(), \"Can't get field of empty path\");\n var field = this;\n path.forEach(function (pathSegment) {\n if (field instanceof ObjectValue) {\n field = field.internalValue.get(pathSegment) || undefined;\n }\n else {\n field = undefined;\n }\n });\n return field;\n };\n ObjectValue.prototype.toString = function () {\n return JSON.stringify(this.value());\n };\n ObjectValue.prototype.child = function (childName) {\n return this.internalValue.get(childName) || undefined;\n };\n ObjectValue.prototype.setChild = function (childName, value) {\n return new ObjectValue(this.internalValue.insert(childName, value));\n };\n ObjectValue.EMPTY = new ObjectValue(new sorted_map_SortedMap(primitiveComparator));\n return ObjectValue;\n}(field_value_FieldValue));\n\nvar field_value_ArrayValue = /** @class */ (function (_super) {\n field_value___extends(ArrayValue, _super);\n function ArrayValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.ArrayValue;\n return _this;\n }\n ArrayValue.prototype.value = function (options) {\n return this.internalValue.map(function (v) { return v.value(options); });\n };\n ArrayValue.prototype.forEach = function (action) {\n this.internalValue.forEach(action);\n };\n ArrayValue.prototype.isEqual = function (other) {\n if (other instanceof ArrayValue) {\n if (this.internalValue.length !== other.internalValue.length) {\n return false;\n }\n for (var i = 0; i < this.internalValue.length; i++) {\n if (!this.internalValue[i].isEqual(other.internalValue[i])) {\n return false;\n }\n }\n return true;\n }\n return false;\n };\n ArrayValue.prototype.compareTo = function (other) {\n if (other instanceof ArrayValue) {\n var minLength = Math.min(this.internalValue.length, other.internalValue.length);\n for (var i = 0; i < minLength; i++) {\n var cmp = this.internalValue[i].compareTo(other.internalValue[i]);\n if (cmp) {\n return cmp;\n }\n }\n return primitiveComparator(this.internalValue.length, other.internalValue.length);\n }\n else {\n return this.defaultCompareTo(other);\n }\n };\n ArrayValue.prototype.toString = function () {\n return JSON.stringify(this.value());\n };\n return ArrayValue;\n}(field_value_FieldValue));\n\n\n//# sourceMappingURL=field_value.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/types.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Untyped Number alias we can use to check for ES6 methods / properties.\n// tslint:disable-next-line:no-any variable-name\nvar NumberAsAny = Number;\n/**\n * Minimum safe integer in Javascript because of floating point precision.\n * Added to not rely on ES6 features.\n */\nvar MIN_SAFE_INTEGER = NumberAsAny.MIN_SAFE_INTEGER || -(Math.pow(2, 53) - 1);\n/**\n * Maximum safe integer in Javascript because of floating point precision.\n * Added to not rely on ES6 features.\n */\nvar MAX_SAFE_INTEGER = NumberAsAny.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1;\n/**\n * Returns whether an number is an integer, uses native implementation if\n * available.\n * Added to not rely on ES6 features.\n * @param value The value to test for being an integer\n */\nvar isInteger = NumberAsAny.isInteger ||\n (function (value) {\n return typeof value === 'number' &&\n isFinite(value) &&\n Math.floor(value) === value;\n });\n/**\n * Returns whether a variable is either undefined or null.\n */\nfunction isNullOrUndefined(value) {\n return value === null || value === undefined;\n}\n/**\n * Returns whether a value is an integer and in the safe integer range\n * @param value The value to test for being an integer and in the safe range\n */\nfunction isSafeInteger(value) {\n return (isInteger(value) &&\n value <= MAX_SAFE_INTEGER &&\n value >= MIN_SAFE_INTEGER);\n}\n/**\n * Safely checks if the number is NaN.\n */\nfunction safeIsNaN(value) {\n if (NumberAsAny.IsNaN) {\n return NumberAsAny.IsNaN(value);\n }\n else {\n return typeof value === 'number' && isNaN(value);\n }\n}\n\n//# sourceMappingURL=types.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/query.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n\n\n\n\nvar query_Query = /** @class */ (function () {\n function Query(path, explicitOrderBy, filters, limit, startAt, endAt) {\n if (explicitOrderBy === void 0) { explicitOrderBy = []; }\n if (filters === void 0) { filters = []; }\n if (limit === void 0) { limit = null; }\n if (startAt === void 0) { startAt = null; }\n if (endAt === void 0) { endAt = null; }\n this.path = path;\n this.explicitOrderBy = explicitOrderBy;\n this.filters = filters;\n this.limit = limit;\n this.startAt = startAt;\n this.endAt = endAt;\n this.memoizedCanonicalId = null;\n this.memoizedOrderBy = null;\n if (this.startAt) {\n this.assertValidBound(this.startAt);\n }\n if (this.endAt) {\n this.assertValidBound(this.endAt);\n }\n }\n Query.atPath = function (path) {\n return new Query(path);\n };\n Object.defineProperty(Query.prototype, \"orderBy\", {\n get: function () {\n if (this.memoizedOrderBy === null) {\n var inequalityField = this.getInequalityFilterField();\n var firstOrderByField = this.getFirstOrderByField();\n if (inequalityField !== null && firstOrderByField === null) {\n // In order to implicitly add key ordering, we must also add the\n // inequality filter field for it to be a valid query.\n // Note that the default inequality field and key ordering is ascending.\n if (inequalityField.isKeyField()) {\n this.memoizedOrderBy = [KEY_ORDERING_ASC];\n }\n else {\n this.memoizedOrderBy = [\n new query_OrderBy(inequalityField),\n KEY_ORDERING_ASC\n ];\n }\n }\n else {\n assert(inequalityField === null ||\n (firstOrderByField !== null &&\n inequalityField.isEqual(firstOrderByField)), 'First orderBy should match inequality field.');\n this.memoizedOrderBy = [];\n var foundKeyOrdering = false;\n for (var _i = 0, _a = this.explicitOrderBy; _i < _a.length; _i++) {\n var orderBy = _a[_i];\n this.memoizedOrderBy.push(orderBy);\n if (orderBy.field.isKeyField()) {\n foundKeyOrdering = true;\n }\n }\n if (!foundKeyOrdering) {\n // The order of the implicit key ordering always matches the last\n // explicit order by\n var lastDirection = this.explicitOrderBy.length > 0\n ? this.explicitOrderBy[this.explicitOrderBy.length - 1].dir\n : Direction.ASCENDING;\n this.memoizedOrderBy.push(lastDirection === Direction.ASCENDING\n ? KEY_ORDERING_ASC\n : KEY_ORDERING_DESC);\n }\n }\n }\n return this.memoizedOrderBy;\n },\n enumerable: true,\n configurable: true\n });\n Query.prototype.addFilter = function (filter) {\n assert(this.getInequalityFilterField() == null ||\n !(filter instanceof query_RelationFilter) ||\n !filter.isInequality() ||\n filter.field.isEqual(this.getInequalityFilterField()), 'Query must only have one inequality field.');\n assert(!document_key_DocumentKey.isDocumentKey(this.path), 'No filtering allowed for document query');\n var newFilters = this.filters.concat([filter]);\n return new Query(this.path, this.explicitOrderBy.slice(), newFilters, this.limit, this.startAt, this.endAt);\n };\n Query.prototype.addOrderBy = function (orderBy) {\n assert(!document_key_DocumentKey.isDocumentKey(this.path), 'No ordering allowed for document query');\n assert(!this.startAt && !this.endAt, 'Bounds must be set after orderBy');\n // TODO(dimond): validate that orderBy does not list the same key twice.\n var newOrderBy = this.explicitOrderBy.concat([orderBy]);\n return new Query(this.path, newOrderBy, this.filters.slice(), this.limit, this.startAt, this.endAt);\n };\n Query.prototype.withLimit = function (limit) {\n return new Query(this.path, this.explicitOrderBy.slice(), this.filters.slice(), limit, this.startAt, this.endAt);\n };\n Query.prototype.withStartAt = function (bound) {\n return new Query(this.path, this.explicitOrderBy.slice(), this.filters.slice(), this.limit, bound, this.endAt);\n };\n Query.prototype.withEndAt = function (bound) {\n return new Query(this.path, this.explicitOrderBy.slice(), this.filters.slice(), this.limit, this.startAt, bound);\n };\n // TODO(b/29183165): This is used to get a unique string from a query to, for\n // example, use as a dictionary key, but the implementation is subject to\n // collisions. Make it collision-free.\n Query.prototype.canonicalId = function () {\n if (this.memoizedCanonicalId === null) {\n var canonicalId = this.path.canonicalString();\n canonicalId += '|f:';\n for (var _i = 0, _a = this.filters; _i < _a.length; _i++) {\n var filter = _a[_i];\n canonicalId += filter.canonicalId();\n canonicalId += ',';\n }\n canonicalId += '|ob:';\n // TODO(dimond): make this collision resistant\n for (var _b = 0, _c = this.orderBy; _b < _c.length; _b++) {\n var orderBy = _c[_b];\n canonicalId += orderBy.canonicalId();\n canonicalId += ',';\n }\n if (!isNullOrUndefined(this.limit)) {\n canonicalId += '|l:';\n canonicalId += this.limit;\n }\n if (this.startAt) {\n canonicalId += '|lb:';\n canonicalId += this.startAt.canonicalId();\n }\n if (this.endAt) {\n canonicalId += '|ub:';\n canonicalId += this.endAt.canonicalId();\n }\n this.memoizedCanonicalId = canonicalId;\n }\n return this.memoizedCanonicalId;\n };\n Query.prototype.toString = function () {\n var str = 'Query(' + this.path.canonicalString();\n if (this.filters.length > 0) {\n str += \", filters: [\" + this.filters.join(', ') + \"]\";\n }\n if (!isNullOrUndefined(this.limit)) {\n str += ', limit: ' + this.limit;\n }\n if (this.explicitOrderBy.length > 0) {\n str += \", orderBy: [\" + this.explicitOrderBy.join(', ') + \"]\";\n }\n if (this.startAt) {\n str += ', startAt: ' + this.startAt.canonicalId();\n }\n if (this.endAt) {\n str += ', endAt: ' + this.endAt.canonicalId();\n }\n return str + ')';\n };\n Query.prototype.isEqual = function (other) {\n if (this.limit !== other.limit) {\n return false;\n }\n if (this.orderBy.length !== other.orderBy.length) {\n return false;\n }\n for (var i = 0; i < this.orderBy.length; i++) {\n if (!this.orderBy[i].isEqual(other.orderBy[i])) {\n return false;\n }\n }\n if (this.filters.length !== other.filters.length) {\n return false;\n }\n for (var i = 0; i < this.filters.length; i++) {\n if (!this.filters[i].isEqual(other.filters[i])) {\n return false;\n }\n }\n if (!this.path.isEqual(other.path)) {\n return false;\n }\n if (this.startAt !== null\n ? !this.startAt.isEqual(other.startAt)\n : other.startAt !== null) {\n return false;\n }\n return this.endAt !== null\n ? this.endAt.isEqual(other.endAt)\n : other.endAt === null;\n };\n Query.prototype.docComparator = function (d1, d2) {\n var comparedOnKeyField = false;\n for (var _i = 0, _a = this.orderBy; _i < _a.length; _i++) {\n var orderBy = _a[_i];\n var comp = orderBy.compare(d1, d2);\n if (comp !== 0)\n return comp;\n comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField();\n }\n // Assert that we actually compared by key\n assert(comparedOnKeyField, \"orderBy used that doesn't compare on key field\");\n return 0;\n };\n Query.prototype.matches = function (doc) {\n return (this.matchesAncestor(doc) &&\n this.matchesOrderBy(doc) &&\n this.matchesFilters(doc) &&\n this.matchesBounds(doc));\n };\n Query.prototype.hasLimit = function () {\n return !isNullOrUndefined(this.limit);\n };\n Query.prototype.getFirstOrderByField = function () {\n return this.explicitOrderBy.length > 0\n ? this.explicitOrderBy[0].field\n : null;\n };\n Query.prototype.getInequalityFilterField = function () {\n for (var _i = 0, _a = this.filters; _i < _a.length; _i++) {\n var filter = _a[_i];\n if (filter instanceof query_RelationFilter && filter.isInequality()) {\n return filter.field;\n }\n }\n return null;\n };\n Query.prototype.isDocumentQuery = function () {\n return document_key_DocumentKey.isDocumentKey(this.path) && this.filters.length === 0;\n };\n Query.prototype.matchesAncestor = function (doc) {\n var docPath = doc.key.path;\n if (document_key_DocumentKey.isDocumentKey(this.path)) {\n // exact match for document queries\n return this.path.isEqual(docPath);\n }\n else {\n // shallow ancestor queries by default\n return (this.path.isPrefixOf(docPath) && this.path.length === docPath.length - 1);\n }\n };\n /**\n * A document must have a value for every ordering clause in order to show up\n * in the results.\n */\n Query.prototype.matchesOrderBy = function (doc) {\n for (var _i = 0, _a = this.explicitOrderBy; _i < _a.length; _i++) {\n var orderBy = _a[_i];\n // order by key always matches\n if (!orderBy.field.isKeyField() &&\n doc.field(orderBy.field) === undefined) {\n return false;\n }\n }\n return true;\n };\n Query.prototype.matchesFilters = function (doc) {\n for (var _i = 0, _a = this.filters; _i < _a.length; _i++) {\n var filter = _a[_i];\n if (!filter.matches(doc)) {\n return false;\n }\n }\n return true;\n };\n /**\n * Makes sure a document is within the bounds, if provided.\n */\n Query.prototype.matchesBounds = function (doc) {\n if (this.startAt && !this.startAt.sortsBeforeDocument(this.orderBy, doc)) {\n return false;\n }\n if (this.endAt && this.endAt.sortsBeforeDocument(this.orderBy, doc)) {\n return false;\n }\n return true;\n };\n Query.prototype.assertValidBound = function (bound) {\n assert(bound.position.length <= this.orderBy.length, 'Bound is longer than orderBy');\n };\n return Query;\n}());\n\nvar query_RelationOp = /** @class */ (function () {\n function RelationOp(name) {\n this.name = name;\n }\n RelationOp.fromString = function (op) {\n switch (op) {\n case '<':\n return RelationOp.LESS_THAN;\n case '<=':\n return RelationOp.LESS_THAN_OR_EQUAL;\n case '==':\n return RelationOp.EQUAL;\n case '>=':\n return RelationOp.GREATER_THAN_OR_EQUAL;\n case '>':\n return RelationOp.GREATER_THAN;\n default:\n return fail('Unknown relation: ' + op);\n }\n };\n RelationOp.prototype.toString = function () {\n return this.name;\n };\n RelationOp.prototype.isEqual = function (other) {\n return this.name === other.name;\n };\n RelationOp.LESS_THAN = new RelationOp('<');\n RelationOp.LESS_THAN_OR_EQUAL = new RelationOp('<=');\n RelationOp.EQUAL = new RelationOp('==');\n RelationOp.GREATER_THAN = new RelationOp('>');\n RelationOp.GREATER_THAN_OR_EQUAL = new RelationOp('>=');\n return RelationOp;\n}());\n\nvar query_RelationFilter = /** @class */ (function () {\n function RelationFilter(field, op, value) {\n this.field = field;\n this.op = op;\n this.value = value;\n }\n RelationFilter.prototype.matches = function (doc) {\n if (this.field.isKeyField()) {\n assert(this.value instanceof field_value_RefValue, 'Comparing on key, but filter value not a RefValue');\n var refValue = this.value;\n var comparison = document_key_DocumentKey.comparator(doc.key, refValue.key);\n return this.matchesComparison(comparison);\n }\n else {\n var val = doc.field(this.field);\n return val !== undefined && this.matchesValue(val);\n }\n };\n RelationFilter.prototype.matchesValue = function (value) {\n // Only compare types with matching backend order (such as double and int).\n if (this.value.typeOrder !== value.typeOrder) {\n return false;\n }\n return this.matchesComparison(value.compareTo(this.value));\n };\n RelationFilter.prototype.matchesComparison = function (comparison) {\n switch (this.op) {\n case query_RelationOp.LESS_THAN:\n return comparison < 0;\n case query_RelationOp.LESS_THAN_OR_EQUAL:\n return comparison <= 0;\n case query_RelationOp.EQUAL:\n return comparison === 0;\n case query_RelationOp.GREATER_THAN:\n return comparison > 0;\n case query_RelationOp.GREATER_THAN_OR_EQUAL:\n return comparison >= 0;\n default:\n return fail('Unknown relation op' + this.op);\n }\n };\n RelationFilter.prototype.isInequality = function () {\n return this.op !== query_RelationOp.EQUAL;\n };\n RelationFilter.prototype.canonicalId = function () {\n // TODO(b/29183165): Technically, this won't be unique if two values have\n // the same description, such as the int 3 and the string \"3\". So we should\n // add the types in here somehow, too.\n return (this.field.canonicalString() + this.op.toString() + this.value.toString());\n };\n RelationFilter.prototype.isEqual = function (other) {\n if (other instanceof RelationFilter) {\n return (this.op.isEqual(other.op) &&\n this.field.isEqual(other.field) &&\n this.value.isEqual(other.value));\n }\n else {\n return false;\n }\n };\n RelationFilter.prototype.toString = function () {\n return this.field.canonicalString() + \" \" + this.op + \" \" + this.value.value();\n };\n return RelationFilter;\n}());\n\n/**\n * Filter that matches 'null' values.\n */\nvar NullFilter = /** @class */ (function () {\n function NullFilter(field) {\n this.field = field;\n }\n NullFilter.prototype.matches = function (doc) {\n var val = doc.field(this.field);\n return val !== undefined && val.value() === null;\n };\n NullFilter.prototype.canonicalId = function () {\n return this.field.canonicalString() + ' IS null';\n };\n NullFilter.prototype.toString = function () {\n return this.field.canonicalString() + \" IS null\";\n };\n NullFilter.prototype.isEqual = function (other) {\n if (other instanceof NullFilter) {\n return this.field.isEqual(other.field);\n }\n else {\n return false;\n }\n };\n return NullFilter;\n}());\n\n/**\n * Filter that matches 'NaN' values.\n */\nvar NanFilter = /** @class */ (function () {\n function NanFilter(field) {\n this.field = field;\n }\n NanFilter.prototype.matches = function (doc) {\n var val = doc.field(this.field).value();\n return typeof val === 'number' && isNaN(val);\n };\n NanFilter.prototype.canonicalId = function () {\n return this.field.canonicalString() + ' IS NaN';\n };\n NanFilter.prototype.toString = function () {\n return this.field.canonicalString() + \" IS NaN\";\n };\n NanFilter.prototype.isEqual = function (other) {\n if (other instanceof NanFilter) {\n return this.field.isEqual(other.field);\n }\n else {\n return false;\n }\n };\n return NanFilter;\n}());\n\n/**\n * Creates a filter based on the provided arguments.\n */\nfunction fieldFilter(field, op, value) {\n if (value.isEqual(NullValue.INSTANCE)) {\n if (op !== query_RelationOp.EQUAL) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You can only perform equals ' + 'comparisons on null.');\n }\n return new NullFilter(field);\n }\n else if (value.isEqual(DoubleValue.NAN)) {\n if (op !== query_RelationOp.EQUAL) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You can only perform equals ' + 'comparisons on NaN.');\n }\n return new NanFilter(field);\n }\n else {\n return new query_RelationFilter(field, op, value);\n }\n}\n/**\n * The direction of sorting in an order by.\n */\nvar Direction = /** @class */ (function () {\n function Direction(name) {\n this.name = name;\n }\n Direction.prototype.toString = function () {\n return this.name;\n };\n Direction.ASCENDING = new Direction('asc');\n Direction.DESCENDING = new Direction('desc');\n return Direction;\n}());\n\n/**\n * Represents a bound of a query.\n *\n * The bound is specified with the given components representing a position and\n * whether it's just before or just after the position (relative to whatever the\n * query order is).\n *\n * The position represents a logical index position for a query. It's a prefix\n * of values for the (potentially implicit) order by clauses of a query.\n *\n * Bound provides a function to determine whether a document comes before or\n * after a bound. This is influenced by whether the position is just before or\n * just after the provided values.\n */\nvar query_Bound = /** @class */ (function () {\n function Bound(position, before) {\n this.position = position;\n this.before = before;\n }\n Bound.prototype.canonicalId = function () {\n // TODO(b/29183165): Make this collision robust.\n var canonicalId = this.before ? 'b:' : 'a:';\n for (var _i = 0, _a = this.position; _i < _a.length; _i++) {\n var component = _a[_i];\n canonicalId += component.toString();\n }\n return canonicalId;\n };\n /**\n * Returns true if a document sorts before a bound using the provided sort\n * order.\n */\n Bound.prototype.sortsBeforeDocument = function (orderBy, doc) {\n assert(this.position.length <= orderBy.length, \"Bound has more components than query's orderBy\");\n var comparison = 0;\n for (var i = 0; i < this.position.length; i++) {\n var orderByComponent = orderBy[i];\n var component = this.position[i];\n if (orderByComponent.field.isKeyField()) {\n assert(component instanceof field_value_RefValue, 'Bound has a non-key value where the key path is being used.');\n comparison = document_key_DocumentKey.comparator(component.key, doc.key);\n }\n else {\n var docValue = doc.field(orderByComponent.field);\n assert(docValue !== undefined, 'Field should exist since document matched the orderBy already.');\n comparison = component.compareTo(docValue);\n }\n if (orderByComponent.dir === Direction.DESCENDING) {\n comparison = comparison * -1;\n }\n if (comparison !== 0) {\n break;\n }\n }\n return this.before ? comparison <= 0 : comparison < 0;\n };\n Bound.prototype.isEqual = function (other) {\n if (other === null) {\n return false;\n }\n if (this.before !== other.before ||\n this.position.length !== other.position.length) {\n return false;\n }\n for (var i = 0; i < this.position.length; i++) {\n var thisPosition = this.position[i];\n var otherPosition = other.position[i];\n return thisPosition.isEqual(otherPosition);\n }\n return true;\n };\n return Bound;\n}());\n\n/**\n * An ordering on a field, in some Direction. Direction defaults to ASCENDING.\n */\nvar query_OrderBy = /** @class */ (function () {\n function OrderBy(field, dir) {\n this.field = field;\n if (dir === undefined) {\n dir = Direction.ASCENDING;\n }\n this.dir = dir;\n this.isKeyOrderBy = field.isKeyField();\n }\n OrderBy.prototype.compare = function (d1, d2) {\n var comparison = this.isKeyOrderBy\n ? document_Document.compareByKey(d1, d2)\n : document_Document.compareByField(this.field, d1, d2);\n switch (this.dir) {\n case Direction.ASCENDING:\n return comparison;\n case Direction.DESCENDING:\n return -1 * comparison;\n default:\n return fail('Unknown direction: ' + this.dir);\n }\n };\n OrderBy.prototype.canonicalId = function () {\n // TODO(b/29183165): Make this collision robust.\n return this.field.canonicalString() + this.dir.toString();\n };\n OrderBy.prototype.toString = function () {\n return this.field.canonicalString() + \" (\" + this.dir + \")\";\n };\n OrderBy.prototype.isEqual = function (other) {\n return this.dir === other.dir && this.field.isEqual(other.field);\n };\n return OrderBy;\n}());\n\nvar KEY_ORDERING_ASC = new query_OrderBy(path_FieldPath.keyField(), Direction.ASCENDING);\nvar KEY_ORDERING_DESC = new query_OrderBy(path_FieldPath.keyField(), Direction.DESCENDING);\n\n//# sourceMappingURL=query.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/timestamp.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n// A RegExp matching ISO 8601 UTC timestamps with optional fraction.\nvar isoRegExp = new RegExp(/^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.(\\d+))?Z$/);\nvar timestamp_Timestamp = /** @class */ (function () {\n function Timestamp(seconds, nanos) {\n this.seconds = seconds;\n this.nanos = nanos;\n assert(nanos >= 0, 'timestamp nanoseconds out of range: ' + nanos);\n assert(nanos < 1e9, 'timestamp nanoseconds out of range' + nanos);\n // Midnight at the beginning of 1/1/1 is the earliest Firestore supports.\n assert(seconds >= -62135596800, 'timestamp seconds out of range: ' + seconds);\n // This will break in the year 10,000.\n assert(seconds < 253402300800, 'timestamp seconds out of range' + seconds);\n }\n Timestamp.now = function () {\n return Timestamp.fromEpochMilliseconds(Date.now());\n };\n Timestamp.fromDate = function (date) {\n return Timestamp.fromEpochMilliseconds(date.getTime());\n };\n Timestamp.fromEpochMilliseconds = function (milliseconds) {\n var seconds = Math.floor(milliseconds / 1000);\n var nanos = (milliseconds - seconds * 1000) * 1e6;\n return new Timestamp(seconds, nanos);\n };\n Timestamp.fromISOString = function (utc) {\n // The date string can have higher precision (nanos) than the Date class\n // (millis), so we do some custom parsing here.\n // Parse the nanos right out of the string.\n var nanos = 0;\n var fraction = isoRegExp.exec(utc);\n assert(!!fraction, 'invalid timestamp: ' + utc);\n if (fraction[1]) {\n // Pad the fraction out to 9 digits (nanos).\n var nanoStr = fraction[1];\n nanoStr = (nanoStr + '000000000').substr(0, 9);\n nanos = Number(nanoStr);\n }\n // Parse the date to get the seconds.\n var date = new Date(utc);\n var seconds = Math.floor(date.getTime() / 1000);\n return new Timestamp(seconds, nanos);\n };\n Timestamp.prototype.toDate = function () {\n return new Date(this.toEpochMilliseconds());\n };\n Timestamp.prototype.toEpochMilliseconds = function () {\n return this.seconds * 1000 + this.nanos / 1e6;\n };\n Timestamp.prototype.compareTo = function (other) {\n if (this.seconds === other.seconds) {\n return primitiveComparator(this.nanos, other.nanos);\n }\n return primitiveComparator(this.seconds, other.seconds);\n };\n Timestamp.prototype.isEqual = function (other) {\n return other.seconds === this.seconds && other.nanos === this.nanos;\n };\n Timestamp.prototype.toString = function () {\n return 'Timestamp(seconds=' + this.seconds + ', nanos=' + this.nanos + ')';\n };\n return Timestamp;\n}());\n\n\n//# sourceMappingURL=timestamp.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/snapshot_version.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * A version of a document in Firestore. This corresponds to the version\n * timestamp, such as update_time or read_time.\n */\nvar snapshot_version_SnapshotVersion = /** @class */ (function () {\n function SnapshotVersion(timestamp) {\n this.timestamp = timestamp;\n }\n // TODO(b/34176344): Once we no longer need to use the old alpha protos,\n // delete this constructor and use a timestamp-backed version everywhere.\n SnapshotVersion.fromMicroseconds = function (value) {\n var seconds = Math.floor(value / 1e6);\n var nanos = (value % 1e6) * 1e3;\n return new SnapshotVersion(new timestamp_Timestamp(seconds, nanos));\n };\n SnapshotVersion.fromTimestamp = function (value) {\n return new SnapshotVersion(value);\n };\n SnapshotVersion.forDeletedDoc = function () {\n return SnapshotVersion.MIN;\n };\n SnapshotVersion.prototype.compareTo = function (other) {\n return this.timestamp.compareTo(other.timestamp);\n };\n SnapshotVersion.prototype.isEqual = function (other) {\n return this.timestamp.isEqual(other.timestamp);\n };\n /** Returns a number representation of the version for use in spec tests. */\n SnapshotVersion.prototype.toMicroseconds = function () {\n // Convert to microseconds.\n return this.timestamp.seconds * 1e6 + this.timestamp.nanos / 1000;\n };\n SnapshotVersion.prototype.toString = function () {\n return 'SnapshotVersion(' + this.timestamp.toString() + ')';\n };\n SnapshotVersion.prototype.toTimestamp = function () {\n return this.timestamp;\n };\n SnapshotVersion.MIN = new SnapshotVersion(new timestamp_Timestamp(0, 0));\n return SnapshotVersion;\n}());\n\n\n//# sourceMappingURL=snapshot_version.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/query_data.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n/** An enumeration of the different purposes we have for queries. */\nvar QueryPurpose;\n(function (QueryPurpose) {\n /** A regular, normal query. */\n QueryPurpose[QueryPurpose[\"Listen\"] = 0] = \"Listen\";\n /**\n * The query was used to refill a query after an existence filter mismatch.\n */\n QueryPurpose[QueryPurpose[\"ExistenceFilterMismatch\"] = 1] = \"ExistenceFilterMismatch\";\n /** The query was used to resolve a limbo document. */\n QueryPurpose[QueryPurpose[\"LimboResolution\"] = 2] = \"LimboResolution\";\n})(QueryPurpose || (QueryPurpose = {}));\n/**\n * An immutable set of metadata that the local store tracks for each query.\n */\nvar query_data_QueryData = /** @class */ (function () {\n function QueryData(\n /** The query being listened to. */\n query, \n /**\n * The target ID to which the query corresponds; Assigned by the\n * LocalStore for user listens and by the SyncEngine for limbo watches.\n */\n targetId, \n /** The purpose of the query. */\n purpose, \n /** The latest snapshot version seen for this target. */\n snapshotVersion, \n /**\n * An opaque, server-assigned token that allows watching a query to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the query. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */\n resumeToken) {\n if (snapshotVersion === void 0) { snapshotVersion = snapshot_version_SnapshotVersion.MIN; }\n if (resumeToken === void 0) { resumeToken = emptyByteString(); }\n this.query = query;\n this.targetId = targetId;\n this.purpose = purpose;\n this.snapshotVersion = snapshotVersion;\n this.resumeToken = resumeToken;\n }\n /**\n * Creates a new query data instance with an updated snapshot version and\n * resume token.\n */\n QueryData.prototype.update = function (updated) {\n return new QueryData(this.query, this.targetId, this.purpose, updated.snapshotVersion, updated.resumeToken);\n };\n QueryData.prototype.isEqual = function (other) {\n return (this.targetId === other.targetId &&\n this.purpose === other.purpose &&\n this.snapshotVersion.isEqual(other.snapshotVersion) &&\n this.resumeToken === other.resumeToken &&\n this.query.isEqual(other.query));\n };\n return QueryData;\n}());\n\n\n//# sourceMappingURL=query_data.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/model/mutation.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar mutation___extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n\n\n\n\n\n/**\n * Provides a set of fields that can be used to partially patch a document.\n * FieldMask is used in conjunction with ObjectValue.\n * Examples:\n * foo - Overwrites foo entirely with the provided value. If foo is not\n * present in the companion ObjectValue, the field is deleted.\n * foo.bar - Overwrites only the field bar of the object foo.\n * If foo is not an object, foo is replaced with an object\n * containing foo\n */\nvar mutation_FieldMask = /** @class */ (function () {\n function FieldMask(fields) {\n this.fields = fields;\n // TODO(dimond): validation of FieldMask\n }\n FieldMask.prototype.isEqual = function (other) {\n return arrayEquals(this.fields, other.fields);\n };\n return FieldMask;\n}());\n\n/** Transforms a value into a server-generated timestamp. */\nvar ServerTimestampTransform = /** @class */ (function () {\n function ServerTimestampTransform() {\n }\n ServerTimestampTransform.prototype.isEqual = function (other) {\n return other instanceof ServerTimestampTransform;\n };\n ServerTimestampTransform.instance = new ServerTimestampTransform();\n return ServerTimestampTransform;\n}());\n\n/** A field path and the TransformOperation to perform upon it. */\nvar FieldTransform = /** @class */ (function () {\n function FieldTransform(field, transform) {\n this.field = field;\n this.transform = transform;\n }\n FieldTransform.prototype.isEqual = function (other) {\n return (this.field.isEqual(other.field) && this.transform.isEqual(other.transform));\n };\n return FieldTransform;\n}());\n\n/** The result of successfully applying a mutation to the backend. */\nvar MutationResult = /** @class */ (function () {\n function MutationResult(\n /**\n * The version at which the mutation was committed or null for a delete.\n */\n version, \n /**\n * The resulting fields returned from the backend after a\n * TransformMutation has been committed. Contains one FieldValue for each\n * FieldTransform that was in the mutation.\n *\n * Will be null if the mutation was not a TransformMutation.\n */\n transformResults) {\n this.version = version;\n this.transformResults = transformResults;\n }\n return MutationResult;\n}());\n\nvar MutationType;\n(function (MutationType) {\n MutationType[MutationType[\"Set\"] = 0] = \"Set\";\n MutationType[MutationType[\"Patch\"] = 1] = \"Patch\";\n MutationType[MutationType[\"Transform\"] = 2] = \"Transform\";\n MutationType[MutationType[\"Delete\"] = 3] = \"Delete\";\n})(MutationType || (MutationType = {}));\n/**\n * Encodes a precondition for a mutation. This follows the model that the\n * backend accepts with the special case of an explicit \"empty\" precondition\n * (meaning no precondition).\n */\nvar mutation_Precondition = /** @class */ (function () {\n function Precondition(updateTime, exists) {\n this.updateTime = updateTime;\n this.exists = exists;\n assert(updateTime === undefined || exists === undefined, 'Precondition can specify \"exists\" or \"updateTime\" but not both');\n }\n /** Creates a new Precondition with an exists flag. */\n Precondition.exists = function (exists) {\n return new Precondition(undefined, exists);\n };\n /** Creates a new Precondition based on a version a document exists at. */\n Precondition.updateTime = function (version) {\n return new Precondition(version);\n };\n Object.defineProperty(Precondition.prototype, \"isNone\", {\n /** Returns whether this Precondition is empty. */\n get: function () {\n return this.updateTime === undefined && this.exists === undefined;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns true if the preconditions is valid for the given document\n * (or null if no document is available).\n */\n Precondition.prototype.isValidFor = function (maybeDoc) {\n if (this.updateTime !== undefined) {\n return (maybeDoc instanceof document_Document &&\n maybeDoc.version.isEqual(this.updateTime));\n }\n else if (this.exists !== undefined) {\n if (this.exists) {\n return maybeDoc instanceof document_Document;\n }\n else {\n return maybeDoc === null || maybeDoc instanceof document_NoDocument;\n }\n }\n else {\n assert(this.isNone, 'Precondition should be empty');\n return true;\n }\n };\n Precondition.prototype.isEqual = function (other) {\n return (equals(this.updateTime, other.updateTime) &&\n this.exists === other.exists);\n };\n Precondition.NONE = new Precondition();\n return Precondition;\n}());\n\n/**\n * A mutation describes a self-contained change to a document. Mutations can\n * create, replace, delete, and update subsets of documents.\n *\n * Mutations not only act on the value of the document but also it version.\n * In the case of Set, Patch, and Transform mutations we preserve the existing\n * version. In the case of Delete mutations, we reset the version to 0.\n *\n * Here's the expected transition table.\n *\n * MUTATION APPLIED TO RESULTS IN\n *\n * SetMutation Document(v3) Document(v3)\n * SetMutation NoDocument(v3) Document(v0)\n * SetMutation null Document(v0)\n * PatchMutation Document(v3) Document(v3)\n * PatchMutation NoDocument(v3) NoDocument(v3)\n * PatchMutation null null\n * TransformMutation Document(v3) Document(v3)\n * TransformMutation NoDocument(v3) NoDocument(v3)\n * TransformMutation null null\n * DeleteMutation Document(v3) NoDocument(v0)\n * DeleteMutation NoDocument(v3) NoDocument(v0)\n * DeleteMutation null NoDocument(v0)\n *\n * Note that TransformMutations don't create Documents (in the case of being\n * applied to a NoDocument), even though they would on the backend. This is\n * because the client always combines the TransformMutation with a SetMutation\n * or PatchMutation and we only want to apply the transform if the prior\n * mutation resulted in a Document (always true for a SetMutation, but not\n * necessarily for a PatchMutation).\n *\n * ## Subclassing Notes\n *\n * Subclasses of Mutation need to implement applyToRemoteDocument() and\n * applyToLocalView() to implement the actual behavior of applying the mutation\n * to some source document.\n */\nvar mutation_Mutation = /** @class */ (function () {\n function Mutation() {\n }\n Mutation.prototype.verifyKeyMatches = function (maybeDoc) {\n if (maybeDoc != null) {\n assert(maybeDoc.key.isEqual(this.key), 'Can only apply a mutation to a document with the same key');\n }\n };\n /**\n * Returns the version from the given document for use as the result of a\n * mutation. Mutations are defined to return the version of the base document\n * only if it is an existing document. Deleted and unknown documents have a\n * post-mutation version of SnapshotVersion.MIN.\n */\n Mutation.getPostMutationVersion = function (maybeDoc) {\n if (maybeDoc instanceof document_Document) {\n return maybeDoc.version;\n }\n else {\n return snapshot_version_SnapshotVersion.MIN;\n }\n };\n return Mutation;\n}());\n\n/**\n * A mutation that creates or replaces the document at the given key with the\n * object value contents.\n */\nvar mutation_SetMutation = /** @class */ (function (_super) {\n mutation___extends(SetMutation, _super);\n function SetMutation(key, value, precondition) {\n var _this = _super.call(this) || this;\n _this.key = key;\n _this.value = value;\n _this.precondition = precondition;\n _this.type = MutationType.Set;\n return _this;\n }\n SetMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\n this.verifyKeyMatches(maybeDoc);\n assert(mutationResult.transformResults == null, 'Transform results received by SetMutation.');\n // Unlike applyToLocalView, if we're applying a mutation to a remote\n // document the server has accepted the mutation so the precondition must\n // have held.\n var version = mutation_Mutation.getPostMutationVersion(maybeDoc);\n return new document_Document(this.key, version, this.value, {\n hasLocalMutations: false\n });\n };\n SetMutation.prototype.applyToLocalView = function (maybeDoc, baseDoc, localWriteTime) {\n this.verifyKeyMatches(maybeDoc);\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n var version = mutation_Mutation.getPostMutationVersion(maybeDoc);\n return new document_Document(this.key, version, this.value, {\n hasLocalMutations: true\n });\n };\n SetMutation.prototype.isEqual = function (other) {\n return (other instanceof SetMutation &&\n this.key.isEqual(other.key) &&\n this.value.isEqual(other.value) &&\n this.precondition.isEqual(other.precondition));\n };\n return SetMutation;\n}(mutation_Mutation));\n\n/**\n * A mutation that modifies fields of the document at the given key with the\n * given values. The values are applied through a field mask:\n *\n * * When a field is in both the mask and the values, the corresponding field\n * is updated.\n * * When a field is in neither the mask nor the values, the corresponding\n * field is unmodified.\n * * When a field is in the mask but not in the values, the corresponding field\n * is deleted.\n * * When a field is not in the mask but is in the values, the values map is\n * ignored.\n */\nvar mutation_PatchMutation = /** @class */ (function (_super) {\n mutation___extends(PatchMutation, _super);\n function PatchMutation(key, data, fieldMask, precondition) {\n var _this = _super.call(this) || this;\n _this.key = key;\n _this.data = data;\n _this.fieldMask = fieldMask;\n _this.precondition = precondition;\n _this.type = MutationType.Patch;\n return _this;\n }\n PatchMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\n this.verifyKeyMatches(maybeDoc);\n assert(mutationResult.transformResults == null, 'Transform results received by PatchMutation.');\n // TODO(mcg): Relax enforcement of this precondition\n //\n // We shouldn't actually enforce the precondition since it already passed on\n // the backend, but we may not have a local version of the document to\n // patch, so we use the precondition to prevent incorrectly putting a\n // partial document into our cache.\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n var version = mutation_Mutation.getPostMutationVersion(maybeDoc);\n var newData = this.patchDocument(maybeDoc);\n return new document_Document(this.key, version, newData, {\n hasLocalMutations: false\n });\n };\n PatchMutation.prototype.applyToLocalView = function (maybeDoc, baseDoc, localWriteTime) {\n this.verifyKeyMatches(maybeDoc);\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n var version = mutation_Mutation.getPostMutationVersion(maybeDoc);\n var newData = this.patchDocument(maybeDoc);\n return new document_Document(this.key, version, newData, {\n hasLocalMutations: true\n });\n };\n PatchMutation.prototype.isEqual = function (other) {\n return (other instanceof PatchMutation &&\n this.key.isEqual(other.key) &&\n this.fieldMask.isEqual(other.fieldMask) &&\n this.precondition.isEqual(other.precondition));\n };\n /**\n * Patches the data of document if available or creates a new document. Note\n * that this does not check whether or not the precondition of this patch\n * holds.\n */\n PatchMutation.prototype.patchDocument = function (maybeDoc) {\n var data;\n if (maybeDoc instanceof document_Document) {\n data = maybeDoc.data;\n }\n else {\n data = field_value_ObjectValue.EMPTY;\n }\n return this.patchObject(data);\n };\n PatchMutation.prototype.patchObject = function (data) {\n for (var _i = 0, _a = this.fieldMask.fields; _i < _a.length; _i++) {\n var fieldPath = _a[_i];\n var newValue = this.data.field(fieldPath);\n if (newValue !== undefined) {\n data = data.set(fieldPath, newValue);\n }\n else {\n data = data.delete(fieldPath);\n }\n }\n return data;\n };\n return PatchMutation;\n}(mutation_Mutation));\n\n/**\n * A mutation that modifies specific fields of the document with transform\n * operations. Currently the only supported transform is a server timestamp, but\n * IP Address, increment(n), etc. could be supported in the future.\n *\n * It is somewhat similar to a PatchMutation in that it patches specific fields\n * and has no effect when applied to a null or NoDocument (see comment on\n * Mutation for rationale).\n */\nvar mutation_TransformMutation = /** @class */ (function (_super) {\n mutation___extends(TransformMutation, _super);\n function TransformMutation(key, fieldTransforms) {\n var _this = _super.call(this) || this;\n _this.key = key;\n _this.fieldTransforms = fieldTransforms;\n _this.type = MutationType.Transform;\n // NOTE: We set a precondition of exists: true as a safety-check, since we\n // always combine TransformMutations with a SetMutation or PatchMutation which\n // (if successful) should end up with an existing document.\n _this.precondition = mutation_Precondition.exists(true);\n return _this;\n }\n TransformMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\n this.verifyKeyMatches(maybeDoc);\n assert(mutationResult.transformResults != null, 'Transform results missing for TransformMutation.');\n var transformResults = mutationResult.transformResults;\n // TODO(mcg): Relax enforcement of this precondition\n //\n // We shouldn't actually enforce the precondition since it already passed on\n // the backend, but we may not have a local version of the document to\n // patch, so we use the precondition to prevent incorrectly putting a\n // partial document into our cache.\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n var doc = this.requireDocument(maybeDoc);\n var newData = this.transformObject(doc.data, transformResults);\n return new document_Document(this.key, doc.version, newData, {\n hasLocalMutations: false\n });\n };\n TransformMutation.prototype.applyToLocalView = function (maybeDoc, baseDoc, localWriteTime) {\n this.verifyKeyMatches(maybeDoc);\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n var doc = this.requireDocument(maybeDoc);\n var transformResults = this.localTransformResults(localWriteTime, baseDoc);\n var newData = this.transformObject(doc.data, transformResults);\n return new document_Document(this.key, doc.version, newData, {\n hasLocalMutations: true\n });\n };\n TransformMutation.prototype.isEqual = function (other) {\n return (other instanceof TransformMutation &&\n this.key.isEqual(other.key) &&\n arrayEquals(this.fieldTransforms, other.fieldTransforms) &&\n this.precondition.isEqual(other.precondition));\n };\n /**\n * Asserts that the given MaybeDocument is actually a Document and verifies\n * that it matches the key for this mutation. Since we only support\n * transformations with precondition exists this method is guaranteed to be\n * safe.\n */\n TransformMutation.prototype.requireDocument = function (maybeDoc) {\n assert(maybeDoc instanceof document_Document, 'Unknown MaybeDocument type ' + maybeDoc);\n var doc = maybeDoc;\n assert(doc.key.isEqual(this.key), 'Can only transform a document with the same key');\n return doc;\n };\n /**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use when applying a\n * TransformMutation locally.\n *\n * @param localWriteTime The local time of the transform mutation (used to\n * generate ServerTimestampValues).\n * @param baseDoc The document prior to applying this mutation batch.\n * @return The transform results list.\n */\n TransformMutation.prototype.localTransformResults = function (localWriteTime, baseDoc) {\n var transformResults = [];\n for (var _i = 0, _a = this.fieldTransforms; _i < _a.length; _i++) {\n var fieldTransform = _a[_i];\n var transform = fieldTransform.transform;\n if (transform instanceof ServerTimestampTransform) {\n var previousValue = null;\n if (baseDoc instanceof document_Document) {\n previousValue = baseDoc.field(fieldTransform.field) || null;\n }\n transformResults.push(new ServerTimestampValue(localWriteTime, previousValue));\n }\n else {\n return fail('Encountered unknown transform: ' + transform);\n }\n }\n return transformResults;\n };\n TransformMutation.prototype.transformObject = function (data, transformResults) {\n assert(transformResults.length === this.fieldTransforms.length, 'TransformResults length mismatch.');\n for (var i = 0; i < this.fieldTransforms.length; i++) {\n var fieldTransform = this.fieldTransforms[i];\n var transform = fieldTransform.transform;\n var fieldPath = fieldTransform.field;\n if (transform instanceof ServerTimestampTransform) {\n data = data.set(fieldPath, transformResults[i]);\n }\n else {\n return fail('Encountered unknown transform: ' + transform);\n }\n }\n return data;\n };\n return TransformMutation;\n}(mutation_Mutation));\n\n/** A mutation that deletes the document at the given key. */\nvar mutation_DeleteMutation = /** @class */ (function (_super) {\n mutation___extends(DeleteMutation, _super);\n function DeleteMutation(key, precondition) {\n var _this = _super.call(this) || this;\n _this.key = key;\n _this.precondition = precondition;\n _this.type = MutationType.Delete;\n return _this;\n }\n DeleteMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\n this.verifyKeyMatches(maybeDoc);\n assert(mutationResult.transformResults == null, 'Transform results received by DeleteMutation.');\n // Unlike applyToLocalView, if we're applying a mutation to a remote\n // document the server has accepted the mutation so the precondition must\n // have held.\n return new document_NoDocument(this.key, snapshot_version_SnapshotVersion.MIN);\n };\n DeleteMutation.prototype.applyToLocalView = function (maybeDoc, baseDoc, localWriteTime) {\n this.verifyKeyMatches(maybeDoc);\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n if (maybeDoc) {\n assert(maybeDoc.key.isEqual(this.key), 'Can only apply mutation to document with same key');\n }\n return new document_NoDocument(this.key, snapshot_version_SnapshotVersion.forDeletedDoc());\n };\n DeleteMutation.prototype.isEqual = function (other) {\n return (other instanceof DeleteMutation &&\n this.key.isEqual(other.key) &&\n this.precondition.isEqual(other.precondition));\n };\n return DeleteMutation;\n}(mutation_Mutation));\n\n\n//# sourceMappingURL=mutation.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/remote/existence_filter.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar ExistenceFilter = /** @class */ (function () {\n // TODO(b/33078163): just use simplest form of existence filter for now\n function ExistenceFilter(count) {\n this.count = count;\n }\n ExistenceFilter.prototype.isEqual = function (other) {\n return other && other.count === this.count;\n };\n return ExistenceFilter;\n}());\n\n\n//# sourceMappingURL=existence_filter.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/remote/rpc_error.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n/**\n * Error Codes describing the different ways GRPC can fail. These are copied\n * directly from GRPC's sources here:\n *\n * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n *\n * Important! The names of these identifiers matter because the string forms\n * are used for reverse lookups from the webchannel stream. Do NOT change the\n * names of these identifiers.\n */\nvar RpcCode;\n(function (RpcCode) {\n RpcCode[RpcCode[\"OK\"] = 0] = \"OK\";\n RpcCode[RpcCode[\"CANCELLED\"] = 1] = \"CANCELLED\";\n RpcCode[RpcCode[\"UNKNOWN\"] = 2] = \"UNKNOWN\";\n RpcCode[RpcCode[\"INVALID_ARGUMENT\"] = 3] = \"INVALID_ARGUMENT\";\n RpcCode[RpcCode[\"DEADLINE_EXCEEDED\"] = 4] = \"DEADLINE_EXCEEDED\";\n RpcCode[RpcCode[\"NOT_FOUND\"] = 5] = \"NOT_FOUND\";\n RpcCode[RpcCode[\"ALREADY_EXISTS\"] = 6] = \"ALREADY_EXISTS\";\n RpcCode[RpcCode[\"PERMISSION_DENIED\"] = 7] = \"PERMISSION_DENIED\";\n RpcCode[RpcCode[\"UNAUTHENTICATED\"] = 16] = \"UNAUTHENTICATED\";\n RpcCode[RpcCode[\"RESOURCE_EXHAUSTED\"] = 8] = \"RESOURCE_EXHAUSTED\";\n RpcCode[RpcCode[\"FAILED_PRECONDITION\"] = 9] = \"FAILED_PRECONDITION\";\n RpcCode[RpcCode[\"ABORTED\"] = 10] = \"ABORTED\";\n RpcCode[RpcCode[\"OUT_OF_RANGE\"] = 11] = \"OUT_OF_RANGE\";\n RpcCode[RpcCode[\"UNIMPLEMENTED\"] = 12] = \"UNIMPLEMENTED\";\n RpcCode[RpcCode[\"INTERNAL\"] = 13] = \"INTERNAL\";\n RpcCode[RpcCode[\"UNAVAILABLE\"] = 14] = \"UNAVAILABLE\";\n RpcCode[RpcCode[\"DATA_LOSS\"] = 15] = \"DATA_LOSS\";\n})(RpcCode || (RpcCode = {}));\nfunction isPermanentError(code) {\n switch (code) {\n case Code.OK:\n return fail('Treated status OK as error');\n case Code.CANCELLED:\n case Code.UNKNOWN:\n case Code.DEADLINE_EXCEEDED:\n case Code.RESOURCE_EXHAUSTED:\n case Code.INTERNAL:\n case Code.UNAVAILABLE:\n // Unauthenticated means something went wrong with our token and we need\n // to retry with new credentials which will happen automatically.\n // TODO(b/37325376): Give up after second unauthenticated error.\n case Code.UNAUTHENTICATED:\n return false;\n case Code.INVALID_ARGUMENT:\n case Code.NOT_FOUND:\n case Code.ALREADY_EXISTS:\n case Code.PERMISSION_DENIED:\n case Code.FAILED_PRECONDITION:\n // Aborted might be retried in some scenarios, but that is dependant on\n // the context and should handled individually by the calling code.\n // See https://cloud.google.com/apis/design/errors.\n case Code.ABORTED:\n case Code.OUT_OF_RANGE:\n case Code.UNIMPLEMENTED:\n case Code.DATA_LOSS:\n return true;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n/**\n * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.\n *\n * @returns The Code equivalent to the given status string or undefined if\n * there is no match.\n */\nfunction mapCodeFromRpcStatus(status) {\n // tslint:disable-next-line:no-any lookup by string\n var code = RpcCode[status];\n if (code === undefined) {\n return undefined;\n }\n return mapCodeFromRpcCode(code);\n}\n/**\n * Maps an error Code from GRPC status code number, like 0, 1, or 14. These\n * are not the same as HTTP status codes.\n *\n * @returns The Code equivalent to the given GRPC status code. Fails if there\n * is no match.\n */\nfunction mapCodeFromRpcCode(code) {\n if (code === undefined) {\n // This shouldn't normally happen, but in certain error cases (like trying\n // to send invalid proto messages) we may get an error with no GRPC code.\n log_error('GRPC error has no .code');\n return Code.UNKNOWN;\n }\n switch (code) {\n case RpcCode.OK:\n return Code.OK;\n case RpcCode.CANCELLED:\n return Code.CANCELLED;\n case RpcCode.UNKNOWN:\n return Code.UNKNOWN;\n case RpcCode.DEADLINE_EXCEEDED:\n return Code.DEADLINE_EXCEEDED;\n case RpcCode.RESOURCE_EXHAUSTED:\n return Code.RESOURCE_EXHAUSTED;\n case RpcCode.INTERNAL:\n return Code.INTERNAL;\n case RpcCode.UNAVAILABLE:\n return Code.UNAVAILABLE;\n case RpcCode.UNAUTHENTICATED:\n return Code.UNAUTHENTICATED;\n case RpcCode.INVALID_ARGUMENT:\n return Code.INVALID_ARGUMENT;\n case RpcCode.NOT_FOUND:\n return Code.NOT_FOUND;\n case RpcCode.ALREADY_EXISTS:\n return Code.ALREADY_EXISTS;\n case RpcCode.PERMISSION_DENIED:\n return Code.PERMISSION_DENIED;\n case RpcCode.FAILED_PRECONDITION:\n return Code.FAILED_PRECONDITION;\n case RpcCode.ABORTED:\n return Code.ABORTED;\n case RpcCode.OUT_OF_RANGE:\n return Code.OUT_OF_RANGE;\n case RpcCode.UNIMPLEMENTED:\n return Code.UNIMPLEMENTED;\n case RpcCode.DATA_LOSS:\n return Code.DATA_LOSS;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n/**\n * Maps an RPC code from a Code. This is the reverse operation from\n * mapCodeFromRpcCode and should really only be used in tests.\n */\nfunction mapRpcCodeFromCode(code) {\n if (code === undefined) {\n return RpcCode.OK;\n }\n switch (code) {\n case Code.OK:\n return RpcCode.OK;\n case Code.CANCELLED:\n return RpcCode.CANCELLED;\n case Code.UNKNOWN:\n return RpcCode.UNKNOWN;\n case Code.DEADLINE_EXCEEDED:\n return RpcCode.DEADLINE_EXCEEDED;\n case Code.RESOURCE_EXHAUSTED:\n return RpcCode.RESOURCE_EXHAUSTED;\n case Code.INTERNAL:\n return RpcCode.INTERNAL;\n case Code.UNAVAILABLE:\n return RpcCode.UNAVAILABLE;\n case Code.UNAUTHENTICATED:\n return RpcCode.UNAUTHENTICATED;\n case Code.INVALID_ARGUMENT:\n return RpcCode.INVALID_ARGUMENT;\n case Code.NOT_FOUND:\n return RpcCode.NOT_FOUND;\n case Code.ALREADY_EXISTS:\n return RpcCode.ALREADY_EXISTS;\n case Code.PERMISSION_DENIED:\n return RpcCode.PERMISSION_DENIED;\n case Code.FAILED_PRECONDITION:\n return RpcCode.FAILED_PRECONDITION;\n case Code.ABORTED:\n return RpcCode.ABORTED;\n case Code.OUT_OF_RANGE:\n return RpcCode.OUT_OF_RANGE;\n case Code.UNIMPLEMENTED:\n return RpcCode.UNIMPLEMENTED;\n case Code.DATA_LOSS:\n return RpcCode.DATA_LOSS;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n/**\n * Converts an HTTP Status Code to the equivalent error code.\n *\n * @param status An HTTP Status Code, like 200, 404, 503, etc.\n * @returns The equivalent Code. Unknown status codes are mapped to\n * Code.UNKNOWN.\n */\nfunction mapCodeFromHttpStatus(status) {\n // The canonical error codes for Google APIs [1] specify mapping onto HTTP\n // status codes but the mapping is not bijective. In each case of ambiguity\n // this function chooses a primary error.\n //\n // [1]\n // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\n switch (status) {\n case 200:// OK\n return Code.OK;\n case 400:// Bad Request\n return Code.INVALID_ARGUMENT;\n // Other possibilities based on the forward mapping\n // return Code.FAILED_PRECONDITION;\n // return Code.OUT_OF_RANGE;\n case 401:// Unauthorized\n return Code.UNAUTHENTICATED;\n case 403:// Forbidden\n return Code.PERMISSION_DENIED;\n case 404:// Not Found\n return Code.NOT_FOUND;\n case 409:// Conflict\n return Code.ABORTED;\n // Other possibilities:\n // return Code.ALREADY_EXISTS;\n case 416:// Range Not Satisfiable\n return Code.OUT_OF_RANGE;\n case 429:// Too Many Requests\n return Code.RESOURCE_EXHAUSTED;\n case 499:// Client Closed Request\n return Code.CANCELLED;\n case 500:// Internal Server Error\n return Code.UNKNOWN;\n // Other possibilities:\n // return Code.INTERNAL;\n // return Code.DATA_LOSS;\n case 501:// Unimplemented\n return Code.UNIMPLEMENTED;\n case 503:// Service Unavailable\n return Code.UNAVAILABLE;\n case 504:// Gateway Timeout\n return Code.DEADLINE_EXCEEDED;\n default:\n if (status >= 200 && status < 300)\n return Code.OK;\n if (status >= 400 && status < 500)\n return Code.FAILED_PRECONDITION;\n if (status >= 500 && status < 600)\n return Code.INTERNAL;\n return Code.UNKNOWN;\n }\n}\n\n//# sourceMappingURL=rpc_error.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/sorted_set.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * SortedSet is an immutable (copy-on-write) collection that holds elements\n * in order specified by the provided comparator.\n *\n * NOTE: if provided comparator returns 0 for two elements, we consider them to\n * be equal!\n */\nvar sorted_set_SortedSet = /** @class */ (function () {\n function SortedSet(comparator) {\n this.comparator = comparator;\n this.data = new sorted_map_SortedMap(this.comparator);\n }\n /**\n * Creates a SortedSet from the keys of the map.\n * This is currently implemented as an O(n) copy.\n */\n SortedSet.fromMapKeys = function (map) {\n var keys = new SortedSet(map.comparator);\n map.forEach(function (key) {\n keys = keys.add(key);\n });\n return keys;\n };\n SortedSet.prototype.has = function (elem) {\n return this.data.get(elem) !== null;\n };\n SortedSet.prototype.first = function () {\n return this.data.minKey();\n };\n SortedSet.prototype.last = function () {\n return this.data.maxKey();\n };\n Object.defineProperty(SortedSet.prototype, \"size\", {\n get: function () {\n return this.data.size;\n },\n enumerable: true,\n configurable: true\n });\n SortedSet.prototype.indexOf = function (elem) {\n return this.data.indexOf(elem);\n };\n /** Iterates elements in order defined by \"comparator\" */\n SortedSet.prototype.forEach = function (cb) {\n this.data.inorderTraversal(function (k, v) {\n cb(k);\n return false;\n });\n };\n /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */\n SortedSet.prototype.forEachInRange = function (range, cb) {\n var iter = this.data.getIteratorFrom(range[0]);\n while (iter.hasNext()) {\n var elem = iter.getNext();\n if (this.comparator(elem.key, range[1]) >= 0)\n return;\n cb(elem.key);\n }\n };\n /**\n * Iterates over `elem`s such that: start <= elem until false is returned.\n */\n SortedSet.prototype.forEachWhile = function (cb, start) {\n var iter;\n if (start !== undefined) {\n iter = this.data.getIteratorFrom(start);\n }\n else {\n iter = this.data.getIterator();\n }\n while (iter.hasNext()) {\n var elem = iter.getNext();\n var result = cb(elem.key);\n if (!result)\n return;\n }\n };\n /** Finds the least element greater than or equal to `elem`. */\n SortedSet.prototype.firstAfterOrEqual = function (elem) {\n var iter = this.data.getIteratorFrom(elem);\n return iter.hasNext() ? iter.getNext().key : null;\n };\n /** Inserts or updates an element */\n SortedSet.prototype.add = function (elem) {\n return this.copy(this.data.remove(elem).insert(elem, true));\n };\n /** Deletes an element */\n SortedSet.prototype.delete = function (elem) {\n if (!this.has(elem))\n return this;\n return this.copy(this.data.remove(elem));\n };\n SortedSet.prototype.isEmpty = function () {\n return this.data.isEmpty();\n };\n SortedSet.prototype.unionWith = function (other) {\n var result = this;\n other.forEach(function (elem) {\n result = result.add(elem);\n });\n return result;\n };\n SortedSet.prototype.isEqual = function (other) {\n if (!(other instanceof SortedSet))\n return false;\n if (this.size !== other.size)\n return false;\n var thisIt = this.data.getIterator();\n var otherIt = other.data.getIterator();\n while (thisIt.hasNext()) {\n var thisElem = thisIt.getNext().key;\n var otherElem = otherIt.getNext().key;\n if (this.comparator(thisElem, otherElem) !== 0)\n return false;\n }\n return true;\n };\n SortedSet.prototype.toString = function () {\n var result = [];\n this.forEach(function (elem) { return result.push(elem); });\n return 'SortedSet(' + result.toString() + ')';\n };\n SortedSet.prototype.copy = function (data) {\n var result = new SortedSet(this.comparator);\n result.data = data;\n return result;\n };\n return SortedSet;\n}());\n\n\n//# sourceMappingURL=sorted_set.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/model/collections.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\nvar EMPTY_MAYBE_DOCUMENT_MAP = new sorted_map_SortedMap(document_key_DocumentKey.comparator);\nfunction maybeDocumentMap() {\n return EMPTY_MAYBE_DOCUMENT_MAP;\n}\nvar EMPTY_DOCUMENT_MAP = new sorted_map_SortedMap(document_key_DocumentKey.comparator);\nfunction documentMap() {\n return EMPTY_DOCUMENT_MAP;\n}\nvar EMPTY_DOCUMENT_VERSION_MAP = new sorted_map_SortedMap(document_key_DocumentKey.comparator);\nfunction documentVersionMap() {\n return EMPTY_DOCUMENT_VERSION_MAP;\n}\nvar EMPTY_DOCUMENT_KEY_SET = new sorted_set_SortedSet(document_key_DocumentKey.comparator);\nfunction documentKeySet() {\n return EMPTY_DOCUMENT_KEY_SET;\n}\n\n//# sourceMappingURL=collections.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/remote/remote_event.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n/**\n * An event from the RemoteStore. It is split into targetChanges (changes to the\n * state or the set of documents in our watched targets) and documentUpdates\n * (changes to the actual documents).\n */\nvar remote_event_RemoteEvent = /** @class */ (function () {\n function RemoteEvent(\n /**\n * The snapshot version this event brings us up to, or MIN if not set.\n */\n snapshotVersion, \n /**\n * A map from target to changes to the target. See TargetChange.\n */\n targetChanges, \n /**\n * A set of which documents have changed or been deleted, along with the\n * doc's new values (if not deleted).\n */\n documentUpdates) {\n this.snapshotVersion = snapshotVersion;\n this.targetChanges = targetChanges;\n this.documentUpdates = documentUpdates;\n }\n RemoteEvent.prototype.addDocumentUpdate = function (doc) {\n this.documentUpdates = this.documentUpdates.insert(doc.key, doc);\n };\n RemoteEvent.prototype.handleExistenceFilterMismatch = function (targetId) {\n /*\n * An existence filter mismatch will reset the query and we need to reset\n * the mapping to contain no documents and an empty resume token.\n *\n * Note:\n * * The reset mapping is empty, specifically forcing the consumer of the\n * change to forget all keys for this targetID;\n * * The resume snapshot for this target must be reset\n * * The target must be unacked because unwatching and rewatching\n * introduces a race for changes.\n */\n this.targetChanges[targetId] = {\n mapping: new ResetMapping(),\n snapshotVersion: snapshot_version_SnapshotVersion.MIN,\n currentStatusUpdate: CurrentStatusUpdate.MarkNotCurrent,\n resumeToken: emptyByteString()\n };\n };\n return RemoteEvent;\n}());\n\n/**\n * Represents an update to the current status of a target, either explicitly\n * having no new state, or the new value to set. Note \"current\" has special\n * meaning for in the RPC protocol that implies that a target is both up-to-date\n * and consistent with the rest of the watch stream.\n */\nvar CurrentStatusUpdate;\n(function (CurrentStatusUpdate) {\n /** The current status is not affected and should not be modified. */\n CurrentStatusUpdate[CurrentStatusUpdate[\"None\"] = 0] = \"None\";\n /** The target must be marked as no longer \"current\". */\n CurrentStatusUpdate[CurrentStatusUpdate[\"MarkNotCurrent\"] = 1] = \"MarkNotCurrent\";\n /** The target must be marked as \"current\". */\n CurrentStatusUpdate[CurrentStatusUpdate[\"MarkCurrent\"] = 2] = \"MarkCurrent\";\n})(CurrentStatusUpdate || (CurrentStatusUpdate = {}));\nvar EMPTY_KEY_SET = documentKeySet();\nvar ResetMapping = /** @class */ (function () {\n function ResetMapping() {\n this.docs = EMPTY_KEY_SET;\n }\n Object.defineProperty(ResetMapping.prototype, \"documents\", {\n get: function () {\n return this.docs;\n },\n enumerable: true,\n configurable: true\n });\n ResetMapping.prototype.add = function (key) {\n this.docs = this.docs.add(key);\n };\n ResetMapping.prototype.delete = function (key) {\n this.docs = this.docs.delete(key);\n };\n ResetMapping.prototype.isEqual = function (other) {\n return other !== null && this.docs.isEqual(other.docs);\n };\n return ResetMapping;\n}());\n\nvar UpdateMapping = /** @class */ (function () {\n function UpdateMapping() {\n this.addedDocuments = EMPTY_KEY_SET;\n this.removedDocuments = EMPTY_KEY_SET;\n }\n UpdateMapping.prototype.applyToKeySet = function (keys) {\n var result = keys;\n this.addedDocuments.forEach(function (key) { return (result = result.add(key)); });\n this.removedDocuments.forEach(function (key) { return (result = result.delete(key)); });\n return result;\n };\n UpdateMapping.prototype.add = function (key) {\n this.addedDocuments = this.addedDocuments.add(key);\n this.removedDocuments = this.removedDocuments.delete(key);\n };\n UpdateMapping.prototype.delete = function (key) {\n this.addedDocuments = this.addedDocuments.delete(key);\n this.removedDocuments = this.removedDocuments.add(key);\n };\n UpdateMapping.prototype.isEqual = function (other) {\n return (other !== null &&\n this.addedDocuments.isEqual(other.addedDocuments) &&\n this.removedDocuments.isEqual(other.removedDocuments));\n };\n return UpdateMapping;\n}());\n\n\n//# sourceMappingURL=remote_event.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/remote/watch_change.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n\n\n/**\n * Represents a changed document and a list of target ids to which this change\n * applies.\n *\n * If document has been deleted NoDocument will be provided.\n */\nvar DocumentWatchChange = /** @class */ (function () {\n function DocumentWatchChange(\n /** The new document applies to all of these targets. */\n updatedTargetIds, \n /** The new document is removed from all of these targets. */\n removedTargetIds, \n /** The key of the document for this change. */\n key, \n /**\n * The new document or NoDocument if it was deleted. Is null if the\n * document went out of view without the server sending a new document.\n */\n newDoc) {\n this.updatedTargetIds = updatedTargetIds;\n this.removedTargetIds = removedTargetIds;\n this.key = key;\n this.newDoc = newDoc;\n }\n return DocumentWatchChange;\n}());\n\nvar ExistenceFilterChange = /** @class */ (function () {\n function ExistenceFilterChange(targetId, existenceFilter) {\n this.targetId = targetId;\n this.existenceFilter = existenceFilter;\n }\n return ExistenceFilterChange;\n}());\n\nvar WatchTargetChangeState;\n(function (WatchTargetChangeState) {\n WatchTargetChangeState[WatchTargetChangeState[\"NoChange\"] = 0] = \"NoChange\";\n WatchTargetChangeState[WatchTargetChangeState[\"Added\"] = 1] = \"Added\";\n WatchTargetChangeState[WatchTargetChangeState[\"Removed\"] = 2] = \"Removed\";\n WatchTargetChangeState[WatchTargetChangeState[\"Current\"] = 3] = \"Current\";\n WatchTargetChangeState[WatchTargetChangeState[\"Reset\"] = 4] = \"Reset\";\n})(WatchTargetChangeState || (WatchTargetChangeState = {}));\nvar watch_change_WatchTargetChange = /** @class */ (function () {\n function WatchTargetChange(\n /** What kind of change occurred to the watch target. */\n state, \n /** The target IDs that were added/removed/set. */\n targetIds, \n /**\n * An opaque, server-assigned token that allows watching a query to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the query. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */\n resumeToken, \n /** An RPC error indicating why the watch failed. */\n cause) {\n if (resumeToken === void 0) { resumeToken = emptyByteString(); }\n if (cause === void 0) { cause = null; }\n this.state = state;\n this.targetIds = targetIds;\n this.resumeToken = resumeToken;\n this.cause = cause;\n }\n return WatchTargetChange;\n}());\n\n/**\n * A helper class to accumulate watch changes into a RemoteEvent and other\n * target information.\n */\nvar watch_change_WatchChangeAggregator = /** @class */ (function () {\n function WatchChangeAggregator(snapshotVersion, listenTargets, pendingTargetResponses) {\n this.snapshotVersion = snapshotVersion;\n this.listenTargets = listenTargets;\n /** The existence filter - if any - for the given target IDs. */\n this.existenceFilters = {};\n /** Keeps track of the current target mappings */\n this.targetChanges = {};\n /** Keeps track of document to update */\n this.documentUpdates = maybeDocumentMap();\n /** Whether this aggregator was frozen and can no longer be modified */\n this.frozen = false;\n this.pendingTargetResponses = shallowCopy(pendingTargetResponses);\n }\n /** Aggregates a watch change into the current state */\n WatchChangeAggregator.prototype.add = function (watchChange) {\n assert(!this.frozen, 'Trying to modify frozen WatchChangeAggregator.');\n if (watchChange instanceof DocumentWatchChange) {\n this.addDocumentChange(watchChange);\n }\n else if (watchChange instanceof watch_change_WatchTargetChange) {\n this.addTargetChange(watchChange);\n }\n else if (watchChange instanceof ExistenceFilterChange) {\n this.addExistenceFilterChange(watchChange);\n }\n else {\n fail('Unknown watch change: ' + watchChange);\n }\n };\n /** Aggregates all provided watch changes to the current state in order */\n WatchChangeAggregator.prototype.addChanges = function (watchChanges) {\n var _this = this;\n assert(!this.frozen, 'Trying to modify frozen WatchChangeAggregator.');\n watchChanges.forEach(function (change) { return _this.add(change); });\n };\n /**\n * Converts the current state into a remote event with the snapshot version\n * provided via the constructor.\n */\n WatchChangeAggregator.prototype.createRemoteEvent = function () {\n var _this = this;\n var targetChanges = this.targetChanges;\n // Remove all the non-active targets from the remote event.\n forEachNumber(this.targetChanges, function (targetId) {\n if (!_this.isActiveTarget(targetId)) {\n delete targetChanges[targetId];\n }\n });\n // Mark this aggregator as frozen so no further modifications are made\n this.frozen = true;\n return new remote_event_RemoteEvent(this.snapshotVersion, targetChanges, this.documentUpdates);\n };\n WatchChangeAggregator.prototype.ensureTargetChange = function (targetId) {\n var change = this.targetChanges[targetId];\n if (!change) {\n // Create an UpdateMapping by default, since resets are always explicit.\n change = {\n currentStatusUpdate: CurrentStatusUpdate.None,\n snapshotVersion: this.snapshotVersion,\n mapping: new UpdateMapping(),\n resumeToken: emptyByteString()\n };\n this.targetChanges[targetId] = change;\n }\n return change;\n };\n /**\n * We need to wait for watch to ack targets before we process those events,\n * so to know if a target is active, there must be no pending acks we're\n * waiting for and it must be in the current list of targets that the client\n * cares about.\n *\n * This method is visible for testing.\n */\n WatchChangeAggregator.prototype.isActiveTarget = function (targetId) {\n return (!contains(this.pendingTargetResponses, targetId) &&\n contains(this.listenTargets, targetId));\n };\n WatchChangeAggregator.prototype.addDocumentChange = function (docChange) {\n var relevant = false;\n for (var _i = 0, _a = docChange.updatedTargetIds; _i < _a.length; _i++) {\n var targetId = _a[_i];\n if (this.isActiveTarget(targetId)) {\n var change = this.ensureTargetChange(targetId);\n change.mapping.add(docChange.key);\n relevant = true;\n }\n }\n for (var _b = 0, _c = docChange.removedTargetIds; _b < _c.length; _b++) {\n var targetId = _c[_b];\n if (this.isActiveTarget(targetId)) {\n var change = this.ensureTargetChange(targetId);\n change.mapping.delete(docChange.key);\n relevant = true;\n }\n }\n // Only update the document if there is a new document to replace to an\n // active target that is being listened to, this might be just a target\n // update instead.\n if (docChange.newDoc && relevant) {\n this.documentUpdates = this.documentUpdates.insert(docChange.key, docChange.newDoc);\n }\n };\n WatchChangeAggregator.prototype.addTargetChange = function (targetChange) {\n var _this = this;\n targetChange.targetIds.forEach(function (targetId) {\n var change = _this.ensureTargetChange(targetId);\n switch (targetChange.state) {\n case WatchTargetChangeState.NoChange:\n if (_this.isActiveTarget(targetId)) {\n // Creating the change above satisfies the semantics of no-change.\n applyResumeToken(change, targetChange.resumeToken);\n }\n break;\n case WatchTargetChangeState.Added:\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n _this.recordTargetResponse(targetId);\n if (!contains(_this.pendingTargetResponses, targetId)) {\n // We have a freshly added target, so we need to reset any state\n // that we had previously This can happen e.g. when remove and add\n // back a target for existence filter mismatches.\n change.mapping = new UpdateMapping();\n change.currentStatusUpdate = CurrentStatusUpdate.None;\n delete _this.existenceFilters[targetId];\n }\n applyResumeToken(change, targetChange.resumeToken);\n break;\n case WatchTargetChangeState.Removed:\n // We need to keep track of removed targets to we can\n // post-filter and remove any target changes.\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n _this.recordTargetResponse(targetId);\n assert(!targetChange.cause, 'WatchChangeAggregator does not handle errored targets');\n break;\n case WatchTargetChangeState.Current:\n if (_this.isActiveTarget(targetId)) {\n change.currentStatusUpdate = CurrentStatusUpdate.MarkCurrent;\n applyResumeToken(change, targetChange.resumeToken);\n }\n break;\n case WatchTargetChangeState.Reset:\n if (_this.isActiveTarget(targetId)) {\n // Overwrite any existing target mapping with a reset\n // mapping. Every subsequent update will modify the reset\n // mapping, not an update mapping.\n change.mapping = new ResetMapping();\n applyResumeToken(change, targetChange.resumeToken);\n }\n break;\n default:\n fail('Unknown target watch change state: ' + targetChange.state);\n }\n });\n };\n /**\n * Record that we get a watch target add/remove by decrementing the number of\n * pending target responses that we have.\n */\n WatchChangeAggregator.prototype.recordTargetResponse = function (targetId) {\n var newCount = (this.pendingTargetResponses[targetId] || 0) - 1;\n if (newCount === 0) {\n delete this.pendingTargetResponses[targetId];\n }\n else {\n this.pendingTargetResponses[targetId] = newCount;\n }\n };\n WatchChangeAggregator.prototype.addExistenceFilterChange = function (change) {\n if (this.isActiveTarget(change.targetId)) {\n this.existenceFilters[change.targetId] = change.existenceFilter;\n }\n };\n return WatchChangeAggregator;\n}());\n\n/**\n * Applies the resume token to the TargetChange, but only when it has a new\n * value. null and empty resumeTokens are discarded.\n */\nfunction applyResumeToken(change, resumeToken) {\n if (resumeToken.length > 0) {\n change.resumeToken = resumeToken;\n }\n}\n\n//# sourceMappingURL=watch_change.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/remote/serializer.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nvar DIRECTIONS = (function () {\n var dirs = {};\n dirs[Direction.ASCENDING.name] = 'ASCENDING';\n dirs[Direction.DESCENDING.name] = 'DESCENDING';\n return dirs;\n})();\nvar OPERATORS = (function () {\n var ops = {};\n ops[query_RelationOp.LESS_THAN.name] = 'LESS_THAN';\n ops[query_RelationOp.LESS_THAN_OR_EQUAL.name] = 'LESS_THAN_OR_EQUAL';\n ops[query_RelationOp.GREATER_THAN.name] = 'GREATER_THAN';\n ops[query_RelationOp.GREATER_THAN_OR_EQUAL.name] = 'GREATER_THAN_OR_EQUAL';\n ops[query_RelationOp.EQUAL.name] = 'EQUAL';\n return ops;\n})();\nfunction assertPresent(value, description) {\n assert(!isNullOrUndefined(value), description + ' is missing');\n}\nfunction parseInt64(value) {\n // TODO(bjornick): Handle int64 greater than 53 bits.\n if (typeof value === 'number') {\n return value;\n }\n else if (typeof value === 'string') {\n return Number(value);\n }\n else {\n return fail(\"can't parse \" + value);\n }\n}\n/**\n * Generates JsonObject values for the Datastore API suitable for sending to\n * either GRPC stub methods or via the JSON/HTTP REST API.\n * TODO(klimt): We can remove the databaseId argument if we keep the full\n * resource name in documents.\n */\nvar serializer_JsonProtoSerializer = /** @class */ (function () {\n function JsonProtoSerializer(databaseId, options) {\n this.databaseId = databaseId;\n this.options = options;\n }\n JsonProtoSerializer.prototype.emptyByteString = function () {\n if (this.options.useProto3Json) {\n return '';\n }\n else {\n return new Uint8Array(0);\n }\n };\n JsonProtoSerializer.prototype.unsafeCastProtoByteString = function (byteString) {\n // byteStrings can be either string or UInt8Array, but the typings say\n // it's always a string. Cast as string to avoid type check failing\n return byteString;\n };\n JsonProtoSerializer.prototype.fromRpcStatus = function (status) {\n var code = status.code === undefined\n ? Code.UNKNOWN\n : mapCodeFromRpcCode(status.code);\n return new FirestoreError(code, status.message || '');\n };\n /**\n * Returns a value for a number (or undefined) that's appropriate to put into\n * a google.protobuf.Int32Value proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"number\" because that's what\n * our generated proto interfaces say Int32Value must be. But GRPC actually\n * expects a { value: } struct.\n */\n JsonProtoSerializer.prototype.toInt32Value = function (val) {\n if (!isNullOrUndefined(val)) {\n // tslint:disable-next-line:no-any We need to match generated Proto types.\n return { value: val };\n }\n else {\n return undefined;\n }\n };\n /**\n * Returns a number (or null) from a google.protobuf.Int32Value proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as accepting \"number\" because that's what\n * our generated proto interfaces say Int32Value must be, but it actually\n * accepts { value: number } to match our serialization in toInt32Value().\n */\n JsonProtoSerializer.prototype.fromInt32Value = function (val) {\n var result;\n if (typeof val === 'object') {\n // tslint:disable-next-line:no-any We need to match generated Proto types.\n result = val.value;\n }\n else {\n // We accept raw numbers (without the {value: ... } wrapper) for\n // compatibility with legacy persisted data.\n result = val;\n }\n return isNullOrUndefined(result) ? null : result;\n };\n /**\n * Returns a value for a Date that's appropriate to put into a proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"string\" because that's what\n * our generated proto interfaces say dates must be. But it's easier and safer\n * to actually return a Timestamp proto.\n */\n JsonProtoSerializer.prototype.toTimestamp = function (timestamp) {\n return {\n seconds: timestamp.seconds,\n nanos: timestamp.nanos\n // tslint:disable-next-line:no-any\n };\n };\n JsonProtoSerializer.prototype.fromTimestamp = function (date) {\n // The json interface (for the browser) will return an iso timestamp string,\n // while the proto js library (for node) will return a\n // google.protobuf.Timestamp instance.\n if (typeof date === 'string') {\n // TODO(b/37282237): Use strings for Proto3 timestamps\n // assert(this.options.useProto3Json,\n // 'The timestamp string format requires Proto3.');\n return timestamp_Timestamp.fromISOString(date);\n }\n else {\n assert(!!date, 'Cannot deserialize null or undefined timestamp.');\n // TODO(b/37282237): Use strings for Proto3 timestamps\n // assert(!this.options.useProto3Json,\n // 'The timestamp instance format requires Proto JS.');\n var seconds = parseInt64(date.seconds || '0');\n var nanos = date.nanos || 0;\n return new timestamp_Timestamp(seconds, nanos);\n }\n };\n /**\n * Returns a value for bytes that's appropriate to put in a proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"string\" because that's what\n * our generated proto interfaces say bytes must be. But it should return\n * an Uint8Array in Node.\n */\n JsonProtoSerializer.prototype.toBytes = function (bytes) {\n if (this.options.useProto3Json) {\n return bytes.toBase64();\n }\n else {\n // The typings say it's a string, but it needs to be a Uint8Array in Node.\n return this.unsafeCastProtoByteString(bytes.toUint8Array());\n }\n };\n /**\n * Parse the blob from the protos into the internal Blob class. Note that the\n * typings assume all blobs are strings, but they are actually Uint8Arrays\n * on Node.\n */\n JsonProtoSerializer.prototype.fromBlob = function (blob) {\n if (typeof blob === 'string') {\n assert(this.options.useProto3Json, 'Expected bytes to be passed in as Uint8Array, but got a string instead.');\n return blob_Blob.fromBase64String(blob);\n }\n else {\n assert(!this.options.useProto3Json, 'Expected bytes to be passed in as string, but got something else instead.');\n return blob_Blob.fromUint8Array(blob);\n }\n };\n JsonProtoSerializer.prototype.toVersion = function (version) {\n return this.toTimestamp(version.toTimestamp());\n };\n JsonProtoSerializer.prototype.fromVersion = function (version) {\n assert(!!version, \"Trying to deserialize version that isn't set\");\n return snapshot_version_SnapshotVersion.fromTimestamp(this.fromTimestamp(version));\n };\n JsonProtoSerializer.prototype.toResourceName = function (databaseId, path) {\n return this.fullyQualifiedPrefixPath(databaseId)\n .child('documents')\n .child(path)\n .canonicalString();\n };\n JsonProtoSerializer.prototype.fromResourceName = function (name) {\n var resource = path_ResourcePath.fromString(name);\n assert(this.isValidResourceName(resource), 'Tried to deserialize invalid key ' + resource.toString());\n return resource;\n };\n JsonProtoSerializer.prototype.toName = function (key) {\n return this.toResourceName(this.databaseId, key.path);\n };\n JsonProtoSerializer.prototype.fromName = function (name) {\n var resource = this.fromResourceName(name);\n assert(resource.get(1) === this.databaseId.projectId, 'Tried to deserialize key from different project: ' +\n resource.get(1) +\n ' vs ' +\n this.databaseId.projectId);\n assert((!resource.get(3) && !this.databaseId.database) ||\n resource.get(3) === this.databaseId.database, 'Tried to deserialize key from different database: ' +\n resource.get(3) +\n ' vs ' +\n this.databaseId.database);\n return new document_key_DocumentKey(this.extractLocalPathFromResourceName(resource));\n };\n JsonProtoSerializer.prototype.toQueryPath = function (path) {\n if (path.length === 0) {\n // If the path is empty, the backend requires we leave off the /documents\n // at the end.\n return this.encodedDatabaseId;\n }\n return this.toResourceName(this.databaseId, path);\n };\n JsonProtoSerializer.prototype.fromQueryPath = function (name) {\n var resourceName = this.fromResourceName(name);\n if (resourceName.length === 4) {\n return path_ResourcePath.EMPTY_PATH;\n }\n return this.extractLocalPathFromResourceName(resourceName);\n };\n Object.defineProperty(JsonProtoSerializer.prototype, \"encodedDatabaseId\", {\n get: function () {\n var path = new path_ResourcePath([\n 'projects',\n this.databaseId.projectId,\n 'databases',\n this.databaseId.database\n ]);\n return path.canonicalString();\n },\n enumerable: true,\n configurable: true\n });\n JsonProtoSerializer.prototype.fullyQualifiedPrefixPath = function (databaseId) {\n return new path_ResourcePath([\n 'projects',\n databaseId.projectId,\n 'databases',\n databaseId.database\n ]);\n };\n JsonProtoSerializer.prototype.extractLocalPathFromResourceName = function (resourceName) {\n assert(resourceName.length > 4 && resourceName.get(4) === 'documents', 'tried to deserialize invalid key ' + resourceName.toString());\n return resourceName.popFirst(5);\n };\n JsonProtoSerializer.prototype.isValidResourceName = function (path) {\n // Resource names have at least 4 components (project ID, database ID)\n return (path.length >= 4 &&\n path.get(0) === 'projects' &&\n path.get(2) === 'databases');\n };\n JsonProtoSerializer.prototype.toValue = function (val) {\n if (val instanceof NullValue) {\n return { nullValue: 'NULL_VALUE' };\n }\n else if (val instanceof field_value_BooleanValue) {\n return { booleanValue: val.value() };\n }\n else if (val instanceof IntegerValue) {\n return { integerValue: '' + val.value() };\n }\n else if (val instanceof DoubleValue) {\n var doubleValue = val.value();\n if (this.options.useProto3Json) {\n // Proto 3 let's us encode NaN and Infinity as string values as\n // expected by the backend. This is currently not checked by our unit\n // tests because they rely on protobuf.js.\n if (isNaN(doubleValue)) {\n return { doubleValue: 'NaN' };\n }\n else if (doubleValue === Infinity) {\n return { doubleValue: 'Infinity' };\n }\n else if (doubleValue === -Infinity) {\n return { doubleValue: '-Infinity' };\n }\n }\n return { doubleValue: val.value() };\n }\n else if (val instanceof field_value_StringValue) {\n return { stringValue: val.value() };\n }\n else if (val instanceof field_value_ObjectValue) {\n return { mapValue: this.toMapValue(val) };\n }\n else if (val instanceof field_value_ArrayValue) {\n return { arrayValue: this.toArrayValue(val) };\n }\n else if (val instanceof TimestampValue) {\n return {\n timestampValue: this.toTimestamp(val.internalValue)\n };\n }\n else if (val instanceof GeoPointValue) {\n return {\n geoPointValue: {\n latitude: val.value().latitude,\n longitude: val.value().longitude\n }\n };\n }\n else if (val instanceof BlobValue) {\n return {\n bytesValue: this.toBytes(val.value())\n };\n }\n else if (val instanceof field_value_RefValue) {\n return {\n referenceValue: this.toResourceName(val.databaseId, val.key.path)\n };\n }\n else {\n return fail('Unknown FieldValue ' + JSON.stringify(val));\n }\n };\n JsonProtoSerializer.prototype.fromValue = function (obj) {\n var _this = this;\n // tslint:disable-next-line:no-any\n var type = obj['value_type'];\n if (hasTag(obj, type, 'nullValue')) {\n return NullValue.INSTANCE;\n }\n else if (hasTag(obj, type, 'booleanValue')) {\n return field_value_BooleanValue.of(obj.booleanValue);\n }\n else if (hasTag(obj, type, 'integerValue')) {\n return new IntegerValue(parseInt64(obj.integerValue));\n }\n else if (hasTag(obj, type, 'doubleValue')) {\n if (this.options.useProto3Json) {\n // Proto 3 uses the string values 'NaN' and 'Infinity'.\n if (obj.doubleValue === 'NaN') {\n return DoubleValue.NAN;\n }\n else if (obj.doubleValue === 'Infinity') {\n return DoubleValue.POSITIVE_INFINITY;\n }\n else if (obj.doubleValue === '-Infinity') {\n return DoubleValue.NEGATIVE_INFINITY;\n }\n }\n return new DoubleValue(obj.doubleValue);\n }\n else if (hasTag(obj, type, 'stringValue')) {\n return new field_value_StringValue(obj.stringValue);\n }\n else if (hasTag(obj, type, 'mapValue')) {\n return this.fromFields(obj.mapValue.fields || {});\n }\n else if (hasTag(obj, type, 'arrayValue')) {\n // \"values\" is not present if the array is empty\n assertPresent(obj.arrayValue, 'arrayValue');\n var values = obj.arrayValue.values || [];\n return new field_value_ArrayValue(values.map(function (v) { return _this.fromValue(v); }));\n }\n else if (hasTag(obj, type, 'timestampValue')) {\n assertPresent(obj.timestampValue, 'timestampValue');\n return new TimestampValue(this.fromTimestamp(obj.timestampValue));\n }\n else if (hasTag(obj, type, 'geoPointValue')) {\n assertPresent(obj.geoPointValue, 'geoPointValue');\n var latitude = obj.geoPointValue.latitude || 0;\n var longitude = obj.geoPointValue.longitude || 0;\n return new GeoPointValue(new geo_point_GeoPoint(latitude, longitude));\n }\n else if (hasTag(obj, type, 'bytesValue')) {\n assertPresent(obj.bytesValue, 'bytesValue');\n var blob = this.fromBlob(obj.bytesValue);\n return new BlobValue(blob);\n }\n else if (hasTag(obj, type, 'referenceValue')) {\n assertPresent(obj.referenceValue, 'referenceValue');\n var resourceName = this.fromResourceName(obj.referenceValue);\n var dbId = new database_info_DatabaseId(resourceName.get(1), resourceName.get(3));\n var key = new document_key_DocumentKey(this.extractLocalPathFromResourceName(resourceName));\n return new field_value_RefValue(dbId, key);\n }\n else {\n return fail('Unknown Value proto ' + JSON.stringify(obj));\n }\n };\n /** Creates an api.Document from key and fields (but no create/update time) */\n JsonProtoSerializer.prototype.toMutationDocument = function (key, fields) {\n return {\n name: this.toName(key),\n fields: this.toFields(fields)\n };\n };\n JsonProtoSerializer.prototype.toDocument = function (document) {\n assert(!document.hasLocalMutations, \"Can't serialize documents with mutations.\");\n return {\n name: this.toName(document.key),\n fields: this.toFields(document.data),\n updateTime: this.toTimestamp(document.version.toTimestamp())\n };\n };\n JsonProtoSerializer.prototype.fromDocument = function (document) {\n return new document_Document(this.fromName(document.name), this.fromVersion(document.updateTime), this.fromFields(document.fields || {}), { hasLocalMutations: false });\n };\n JsonProtoSerializer.prototype.toFields = function (fields) {\n var _this = this;\n var result = {};\n fields.forEach(function (key, value) {\n result[key] = _this.toValue(value);\n });\n return result;\n };\n JsonProtoSerializer.prototype.fromFields = function (object) {\n var _this = this;\n // Proto map gets mapped to Object, so cast it.\n var map = object;\n var result = field_value_ObjectValue.EMPTY;\n forEach(map, function (key, value) {\n result = result.set(new path_FieldPath([key]), _this.fromValue(value));\n });\n return result;\n };\n JsonProtoSerializer.prototype.toMapValue = function (map) {\n return {\n fields: this.toFields(map)\n };\n };\n JsonProtoSerializer.prototype.toArrayValue = function (array) {\n var _this = this;\n var result = [];\n array.forEach(function (value) {\n result.push(_this.toValue(value));\n });\n return { values: result };\n };\n JsonProtoSerializer.prototype.fromFound = function (doc) {\n assert(!!doc.found, 'Tried to deserialize a found document from a missing document.');\n assertPresent(doc.found.name, 'doc.found.name');\n assertPresent(doc.found.updateTime, 'doc.found.updateTime');\n var key = this.fromName(doc.found.name);\n var version = this.fromVersion(doc.found.updateTime);\n var fields = this.fromFields(doc.found.fields || {});\n return new document_Document(key, version, fields, { hasLocalMutations: false });\n };\n JsonProtoSerializer.prototype.fromMissing = function (result) {\n assert(!!result.missing, 'Tried to deserialize a missing document from a found document.');\n assert(!!result.readTime, 'Tried to deserialize a missing document without a read time.');\n var key = this.fromName(result.missing);\n var version = this.fromVersion(result.readTime);\n return new document_NoDocument(key, version);\n };\n JsonProtoSerializer.prototype.fromMaybeDocument = function (result) {\n // tslint:disable-next-line:no-any\n var type = result['result'];\n if (hasTag(result, type, 'found')) {\n return this.fromFound(result);\n }\n else if (hasTag(result, type, 'missing')) {\n return this.fromMissing(result);\n }\n return fail('invalid batch get response: ' + JSON.stringify(result));\n };\n JsonProtoSerializer.prototype.toWatchTargetChangeState = function (state) {\n switch (state) {\n case WatchTargetChangeState.Added:\n return 'ADD';\n case WatchTargetChangeState.Current:\n return 'CURRENT';\n case WatchTargetChangeState.NoChange:\n return 'NO_CHANGE';\n case WatchTargetChangeState.Removed:\n return 'REMOVE';\n case WatchTargetChangeState.Reset:\n return 'RESET';\n default:\n return fail('Unknown WatchTargetChangeState: ' + state);\n }\n };\n JsonProtoSerializer.prototype.toTestWatchChange = function (watchChange) {\n if (watchChange instanceof ExistenceFilterChange) {\n return {\n filter: {\n count: watchChange.existenceFilter.count,\n targetId: watchChange.targetId\n }\n };\n }\n if (watchChange instanceof DocumentWatchChange) {\n if (watchChange.newDoc instanceof document_Document) {\n var doc = watchChange.newDoc;\n return {\n documentChange: {\n document: {\n name: this.toName(doc.key),\n fields: this.toFields(doc.data),\n updateTime: this.toVersion(doc.version)\n },\n targetIds: watchChange.updatedTargetIds,\n removedTargetIds: watchChange.removedTargetIds\n }\n };\n }\n else if (watchChange.newDoc instanceof document_NoDocument) {\n var doc = watchChange.newDoc;\n return {\n documentDelete: {\n document: this.toName(doc.key),\n readTime: this.toVersion(doc.version),\n removedTargetIds: watchChange.removedTargetIds\n }\n };\n }\n else if (watchChange.newDoc === null) {\n return {\n documentRemove: {\n document: this.toName(watchChange.key),\n removedTargetIds: watchChange.removedTargetIds\n }\n };\n }\n }\n if (watchChange instanceof watch_change_WatchTargetChange) {\n var cause = undefined;\n if (watchChange.cause) {\n cause = {\n code: mapRpcCodeFromCode(watchChange.cause.code),\n message: watchChange.cause.message\n };\n }\n return {\n targetChange: {\n targetChangeType: this.toWatchTargetChangeState(watchChange.state),\n targetIds: watchChange.targetIds,\n resumeToken: this.unsafeCastProtoByteString(watchChange.resumeToken),\n cause: cause\n }\n };\n }\n return fail('Unrecognized watch change: ' + JSON.stringify(watchChange));\n };\n JsonProtoSerializer.prototype.fromWatchChange = function (change) {\n // tslint:disable-next-line:no-any\n var type = change['response_type'];\n var watchChange;\n if (hasTag(change, type, 'targetChange')) {\n assertPresent(change.targetChange, 'targetChange');\n // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'\n // if unset\n var state = this.fromWatchTargetChangeState(change.targetChange.targetChangeType || 'NO_CHANGE');\n var targetIds = change.targetChange.targetIds || [];\n var resumeToken = change.targetChange.resumeToken || this.emptyByteString();\n var causeProto = change.targetChange.cause;\n var cause = causeProto && this.fromRpcStatus(causeProto);\n watchChange = new watch_change_WatchTargetChange(state, targetIds, resumeToken, cause || null);\n }\n else if (hasTag(change, type, 'documentChange')) {\n assertPresent(change.documentChange, 'documentChange');\n assertPresent(change.documentChange.document, 'documentChange.name');\n assertPresent(change.documentChange.document.name, 'documentChange.document.name');\n assertPresent(change.documentChange.document.updateTime, 'documentChange.document.updateTime');\n var entityChange = change.documentChange;\n var key = this.fromName(entityChange.document.name);\n var version = this.fromVersion(entityChange.document.updateTime);\n var fields = this.fromFields(entityChange.document.fields || {});\n var doc = new document_Document(key, version, fields, {\n hasLocalMutations: false\n });\n var updatedTargetIds = entityChange.targetIds || [];\n var removedTargetIds = entityChange.removedTargetIds || [];\n watchChange = new DocumentWatchChange(updatedTargetIds, removedTargetIds, doc.key, doc);\n }\n else if (hasTag(change, type, 'documentDelete')) {\n assertPresent(change.documentDelete, 'documentDelete');\n assertPresent(change.documentDelete.document, 'documentDelete.document');\n var docDelete = change.documentDelete;\n var key = this.fromName(docDelete.document);\n var version = docDelete.readTime\n ? this.fromVersion(docDelete.readTime)\n : snapshot_version_SnapshotVersion.forDeletedDoc();\n var doc = new document_NoDocument(key, version);\n var removedTargetIds = docDelete.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, doc.key, doc);\n }\n else if (hasTag(change, type, 'documentRemove')) {\n assertPresent(change.documentRemove, 'documentRemove');\n assertPresent(change.documentRemove.document, 'documentRemove');\n var docRemove = change.documentRemove;\n var key = this.fromName(docRemove.document);\n var removedTargetIds = docRemove.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, key, null);\n }\n else if (hasTag(change, type, 'filter')) {\n // TODO(dimond): implement existence filter parsing with strategy.\n assertPresent(change.filter, 'filter');\n assertPresent(change.filter.targetId, 'filter.targetId');\n var filter = change.filter;\n var count = filter.count || 0;\n var existenceFilter = new ExistenceFilter(count);\n var targetId = filter.targetId;\n watchChange = new ExistenceFilterChange(targetId, existenceFilter);\n }\n else {\n return fail('Unknown change type ' + JSON.stringify(change));\n }\n return watchChange;\n };\n JsonProtoSerializer.prototype.fromWatchTargetChangeState = function (state) {\n if (state === 'NO_CHANGE') {\n return WatchTargetChangeState.NoChange;\n }\n else if (state === 'ADD') {\n return WatchTargetChangeState.Added;\n }\n else if (state === 'REMOVE') {\n return WatchTargetChangeState.Removed;\n }\n else if (state === 'CURRENT') {\n return WatchTargetChangeState.Current;\n }\n else if (state === 'RESET') {\n return WatchTargetChangeState.Reset;\n }\n else {\n return fail('Got unexpected TargetChange.state: ' + state);\n }\n };\n JsonProtoSerializer.prototype.versionFromListenResponse = function (change) {\n // We have only reached a consistent snapshot for the entire stream if there\n // is a read_time set and it applies to all targets (i.e. the list of\n // targets is empty). The backend is guaranteed to send such responses.\n // tslint:disable-next-line:no-any\n var type = change['response_type'];\n if (!hasTag(change, type, 'targetChange')) {\n return snapshot_version_SnapshotVersion.MIN;\n }\n var targetChange = change.targetChange;\n if (targetChange.targetIds && targetChange.targetIds.length) {\n return snapshot_version_SnapshotVersion.MIN;\n }\n if (!targetChange.readTime) {\n return snapshot_version_SnapshotVersion.MIN;\n }\n return this.fromVersion(targetChange.readTime);\n };\n JsonProtoSerializer.prototype.toMutation = function (mutation) {\n var _this = this;\n var result;\n if (mutation instanceof mutation_SetMutation) {\n result = {\n update: this.toMutationDocument(mutation.key, mutation.value)\n };\n }\n else if (mutation instanceof mutation_DeleteMutation) {\n result = { delete: this.toName(mutation.key) };\n }\n else if (mutation instanceof mutation_PatchMutation) {\n result = {\n update: this.toMutationDocument(mutation.key, mutation.data),\n updateMask: this.toDocumentMask(mutation.fieldMask)\n };\n }\n else if (mutation instanceof mutation_TransformMutation) {\n result = {\n transform: {\n document: this.toName(mutation.key),\n fieldTransforms: mutation.fieldTransforms.map(function (transform) {\n return _this.toFieldTransform(transform);\n })\n }\n };\n }\n else {\n return fail('Unknown mutation type ' + mutation.type);\n }\n if (!mutation.precondition.isNone) {\n result.currentDocument = this.toPrecondition(mutation.precondition);\n }\n return result;\n };\n JsonProtoSerializer.prototype.fromMutation = function (proto) {\n var _this = this;\n var precondition = proto.currentDocument\n ? this.fromPrecondition(proto.currentDocument)\n : mutation_Precondition.NONE;\n if (proto.update) {\n assertPresent(proto.update.name, 'name');\n var key = this.fromName(proto.update.name);\n var value = this.fromFields(proto.update.fields || {});\n if (proto.updateMask) {\n var fieldMask = this.fromDocumentMask(proto.updateMask);\n return new mutation_PatchMutation(key, value, fieldMask, precondition);\n }\n else {\n return new mutation_SetMutation(key, value, precondition);\n }\n }\n else if (proto.delete) {\n var key = this.fromName(proto.delete);\n return new mutation_DeleteMutation(key, precondition);\n }\n else if (proto.transform) {\n var key = this.fromName(proto.transform.document);\n var fieldTransforms = proto.transform.fieldTransforms.map(function (transform) {\n return _this.fromFieldTransform(transform);\n });\n assert(precondition.exists === true, 'Transforms only support precondition \"exists == true\"');\n return new mutation_TransformMutation(key, fieldTransforms);\n }\n else {\n return fail('unknown mutation proto: ' + JSON.stringify(proto));\n }\n };\n JsonProtoSerializer.prototype.toPrecondition = function (precondition) {\n assert(!precondition.isNone, \"Can't serialize an empty precondition\");\n if (precondition.updateTime !== undefined) {\n return {\n updateTime: this.toVersion(precondition.updateTime)\n };\n }\n else if (precondition.exists !== undefined) {\n return { exists: precondition.exists };\n }\n else {\n return fail('Unknown precondition');\n }\n };\n JsonProtoSerializer.prototype.fromPrecondition = function (precondition) {\n if (precondition.updateTime !== undefined) {\n return mutation_Precondition.updateTime(this.fromVersion(precondition.updateTime));\n }\n else if (precondition.exists !== undefined) {\n return mutation_Precondition.exists(precondition.exists);\n }\n else {\n return mutation_Precondition.NONE;\n }\n };\n JsonProtoSerializer.prototype.fromWriteResult = function (proto) {\n var _this = this;\n // NOTE: Deletes don't have an updateTime.\n var version = proto.updateTime\n ? this.fromVersion(proto.updateTime)\n : null;\n var transformResults = null;\n if (proto.transformResults && proto.transformResults.length > 0) {\n transformResults = proto.transformResults.map(function (result) {\n return _this.fromValue(result);\n });\n }\n return new MutationResult(version, transformResults);\n };\n JsonProtoSerializer.prototype.fromWriteResults = function (protos) {\n var _this = this;\n return (protos || []).map(function (proto) { return _this.fromWriteResult(proto); });\n };\n JsonProtoSerializer.prototype.toFieldTransform = function (fieldTransform) {\n assert(fieldTransform.transform instanceof ServerTimestampTransform, 'Unknown transform: ' + fieldTransform.transform);\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n setToServerValue: 'REQUEST_TIME'\n };\n };\n JsonProtoSerializer.prototype.fromFieldTransform = function (proto) {\n assert(proto.setToServerValue === 'REQUEST_TIME', 'Unknown transform proto: ' + JSON.stringify(proto));\n var fieldPath = path_FieldPath.fromServerFormat(proto.fieldPath);\n return new FieldTransform(fieldPath, ServerTimestampTransform.instance);\n };\n JsonProtoSerializer.prototype.toDocumentsTarget = function (query) {\n return { documents: [this.toQueryPath(query.path)] };\n };\n JsonProtoSerializer.prototype.fromDocumentsTarget = function (documentsTarget) {\n var count = documentsTarget.documents.length;\n assert(count === 1, 'DocumentsTarget contained other than 1 document: ' + count);\n var name = documentsTarget.documents[0];\n return query_Query.atPath(this.fromQueryPath(name));\n };\n JsonProtoSerializer.prototype.toQueryTarget = function (query) {\n // Dissect the path into parent, collectionId, and optional key filter.\n var result = { structuredQuery: {} };\n if (query.path.isEmpty()) {\n result.parent = this.toQueryPath(path_ResourcePath.EMPTY_PATH);\n }\n else {\n var path = query.path;\n assert(path.length % 2 !== 0, 'Document queries with filters are not supported.');\n result.parent = this.toQueryPath(path.popLast());\n result.structuredQuery.from = [{ collectionId: path.lastSegment() }];\n }\n var where = this.toFilter(query.filters);\n if (where) {\n result.structuredQuery.where = where;\n }\n var orderBy = this.toOrder(query.orderBy);\n if (orderBy) {\n result.structuredQuery.orderBy = orderBy;\n }\n var limit = this.toInt32Value(query.limit);\n if (limit !== undefined) {\n result.structuredQuery.limit = limit;\n }\n if (query.startAt) {\n result.structuredQuery.startAt = this.toCursor(query.startAt);\n }\n if (query.endAt) {\n result.structuredQuery.endAt = this.toCursor(query.endAt);\n }\n return result;\n };\n JsonProtoSerializer.prototype.fromQueryTarget = function (target) {\n var path = this.fromQueryPath(target.parent);\n var query = target.structuredQuery;\n var fromCount = query.from ? query.from.length : 0;\n if (fromCount > 0) {\n assert(fromCount === 1, 'StructuredQuery.from with more than one collection is not supported.');\n var from = query.from[0];\n path = path.child(from.collectionId);\n }\n var filterBy = [];\n if (query.where) {\n filterBy = this.fromFilter(query.where);\n }\n var orderBy = [];\n if (query.orderBy) {\n orderBy = this.fromOrder(query.orderBy);\n }\n var limit = null;\n if (query.limit) {\n limit = this.fromInt32Value(query.limit);\n }\n var startAt = null;\n if (query.startAt) {\n startAt = this.fromCursor(query.startAt);\n }\n var endAt = null;\n if (query.endAt) {\n endAt = this.fromCursor(query.endAt);\n }\n return new query_Query(path, orderBy, filterBy, limit, startAt, endAt);\n };\n JsonProtoSerializer.prototype.toListenRequestLabels = function (queryData) {\n var value = this.toLabel(queryData.purpose);\n if (value == null) {\n return null;\n }\n else {\n return {\n 'goog-listen-tags': value\n };\n }\n };\n JsonProtoSerializer.prototype.toLabel = function (purpose) {\n switch (purpose) {\n case QueryPurpose.Listen:\n return null;\n case QueryPurpose.ExistenceFilterMismatch:\n return 'existence-filter-mismatch';\n case QueryPurpose.LimboResolution:\n return 'limbo-document';\n default:\n return fail('Unrecognized query purpose: ' + purpose);\n }\n };\n JsonProtoSerializer.prototype.toTarget = function (queryData) {\n var result;\n var query = queryData.query;\n if (query.isDocumentQuery()) {\n result = { documents: this.toDocumentsTarget(query) };\n }\n else {\n result = { query: this.toQueryTarget(query) };\n }\n result.targetId = queryData.targetId;\n if (queryData.resumeToken.length > 0) {\n result.resumeToken = this.unsafeCastProtoByteString(queryData.resumeToken);\n }\n return result;\n };\n JsonProtoSerializer.prototype.toFilter = function (filters) {\n var _this = this;\n if (filters.length === 0)\n return;\n var protos = filters.map(function (filter) {\n return filter instanceof query_RelationFilter\n ? _this.toRelationFilter(filter)\n : _this.toUnaryFilter(filter);\n });\n if (protos.length === 1) {\n return protos[0];\n }\n return { compositeFilter: { op: 'AND', filters: protos } };\n };\n JsonProtoSerializer.prototype.fromFilter = function (filter) {\n var _this = this;\n if (!filter) {\n return [];\n }\n else if (filter.unaryFilter !== undefined) {\n return [this.fromUnaryFilter(filter)];\n }\n else if (filter.fieldFilter !== undefined) {\n return [this.fromRelationFilter(filter)];\n }\n else if (filter.compositeFilter !== undefined) {\n return filter.compositeFilter.filters\n .map(function (f) { return _this.fromFilter(f); })\n .reduce(function (accum, current) { return accum.concat(current); });\n }\n else {\n return fail('Unknown filter: ' + JSON.stringify(filter));\n }\n };\n JsonProtoSerializer.prototype.toOrder = function (orderBys) {\n var _this = this;\n if (orderBys.length === 0)\n return;\n return orderBys.map(function (order) { return _this.toPropertyOrder(order); });\n };\n JsonProtoSerializer.prototype.fromOrder = function (orderBys) {\n var _this = this;\n return orderBys.map(function (order) { return _this.fromPropertyOrder(order); });\n };\n JsonProtoSerializer.prototype.toCursor = function (cursor) {\n var _this = this;\n return {\n before: cursor.before,\n values: cursor.position.map(function (component) { return _this.toValue(component); })\n };\n };\n JsonProtoSerializer.prototype.fromCursor = function (cursor) {\n var _this = this;\n var before = !!cursor.before;\n var position = cursor.values.map(function (component) { return _this.fromValue(component); });\n return new query_Bound(position, before);\n };\n // visible for testing\n JsonProtoSerializer.prototype.toDirection = function (dir) {\n return DIRECTIONS[dir.name];\n };\n // visible for testing\n JsonProtoSerializer.prototype.fromDirection = function (dir) {\n switch (dir) {\n case 'ASCENDING':\n return Direction.ASCENDING;\n case 'DESCENDING':\n return Direction.DESCENDING;\n default:\n return undefined;\n }\n };\n // visible for testing\n JsonProtoSerializer.prototype.toOperatorName = function (op) {\n return OPERATORS[op.name];\n };\n JsonProtoSerializer.prototype.fromOperatorName = function (op) {\n switch (op) {\n case 'EQUAL':\n return query_RelationOp.EQUAL;\n case 'GREATER_THAN':\n return query_RelationOp.GREATER_THAN;\n case 'GREATER_THAN_OR_EQUAL':\n return query_RelationOp.GREATER_THAN_OR_EQUAL;\n case 'LESS_THAN':\n return query_RelationOp.LESS_THAN;\n case 'LESS_THAN_OR_EQUAL':\n return query_RelationOp.LESS_THAN_OR_EQUAL;\n case 'OPERATOR_UNSPECIFIED':\n return fail('Unspecified relation');\n default:\n return fail('Unknown relation');\n }\n };\n JsonProtoSerializer.prototype.toFieldPathReference = function (path) {\n return { fieldPath: path.canonicalString() };\n };\n JsonProtoSerializer.prototype.fromFieldPathReference = function (fieldReference) {\n return path_FieldPath.fromServerFormat(fieldReference.fieldPath);\n };\n // visible for testing\n JsonProtoSerializer.prototype.toPropertyOrder = function (orderBy) {\n return {\n field: this.toFieldPathReference(orderBy.field),\n direction: this.toDirection(orderBy.dir)\n };\n };\n JsonProtoSerializer.prototype.fromPropertyOrder = function (orderBy) {\n return new query_OrderBy(this.fromFieldPathReference(orderBy.field), this.fromDirection(orderBy.direction));\n };\n // visible for testing\n JsonProtoSerializer.prototype.toRelationFilter = function (filter) {\n if (filter instanceof query_RelationFilter) {\n return {\n fieldFilter: {\n field: this.toFieldPathReference(filter.field),\n op: this.toOperatorName(filter.op),\n value: this.toValue(filter.value)\n }\n };\n }\n else {\n return fail('Unrecognized filter: ' + JSON.stringify(filter));\n }\n };\n JsonProtoSerializer.prototype.fromRelationFilter = function (filter) {\n return new query_RelationFilter(this.fromFieldPathReference(filter.fieldFilter.field), this.fromOperatorName(filter.fieldFilter.op), this.fromValue(filter.fieldFilter.value));\n };\n // visible for testing\n JsonProtoSerializer.prototype.toUnaryFilter = function (filter) {\n if (filter instanceof NanFilter) {\n return {\n unaryFilter: {\n field: this.toFieldPathReference(filter.field),\n op: 'IS_NAN'\n }\n };\n }\n else if (filter instanceof NullFilter) {\n return {\n unaryFilter: {\n field: this.toFieldPathReference(filter.field),\n op: 'IS_NULL'\n }\n };\n }\n else {\n return fail('Unrecognized filter: ' + JSON.stringify(filter));\n }\n };\n JsonProtoSerializer.prototype.fromUnaryFilter = function (filter) {\n switch (filter.unaryFilter.op) {\n case 'IS_NAN':\n var nanField = this.fromFieldPathReference(filter.unaryFilter.field);\n return new NanFilter(nanField);\n case 'IS_NULL':\n var nullField = this.fromFieldPathReference(filter.unaryFilter.field);\n return new NullFilter(nullField);\n case 'OPERATOR_UNSPECIFIED':\n return fail('Unspecified filter');\n default:\n return fail('Unknown filter');\n }\n };\n JsonProtoSerializer.prototype.toDocumentMask = function (fieldMask) {\n return {\n fieldPaths: fieldMask.fields.map(function (field) { return field.canonicalString(); })\n };\n };\n JsonProtoSerializer.prototype.fromDocumentMask = function (proto) {\n var paths = proto.fieldPaths || [];\n var fields = paths.map(function (path) { return path_FieldPath.fromServerFormat(path); });\n return new mutation_FieldMask(fields);\n };\n return JsonProtoSerializer;\n}());\n\n/**\n * Checks for a specific oneof tag in a protocol buffer message.\n *\n * This intentionally accommodates two distinct cases:\n *\n * 1) Messages containing a type tag: these are the format produced by GRPC in\n * return values. These may contain default-value mappings for all tags in the\n * oneof but the type tag specifies which one was actually set.\n *\n * 2) Messages that don't contain a type tag: these are the format required by\n * GRPC as inputs. If we emitted objects with type tags, ProtoBuf.js would\n * choke claiming that the tags aren't fields in the Message.\n *\n * Allowing both formats here makes the serializer able to consume the outputs\n * it produces: for all messages it supports, fromX(toX(value)) == value.\n *\n * Note that case 2 suffers from ambiguity: if multiple tags are present\n * without a type tag then the callers are structured in such a way that the\n * first invocation will win. Since we only parse in this mode when parsing\n * the output of a serialize method this works, but it's not a general\n * solution.\n *\n * Unfortunately there is no general solution here because proto3 makes it\n * impossible to distinguish unset from explicitly set fields: both have the\n * default value for the type. Without the type tag but multiple value tags\n * it's possible to have default values for each tag in the oneof and not be\n * able to know which was actually in effect.\n */\nfunction hasTag(obj, type, tag) {\n return type === tag || (!type && tag in obj);\n}\n\n//# sourceMappingURL=serializer.js.map\n\n// EXTERNAL MODULE: ../webchannel-wrapper/dist/index.js\nvar dist = __webpack_require__(115);\nvar dist_default = /*#__PURE__*/__webpack_require__.n(dist);\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/remote/stream_bridge.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Provides a simple helper class that implements the Stream interface to\n * bridge to other implementations that are streams but do not implement the\n * interface. The stream callbacks are invoked with the callOn... methods.\n */\nvar stream_bridge_StreamBridge = /** @class */ (function () {\n function StreamBridge(args) {\n this.sendFn = args.sendFn;\n this.closeFn = args.closeFn;\n }\n StreamBridge.prototype.onOpen = function (callback) {\n assert(!this.wrappedOnOpen, 'Called onOpen on stream twice!');\n this.wrappedOnOpen = callback;\n };\n StreamBridge.prototype.onClose = function (callback) {\n assert(!this.wrappedOnClose, 'Called onClose on stream twice!');\n this.wrappedOnClose = callback;\n };\n StreamBridge.prototype.onMessage = function (callback) {\n assert(!this.wrappedOnMessage, 'Called onMessage on stream twice!');\n this.wrappedOnMessage = callback;\n };\n StreamBridge.prototype.close = function () {\n this.closeFn();\n };\n StreamBridge.prototype.send = function (msg) {\n this.sendFn(msg);\n };\n StreamBridge.prototype.callOnOpen = function () {\n assert(this.wrappedOnOpen !== undefined, 'Cannot call onOpen because no callback was set');\n this.wrappedOnOpen();\n };\n StreamBridge.prototype.callOnClose = function (err) {\n assert(this.wrappedOnClose !== undefined, 'Cannot call onClose because no callback was set');\n this.wrappedOnClose(err);\n };\n StreamBridge.prototype.callOnMessage = function (msg) {\n assert(this.wrappedOnMessage !== undefined, 'Cannot call onMessage because no callback was set');\n this.wrappedOnMessage(msg);\n };\n return StreamBridge;\n}());\n\n\n//# sourceMappingURL=stream_bridge.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/platform_browser/webchannel_connection.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n\n\n\n\nvar LOG_TAG = 'Connection';\nvar RPC_STREAM_SERVICE = 'google.firestore.v1beta1.Firestore';\nvar RPC_URL_VERSION = 'v1beta1';\n/** Maps RPC names to the corresponding REST endpoint name. */\nvar RPC_NAME_REST_MAPPING = {\n BatchGetDocuments: 'batchGet',\n Commit: 'commit'\n};\n// TODO(b/38203344): The SDK_VERSION is set independently from Firebase because\n// we are doing out-of-band releases. Once we release as part of Firebase, we\n// should use the Firebase version instead.\nvar X_GOOG_API_CLIENT_VALUE = 'gl-js/ fire/' + SDK_VERSION;\nvar XHR_TIMEOUT_SECS = 15;\nvar webchannel_connection_WebChannelConnection = /** @class */ (function () {\n function WebChannelConnection(info) {\n this.databaseId = info.databaseId;\n this.pool = new dist[\"XhrIoPool\"]();\n var proto = info.ssl ? 'https' : 'http';\n this.baseUrl = proto + '://' + info.host;\n }\n /**\n * Modifies the headers for a request, adding any authorization token if\n * present and any additional headers for the request.\n */\n WebChannelConnection.prototype.modifyHeadersForRequest = function (headers, token) {\n if (token) {\n for (var header in token.authHeaders) {\n if (token.authHeaders.hasOwnProperty(header)) {\n headers[header] = token.authHeaders[header];\n }\n }\n }\n headers['X-Goog-Api-Client'] = X_GOOG_API_CLIENT_VALUE;\n // This header is used to improve routing and project isolation by the\n // backend.\n headers['google-cloud-resource-prefix'] =\n \"projects/\" + this.databaseId.projectId + \"/\" +\n (\"databases/\" + this.databaseId.database);\n };\n WebChannelConnection.prototype.invokeRPC = function (rpcName, request, token) {\n var _this = this;\n var url = this.makeUrl(rpcName);\n return new Promise(function (resolve, reject) {\n // tslint:disable-next-line:no-any XhrIoPool doesn't have TS typings.\n _this.pool.getObject(function (xhr) {\n xhr.listenOnce(dist[\"EventType\"].COMPLETE, function () {\n try {\n switch (xhr.getLastErrorCode()) {\n case dist[\"ErrorCode\"].NO_ERROR:\n var json = xhr.getResponseJson();\n debug(LOG_TAG, 'XHR received:', JSON.stringify(json));\n resolve(json);\n break;\n case dist[\"ErrorCode\"].TIMEOUT:\n debug(LOG_TAG, 'RPC \"' + rpcName + '\" timed out');\n reject(new FirestoreError(Code.DEADLINE_EXCEEDED, 'Request time out'));\n break;\n case dist[\"ErrorCode\"].HTTP_ERROR:\n var status_1 = xhr.getStatus();\n debug(LOG_TAG, 'RPC \"' + rpcName + '\" failed with status:', status_1, 'response text:', xhr.getResponseText());\n if (status_1 > 0) {\n reject(new FirestoreError(mapCodeFromHttpStatus(status_1), 'Server responded with status ' + xhr.getStatusText()));\n }\n else {\n // If we received an HTTP_ERROR but there's no status code,\n // it's most probably a connection issue\n debug(LOG_TAG, 'RPC \"' + rpcName + '\" failed');\n reject(new FirestoreError(Code.UNAVAILABLE, 'Connection failed.'));\n }\n break;\n default:\n fail('RPC \"' +\n rpcName +\n '\" failed with unanticipated ' +\n 'webchannel error ' +\n xhr.getLastErrorCode() +\n ': ' +\n xhr.getLastError() +\n ', giving up.');\n }\n }\n finally {\n debug(LOG_TAG, 'RPC \"' + rpcName + '\" completed.');\n _this.pool.releaseObject(xhr);\n }\n });\n var requestString = JSON.stringify(request);\n debug(LOG_TAG, 'XHR sending: ', url + ' ' + requestString);\n // Content-Type: text/plain will avoid preflight requests which might\n // mess with CORS and redirects by proxies. If we add custom headers\n // we will need to change this code to potentially use the\n // $httpOverwrite parameter supported by ESF to avoid\n // triggering preflight requests.\n var headers = { 'Content-Type': 'text/plain' };\n _this.modifyHeadersForRequest(headers, token);\n xhr.send(url, 'POST', requestString, headers, XHR_TIMEOUT_SECS);\n });\n });\n };\n WebChannelConnection.prototype.invokeStreamingRPC = function (rpcName, request, token) {\n // The REST API automatically aggregates all of the streamed results, so we\n // can just use the normal invoke() method.\n return this.invokeRPC(rpcName, request, token);\n };\n WebChannelConnection.prototype.openStream = function (rpcName, token) {\n var urlParts = [\n this.baseUrl,\n '/',\n RPC_STREAM_SERVICE,\n '/',\n rpcName,\n '/channel'\n ];\n var webchannelTransport = Object(dist[\"createWebChannelTransport\"])();\n var request = {\n // Background channel test avoids the initial two test calls and decreases\n // initial cold start time.\n // TODO(dimond): wenboz@ mentioned this might affect use with proxies and\n // we should monitor closely for any reports.\n backgroundChannelTest: true,\n // Required for backend stickiness, routing behavior is based on this\n // parameter.\n httpSessionIdParam: 'gsessionid',\n initMessageHeaders: {},\n // Send our custom headers as a '$httpHeaders=' url param to avoid CORS\n // preflight round-trip. This is formally defined here:\n // https://github.com/google/closure-library/blob/b0e1815b13fb92a46d7c9b3c30de5d6a396a3245/closure/goog/net/rpc/httpcors.js#L40\n httpHeadersOverwriteParam: '$httpHeaders',\n sendRawJson: true,\n supportsCrossDomainXhr: true\n };\n this.modifyHeadersForRequest(request.initMessageHeaders, token);\n var url = urlParts.join('');\n debug(LOG_TAG, 'Creating WebChannel: ' + url + ' ' + request);\n // tslint:disable-next-line:no-any Because listen isn't defined on it.\n var channel = webchannelTransport.createWebChannel(url, request);\n // WebChannel supports sending the first message with the handshake - saving\n // a network round trip. However, it will have to call send in the same\n // JS event loop as open. In order to enforce this, we delay actually\n // opening the WebChannel until send is called. Whether we have called\n // open is tracked with this variable.\n var opened = false;\n // A flag to determine whether the stream was closed (by us or through an\n // error/close event) to avoid delivering multiple close events or sending\n // on a closed stream\n var closed = false;\n var streamBridge = new stream_bridge_StreamBridge({\n sendFn: function (msg) {\n if (!closed) {\n if (!opened) {\n debug(LOG_TAG, 'Opening WebChannel transport.');\n channel.open();\n opened = true;\n }\n debug(LOG_TAG, 'WebChannel sending:', msg);\n channel.send(msg);\n }\n else {\n debug(LOG_TAG, 'Not sending because WebChannel is closed:', msg);\n }\n },\n closeFn: function () { return channel.close(); }\n });\n // Closure events are guarded and exceptions are swallowed, so catch any\n // exception and rethrow using a setTimeout so they become visible again.\n // Note that eventually this function could go away if we are confident\n // enough the code is exception free.\n var unguardedEventListen = function (type, fn) {\n // TODO(dimond): closure typing seems broken because WebChannel does\n // not implement goog.events.Listenable\n channel.listen(type, function (param) {\n try {\n fn(param);\n }\n catch (e) {\n setTimeout(function () {\n throw e;\n }, 0);\n }\n });\n };\n unguardedEventListen(dist[\"WebChannel\"].EventType.OPEN, function () {\n if (!closed) {\n debug(LOG_TAG, 'WebChannel transport opened.');\n }\n });\n unguardedEventListen(dist[\"WebChannel\"].EventType.CLOSE, function () {\n if (!closed) {\n closed = true;\n debug(LOG_TAG, 'WebChannel transport closed');\n streamBridge.callOnClose();\n }\n });\n unguardedEventListen(dist[\"WebChannel\"].EventType.ERROR, function (err) {\n if (!closed) {\n closed = true;\n debug(LOG_TAG, 'WebChannel transport errored:', err);\n streamBridge.callOnClose(new FirestoreError(Code.UNAVAILABLE, 'The operation could not be completed'));\n }\n });\n unguardedEventListen(dist[\"WebChannel\"].EventType.MESSAGE, function (msg) {\n if (!closed) {\n var msgData = msg.data[0];\n assert(!!msgData, 'Got a webchannel message without data.');\n // TODO(b/35143891): There is a bug in One Platform that caused errors\n // (and only errors) to be wrapped in an extra array. To be forward\n // compatible with the bug we need to check either condition. The latter\n // can be removed once the fix has been rolled out.\n var error = \n // tslint:disable-next-line:no-any msgData.error is not typed.\n msgData.error || (msgData[0] && msgData[0].error);\n if (error) {\n debug(LOG_TAG, 'WebChannel received error:', error);\n // error.status will be a string like 'OK' or 'NOT_FOUND'.\n var status_2 = error.status;\n var code = mapCodeFromRpcStatus(status_2);\n var message = error.message;\n if (code === undefined) {\n code = Code.INTERNAL;\n message =\n 'Unknown error status: ' +\n status_2 +\n ' with message ' +\n error.message;\n }\n // Mark closed so no further events are propagated\n closed = true;\n streamBridge.callOnClose(new FirestoreError(code, message));\n channel.close();\n }\n else {\n debug(LOG_TAG, 'WebChannel received:', msgData);\n streamBridge.callOnMessage(msgData);\n }\n }\n });\n setTimeout(function () {\n // Technically we could/should wait for the WebChannel opened event,\n // but because we want to send the first message with the WebChannel\n // handshake we pretend the channel opened here (asynchronously), and\n // then delay the actual open until the first message is sent.\n streamBridge.callOnOpen();\n }, 0);\n return streamBridge;\n };\n // visible for testing\n WebChannelConnection.prototype.makeUrl = function (rpcName) {\n var urlRpcName = RPC_NAME_REST_MAPPING[rpcName];\n assert(urlRpcName !== undefined, 'Unknown REST mapping for: ' + rpcName);\n var url = [this.baseUrl, '/', RPC_URL_VERSION];\n url.push('/projects/');\n url.push(this.databaseId.projectId);\n url.push('/databases/');\n url.push(this.databaseId.database);\n url.push('/documents');\n url.push(':');\n url.push(urlRpcName);\n return url.join('');\n };\n return WebChannelConnection;\n}());\n\n\n//# sourceMappingURL=webchannel_connection.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/platform_browser/browser_platform.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\nvar browser_platform_BrowserPlatform = /** @class */ (function () {\n function BrowserPlatform() {\n this.emptyByteString = '';\n this.base64Available = typeof atob !== 'undefined';\n }\n BrowserPlatform.prototype.loadConnection = function (databaseInfo) {\n return Promise.resolve(new webchannel_connection_WebChannelConnection(databaseInfo));\n };\n BrowserPlatform.prototype.newSerializer = function (databaseId) {\n return new serializer_JsonProtoSerializer(databaseId, { useProto3Json: true });\n };\n BrowserPlatform.prototype.formatJSON = function (value) {\n return JSON.stringify(value);\n };\n BrowserPlatform.prototype.atob = function (encoded) {\n return atob(encoded);\n };\n BrowserPlatform.prototype.btoa = function (raw) {\n return btoa(raw);\n };\n return BrowserPlatform;\n}());\n\n\n//# sourceMappingURL=browser_platform.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/platform_browser/browser_init.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n/**\n * This code needs to run before Firestore is used. This can be achieved in\n * several ways:\n * 1) Through the JSCompiler compiling this code and then (automatically)\n * executing it before exporting the Firestore symbols.\n * 2) Through importing this module first in a Firestore main module\n */\nplatform_PlatformSupport.setPlatform(new browser_platform_BrowserPlatform());\n\n//# sourceMappingURL=browser_init.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/api/field_path.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n// The objects that are a part of this API are exposed to third-parties as\n// compiled javascript so we want to flag our private members with a leading\n// underscore to discourage their use.\n// tslint:disable:strip-private-property-underscore\n/**\n * A FieldPath refers to a field in a document. The path may consist of a single\n * field name (referring to a top-level field in the document), or a list of\n * field names (referring to a nested field in the document).\n */\nvar field_path_FieldPath = /** @class */ (function () {\n /**\n * Creates a FieldPath from the provided field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n *\n * @param fieldNames A list of field names.\n */\n function FieldPath() {\n var fieldNames = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n fieldNames[_i] = arguments[_i];\n }\n validateNamedArrayAtLeastNumberOfElements('FieldPath', fieldNames, 'fieldNames', 1);\n for (var i = 0; i < fieldNames.length; ++i) {\n validateArgType('FieldPath', 'string', i, fieldNames[i]);\n if (fieldNames[i].length === 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field name at argument $(i + 1). \" +\n 'Field names must not be empty.');\n }\n }\n this._internalPath = new path_FieldPath(fieldNames);\n }\n FieldPath.documentId = function () {\n return FieldPath._DOCUMENT_ID;\n };\n FieldPath.prototype.isEqual = function (other) {\n if (!(other instanceof FieldPath)) {\n throw invalidClassError('isEqual', 'FieldPath', 1, other);\n }\n return this._internalPath.isEqual(other._internalPath);\n };\n /**\n * Internal Note: The backend doesn't technically support querying by\n * document ID. Instead it queries by the entire document name (full path\n * included), but in the cases we currently support documentId(), the net\n * effect is the same.\n */\n FieldPath._DOCUMENT_ID = new FieldPath(path_FieldPath.keyField().canonicalString());\n return FieldPath;\n}());\n\n/**\n * Matches any characters in a field path string that are reserved.\n */\nvar RESERVED = new RegExp('[~\\\\*/\\\\[\\\\]]');\n/**\n * Parses a field path string into a FieldPath, treating dots as separators.\n */\nfunction fromDotSeparatedString(path) {\n var found = path.search(RESERVED);\n if (found >= 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field path (\" + path + \"). Paths must not contain \" +\n \"'~', '*', '/', '[', or ']'\");\n }\n try {\n return new (field_path_FieldPath.bind.apply(field_path_FieldPath, [void 0].concat(path.split('.'))))();\n }\n catch (e) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field path (\" + path + \"). Paths must not be empty, \" +\n \"begin with '.', end with '.', or contain '..'\");\n }\n}\n\n//# sourceMappingURL=field_path.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/types.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Describes the online state of the Firestore client. Note that this does not\n * indicate whether or not the remote store is trying to connect or not. This is\n * primarily used by the View / EventManager code to change their behavior while\n * offline (e.g. get() calls shouldn't wait for data from the server and\n * snapshot events should set metadata.isFromCache=true).\n */\nvar OnlineState;\n(function (OnlineState) {\n /**\n * The Firestore client is in an unknown online state. This means the client\n * is either not actively trying to establish a connection or it is currently\n * trying to establish a connection, but it has not succeeded or failed yet.\n * Higher-level components should not operate in offline mode.\n */\n OnlineState[OnlineState[\"Unknown\"] = 0] = \"Unknown\";\n /**\n * The client is connected and the connections are healthy. This state is\n * reached after a successful connection and there has been at least one\n * successful message received from the backends.\n */\n OnlineState[OnlineState[\"Healthy\"] = 1] = \"Healthy\";\n /**\n * The client is either trying to establish a connection but failing, or it\n * has been explicitly marked offline via a call to disableNetwork().\n * Higher-level components should operate in offline mode.\n */\n OnlineState[OnlineState[\"Failed\"] = 2] = \"Failed\";\n})(OnlineState || (OnlineState = {}));\n\n//# sourceMappingURL=types.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/view_snapshot.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\nvar ChangeType;\n(function (ChangeType) {\n ChangeType[ChangeType[\"Added\"] = 0] = \"Added\";\n ChangeType[ChangeType[\"Removed\"] = 1] = \"Removed\";\n ChangeType[ChangeType[\"Modified\"] = 2] = \"Modified\";\n ChangeType[ChangeType[\"Metadata\"] = 3] = \"Metadata\";\n})(ChangeType || (ChangeType = {}));\nvar SyncState;\n(function (SyncState) {\n SyncState[SyncState[\"Local\"] = 0] = \"Local\";\n SyncState[SyncState[\"Synced\"] = 1] = \"Synced\";\n})(SyncState || (SyncState = {}));\n/**\n * DocumentChangeSet keeps track of a set of changes to docs in a query, merging\n * duplicate events for the same doc.\n */\nvar view_snapshot_DocumentChangeSet = /** @class */ (function () {\n function DocumentChangeSet() {\n this.changeMap = new sorted_map_SortedMap(document_key_DocumentKey.comparator);\n }\n DocumentChangeSet.prototype.track = function (change) {\n var key = change.doc.key;\n var oldChange = this.changeMap.get(key);\n if (!oldChange) {\n this.changeMap = this.changeMap.insert(key, change);\n return;\n }\n // Merge the new change with the existing change.\n if (change.type !== ChangeType.Added &&\n oldChange.type === ChangeType.Metadata) {\n this.changeMap = this.changeMap.insert(key, change);\n }\n else if (change.type === ChangeType.Metadata &&\n oldChange.type !== ChangeType.Removed) {\n this.changeMap = this.changeMap.insert(key, {\n type: oldChange.type,\n doc: change.doc\n });\n }\n else if (change.type === ChangeType.Modified &&\n oldChange.type === ChangeType.Modified) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Modified,\n doc: change.doc\n });\n }\n else if (change.type === ChangeType.Modified &&\n oldChange.type === ChangeType.Added) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Added,\n doc: change.doc\n });\n }\n else if (change.type === ChangeType.Removed &&\n oldChange.type === ChangeType.Added) {\n this.changeMap = this.changeMap.remove(key);\n }\n else if (change.type === ChangeType.Removed &&\n oldChange.type === ChangeType.Modified) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Removed,\n doc: oldChange.doc\n });\n }\n else if (change.type === ChangeType.Added &&\n oldChange.type === ChangeType.Removed) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Modified,\n doc: change.doc\n });\n }\n else {\n // This includes these cases, which don't make sense:\n // Added->Added\n // Removed->Removed\n // Modified->Added\n // Removed->Modified\n // Metadata->Added\n // Removed->Metadata\n fail('unsupported combination of changes: ' +\n JSON.stringify(change) +\n ' after ' +\n JSON.stringify(oldChange));\n }\n };\n DocumentChangeSet.prototype.getChanges = function () {\n var changes = [];\n this.changeMap.inorderTraversal(function (key, change) {\n changes.push(change);\n });\n return changes;\n };\n return DocumentChangeSet;\n}());\n\nvar ViewSnapshot = /** @class */ (function () {\n function ViewSnapshot(query, docs, oldDocs, docChanges, fromCache, hasPendingWrites, syncStateChanged) {\n this.query = query;\n this.docs = docs;\n this.oldDocs = oldDocs;\n this.docChanges = docChanges;\n this.fromCache = fromCache;\n this.hasPendingWrites = hasPendingWrites;\n this.syncStateChanged = syncStateChanged;\n }\n ViewSnapshot.prototype.isEqual = function (other) {\n if (this.fromCache !== other.fromCache ||\n this.hasPendingWrites !== other.hasPendingWrites ||\n this.syncStateChanged !== other.syncStateChanged ||\n !this.query.isEqual(other.query) ||\n !this.docs.isEqual(other.docs) ||\n !this.oldDocs.isEqual(other.oldDocs)) {\n return false;\n }\n var changes = this.docChanges;\n var otherChanges = other.docChanges;\n if (changes.length !== otherChanges.length) {\n return false;\n }\n for (var i = 0; i < changes.length; i++) {\n if (changes[i].type !== otherChanges[i].type ||\n !changes[i].doc.isEqual(otherChanges[i].doc)) {\n return false;\n }\n }\n return true;\n };\n return ViewSnapshot;\n}());\n\n\n//# sourceMappingURL=view_snapshot.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/model/document_set.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n\n/**\n * DocumentSet is an immutable (copy-on-write) collection that holds documents\n * in order specified by the provided comparator. We always add a document key\n * comparator on top of what is provided to guarantee document equality based on\n * the key.\n */\nvar document_set_DocumentSet = /** @class */ (function () {\n /** The default ordering is by key if the comparator is omitted */\n function DocumentSet(comp) {\n // We are adding document key comparator to the end as it's the only\n // guaranteed unique property of a document.\n if (comp) {\n this.comparator = function (d1, d2) {\n return comp(d1, d2) || document_key_DocumentKey.comparator(d1.key, d2.key);\n };\n }\n else {\n this.comparator = function (d1, d2) {\n return document_key_DocumentKey.comparator(d1.key, d2.key);\n };\n }\n this.keyedMap = documentMap();\n this.sortedSet = new sorted_map_SortedMap(this.comparator);\n }\n /**\n * Returns an empty copy of the existing DocumentSet, using the same\n * comparator.\n */\n DocumentSet.emptySet = function (oldSet) {\n return new DocumentSet(oldSet.comparator);\n };\n DocumentSet.prototype.has = function (key) {\n return this.keyedMap.get(key) != null;\n };\n DocumentSet.prototype.get = function (key) {\n return this.keyedMap.get(key);\n };\n DocumentSet.prototype.first = function () {\n return this.sortedSet.minKey();\n };\n DocumentSet.prototype.last = function () {\n return this.sortedSet.maxKey();\n };\n DocumentSet.prototype.isEmpty = function () {\n return this.sortedSet.isEmpty();\n };\n /**\n * Returns previous document or null if it's a first doc.\n *\n * @param key A key that MUST be present in the DocumentSet.\n */\n DocumentSet.prototype.prevDoc = function (key) {\n assert(this.has(key), 'Trying to get a previous document to non-existing key: ' + key);\n var doc = this.keyedMap.get(key);\n return this.sortedSet.getPredecessorKey(doc);\n };\n /**\n * Returns the index of the provided key in the document set, or -1 if the\n * document key is not present in the set;\n */\n DocumentSet.prototype.indexOf = function (key) {\n var doc = this.keyedMap.get(key);\n return doc ? this.sortedSet.indexOf(doc) : -1;\n };\n Object.defineProperty(DocumentSet.prototype, \"size\", {\n get: function () {\n return this.sortedSet.size;\n },\n enumerable: true,\n configurable: true\n });\n /** Iterates documents in order defined by \"comparator\" */\n DocumentSet.prototype.forEach = function (cb) {\n this.sortedSet.inorderTraversal(function (k, v) {\n cb(k);\n return false;\n });\n };\n /** Inserts or updates a document with the same key */\n DocumentSet.prototype.add = function (doc) {\n // First remove the element if we have it.\n var set = this.delete(doc.key);\n return set.copy(set.keyedMap.insert(doc.key, doc), set.sortedSet.insert(doc, null));\n };\n /** Deletes a document with a given key */\n DocumentSet.prototype.delete = function (key) {\n var doc = this.get(key);\n if (!doc) {\n return this;\n }\n return this.copy(this.keyedMap.remove(key), this.sortedSet.remove(doc));\n };\n DocumentSet.prototype.isEqual = function (other) {\n if (!(other instanceof DocumentSet))\n return false;\n if (this.size !== other.size)\n return false;\n var thisIt = this.sortedSet.getIterator();\n var otherIt = other.sortedSet.getIterator();\n while (thisIt.hasNext()) {\n var thisDoc = thisIt.getNext().key;\n var otherDoc = otherIt.getNext().key;\n if (!thisDoc.isEqual(otherDoc))\n return false;\n }\n return true;\n };\n DocumentSet.prototype.toString = function () {\n var docStrings = [];\n this.forEach(function (doc) {\n docStrings.push(doc.toString());\n });\n if (docStrings.length === 0) {\n return 'DocumentSet ()';\n }\n else {\n return 'DocumentSet (\\n ' + docStrings.join(' \\n') + '\\n)';\n }\n };\n DocumentSet.prototype.copy = function (keyedMap, sortedSet) {\n var newSet = new DocumentSet();\n newSet.comparator = this.comparator;\n newSet.keyedMap = keyedMap;\n newSet.sortedSet = sortedSet;\n return newSet;\n };\n return DocumentSet;\n}());\n\n\n//# sourceMappingURL=document_set.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/obj_map.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * A map implementation that uses objects as keys. Objects must implement the\n * Equatable interface and must be immutable. Entries in the map are stored\n * together with the key being produced from the mapKeyFn. This map\n * automatically handles collisions of keys.\n */\nvar obj_map_ObjectMap = /** @class */ (function () {\n function ObjectMap(mapKeyFn) {\n this.mapKeyFn = mapKeyFn;\n /**\n * The inner map for a key -> value pair. Due to the possibility of\n * collisions we keep a list of entries that we do a linear search through\n * to find an actual match. Note that collisions should be rare, so we still\n * expect near constant time lookups in practice.\n */\n this.inner = {};\n }\n /** Get a value for this key, or undefined if it does not exist. */\n ObjectMap.prototype.get = function (key) {\n var id = this.mapKeyFn(key);\n var matches = this.inner[id];\n if (matches === undefined) {\n return undefined;\n }\n for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) {\n var _a = matches_1[_i], otherKey = _a[0], value = _a[1];\n if (otherKey.isEqual(key)) {\n return value;\n }\n }\n return undefined;\n };\n ObjectMap.prototype.has = function (key) {\n return this.get(key) !== undefined;\n };\n /** Put this key and value in the map. */\n ObjectMap.prototype.set = function (key, value) {\n var id = this.mapKeyFn(key);\n var matches = this.inner[id];\n if (matches === undefined) {\n this.inner[id] = [[key, value]];\n return;\n }\n for (var i = 0; i < matches.length; i++) {\n if (matches[i][0].isEqual(key)) {\n matches[i] = [key, value];\n return;\n }\n }\n matches.push([key, value]);\n };\n /**\n * Remove this key from the map. Returns a boolean if anything was deleted.\n */\n ObjectMap.prototype.delete = function (key) {\n var id = this.mapKeyFn(key);\n var matches = this.inner[id];\n if (matches === undefined) {\n return false;\n }\n for (var i = 0; i < matches.length; i++) {\n if (matches[i][0].isEqual(key)) {\n if (matches.length === 1) {\n delete this.inner[id];\n }\n else {\n matches.splice(i, 1);\n }\n return true;\n }\n }\n return false;\n };\n ObjectMap.prototype.forEach = function (fn) {\n forEach(this.inner, function (_, entries) {\n for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {\n var _a = entries_1[_i], k = _a[0], v = _a[1];\n fn(k, v);\n }\n });\n };\n ObjectMap.prototype.isEmpty = function () {\n return isEmpty(this.inner);\n };\n return ObjectMap;\n}());\n\n\n//# sourceMappingURL=obj_map.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/event_manager.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n\n\n/**\n * Holds the listeners and the last received ViewSnapshot for a query being\n * tracked by EventManager.\n */\nvar QueryListenersInfo = /** @class */ (function () {\n function QueryListenersInfo() {\n this.listeners = [];\n }\n return QueryListenersInfo;\n}());\n/**\n * EventManager is responsible for mapping queries to query event emitters.\n * It handles \"fan-out\". -- Identical queries will re-use the same watch on the\n * backend.\n */\nvar event_manager_EventManager = /** @class */ (function () {\n function EventManager(syncEngine) {\n this.syncEngine = syncEngine;\n this.queries = new obj_map_ObjectMap(function (q) {\n return q.canonicalId();\n });\n this.onlineState = OnlineState.Unknown;\n this.syncEngine.subscribe(this.onChange.bind(this), this.onError.bind(this));\n }\n EventManager.prototype.listen = function (listener) {\n var query = listener.query;\n var firstListen = false;\n var queryInfo = this.queries.get(query);\n if (!queryInfo) {\n firstListen = true;\n queryInfo = new QueryListenersInfo();\n this.queries.set(query, queryInfo);\n }\n queryInfo.listeners.push(listener);\n listener.applyOnlineStateChange(this.onlineState);\n if (queryInfo.viewSnap)\n listener.onViewSnapshot(queryInfo.viewSnap);\n if (firstListen) {\n return this.syncEngine.listen(query).then(function (targetId) {\n queryInfo.targetId = targetId;\n return targetId;\n });\n }\n else {\n return Promise.resolve(queryInfo.targetId);\n }\n };\n EventManager.prototype.unlisten = function (listener) {\n var query = listener.query;\n var lastListen = false;\n var queryInfo = this.queries.get(query);\n if (queryInfo) {\n var i = queryInfo.listeners.indexOf(listener);\n if (i >= 0) {\n queryInfo.listeners.splice(i, 1);\n lastListen = queryInfo.listeners.length === 0;\n }\n }\n if (lastListen) {\n this.queries.delete(query);\n return this.syncEngine.unlisten(query);\n }\n else {\n return Promise.resolve();\n }\n };\n EventManager.prototype.onChange = function (viewSnaps) {\n for (var _i = 0, viewSnaps_1 = viewSnaps; _i < viewSnaps_1.length; _i++) {\n var viewSnap = viewSnaps_1[_i];\n var query = viewSnap.query;\n var queryInfo = this.queries.get(query);\n if (queryInfo) {\n for (var _a = 0, _b = queryInfo.listeners; _a < _b.length; _a++) {\n var listener = _b[_a];\n listener.onViewSnapshot(viewSnap);\n }\n queryInfo.viewSnap = viewSnap;\n }\n }\n };\n EventManager.prototype.onError = function (query, error) {\n var queryInfo = this.queries.get(query);\n if (queryInfo) {\n for (var _i = 0, _a = queryInfo.listeners; _i < _a.length; _i++) {\n var listener = _a[_i];\n listener.onError(error);\n }\n }\n // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()\n // after an error.\n this.queries.delete(query);\n };\n EventManager.prototype.applyOnlineStateChange = function (onlineState) {\n this.onlineState = onlineState;\n this.queries.forEach(function (_, queryInfo) {\n for (var _i = 0, _a = queryInfo.listeners; _i < _a.length; _i++) {\n var listener = _a[_i];\n listener.applyOnlineStateChange(onlineState);\n }\n });\n };\n return EventManager;\n}());\n\n/**\n * QueryListener takes a series of internal view snapshots and determines\n * when to raise the event.\n *\n * It uses an Observer to dispatch events.\n */\nvar event_manager_QueryListener = /** @class */ (function () {\n function QueryListener(query, queryObserver, options) {\n this.query = query;\n this.queryObserver = queryObserver;\n /**\n * Initial snapshots (e.g. from cache) may not be propagated to the wrapped\n * observer. This flag is set to true once we've actually raised an event.\n */\n this.raisedInitialEvent = false;\n this.onlineState = OnlineState.Unknown;\n this.options = options || {};\n }\n QueryListener.prototype.onViewSnapshot = function (snap) {\n assert(snap.docChanges.length > 0 || snap.syncStateChanged, 'We got a new snapshot with no changes?');\n if (!this.options.includeDocumentMetadataChanges) {\n // Remove the metadata only changes.\n var docChanges = [];\n for (var _i = 0, _a = snap.docChanges; _i < _a.length; _i++) {\n var docChange = _a[_i];\n if (docChange.type !== ChangeType.Metadata) {\n docChanges.push(docChange);\n }\n }\n snap = new ViewSnapshot(snap.query, snap.docs, snap.oldDocs, docChanges, snap.fromCache, snap.hasPendingWrites, snap.syncStateChanged);\n }\n if (!this.raisedInitialEvent) {\n if (this.shouldRaiseInitialEvent(snap, this.onlineState)) {\n this.raiseInitialEvent(snap);\n }\n }\n else if (this.shouldRaiseEvent(snap)) {\n this.queryObserver.next(snap);\n }\n this.snap = snap;\n };\n QueryListener.prototype.onError = function (error) {\n this.queryObserver.error(error);\n };\n QueryListener.prototype.applyOnlineStateChange = function (onlineState) {\n this.onlineState = onlineState;\n if (this.snap &&\n !this.raisedInitialEvent &&\n this.shouldRaiseInitialEvent(this.snap, onlineState)) {\n this.raiseInitialEvent(this.snap);\n }\n };\n QueryListener.prototype.shouldRaiseInitialEvent = function (snap, onlineState) {\n assert(!this.raisedInitialEvent, 'Determining whether to raise first event but already had first event');\n // Always raise the first event when we're synced\n if (!snap.fromCache) {\n return true;\n }\n // NOTE: We consider OnlineState.Unknown as online (it should become Failed\n // or Online if we wait long enough).\n var maybeOnline = onlineState !== OnlineState.Failed;\n // Don't raise the event if we're online, aren't synced yet (checked\n // above) and are waiting for a sync.\n if (this.options.waitForSyncWhenOnline && maybeOnline) {\n assert(snap.fromCache, 'Waiting for sync, but snapshot is not from cache');\n return false;\n }\n // Raise data from cache if we have any documents or we are offline\n return !snap.docs.isEmpty() || onlineState === OnlineState.Failed;\n };\n QueryListener.prototype.shouldRaiseEvent = function (snap) {\n // We don't need to handle includeDocumentMetadataChanges here because\n // the Metadata only changes have already been stripped out if needed.\n // At this point the only changes we will see are the ones we should\n // propagate.\n if (snap.docChanges.length > 0) {\n return true;\n }\n var hasPendingWritesChanged = this.snap && this.snap.hasPendingWrites !== snap.hasPendingWrites;\n if (snap.syncStateChanged || hasPendingWritesChanged) {\n return this.options.includeQueryMetadataChanges === true;\n }\n // Generally we should have hit one of the cases above, but it's possible\n // to get here if there were only metadata docChanges and they got\n // stripped out.\n return false;\n };\n QueryListener.prototype.raiseInitialEvent = function (snap) {\n assert(!this.raisedInitialEvent, 'Trying to raise initial events for second time');\n snap = new ViewSnapshot(snap.query, snap.docs, document_set_DocumentSet.emptySet(snap.docs), QueryListener.getInitialViewChanges(snap), snap.fromCache, snap.hasPendingWrites, true);\n this.raisedInitialEvent = true;\n this.queryObserver.next(snap);\n };\n /** Returns changes as if all documents in the snap were added. */\n QueryListener.getInitialViewChanges = function (snap) {\n var result = [];\n snap.docs.forEach(function (doc) {\n result.push({ type: ChangeType.Added, doc: doc });\n });\n return result;\n };\n return QueryListener;\n}());\n\n\n//# sourceMappingURL=event_manager.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/persistence_promise.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * PersistencePromise<> is essentially a re-implementation of Promise<> except\n * it has a .next() method instead of .then() and .next() and .catch() callbacks\n * are executed synchronously when a PersistencePromise resolves rather than\n * asynchronously (Promise<> implementations use setImmediate() or similar).\n *\n * This is necessary to interoperate with IndexedDB which will automatically\n * commit transactions if control is returned to the event loop without\n * synchronously initiating another operation on the transaction.\n *\n * NOTE: .then() and .catch() only allow a single consumer, unlike normal\n * Promises.\n */\nvar persistence_promise_PersistencePromise = /** @class */ (function () {\n function PersistencePromise(callback) {\n var _this = this;\n // NOTE: next/catchCallback will always point to our own wrapper functions,\n // not the user's raw next() or catch() callbacks.\n // tslint:disable-next-line:no-any Accept any result type for the next call in the Promise chain.\n this.nextCallback = null;\n // tslint:disable-next-line:no-any Accept any result type for the error handler.\n this.catchCallback = null;\n // When the operation resolves, we'll set result or error and mark isDone.\n this.result = undefined;\n this.error = undefined;\n this.isDone = false;\n // Set to true when .then() or .catch() are called and prevents additional\n // chaining.\n this.callbackAttached = false;\n callback(function (value) {\n _this.isDone = true;\n _this.result = value;\n if (_this.nextCallback) {\n // value should be defined unless T is Void, but we can't express\n // that in the type system.\n _this.nextCallback(value);\n }\n }, function (error) {\n _this.isDone = true;\n _this.error = error;\n if (_this.catchCallback) {\n _this.catchCallback(error);\n }\n });\n }\n PersistencePromise.prototype.catch = function (fn) {\n return this.next(undefined, fn);\n };\n PersistencePromise.prototype.next = function (nextFn, catchFn) {\n var _this = this;\n if (this.callbackAttached) {\n fail('Called next() or catch() twice for PersistencePromise');\n }\n this.callbackAttached = true;\n if (this.isDone) {\n if (!this.error) {\n return this.wrapSuccess(nextFn, this.result);\n }\n else {\n return this.wrapFailure(catchFn, this.error);\n }\n }\n else {\n return new PersistencePromise(function (resolve, reject) {\n _this.nextCallback = function (value) {\n _this.wrapSuccess(nextFn, value).next(resolve, reject);\n };\n _this.catchCallback = function (error) {\n _this.wrapFailure(catchFn, error).next(resolve, reject);\n };\n });\n }\n };\n PersistencePromise.prototype.toPromise = function () {\n var _this = this;\n return new Promise(function (resolve, reject) {\n _this.next(resolve, reject);\n });\n };\n PersistencePromise.prototype.wrapUserFunction = function (fn) {\n try {\n var result = fn();\n if (result instanceof PersistencePromise) {\n return result;\n }\n else {\n return PersistencePromise.resolve(result);\n }\n }\n catch (e) {\n return PersistencePromise.reject(e);\n }\n };\n PersistencePromise.prototype.wrapSuccess = function (nextFn, value) {\n if (nextFn) {\n return this.wrapUserFunction(function () { return nextFn(value); });\n }\n else {\n // If there's no nextFn, then R must be the same as T but we\n // can't express that in the type system.\n // tslint:disable-next-line:no-any\n return PersistencePromise.resolve(value);\n }\n };\n PersistencePromise.prototype.wrapFailure = function (catchFn, error) {\n if (catchFn) {\n return this.wrapUserFunction(function () { return catchFn(error); });\n }\n else {\n return PersistencePromise.reject(error);\n }\n };\n PersistencePromise.resolve = function (result) {\n return new PersistencePromise(function (resolve, reject) {\n resolve(result);\n });\n };\n PersistencePromise.reject = function (error) {\n return new PersistencePromise(function (resolve, reject) {\n reject(error);\n });\n };\n PersistencePromise.waitFor = function (\n // tslint:disable-next-line:no-any Accept all Promise types in waitFor().\n all) {\n return all.reduce(function (promise, nextPromise, idx) {\n return promise.next(function () {\n return nextPromise;\n });\n }, PersistencePromise.resolve());\n };\n PersistencePromise.map = function (all) {\n var results = [];\n var first = true;\n // initial is ignored, so we can cheat on the type.\n // tslint:disable-next-line:no-any\n var initial = PersistencePromise.resolve(null);\n return all\n .reduce(function (promise, nextPromise) {\n return promise.next(function (result) {\n if (!first) {\n results.push(result);\n }\n first = false;\n return nextPromise;\n });\n }, initial)\n .next(function (result) {\n results.push(result);\n return results;\n });\n };\n return PersistencePromise;\n}());\n\n\n//# sourceMappingURL=persistence_promise.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/eager_garbage_collector.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n/**\n * A garbage collector implementation that eagerly collects documents as soon as\n * they're no longer referenced in any of its registered GarbageSources.\n *\n * This implementation keeps track of a set of keys that are potentially garbage\n * without keeping an exact reference count. During collectGarbage, the\n * collector verifies that all potential garbage keys actually have no\n * references by consulting its list of garbage sources.\n */\nvar eager_garbage_collector_EagerGarbageCollector = /** @class */ (function () {\n function EagerGarbageCollector() {\n this.isEager = true;\n /**\n * The garbage collectible sources to double-check during garbage collection.\n */\n this.sources = [];\n /**\n * A set of potentially garbage keys.\n * PORTING NOTE: This would be a mutable set if Javascript had one.\n */\n this.potentialGarbage = documentKeySet();\n }\n EagerGarbageCollector.prototype.addGarbageSource = function (garbageSource) {\n this.sources.push(garbageSource);\n garbageSource.setGarbageCollector(this);\n };\n EagerGarbageCollector.prototype.removeGarbageSource = function (garbageSource) {\n this.sources.splice(this.sources.indexOf(garbageSource), 1);\n garbageSource.setGarbageCollector(null);\n };\n EagerGarbageCollector.prototype.addPotentialGarbageKey = function (key) {\n this.potentialGarbage = this.potentialGarbage.add(key);\n };\n EagerGarbageCollector.prototype.collectGarbage = function (txn) {\n var _this = this;\n var promises = [];\n var garbageKeys = documentKeySet();\n this.potentialGarbage.forEach(function (key) {\n var hasRefsPromise = _this.documentHasAnyReferences(txn, key);\n promises.push(hasRefsPromise.next(function (hasRefs) {\n // If there are no references, get the key.\n if (!hasRefs) {\n garbageKeys = garbageKeys.add(key);\n }\n return persistence_promise_PersistencePromise.resolve();\n }));\n });\n // Clear locally retained potential keys and returned confirmed garbage.\n this.potentialGarbage = documentKeySet();\n return persistence_promise_PersistencePromise.waitFor(promises).next(function () { return garbageKeys; });\n };\n EagerGarbageCollector.prototype.documentHasAnyReferences = function (txn, key) {\n var initial = persistence_promise_PersistencePromise.resolve(false);\n return this.sources\n .map(function (source) { return function () { return source.containsKey(txn, key); }; })\n .reduce(function (promise, nextPromise) {\n return promise.next(function (result) {\n if (result) {\n return persistence_promise_PersistencePromise.resolve(true);\n }\n else {\n return nextPromise();\n }\n });\n }, initial);\n };\n return EagerGarbageCollector;\n}());\n\n\n//# sourceMappingURL=eager_garbage_collector.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/local_view_changes.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n/**\n * A set of changes to what documents are currently in view and out of view for\n * a given query. These changes are sent to the LocalStore by the View (via\n * the SyncEngine) and are used to pin / unpin documents as appropriate.\n */\nvar local_view_changes_LocalViewChanges = /** @class */ (function () {\n function LocalViewChanges(query, addedKeys, removedKeys) {\n this.query = query;\n this.addedKeys = addedKeys;\n this.removedKeys = removedKeys;\n }\n LocalViewChanges.fromSnapshot = function (viewSnapshot) {\n var addedKeys = documentKeySet();\n var removedKeys = documentKeySet();\n for (var _i = 0, _a = viewSnapshot.docChanges; _i < _a.length; _i++) {\n var docChange = _a[_i];\n switch (docChange.type) {\n case ChangeType.Added:\n addedKeys = addedKeys.add(docChange.doc.key);\n break;\n case ChangeType.Removed:\n removedKeys = removedKeys.add(docChange.doc.key);\n break;\n default:\n }\n }\n return new LocalViewChanges(viewSnapshot.query, addedKeys, removedKeys);\n };\n return LocalViewChanges;\n}());\n\n\n//# sourceMappingURL=local_view_changes.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/reference_set.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n\n\n/**\n * A collection of references to a document from some kind of numbered entity\n * (either a target ID or batch ID). As references are added to or removed from\n * the set corresponding events are emitted to a registered garbage collector.\n *\n * Each reference is represented by a DocumentReference object. Each of them\n * contains enough information to uniquely identify the reference. They are all\n * stored primarily in a set sorted by key. A document is considered garbage if\n * there's no references in that set (this can be efficiently checked thanks to\n * sorting by key).\n *\n * ReferenceSet also keeps a secondary set that contains references sorted by\n * IDs. This one is used to efficiently implement removal of all references by\n * some target ID.\n */\nvar reference_set_ReferenceSet = /** @class */ (function () {\n function ReferenceSet() {\n // A set of outstanding references to a document sorted by key.\n this.refsByKey = new sorted_set_SortedSet(reference_set_DocReference.compareByKey);\n // A set of outstanding references to a document sorted by target id.\n this.refsByTarget = new sorted_set_SortedSet(reference_set_DocReference.compareByTargetId);\n /** Keeps track of keys that have references */\n this.garbageCollector = null;\n }\n /** Returns true if the reference set contains no references. */\n ReferenceSet.prototype.isEmpty = function () {\n return this.refsByKey.isEmpty();\n };\n /** Adds a reference to the given document key for the given ID. */\n ReferenceSet.prototype.addReference = function (key, id) {\n var ref = new reference_set_DocReference(key, id);\n this.refsByKey = this.refsByKey.add(ref);\n this.refsByTarget = this.refsByTarget.add(ref);\n };\n /** Add references to the given document keys for the given ID. */\n ReferenceSet.prototype.addReferences = function (keys, id) {\n var _this = this;\n keys.forEach(function (key) { return _this.addReference(key, id); });\n };\n /**\n * Removes a reference to the given document key for the given\n * ID.\n */\n ReferenceSet.prototype.removeReference = function (key, id) {\n this.removeRef(new reference_set_DocReference(key, id));\n };\n ReferenceSet.prototype.removeReferences = function (keys, id) {\n var _this = this;\n keys.forEach(function (key) { return _this.removeReference(key, id); });\n };\n /**\n * Clears all references with a given ID. Calls removeRef() for each key\n * removed.\n */\n ReferenceSet.prototype.removeReferencesForId = function (id) {\n var _this = this;\n var emptyKey = document_key_DocumentKey.EMPTY;\n var startRef = new reference_set_DocReference(emptyKey, id);\n var endRef = new reference_set_DocReference(emptyKey, id + 1);\n this.refsByTarget.forEachInRange([startRef, endRef], function (ref) {\n _this.removeRef(ref);\n });\n };\n ReferenceSet.prototype.removeAllReferences = function () {\n var _this = this;\n this.refsByKey.forEach(function (ref) { return _this.removeRef(ref); });\n };\n ReferenceSet.prototype.removeRef = function (ref) {\n this.refsByKey = this.refsByKey.delete(ref);\n this.refsByTarget = this.refsByTarget.delete(ref);\n if (this.garbageCollector !== null) {\n this.garbageCollector.addPotentialGarbageKey(ref.key);\n }\n };\n ReferenceSet.prototype.referencesForId = function (id) {\n var emptyKey = document_key_DocumentKey.EMPTY;\n var startRef = new reference_set_DocReference(emptyKey, id);\n var endRef = new reference_set_DocReference(emptyKey, id + 1);\n var keys = documentKeySet();\n this.refsByTarget.forEachInRange([startRef, endRef], function (ref) {\n keys = keys.add(ref.key);\n });\n return keys;\n };\n ReferenceSet.prototype.setGarbageCollector = function (garbageCollector) {\n this.garbageCollector = garbageCollector;\n };\n ReferenceSet.prototype.containsKey = function (txn, key) {\n var ref = new reference_set_DocReference(key, 0);\n var firstRef = this.refsByKey.firstAfterOrEqual(ref);\n return persistence_promise_PersistencePromise.resolve(firstRef !== null && key.isEqual(firstRef.key));\n };\n return ReferenceSet;\n}());\n\nvar reference_set_DocReference = /** @class */ (function () {\n function DocReference(key, targetOrBatchId) {\n this.key = key;\n this.targetOrBatchId = targetOrBatchId;\n }\n /** Compare by key then by ID */\n DocReference.compareByKey = function (left, right) {\n return (document_key_DocumentKey.comparator(left.key, right.key) ||\n primitiveComparator(left.targetOrBatchId, right.targetOrBatchId));\n };\n /** Compare by ID then by key */\n DocReference.compareByTargetId = function (left, right) {\n return (primitiveComparator(left.targetOrBatchId, right.targetOrBatchId) ||\n document_key_DocumentKey.comparator(left.key, right.key));\n };\n return DocReference;\n}());\n\n\n//# sourceMappingURL=reference_set.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/target_id_generator.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar RESERVED_BITS = 1;\nvar GeneratorIds;\n(function (GeneratorIds) {\n GeneratorIds[GeneratorIds[\"LocalStore\"] = 0] = \"LocalStore\";\n GeneratorIds[GeneratorIds[\"SyncEngine\"] = 1] = \"SyncEngine\";\n})(GeneratorIds || (GeneratorIds = {}));\n/**\n * TargetIdGenerator generates monotonically increasing integer IDs. There are\n * separate generators for different scopes. While these generators will operate\n * independently of each other, they are scoped, such that no two generators\n * will ever produce the same ID. This is useful, because sometimes the backend\n * may group IDs from separate parts of the client into the same ID space.\n */\nvar TargetIdGenerator = /** @class */ (function () {\n function TargetIdGenerator(generatorId, initAfter) {\n if (initAfter === void 0) { initAfter = 0; }\n this.generatorId = generatorId;\n // Replace the generator part of initAfter with this generator's ID.\n var afterWithoutGenerator = (initAfter >> RESERVED_BITS) << RESERVED_BITS;\n var afterGenerator = initAfter - afterWithoutGenerator;\n if (afterGenerator >= generatorId) {\n // For example, if:\n // this.generatorId = 0b0000\n // after = 0b1011\n // afterGenerator = 0b0001\n // Then:\n // previous = 0b1010\n // next = 0b1100\n this.previousId = afterWithoutGenerator | this.generatorId;\n }\n else {\n // For example, if:\n // this.generatorId = 0b0001\n // after = 0b1010\n // afterGenerator = 0b0000\n // Then:\n // previous = 0b1001\n // next = 0b1011\n this.previousId =\n (afterWithoutGenerator | this.generatorId) - (1 << RESERVED_BITS);\n }\n }\n TargetIdGenerator.prototype.next = function () {\n this.previousId += 1 << RESERVED_BITS;\n return this.previousId;\n };\n TargetIdGenerator.forLocalStore = function (initAfter) {\n if (initAfter === void 0) { initAfter = 0; }\n return new TargetIdGenerator(GeneratorIds.LocalStore, initAfter);\n };\n TargetIdGenerator.forSyncEngine = function () {\n return new TargetIdGenerator(GeneratorIds.SyncEngine);\n };\n return TargetIdGenerator;\n}());\n\n\n//# sourceMappingURL=target_id_generator.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/view.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n\n\n\n\nvar AddedLimboDocument = /** @class */ (function () {\n function AddedLimboDocument(key) {\n this.key = key;\n }\n return AddedLimboDocument;\n}());\n\nvar RemovedLimboDocument = /** @class */ (function () {\n function RemovedLimboDocument(key) {\n this.key = key;\n }\n return RemovedLimboDocument;\n}());\n\n/**\n * View is responsible for computing the final merged truth of what docs are in\n * a query. It gets notified of local and remote changes to docs, and applies\n * the query filters and limits to determine the most correct possible results.\n */\nvar view_View = /** @class */ (function () {\n function View(query, \n /** Documents included in the remote target */\n syncedDocuments) {\n this.query = query;\n this.syncedDocuments = syncedDocuments;\n this.syncState = null;\n /**\n * A flag whether the view is current with the backend. A view is considered\n * current after it has seen the current flag from the backend and did not\n * lose consistency within the watch stream (e.g. because of an existence\n * filter mismatch).\n */\n this.current = false;\n /** Documents in the view but not in the remote target */\n this.limboDocuments = documentKeySet();\n /** Document Keys that have local changes */\n this.mutatedKeys = documentKeySet();\n this.documentSet = new document_set_DocumentSet(query.docComparator.bind(query));\n }\n /**\n * Iterates over a set of doc changes, applies the query limit, and computes\n * what the new results should be, what the changes were, and whether we may\n * need to go back to the local cache for more results. Does not make any\n * changes to the view.\n * @param docChanges The doc changes to apply to this view.\n * @param previousChanges If this is being called with a refill, then start\n * with this set of docs and changes instead of the current view.\n * @return a new set of docs, changes, and refill flag.\n */\n View.prototype.computeDocChanges = function (docChanges, previousChanges) {\n var _this = this;\n var changeSet = previousChanges\n ? previousChanges.changeSet\n : new view_snapshot_DocumentChangeSet();\n var oldDocumentSet = previousChanges\n ? previousChanges.documentSet\n : this.documentSet;\n var newMutatedKeys = previousChanges\n ? previousChanges.mutatedKeys\n : this.mutatedKeys;\n var newDocumentSet = oldDocumentSet;\n var needsRefill = false;\n // Track the last doc in a (full) limit. This is necessary, because some\n // update (a delete, or an update moving a doc past the old limit) might\n // mean there is some other document in the local cache that either should\n // come (1) between the old last limit doc and the new last document, in the\n // case of updates, or (2) after the new last document, in the case of\n // deletes. So we keep this doc at the old limit to compare the updates to.\n //\n // Note that this should never get used in a refill (when previousChanges is\n // set), because there will only be adds -- no deletes or updates.\n var lastDocInLimit = this.query.hasLimit() && oldDocumentSet.size === this.query.limit\n ? oldDocumentSet.last()\n : null;\n docChanges.inorderTraversal(function (key, newMaybeDoc) {\n var oldDoc = oldDocumentSet.get(key);\n var newDoc = newMaybeDoc instanceof document_Document ? newMaybeDoc : null;\n if (newDoc) {\n assert(key.isEqual(newDoc.key), 'Mismatching keys found in document changes: ' +\n key +\n ' != ' +\n newDoc.key);\n newDoc = _this.query.matches(newDoc) ? newDoc : null;\n }\n if (newDoc) {\n newDocumentSet = newDocumentSet.add(newDoc);\n if (newDoc.hasLocalMutations) {\n newMutatedKeys = newMutatedKeys.add(key);\n }\n else {\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n }\n else {\n newDocumentSet = newDocumentSet.delete(key);\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n // Calculate change\n if (oldDoc && newDoc) {\n var docsEqual = oldDoc.data.isEqual(newDoc.data);\n if (!docsEqual ||\n oldDoc.hasLocalMutations !== newDoc.hasLocalMutations) {\n // only report a change if document actually changed\n if (docsEqual) {\n changeSet.track({ type: ChangeType.Metadata, doc: newDoc });\n }\n else {\n changeSet.track({ type: ChangeType.Modified, doc: newDoc });\n }\n if (lastDocInLimit &&\n _this.query.docComparator(newDoc, lastDocInLimit) > 0) {\n // This doc moved from inside the limit to after the limit.\n // That means there may be some doc in the local cache that's\n // actually less than this one.\n needsRefill = true;\n }\n }\n }\n else if (!oldDoc && newDoc) {\n changeSet.track({ type: ChangeType.Added, doc: newDoc });\n }\n else if (oldDoc && !newDoc) {\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc });\n if (lastDocInLimit) {\n // A doc was removed from a full limit query. We'll need to\n // requery from the local cache to see if we know about some other\n // doc that should be in the results.\n needsRefill = true;\n }\n }\n });\n if (this.query.hasLimit()) {\n // TODO(klimt): Make DocumentSet size be constant time.\n while (newDocumentSet.size > this.query.limit) {\n var oldDoc = newDocumentSet.last();\n newDocumentSet = newDocumentSet.delete(oldDoc.key);\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc });\n }\n }\n assert(!needsRefill || !previousChanges, 'View was refilled using docs that themselves needed refilling.');\n return {\n documentSet: newDocumentSet,\n changeSet: changeSet,\n needsRefill: needsRefill,\n mutatedKeys: newMutatedKeys\n };\n };\n /**\n * Updates the view with the given ViewDocumentChanges and updates limbo docs\n * and sync state from the given (optional) target change.\n * @param docChanges The set of changes to make to the view's docs.\n * @param targetChange A target change to apply for computing limbo docs and\n * sync state.\n * @return A new ViewChange with the given docs, changes, and sync state.\n */\n View.prototype.applyChanges = function (docChanges, targetChange) {\n var _this = this;\n assert(!docChanges.needsRefill, 'Cannot apply changes that need a refill');\n var oldDocs = this.documentSet;\n this.documentSet = docChanges.documentSet;\n this.mutatedKeys = docChanges.mutatedKeys;\n // Sort changes based on type and query comparator\n var changes = docChanges.changeSet.getChanges();\n changes.sort(function (c1, c2) {\n return (compareChangeType(c1.type, c2.type) ||\n _this.query.docComparator(c1.doc, c2.doc));\n });\n var limboChanges = this.applyTargetChange(targetChange);\n var synced = this.limboDocuments.size === 0 && this.current;\n var newSyncState = synced ? SyncState.Synced : SyncState.Local;\n var syncStateChanged = newSyncState !== this.syncState;\n this.syncState = newSyncState;\n if (changes.length === 0 && !syncStateChanged) {\n // no changes\n return { limboChanges: limboChanges };\n }\n else {\n var snap = new ViewSnapshot(this.query, docChanges.documentSet, oldDocs, changes, newSyncState === SyncState.Local, !docChanges.mutatedKeys.isEmpty(), syncStateChanged);\n return {\n snapshot: snap,\n limboChanges: limboChanges\n };\n }\n };\n /**\n * Applies an OnlineState change to the view, potentially generating a\n * ViewChange if the view's syncState changes as a result.\n */\n View.prototype.applyOnlineStateChange = function (onlineState) {\n if (this.current && onlineState === OnlineState.Failed) {\n // If we're offline, set `current` to false and then call applyChanges()\n // to refresh our syncState and generate a ViewChange as appropriate. We\n // are guaranteed to get a new TargetChange that sets `current` back to\n // true once the client is back online.\n this.current = false;\n return this.applyChanges({\n documentSet: this.documentSet,\n changeSet: new view_snapshot_DocumentChangeSet(),\n mutatedKeys: this.mutatedKeys,\n needsRefill: false\n });\n }\n else {\n // No effect, just return a no-op ViewChange.\n return { limboChanges: [] };\n }\n };\n /**\n * Returns whether the doc for the given key should be in limbo.\n */\n View.prototype.shouldBeInLimbo = function (key) {\n // If the remote end says it's part of this query, it's not in limbo.\n if (this.syncedDocuments.has(key)) {\n return false;\n }\n // The local store doesn't think it's a result, so it shouldn't be in limbo.\n if (!this.documentSet.has(key)) {\n return false;\n }\n // If there are local changes to the doc, they might explain why the server\n // doesn't know that it's part of the query. So don't put it in limbo.\n // TODO(klimt): Ideally, we would only consider changes that might actually\n // affect this specific query.\n if (this.documentSet.get(key).hasLocalMutations) {\n return false;\n }\n // Everything else is in limbo.\n return true;\n };\n /**\n * Updates syncedDocuments, current, and limbo docs based on the given change.\n * Returns the list of changes to which docs are in limbo.\n */\n View.prototype.applyTargetChange = function (targetChange) {\n var _this = this;\n if (targetChange) {\n var targetMapping = targetChange.mapping;\n if (targetMapping instanceof ResetMapping) {\n this.syncedDocuments = targetMapping.documents;\n }\n else if (targetMapping instanceof UpdateMapping) {\n this.syncedDocuments = targetMapping.applyToKeySet(this.syncedDocuments);\n }\n switch (targetChange.currentStatusUpdate) {\n case CurrentStatusUpdate.MarkCurrent:\n this.current = true;\n break;\n case CurrentStatusUpdate.MarkNotCurrent:\n this.current = false;\n break;\n case CurrentStatusUpdate.None:\n break;\n default:\n fail('Unknown current status update: ' + targetChange.currentStatusUpdate);\n }\n }\n // Recompute the set of limbo docs.\n // TODO(klimt): Do this incrementally so that it's not quadratic when\n // updating many documents.\n var oldLimboDocuments = this.limboDocuments;\n this.limboDocuments = documentKeySet();\n if (this.current) {\n this.documentSet.forEach(function (doc) {\n if (_this.shouldBeInLimbo(doc.key)) {\n _this.limboDocuments = _this.limboDocuments.add(doc.key);\n }\n });\n }\n // Diff the new limbo docs with the old limbo docs.\n var changes = [];\n oldLimboDocuments.forEach(function (key) {\n if (!_this.limboDocuments.has(key)) {\n changes.push(new RemovedLimboDocument(key));\n }\n });\n this.limboDocuments.forEach(function (key) {\n if (!oldLimboDocuments.has(key)) {\n changes.push(new AddedLimboDocument(key));\n }\n });\n return changes;\n };\n return View;\n}());\n\nfunction compareChangeType(c1, c2) {\n var order = function (change) {\n switch (change) {\n case ChangeType.Added:\n return 1;\n case ChangeType.Modified:\n return 2;\n case ChangeType.Metadata:\n // A metadata change is converted to a modified change at the public\n // api layer. Since we sort by document key and then change type,\n // metadata and modified changes must be sorted equivalently.\n return 2;\n case ChangeType.Removed:\n return 0;\n default:\n return fail('Unknown ChangeType: ' + change);\n }\n };\n return order(c1) - order(c2);\n}\n\n//# sourceMappingURL=view.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/sync_engine.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nvar sync_engine_LOG_TAG = 'SyncEngine';\n/**\n * QueryView contains all of the data that SyncEngine needs to keep track of for\n * a particular query.\n */\nvar QueryView = /** @class */ (function () {\n function QueryView(\n /**\n * The query itself.\n */\n query, \n /**\n * The target number created by the client that is used in the watch\n * stream to identify this query.\n */\n targetId, \n /**\n * An identifier from the datastore backend that indicates the last state\n * of the results that was received. This can be used to indicate where\n * to continue receiving new doc changes for the query.\n */\n resumeToken, \n /**\n * The view is responsible for computing the final merged truth of what\n * docs are in the query. It gets notified of local and remote changes,\n * and applies the query filters and limits to determine the most correct\n * possible results.\n */\n view) {\n this.query = query;\n this.targetId = targetId;\n this.resumeToken = resumeToken;\n this.view = view;\n }\n return QueryView;\n}());\n/**\n * SyncEngine is the central controller in the client SDK architecture. It is\n * the glue code between the EventManager, LocalStore, and RemoteStore. Some of\n * SyncEngine's responsibilities include:\n * 1. Coordinating client requests and remote events between the EventManager\n * and the local and remote data stores.\n * 2. Managing a View object for each query, providing the unified view between\n * the local and remote data stores.\n * 3. Notifying the RemoteStore when the LocalStore has new mutations in its\n * queue that need sending to the backend.\n *\n * The SyncEngine’s methods should only ever be called by methods running in the\n * global async queue.\n */\nvar sync_engine_SyncEngine = /** @class */ (function () {\n function SyncEngine(localStore, remoteStore, currentUser) {\n this.localStore = localStore;\n this.remoteStore = remoteStore;\n this.currentUser = currentUser;\n this.viewHandler = null;\n this.errorHandler = null;\n this.queryViewsByQuery = new obj_map_ObjectMap(function (q) {\n return q.canonicalId();\n });\n this.queryViewsByTarget = {};\n this.limboTargetsByKey = new sorted_map_SortedMap(document_key_DocumentKey.comparator);\n this.limboKeysByTarget = {};\n this.limboDocumentRefs = new reference_set_ReferenceSet();\n this.limboCollector = new eager_garbage_collector_EagerGarbageCollector();\n /** Stores user completion handlers, indexed by User and BatchId. */\n this.mutationUserCallbacks = {};\n this.targetIdGenerator = TargetIdGenerator.forSyncEngine();\n }\n /** Subscribes view and error handler. Can be called only once. */\n SyncEngine.prototype.subscribe = function (viewHandler, errorHandler) {\n assert(viewHandler !== null && errorHandler !== null, 'View and error handlers cannot be null');\n assert(this.viewHandler === null && this.errorHandler === null, 'SyncEngine already has a subscriber.');\n this.viewHandler = viewHandler;\n this.errorHandler = errorHandler;\n this.limboCollector.addGarbageSource(this.limboDocumentRefs);\n };\n /**\n * Initiates the new listen, resolves promise when listen enqueued to the\n * server. All the subsequent view snapshots or errors are sent to the\n * subscribed handlers. Returns the targetId of the query.\n */\n SyncEngine.prototype.listen = function (query) {\n var _this = this;\n this.assertSubscribed('listen()');\n assert(!this.queryViewsByQuery.has(query), 'We already listen to the query: ' + query);\n return this.localStore.allocateQuery(query).then(function (queryData) {\n return _this.localStore\n .executeQuery(query)\n .then(function (docs) {\n return _this.localStore\n .remoteDocumentKeys(queryData.targetId)\n .then(function (remoteKeys) {\n var view = new view_View(query, remoteKeys);\n var viewDocChanges = view.computeDocChanges(docs);\n var viewChange = view.applyChanges(viewDocChanges);\n assert(viewChange.limboChanges.length === 0, 'View returned limbo docs before target ack from the server.');\n assert(!!viewChange.snapshot, 'applyChanges for new view should always return a snapshot');\n var data = new QueryView(query, queryData.targetId, queryData.resumeToken, view);\n _this.queryViewsByQuery.set(query, data);\n _this.queryViewsByTarget[queryData.targetId] = data;\n _this.viewHandler([viewChange.snapshot]);\n _this.remoteStore.listen(queryData);\n });\n })\n .then(function () {\n return queryData.targetId;\n });\n });\n };\n /** Stops listening to the query. */\n SyncEngine.prototype.unlisten = function (query) {\n var _this = this;\n this.assertSubscribed('unlisten()');\n var queryView = this.queryViewsByQuery.get(query);\n assert(!!queryView, 'Trying to unlisten on query not found:' + query);\n return this.localStore.releaseQuery(query).then(function () {\n _this.remoteStore.unlisten(queryView.targetId);\n return _this.removeAndCleanupQuery(queryView).then(function () {\n return _this.localStore.collectGarbage();\n });\n });\n };\n /**\n * Initiates the write of local mutation batch which involves adding the\n * writes to the mutation queue, notifying the remote store about new\n * mutations and raising events for any changes this write caused.\n *\n * The promise returned by this call is resolved when the above steps\n * have completed, *not* when the write was acked by the backend. The\n * userCallback is resolved once the write was acked/rejected by the\n * backend (or failed locally for any other reason).\n */\n SyncEngine.prototype.write = function (batch, userCallback) {\n var _this = this;\n this.assertSubscribed('write()');\n return this.localStore\n .localWrite(batch)\n .then(function (result) {\n _this.addMutationCallback(result.batchId, userCallback);\n return _this.emitNewSnapsAndNotifyLocalStore(result.changes);\n })\n .then(function () {\n return _this.remoteStore.fillWritePipeline();\n });\n };\n // TODO(klimt): Wrap the given error in a standard Firestore error object.\n SyncEngine.prototype.wrapUpdateFunctionError = function (error) {\n return error;\n };\n /**\n * Takes an updateFunction in which a set of reads and writes can be performed\n * atomically. In the updateFunction, the client can read and write values\n * using the supplied transaction object. After the updateFunction, all\n * changes will be committed. If some other client has changed any of the data\n * referenced, then the updateFunction will be called again. If the\n * updateFunction still fails after the given number of retries, then the\n * transaction will be rejection.\n *\n * The transaction object passed to the updateFunction contains methods for\n * accessing documents and collections. Unlike other datastore access, data\n * accessed with the transaction will not reflect local changes that have not\n * been committed. For this reason, it is required that all reads are\n * performed before any writes. Transactions must be performed while online.\n *\n * The promise returned is resolved when the transaction is fully committed.\n */\n SyncEngine.prototype.runTransaction = function (updateFunction, retries) {\n var _this = this;\n if (retries === void 0) { retries = 5; }\n assert(retries >= 0, 'Got negative number of retries for transaction.');\n var transaction = this.remoteStore.createTransaction();\n var wrappedUpdateFunction = function () {\n try {\n var userPromise = updateFunction(transaction);\n if (isNullOrUndefined(userPromise) ||\n !userPromise.catch ||\n !userPromise.then) {\n return Promise.reject(Error('Transaction callback must return a Promise'));\n }\n return userPromise.catch(function (e) {\n return Promise.reject(_this.wrapUpdateFunctionError(e));\n });\n }\n catch (e) {\n return Promise.reject(_this.wrapUpdateFunctionError(e));\n }\n };\n return wrappedUpdateFunction().then(function (result) {\n return transaction\n .commit()\n .then(function () {\n return result;\n })\n .catch(function (error) {\n if (retries === 0) {\n return Promise.reject(error);\n }\n // TODO(klimt): Put in a retry delay?\n return _this.runTransaction(updateFunction, retries - 1);\n });\n });\n };\n SyncEngine.prototype.applyRemoteEvent = function (remoteEvent) {\n var _this = this;\n this.assertSubscribed('applyRemoteEvent()');\n // Make sure limbo documents are deleted if there were no results\n forEachNumber(remoteEvent.targetChanges, function (targetId, targetChange) {\n var limboKey = _this.limboKeysByTarget[targetId];\n if (limboKey &&\n targetChange.currentStatusUpdate ===\n CurrentStatusUpdate.MarkCurrent &&\n !remoteEvent.documentUpdates.get(limboKey)) {\n // When listening to a query the server responds with a snapshot\n // containing documents matching the query and a current marker\n // telling us we're now in sync. It's possible for these to arrive\n // as separate remote events or as a single remote event.\n // For a document query, there will be no documents sent in the\n // response if the document doesn't exist.\n //\n // If the snapshot arrives separately from the current marker,\n // we handle it normally and updateTrackedLimbos will resolve the\n // limbo status of the document, removing it from limboDocumentRefs.\n // This works because clients only initiate limbo resolution when\n // a target is current and because all current targets are\n // always at a consistent snapshot.\n //\n // However, if the document doesn't exist and the current marker\n // arrives, the document is not present in the snapshot and our\n // normal view handling would consider the document to remain in\n // limbo indefinitely because there are no updates to the document.\n // To avoid this, we specially handle this just this case here:\n // synthesizing a delete.\n //\n // TODO(dimond): Ideally we would have an explicit lookup query\n // instead resulting in an explicit delete message and we could\n // remove this special logic.\n remoteEvent.addDocumentUpdate(new document_NoDocument(limboKey, remoteEvent.snapshotVersion));\n }\n });\n return this.localStore.applyRemoteEvent(remoteEvent).then(function (changes) {\n return _this.emitNewSnapsAndNotifyLocalStore(changes, remoteEvent);\n });\n };\n /**\n * Applies an OnlineState change to the sync engine and notifies any views of\n * the change.\n */\n SyncEngine.prototype.applyOnlineStateChange = function (onlineState) {\n var newViewSnapshots = [];\n this.queryViewsByQuery.forEach(function (query, queryView) {\n var viewChange = queryView.view.applyOnlineStateChange(onlineState);\n assert(viewChange.limboChanges.length === 0, 'OnlineState should not affect limbo documents.');\n if (viewChange.snapshot) {\n newViewSnapshots.push(viewChange.snapshot);\n }\n });\n this.viewHandler(newViewSnapshots);\n };\n SyncEngine.prototype.rejectListen = function (targetId, err) {\n var _this = this;\n this.assertSubscribed('rejectListens()');\n var limboKey = this.limboKeysByTarget[targetId];\n if (limboKey) {\n // Since this query failed, we won't want to manually unlisten to it.\n // So go ahead and remove it from bookkeeping.\n this.limboTargetsByKey = this.limboTargetsByKey.remove(limboKey);\n delete this.limboKeysByTarget[targetId];\n // TODO(klimt): We really only should do the following on permission\n // denied errors, but we don't have the cause code here.\n // It's a limbo doc. Create a synthetic event saying it was deleted.\n // This is kind of a hack. Ideally, we would have a method in the local\n // store to purge a document. However, it would be tricky to keep all of\n // the local store's invariants with another method.\n var docMap = new sorted_map_SortedMap(document_key_DocumentKey.comparator);\n docMap = docMap.insert(limboKey, new document_NoDocument(limboKey, snapshot_version_SnapshotVersion.forDeletedDoc()));\n var event_1 = new remote_event_RemoteEvent(snapshot_version_SnapshotVersion.MIN, {}, docMap);\n return this.applyRemoteEvent(event_1);\n }\n else {\n var queryView_1 = this.queryViewsByTarget[targetId];\n assert(!!queryView_1, 'Unknown targetId: ' + targetId);\n return this.localStore.releaseQuery(queryView_1.query).then(function () {\n return _this.removeAndCleanupQuery(queryView_1).then(function () {\n _this.errorHandler(queryView_1.query, err);\n });\n });\n }\n };\n SyncEngine.prototype.applySuccessfulWrite = function (mutationBatchResult) {\n var _this = this;\n this.assertSubscribed('applySuccessfulWrite()');\n // The local store may or may not be able to apply the write result and\n // raise events immediately (depending on whether the watcher is caught\n // up), so we raise user callbacks first so that they consistently happen\n // before listen events.\n this.processUserCallback(mutationBatchResult.batch.batchId, \n /*error=*/ null);\n return this.localStore\n .acknowledgeBatch(mutationBatchResult)\n .then(function (changes) {\n return _this.emitNewSnapsAndNotifyLocalStore(changes);\n });\n };\n SyncEngine.prototype.rejectFailedWrite = function (batchId, error) {\n var _this = this;\n this.assertSubscribed('rejectFailedWrite()');\n // The local store may or may not be able to apply the write result and\n // raise events immediately (depending on whether the watcher is caught up),\n // so we raise user callbacks first so that they consistently happen before\n // listen events.\n this.processUserCallback(batchId, error);\n return this.localStore.rejectBatch(batchId).then(function (changes) {\n return _this.emitNewSnapsAndNotifyLocalStore(changes);\n });\n };\n SyncEngine.prototype.addMutationCallback = function (batchId, callback) {\n var newCallbacks = this.mutationUserCallbacks[this.currentUser.toKey()];\n if (!newCallbacks) {\n newCallbacks = new sorted_map_SortedMap(primitiveComparator);\n }\n newCallbacks = newCallbacks.insert(batchId, callback);\n this.mutationUserCallbacks[this.currentUser.toKey()] = newCallbacks;\n };\n /**\n * Resolves or rejects the user callback for the given batch and then discards\n * it.\n */\n SyncEngine.prototype.processUserCallback = function (batchId, error) {\n var newCallbacks = this.mutationUserCallbacks[this.currentUser.toKey()];\n // NOTE: Mutations restored from persistence won't have callbacks, so it's\n // okay for there to be no callback for this ID.\n if (newCallbacks) {\n var callback = newCallbacks.get(batchId);\n if (callback) {\n assert(batchId === newCallbacks.minKey(), 'Mutation callbacks processed out-of-order?');\n if (error) {\n callback.reject(error);\n }\n else {\n callback.resolve();\n }\n newCallbacks = newCallbacks.remove(batchId);\n }\n this.mutationUserCallbacks[this.currentUser.toKey()] = newCallbacks;\n }\n };\n SyncEngine.prototype.removeAndCleanupQuery = function (queryView) {\n this.queryViewsByQuery.delete(queryView.query);\n delete this.queryViewsByTarget[queryView.targetId];\n this.limboDocumentRefs.removeReferencesForId(queryView.targetId);\n return this.gcLimboDocuments();\n };\n SyncEngine.prototype.updateTrackedLimbos = function (targetId, limboChanges) {\n for (var _i = 0, limboChanges_1 = limboChanges; _i < limboChanges_1.length; _i++) {\n var limboChange = limboChanges_1[_i];\n if (limboChange instanceof AddedLimboDocument) {\n this.limboDocumentRefs.addReference(limboChange.key, targetId);\n this.trackLimboChange(limboChange);\n }\n else if (limboChange instanceof RemovedLimboDocument) {\n debug(sync_engine_LOG_TAG, 'Document no longer in limbo: ' + limboChange.key);\n this.limboDocumentRefs.removeReference(limboChange.key, targetId);\n }\n else {\n fail('Unknown limbo change: ' + JSON.stringify(limboChange));\n }\n }\n return this.gcLimboDocuments();\n };\n SyncEngine.prototype.trackLimboChange = function (limboChange) {\n var key = limboChange.key;\n if (!this.limboTargetsByKey.get(key)) {\n debug(sync_engine_LOG_TAG, 'New document in limbo: ' + key);\n var limboTargetId = this.targetIdGenerator.next();\n var query = query_Query.atPath(key.path);\n this.limboKeysByTarget[limboTargetId] = key;\n this.remoteStore.listen(new query_data_QueryData(query, limboTargetId, QueryPurpose.Listen));\n this.limboTargetsByKey = this.limboTargetsByKey.insert(key, limboTargetId);\n }\n };\n SyncEngine.prototype.gcLimboDocuments = function () {\n var _this = this;\n // HACK: We can use a null transaction here, because we know that the\n // reference set is entirely within memory and doesn't need a store engine.\n return this.limboCollector\n .collectGarbage(null)\n .next(function (keys) {\n keys.forEach(function (key) {\n var limboTargetId = _this.limboTargetsByKey.get(key);\n if (limboTargetId === null) {\n // This target already got removed, because the query failed.\n return;\n }\n _this.remoteStore.unlisten(limboTargetId);\n _this.limboTargetsByKey = _this.limboTargetsByKey.remove(key);\n delete _this.limboKeysByTarget[limboTargetId];\n });\n })\n .toPromise();\n };\n // Visible for testing\n SyncEngine.prototype.currentLimboDocs = function () {\n return this.limboTargetsByKey;\n };\n SyncEngine.prototype.emitNewSnapsAndNotifyLocalStore = function (changes, remoteEvent) {\n var _this = this;\n var newSnaps = [];\n var docChangesInAllViews = [];\n var queriesProcessed = [];\n this.queryViewsByQuery.forEach(function (_, queryView) {\n queriesProcessed.push(Promise.resolve()\n .then(function () {\n var viewDocChanges = queryView.view.computeDocChanges(changes);\n if (!viewDocChanges.needsRefill) {\n return viewDocChanges;\n }\n // The query has a limit and some docs were removed, so we need\n // to re-run the query against the local store to make sure we\n // didn't lose any good docs that had been past the limit.\n return _this.localStore.executeQuery(queryView.query).then(function (docs) {\n return queryView.view.computeDocChanges(docs, viewDocChanges);\n });\n })\n .then(function (viewDocChanges) {\n var targetChange = remoteEvent && remoteEvent.targetChanges[queryView.targetId];\n var viewChange = queryView.view.applyChanges(viewDocChanges, targetChange);\n return _this.updateTrackedLimbos(queryView.targetId, viewChange.limboChanges).then(function () {\n if (viewChange.snapshot) {\n newSnaps.push(viewChange.snapshot);\n var docChanges = local_view_changes_LocalViewChanges.fromSnapshot(viewChange.snapshot);\n docChangesInAllViews.push(docChanges);\n }\n });\n }));\n });\n return Promise.all(queriesProcessed)\n .then(function () {\n _this.viewHandler(newSnaps);\n return _this.localStore.notifyLocalViewChanges(docChangesInAllViews);\n })\n .then(function () {\n return _this.localStore.collectGarbage();\n });\n };\n SyncEngine.prototype.assertSubscribed = function (fnName) {\n assert(this.viewHandler !== null && this.errorHandler !== null, 'Trying to call ' + fnName + ' before calling subscribe().');\n };\n SyncEngine.prototype.handleUserChange = function (user) {\n var _this = this;\n this.currentUser = user;\n return this.localStore\n .handleUserChange(user)\n .then(function (changes) {\n return _this.emitNewSnapsAndNotifyLocalStore(changes);\n })\n .then(function () {\n return _this.remoteStore.handleUserChange(user);\n });\n };\n return SyncEngine;\n}());\n\n\n//# sourceMappingURL=sync_engine.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/model/mutation_batch.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\nvar BATCHID_UNKNOWN = -1;\n/**\n * A batch of mutations that will be sent as one unit to the backend.\n */\nvar mutation_batch_MutationBatch = /** @class */ (function () {\n function MutationBatch(batchId, localWriteTime, mutations) {\n this.batchId = batchId;\n this.localWriteTime = localWriteTime;\n this.mutations = mutations;\n }\n /**\n * Applies all the mutations in this MutationBatch to the specified document\n * to create a new remote document\n *\n * @param docKey The key of the document to apply mutations to.\n * @param maybeDoc The document to apply mutations to.\n * @param batchResult The result of applying the MutationBatch to the\n * backend.\n */\n MutationBatch.prototype.applyToRemoteDocument = function (docKey, maybeDoc, batchResult) {\n if (maybeDoc) {\n assert(maybeDoc.key.isEqual(docKey), \"applyToRemoteDocument: key \" + docKey + \" should match maybeDoc key\\n \" + maybeDoc.key);\n }\n var mutationResults = batchResult.mutationResults;\n assert(mutationResults.length === this.mutations.length, \"Mismatch between mutations length\\n (\" + this.mutations.length + \") and mutation results length\\n (\" + mutationResults.length + \").\");\n for (var i = 0; i < this.mutations.length; i++) {\n var mutation = this.mutations[i];\n if (mutation.key.isEqual(docKey)) {\n var mutationResult = mutationResults[i];\n maybeDoc = mutation.applyToRemoteDocument(maybeDoc, mutationResult);\n }\n }\n return maybeDoc;\n };\n /**\n * Computes the local view of a document given all the mutations in this\n * batch.\n *\n * @param docKey The key of the document to apply mutations to.\n * @param maybeDoc The document to apply mutations to.\n */\n MutationBatch.prototype.applyToLocalView = function (docKey, maybeDoc) {\n if (maybeDoc) {\n assert(maybeDoc.key.isEqual(docKey), \"applyToLocalDocument: key \" + docKey + \" should match maybeDoc key\\n \" + maybeDoc.key);\n }\n var baseDoc = maybeDoc;\n for (var i = 0; i < this.mutations.length; i++) {\n var mutation = this.mutations[i];\n if (mutation.key.isEqual(docKey)) {\n maybeDoc = mutation.applyToLocalView(maybeDoc, baseDoc, this.localWriteTime);\n }\n }\n return maybeDoc;\n };\n MutationBatch.prototype.keys = function () {\n var keySet = documentKeySet();\n for (var _i = 0, _a = this.mutations; _i < _a.length; _i++) {\n var mutation = _a[_i];\n keySet = keySet.add(mutation.key);\n }\n return keySet;\n };\n MutationBatch.prototype.isEqual = function (other) {\n return (this.batchId === other.batchId &&\n arrayEquals(this.mutations, other.mutations));\n };\n /**\n * Returns true if this mutation batch has already been removed from the\n * mutation queue.\n *\n * Note that not all implementations of the MutationQueue necessarily use\n * tombstones as part of their implementation and generally speaking no code\n * outside the mutation queues should really care about this.\n */\n MutationBatch.prototype.isTombstone = function () {\n return this.mutations.length === 0;\n };\n /** Converts this batch into a tombstone */\n MutationBatch.prototype.toTombstone = function () {\n return new MutationBatch(this.batchId, this.localWriteTime, []);\n };\n return MutationBatch;\n}());\n\n/** The result of applying a mutation batch to the backend. */\nvar mutation_batch_MutationBatchResult = /** @class */ (function () {\n function MutationBatchResult(batch, commitVersion, mutationResults, streamToken, \n /**\n * A pre-computed mapping from each mutated document to the resulting\n * version.\n */\n docVersions) {\n this.batch = batch;\n this.commitVersion = commitVersion;\n this.mutationResults = mutationResults;\n this.streamToken = streamToken;\n this.docVersions = docVersions;\n }\n /**\n * Creates a new MutationBatchResult for the given batch and results. There\n * must be one result for each mutation in the batch. This static factory\n * caches a document=>version mapping (docVersions).\n */\n MutationBatchResult.from = function (batch, commitVersion, results, streamToken) {\n assert(batch.mutations.length === results.length, 'Mutations sent ' +\n batch.mutations.length +\n ' must equal results received ' +\n results.length);\n var versionMap = documentVersionMap();\n var mutations = batch.mutations;\n for (var i = 0; i < mutations.length; i++) {\n var version = results[i].version;\n if (version === null) {\n // deletes don't have a version, so we substitute the commitVersion\n // of the entire batch.\n version = commitVersion;\n }\n versionMap = versionMap.insert(mutations[i].key, version);\n }\n return new MutationBatchResult(batch, commitVersion, results, streamToken, versionMap);\n };\n return MutationBatchResult;\n}());\n\n\n//# sourceMappingURL=mutation_batch.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/encoded_resource_path.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\nvar escapeChar = '\\u0001';\nvar encodedSeparatorChar = '\\u0001';\nvar encodedNul = '\\u0010';\nvar encodedEscape = '\\u0011';\n/**\n * Encodes a resource path into a IndexedDb-compatible string form.\n */\nfunction encode(path) {\n var result = '';\n for (var i = 0; i < path.length; i++) {\n if (result.length > 0) {\n result = encodeSeparator(result);\n }\n result = encodeSegment(path.get(i), result);\n }\n return encodeSeparator(result);\n}\n/** Encodes a single segment of a resource path into the given result */\nfunction encodeSegment(segment, resultBuf) {\n var result = resultBuf;\n var length = segment.length;\n for (var i = 0; i < length; i++) {\n var c = segment.charAt(i);\n switch (c) {\n case '\\0':\n result += escapeChar + encodedNul;\n break;\n case escapeChar:\n result += escapeChar + encodedEscape;\n break;\n default:\n result += c;\n }\n }\n return result;\n}\n/** Encodes a path separator into the given result */\nfunction encodeSeparator(result) {\n return result + escapeChar + encodedSeparatorChar;\n}\n/**\n * Decodes the given IndexedDb-compatible string form of a resource path into\n * a ResourcePath instance. Note that this method is not suitable for use with\n * decoding resource names from the server; those are One Platform format\n * strings.\n */\nfunction decode(path) {\n // Event the empty path must encode as a path of at least length 2. A path\n // with exactly 2 must be the empty path.\n var length = path.length;\n assert(length >= 2, 'Invalid path ' + path);\n if (length === 2) {\n assert(path.charAt(0) === escapeChar && path.charAt(1) === encodedSeparatorChar, 'Non-empty path ' + path + ' had length 2');\n return path_ResourcePath.EMPTY_PATH;\n }\n // Escape characters cannot exist past the second-to-last position in the\n // source value.\n var lastReasonableEscapeIndex = length - 2;\n var segments = [];\n var segmentBuilder = '';\n for (var start = 0; start < length;) {\n // The last two characters of a valid encoded path must be a separator, so\n // there must be an end to this segment.\n var end = path.indexOf(escapeChar, start);\n if (end < 0 || end > lastReasonableEscapeIndex) {\n fail('Invalid encoded resource path: \"' + path + '\"');\n }\n var next = path.charAt(end + 1);\n switch (next) {\n case encodedSeparatorChar:\n var currentPiece = path.substring(start, end);\n var segment = void 0;\n if (segmentBuilder.length === 0) {\n // Avoid copying for the common case of a segment that excludes \\0\n // and \\001\n segment = currentPiece;\n }\n else {\n segmentBuilder += currentPiece;\n segment = segmentBuilder;\n segmentBuilder = '';\n }\n segments.push(segment);\n break;\n case encodedNul:\n segmentBuilder += path.substring(start, end);\n segmentBuilder += '\\0';\n break;\n case encodedEscape:\n // The escape character can be used in the output to encode itself.\n segmentBuilder += path.substring(start, end + 1);\n break;\n default:\n fail('Invalid encoded resource path: \"' + path + '\"');\n }\n start = end + 2;\n }\n return new path_ResourcePath(segments);\n}\n/**\n * Computes the prefix successor of the given path, computed by encode above.\n * A prefix successor is the first key that cannot be prefixed by the given\n * path. It's useful for defining the end of a prefix scan such that all keys\n * in the scan have the same prefix.\n *\n * Note that this is not a general prefix successor implementation, which is\n * tricky to get right with Strings, given that they encode down to UTF-8.\n * Instead this relies on the fact that all paths encoded by this class are\n * always terminated with a separator, and so a successor can always be\n * cheaply computed by incrementing the last character of the path.\n */\nfunction prefixSuccessor(path) {\n var c = path.charCodeAt(path.length - 1);\n // TODO(mcg): this really should be a general thing, but not worth it right\n // now\n assert(c === 1, 'successor may only operate on paths generated by encode');\n return path.substring(0, path.length - 1) + String.fromCharCode(c + 1);\n}\n\n//# sourceMappingURL=encoded_resource_path.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/indexeddb_schema.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\nvar SCHEMA_VERSION = 1;\n/** Performs database creation and (in the future) upgrades between versions. */\nfunction createOrUpgradeDb(db, oldVersion) {\n assert(oldVersion === 0, 'Unexpected upgrade from version ' + oldVersion);\n db.createObjectStore(DbMutationQueue.store, {\n keyPath: DbMutationQueue.keyPath\n });\n // TODO(mikelehen): Get rid of \"as any\" if/when TypeScript fixes their\n // types. https://github.com/Microsoft/TypeScript/issues/14322\n db.createObjectStore(DbMutationBatch.store, \n // tslint:disable-next-line:no-any\n { keyPath: DbMutationBatch.keyPath });\n var targetDocumentsStore = db.createObjectStore(DbTargetDocument.store, \n // tslint:disable-next-line:no-any\n { keyPath: DbTargetDocument.keyPath });\n targetDocumentsStore.createIndex(DbTargetDocument.documentTargetsIndex, DbTargetDocument.documentTargetsKeyPath, { unique: true });\n var targetStore = db.createObjectStore(DbTarget.store, {\n keyPath: DbTarget.keyPath\n });\n // NOTE: This is unique only because the TargetId is the suffix.\n targetStore.createIndex(DbTarget.queryTargetsIndexName, DbTarget.queryTargetsKeyPath, { unique: true });\n // NOTE: keys for these stores are specified explicitly rather than using a\n // keyPath.\n db.createObjectStore(indexeddb_schema_DbDocumentMutation.store);\n db.createObjectStore(DbRemoteDocument.store);\n db.createObjectStore(DbOwner.store);\n db.createObjectStore(DbTargetGlobal.store);\n}\n/**\n * Wrapper class to store timestamps (seconds and nanos) in IndexedDb objects.\n */\nvar DbTimestamp = /** @class */ (function () {\n function DbTimestamp(seconds, nanos) {\n this.seconds = seconds;\n this.nanos = nanos;\n }\n return DbTimestamp;\n}());\n\n/**\n * A singleton object to be stored in the 'owner' store in IndexedDb.\n *\n * A given database can be owned by a single tab at a given time. That tab\n * must validate that it is still the owner before every write operation and\n * should regularly write an updated timestamp to prevent other tabs from\n * \"stealing\" ownership of the db.\n */\nvar DbOwner = /** @class */ (function () {\n function DbOwner(ownerId, leaseTimestampMs) {\n this.ownerId = ownerId;\n this.leaseTimestampMs = leaseTimestampMs;\n }\n /** Name of the IndexedDb object store. */\n DbOwner.store = 'owner';\n return DbOwner;\n}());\n\n/**\n * An object to be stored in the 'mutationQueues' store in IndexedDb.\n *\n * Each user gets a single queue of MutationBatches to apply to the server.\n * DbMutationQueue tracks the metadata about the queue.\n */\nvar DbMutationQueue = /** @class */ (function () {\n function DbMutationQueue(\n /**\n * The normalized user ID to which this queue belongs.\n */\n userId, \n /**\n * An identifier for the highest numbered batch that has been acknowledged\n * by the server. All MutationBatches in this queue with batchIds less\n * than or equal to this value are considered to have been acknowledged by\n * the server.\n */\n lastAcknowledgedBatchId, \n /**\n * A stream token that was previously sent by the server.\n *\n * See StreamingWriteRequest in datastore.proto for more details about\n * usage.\n *\n * After sending this token, earlier tokens may not be used anymore so\n * only a single stream token is retained.\n */\n lastStreamToken) {\n this.userId = userId;\n this.lastAcknowledgedBatchId = lastAcknowledgedBatchId;\n this.lastStreamToken = lastStreamToken;\n }\n /** Name of the IndexedDb object store. */\n DbMutationQueue.store = 'mutationQueues';\n /** Keys are automatically assigned via the userId property. */\n DbMutationQueue.keyPath = 'userId';\n return DbMutationQueue;\n}());\n\n/**\n * An object to be stored in the 'mutations' store in IndexedDb.\n *\n * Represents a batch of user-level mutations intended to be sent to the server\n * in a single write. Each user-level batch gets a separate DbMutationBatch\n * with a new batchId.\n */\nvar DbMutationBatch = /** @class */ (function () {\n function DbMutationBatch(\n /**\n * The normalized user ID to which this batch belongs.\n */\n userId, \n /**\n * An identifier for this batch, allocated by the mutation queue in a\n * monotonically increasing manner.\n */\n batchId, \n /**\n * The local write time of the batch, stored as milliseconds since the\n * epoch.\n */\n localWriteTimeMs, \n /**\n * A list of mutations to apply. All mutations will be applied atomically.\n *\n * Mutations are serialized via JsonProtoSerializer.toMutation().\n */\n mutations) {\n this.userId = userId;\n this.batchId = batchId;\n this.localWriteTimeMs = localWriteTimeMs;\n this.mutations = mutations;\n }\n /** Name of the IndexedDb object store. */\n DbMutationBatch.store = 'mutations';\n /** Keys are automatically assigned via the userId, batchId properties. */\n DbMutationBatch.keyPath = ['userId', 'batchId'];\n return DbMutationBatch;\n}());\n\n/**\n * An object to be stored in the 'documentMutations' store in IndexedDb.\n *\n * A manually maintained index of all the mutation batches that affect a given\n * document key. The rows in this table are references based on the contents of\n * DbMutationBatch.mutations.\n */\nvar indexeddb_schema_DbDocumentMutation = /** @class */ (function () {\n function DbDocumentMutation() {\n }\n /**\n * Creates a [userId] key for use in the DbDocumentMutations index to iterate\n * over all of a user's document mutations.\n */\n DbDocumentMutation.prefixForUser = function (userId) {\n return [userId];\n };\n /**\n * Creates a [userId, encodedPath] key for use in the DbDocumentMutations\n * index to iterate over all at document mutations for a given path or lower.\n */\n DbDocumentMutation.prefixForPath = function (userId, path) {\n return [userId, encode(path)];\n };\n /**\n * Creates a full index key of [userId, encodedPath, batchId] for inserting\n * and deleting into the DbDocumentMutations index.\n */\n DbDocumentMutation.key = function (userId, path, batchId) {\n return [userId, encode(path), batchId];\n };\n DbDocumentMutation.store = 'documentMutations';\n /**\n * Because we store all the useful information for this store in the key,\n * there is no useful information to store as the value. The raw (unencoded)\n * path cannot be stored because IndexedDb doesn't store prototype\n * information.\n */\n DbDocumentMutation.PLACEHOLDER = new DbDocumentMutation();\n return DbDocumentMutation;\n}());\n\n/**\n * Represents the known absence of a document at a particular version.\n * Stored in IndexedDb as part of a DbRemoteDocument object.\n */\nvar DbNoDocument = /** @class */ (function () {\n function DbNoDocument(path, readTime) {\n this.path = path;\n this.readTime = readTime;\n }\n return DbNoDocument;\n}());\n\n/**\n * An object to be stored in the 'remoteDocuments' store in IndexedDb. It\n * represents either a cached document (if it exists) or a cached \"no-document\"\n * (if it is known to not exist).\n *\n * Note: This is the persisted equivalent of a MaybeDocument and could perhaps\n * be made more general if necessary.\n */\nvar DbRemoteDocument = /** @class */ (function () {\n function DbRemoteDocument(\n /**\n * Set to an instance of a DbNoDocument if it is known that no document\n * exists.\n */\n noDocument, \n /**\n * Set to an instance of a Document if there's a cached version of the\n * document.\n */\n document) {\n this.noDocument = noDocument;\n this.document = document;\n }\n DbRemoteDocument.store = 'remoteDocuments';\n return DbRemoteDocument;\n}());\n\n/**\n * An object to be stored in the 'targets' store in IndexedDb.\n *\n * This is based on and should be kept in sync with the proto used in the iOS\n * client.\n *\n * Each query the client listens to against the server is tracked on disk so\n * that the query can be efficiently resumed on restart.\n */\nvar DbTarget = /** @class */ (function () {\n function DbTarget(\n /**\n * An auto-generated sequential numeric identifier for the query.\n *\n * Queries are stored using their canonicalId as the key, but these\n * canonicalIds can be quite long so we additionally assign a unique\n * queryId which can be used by referenced data structures (e.g.\n * indexes) to minimize the on-disk cost.\n */\n targetId, \n /**\n * The canonical string representing this query. This is not unique.\n */\n canonicalId, \n /**\n * The last readTime received from the Watch Service for this query.\n *\n * This is the same value as TargetChange.read_time in the protos.\n */\n readTime, \n /**\n * An opaque, server-assigned token that allows watching a query to be\n * resumed after disconnecting without retransmitting all the data\n * that matches the query. The resume token essentially identifies a\n * point in time from which the server should resume sending results.\n *\n * This is related to the snapshotVersion in that the resumeToken\n * effectively also encodes that value, but the resumeToken is opaque\n * and sometimes encodes additional information.\n *\n * A consequence of this is that the resumeToken should be used when\n * asking the server to reason about where this client is in the watch\n * stream, but the client should use the snapshotVersion for its own\n * purposes.\n *\n * This is the same value as TargetChange.resume_token in the protos.\n */\n resumeToken, \n /**\n * A sequence number representing the last time this query was\n * listened to, used for garbage collection purposes.\n *\n * Conventionally this would be a timestamp value, but device-local\n * clocks are unreliable and they must be able to create new listens\n * even while disconnected. Instead this should be a monotonically\n * increasing number that's incremented on each listen call.\n *\n * This is different from the queryId since the queryId is an\n * immutable identifier assigned to the Query on first use while\n * lastListenSequenceNumber is updated every time the query is\n * listened to.\n */\n lastListenSequenceNumber, \n /**\n * The query for this target.\n *\n * Because canonical ids are not unique we must store the actual query. We\n * use the proto to have an object we can persist without having to\n * duplicate translation logic to and from a `Query` object.\n */\n query) {\n this.targetId = targetId;\n this.canonicalId = canonicalId;\n this.readTime = readTime;\n this.resumeToken = resumeToken;\n this.lastListenSequenceNumber = lastListenSequenceNumber;\n this.query = query;\n }\n DbTarget.store = 'targets';\n /** Keys are automatically assigned via the targetId property. */\n DbTarget.keyPath = 'targetId';\n /** The name of the queryTargets index. */\n DbTarget.queryTargetsIndexName = 'queryTargetsIndex';\n /**\n * The index of all canonicalIds to the targets that they match. This is not\n * a unique mapping because canonicalId does not promise a unique name for all\n * possible queries, so we append the targetId to make the mapping unique.\n */\n DbTarget.queryTargetsKeyPath = ['canonicalId', 'targetId'];\n return DbTarget;\n}());\n\n/**\n * An object representing an association between a target and a document.\n * Stored in the targetDocument object store to store the documents tracked by a\n * particular target.\n */\nvar DbTargetDocument = /** @class */ (function () {\n function DbTargetDocument(\n /**\n * The targetId identifying a target.\n */\n targetId, \n /**\n * The path to the document, as encoded in the key.\n */\n path) {\n this.targetId = targetId;\n this.path = path;\n }\n /** Name of the IndexedDb object store. */\n DbTargetDocument.store = 'targetDocuments';\n /** Keys are automatically assigned via the targetId, path properties. */\n DbTargetDocument.keyPath = ['targetId', 'path'];\n /** The index name for the reverse index. */\n DbTargetDocument.documentTargetsIndex = 'documentTargetsIndex';\n /** We also need to create the reverse index for these properties. */\n DbTargetDocument.documentTargetsKeyPath = ['path', 'targetId'];\n return DbTargetDocument;\n}());\n\n/**\n * A record of global state tracked across all Targets, tracked separately\n * to avoid the need for extra indexes.\n *\n * This should be kept in-sync with the proto used in the iOS client.\n */\nvar DbTargetGlobal = /** @class */ (function () {\n function DbTargetGlobal(\n /**\n * The highest numbered target id across all targets.\n *\n * See DbTarget.targetId.\n */\n highestTargetId, \n /**\n * The highest numbered lastListenSequenceNumber across all targets.\n *\n * See DbTarget.lastListenSequenceNumber.\n */\n highestListenSequenceNumber, \n /**\n * A global snapshot version representing the last consistent snapshot we\n * received from the backend. This is monotonically increasing and any\n * snapshots received from the backend prior to this version (e.g. for\n * targets resumed with a resumeToken) should be suppressed (buffered)\n * until the backend has caught up to this snapshot version again. This\n * prevents our cache from ever going backwards in time.\n */\n lastRemoteSnapshotVersion) {\n this.highestTargetId = highestTargetId;\n this.highestListenSequenceNumber = highestListenSequenceNumber;\n this.lastRemoteSnapshotVersion = lastRemoteSnapshotVersion;\n }\n /**\n * The key string used for the single object that exists in the\n * DbTargetGlobal store.\n */\n DbTargetGlobal.key = 'targetGlobalKey';\n DbTargetGlobal.store = 'targetGlobal';\n return DbTargetGlobal;\n}());\n\n/**\n * The list of all IndexedDB stored used by the SDK. This is used when creating\n * transactions so that access across all stores is done atomically.\n */\nvar ALL_STORES = [\n DbMutationQueue.store,\n DbMutationBatch.store,\n indexeddb_schema_DbDocumentMutation.store,\n DbRemoteDocument.store,\n DbTarget.store,\n DbOwner.store,\n DbTargetGlobal.store,\n DbTargetDocument.store\n];\n\n//# sourceMappingURL=indexeddb_schema.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/simple_db.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\nvar simple_db_LOG_TAG = 'SimpleDb';\n/**\n * Provides a wrapper around IndexedDb with a simplified interface that uses\n * Promise-like return values to chain operations. Real promises cannot be used\n * since .then() continuations are executed asynchronously (e.g. via\n * .setImmediate), which would cause IndexedDB to end the transaction.\n * See PersistencePromise for more details.\n */\nvar simple_db_SimpleDb = /** @class */ (function () {\n function SimpleDb(db) {\n this.db = db;\n }\n /** Opens the specified database, creating or upgrading it if necessary. */\n SimpleDb.openOrCreate = function (name, version, runUpgrade) {\n assert(SimpleDb.isAvailable(), 'IndexedDB not supported in current environment.');\n debug(simple_db_LOG_TAG, 'Opening database:', name);\n return new persistence_promise_PersistencePromise(function (resolve, reject) {\n // TODO(mikelehen): Investigate browser compatibility.\n // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB\n // suggests IE9 and older WebKit browsers handle upgrade\n // differently.\n var request = window.indexedDB.open(name, version);\n request.onsuccess = function (event) {\n var db = event.target.result;\n resolve(new SimpleDb(db));\n };\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onupgradeneeded = function (event) {\n debug(simple_db_LOG_TAG, 'Database \"' + name + '\" requires upgrade from version:', event.oldVersion);\n // TODO(mikelehen): If/when we need to do an actual data\n // migration, we'll want to wrap db in a SimpleDb and have the\n // runUpgrade function return a PersistencePromise, since we'll\n // likely need to do async reads and writes. For now we're\n // cheating and just passing the raw IndexedDB in, since\n // createObjectStore(), etc. are synchronous.\n var db = event.target.result;\n runUpgrade(db, event.oldVersion);\n };\n }).toPromise();\n };\n /** Deletes the specified database. */\n SimpleDb.delete = function (name) {\n debug(simple_db_LOG_TAG, 'Removing database:', name);\n return wrapRequest(window.indexedDB.deleteDatabase(name)).toPromise();\n };\n /** Returns true if IndexedDB is available in the current environment. */\n SimpleDb.isAvailable = function () {\n if (typeof window === 'undefined' || window.indexedDB == null) {\n return false;\n }\n // We extensively use indexed array values and compound keys,\n // which IE and Edge do not support. However, they still have indexedDB\n // defined on the window, so we need to check for them here and make sure\n // to return that persistence is not enabled for those browsers.\n // For tracking support of this feature, see here:\n // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/\n // Check the UA string to find out the browser.\n var ua = window.navigator.userAgent;\n // IE 10\n // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';\n // IE 11\n // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';\n // Edge\n // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,\n // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';\n if (ua.indexOf('MSIE ') > 0 ||\n ua.indexOf('Trident/') > 0 ||\n ua.indexOf('Edge/') > 0) {\n return false;\n }\n else {\n return true;\n }\n };\n SimpleDb.prototype.runTransaction = function (mode, objectStores, transactionFn) {\n var transaction = new simple_db_SimpleDbTransaction(this.db, mode, objectStores);\n var transactionFnResult = transactionFn(transaction)\n .catch(function (error) {\n // Abort the transaction if there was an\n // error.\n transaction.abort();\n return persistence_promise_PersistencePromise.reject(error);\n })\n .toPromise();\n // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to\n // fire), but still return the original transactionFnResult back to the\n // caller.\n return transaction.completionPromise.then(function () { return transactionFnResult; });\n };\n SimpleDb.prototype.close = function () {\n this.db.close();\n };\n return SimpleDb;\n}());\n\n/**\n * A controller for iterating over a key range or index. It allows an iterate\n * callback to delete the currently-referenced object, or jump to a new key\n * within the key range or index.\n */\nvar IterationController = /** @class */ (function () {\n function IterationController(dbCursor) {\n this.dbCursor = dbCursor;\n this.shouldStop = false;\n this.nextKey = null;\n }\n Object.defineProperty(IterationController.prototype, \"isDone\", {\n get: function () {\n return this.shouldStop;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(IterationController.prototype, \"skipToKey\", {\n get: function () {\n return this.nextKey;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(IterationController.prototype, \"cursor\", {\n set: function (value) {\n this.dbCursor = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * This function can be called to stop iteration at any point.\n */\n IterationController.prototype.done = function () {\n this.shouldStop = true;\n };\n /**\n * This function can be called to skip to that next key, which could be\n * an index or a primary key.\n */\n IterationController.prototype.skip = function (key) {\n this.nextKey = key;\n };\n /**\n * Delete the current cursor value from the object store.\n *\n * NOTE: You CANNOT do this with a keysOnly query.\n */\n IterationController.prototype.delete = function () {\n return wrapRequest(this.dbCursor.delete());\n };\n return IterationController;\n}());\n\n/**\n * Wraps an IDBTransaction and exposes a store() method to get a handle to a\n * specific object store.\n */\nvar simple_db_SimpleDbTransaction = /** @class */ (function () {\n function SimpleDbTransaction(db, mode, objectStoresNames) {\n var _this = this;\n this.aborted = false;\n this.transaction = db.transaction(objectStoresNames, mode);\n this.completionPromise = new Promise(function (resolve, reject) {\n // We consider aborting to be \"normal\" and just resolve the promise.\n // May need to revisit if/when we actually need to abort transactions.\n _this.transaction.onabort = _this.transaction.oncomplete = function (event) {\n resolve();\n };\n _this.transaction.onerror = function (event) {\n reject(event.target.error);\n };\n });\n }\n SimpleDbTransaction.prototype.abort = function () {\n if (!this.aborted) {\n debug(simple_db_LOG_TAG, 'Aborting transaction.');\n this.aborted = true;\n this.transaction.abort();\n }\n };\n /**\n * Returns a SimpleDbStore for the specified store. All\n * operations performed on the SimpleDbStore happen within the context of this\n * transaction and it cannot be used anymore once the transaction is\n * completed.\n *\n * Note that we can't actually enforce that the KeyType and ValueType are\n * correct, but they allow type safety through the rest of the consuming code.\n */\n SimpleDbTransaction.prototype.store = function (storeName) {\n var store = this.transaction.objectStore(storeName);\n assert(!!store, 'Object store not part of transaction: ' + storeName);\n return new simple_db_SimpleDbStore(store);\n };\n return SimpleDbTransaction;\n}());\n\n/**\n * A wrapper around an IDBObjectStore providing an API that:\n *\n * 1) Has generic KeyType / ValueType parameters to provide strongly-typed\n * methods for acting against the object store.\n * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every\n * method return a PersistencePromise instead.\n * 3) Provides a higher-level API to avoid needing to do excessive wrapping of\n * intermediate IndexedDB types (IDBCursorWithValue, etc.)\n */\nvar simple_db_SimpleDbStore = /** @class */ (function () {\n function SimpleDbStore(store) {\n this.store = store;\n }\n SimpleDbStore.prototype.put = function (keyOrValue, value) {\n var request;\n if (value !== undefined) {\n debug(simple_db_LOG_TAG, 'PUT', this.store.name, keyOrValue, value);\n request = this.store.put(value, keyOrValue);\n }\n else {\n debug(simple_db_LOG_TAG, 'PUT', this.store.name, '', keyOrValue);\n request = this.store.put(keyOrValue);\n }\n return wrapRequest(request);\n };\n /**\n * Gets the object with the specified key from the specified store, or null\n * if no object exists with the specified key.\n *\n * @key The key of the object to get.\n * @return The object with the specified key or null if no object exists.\n */\n SimpleDbStore.prototype.get = function (key) {\n var _this = this;\n var request = this.store.get(key);\n // tslint:disable-next-line:no-any We're doing an unsafe cast to ValueType.\n return wrapRequest(request).next(function (result) {\n // Normalize nonexistence to null.\n if (result === undefined) {\n result = null;\n }\n debug(simple_db_LOG_TAG, 'GET', _this.store.name, key, result);\n return result;\n });\n };\n SimpleDbStore.prototype.delete = function (key) {\n debug(simple_db_LOG_TAG, 'DELETE', this.store.name, key);\n var request = this.store.delete(key);\n return wrapRequest(request);\n };\n SimpleDbStore.prototype.loadAll = function (indexOrRange, range) {\n var cursor = this.cursor(this.options(indexOrRange, range));\n var results = [];\n return this.iterateCursor(cursor, function (key, value) {\n results.push(value);\n }).next(function () {\n return results;\n });\n };\n SimpleDbStore.prototype.deleteAll = function (indexOrRange, range) {\n debug(simple_db_LOG_TAG, 'DELETE ALL', this.store.name);\n var options = this.options(indexOrRange, range);\n options.keysOnly = false;\n var cursor = this.cursor(options);\n return this.iterateCursor(cursor, function (key, value, control) {\n // NOTE: Calling delete() on a cursor is documented as more efficient than\n // calling delete() on an object store with a single key\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete),\n // however, this requires us *not* to use a keysOnly cursor\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/delete). We\n // may want to compare the performance of each method.\n return control.delete();\n });\n };\n SimpleDbStore.prototype.iterate = function (optionsOrCallback, callback) {\n var options;\n if (!callback) {\n options = {};\n callback = optionsOrCallback;\n }\n else {\n options = optionsOrCallback;\n }\n var cursor = this.cursor(options);\n return this.iterateCursor(cursor, callback);\n };\n SimpleDbStore.prototype.iterateCursor = function (cursorRequest, fn) {\n var results = [];\n return new persistence_promise_PersistencePromise(function (resolve, reject) {\n cursorRequest.onerror = function (event) {\n reject(event.target.error);\n };\n cursorRequest.onsuccess = function (event) {\n var cursor = event.target.result;\n if (!cursor) {\n resolve();\n return;\n }\n var controller = new IterationController(cursor);\n var userResult = fn(cursor.primaryKey, cursor.value, controller);\n if (userResult instanceof persistence_promise_PersistencePromise) {\n results.push(userResult);\n }\n if (controller.isDone) {\n resolve();\n }\n else if (controller.skipToKey === null) {\n cursor.continue();\n }\n else {\n cursor.continue(controller.skipToKey);\n }\n };\n }).next(function () {\n return persistence_promise_PersistencePromise.waitFor(results);\n });\n };\n SimpleDbStore.prototype.options = function (indexOrRange, range) {\n var indexName = undefined;\n if (indexOrRange !== undefined) {\n if (typeof indexOrRange === 'string') {\n indexName = indexOrRange;\n }\n else {\n assert(range === undefined, '3rd argument must not be defined if 2nd is a range.');\n range = indexOrRange;\n }\n }\n return { index: indexName, range: range };\n };\n SimpleDbStore.prototype.cursor = function (options) {\n var direction = 'next';\n if (options.reverse) {\n direction = 'prev';\n }\n if (options.index) {\n var index = this.store.index(options.index);\n if (options.keysOnly) {\n return index.openKeyCursor(options.range, direction);\n }\n else {\n return index.openCursor(options.range, direction);\n }\n }\n else {\n return this.store.openCursor(options.range, direction);\n }\n };\n return SimpleDbStore;\n}());\n\n/**\n * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror\n * handlers to resolve / reject the PersistencePromise as appropriate.\n */\nfunction wrapRequest(request) {\n return new persistence_promise_PersistencePromise(function (resolve, reject) {\n request.onsuccess = function (event) {\n var result = event.target.result;\n resolve(result);\n };\n request.onerror = function (event) {\n reject(event.target.error);\n };\n });\n}\n\n//# sourceMappingURL=simple_db.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/indexeddb_mutation_queue.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n\n\n\n\n\n/** A mutation queue for a specific user, backed by IndexedDB. */\nvar indexeddb_mutation_queue_IndexedDbMutationQueue = /** @class */ (function () {\n function IndexedDbMutationQueue(\n /**\n * The normalized userId (e.g. null UID => \"\" userId) used to store /\n * retrieve mutations.\n */\n userId, serializer) {\n this.userId = userId;\n this.serializer = serializer;\n this.garbageCollector = null;\n }\n /**\n * Creates a new mutation queue for the given user.\n * @param user The user for which to create a mutation queue.\n * @param serializer The serializer to use when persisting to IndexedDb.\n */\n IndexedDbMutationQueue.forUser = function (user, serializer) {\n // TODO(mcg): Figure out what constraints there are on userIDs\n // In particular, are there any reserved characters? are empty ids allowed?\n // For the moment store these together in the same mutations table assuming\n // that empty userIDs aren't allowed.\n assert(user.uid !== '', 'UserID must not be an empty string.');\n var userId = user.isUnauthenticated() ? '' : user.uid;\n return new IndexedDbMutationQueue(userId, serializer);\n };\n IndexedDbMutationQueue.prototype.start = function (transaction) {\n var _this = this;\n return IndexedDbMutationQueue.loadNextBatchIdFromDb(transaction)\n .next(function (nextBatchId) {\n _this.nextBatchId = nextBatchId;\n return mutationQueuesStore(transaction).get(_this.userId);\n })\n .next(function (metadata) {\n if (!metadata) {\n metadata = new DbMutationQueue(_this.userId, BATCHID_UNKNOWN, \n /*lastStreamToken=*/ '');\n }\n _this.metadata = metadata;\n // On restart, nextBatchId may end up lower than\n // lastAcknowledgedBatchId since it's computed from the queue\n // contents, and there may be no mutations in the queue. In this\n // case, we need to reset lastAcknowledgedBatchId (which is safe\n // since the queue must be empty).\n if (_this.metadata.lastAcknowledgedBatchId >= _this.nextBatchId) {\n return _this.checkEmpty(transaction).next(function (empty) {\n assert(empty, 'Reset nextBatchID is only possible when the queue is empty');\n _this.metadata.lastAcknowledgedBatchId = BATCHID_UNKNOWN;\n return mutationQueuesStore(transaction).put(_this.metadata);\n });\n }\n else {\n return persistence_promise_PersistencePromise.resolve();\n }\n });\n };\n /**\n * Returns one larger than the largest batch ID that has been stored. If there\n * are no mutations returns 0. Note that batch IDs are global.\n */\n IndexedDbMutationQueue.loadNextBatchIdFromDb = function (txn) {\n var maxBatchId = BATCHID_UNKNOWN;\n return mutationsStore(txn)\n .iterate({ reverse: true }, function (key, batch, control) {\n var userId = key[0], batchId = key[1];\n if (batchId > maxBatchId) {\n maxBatchId = batch.batchId;\n }\n if (userId === '') {\n // We can't compute a predecessor for the empty string, since it\n // is lexographically first. That also means that no other\n // userIds can come before this one, so we can just exit early.\n control.done();\n }\n else {\n var nextUser = immediatePredecessor(userId);\n control.skip([nextUser]);\n }\n })\n .next(function () { return maxBatchId + 1; });\n };\n IndexedDbMutationQueue.prototype.checkEmpty = function (transaction) {\n var empty = true;\n var range = IDBKeyRange.bound(this.keyForBatchId(Number.NEGATIVE_INFINITY), this.keyForBatchId(Number.POSITIVE_INFINITY));\n return mutationsStore(transaction)\n .iterate({ range: range }, function (key, value, control) {\n empty = false;\n control.done();\n })\n .next(function () { return empty; });\n };\n IndexedDbMutationQueue.prototype.getNextBatchId = function (transaction) {\n return persistence_promise_PersistencePromise.resolve(this.nextBatchId);\n };\n IndexedDbMutationQueue.prototype.getHighestAcknowledgedBatchId = function (transaction) {\n return persistence_promise_PersistencePromise.resolve(this.metadata.lastAcknowledgedBatchId);\n };\n IndexedDbMutationQueue.prototype.acknowledgeBatch = function (transaction, batch, streamToken) {\n var batchId = batch.batchId;\n assert(batchId > this.metadata.lastAcknowledgedBatchId, 'Mutation batchIDs must be acknowledged in order');\n this.metadata.lastAcknowledgedBatchId = batchId;\n this.metadata.lastStreamToken = validateStreamToken(streamToken);\n return mutationQueuesStore(transaction).put(this.metadata);\n };\n IndexedDbMutationQueue.prototype.getLastStreamToken = function (transaction) {\n return persistence_promise_PersistencePromise.resolve(this.metadata.lastStreamToken);\n };\n IndexedDbMutationQueue.prototype.setLastStreamToken = function (transaction, streamToken) {\n this.metadata.lastStreamToken = validateStreamToken(streamToken);\n return mutationQueuesStore(transaction).put(this.metadata);\n };\n IndexedDbMutationQueue.prototype.addMutationBatch = function (transaction, localWriteTime, mutations) {\n var _this = this;\n var batchId = this.nextBatchId;\n this.nextBatchId++;\n var batch = new mutation_batch_MutationBatch(batchId, localWriteTime, mutations);\n var dbBatch = this.serializer.toDbMutationBatch(this.userId, batch);\n return mutationsStore(transaction)\n .put(dbBatch)\n .next(function () {\n var promises = [];\n for (var _i = 0, mutations_1 = mutations; _i < mutations_1.length; _i++) {\n var mutation = mutations_1[_i];\n var encodedPath = encode(mutation.key.path);\n var indexKey = indexeddb_schema_DbDocumentMutation.key(_this.userId, mutation.key.path, batchId);\n documentMutationsStore(transaction).put(indexKey, indexeddb_schema_DbDocumentMutation.PLACEHOLDER);\n }\n return persistence_promise_PersistencePromise.waitFor(promises);\n })\n .next(function () {\n return batch;\n });\n };\n IndexedDbMutationQueue.prototype.lookupMutationBatch = function (transaction, batchId) {\n var _this = this;\n return mutationsStore(transaction)\n .get(this.keyForBatchId(batchId))\n .next(function (dbBatch) {\n return dbBatch ? _this.serializer.fromDbMutationBatch(dbBatch) : null;\n });\n };\n IndexedDbMutationQueue.prototype.getNextMutationBatchAfterBatchId = function (transaction, batchId) {\n var _this = this;\n var range = IDBKeyRange.lowerBound(this.keyForBatchId(batchId + 1));\n var foundBatch = null;\n return mutationsStore(transaction)\n .iterate({ range: range }, function (key, dbBatch, control) {\n if (dbBatch.userId === _this.userId) {\n assert(dbBatch.batchId > batchId, 'Should have found mutation after ' + batchId);\n foundBatch = _this.serializer.fromDbMutationBatch(dbBatch);\n }\n control.done();\n })\n .next(function () { return foundBatch; });\n };\n IndexedDbMutationQueue.prototype.getAllMutationBatches = function (transaction) {\n var _this = this;\n var range = IDBKeyRange.bound(this.keyForBatchId(BATCHID_UNKNOWN), this.keyForBatchId(Number.POSITIVE_INFINITY));\n return mutationsStore(transaction)\n .loadAll(range)\n .next(function (dbBatches) {\n return dbBatches.map(function (dbBatch) { return _this.serializer.fromDbMutationBatch(dbBatch); });\n });\n };\n IndexedDbMutationQueue.prototype.getAllMutationBatchesThroughBatchId = function (transaction, batchId) {\n var _this = this;\n var range = IDBKeyRange.bound(this.keyForBatchId(BATCHID_UNKNOWN), this.keyForBatchId(batchId));\n return mutationsStore(transaction)\n .loadAll(range)\n .next(function (dbBatches) {\n return dbBatches.map(function (dbBatch) { return _this.serializer.fromDbMutationBatch(dbBatch); });\n });\n };\n IndexedDbMutationQueue.prototype.getAllMutationBatchesAffectingDocumentKey = function (transaction, documentKey) {\n var _this = this;\n // Scan the document-mutation index starting with a prefix starting with\n // the given documentKey.\n var indexPrefix = indexeddb_schema_DbDocumentMutation.prefixForPath(this.userId, documentKey.path);\n var indexStart = IDBKeyRange.lowerBound(indexPrefix);\n var results = [];\n return documentMutationsStore(transaction)\n .iterate({ range: indexStart }, function (indexKey, _, control) {\n var userID = indexKey[0], encodedPath = indexKey[1], batchID = indexKey[2];\n // Only consider rows matching exactly the specific key of\n // interest. Note that because we order by path first, and we\n // order terminators before path separators, we'll encounter all\n // the index rows for documentKey contiguously. In particular, all\n // the rows for documentKey will occur before any rows for\n // documents nested in a subcollection beneath documentKey so we\n // can stop as soon as we hit any such row.\n var path = decode(encodedPath);\n if (userID !== _this.userId || !documentKey.path.isEqual(path)) {\n control.done();\n return;\n }\n var mutationKey = _this.keyForBatchId(batchID);\n // Look up the mutation batch in the store.\n // PORTING NOTE: because iteration is callback driven in the web,\n // we just look up the key instead of keeping an open iterator\n // like iOS.\n return mutationsStore(transaction)\n .get(mutationKey)\n .next(function (dbBatch) {\n if (dbBatch === null) {\n fail('Dangling document-mutation reference found: ' +\n indexKey +\n ' which points to ' +\n mutationKey);\n }\n results.push(_this.serializer.fromDbMutationBatch(dbBatch));\n });\n })\n .next(function () { return results; });\n };\n IndexedDbMutationQueue.prototype.getAllMutationBatchesAffectingQuery = function (transaction, query) {\n var _this = this;\n assert(!query.isDocumentQuery(), \"Document queries shouldn't go down this path\");\n var queryPath = query.path;\n var immediateChildrenLength = queryPath.length + 1;\n // TODO(mcg): Actually implement a single-collection query\n //\n // This is actually executing an ancestor query, traversing the whole\n // subtree below the collection which can be horrifically inefficient for\n // some structures. The right way to solve this is to implement the full\n // value index, but that's not in the cards in the near future so this is\n // the best we can do for the moment.\n //\n // Since we don't yet index the actual properties in the mutations, our\n // current approach is to just return all mutation batches that affect\n // documents in the collection being queried.\n var indexPrefix = indexeddb_schema_DbDocumentMutation.prefixForPath(this.userId, queryPath);\n var encodedQueryPath = indexPrefix[1];\n var indexStart = IDBKeyRange.lowerBound(indexPrefix);\n // Collect up unique batchIDs encountered during a scan of the index. Use a\n // SortedSet to accumulate batch IDs so they can be traversed in order in a\n // scan of the main table.\n var uniqueBatchIDs = new sorted_set_SortedSet(primitiveComparator);\n return documentMutationsStore(transaction)\n .iterate({ range: indexStart }, function (indexKey, _, control) {\n var userID = indexKey[0], encodedPath = indexKey[1], batchID = indexKey[2];\n var path = decode(encodedPath);\n if (userID !== _this.userId || !queryPath.isPrefixOf(path)) {\n control.done();\n return;\n }\n // Rows with document keys more than one segment longer than the\n // query path can't be matches. For example, a query on 'rooms'\n // can't match the document /rooms/abc/messages/xyx.\n // TODO(mcg): we'll need a different scanner when we implement\n // ancestor queries.\n if (path.length !== immediateChildrenLength) {\n return;\n }\n uniqueBatchIDs = uniqueBatchIDs.add(batchID);\n })\n .next(function () {\n var results = [];\n var promises = [];\n // TODO(rockwood): Implement this using iterate.\n uniqueBatchIDs.forEach(function (batchID) {\n var mutationKey = _this.keyForBatchId(batchID);\n promises.push(mutationsStore(transaction)\n .get(mutationKey)\n .next(function (mutation) {\n if (mutation === null) {\n fail('Dangling document-mutation reference found, ' +\n 'which points to ' +\n mutationKey);\n }\n results.push(_this.serializer.fromDbMutationBatch(mutation));\n }));\n });\n return persistence_promise_PersistencePromise.waitFor(promises).next(function () { return results; });\n });\n };\n IndexedDbMutationQueue.prototype.removeMutationBatches = function (transaction, batches) {\n var txn = mutationsStore(transaction);\n var indexTxn = documentMutationsStore(transaction);\n var promises = [];\n var _loop_1 = function (batch) {\n var range = IDBKeyRange.only(this_1.keyForBatchId(batch.batchId));\n var numDeleted = 0;\n var removePromise = txn.iterate({ range: range }, function (key, value, control) {\n numDeleted++;\n return control.delete();\n });\n promises.push(removePromise.next(function () {\n assert(numDeleted === 1, 'Dangling document-mutation reference found: Missing batch ' +\n batch.batchId);\n }));\n for (var _i = 0, _a = batch.mutations; _i < _a.length; _i++) {\n var mutation = _a[_i];\n var indexKey = indexeddb_schema_DbDocumentMutation.key(this_1.userId, mutation.key.path, batch.batchId);\n promises.push(indexTxn.delete(indexKey));\n if (this_1.garbageCollector !== null) {\n this_1.garbageCollector.addPotentialGarbageKey(mutation.key);\n }\n }\n };\n var this_1 = this;\n for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {\n var batch = batches_1[_i];\n _loop_1(batch);\n }\n return persistence_promise_PersistencePromise.waitFor(promises);\n };\n IndexedDbMutationQueue.prototype.performConsistencyCheck = function (txn) {\n var _this = this;\n return this.checkEmpty(txn).next(function (empty) {\n if (!empty) {\n return persistence_promise_PersistencePromise.resolve();\n }\n // Verify that there are no entries in the documentMutations index if\n // the queue is empty.\n var startRange = IDBKeyRange.lowerBound(indexeddb_schema_DbDocumentMutation.prefixForUser(_this.userId));\n var danglingMutationReferences = [];\n return documentMutationsStore(txn)\n .iterate({ range: startRange }, function (key, _, control) {\n var userID = key[0];\n if (userID !== _this.userId) {\n control.done();\n return;\n }\n else {\n var path = decode(key[1]);\n danglingMutationReferences.push(path);\n }\n })\n .next(function () {\n assert(danglingMutationReferences.length === 0, 'Document leak -- detected dangling mutation references when queue is empty. Dangling keys: ' +\n danglingMutationReferences.map(function (p) { return p.canonicalString(); }));\n });\n });\n };\n IndexedDbMutationQueue.prototype.setGarbageCollector = function (gc) {\n this.garbageCollector = gc;\n };\n IndexedDbMutationQueue.prototype.containsKey = function (txn, key) {\n var _this = this;\n var indexKey = indexeddb_schema_DbDocumentMutation.prefixForPath(this.userId, key.path);\n var encodedPath = indexKey[1];\n var startRange = IDBKeyRange.lowerBound(indexKey);\n var containsKey = false;\n return documentMutationsStore(txn)\n .iterate({ range: startRange, keysOnly: true }, function (key, _, control) {\n var userID = key[0], keyPath = key[1], batchID = key[2];\n if (userID === _this.userId && keyPath === encodedPath) {\n containsKey = true;\n }\n control.done();\n })\n .next(function () { return containsKey; });\n };\n /**\n * Creates a [userId, batchId] key for use with the DbMutationQueue object\n * store.\n */\n IndexedDbMutationQueue.prototype.keyForBatchId = function (batchId) {\n return [this.userId, batchId];\n };\n return IndexedDbMutationQueue;\n}());\n\nfunction validateStreamToken(token) {\n assert(typeof token === 'string', 'Persisting non-string stream token not supported.');\n return token;\n}\n/**\n * Helper to get a typed SimpleDbStore for the mutations object store.\n */\nfunction mutationsStore(txn) {\n return getStore(txn, DbMutationBatch.store);\n}\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */\nfunction documentMutationsStore(txn) {\n return getStore(txn, indexeddb_schema_DbDocumentMutation.store);\n}\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */\nfunction mutationQueuesStore(txn) {\n return getStore(txn, DbMutationQueue.store);\n}\n/**\n * Helper to get a typed SimpleDbStore from a transaction.\n */\nfunction getStore(txn, store) {\n if (txn instanceof simple_db_SimpleDbTransaction) {\n return txn.store(store);\n }\n else {\n return fail('Invalid transaction object provided!');\n }\n}\n\n//# sourceMappingURL=indexeddb_mutation_queue.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/indexeddb_query_cache.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n\n\n\n\n\n\n\nvar indexeddb_query_cache_IndexedDbQueryCache = /** @class */ (function () {\n function IndexedDbQueryCache(serializer) {\n this.serializer = serializer;\n /**\n * The last received snapshot version. We store this seperately from the\n * metadata to avoid the extra conversion to/from DbTimestamp.\n */\n this.lastRemoteSnapshotVersion = snapshot_version_SnapshotVersion.MIN;\n /**\n * A cached copy of the metadata for the query cache.\n */\n this.metadata = new DbTargetGlobal(\n /*highestTargetId=*/ 0, \n /*lastListenSequenceNumber=*/ 0, snapshot_version_SnapshotVersion.MIN.toTimestamp());\n /** The garbage collector to notify about potential garbage keys. */\n this.garbageCollector = null;\n }\n IndexedDbQueryCache.prototype.start = function (transaction) {\n var _this = this;\n return globalTargetStore(transaction)\n .get(DbTargetGlobal.key)\n .next(function (metadata) {\n if (metadata !== null) {\n _this.metadata = metadata;\n var lastSavedVersion = metadata.lastRemoteSnapshotVersion;\n _this.lastRemoteSnapshotVersion = snapshot_version_SnapshotVersion.fromTimestamp(new timestamp_Timestamp(lastSavedVersion.seconds, lastSavedVersion.nanos));\n }\n return persistence_promise_PersistencePromise.resolve();\n });\n };\n IndexedDbQueryCache.prototype.getHighestTargetId = function () {\n return this.metadata.highestTargetId;\n };\n IndexedDbQueryCache.prototype.getLastRemoteSnapshotVersion = function () {\n return this.lastRemoteSnapshotVersion;\n };\n IndexedDbQueryCache.prototype.setLastRemoteSnapshotVersion = function (transaction, snapshotVersion) {\n this.lastRemoteSnapshotVersion = snapshotVersion;\n this.metadata.lastRemoteSnapshotVersion = snapshotVersion.toTimestamp();\n return globalTargetStore(transaction).put(DbTargetGlobal.key, this.metadata);\n };\n IndexedDbQueryCache.prototype.addQueryData = function (transaction, queryData) {\n var _this = this;\n var targetId = queryData.targetId;\n var addedQueryPromise = targetsStore(transaction).put(this.serializer.toDbTarget(queryData));\n if (targetId > this.metadata.highestTargetId) {\n this.metadata.highestTargetId = targetId;\n return addedQueryPromise.next(function () {\n return globalTargetStore(transaction).put(DbTargetGlobal.key, _this.metadata);\n });\n }\n else {\n return addedQueryPromise;\n }\n };\n IndexedDbQueryCache.prototype.removeQueryData = function (transaction, queryData) {\n return this.removeMatchingKeysForTargetId(transaction, queryData.targetId).next(function () {\n targetsStore(transaction).delete(queryData.targetId);\n });\n };\n IndexedDbQueryCache.prototype.getQueryData = function (transaction, query) {\n var _this = this;\n // Iterating by the canonicalId may yield more than one result because\n // canonicalId values are not required to be unique per target. This query\n // depends on the queryTargets index to be efficent.\n var canonicalId = query.canonicalId();\n var range = IDBKeyRange.bound([canonicalId, Number.NEGATIVE_INFINITY], [canonicalId, Number.POSITIVE_INFINITY]);\n var result = null;\n return targetsStore(transaction)\n .iterate({ range: range, index: DbTarget.queryTargetsIndexName }, function (key, value, control) {\n var found = _this.serializer.fromDbTarget(value);\n // After finding a potential match, check that the query is\n // actually equal to the requested query.\n if (query.isEqual(found.query)) {\n result = found;\n control.done();\n }\n })\n .next(function () { return result; });\n };\n IndexedDbQueryCache.prototype.addMatchingKeys = function (txn, keys, targetId) {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // Indexeddb.\n var promises = [];\n var store = documentTargetStore(txn);\n keys.forEach(function (key) {\n var path = encode(key.path);\n promises.push(store.put(new DbTargetDocument(targetId, path)));\n });\n return persistence_promise_PersistencePromise.waitFor(promises);\n };\n IndexedDbQueryCache.prototype.removeMatchingKeys = function (txn, keys, targetId) {\n var _this = this;\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n var promises = [];\n var store = documentTargetStore(txn);\n keys.forEach(function (key) {\n var path = encode(key.path);\n promises.push(store.delete([targetId, path]));\n if (_this.garbageCollector !== null) {\n _this.garbageCollector.addPotentialGarbageKey(key);\n }\n });\n return persistence_promise_PersistencePromise.waitFor(promises);\n };\n IndexedDbQueryCache.prototype.removeMatchingKeysForTargetId = function (txn, targetId) {\n var store = documentTargetStore(txn);\n var range = IDBKeyRange.bound([targetId], [targetId + 1], \n /*lowerOpen=*/ false, \n /*upperOpen=*/ true);\n return this.notifyGCForRemovedKeys(txn, range).next(function () {\n return store.delete(range);\n });\n };\n IndexedDbQueryCache.prototype.notifyGCForRemovedKeys = function (txn, range) {\n var _this = this;\n var store = documentTargetStore(txn);\n if (this.garbageCollector !== null && this.garbageCollector.isEager) {\n // In order to generate garbage events properly, we need to read these\n // keys before deleting.\n return store.iterate({ range: range, keysOnly: true }, function (key, _, control) {\n var path = decode(key[1]);\n var docKey = new document_key_DocumentKey(path);\n // Paranoid assertion in case the the collector is set to null\n // during the iteration.\n assert(_this.garbageCollector !== null, 'GarbageCollector for query cache set to null during key removal.');\n _this.garbageCollector.addPotentialGarbageKey(docKey);\n });\n }\n else {\n return persistence_promise_PersistencePromise.resolve();\n }\n };\n IndexedDbQueryCache.prototype.getMatchingKeysForTargetId = function (txn, targetId) {\n var promises = [];\n var range = IDBKeyRange.bound([targetId], [targetId + 1], \n /*lowerOpen=*/ false, \n /*upperOpen=*/ true);\n var store = documentTargetStore(txn);\n var result = documentKeySet();\n return store\n .iterate({ range: range, keysOnly: true }, function (key, _, control) {\n var path = decode(key[1]);\n var docKey = new document_key_DocumentKey(path);\n result = result.add(docKey);\n })\n .next(function () { return result; });\n };\n IndexedDbQueryCache.prototype.setGarbageCollector = function (gc) {\n this.garbageCollector = gc;\n };\n IndexedDbQueryCache.prototype.containsKey = function (txn, key) {\n assert(txn !== null, 'Persistence Transaction cannot be null for query cache containsKey');\n var path = encode(key.path);\n var range = IDBKeyRange.bound([path], [immediateSuccessor(path)], \n /*lowerOpen=*/ false, \n /*upperOpen=*/ true);\n var count = 0;\n return documentTargetStore(txn)\n .iterate({\n index: DbTargetDocument.documentTargetsIndex,\n keysOnly: true,\n range: range\n }, function (key, _, control) {\n count++;\n control.done();\n })\n .next(function () { return count > 0; });\n };\n return IndexedDbQueryCache;\n}());\n\n/**\n * Helper to get a typed SimpleDbStore for the queries object store.\n */\nfunction targetsStore(txn) {\n return indexeddb_query_cache_getStore(txn, DbTarget.store);\n}\n/**\n * Helper to get a typed SimpleDbStore for the target globals object store.\n */\nfunction globalTargetStore(txn) {\n return indexeddb_query_cache_getStore(txn, DbTargetGlobal.store);\n}\n/**\n * Helper to get a typed SimpleDbStore for the document target object store.\n */\nfunction documentTargetStore(txn) {\n return indexeddb_query_cache_getStore(txn, DbTargetDocument.store);\n}\n/**\n * Helper to get a typed SimpleDbStore from a transaction.\n */\nfunction indexeddb_query_cache_getStore(txn, store) {\n if (txn instanceof simple_db_SimpleDbTransaction) {\n return txn.store(store);\n }\n else {\n return fail('Invalid transaction object provided!');\n }\n}\n\n//# sourceMappingURL=indexeddb_query_cache.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/indexeddb_remote_document_cache.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n\n\nvar indexeddb_remote_document_cache_IndexedDbRemoteDocumentCache = /** @class */ (function () {\n function IndexedDbRemoteDocumentCache(serializer) {\n this.serializer = serializer;\n }\n IndexedDbRemoteDocumentCache.prototype.addEntry = function (transaction, maybeDocument) {\n return remoteDocumentsStore(transaction).put(dbKey(maybeDocument.key), this.serializer.toDbRemoteDocument(maybeDocument));\n };\n IndexedDbRemoteDocumentCache.prototype.removeEntry = function (transaction, documentKey) {\n return remoteDocumentsStore(transaction).delete(dbKey(documentKey));\n };\n IndexedDbRemoteDocumentCache.prototype.getEntry = function (transaction, documentKey) {\n var _this = this;\n return remoteDocumentsStore(transaction)\n .get(dbKey(documentKey))\n .next(function (dbRemoteDoc) {\n return dbRemoteDoc\n ? _this.serializer.fromDbRemoteDocument(dbRemoteDoc)\n : null;\n });\n };\n IndexedDbRemoteDocumentCache.prototype.getDocumentsMatchingQuery = function (transaction, query) {\n var _this = this;\n var results = documentMap();\n // Documents are ordered by key, so we can use a prefix scan to narrow down\n // the documents we need to match the query against.\n var startKey = query.path.toArray();\n var range = IDBKeyRange.lowerBound(startKey);\n return remoteDocumentsStore(transaction)\n .iterate({ range: range }, function (key, dbRemoteDoc, control) {\n var maybeDoc = _this.serializer.fromDbRemoteDocument(dbRemoteDoc);\n if (!query.path.isPrefixOf(maybeDoc.key.path)) {\n control.done();\n }\n else if (maybeDoc instanceof document_Document && query.matches(maybeDoc)) {\n results = results.insert(maybeDoc.key, maybeDoc);\n }\n })\n .next(function () { return results; });\n };\n return IndexedDbRemoteDocumentCache;\n}());\n\n/**\n * Helper to get a typed SimpleDbStore for the remoteDocuments object store.\n */\nfunction remoteDocumentsStore(txn) {\n if (txn instanceof simple_db_SimpleDbTransaction) {\n return txn.store(DbRemoteDocument.store);\n }\n else {\n return fail('Invalid transaction object provided!');\n }\n}\nfunction dbKey(docKey) {\n return docKey.path.toArray();\n}\n\n//# sourceMappingURL=indexeddb_remote_document_cache.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/local_serializer.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n\n\n\n\n\n/** Serializer for values stored in the LocalStore. */\nvar local_serializer_LocalSerializer = /** @class */ (function () {\n function LocalSerializer(remoteSerializer) {\n this.remoteSerializer = remoteSerializer;\n }\n /** Decodes a remote document from storage locally to a Document. */\n LocalSerializer.prototype.fromDbRemoteDocument = function (remoteDoc) {\n if (remoteDoc.document) {\n return this.remoteSerializer.fromDocument(remoteDoc.document);\n }\n else if (remoteDoc.noDocument) {\n var key = document_key_DocumentKey.fromSegments(remoteDoc.noDocument.path);\n var readTime = remoteDoc.noDocument.readTime;\n var timestamp = new timestamp_Timestamp(readTime.seconds, readTime.nanos);\n return new document_NoDocument(key, snapshot_version_SnapshotVersion.fromTimestamp(timestamp));\n }\n else {\n return fail('Unexpected DbRemoteDocument');\n }\n };\n /** Encodes a document for storage locally. */\n LocalSerializer.prototype.toDbRemoteDocument = function (maybeDoc) {\n if (maybeDoc instanceof document_Document) {\n var doc = this.remoteSerializer.toDocument(maybeDoc);\n return new DbRemoteDocument(null, doc);\n }\n else {\n var path = maybeDoc.key.path.toArray();\n var timestamp = maybeDoc.version.toTimestamp();\n var readTime = new DbTimestamp(timestamp.seconds, timestamp.nanos);\n return new DbRemoteDocument(new DbNoDocument(path, readTime), null);\n }\n };\n /** Encodes a batch of mutations into a DbMutationBatch for local storage. */\n LocalSerializer.prototype.toDbMutationBatch = function (userId, batch) {\n var _this = this;\n var serializedMutations = batch.mutations.map(function (m) {\n return _this.remoteSerializer.toMutation(m);\n });\n return new DbMutationBatch(userId, batch.batchId, batch.localWriteTime.toEpochMilliseconds(), serializedMutations);\n };\n /** Decodes a DbMutationBatch into a MutationBatch */\n LocalSerializer.prototype.fromDbMutationBatch = function (dbBatch) {\n var _this = this;\n var mutations = dbBatch.mutations.map(function (m) {\n return _this.remoteSerializer.fromMutation(m);\n });\n var timestamp = timestamp_Timestamp.fromEpochMilliseconds(dbBatch.localWriteTimeMs);\n return new mutation_batch_MutationBatch(dbBatch.batchId, timestamp, mutations);\n };\n /** Decodes a DbTarget into QueryData */\n LocalSerializer.prototype.fromDbTarget = function (dbTarget) {\n var readTime = new timestamp_Timestamp(dbTarget.readTime.seconds, dbTarget.readTime.nanos);\n var version = snapshot_version_SnapshotVersion.fromTimestamp(readTime);\n var query;\n if (isDocumentQuery(dbTarget.query)) {\n query = this.remoteSerializer.fromDocumentsTarget(dbTarget.query);\n }\n else {\n query = this.remoteSerializer.fromQueryTarget(dbTarget.query);\n }\n return new query_data_QueryData(query, dbTarget.targetId, QueryPurpose.Listen, version, dbTarget.resumeToken);\n };\n /** Encodes QueryData into a DbTarget for storage locally. */\n LocalSerializer.prototype.toDbTarget = function (queryData) {\n assert(QueryPurpose.Listen === queryData.purpose, 'Only queries with purpose ' +\n QueryPurpose.Listen +\n ' may be stored, got ' +\n queryData.purpose);\n var timestamp = queryData.snapshotVersion.toTimestamp();\n var dbTimestamp = new DbTimestamp(timestamp.seconds, timestamp.nanos);\n var queryProto;\n if (queryData.query.isDocumentQuery()) {\n queryProto = this.remoteSerializer.toDocumentsTarget(queryData.query);\n }\n else {\n queryProto = this.remoteSerializer.toQueryTarget(queryData.query);\n }\n assert(typeof queryData.resumeToken === 'string', 'Persisting non-string resume token not supported.');\n var resumeToken = queryData.resumeToken;\n // lastListenSequenceNumber is always 0 until we do real GC.\n return new DbTarget(queryData.targetId, queryData.query.canonicalId(), dbTimestamp, resumeToken, 0, queryProto);\n };\n return LocalSerializer;\n}());\n\n/**\n * A helper function for figuring out what kind of query has been stored.\n */\nfunction isDocumentQuery(dbQuery) {\n return dbQuery.documents !== undefined;\n}\n\n//# sourceMappingURL=local_serializer.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/indexeddb_persistence.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n\n\n\n\n\n\n\n\n\nvar indexeddb_persistence_LOG_TAG = 'IndexedDbPersistence';\n/** If the owner lease is older than 5 seconds, try to take ownership. */\nvar OWNER_LEASE_MAX_AGE_MS = 5000;\n/** Refresh the owner lease every 4 seconds while owner. */\nvar OWNER_LEASE_REFRESH_INTERVAL_MS = 4000;\n/** LocalStorage location to indicate a zombied ownerId (see class comment). */\nvar ZOMBIE_OWNER_LOCALSTORAGE_SUFFIX = 'zombiedOwnerId';\n/** Error when the owner lease cannot be acquired or is lost. */\nvar EXISTING_OWNER_ERROR_MSG = 'There is another tab open with offline' +\n ' persistence enabled. Only one such tab is allowed at a time. The' +\n ' other tab must be closed or persistence must be disabled.';\nvar UNSUPPORTED_PLATFORM_ERROR_MSG = 'This platform is either missing' +\n ' IndexedDB or is known to have an incomplete implementation. Offline' +\n ' persistence has been disabled.';\n/**\n * An IndexedDB-backed instance of Persistence. Data is stored persistently\n * across sessions.\n *\n * Currently the Firestore SDK only supports a single consumer of the database,\n * but browsers obviously support multiple tabs. IndexedDbPersistence ensures a\n * single consumer of the database via an \"owner lease\" stored in the database.\n *\n * On startup, IndexedDbPersistence assigns itself a random \"ownerId\" and writes\n * it to a special \"owner\" object in the database (if no entry exists already or\n * the current entry is expired). This owner lease is then verified inside every\n * transaction to ensure the lease has not been lost.\n *\n * If a tab opts not to acquire the owner lease (because there's an existing\n * non-expired owner) or loses the owner lease, IndexedDbPersistence enters a\n * failed state and all subsequent operations will automatically fail.\n *\n * The current owner regularly refreshes the owner lease with new timestamps to\n * prevent newly-opened tabs from taking over ownership.\n *\n * Additionally there is an optimization so that when a tab is closed, the owner\n * lease is released immediately (this is especially important to make sure that\n * a refreshed tab is able to immediately re-acquire the owner lease).\n * Unfortunately, IndexedDB cannot be reliably used in window.unload since it is\n * an asynchronous API. So in addition to attempting to give up the lease,\n * the owner writes its ownerId to a \"zombiedOwnerId\" entry in LocalStorage\n * which acts as an indicator that another tab should go ahead and take the\n * owner lease immediately regardless of the current lease timestamp.\n */\nvar indexeddb_persistence_IndexedDbPersistence = /** @class */ (function () {\n function IndexedDbPersistence(prefix, serializer) {\n this.ownerId = this.generateOwnerId();\n this.dbName = prefix + IndexedDbPersistence.MAIN_DATABASE;\n this.serializer = new local_serializer_LocalSerializer(serializer);\n this.localStoragePrefix = prefix;\n }\n IndexedDbPersistence.prototype.start = function () {\n var _this = this;\n if (!IndexedDbPersistence.isAvailable()) {\n this.persistenceError = new FirestoreError(Code.UNIMPLEMENTED, UNSUPPORTED_PLATFORM_ERROR_MSG);\n return Promise.reject(this.persistenceError);\n }\n assert(!this.started, 'IndexedDbPersistence double-started!');\n this.started = true;\n return simple_db_SimpleDb.openOrCreate(this.dbName, SCHEMA_VERSION, createOrUpgradeDb)\n .then(function (db) {\n _this.simpleDb = db;\n })\n .then(function () { return _this.tryAcquireOwnerLease(); })\n .then(function () {\n _this.scheduleOwnerLeaseRefreshes();\n _this.attachWindowUnloadHook();\n });\n };\n IndexedDbPersistence.prototype.shutdown = function () {\n var _this = this;\n assert(this.started, 'IndexedDbPersistence shutdown without start!');\n this.started = false;\n this.detachWindowUnloadHook();\n this.stopOwnerLeaseRefreshes();\n return this.releaseOwnerLease().then(function () {\n _this.simpleDb.close();\n });\n };\n IndexedDbPersistence.prototype.getMutationQueue = function (user) {\n return indexeddb_mutation_queue_IndexedDbMutationQueue.forUser(user, this.serializer);\n };\n IndexedDbPersistence.prototype.getQueryCache = function () {\n return new indexeddb_query_cache_IndexedDbQueryCache(this.serializer);\n };\n IndexedDbPersistence.prototype.getRemoteDocumentCache = function () {\n return new indexeddb_remote_document_cache_IndexedDbRemoteDocumentCache(this.serializer);\n };\n IndexedDbPersistence.prototype.runTransaction = function (action, operation) {\n var _this = this;\n if (this.persistenceError) {\n return Promise.reject(this.persistenceError);\n }\n debug(indexeddb_persistence_LOG_TAG, 'Starting transaction:', action);\n // Do all transactions as readwrite against all object stores, since we\n // are the only reader/writer.\n return this.simpleDb.runTransaction('readwrite', ALL_STORES, function (txn) {\n // Verify that we still have the owner lease as part of every transaction.\n return _this.ensureOwnerLease(txn).next(function () { return operation(txn); });\n });\n };\n IndexedDbPersistence.isAvailable = function () {\n return simple_db_SimpleDb.isAvailable();\n };\n /**\n * Generates a string used as a prefix when storing data in IndexedDB and\n * LocalStorage.\n */\n IndexedDbPersistence.buildStoragePrefix = function (databaseInfo) {\n // Use two different prefix formats:\n //\n // * firestore / persistenceKey / projectID . databaseID / ...\n // * firestore / persistenceKey / projectID / ...\n //\n // projectIDs are DNS-compatible names and cannot contain dots\n // so there's no danger of collisions.\n var database = databaseInfo.databaseId.projectId;\n if (!databaseInfo.databaseId.isDefaultDatabase) {\n database += '.' + databaseInfo.databaseId.database;\n }\n return 'firestore/' + databaseInfo.persistenceKey + '/' + database + '/';\n };\n /**\n * Acquires the owner lease if there's no valid owner. Else returns a rejected\n * promise.\n */\n IndexedDbPersistence.prototype.tryAcquireOwnerLease = function () {\n var _this = this;\n // NOTE: Don't use this.runTransaction, since it requires us to already\n // have the lease.\n return this.simpleDb.runTransaction('readwrite', [DbOwner.store], function (txn) {\n var store = txn.store(DbOwner.store);\n return store.get('owner').next(function (dbOwner) {\n if (!_this.validOwner(dbOwner)) {\n var newDbOwner = new DbOwner(_this.ownerId, Date.now());\n debug(indexeddb_persistence_LOG_TAG, 'No valid owner. Acquiring owner lease. Current owner:', dbOwner, 'New owner:', newDbOwner);\n return store.put('owner', newDbOwner);\n }\n else {\n debug(indexeddb_persistence_LOG_TAG, 'Valid owner already. Failing. Current owner:', dbOwner);\n _this.persistenceError = new FirestoreError(Code.FAILED_PRECONDITION, EXISTING_OWNER_ERROR_MSG);\n return persistence_promise_PersistencePromise.reject(_this.persistenceError);\n }\n });\n });\n };\n /** Checks the owner lease and deletes it if we are the current owner. */\n IndexedDbPersistence.prototype.releaseOwnerLease = function () {\n var _this = this;\n // NOTE: Don't use this.runTransaction, since it requires us to already\n // have the lease.\n return this.simpleDb.runTransaction('readwrite', [DbOwner.store], function (txn) {\n var store = txn.store(DbOwner.store);\n return store.get('owner').next(function (dbOwner) {\n if (dbOwner !== null && dbOwner.ownerId === _this.ownerId) {\n debug(indexeddb_persistence_LOG_TAG, 'Releasing owner lease.');\n return store.delete('owner');\n }\n else {\n return persistence_promise_PersistencePromise.resolve();\n }\n });\n });\n };\n /**\n * Checks the owner lease and returns a rejected promise if we are not the\n * current owner. This should be included in every transaction to guard\n * against losing the owner lease.\n */\n IndexedDbPersistence.prototype.ensureOwnerLease = function (txn) {\n var _this = this;\n var store = txn.store(DbOwner.store);\n return store.get('owner').next(function (dbOwner) {\n if (dbOwner === null || dbOwner.ownerId !== _this.ownerId) {\n _this.persistenceError = new FirestoreError(Code.FAILED_PRECONDITION, EXISTING_OWNER_ERROR_MSG);\n return persistence_promise_PersistencePromise.reject(_this.persistenceError);\n }\n else {\n return persistence_promise_PersistencePromise.resolve();\n }\n });\n };\n /**\n * Returns true if the provided owner exists, has a recent timestamp, and\n * isn't zombied.\n *\n * NOTE: To determine if the owner is zombied, this method reads from\n * LocalStorage which could be mildly expensive.\n */\n IndexedDbPersistence.prototype.validOwner = function (dbOwner) {\n var now = Date.now();\n var minAcceptable = now - OWNER_LEASE_MAX_AGE_MS;\n var maxAcceptable = now;\n if (dbOwner === null) {\n return false; // no owner.\n }\n else if (dbOwner.leaseTimestampMs < minAcceptable) {\n return false; // owner lease has expired.\n }\n else if (dbOwner.leaseTimestampMs > maxAcceptable) {\n log_error('Persistence owner-lease is in the future. Discarding.', dbOwner);\n return false;\n }\n else if (dbOwner.ownerId === this.getZombiedOwnerId()) {\n return false; // owner's tab closed.\n }\n else {\n return true;\n }\n };\n /**\n * Schedules a recurring timer to update the owner lease timestamp to prevent\n * other tabs from taking the lease.\n */\n IndexedDbPersistence.prototype.scheduleOwnerLeaseRefreshes = function () {\n var _this = this;\n // NOTE: This doesn't need to be scheduled on the async queue and doing so\n // would increase the chances of us not refreshing on time if the queue is\n // backed up for some reason.\n this.ownerLeaseRefreshHandle = setInterval(function () {\n var txResult = _this.runTransaction('Refresh owner timestamp', function (txn) {\n // NOTE: We don't need to validate the current owner contents, since\n // runTransaction does that automatically.\n var store = txn.store(DbOwner.store);\n return store.put('owner', new DbOwner(_this.ownerId, Date.now()));\n });\n txResult.catch(function (reason) {\n // Probably means we lost the lease. Report the error and stop trying to\n // refresh the lease.\n log_error(reason);\n _this.stopOwnerLeaseRefreshes();\n });\n }, OWNER_LEASE_REFRESH_INTERVAL_MS);\n };\n IndexedDbPersistence.prototype.stopOwnerLeaseRefreshes = function () {\n if (this.ownerLeaseRefreshHandle) {\n clearInterval(this.ownerLeaseRefreshHandle);\n this.ownerLeaseRefreshHandle = null;\n }\n };\n /**\n * Attaches a window.unload handler that will synchronously write our\n * ownerId to a \"zombie owner id\" location in localstorage. This can be used\n * by tabs trying to acquire the lease to determine that the lease should be\n * acquired immediately even if the timestamp is recent. This is particularly\n * important for the refresh case (so the tab correctly re-acquires the owner\n * lease). LocalStorage is used for this rather than IndexedDb because it is\n * a synchronous API and so can be used reliably from an unload handler.\n */\n IndexedDbPersistence.prototype.attachWindowUnloadHook = function () {\n var _this = this;\n this.windowUnloadHandler = function () {\n // Record that we're zombied.\n _this.setZombiedOwnerId(_this.ownerId);\n // Attempt graceful shutdown (including releasing our owner lease), but\n // there's no guarantee it will complete.\n _this.shutdown();\n };\n window.addEventListener('unload', this.windowUnloadHandler);\n };\n IndexedDbPersistence.prototype.detachWindowUnloadHook = function () {\n if (this.windowUnloadHandler) {\n window.removeEventListener('unload', this.windowUnloadHandler);\n this.windowUnloadHandler = null;\n }\n };\n /**\n * Returns any recorded \"zombied owner\" (i.e. a previous owner that became\n * zombied due to their tab closing) from LocalStorage, or null if no such\n * record exists.\n */\n IndexedDbPersistence.prototype.getZombiedOwnerId = function () {\n try {\n var zombiedOwnerId = window.localStorage.getItem(this.zombiedOwnerLocalStorageKey());\n debug(indexeddb_persistence_LOG_TAG, 'Zombied ownerID from LocalStorage:', zombiedOwnerId);\n return zombiedOwnerId;\n }\n catch (e) {\n // Gracefully handle if LocalStorage isn't available / working.\n log_error('Failed to get zombie owner id.', e);\n return null;\n }\n };\n /**\n * Records a zombied owner (an owner that had its tab closed) in LocalStorage\n * or, if passed null, deletes any recorded zombied owner.\n */\n IndexedDbPersistence.prototype.setZombiedOwnerId = function (zombieOwnerId) {\n try {\n if (zombieOwnerId === null) {\n window.localStorage.removeItem(this.zombiedOwnerLocalStorageKey());\n }\n else {\n window.localStorage.setItem(this.zombiedOwnerLocalStorageKey(), zombieOwnerId);\n }\n }\n catch (e) {\n // Gracefully handle if LocalStorage isn't available / working.\n log_error('Failed to set zombie owner id.', e);\n }\n };\n IndexedDbPersistence.prototype.zombiedOwnerLocalStorageKey = function () {\n return this.localStoragePrefix + ZOMBIE_OWNER_LOCALSTORAGE_SUFFIX;\n };\n IndexedDbPersistence.prototype.generateOwnerId = function () {\n // For convenience, just use an AutoId.\n return misc_AutoId.newId();\n };\n /**\n * The name of the main (and currently only) IndexedDB database. this name is\n * appended to the prefix provided to the IndexedDbPersistence constructor.\n */\n IndexedDbPersistence.MAIN_DATABASE = 'main';\n return IndexedDbPersistence;\n}());\n\n\n//# sourceMappingURL=indexeddb_persistence.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/local_documents_view.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n\n\n\n/**\n * A readonly view of the local state of all documents we're tracking (i.e. we\n * have a cached version in remoteDocumentCache or local mutations for the\n * document). The view is computed by applying the mutations in the\n * MutationQueue to the RemoteDocumentCache.\n */\nvar local_documents_view_LocalDocumentsView = /** @class */ (function () {\n function LocalDocumentsView(remoteDocumentCache, mutationQueue) {\n this.remoteDocumentCache = remoteDocumentCache;\n this.mutationQueue = mutationQueue;\n }\n /**\n * Get the local view of the document identified by `key`.\n *\n * @return Local view of the document or null if we don't have any cached\n * state for it.\n */\n LocalDocumentsView.prototype.getDocument = function (transaction, key) {\n var _this = this;\n return this.remoteDocumentCache\n .getEntry(transaction, key)\n .next(function (remoteDoc) {\n return _this.computeLocalDocument(transaction, key, remoteDoc);\n });\n };\n /**\n * Gets the local view of the documents identified by `keys`.\n *\n * If we don't have cached state for a document in `keys`, a NoDocument will\n * be stored for that key in the resulting set.\n */\n LocalDocumentsView.prototype.getDocuments = function (transaction, keys) {\n var _this = this;\n var promises = [];\n var results = maybeDocumentMap();\n keys.forEach(function (key) {\n promises.push(_this.getDocument(transaction, key).next(function (maybeDoc) {\n // TODO(http://b/32275378): Don't conflate missing / deleted.\n if (!maybeDoc) {\n maybeDoc = new document_NoDocument(key, snapshot_version_SnapshotVersion.forDeletedDoc());\n }\n results = results.insert(key, maybeDoc);\n }));\n });\n return persistence_promise_PersistencePromise.waitFor(promises).next(function () { return results; });\n };\n /** Performs a query against the local view of all documents. */\n LocalDocumentsView.prototype.getDocumentsMatchingQuery = function (transaction, query) {\n if (document_key_DocumentKey.isDocumentKey(query.path)) {\n return this.getDocumentsMatchingDocumentQuery(transaction, query.path);\n }\n else {\n return this.getDocumentsMatchingCollectionQuery(transaction, query);\n }\n };\n LocalDocumentsView.prototype.getDocumentsMatchingDocumentQuery = function (transaction, docPath) {\n // Just do a simple document lookup.\n return this.getDocument(transaction, new document_key_DocumentKey(docPath)).next(function (maybeDoc) {\n var result = documentMap();\n if (maybeDoc instanceof document_Document) {\n result = result.insert(maybeDoc.key, maybeDoc);\n }\n return result;\n });\n };\n LocalDocumentsView.prototype.getDocumentsMatchingCollectionQuery = function (transaction, query) {\n var _this = this;\n // Query the remote documents and overlay mutations.\n // TODO(mikelehen): There may be significant overlap between the mutations\n // affecting these remote documents and the\n // getAllMutationBatchesAffectingQuery() mutations. Consider optimizing.\n var results;\n return this.remoteDocumentCache\n .getDocumentsMatchingQuery(transaction, query)\n .next(function (queryResults) {\n return _this.computeLocalDocuments(transaction, queryResults);\n })\n .next(function (promisedResults) {\n results = promisedResults;\n // Now use the mutation queue to discover any other documents that may\n // match the query after applying mutations.\n return _this.mutationQueue.getAllMutationBatchesAffectingQuery(transaction, query);\n })\n .next(function (matchingMutationBatches) {\n var matchingKeys = documentKeySet();\n for (var _i = 0, matchingMutationBatches_1 = matchingMutationBatches; _i < matchingMutationBatches_1.length; _i++) {\n var batch = matchingMutationBatches_1[_i];\n for (var _a = 0, _b = batch.mutations; _a < _b.length; _a++) {\n var mutation = _b[_a];\n // TODO(mikelehen): PERF: Check if this mutation actually\n // affects the query to reduce work.\n if (!results.get(mutation.key)) {\n matchingKeys = matchingKeys.add(mutation.key);\n }\n }\n }\n // Now add in the results for the matchingKeys.\n var promises = [];\n matchingKeys.forEach(function (key) {\n promises.push(_this.getDocument(transaction, key).next(function (doc) {\n if (doc instanceof document_Document) {\n results = results.insert(doc.key, doc);\n }\n }));\n });\n return persistence_promise_PersistencePromise.waitFor(promises);\n })\n .next(function () {\n // Finally, filter out any documents that don't actually match\n // the query.\n results.forEach(function (key, doc) {\n if (!query.matches(doc)) {\n results = results.remove(key);\n }\n });\n return results;\n });\n };\n /**\n * Takes a remote document and applies local mutations to generate the local\n * view of the document.\n * @param transaction The transaction in which to perform any persistence\n * operations.\n * @param documentKey The key of the document (necessary when remoteDocument\n * is null).\n * @param document The base remote document to apply mutations to or null.\n */\n LocalDocumentsView.prototype.computeLocalDocument = function (transaction, documentKey, document) {\n return this.mutationQueue\n .getAllMutationBatchesAffectingDocumentKey(transaction, documentKey)\n .next(function (batches) {\n for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {\n var batch = batches_1[_i];\n document = batch.applyToLocalView(documentKey, document);\n }\n return document;\n });\n };\n /**\n * Takes a set of remote documents and applies local mutations to generate the\n * local view of the documents.\n * @param transaction The transaction in which to perform any persistence\n * operations.\n * @param documents The base remote documents to apply mutations to.\n * @return The local view of the documents.\n */\n LocalDocumentsView.prototype.computeLocalDocuments = function (transaction, documents) {\n var _this = this;\n var promises = [];\n documents.forEach(function (key, doc) {\n promises.push(_this.computeLocalDocument(transaction, key, doc).next(function (mutatedDoc) {\n if (mutatedDoc instanceof document_Document) {\n documents = documents.insert(mutatedDoc.key, mutatedDoc);\n }\n else if (mutatedDoc instanceof document_NoDocument) {\n documents = documents.remove(mutatedDoc.key);\n }\n else {\n fail('Unknown MaybeDocument: ' + mutatedDoc);\n }\n }));\n });\n return persistence_promise_PersistencePromise.waitFor(promises).next(function () { return documents; });\n };\n return LocalDocumentsView;\n}());\n\n\n//# sourceMappingURL=local_documents_view.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/remote_document_change_buffer.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n/**\n * An in-memory buffer of entries to be written to a RemoteDocumentCache.\n * It can be used to batch up a set of changes to be written to the cache, but\n * additionally supports reading entries back with the `getEntry()` method,\n * falling back to the underlying RemoteDocumentCache if no entry is\n * buffered.\n *\n * NOTE: This class was introduced in iOS to work around a limitation in\n * LevelDB. Given IndexedDb has full transaction support with\n * read-your-own-writes capability, this class is not technically needed, but\n * has been preserved as a convenience and to aid portability.\n */\nvar remote_document_change_buffer_RemoteDocumentChangeBuffer = /** @class */ (function () {\n function RemoteDocumentChangeBuffer(remoteDocumentCache) {\n this.remoteDocumentCache = remoteDocumentCache;\n this.changes = maybeDocumentMap();\n }\n /** Buffers a `RemoteDocumentCache.addEntry()` call. */\n RemoteDocumentChangeBuffer.prototype.addEntry = function (maybeDocument) {\n var changes = this.assertChanges();\n this.changes = changes.insert(maybeDocument.key, maybeDocument);\n };\n // NOTE: removeEntry() is not presently necessary and so is omitted.\n /**\n * Looks up an entry in the cache. The buffered changes will first be checked,\n * and if no buffered change applies, this will forward to\n * `RemoteDocumentCache.getEntry()`.\n *\n * @param transaction The transaction in which to perform any persistence\n * operations.\n * @param documentKey The key of the entry to look up.\n * @return The cached Document or NoDocument entry, or null if we have nothing\n * cached.\n */\n RemoteDocumentChangeBuffer.prototype.getEntry = function (transaction, documentKey) {\n var changes = this.assertChanges();\n var bufferedEntry = changes.get(documentKey);\n if (bufferedEntry) {\n return persistence_promise_PersistencePromise.resolve(bufferedEntry);\n }\n else {\n return this.remoteDocumentCache.getEntry(transaction, documentKey);\n }\n };\n /**\n * Applies buffered changes to the underlying RemoteDocumentCache, using\n * the provided transaction.\n */\n RemoteDocumentChangeBuffer.prototype.apply = function (transaction) {\n var _this = this;\n var changes = this.assertChanges();\n var promises = [];\n changes.forEach(function (key, maybeDoc) {\n promises.push(_this.remoteDocumentCache.addEntry(transaction, maybeDoc));\n });\n // We should not be used to buffer any more changes.\n this.changes = null;\n return persistence_promise_PersistencePromise.waitFor(promises);\n };\n /** Helper to assert this.changes is not null and return it. */\n RemoteDocumentChangeBuffer.prototype.assertChanges = function () {\n assert(this.changes !== null, 'Changes have already been applied.');\n return this.changes;\n };\n return RemoteDocumentChangeBuffer;\n}());\n\n\n//# sourceMappingURL=remote_document_change_buffer.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/local_store.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nvar local_store_LOG_TAG = 'LocalStore';\n/**\n * Local storage in the Firestore client. Coordinates persistence components\n * like the mutation queue and remote document cache to present a\n * latency-compensated view of stored data.\n *\n * The LocalStore is responsible for accepting mutations from the Sync Engine.\n * Writes from the client are put into a queue as provisional Mutations until\n * they are processed by the RemoteStore and confirmed as having been written\n * to the server.\n *\n * The local store provides the local version of documents that have been\n * modified locally. It maintains the constraint:\n *\n * LocalDocument = RemoteDocument + Active(LocalMutations)\n *\n * (Active mutations are those that are enqueued and have not been previously\n * acknowledged or rejected).\n *\n * The RemoteDocument (\"ground truth\") state is provided via the\n * applyChangeBatch method. It will be some version of a server-provided\n * document OR will be a server-provided document PLUS acknowledged mutations:\n *\n * RemoteDocument' = RemoteDocument + Acknowledged(LocalMutations)\n *\n * Note that this \"dirty\" version of a RemoteDocument will not be identical to a\n * server base version, since it has LocalMutations added to it pending getting\n * an authoritative copy from the server.\n *\n * Since LocalMutations can be rejected by the server, we have to be able to\n * revert a LocalMutation that has already been applied to the LocalDocument\n * (typically done by replaying all remaining LocalMutations to the\n * RemoteDocument to re-apply).\n *\n * The LocalStore is responsible for the garbage collection of the documents it\n * contains. For now, it every doc referenced by a view, the mutation queue, or\n * the RemoteStore.\n *\n * It also maintains the persistence of mapping queries to resume tokens and\n * target ids. It needs to know this data about queries to properly know what\n * docs it would be allowed to garbage collect.\n *\n * The LocalStore must be able to efficiently execute queries against its local\n * cache of the documents, to provide the initial set of results before any\n * remote changes have been received.\n *\n * Note: In TypeScript, most methods return Promises since the implementation\n * may rely on fetching data from IndexedDB which is async.\n * These Promises will only be rejected on an I/O error or other internal\n * (unexpected) failure (e.g. failed assert) and always represent an\n * unrecoverable error (should be caught / reported by the async_queue).\n */\nvar local_store_LocalStore = /** @class */ (function () {\n function LocalStore(\n /** Manages our in-memory or durable persistence. */\n persistence, initialUser, \n /**\n * The garbage collector collects documents that should no longer be\n * cached (e.g. if they are no longer retained by the above reference sets\n * and the garbage collector is performing eager collection).\n */\n garbageCollector) {\n this.persistence = persistence;\n this.garbageCollector = garbageCollector;\n /**\n * The set of document references maintained by any local views.\n */\n this.localViewReferences = new reference_set_ReferenceSet();\n /** Maps a targetID to data about its query. */\n this.targetIds = {};\n /** Used to generate targetIDs for queries tracked locally. */\n this.targetIdGenerator = TargetIdGenerator.forLocalStore();\n /**\n * A heldBatchResult is a mutation batch result (from a write acknowledgement)\n * that arrived before the watch stream got notified of a snapshot that\n * includes the write. So we \"hold\" it until the watch stream catches up. It\n * ensures that the local write remains visible (latency compensation) and\n * doesn't temporarily appear reverted because the watch stream is slower than\n * the write stream and so wasn't reflecting it.\n *\n * NOTE: Eventually we want to move this functionality into the remote store.\n */\n this.heldBatchResults = [];\n this.mutationQueue = persistence.getMutationQueue(initialUser);\n this.remoteDocuments = persistence.getRemoteDocumentCache();\n this.queryCache = persistence.getQueryCache();\n this.localDocuments = new local_documents_view_LocalDocumentsView(this.remoteDocuments, this.mutationQueue);\n this.garbageCollector.addGarbageSource(this.localViewReferences);\n this.garbageCollector.addGarbageSource(this.queryCache);\n this.garbageCollector.addGarbageSource(this.mutationQueue);\n }\n /** Performs any initial startup actions required by the local store. */\n LocalStore.prototype.start = function () {\n var _this = this;\n return this.persistence.runTransaction('Start LocalStore', function (txn) {\n return _this.startMutationQueue(txn).next(function () { return _this.startQueryCache(txn); });\n });\n };\n /**\n * Tells the LocalStore that the currently authenticated user has changed.\n *\n * In response the local store switches the mutation queue to the new user and\n * returns any resulting document changes.\n */\n LocalStore.prototype.handleUserChange = function (user) {\n var _this = this;\n return this.persistence.runTransaction('Handle user change', function (txn) {\n // Swap out the mutation queue, grabbing the pending mutation batches\n // before and after.\n var oldBatches;\n return _this.mutationQueue\n .getAllMutationBatches(txn)\n .next(function (promisedOldBatches) {\n oldBatches = promisedOldBatches;\n _this.garbageCollector.removeGarbageSource(_this.mutationQueue);\n _this.mutationQueue = _this.persistence.getMutationQueue(user);\n _this.garbageCollector.addGarbageSource(_this.mutationQueue);\n return _this.startMutationQueue(txn);\n })\n .next(function () {\n // Recreate our LocalDocumentsView using the new\n // MutationQueue.\n _this.localDocuments = new local_documents_view_LocalDocumentsView(_this.remoteDocuments, _this.mutationQueue);\n return _this.mutationQueue.getAllMutationBatches(txn);\n })\n .next(function (newBatches) {\n // Union the old/new changed keys.\n var changedKeys = documentKeySet();\n for (var _i = 0, _a = [oldBatches, newBatches]; _i < _a.length; _i++) {\n var batches = _a[_i];\n for (var _b = 0, batches_1 = batches; _b < batches_1.length; _b++) {\n var batch = batches_1[_b];\n for (var _c = 0, _d = batch.mutations; _c < _d.length; _c++) {\n var mutation = _d[_c];\n changedKeys = changedKeys.add(mutation.key);\n }\n }\n }\n // Return the set of all (potentially) changed documents as the\n // result of the user change.\n return _this.localDocuments.getDocuments(txn, changedKeys);\n });\n });\n };\n LocalStore.prototype.startQueryCache = function (txn) {\n var _this = this;\n return this.queryCache.start(txn).next(function () {\n var targetId = _this.queryCache.getHighestTargetId();\n _this.targetIdGenerator = TargetIdGenerator.forLocalStore(targetId);\n });\n };\n LocalStore.prototype.startMutationQueue = function (txn) {\n var _this = this;\n return this.mutationQueue\n .start(txn)\n .next(function () {\n // If we have any leftover mutation batch results from a prior run,\n // just drop them.\n // TODO(http://b/33446471): We probably need to repopulate\n // heldBatchResults or similar instead, but that is not\n // straightforward since we're not persisting the write ack versions.\n _this.heldBatchResults = [];\n return _this.mutationQueue.getHighestAcknowledgedBatchId(txn);\n })\n .next(function (highestAck) {\n // TODO(mikelehen): This is the only usage of\n // getAllMutationBatchesThroughBatchId(). Consider removing it in\n // favor of a getAcknowledgedBatches() method.\n if (highestAck !== BATCHID_UNKNOWN) {\n return _this.mutationQueue.getAllMutationBatchesThroughBatchId(txn, highestAck);\n }\n else {\n return persistence_promise_PersistencePromise.resolve([]);\n }\n })\n .next(function (ackedBatches) {\n if (ackedBatches.length > 0) {\n return _this.mutationQueue.removeMutationBatches(txn, ackedBatches);\n }\n else {\n return persistence_promise_PersistencePromise.resolve();\n }\n });\n };\n /* Accept locally generated Mutations and commit them to storage. */\n LocalStore.prototype.localWrite = function (mutations) {\n var _this = this;\n return this.persistence.runTransaction('Locally write mutations', function (txn) {\n var batch;\n var localWriteTime = timestamp_Timestamp.now();\n return _this.mutationQueue\n .addMutationBatch(txn, localWriteTime, mutations)\n .next(function (promisedBatch) {\n batch = promisedBatch;\n // TODO(koss): This is doing an N^2 update by replaying ALL the\n // mutations on each document (instead of just the ones added) in\n // this batch.\n var keys = batch.keys();\n return _this.localDocuments.getDocuments(txn, keys);\n })\n .next(function (changedDocuments) {\n return { batchId: batch.batchId, changes: changedDocuments };\n });\n });\n };\n /**\n * Acknowledge the given batch.\n *\n * On the happy path when a batch is acknowledged, the local store will\n *\n * + remove the batch from the mutation queue;\n * + apply the changes to the remote document cache;\n * + recalculate the latency compensated view implied by those changes (there\n * may be mutations in the queue that affect the documents but haven't been\n * acknowledged yet); and\n * + give the changed documents back the sync engine\n *\n * @returns The resulting (modified) documents.\n */\n LocalStore.prototype.acknowledgeBatch = function (batchResult) {\n var _this = this;\n return this.persistence.runTransaction('Acknowledge batch', function (txn) {\n var affected;\n return _this.mutationQueue\n .acknowledgeBatch(txn, batchResult.batch, batchResult.streamToken)\n .next(function () {\n if (_this.shouldHoldBatchResult(batchResult.commitVersion)) {\n _this.heldBatchResults.push(batchResult);\n affected = documentKeySet();\n return persistence_promise_PersistencePromise.resolve();\n }\n else {\n var documentBuffer_1 = new remote_document_change_buffer_RemoteDocumentChangeBuffer(_this.remoteDocuments);\n return _this.releaseBatchResults(txn, [batchResult], documentBuffer_1).next(function (promisedAffectedKeys) {\n affected = promisedAffectedKeys;\n return documentBuffer_1.apply(txn);\n });\n }\n })\n .next(function () {\n return _this.mutationQueue.performConsistencyCheck(txn);\n })\n .next(function () {\n return _this.localDocuments.getDocuments(txn, affected);\n });\n });\n };\n /**\n * Remove mutations from the MutationQueue for the specified batch;\n * LocalDocuments will be recalculated.\n *\n * @returns The resulting modified documents.\n */\n LocalStore.prototype.rejectBatch = function (batchId) {\n var _this = this;\n return this.persistence.runTransaction('Reject batch', function (txn) {\n var toReject;\n var affectedKeys;\n return _this.mutationQueue\n .lookupMutationBatch(txn, batchId)\n .next(function (promisedToReject) {\n assert(promisedToReject != null, 'Attempt to reject nonexistent batch!');\n toReject = promisedToReject;\n return _this.mutationQueue\n .getHighestAcknowledgedBatchId(txn)\n .next(function (lastAcked) {\n assert(batchId > lastAcked, \"Acknowledged batches can't be rejected.\");\n return toReject;\n });\n })\n .next(function () {\n return _this.removeMutationBatch(txn, toReject);\n })\n .next(function (promisedAffectedKeys) {\n affectedKeys = promisedAffectedKeys;\n return _this.mutationQueue.performConsistencyCheck(txn);\n })\n .next(function () {\n return _this.localDocuments.getDocuments(txn, affectedKeys);\n });\n });\n };\n /** Returns the last recorded stream token for the current user. */\n LocalStore.prototype.getLastStreamToken = function () {\n var _this = this;\n return this.persistence.runTransaction('Get last stream token', function (txn) {\n return _this.mutationQueue.getLastStreamToken(txn);\n });\n };\n /**\n * Sets the stream token for the current user without acknowledging any\n * mutation batch. This is usually only useful after a stream handshake or in\n * response to an error that requires clearing the stream token.\n */\n LocalStore.prototype.setLastStreamToken = function (streamToken) {\n var _this = this;\n return this.persistence.runTransaction('Set last stream token', function (txn) {\n return _this.mutationQueue.setLastStreamToken(txn, streamToken);\n });\n };\n /**\n * Returns the last consistent snapshot processed (used by the RemoteStore to\n * determine whether to buffer incoming snapshots from the backend).\n */\n LocalStore.prototype.getLastRemoteSnapshotVersion = function () {\n return this.queryCache.getLastRemoteSnapshotVersion();\n };\n /**\n * Update the \"ground-state\" (remote) documents. We assume that the remote\n * event reflects any write batches that have been acknowledged or rejected\n * (i.e. we do not re-apply local mutations to updates from this event).\n *\n * LocalDocuments are re-calculated if there are remaining mutations in the\n * queue.\n */\n LocalStore.prototype.applyRemoteEvent = function (remoteEvent) {\n var _this = this;\n var documentBuffer = new remote_document_change_buffer_RemoteDocumentChangeBuffer(this.remoteDocuments);\n return this.persistence.runTransaction('Apply remote event', function (txn) {\n var promises = [];\n forEachNumber(remoteEvent.targetChanges, function (targetId, change) {\n // Do not ref/unref unassigned targetIds - it may lead to leaks.\n var queryData = _this.targetIds[targetId];\n if (!queryData)\n return;\n var mapping = change.mapping;\n if (mapping) {\n // First make sure that all references are deleted\n if (mapping instanceof ResetMapping) {\n promises.push(_this.queryCache\n .removeMatchingKeysForTargetId(txn, targetId)\n .next(function () {\n return _this.queryCache.addMatchingKeys(txn, mapping.documents, targetId);\n }));\n }\n else if (mapping instanceof UpdateMapping) {\n promises.push(_this.queryCache\n .removeMatchingKeys(txn, mapping.removedDocuments, targetId)\n .next(function () {\n return _this.queryCache.addMatchingKeys(txn, mapping.addedDocuments, targetId);\n }));\n }\n else {\n return fail('Unknown mapping type: ' + JSON.stringify(mapping));\n }\n }\n // Update the resume token if the change includes one. Don't clear\n // any preexisting value.\n var resumeToken = change.resumeToken;\n if (resumeToken.length > 0) {\n queryData = queryData.update({\n resumeToken: resumeToken,\n snapshotVersion: change.snapshotVersion\n });\n _this.targetIds[targetId] = queryData;\n promises.push(_this.queryCache.addQueryData(txn, queryData));\n }\n });\n var changedDocKeys = documentKeySet();\n remoteEvent.documentUpdates.forEach(function (key, doc) {\n changedDocKeys = changedDocKeys.add(key);\n promises.push(documentBuffer.getEntry(txn, key).next(function (existingDoc) {\n // Make sure we don't apply an old document version to the remote\n // cache, though we make an exception for SnapshotVersion.MIN which\n // can happen for manufactured events (e.g. in the case of a limbo\n // document resolution failing).\n if (existingDoc == null ||\n doc.version.isEqual(snapshot_version_SnapshotVersion.MIN) ||\n doc.version.compareTo(existingDoc.version) >= 0) {\n documentBuffer.addEntry(doc);\n }\n else {\n debug(local_store_LOG_TAG, 'Ignoring outdated watch update for ', key, '. Current version:', existingDoc.version, ' Watch version:', doc.version);\n }\n // The document might be garbage because it was unreferenced by\n // everything. Make sure to mark it as garbage if it is...\n _this.garbageCollector.addPotentialGarbageKey(key);\n }));\n });\n // HACK: The only reason we allow a null snapshot version is so that we\n // can synthesize remote events when we get permission denied errors while\n // trying to resolve the state of a locally cached document that is in\n // limbo.\n var lastRemoteVersion = _this.queryCache.getLastRemoteSnapshotVersion();\n var remoteVersion = remoteEvent.snapshotVersion;\n if (!remoteVersion.isEqual(snapshot_version_SnapshotVersion.MIN)) {\n assert(remoteVersion.compareTo(lastRemoteVersion) >= 0, 'Watch stream reverted to previous snapshot?? ' +\n remoteVersion +\n ' < ' +\n lastRemoteVersion);\n promises.push(_this.queryCache.setLastRemoteSnapshotVersion(txn, remoteVersion));\n }\n var releasedWriteKeys;\n return persistence_promise_PersistencePromise.waitFor(promises)\n .next(function () { return _this.releaseHeldBatchResults(txn, documentBuffer); })\n .next(function (promisedReleasedWriteKeys) {\n releasedWriteKeys = promisedReleasedWriteKeys;\n return documentBuffer.apply(txn);\n })\n .next(function () {\n return _this.localDocuments.getDocuments(txn, changedDocKeys.unionWith(releasedWriteKeys));\n });\n });\n };\n /**\n * Notify local store of the changed views to locally pin documents.\n */\n LocalStore.prototype.notifyLocalViewChanges = function (viewChanges) {\n var _this = this;\n return this.persistence.runTransaction('Notify local view changes', function (txn) {\n var promises = [];\n var _loop_1 = function (view) {\n promises.push(_this.queryCache\n .getQueryData(txn, view.query)\n .next(function (queryData) {\n assert(queryData !== null, 'Local view changes contain unallocated query.');\n var targetId = queryData.targetId;\n _this.localViewReferences.addReferences(view.addedKeys, targetId);\n _this.localViewReferences.removeReferences(view.removedKeys, targetId);\n }));\n };\n for (var _i = 0, viewChanges_1 = viewChanges; _i < viewChanges_1.length; _i++) {\n var view = viewChanges_1[_i];\n _loop_1(view);\n }\n return persistence_promise_PersistencePromise.waitFor(promises);\n });\n };\n /**\n * Gets the mutation batch after the passed in batchId in the mutation queue\n * or null if empty.\n * @param afterBatchId If provided, the batch to search after.\n * @returns The next mutation or null if there wasn't one.\n */\n LocalStore.prototype.nextMutationBatch = function (afterBatchId) {\n var _this = this;\n return this.persistence.runTransaction('Get next mutation batch', function (txn) {\n if (afterBatchId === undefined) {\n afterBatchId = BATCHID_UNKNOWN;\n }\n return _this.mutationQueue.getNextMutationBatchAfterBatchId(txn, afterBatchId);\n });\n };\n /**\n * Read the current value of a Document with a given key or null if not\n * found - used for testing.\n */\n LocalStore.prototype.readDocument = function (key) {\n var _this = this;\n return this.persistence.runTransaction('read document', function (txn) {\n return _this.localDocuments.getDocument(txn, key);\n });\n };\n /**\n * Assigns the given query an internal ID so that its results can be pinned so\n * they don't get GC'd. A query must be allocated in the local store before\n * the store can be used to manage its view.\n */\n LocalStore.prototype.allocateQuery = function (query) {\n var _this = this;\n return this.persistence.runTransaction('Allocate query', function (txn) {\n var queryData;\n return _this.queryCache\n .getQueryData(txn, query)\n .next(function (cached) {\n if (cached) {\n // This query has been listened to previously, so reuse the\n // previous targetID.\n // TODO(mcg): freshen last accessed date?\n queryData = cached;\n return persistence_promise_PersistencePromise.resolve();\n }\n else {\n var targetId = _this.targetIdGenerator.next();\n queryData = new query_data_QueryData(query, targetId, QueryPurpose.Listen);\n return _this.queryCache.addQueryData(txn, queryData);\n }\n })\n .next(function () {\n assert(!_this.targetIds[queryData.targetId], 'Tried to allocate an already allocated query: ' + query);\n _this.targetIds[queryData.targetId] = queryData;\n return queryData;\n });\n });\n };\n /** Unpin all the documents associated with the given query. */\n LocalStore.prototype.releaseQuery = function (query) {\n var _this = this;\n return this.persistence.runTransaction('Release query', function (txn) {\n return _this.queryCache\n .getQueryData(txn, query)\n .next(function (queryData) {\n assert(queryData != null, 'Tried to release nonexistent query: ' + query);\n _this.localViewReferences.removeReferencesForId(queryData.targetId);\n delete _this.targetIds[queryData.targetId];\n if (_this.garbageCollector.isEager) {\n return _this.queryCache.removeQueryData(txn, queryData);\n }\n else {\n return persistence_promise_PersistencePromise.resolve();\n }\n })\n .next(function () {\n // If this was the last watch target, then we won't get any more\n // watch snapshots, so we should release any held batch results.\n if (isEmpty(_this.targetIds)) {\n var documentBuffer_2 = new remote_document_change_buffer_RemoteDocumentChangeBuffer(_this.remoteDocuments);\n return _this.releaseHeldBatchResults(txn, documentBuffer_2).next(function () {\n documentBuffer_2.apply(txn);\n });\n }\n else {\n return persistence_promise_PersistencePromise.resolve();\n }\n });\n });\n };\n /**\n * Runs the specified query against all the documents in the local store and\n * returns the results.\n */\n LocalStore.prototype.executeQuery = function (query) {\n var _this = this;\n return this.persistence.runTransaction('Execute query', function (txn) {\n return _this.localDocuments.getDocumentsMatchingQuery(txn, query);\n });\n };\n /**\n * Returns the keys of the documents that are associated with the given\n * target id in the remote table.\n */\n LocalStore.prototype.remoteDocumentKeys = function (targetId) {\n var _this = this;\n return this.persistence.runTransaction('Remote document keys', function (txn) {\n return _this.queryCache.getMatchingKeysForTargetId(txn, targetId);\n });\n };\n /**\n * Collect garbage if necessary.\n * Should be called periodically by Sync Engine to recover resources. The\n * implementation must guarantee that GC won't happen in other places than\n * this method call.\n */\n LocalStore.prototype.collectGarbage = function () {\n var _this = this;\n // Call collectGarbage regardless of whether isGCEnabled so the referenceSet\n // doesn't continue to accumulate the garbage keys.\n return this.persistence.runTransaction('Garbage collection', function (txn) {\n return _this.garbageCollector.collectGarbage(txn).next(function (garbage) {\n var promises = [];\n garbage.forEach(function (key) {\n promises.push(_this.remoteDocuments.removeEntry(txn, key));\n });\n return persistence_promise_PersistencePromise.waitFor(promises);\n });\n });\n };\n LocalStore.prototype.releaseHeldBatchResults = function (txn, documentBuffer) {\n var toRelease = [];\n for (var _i = 0, _a = this.heldBatchResults; _i < _a.length; _i++) {\n var batchResult = _a[_i];\n if (!this.isRemoteUpToVersion(batchResult.commitVersion)) {\n break;\n }\n toRelease.push(batchResult);\n }\n if (toRelease.length === 0) {\n return persistence_promise_PersistencePromise.resolve(documentKeySet());\n }\n else {\n this.heldBatchResults.splice(0, toRelease.length);\n return this.releaseBatchResults(txn, toRelease, documentBuffer);\n }\n };\n LocalStore.prototype.isRemoteUpToVersion = function (version) {\n // If there are no watch targets, then we won't get remote snapshots, and\n // we are always \"up-to-date.\"\n var lastRemoteVersion = this.queryCache.getLastRemoteSnapshotVersion();\n return (version.compareTo(lastRemoteVersion) <= 0 ||\n isEmpty(this.targetIds));\n };\n LocalStore.prototype.shouldHoldBatchResult = function (version) {\n // Check if watcher isn't up to date or prior results are already held.\n return (!this.isRemoteUpToVersion(version) || this.heldBatchResults.length > 0);\n };\n LocalStore.prototype.releaseBatchResults = function (txn, batchResults, documentBuffer) {\n var _this = this;\n var promiseChain = persistence_promise_PersistencePromise.resolve();\n var _loop_2 = function (batchResult) {\n promiseChain = promiseChain.next(function () {\n return _this.applyWriteToRemoteDocuments(txn, batchResult, documentBuffer);\n });\n };\n for (var _i = 0, batchResults_1 = batchResults; _i < batchResults_1.length; _i++) {\n var batchResult = batchResults_1[_i];\n _loop_2(batchResult);\n }\n return promiseChain.next(function () {\n return _this.removeMutationBatches(txn, batchResults.map(function (result) { return result.batch; }));\n });\n };\n LocalStore.prototype.removeMutationBatch = function (txn, batch) {\n return this.removeMutationBatches(txn, [batch]);\n };\n /** Removes all the mutation batches named in the given array. */\n LocalStore.prototype.removeMutationBatches = function (txn, batches) {\n var affectedDocs = documentKeySet();\n for (var _i = 0, batches_2 = batches; _i < batches_2.length; _i++) {\n var batch = batches_2[_i];\n for (var _a = 0, _b = batch.mutations; _a < _b.length; _a++) {\n var mutation = _b[_a];\n var key = mutation.key;\n affectedDocs = affectedDocs.add(key);\n }\n }\n return this.mutationQueue\n .removeMutationBatches(txn, batches)\n .next(function () { return affectedDocs; });\n };\n LocalStore.prototype.applyWriteToRemoteDocuments = function (txn, batchResult, documentBuffer) {\n var batch = batchResult.batch;\n var docKeys = batch.keys();\n var promiseChain = persistence_promise_PersistencePromise.resolve();\n docKeys.forEach(function (docKey) {\n promiseChain = promiseChain\n .next(function () {\n return documentBuffer.getEntry(txn, docKey);\n })\n .next(function (remoteDoc) {\n var doc = remoteDoc;\n var ackVersion = batchResult.docVersions.get(docKey);\n assert(ackVersion !== null, 'ackVersions should contain every doc in the write.');\n if (!doc || doc.version.compareTo(ackVersion) < 0) {\n doc = batch.applyToRemoteDocument(docKey, doc, batchResult);\n if (!doc) {\n assert(!remoteDoc, 'Mutation batch ' +\n batch +\n ' applied to document ' +\n remoteDoc +\n ' resulted in null');\n }\n else {\n documentBuffer.addEntry(doc);\n }\n }\n });\n });\n return promiseChain;\n };\n return LocalStore;\n}());\n\n\n//# sourceMappingURL=local_store.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/memory_mutation_queue.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n\n\n\n\n\nvar memory_mutation_queue_MemoryMutationQueue = /** @class */ (function () {\n function MemoryMutationQueue() {\n /**\n * The set of all mutations that have been sent but not yet been applied to\n * the backend.\n */\n this.mutationQueue = [];\n /** Next value to use when assigning sequential IDs to each mutation batch. */\n this.nextBatchId = 1;\n /** The highest acknowledged mutation in the queue. */\n this.highestAcknowledgedBatchId = BATCHID_UNKNOWN;\n /** The last received stream token from the server, used to acknowledge which\n * responses the client has processed. Stream tokens are opaque checkpoint\n * markers whose only real value is their inclusion in the next request.\n */\n this.lastStreamToken = emptyByteString();\n /** The garbage collector to notify about potential garbage keys. */\n this.garbageCollector = null;\n /** An ordered mapping between documents and the mutations batch IDs. */\n this.batchesByDocumentKey = new sorted_set_SortedSet(reference_set_DocReference.compareByKey);\n }\n MemoryMutationQueue.prototype.start = function (transaction) {\n // NOTE: The queue may be shutdown / started multiple times, since we\n // maintain the queue for the duration of the app session in case a user\n // logs out / back in. To behave like the LevelDB-backed MutationQueue (and\n // accommodate tests that expect as much), we reset nextBatchId and\n // highestAcknowledgedBatchId if the queue is empty.\n if (this.mutationQueue.length === 0) {\n this.nextBatchId = 1;\n this.highestAcknowledgedBatchId = BATCHID_UNKNOWN;\n }\n assert(this.highestAcknowledgedBatchId < this.nextBatchId, 'highestAcknowledgedBatchId must be less than the nextBatchId');\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryMutationQueue.prototype.checkEmpty = function (transaction) {\n return persistence_promise_PersistencePromise.resolve(this.mutationQueue.length === 0);\n };\n MemoryMutationQueue.prototype.getNextBatchId = function (transaction) {\n return persistence_promise_PersistencePromise.resolve(this.nextBatchId);\n };\n MemoryMutationQueue.prototype.getHighestAcknowledgedBatchId = function (transaction) {\n return persistence_promise_PersistencePromise.resolve(this.highestAcknowledgedBatchId);\n };\n MemoryMutationQueue.prototype.acknowledgeBatch = function (transaction, batch, streamToken) {\n var batchId = batch.batchId;\n assert(batchId > this.highestAcknowledgedBatchId, 'Mutation batchIDs must be acknowledged in order');\n var batchIndex = this.indexOfExistingBatchId(batchId, 'acknowledged');\n // Verify that the batch in the queue is the one to be acknowledged.\n var check = this.mutationQueue[batchIndex];\n assert(batchId === check.batchId, 'Queue ordering failure: expected batch ' +\n batchId +\n ', got batch ' +\n check.batchId);\n assert(!check.isTombstone(), \"Can't acknowledge a previously removed batch\");\n this.highestAcknowledgedBatchId = batchId;\n this.lastStreamToken = streamToken;\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryMutationQueue.prototype.getLastStreamToken = function (transaction) {\n return persistence_promise_PersistencePromise.resolve(this.lastStreamToken);\n };\n MemoryMutationQueue.prototype.setLastStreamToken = function (transaction, streamToken) {\n this.lastStreamToken = streamToken;\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryMutationQueue.prototype.addMutationBatch = function (transaction, localWriteTime, mutations) {\n assert(mutations.length !== 0, 'Mutation batches should not be empty');\n var batchId = this.nextBatchId;\n this.nextBatchId++;\n if (this.mutationQueue.length > 0) {\n var prior = this.mutationQueue[this.mutationQueue.length - 1];\n assert(prior.batchId < batchId, 'Mutation batchIDs must be monotonically increasing order');\n }\n var batch = new mutation_batch_MutationBatch(batchId, localWriteTime, mutations);\n this.mutationQueue.push(batch);\n // Track references by document key.\n for (var _i = 0, mutations_1 = mutations; _i < mutations_1.length; _i++) {\n var mutation = mutations_1[_i];\n this.batchesByDocumentKey = this.batchesByDocumentKey.add(new reference_set_DocReference(mutation.key, batchId));\n }\n return persistence_promise_PersistencePromise.resolve(batch);\n };\n MemoryMutationQueue.prototype.lookupMutationBatch = function (transaction, batchId) {\n return persistence_promise_PersistencePromise.resolve(this.findMutationBatch(batchId));\n };\n MemoryMutationQueue.prototype.getNextMutationBatchAfterBatchId = function (transaction, batchId) {\n var size = this.mutationQueue.length;\n // All batches with batchId <= this.highestAcknowledgedBatchId have been\n // acknowledged so the first unacknowledged batch after batchID will have a\n // batchID larger than both of these values.\n batchId = Math.max(batchId + 1, this.highestAcknowledgedBatchId);\n // The requested batchId may still be out of range so normalize it to the\n // start of the queue.\n var rawIndex = this.indexOfBatchId(batchId);\n var index = rawIndex < 0 ? 0 : rawIndex;\n // Finally return the first non-tombstone batch.\n for (; index < size; index++) {\n var batch = this.mutationQueue[index];\n if (!batch.isTombstone()) {\n return persistence_promise_PersistencePromise.resolve(batch);\n }\n }\n return persistence_promise_PersistencePromise.resolve(null);\n };\n MemoryMutationQueue.prototype.getAllMutationBatches = function (transaction) {\n return persistence_promise_PersistencePromise.resolve(this.getAllLiveMutationBatchesBeforeIndex(this.mutationQueue.length));\n };\n MemoryMutationQueue.prototype.getAllMutationBatchesThroughBatchId = function (transaction, batchId) {\n var count = this.mutationQueue.length;\n var endIndex = this.indexOfBatchId(batchId);\n if (endIndex < 0) {\n endIndex = 0;\n }\n else if (endIndex >= count) {\n endIndex = count;\n }\n else {\n // The endIndex is in the queue so increment to pull everything in the\n // queue including it.\n endIndex++;\n }\n return persistence_promise_PersistencePromise.resolve(this.getAllLiveMutationBatchesBeforeIndex(endIndex));\n };\n MemoryMutationQueue.prototype.getAllMutationBatchesAffectingDocumentKey = function (transaction, documentKey) {\n var _this = this;\n var start = new reference_set_DocReference(documentKey, 0);\n var end = new reference_set_DocReference(documentKey, Number.POSITIVE_INFINITY);\n var result = [];\n this.batchesByDocumentKey.forEachInRange([start, end], function (ref) {\n assert(documentKey.isEqual(ref.key), \"Should only iterate over a single key's batches\");\n var batch = _this.findMutationBatch(ref.targetOrBatchId);\n assert(batch !== null, 'Batches in the index must exist in the main table');\n result.push(batch);\n });\n return persistence_promise_PersistencePromise.resolve(result);\n };\n MemoryMutationQueue.prototype.getAllMutationBatchesAffectingQuery = function (transaction, query) {\n var _this = this;\n // Use the query path as a prefix for testing if a document matches the\n // query.\n var prefix = query.path;\n var immediateChildrenPathLength = prefix.length + 1;\n // Construct a document reference for actually scanning the index. Unlike\n // the prefix the document key in this reference must have an even number of\n // segments. The empty segment can be used a suffix of the query path\n // because it precedes all other segments in an ordered traversal.\n var startPath = prefix;\n if (!document_key_DocumentKey.isDocumentKey(startPath)) {\n startPath = startPath.child('');\n }\n var start = new reference_set_DocReference(new document_key_DocumentKey(startPath), 0);\n // Find unique batchIDs referenced by all documents potentially matching the\n // query.\n var uniqueBatchIDs = new sorted_set_SortedSet(primitiveComparator);\n this.batchesByDocumentKey.forEachWhile(function (ref) {\n var rowKeyPath = ref.key.path;\n if (!prefix.isPrefixOf(rowKeyPath)) {\n return false;\n }\n else {\n // Rows with document keys more than one segment longer than the query\n // path can't be matches. For example, a query on 'rooms' can't match\n // the document /rooms/abc/messages/xyx.\n // TODO(mcg): we'll need a different scanner when we implement\n // ancestor queries.\n if (rowKeyPath.length === immediateChildrenPathLength) {\n uniqueBatchIDs = uniqueBatchIDs.add(ref.targetOrBatchId);\n }\n return true;\n }\n }, start);\n // Construct an array of matching batches, sorted by batchID to ensure that\n // multiple mutations affecting the same document key are applied in order.\n var result = [];\n uniqueBatchIDs.forEach(function (batchId) {\n var batch = _this.findMutationBatch(batchId);\n if (batch !== null) {\n result.push(batch);\n }\n });\n return persistence_promise_PersistencePromise.resolve(result);\n };\n MemoryMutationQueue.prototype.removeMutationBatches = function (transaction, batches) {\n var batchCount = batches.length;\n assert(batchCount > 0, 'Should not remove mutations when none exist.');\n var firstBatchId = batches[0].batchId;\n var queueCount = this.mutationQueue.length;\n // Find the position of the first batch for removal. This need not be the\n // first entry in the queue.\n var startIndex = this.indexOfExistingBatchId(firstBatchId, 'removed');\n assert(this.mutationQueue[startIndex].batchId === firstBatchId, 'Removed batches must exist in the queue');\n // Check that removed batches are contiguous (while excluding tombstones).\n var batchIndex = 1;\n var queueIndex = startIndex + 1;\n while (batchIndex < batchCount && queueIndex < queueCount) {\n var batch = this.mutationQueue[queueIndex];\n if (batch.isTombstone()) {\n queueIndex++;\n continue;\n }\n assert(batch.batchId === batches[batchIndex].batchId, 'Removed batches must be contiguous in the queue');\n batchIndex++;\n queueIndex++;\n }\n // Only actually remove batches if removing at the front of the queue.\n // Previously rejected batches may have left tombstones in the queue, so\n // expand the removal range to include any tombstones.\n if (startIndex === 0) {\n for (; queueIndex < queueCount; queueIndex++) {\n var batch = this.mutationQueue[queueIndex];\n if (!batch.isTombstone()) {\n break;\n }\n }\n var length_1 = queueIndex - startIndex;\n this.mutationQueue.splice(startIndex, length_1);\n }\n else {\n // Mark the tombstones\n for (var i = startIndex; i < queueIndex; i++) {\n this.mutationQueue[i] = this.mutationQueue[i].toTombstone();\n }\n }\n var references = this.batchesByDocumentKey;\n for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {\n var batch = batches_1[_i];\n var batchId = batch.batchId;\n for (var _a = 0, _b = batch.mutations; _a < _b.length; _a++) {\n var mutation = _b[_a];\n var key = mutation.key;\n if (this.garbageCollector !== null) {\n this.garbageCollector.addPotentialGarbageKey(key);\n }\n var ref = new reference_set_DocReference(key, batchId);\n references = references.delete(ref);\n }\n }\n this.batchesByDocumentKey = references;\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryMutationQueue.prototype.setGarbageCollector = function (garbageCollector) {\n this.garbageCollector = garbageCollector;\n };\n MemoryMutationQueue.prototype.containsKey = function (txn, key) {\n var ref = new reference_set_DocReference(key, 0);\n var firstRef = this.batchesByDocumentKey.firstAfterOrEqual(ref);\n return persistence_promise_PersistencePromise.resolve(key.isEqual(firstRef && firstRef.key));\n };\n MemoryMutationQueue.prototype.performConsistencyCheck = function (txn) {\n if (this.mutationQueue.length === 0) {\n assert(this.batchesByDocumentKey.isEmpty(), 'Document leak -- detected dangling mutation references when queue is empty.');\n }\n return persistence_promise_PersistencePromise.resolve();\n };\n /**\n * A private helper that collects all the mutations batches in the queue up to\n * but not including the given endIndex. All tombstones in the queue are\n * excluded.\n */\n MemoryMutationQueue.prototype.getAllLiveMutationBatchesBeforeIndex = function (endIndex) {\n var result = [];\n for (var i = 0; i < endIndex; i++) {\n var batch = this.mutationQueue[i];\n if (!batch.isTombstone()) {\n result.push(batch);\n }\n }\n return result;\n };\n /**\n * Finds the index of the given batchId in the mutation queue and asserts that\n * the resulting index is within the bounds of the queue.\n *\n * @param batchId The batchId to search for\n * @param action A description of what the caller is doing, phrased in passive\n * form (e.g. \"acknowledged\" in a routine that acknowledges batches).\n */\n MemoryMutationQueue.prototype.indexOfExistingBatchId = function (batchId, action) {\n var index = this.indexOfBatchId(batchId);\n assert(index >= 0 && index < this.mutationQueue.length, 'Batches must exist to be ' + action);\n return index;\n };\n /**\n * Finds the index of the given batchId in the mutation queue. This operation\n * is O(1).\n *\n * @return The computed index of the batch with the given batchId, based on\n * the state of the queue. Note this index can be negative if the requested\n * batchId has already been remvoed from the queue or past the end of the\n * queue if the batchId is larger than the last added batch.\n */\n MemoryMutationQueue.prototype.indexOfBatchId = function (batchId) {\n if (this.mutationQueue.length === 0) {\n // As an index this is past the end of the queue\n return 0;\n }\n // Examine the front of the queue to figure out the difference between the\n // batchId and indexes in the array. Note that since the queue is ordered\n // by batchId, if the first batch has a larger batchId then the requested\n // batchId doesn't exist in the queue.\n var firstBatchId = this.mutationQueue[0].batchId;\n return batchId - firstBatchId;\n };\n /**\n * A version of lookupMutationBatch that doesn't return a promise, this makes\n * other functions that uses this code easier to read and more efficent.\n */\n MemoryMutationQueue.prototype.findMutationBatch = function (batchId) {\n var index = this.indexOfBatchId(batchId);\n if (index < 0 || index >= this.mutationQueue.length) {\n return null;\n }\n var batch = this.mutationQueue[index];\n assert(batch.batchId === batchId, 'If found batch must match');\n return batch.isTombstone() ? null : batch;\n };\n return MemoryMutationQueue;\n}());\n\n\n//# sourceMappingURL=memory_mutation_queue.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/memory_query_cache.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n\nvar memory_query_cache_MemoryQueryCache = /** @class */ (function () {\n function MemoryQueryCache() {\n /**\n * Maps a query to the data about that query\n */\n this.queries = new obj_map_ObjectMap(function (q) { return q.canonicalId(); });\n /** The last received snapshot version. */\n this.lastRemoteSnapshotVersion = snapshot_version_SnapshotVersion.MIN;\n /** The highest numbered target ID encountered. */\n this.highestTargetId = 0;\n /**\n * A ordered bidirectional mapping between documents and the remote target\n * IDs.\n */\n this.references = new reference_set_ReferenceSet();\n }\n MemoryQueryCache.prototype.start = function (transaction) {\n // Nothing to do.\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.getLastRemoteSnapshotVersion = function () {\n return this.lastRemoteSnapshotVersion;\n };\n MemoryQueryCache.prototype.getHighestTargetId = function () {\n return this.highestTargetId;\n };\n MemoryQueryCache.prototype.setLastRemoteSnapshotVersion = function (transaction, snapshotVersion) {\n this.lastRemoteSnapshotVersion = snapshotVersion;\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.addQueryData = function (transaction, queryData) {\n this.queries.set(queryData.query, queryData);\n var targetId = queryData.targetId;\n if (targetId > this.highestTargetId) {\n this.highestTargetId = targetId;\n }\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.removeQueryData = function (transaction, queryData) {\n this.queries.delete(queryData.query);\n this.references.removeReferencesForId(queryData.targetId);\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.getQueryData = function (transaction, query) {\n var queryData = this.queries.get(query) || null;\n return persistence_promise_PersistencePromise.resolve(queryData);\n };\n MemoryQueryCache.prototype.addMatchingKeys = function (txn, keys, targetId) {\n this.references.addReferences(keys, targetId);\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.removeMatchingKeys = function (txn, keys, targetId) {\n this.references.removeReferences(keys, targetId);\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.removeMatchingKeysForTargetId = function (txn, targetId) {\n this.references.removeReferencesForId(targetId);\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.getMatchingKeysForTargetId = function (txn, targetId) {\n var matchingKeys = this.references.referencesForId(targetId);\n return persistence_promise_PersistencePromise.resolve(matchingKeys);\n };\n MemoryQueryCache.prototype.setGarbageCollector = function (gc) {\n this.references.setGarbageCollector(gc);\n };\n MemoryQueryCache.prototype.containsKey = function (txn, key) {\n return this.references.containsKey(txn, key);\n };\n return MemoryQueryCache;\n}());\n\n\n//# sourceMappingURL=memory_query_cache.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/memory_remote_document_cache.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n\nvar memory_remote_document_cache_MemoryRemoteDocumentCache = /** @class */ (function () {\n function MemoryRemoteDocumentCache() {\n this.docs = maybeDocumentMap();\n }\n MemoryRemoteDocumentCache.prototype.addEntry = function (transaction, maybeDocument) {\n this.docs = this.docs.insert(maybeDocument.key, maybeDocument);\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryRemoteDocumentCache.prototype.removeEntry = function (transaction, documentKey) {\n this.docs = this.docs.remove(documentKey);\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryRemoteDocumentCache.prototype.getEntry = function (transaction, documentKey) {\n return persistence_promise_PersistencePromise.resolve(this.docs.get(documentKey));\n };\n MemoryRemoteDocumentCache.prototype.getDocumentsMatchingQuery = function (transaction, query) {\n var results = documentMap();\n // Documents are ordered by key, so we can use a prefix scan to narrow down\n // the documents we need to match the query against.\n var prefix = new document_key_DocumentKey(query.path.child(''));\n var iterator = this.docs.getIteratorFrom(prefix);\n while (iterator.hasNext()) {\n var _a = iterator.getNext(), key = _a.key, maybeDoc = _a.value;\n if (!query.path.isPrefixOf(key.path)) {\n break;\n }\n if (maybeDoc instanceof document_Document && query.matches(maybeDoc)) {\n results = results.insert(maybeDoc.key, maybeDoc);\n }\n }\n return persistence_promise_PersistencePromise.resolve(results);\n };\n return MemoryRemoteDocumentCache;\n}());\n\n\n//# sourceMappingURL=memory_remote_document_cache.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/memory_persistence.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n\n\nvar memory_persistence_LOG_TAG = 'MemoryPersistence';\n/**\n * A memory-backed instance of Persistence. Data is stored only in RAM and\n * not persisted across sessions.\n */\nvar memory_persistence_MemoryPersistence = /** @class */ (function () {\n function MemoryPersistence() {\n /**\n * Note that these are retained here to make it easier to write tests\n * affecting both the in-memory and IndexedDB-backed persistence layers. Tests\n * can create a new LocalStore wrapping this Persistence instance and this\n * will make the in-memory persistence layer behave as if it were actually\n * persisting values.\n */\n this.mutationQueues = {};\n this.remoteDocumentCache = new memory_remote_document_cache_MemoryRemoteDocumentCache();\n this.queryCache = new memory_query_cache_MemoryQueryCache();\n this.started = false;\n }\n MemoryPersistence.prototype.start = function () {\n assert(!this.started, 'MemoryPersistence double-started!');\n this.started = true;\n // No durable state to read on startup.\n return Promise.resolve();\n };\n MemoryPersistence.prototype.shutdown = function () {\n // No durable state to ensure is closed on shutdown.\n assert(this.started, 'MemoryPersistence shutdown without start!');\n this.started = false;\n return Promise.resolve();\n };\n MemoryPersistence.prototype.getMutationQueue = function (user) {\n var queue = this.mutationQueues[user.toKey()];\n if (!queue) {\n queue = new memory_mutation_queue_MemoryMutationQueue();\n this.mutationQueues[user.toKey()] = queue;\n }\n return queue;\n };\n MemoryPersistence.prototype.getQueryCache = function () {\n return this.queryCache;\n };\n MemoryPersistence.prototype.getRemoteDocumentCache = function () {\n return this.remoteDocumentCache;\n };\n MemoryPersistence.prototype.runTransaction = function (action, operation) {\n debug(memory_persistence_LOG_TAG, 'Starting transaction:', action);\n return operation(new MemoryPersistenceTransaction()).toPromise();\n };\n return MemoryPersistence;\n}());\n\n/** Dummy class since memory persistence doesn't actually use transactions. */\nvar MemoryPersistenceTransaction = /** @class */ (function () {\n function MemoryPersistenceTransaction() {\n }\n return MemoryPersistenceTransaction;\n}());\n\n//# sourceMappingURL=memory_persistence.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/no_op_garbage_collector.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n/**\n * A garbage collector implementation that does absolutely nothing. It ignores\n * all addGarbageSource and addPotentialGarbageKey messages and and never\n * produces any garbage.\n */\nvar no_op_garbage_collector_NoOpGarbageCollector = /** @class */ (function () {\n function NoOpGarbageCollector() {\n this.isEager = false;\n }\n NoOpGarbageCollector.prototype.addGarbageSource = function (garbageSource) {\n // Not tracking garbage so don't track sources.\n };\n NoOpGarbageCollector.prototype.removeGarbageSource = function (garbageSource) {\n // Not tracking garbage so don't track sources.\n };\n NoOpGarbageCollector.prototype.addPotentialGarbageKey = function (key) {\n // Not tracking garbage so ignore.\n };\n NoOpGarbageCollector.prototype.collectGarbage = function (txn) {\n return persistence_promise_PersistencePromise.resolve(documentKeySet());\n };\n return NoOpGarbageCollector;\n}());\n\n\n//# sourceMappingURL=no_op_garbage_collector.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/promise.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar Deferred = /** @class */ (function () {\n function Deferred() {\n var _this = this;\n this.promise = new Promise(function (resolve, reject) {\n _this.resolve = resolve;\n _this.reject = reject;\n });\n }\n return Deferred;\n}());\n\n/**\n * Takes an array of values and sequences them using the promise (or value)\n * returned by the supplied callback. The callback for each item is called\n * after the promise is resolved for the previous item.\n * The function returns a promise which is resolved after the promise for\n * the last item is resolved.\n */\nfunction sequence(values, fn, initialValue) {\n var result = Promise.resolve(initialValue);\n values.forEach(function (value) {\n result = result.then(function (lastResult) { return fn(value, lastResult); });\n });\n return result;\n}\n\n//# sourceMappingURL=promise.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/remote/backoff.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\nvar backoff_LOG_TAG = 'ExponentialBackoff';\n/**\n * A helper for running delayed tasks following an exponential backoff curve\n * between attempts.\n *\n * Each delay is made up of a \"base\" delay which follows the exponential\n * backoff curve, and a +/- 50% \"jitter\" that is calculated and added to the\n * base delay. This prevents clients from accidentally synchronizing their\n * delays causing spikes of load to the backend.\n */\nvar backoff_ExponentialBackoff = /** @class */ (function () {\n function ExponentialBackoff(\n /**\n * The initial delay (used as the base delay on the first retry attempt).\n * Note that jitter will still be applied, so the actual delay could be as\n * little as 0.5*initialDelayMs.\n */\n initialDelayMs, \n /**\n * The multiplier to use to determine the extended base delay after each\n * attempt.\n */\n backoffFactor, \n /**\n * The maximum base delay after which no further backoff is performed.\n * Note that jitter will still be applied, so the actual delay could be as\n * much as 1.5*maxDelayMs.\n */\n maxDelayMs) {\n this.initialDelayMs = initialDelayMs;\n this.backoffFactor = backoffFactor;\n this.maxDelayMs = maxDelayMs;\n this.reset();\n }\n /**\n * Resets the backoff delay.\n *\n * The very next backoffAndWait() will have no delay. If it is called again\n * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and\n * subsequent ones will increase according to the backoffFactor.\n */\n ExponentialBackoff.prototype.reset = function () {\n this.currentBaseMs = 0;\n };\n /**\n * Resets the backoff delay to the maximum delay (e.g. for use after a\n * RESOURCE_EXHAUSTED error).\n */\n ExponentialBackoff.prototype.resetToMax = function () {\n this.currentBaseMs = this.maxDelayMs;\n };\n /**\n * Returns a promise that resolves after currentDelayMs, and increases the\n * delay for any subsequent attempts.\n */\n ExponentialBackoff.prototype.backoffAndWait = function () {\n var def = new Deferred();\n // First schedule using the current base (which may be 0 and should be\n // honored as such).\n var delayWithJitterMs = this.currentBaseMs + this.jitterDelayMs();\n if (this.currentBaseMs > 0) {\n debug(backoff_LOG_TAG, \"Backing off for \" + delayWithJitterMs + \" ms \" +\n (\"(base delay: \" + this.currentBaseMs + \" ms)\"));\n }\n setTimeout(function () {\n def.resolve();\n }, delayWithJitterMs);\n // Apply backoff factor to determine next delay and ensure it is within\n // bounds.\n this.currentBaseMs *= this.backoffFactor;\n if (this.currentBaseMs < this.initialDelayMs) {\n this.currentBaseMs = this.initialDelayMs;\n }\n if (this.currentBaseMs > this.maxDelayMs) {\n this.currentBaseMs = this.maxDelayMs;\n }\n return def.promise;\n };\n /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */\n ExponentialBackoff.prototype.jitterDelayMs = function () {\n return (Math.random() - 0.5) * this.currentBaseMs;\n };\n return ExponentialBackoff;\n}());\n\n\n//# sourceMappingURL=backoff.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/remote/persistent_stream.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar persistent_stream___extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n\n\n\n\n\nvar persistent_stream_LOG_TAG = 'PersistentStream';\nvar PersistentStreamState;\n(function (PersistentStreamState) {\n /**\n * The streaming RPC is not running and there's no error condition.\n * Calling `start` will start the stream immediately without backoff.\n * While in this state isStarted will return false.\n */\n PersistentStreamState[PersistentStreamState[\"Initial\"] = 0] = \"Initial\";\n /**\n * The stream is starting, and is waiting for an auth token to attach to\n * the initial request. While in this state, isStarted will return\n * true but isOpen will return false.\n */\n PersistentStreamState[PersistentStreamState[\"Auth\"] = 1] = \"Auth\";\n /**\n * The streaming RPC is up and running. Requests and responses can flow\n * freely. Both isStarted and isOpen will return true.\n */\n PersistentStreamState[PersistentStreamState[\"Open\"] = 2] = \"Open\";\n /**\n * The stream encountered an error. The next start attempt will back off.\n * While in this state isStarted() will return false.\n *\n */\n PersistentStreamState[PersistentStreamState[\"Error\"] = 3] = \"Error\";\n /**\n * An in-between state after an error where the stream is waiting before\n * re-starting. After\n * waiting is complete, the stream will try to open. While in this\n * state isStarted() will return YES but isOpen will return false.\n */\n PersistentStreamState[PersistentStreamState[\"Backoff\"] = 4] = \"Backoff\";\n /**\n * The stream has been explicitly stopped; no further events will be emitted.\n */\n PersistentStreamState[PersistentStreamState[\"Stopped\"] = 5] = \"Stopped\";\n})(PersistentStreamState || (PersistentStreamState = {}));\n/**\n * Initial backoff time in milliseconds after an error.\n * Set to 1s according to https://cloud.google.com/apis/design/errors.\n */\nvar BACKOFF_INITIAL_DELAY_MS = 1000;\n/** Maximum backoff time in milliseconds */\nvar BACKOFF_MAX_DELAY_MS = 60 * 1000;\nvar BACKOFF_FACTOR = 1.5;\n/** The time a stream stays open after it is marked idle. */\nvar IDLE_TIMEOUT_MS = 60 * 1000;\n/**\n * A PersistentStream is an abstract base class that represents a streaming RPC\n * to the Firestore backend. It's built on top of the connections own support\n * for streaming RPCs, and adds several critical features for our clients:\n *\n * - Exponential backoff on failure\n * - Authentication via CredentialsProvider\n * - Dispatching all callbacks into the shared worker queue\n *\n * Subclasses of PersistentStream implement serialization of models to and\n * from the JSON representation of the protocol buffers for a specific\n * streaming RPC.\n *\n * ## Starting and Stopping\n *\n * Streaming RPCs are stateful and need to be `start`ed before messages can\n * be sent and received. The PersistentStream will call the onOpen function\n * of the listener once the stream is ready to accept requests.\n *\n * Should a `start` fail, PersistentStream will call the registered\n * onClose with a FirestoreError indicating what went wrong.\n *\n * A PersistentStream can be started and stopped repeatedly.\n *\n * Generic types:\n * SendType: The type of the outgoing message of the underlying\n * connection stream\n * ReceiveType: The type of the incoming message of the underlying\n * connection stream\n * ListenerType: The type of the listener that will be used for callbacks\n */\nvar persistent_stream_PersistentStream = /** @class */ (function () {\n function PersistentStream(queue, connection, credentialsProvider, \n // Used for faster retries in testing\n initialBackoffDelay) {\n this.queue = queue;\n this.connection = connection;\n this.credentialsProvider = credentialsProvider;\n this.idle = false;\n this.stream = null;\n this.listener = null;\n this.backoff = new backoff_ExponentialBackoff(initialBackoffDelay ? initialBackoffDelay : BACKOFF_INITIAL_DELAY_MS, BACKOFF_FACTOR, BACKOFF_MAX_DELAY_MS);\n this.state = PersistentStreamState.Initial;\n }\n /**\n * Returns true if `start` has been called and no error has occurred. True\n * indicates the stream is open or in the process of opening (which\n * encompasses respecting backoff, getting auth tokens, and starting the\n * actual RPC). Use `isOpen` to determine if the stream is open and ready for\n * outbound requests.\n */\n PersistentStream.prototype.isStarted = function () {\n return (this.state === PersistentStreamState.Backoff ||\n this.state === PersistentStreamState.Auth ||\n this.state === PersistentStreamState.Open);\n };\n /**\n * Returns true if the underlying RPC is open (the openHandler has been\n * called) and the stream is ready for outbound requests.\n */\n PersistentStream.prototype.isOpen = function () {\n return this.state === PersistentStreamState.Open;\n };\n /**\n * Starts the RPC. Only allowed if isStarted returns false. The stream is\n * not immediately ready for use: onOpen will be invoked when the RPC is ready\n * for outbound requests, at which point isOpen will return true.\n *\n * When start returns, isStarted will return true.\n */\n PersistentStream.prototype.start = function (listener) {\n if (this.state === PersistentStreamState.Error) {\n this.performBackoff(listener);\n return;\n }\n assert(this.state === PersistentStreamState.Initial, 'Already started');\n this.listener = listener;\n this.auth();\n };\n /**\n * Stops the RPC. This call is idempotent and allowed regardless of the\n * current isStarted state.\n *\n * When stop returns, isStarted and isOpen will both return false.\n */\n PersistentStream.prototype.stop = function () {\n if (this.isStarted()) {\n this.close(PersistentStreamState.Stopped);\n }\n };\n /**\n * After an error the stream will usually back off on the next attempt to\n * start it. If the error warrants an immediate restart of the stream, the\n * sender can use this to indicate that the receiver should not back off.\n *\n * Each error will call the onClose function. That function can decide to\n * inhibit backoff if required.\n */\n PersistentStream.prototype.inhibitBackoff = function () {\n assert(!this.isStarted(), 'Can only inhibit backoff in a stopped state');\n this.state = PersistentStreamState.Initial;\n this.backoff.reset();\n };\n /**\n * Initializes the idle timer. If no write takes place within one minute, the\n * WebChannel stream will be closed.\n */\n PersistentStream.prototype.markIdle = function () {\n var _this = this;\n this.idle = true;\n this.queue\n .schedule(function () {\n return _this.handleIdleCloseTimer();\n }, IDLE_TIMEOUT_MS)\n .catch(function (err) {\n // When the AsyncQueue gets drained during testing, pending Promises\n // (including these idle checks) will get rejected. We special-case\n // these cancelled idle checks to make sure that these specific Promise\n // rejections are not considered unhandled.\n assert(err.code === Code.CANCELLED, \"Received unexpected error in idle timeout closure. Expected CANCELLED, but was: \" + err);\n });\n };\n /** Sends a message to the underlying stream. */\n PersistentStream.prototype.sendRequest = function (msg) {\n this.cancelIdleCheck();\n this.stream.send(msg);\n };\n /** Called by the idle timer when the stream should close due to inactivity. */\n PersistentStream.prototype.handleIdleCloseTimer = function () {\n if (this.isOpen() && this.idle) {\n // When timing out an idle stream there's no reason to force the stream into backoff when\n // it restarts so set the stream state to Initial instead of Error.\n return this.close(PersistentStreamState.Initial);\n }\n return Promise.resolve();\n };\n /** Marks the stream as active again. */\n PersistentStream.prototype.cancelIdleCheck = function () {\n this.idle = false;\n };\n /**\n * Closes the stream and cleans up as necessary:\n *\n * * closes the underlying GRPC stream;\n * * calls the onClose handler with the given 'error';\n * * sets internal stream state to 'finalState';\n * * adjusts the backoff timer based on the error\n *\n * A new stream can be opened by calling `start` unless `finalState` is set to\n * `PersistentStreamState.Stopped`.\n *\n * @param finalState the intended state of the stream after closing.\n * @param error the error the connection was closed with.\n */\n PersistentStream.prototype.close = function (finalState, error) {\n assert(finalState === PersistentStreamState.Error || isNullOrUndefined(error), \"Can't provide an error when not in an error state.\");\n this.cancelIdleCheck();\n if (finalState !== PersistentStreamState.Error) {\n // If this is an intentional close ensure we don't delay our next connection attempt.\n this.backoff.reset();\n }\n else if (error && error.code === Code.RESOURCE_EXHAUSTED) {\n // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)\n log_error(error.toString());\n log_error('Using maximum backoff delay to prevent overloading the backend.');\n this.backoff.resetToMax();\n }\n // Clean up the underlying stream because we are no longer interested in events.\n if (this.stream !== null) {\n this.tearDown();\n this.stream.close();\n this.stream = null;\n }\n // This state must be assigned before calling onClose() to allow the callback to\n // inhibit backoff or otherwise manipulate the state in its non-started state.\n this.state = finalState;\n var listener = this.listener;\n // Clear the listener to avoid bleeding of events from the underlying streams.\n this.listener = null;\n // If the caller explicitly requested a stream stop, don't notify them of a closing stream (it\n // could trigger undesirable recovery logic, etc.).\n if (finalState !== PersistentStreamState.Stopped) {\n return listener.onClose(error);\n }\n else {\n return Promise.resolve();\n }\n };\n /**\n * Can be overridden to perform additional cleanup before the stream is closed.\n * Calling super.tearDown() is not required.\n */\n PersistentStream.prototype.tearDown = function () { };\n PersistentStream.prototype.auth = function () {\n var _this = this;\n assert(this.state === PersistentStreamState.Initial, 'Must be in initial state to auth');\n this.state = PersistentStreamState.Auth;\n this.credentialsProvider.getToken(/*forceRefresh=*/ false).then(function (token) {\n // Normally we'd have to schedule the callback on the AsyncQueue.\n // However, the following calls are safe to be called outside the\n // AsyncQueue since they don't chain asynchronous calls\n _this.startStream(token);\n }, function (error) {\n _this.queue.schedule(function () {\n if (_this.state !== PersistentStreamState.Stopped) {\n // Stream can be stopped while waiting for authorization.\n var rpcError = new FirestoreError(Code.UNKNOWN, 'Fetching auth token failed: ' + error.message);\n return _this.handleStreamClose(rpcError);\n }\n else {\n return Promise.resolve();\n }\n });\n });\n };\n PersistentStream.prototype.startStream = function (token) {\n var _this = this;\n if (this.state === PersistentStreamState.Stopped) {\n // Stream can be stopped while waiting for authorization.\n return;\n }\n assert(this.state === PersistentStreamState.Auth, 'Trying to start stream in a non-auth state');\n // Helper function to dispatch to AsyncQueue and make sure that any\n // close will seem instantaneous and events are prevented from being\n // raised after the close call\n var dispatchIfStillActive = function (stream, fn) {\n _this.queue.schedule(function () {\n // Only raise events if the stream instance has not changed\n if (_this.stream === stream) {\n return fn();\n }\n else {\n return Promise.resolve();\n }\n });\n };\n // Only start stream if listener has not changed\n if (this.listener !== null) {\n var currentStream_1 = this.startRpc(token);\n this.stream = currentStream_1;\n this.stream.onOpen(function () {\n dispatchIfStillActive(currentStream_1, function () {\n assert(_this.state === PersistentStreamState.Auth, 'Expected stream to be in state auth, but was ' + _this.state);\n _this.state = PersistentStreamState.Open;\n return _this.listener.onOpen();\n });\n });\n this.stream.onClose(function (error) {\n dispatchIfStillActive(currentStream_1, function () {\n return _this.handleStreamClose(error);\n });\n });\n this.stream.onMessage(function (msg) {\n dispatchIfStillActive(currentStream_1, function () {\n return _this.onMessage(msg);\n });\n });\n }\n };\n PersistentStream.prototype.performBackoff = function (listener) {\n var _this = this;\n assert(this.state === PersistentStreamState.Error, 'Should only perform backoff in an error case');\n this.state = PersistentStreamState.Backoff;\n this.backoff.backoffAndWait().then(function () {\n // Backoff does not run on the AsyncQueue, so we need to reschedule to\n // make sure the queue blocks\n _this.queue.schedule(function () {\n if (_this.state === PersistentStreamState.Stopped) {\n // Stream can be stopped while waiting for backoff to complete.\n return Promise.resolve();\n }\n _this.state = PersistentStreamState.Initial;\n _this.start(listener);\n assert(_this.isStarted(), 'PersistentStream should have started');\n return Promise.resolve();\n });\n });\n };\n PersistentStream.prototype.handleStreamClose = function (error) {\n assert(this.isStarted(), \"Can't handle server close on non-started stream\");\n debug(persistent_stream_LOG_TAG, \"close with error: \" + error);\n this.stream = null;\n // In theory the stream could close cleanly, however, in our current model\n // we never expect this to happen because if we stop a stream ourselves,\n // this callback will never be called. To prevent cases where we retry\n // without a backoff accidentally, we set the stream to error in all cases.\n return this.close(PersistentStreamState.Error, error);\n };\n return PersistentStream;\n}());\n\n/**\n * A PersistentStream that implements the Listen RPC.\n *\n * Once the Listen stream has called the openHandler, any number of listen and\n * unlisten calls calls can be sent to control what changes will be sent from\n * the server for ListenResponses.\n */\nvar PersistentListenStream = /** @class */ (function (_super) {\n persistent_stream___extends(PersistentListenStream, _super);\n function PersistentListenStream(databaseInfo, queue, connection, credentials, serializer, initialBackoffDelay) {\n var _this = _super.call(this, queue, connection, credentials, initialBackoffDelay) || this;\n _this.databaseInfo = databaseInfo;\n _this.serializer = serializer;\n return _this;\n }\n PersistentListenStream.prototype.startRpc = function (token) {\n return this.connection.openStream('Listen', token);\n };\n PersistentListenStream.prototype.onMessage = function (watchChangeProto) {\n // A successful response means the stream is healthy\n this.backoff.reset();\n var watchChange = this.serializer.fromWatchChange(watchChangeProto);\n var snapshot = this.serializer.versionFromListenResponse(watchChangeProto);\n return this.listener.onWatchChange(watchChange, snapshot);\n };\n /**\n * Registers interest in the results of the given query. If the query\n * includes a resumeToken it will be included in the request. Results that\n * affect the query will be streamed back as WatchChange messages that\n * reference the targetId.\n */\n PersistentListenStream.prototype.watch = function (queryData) {\n var request = {};\n request.database = this.serializer.encodedDatabaseId;\n request.addTarget = this.serializer.toTarget(queryData);\n var labels = this.serializer.toListenRequestLabels(queryData);\n if (labels) {\n request.labels = labels;\n }\n this.sendRequest(request);\n };\n /**\n * Unregisters interest in the results of the query associated with the\n * given targetId.\n */\n PersistentListenStream.prototype.unwatch = function (targetId) {\n var request = {};\n request.database = this.serializer.encodedDatabaseId;\n request.removeTarget = targetId;\n this.sendRequest(request);\n };\n return PersistentListenStream;\n}(persistent_stream_PersistentStream));\n\n/**\n * A Stream that implements the Write RPC.\n *\n * The Write RPC requires the caller to maintain special streamToken\n * state in between calls, to help the server understand which responses the\n * client has processed by the time the next request is made. Every response\n * will contain a streamToken; this value must be passed to the next\n * request.\n *\n * After calling start() on this stream, the next request must be a handshake,\n * containing whatever streamToken is on hand. Once a response to this\n * request is received, all pending mutations may be submitted. When\n * submitting multiple batches of mutations at the same time, it's\n * okay to use the same streamToken for the calls to writeMutations.\n *\n * TODO(b/33271235): Use proto types\n */\nvar persistent_stream_PersistentWriteStream = /** @class */ (function (_super) {\n persistent_stream___extends(PersistentWriteStream, _super);\n function PersistentWriteStream(databaseInfo, queue, connection, credentials, serializer, initialBackoffDelay) {\n var _this = _super.call(this, queue, connection, credentials, initialBackoffDelay) || this;\n _this.databaseInfo = databaseInfo;\n _this.serializer = serializer;\n _this.handshakeComplete_ = false;\n return _this;\n }\n Object.defineProperty(PersistentWriteStream.prototype, \"handshakeComplete\", {\n /**\n * Tracks whether or not a handshake has been successfully exchanged and\n * the stream is ready to accept mutations.\n */\n get: function () {\n return this.handshakeComplete_;\n },\n enumerable: true,\n configurable: true\n });\n // Override of PersistentStream.start\n PersistentWriteStream.prototype.start = function (listener) {\n this.handshakeComplete_ = false;\n _super.prototype.start.call(this, listener);\n };\n PersistentWriteStream.prototype.tearDown = function () {\n if (this.handshakeComplete_) {\n this.writeMutations([]);\n }\n };\n PersistentWriteStream.prototype.startRpc = function (token) {\n return this.connection.openStream('Write', token);\n };\n PersistentWriteStream.prototype.onMessage = function (responseProto) {\n // Always capture the last stream token.\n assert(!!responseProto.streamToken, 'Got a write response without a stream token');\n this.lastStreamToken = responseProto.streamToken;\n if (!this.handshakeComplete_) {\n // The first response is always the handshake response\n assert(!responseProto.writeResults || responseProto.writeResults.length === 0, 'Got mutation results for handshake');\n this.handshakeComplete_ = true;\n return this.listener.onHandshakeComplete();\n }\n else {\n // A successful first write response means the stream is healthy,\n // Note, that we could consider a successful handshake healthy, however,\n // the write itself might be causing an error we want to back off from.\n this.backoff.reset();\n var results = this.serializer.fromWriteResults(responseProto.writeResults);\n var commitVersion = this.serializer.fromVersion(responseProto.commitTime);\n return this.listener.onMutationResult(commitVersion, results);\n }\n };\n /**\n * Sends an initial streamToken to the server, performing the handshake\n * required to make the StreamingWrite RPC work. Subsequent\n * calls should wait until onHandshakeComplete was called.\n */\n PersistentWriteStream.prototype.writeHandshake = function () {\n assert(this.isOpen(), 'Writing handshake requires an opened stream');\n assert(!this.handshakeComplete_, 'Handshake already completed');\n // TODO(dimond): Support stream resumption. We intentionally do not set the\n // stream token on the handshake, ignoring any stream token we might have.\n var request = {};\n request.database = this.serializer.encodedDatabaseId;\n this.sendRequest(request);\n };\n /** Sends a group of mutations to the Firestore backend to apply. */\n PersistentWriteStream.prototype.writeMutations = function (mutations) {\n var _this = this;\n assert(this.isOpen(), 'Writing mutations requires an opened stream');\n assert(this.handshakeComplete_, 'Handshake must be complete before writing mutations');\n assert(this.lastStreamToken.length > 0, 'Trying to write mutation without a token');\n var request = {\n // Protos are typed with string, but we support UInt8Array on Node\n // tslint:disable-next-line:no-any\n streamToken: this.lastStreamToken,\n writes: mutations.map(function (mutation) { return _this.serializer.toMutation(mutation); })\n };\n this.sendRequest(request);\n };\n return PersistentWriteStream;\n}(persistent_stream_PersistentStream));\n\n\n//# sourceMappingURL=persistent_stream.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/remote/datastore.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n/**\n * Datastore is a wrapper around the external Google Cloud Datastore grpc API,\n * which provides an interface that is more convenient for the rest of the\n * client SDK architecture to consume.\n */\nvar datastore_Datastore = /** @class */ (function () {\n function Datastore(databaseInfo, queue, connection, credentials, serializer, initialBackoffDelay) {\n this.databaseInfo = databaseInfo;\n this.queue = queue;\n this.connection = connection;\n this.credentials = credentials;\n this.serializer = serializer;\n this.initialBackoffDelay = initialBackoffDelay;\n }\n Datastore.prototype.newPersistentWriteStream = function () {\n return new persistent_stream_PersistentWriteStream(this.databaseInfo, this.queue, this.connection, this.credentials, this.serializer, this.initialBackoffDelay);\n };\n Datastore.prototype.newPersistentWatchStream = function () {\n return new PersistentListenStream(this.databaseInfo, this.queue, this.connection, this.credentials, this.serializer, this.initialBackoffDelay);\n };\n Datastore.prototype.commit = function (mutations) {\n var _this = this;\n var params = {\n database: this.serializer.encodedDatabaseId,\n writes: mutations.map(function (m) { return _this.serializer.toMutation(m); })\n };\n return this.invokeRPC('Commit', params).then(function (response) {\n return _this.serializer.fromWriteResults(response.writeResults);\n });\n };\n Datastore.prototype.lookup = function (keys) {\n var _this = this;\n var params = {\n database: this.serializer.encodedDatabaseId,\n documents: keys.map(function (k) { return _this.serializer.toName(k); })\n };\n return this.invokeStreamingRPC('BatchGetDocuments', params).then(function (response) {\n var docs = maybeDocumentMap();\n response.forEach(function (proto) {\n var doc = _this.serializer.fromMaybeDocument(proto);\n docs = docs.insert(doc.key, doc);\n });\n var result = [];\n keys.forEach(function (key) {\n var doc = docs.get(key);\n assert(!!doc, 'Missing entity in write response for ' + key);\n result.push(doc);\n });\n return result;\n });\n };\n /** Gets an auth token and invokes the provided RPC. */\n Datastore.prototype.invokeRPC = function (rpcName, request) {\n var _this = this;\n // TODO(mikelehen): Retry (with backoff) on token failures?\n return this.credentials.getToken(/*forceRefresh=*/ false).then(function (token) {\n return _this.connection.invokeRPC(rpcName, request, token);\n });\n };\n /** Gets an auth token and invokes the provided RPC with streamed results. */\n Datastore.prototype.invokeStreamingRPC = function (rpcName, request) {\n var _this = this;\n // TODO(mikelehen): Retry (with backoff) on token failures?\n return this.credentials.getToken(/*forceRefresh=*/ false).then(function (token) {\n return _this.connection.invokeStreamingRPC(rpcName, request, token);\n });\n };\n return Datastore;\n}());\n\n\n//# sourceMappingURL=datastore.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/transaction.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n\n\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */\nvar transaction_Transaction = /** @class */ (function () {\n function Transaction(datastore) {\n this.datastore = datastore;\n // The version of each document that was read during this transaction.\n this.readVersions = documentVersionMap();\n this.mutations = [];\n this.committed = false;\n }\n Transaction.prototype.recordVersion = function (doc) {\n var docVersion = doc.version;\n if (doc instanceof document_NoDocument) {\n // For deleted docs, we must use baseVersion 0 when we overwrite them.\n docVersion = snapshot_version_SnapshotVersion.forDeletedDoc();\n }\n var existingVersion = this.readVersions.get(doc.key);\n if (existingVersion !== null) {\n if (!docVersion.isEqual(existingVersion)) {\n // This transaction will fail no matter what.\n throw new FirestoreError(Code.ABORTED, 'Document version changed between two reads.');\n }\n }\n else {\n this.readVersions = this.readVersions.insert(doc.key, docVersion);\n }\n };\n Transaction.prototype.lookup = function (keys) {\n var _this = this;\n if (this.committed) {\n return Promise.reject('Transaction has already completed.');\n }\n if (this.mutations.length > 0) {\n return Promise.reject('Transactions lookups are invalid after writes.');\n }\n return this.datastore.lookup(keys).then(function (docs) {\n docs.forEach(function (doc) { return _this.recordVersion(doc); });\n return docs;\n });\n };\n Transaction.prototype.write = function (mutations) {\n if (this.committed) {\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'Transaction has already completed.');\n }\n this.mutations = this.mutations.concat(mutations);\n };\n /**\n * Returns the version of this document when it was read in this transaction,\n * as a precondition, or no precondition if it was not read.\n */\n Transaction.prototype.precondition = function (key) {\n var version = this.readVersions.get(key);\n if (version) {\n return mutation_Precondition.updateTime(version);\n }\n else {\n return mutation_Precondition.NONE;\n }\n };\n /**\n * Returns the precondition for a document if the operation is an update.\n */\n Transaction.prototype.preconditionForUpdate = function (key) {\n var version = this.readVersions.get(key);\n if (version && version.isEqual(snapshot_version_SnapshotVersion.forDeletedDoc())) {\n // The document doesn't exist, so fail the transaction.\n throw new FirestoreError(Code.FAILED_PRECONDITION, \"Can't update a document that doesn't exist.\");\n }\n else if (version) {\n // Document exists, base precondition on document update time.\n return mutation_Precondition.updateTime(version);\n }\n else {\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return mutation_Precondition.exists(true);\n }\n };\n Transaction.prototype.set = function (key, data) {\n this.write(data.toMutations(key, this.precondition(key)));\n };\n Transaction.prototype.update = function (key, data) {\n this.write(data.toMutations(key, this.preconditionForUpdate(key)));\n };\n Transaction.prototype.delete = function (key) {\n this.write([new mutation_DeleteMutation(key, this.precondition(key))]);\n // Since the delete will be applied before all following writes, we need to\n // ensure that the precondition for the next write will be exists: false.\n this.readVersions = this.readVersions.insert(key, snapshot_version_SnapshotVersion.forDeletedDoc());\n };\n Transaction.prototype.commit = function () {\n var _this = this;\n var unwritten = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach(function (mutation) {\n unwritten = unwritten.remove(mutation.key);\n });\n if (!unwritten.isEmpty()) {\n return Promise.reject(Error('Every document read in a transaction must also be written.'));\n }\n return this.datastore.commit(this.mutations).then(function () {\n _this.committed = true;\n });\n };\n return Transaction;\n}());\n\n\n//# sourceMappingURL=transaction.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/remote/remote_store.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nvar remote_store_LOG_TAG = 'RemoteStore';\n// TODO(b/35853402): Negotiate this with the stream.\nvar MAX_PENDING_WRITES = 10;\n// The RemoteStore notifies an onlineStateHandler with OnlineState.Failed if we\n// fail to connect to the backend. This subsequently triggers get() requests to\n// fail or use cached data, etc. Unfortunately, our connections have\n// historically been subject to various transient failures. So we wait for\n// multiple failures before notifying the onlineStateHandler.\nvar ONLINE_ATTEMPTS_BEFORE_FAILURE = 2;\n/**\n * RemoteStore - An interface to remotely stored data, basically providing a\n * wrapper around the Datastore that is more reliable for the rest of the\n * system.\n *\n * RemoteStore is responsible for maintaining the connection to the server.\n * - maintaining a list of active listens.\n * - reconnecting when the connection is dropped.\n * - resuming all the active listens on reconnect.\n *\n * RemoteStore handles all incoming events from the Datastore.\n * - listening to the watch stream and repackaging the events as RemoteEvents\n * - notifying SyncEngine of any changes to the active listens.\n *\n * RemoteStore takes writes from other components and handles them reliably.\n * - pulling pending mutations from LocalStore and sending them to Datastore.\n * - retrying mutations that failed because of network problems.\n * - acking mutations to the SyncEngine once they are accepted or rejected.\n */\nvar remote_store_RemoteStore = /** @class */ (function () {\n function RemoteStore(\n /**\n * The local store, used to fill the write pipeline with outbound\n * mutations and resolve existence filter mismatches.\n */\n localStore, \n /** The client-side proxy for interacting with the backend. */\n datastore, onlineStateHandler) {\n this.localStore = localStore;\n this.datastore = datastore;\n this.onlineStateHandler = onlineStateHandler;\n this.pendingWrites = [];\n this.lastBatchSeen = BATCHID_UNKNOWN;\n /**\n * A mapping of watched targets that the client cares about tracking and the\n * user has explicitly called a 'listen' for this target.\n *\n * These targets may or may not have been sent to or acknowledged by the\n * server. On re-establishing the listen stream, these targets should be sent\n * to the server. The targets removed with unlistens are removed eagerly\n * without waiting for confirmation from the listen stream.\n */\n this.listenTargets = {};\n /**\n * A mapping of targetId to pending acks needed.\n *\n * If a targetId is present in this map, then we're waiting for watch to\n * acknowledge a removal or addition of the target. If a target is not in this\n * mapping, and it's in the listenTargets map, then we consider the target to\n * be active.\n *\n * We increment the count here every time we issue a request over the stream\n * to watch or unwatch. We then decrement the count every time we get a target\n * added or target removed message from the server. Once the count is equal to\n * 0 we know that the client and server are in the same state (once this state\n * is reached the targetId is removed from the map to free the memory).\n */\n this.pendingTargetResponses = {};\n this.accumulatedWatchChanges = [];\n this.watchStream = null;\n this.writeStream = null;\n /**\n * The online state of the watch stream. The state is set to healthy if and\n * only if there are messages received by the backend.\n */\n this.watchStreamOnlineState = OnlineState.Unknown;\n /** A count of consecutive failures to open the stream. */\n this.watchStreamFailures = 0;\n /** Whether the client should fire offline warning. */\n this.shouldWarnOffline = true;\n }\n /**\n * Starts up the remote store, creating streams, restoring state from\n * LocalStore, etc.\n */\n RemoteStore.prototype.start = function () {\n return this.enableNetwork();\n };\n /**\n * Updates our OnlineState to the new state, updating local state\n * and notifying the onlineStateHandler as appropriate. Idempotent.\n */\n RemoteStore.prototype.updateOnlineState = function (newState) {\n if (newState !== this.watchStreamOnlineState) {\n if (newState === OnlineState.Healthy) {\n // We've connected to watch at least once. Don't warn the developer about\n // being offline going forward.\n this.shouldWarnOffline = false;\n }\n else if (newState === OnlineState.Unknown) {\n // The state is set to unknown when a healthy stream is closed (e.g. due to\n // a token timeout) or when we have no active listens and therefore there's\n // no need to start the stream. Assuming there is (possibly in the future)\n // an active listen, then we will eventually move to state Online or Failed,\n // but we always want to make at least ONLINE_ATTEMPTS_BEFORE_FAILURE\n // attempts before failing, so we reset the count here.\n this.watchStreamFailures = 0;\n }\n this.watchStreamOnlineState = newState;\n this.onlineStateHandler(newState);\n }\n };\n /**\n * Updates our OnlineState as appropriate after the watch stream reports a\n * failure. The first failure moves us to the 'Unknown' state. We then may\n * allow multiple failures (based on ONLINE_ATTEMPTS_BEFORE_FAILURE) before we\n * actually transition to OnlineState.Failed.\n */\n RemoteStore.prototype.updateOnlineStateAfterFailure = function () {\n if (this.watchStreamOnlineState === OnlineState.Healthy) {\n this.updateOnlineState(OnlineState.Unknown);\n }\n else {\n this.watchStreamFailures++;\n if (this.watchStreamFailures >= ONLINE_ATTEMPTS_BEFORE_FAILURE) {\n if (this.shouldWarnOffline) {\n log_error('Could not reach Firestore backend.');\n this.shouldWarnOffline = false;\n }\n this.updateOnlineState(OnlineState.Failed);\n }\n }\n };\n RemoteStore.prototype.isNetworkEnabled = function () {\n assert((this.watchStream == null) === (this.writeStream == null), 'WatchStream and WriteStream should both be null or non-null');\n return this.watchStream != null;\n };\n /** Re-enables the network. Idempotent. */\n RemoteStore.prototype.enableNetwork = function () {\n var _this = this;\n if (this.isNetworkEnabled()) {\n return Promise.resolve();\n }\n // Create new streams (but note they're not started yet).\n this.watchStream = this.datastore.newPersistentWatchStream();\n this.writeStream = this.datastore.newPersistentWriteStream();\n // Load any saved stream token from persistent storage\n return this.localStore.getLastStreamToken().then(function (token) {\n _this.writeStream.lastStreamToken = token;\n if (_this.shouldStartWatchStream()) {\n _this.startWatchStream();\n }\n _this.updateOnlineState(OnlineState.Unknown);\n return _this.fillWritePipeline(); // This may start the writeStream.\n });\n };\n /**\n * Temporarily disables the network. The network can be re-enabled using\n * enableNetwork().\n */\n RemoteStore.prototype.disableNetwork = function () {\n this.disableNetworkInternal();\n // Set the OnlineState to failed so get()'s return from cache, etc.\n this.updateOnlineState(OnlineState.Failed);\n return Promise.resolve();\n };\n /**\n * Disables the network, if it is currently enabled.\n */\n RemoteStore.prototype.disableNetworkInternal = function () {\n if (this.isNetworkEnabled()) {\n // NOTE: We're guaranteed not to get any further events from these streams (not even a close\n // event).\n this.watchStream.stop();\n this.writeStream.stop();\n this.cleanUpWatchStreamState();\n this.cleanUpWriteStreamState();\n this.writeStream = null;\n this.watchStream = null;\n }\n };\n RemoteStore.prototype.shutdown = function () {\n debug(remote_store_LOG_TAG, 'RemoteStore shutting down.');\n this.disableNetworkInternal();\n // Set the OnlineState to Unknown (rather than Failed) to avoid potentially\n // triggering spurious listener events with cached data, etc.\n this.updateOnlineState(OnlineState.Unknown);\n return Promise.resolve();\n };\n /** Starts new listen for the given query. Uses resume token if provided */\n RemoteStore.prototype.listen = function (queryData) {\n assert(!contains(this.listenTargets, queryData.targetId), 'listen called with duplicate targetId!');\n // Mark this as something the client is currently listening for.\n this.listenTargets[queryData.targetId] = queryData;\n if (this.shouldStartWatchStream()) {\n // The listen will be sent in onWatchStreamOpen\n this.startWatchStream();\n }\n else if (this.isNetworkEnabled() && this.watchStream.isOpen()) {\n this.sendWatchRequest(queryData);\n }\n };\n /** Removes the listen from server */\n RemoteStore.prototype.unlisten = function (targetId) {\n assert(contains(this.listenTargets, targetId), 'unlisten called without assigned target ID!');\n var queryData = this.listenTargets[targetId];\n delete this.listenTargets[targetId];\n if (this.isNetworkEnabled() && this.watchStream.isOpen()) {\n this.sendUnwatchRequest(targetId);\n if (isEmpty(this.listenTargets)) {\n this.watchStream.markIdle();\n }\n }\n };\n /**\n * We need to increment the the expected number of pending responses we're due\n * from watch so we wait for the ack to process any messages from this target.\n */\n RemoteStore.prototype.sendWatchRequest = function (queryData) {\n this.recordPendingTargetRequest(queryData.targetId);\n this.watchStream.watch(queryData);\n };\n /**\n * We need to increment the expected number of pending responses we're due\n * from watch so we wait for the removal on the server before we process any\n * messages from this target.\n */\n RemoteStore.prototype.sendUnwatchRequest = function (targetId) {\n this.recordPendingTargetRequest(targetId);\n this.watchStream.unwatch(targetId);\n };\n /**\n * Increment the mapping of how many acks are needed from watch before we can\n * consider the server to be 'in-sync' with the client's active targets.\n */\n RemoteStore.prototype.recordPendingTargetRequest = function (targetId) {\n // For each request we get we need to record we need a response for it.\n this.pendingTargetResponses[targetId] =\n (this.pendingTargetResponses[targetId] || 0) + 1;\n };\n RemoteStore.prototype.startWatchStream = function () {\n assert(this.shouldStartWatchStream(), 'startWriteStream() called when shouldStartWatchStream() is false.');\n this.watchStream.start({\n onOpen: this.onWatchStreamOpen.bind(this),\n onClose: this.onWatchStreamClose.bind(this),\n onWatchChange: this.onWatchStreamChange.bind(this)\n });\n };\n /**\n * Returns whether the watch stream should be started because there are\n * active targets trying to be listened too\n */\n RemoteStore.prototype.shouldStartWatchStream = function () {\n return (this.isNetworkEnabled() &&\n !this.watchStream.isStarted() &&\n !isEmpty(this.listenTargets));\n };\n RemoteStore.prototype.cleanUpWatchStreamState = function () {\n // If the connection is closed then we'll never get a snapshot version for\n // the accumulated changes and so we'll never be able to complete the batch.\n // When we start up again the server is going to resend these changes\n // anyway, so just toss the accumulated state.\n this.accumulatedWatchChanges = [];\n this.pendingTargetResponses = {};\n };\n RemoteStore.prototype.onWatchStreamOpen = function () {\n var _this = this;\n // TODO(b/35852690): close the stream again (with some timeout?) if no watch\n // targets are active\n forEachNumber(this.listenTargets, function (targetId, queryData) {\n _this.sendWatchRequest(queryData);\n });\n return Promise.resolve();\n };\n RemoteStore.prototype.onWatchStreamClose = function (error) {\n assert(this.isNetworkEnabled(), 'onWatchStreamClose() should only be called when the network is enabled');\n this.cleanUpWatchStreamState();\n // If there was an error, retry the connection.\n if (this.shouldStartWatchStream()) {\n this.updateOnlineStateAfterFailure();\n this.startWatchStream();\n }\n else {\n // No need to restart watch stream because there are no active targets.\n // The online state is set to unknown because there is no active attempt\n // at establishing a connection\n this.updateOnlineState(OnlineState.Unknown);\n }\n return Promise.resolve();\n };\n RemoteStore.prototype.onWatchStreamChange = function (watchChange, snapshotVersion) {\n // Mark the connection as healthy because we got a message from the server\n this.updateOnlineState(OnlineState.Healthy);\n if (watchChange instanceof watch_change_WatchTargetChange &&\n watchChange.state === WatchTargetChangeState.Removed &&\n watchChange.cause) {\n // There was an error on a target, don't wait for a consistent snapshot\n // to raise events\n return this.handleTargetError(watchChange);\n }\n // Accumulate watch changes but don't process them if there's no\n // snapshotVersion or it's older than a previous snapshot we've processed\n // (can happen after we resume a target using a resume token).\n this.accumulatedWatchChanges.push(watchChange);\n if (!snapshotVersion.isEqual(snapshot_version_SnapshotVersion.MIN) &&\n snapshotVersion.compareTo(this.localStore.getLastRemoteSnapshotVersion()) >= 0) {\n var changes = this.accumulatedWatchChanges;\n this.accumulatedWatchChanges = [];\n return this.handleWatchChangeBatch(snapshotVersion, changes);\n }\n else {\n return Promise.resolve();\n }\n };\n /**\n * Takes a batch of changes from the Datastore, repackages them as a\n * RemoteEvent, and passes that on to the listener, which is typically the\n * SyncEngine.\n */\n RemoteStore.prototype.handleWatchChangeBatch = function (snapshotVersion, changes) {\n var _this = this;\n var aggregator = new watch_change_WatchChangeAggregator(snapshotVersion, this.listenTargets, this.pendingTargetResponses);\n aggregator.addChanges(changes);\n var remoteEvent = aggregator.createRemoteEvent();\n // Get the new response counts from the aggregator\n this.pendingTargetResponses = aggregator.pendingTargetResponses;\n var promises = [];\n // Handle existence filters and existence filter mismatches.\n forEachNumber(aggregator.existenceFilters, function (targetId, filter) {\n var queryData = _this.listenTargets[targetId];\n if (!queryData) {\n // A watched target might have been removed already.\n return;\n }\n var query = queryData.query;\n if (query.isDocumentQuery()) {\n if (filter.count === 0) {\n // The existence filter told us the document does not exist.\n // We need to deduce that this document does not exist and apply\n // a deleted document to our updates. Without applying a deleted\n // document there might be another query that will raise this\n // document as part of a snapshot until it is resolved,\n // essentially exposing inconsistency between queries.\n var key = new document_key_DocumentKey(query.path);\n var deletedDoc = new document_NoDocument(key, snapshotVersion);\n remoteEvent.addDocumentUpdate(deletedDoc);\n }\n else {\n assert(filter.count === 1, 'Single document existence filter with count: ' + filter.count);\n }\n }\n else {\n // Not a document query.\n var promise = _this.localStore\n .remoteDocumentKeys(targetId)\n .then(function (trackedRemote) {\n if (remoteEvent.targetChanges[targetId]) {\n var mapping = remoteEvent.targetChanges[targetId].mapping;\n if (mapping !== null) {\n if (mapping instanceof UpdateMapping) {\n trackedRemote = mapping.applyToKeySet(trackedRemote);\n }\n else {\n assert(mapping instanceof ResetMapping, 'Expected either reset or update mapping but got something else: ' +\n mapping);\n trackedRemote = mapping.documents;\n }\n }\n }\n if (trackedRemote.size !== filter.count) {\n // Existence filter mismatch, resetting mapping.\n // Make sure the mismatch is exposed in the remote event.\n remoteEvent.handleExistenceFilterMismatch(targetId);\n // Clear the resume token for the query, since we're in a\n // known mismatch state.\n var newQueryData = new query_data_QueryData(query, targetId, queryData.purpose);\n _this.listenTargets[targetId] = newQueryData;\n // Cause a hard reset by unwatching and rewatching\n // immediately, but deliberately don't send a resume token\n // so that we get a full update.\n // Make sure we expect that this acks are going to happen.\n _this.sendUnwatchRequest(targetId);\n // Mark the query we send as being on behalf of an existence\n // filter mismatch, but don't actually retain that in\n // listenTargets. This ensures that we flag the first\n // re-listen this way without impacting future listens of\n // this target (that might happen e.g. on reconnect).\n var requestQueryData = new query_data_QueryData(query, targetId, QueryPurpose.ExistenceFilterMismatch);\n _this.sendWatchRequest(requestQueryData);\n }\n });\n promises.push(promise);\n }\n });\n return Promise.all(promises).then(function () {\n // Update in-memory resume tokens. LocalStore will update the\n // persistent view of these when applying the completed RemoteEvent.\n forEachNumber(remoteEvent.targetChanges, function (targetId, change) {\n if (change.resumeToken.length > 0) {\n var queryData = _this.listenTargets[targetId];\n // A watched target might have been removed already.\n if (queryData) {\n _this.listenTargets[targetId] = queryData.update({\n resumeToken: change.resumeToken,\n snapshotVersion: change.snapshotVersion\n });\n }\n }\n });\n // Finally handle remote event\n return _this.syncEngine.applyRemoteEvent(remoteEvent);\n });\n };\n /** Handles an error on a target */\n RemoteStore.prototype.handleTargetError = function (watchChange) {\n var _this = this;\n assert(!!watchChange.cause, 'Handling target error without a cause');\n var error = watchChange.cause;\n var promiseChain = Promise.resolve();\n watchChange.targetIds.forEach(function (targetId) {\n promiseChain = promiseChain.then(function () {\n if (contains(_this.listenTargets, targetId)) {\n delete _this.listenTargets[targetId];\n return _this.syncEngine.rejectListen(targetId, error);\n }\n else {\n // A watched target might have been removed already.\n return Promise.resolve();\n }\n });\n });\n return promiseChain;\n };\n RemoteStore.prototype.cleanUpWriteStreamState = function () {\n this.lastBatchSeen = BATCHID_UNKNOWN;\n debug(remote_store_LOG_TAG, 'Stopping write stream with ' +\n this.pendingWrites.length +\n ' pending writes');\n this.pendingWrites = [];\n };\n /**\n * Notifies that there are new mutations to process in the queue. This is\n * typically called by SyncEngine after it has sent mutations to LocalStore.\n */\n RemoteStore.prototype.fillWritePipeline = function () {\n var _this = this;\n if (!this.canWriteMutations()) {\n return Promise.resolve();\n }\n else {\n return this.localStore\n .nextMutationBatch(this.lastBatchSeen)\n .then(function (batch) {\n if (batch === null) {\n if (_this.pendingWrites.length === 0) {\n _this.writeStream.markIdle();\n }\n return Promise.resolve();\n }\n else {\n _this.commit(batch);\n return _this.fillWritePipeline();\n }\n });\n }\n };\n /**\n * Returns true if the backend can accept additional write requests.\n *\n * When sending mutations to the write stream (e.g. in fillWritePipeline),\n * call this method first to check if more mutations can be sent.\n *\n * Currently the only thing that can prevent the backend from accepting\n * write requests is if there are too many requests already outstanding. As\n * writes complete the backend will be able to accept more.\n */\n RemoteStore.prototype.canWriteMutations = function () {\n return (this.isNetworkEnabled() && this.pendingWrites.length < MAX_PENDING_WRITES);\n };\n // For testing\n RemoteStore.prototype.outstandingWrites = function () {\n return this.pendingWrites.length;\n };\n /**\n * Given mutations to commit, actually commits them to the Datastore. Note\n * that this does *not* return a Promise specifically because the AsyncQueue\n * should not block operations for this.\n */\n RemoteStore.prototype.commit = function (batch) {\n assert(this.canWriteMutations(), \"commit called when batches can't be written\");\n this.lastBatchSeen = batch.batchId;\n this.pendingWrites.push(batch);\n if (this.shouldStartWriteStream()) {\n this.startWriteStream();\n }\n else if (this.isNetworkEnabled() && this.writeStream.handshakeComplete) {\n this.writeStream.writeMutations(batch.mutations);\n }\n };\n RemoteStore.prototype.shouldStartWriteStream = function () {\n return (this.isNetworkEnabled() &&\n !this.writeStream.isStarted() &&\n this.pendingWrites.length > 0);\n };\n RemoteStore.prototype.startWriteStream = function () {\n assert(this.shouldStartWriteStream(), 'startWriteStream() called when shouldStartWriteStream() is false.');\n this.writeStream.start({\n onOpen: this.onWriteStreamOpen.bind(this),\n onClose: this.onWriteStreamClose.bind(this),\n onHandshakeComplete: this.onWriteHandshakeComplete.bind(this),\n onMutationResult: this.onMutationResult.bind(this)\n });\n };\n RemoteStore.prototype.onWriteStreamOpen = function () {\n this.writeStream.writeHandshake();\n return Promise.resolve();\n };\n RemoteStore.prototype.onWriteHandshakeComplete = function () {\n var _this = this;\n // Record the stream token.\n return this.localStore\n .setLastStreamToken(this.writeStream.lastStreamToken)\n .then(function () {\n // Drain any pending writes.\n //\n // Note that at this point pendingWrites contains mutations that\n // have already been accepted by fillWritePipeline/commitBatch. If\n // the pipeline is full, canWriteMutations will be false, despite\n // the fact that we actually need to send mutations over.\n //\n // This also means that this method indirectly respects the limits\n // imposed by canWriteMutations since writes can't be added to the\n // pendingWrites array when canWriteMutations is false. If the\n // limits imposed by canWriteMutations actually protect us from\n // DOSing ourselves then those limits won't be exceeded here and\n // we'll continue to make progress.\n for (var _i = 0, _a = _this.pendingWrites; _i < _a.length; _i++) {\n var batch = _a[_i];\n _this.writeStream.writeMutations(batch.mutations);\n }\n });\n };\n RemoteStore.prototype.onMutationResult = function (commitVersion, results) {\n var _this = this;\n // This is a response to a write containing mutations and should be\n // correlated to the first pending write.\n assert(this.pendingWrites.length > 0, 'Got result for empty pending writes');\n var batch = this.pendingWrites.shift();\n var success = mutation_batch_MutationBatchResult.from(batch, commitVersion, results, this.writeStream.lastStreamToken);\n return this.syncEngine.applySuccessfulWrite(success).then(function () {\n // It's possible that with the completion of this mutation another\n // slot has freed up.\n return _this.fillWritePipeline();\n });\n };\n RemoteStore.prototype.onWriteStreamClose = function (error) {\n var _this = this;\n assert(this.isNetworkEnabled(), 'onWriteStreamClose() should only be called when the network is enabled');\n // If the write stream closed due to an error, invoke the error callbacks if\n // there are pending writes.\n if (error && this.pendingWrites.length > 0) {\n assert(!!error, 'We have pending writes, but the write stream closed without an error');\n // A promise that is resolved after we processed the error\n var errorHandling = void 0;\n if (this.writeStream.handshakeComplete) {\n // This error affects the actual write.\n errorHandling = this.handleWriteError(error);\n }\n else {\n // If there was an error before the handshake has finished, it's\n // possible that the server is unable to process the stream token\n // we're sending. (Perhaps it's too old?)\n errorHandling = this.handleHandshakeError(error);\n }\n return errorHandling.then(function () {\n // The write stream might have been started by refilling the write\n // pipeline for failed writes\n if (_this.shouldStartWriteStream()) {\n _this.startWriteStream();\n }\n });\n }\n else {\n // No pending writes, nothing to do\n return Promise.resolve();\n }\n };\n RemoteStore.prototype.handleHandshakeError = function (error) {\n // Reset the token if it's a permanent error or the error code is\n // ABORTED, signaling the write stream is no longer valid.\n if (isPermanentError(error.code) || error.code === Code.ABORTED) {\n debug(remote_store_LOG_TAG, 'RemoteStore error before completed handshake; resetting stream token: ', this.writeStream.lastStreamToken);\n this.writeStream.lastStreamToken = emptyByteString();\n return this.localStore.setLastStreamToken(emptyByteString());\n }\n else {\n // Some other error, don't reset stream token. Our stream logic will\n // just retry with exponential backoff.\n return Promise.resolve();\n }\n };\n RemoteStore.prototype.handleWriteError = function (error) {\n var _this = this;\n if (isPermanentError(error.code)) {\n // This was a permanent error, the request itself was the problem\n // so it's not going to succeed if we resend it.\n var batch = this.pendingWrites.shift();\n // In this case it's also unlikely that the server itself is melting\n // down -- this was just a bad request so inhibit backoff on the next\n // restart.\n this.writeStream.inhibitBackoff();\n return this.syncEngine\n .rejectFailedWrite(batch.batchId, error)\n .then(function () {\n // It's possible that with the completion of this mutation\n // another slot has freed up.\n return _this.fillWritePipeline();\n });\n }\n else {\n // Transient error, just let the retry logic kick in.\n return Promise.resolve();\n }\n };\n RemoteStore.prototype.createTransaction = function () {\n return new transaction_Transaction(this.datastore);\n };\n RemoteStore.prototype.handleUserChange = function (user) {\n debug(remote_store_LOG_TAG, 'RemoteStore changing users: uid=', user.uid);\n // If the network has been explicitly disabled, make sure we don't\n // accidentally re-enable it.\n if (this.isNetworkEnabled()) {\n // Tear down and re-create our network streams. This will ensure we get a fresh auth token\n // for the new user and re-fill the write pipeline with new mutations from the LocalStore\n // (since mutations are per-user).\n this.disableNetworkInternal();\n this.updateOnlineState(OnlineState.Unknown);\n return this.enableNetwork();\n }\n };\n return RemoteStore;\n}());\n\n\n//# sourceMappingURL=remote_store.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/firestore_client.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n\n\n\n\n\n\n\n\n\n\nvar firestore_client_LOG_TAG = 'FirestoreClient';\n/**\n * FirestoreClient is a top-level class that constructs and owns all of the\n * pieces of the client SDK architecture. It is responsible for creating the\n * async queue that is shared by all of the other components in the system.\n */\nvar firestore_client_FirestoreClient = /** @class */ (function () {\n function FirestoreClient(platform, databaseInfo, credentials, \n /**\n * Asynchronous queue responsible for all of our internal processing. When\n * we get incoming work from the user (via public API) or the network\n * (incoming GRPC messages), we should always schedule onto this queue.\n * This ensures all of our work is properly serialized (e.g. we don't\n * start processing a new operation while the previous one is waiting for\n * an async I/O to complete).\n */\n asyncQueue) {\n this.platform = platform;\n this.databaseInfo = databaseInfo;\n this.credentials = credentials;\n this.asyncQueue = asyncQueue;\n }\n /**\n * Starts up the FirestoreClient, returning only whether or not enabling\n * persistence succeeded.\n *\n * The intent here is to \"do the right thing\" as far as users are concerned.\n * Namely, in cases where offline persistence is requested and possible,\n * enable it, but otherwise fall back to persistence disabled. For the most\n * part we expect this to succeed one way or the other so we don't expect our\n * users to actually wait on the firestore.enablePersistence Promise since\n * they generally won't care.\n *\n * Of course some users actually do care about whether or not persistence\n * was successfully enabled, so the Promise returned from this method\n * indicates this outcome.\n *\n * This presents a problem though: even before enablePersistence resolves or\n * rejects, users may have made calls to e.g. firestore.collection() which\n * means that the FirestoreClient in there will be available and will be\n * enqueuing actions on the async queue.\n *\n * Meanwhile any failure of an operation on the async queue causes it to\n * panic and reject any further work, on the premise that unhandled errors\n * are fatal.\n *\n * Consequently the fallback is handled internally here in start, and if the\n * fallback succeeds we signal success to the async queue even though the\n * start() itself signals failure.\n *\n * @param usePersistence Whether or not to attempt to enable persistence.\n * @returns A deferred result indicating the user-visible result of enabling\n * offline persistence. This method will reject this if IndexedDB fails to\n * start for any reason. If usePersistence is false this is\n * unconditionally resolved.\n */\n FirestoreClient.prototype.start = function (usePersistence) {\n var _this = this;\n // We defer our initialization until we get the current user from\n // setUserChangeListener(). We block the async queue until we got the\n // initial user and the initialization is completed. This will prevent\n // any scheduled work from happening before initialization is completed.\n //\n // If initializationDone resolved then the FirestoreClient is in a usable\n // state.\n var initializationDone = new Deferred();\n // If usePersistence is true, certain classes of errors while starting are\n // recoverable but only by falling back to persistence disabled.\n //\n // If there's an error in the first case but not in recovery we cannot\n // reject the promise blocking the async queue because this will cause the\n // async queue to panic.\n var persistenceResult = new Deferred();\n var initialized = false;\n this.credentials.setUserChangeListener(function (user) {\n if (!initialized) {\n initialized = true;\n _this.initializePersistence(usePersistence, persistenceResult)\n .then(function () { return _this.initializeRest(user); })\n .then(initializationDone.resolve, initializationDone.reject);\n }\n else {\n _this.asyncQueue.schedule(function () {\n return _this.handleUserChange(user);\n });\n }\n });\n // Block the async queue until initialization is done\n this.asyncQueue.schedule(function () {\n return initializationDone.promise;\n });\n // Return only the result of enabling persistence. Note that this does not\n // need to await the completion of initializationDone because the result of\n // this method should not reflect any other kind of failure to start.\n return persistenceResult.promise;\n };\n /** Enables the network connection and requeues all pending operations. */\n FirestoreClient.prototype.enableNetwork = function () {\n var _this = this;\n return this.asyncQueue.schedule(function () {\n return _this.remoteStore.enableNetwork();\n });\n };\n /**\n * Initializes persistent storage, attempting to use IndexedDB if\n * usePersistence is true or memory-only if false.\n *\n * If IndexedDB fails because it's already open in another tab or because the\n * platform can't possibly support our implementation then this method rejects\n * the persistenceResult and falls back on memory-only persistence.\n *\n * @param usePersistence indicates whether or not to use offline persistence\n * @param persistenceResult A deferred result indicating the user-visible\n * result of enabling offline persistence. This method will reject this if\n * IndexedDB fails to start for any reason. If usePersistence is false\n * this is unconditionally resolved.\n * @returns a Promise indicating whether or not initialization should\n * continue, i.e. that one of the persistence implementations actually\n * succeeded.\n */\n FirestoreClient.prototype.initializePersistence = function (usePersistence, persistenceResult) {\n var _this = this;\n if (usePersistence) {\n return this.startIndexedDbPersistence()\n .then(persistenceResult.resolve)\n .catch(function (error) {\n // Regardless of whether or not the retry succeeds, from an user\n // perspective, offline persistence has failed.\n persistenceResult.reject(error);\n // An unknown failure on the first stage shuts everything down.\n if (!_this.canFallback(error)) {\n return Promise.reject(error);\n }\n console.warn('Error enabling offline storage. Falling back to' +\n ' storage disabled: ' +\n error);\n return _this.startMemoryPersistence();\n });\n }\n else {\n // When usePersistence == false, enabling offline persistence is defined\n // to unconditionally succeed. This allows start() to have the same\n // signature for both cases, despite the fact that the returned promise\n // is only used in the enablePersistence call.\n persistenceResult.resolve();\n return this.startMemoryPersistence();\n }\n };\n FirestoreClient.prototype.canFallback = function (error) {\n return (error.code === Code.FAILED_PRECONDITION ||\n error.code === Code.UNIMPLEMENTED);\n };\n /**\n * Starts IndexedDB-based persistence.\n *\n * @returns A promise indicating success or failure.\n */\n FirestoreClient.prototype.startIndexedDbPersistence = function () {\n // TODO(http://b/33384523): For now we just disable garbage collection\n // when persistence is enabled.\n this.garbageCollector = new no_op_garbage_collector_NoOpGarbageCollector();\n var storagePrefix = indexeddb_persistence_IndexedDbPersistence.buildStoragePrefix(this.databaseInfo);\n // Opt to use proto3 JSON in case the platform doesn't support Uint8Array.\n var serializer = new serializer_JsonProtoSerializer(this.databaseInfo.databaseId, {\n useProto3Json: true\n });\n this.persistence = new indexeddb_persistence_IndexedDbPersistence(storagePrefix, serializer);\n return this.persistence.start();\n };\n /**\n * Starts Memory-backed persistence. In practice this cannot fail.\n *\n * @returns A promise that will successfully resolve.\n */\n FirestoreClient.prototype.startMemoryPersistence = function () {\n this.garbageCollector = new eager_garbage_collector_EagerGarbageCollector();\n this.persistence = new memory_persistence_MemoryPersistence();\n return this.persistence.start();\n };\n /**\n * Initializes the rest of the FirestoreClient, assuming the initial user\n * has been obtained from the credential provider and some persistence\n * implementation is available in this.persistence.\n */\n FirestoreClient.prototype.initializeRest = function (user) {\n var _this = this;\n return this.platform\n .loadConnection(this.databaseInfo)\n .then(function (connection) {\n _this.localStore = new local_store_LocalStore(_this.persistence, user, _this.garbageCollector);\n var serializer = _this.platform.newSerializer(_this.databaseInfo.databaseId);\n var datastore = new datastore_Datastore(_this.databaseInfo, _this.asyncQueue, connection, _this.credentials, serializer);\n var onlineStateChangedHandler = function (onlineState) {\n _this.syncEngine.applyOnlineStateChange(onlineState);\n _this.eventMgr.applyOnlineStateChange(onlineState);\n };\n _this.remoteStore = new remote_store_RemoteStore(_this.localStore, datastore, onlineStateChangedHandler);\n _this.syncEngine = new sync_engine_SyncEngine(_this.localStore, _this.remoteStore, user);\n // Setup wiring between sync engine and remote store\n _this.remoteStore.syncEngine = _this.syncEngine;\n _this.eventMgr = new event_manager_EventManager(_this.syncEngine);\n // NOTE: RemoteStore depends on LocalStore (for persisting stream\n // tokens, refilling mutation queue, etc.) so must be started after\n // LocalStore.\n return _this.localStore.start();\n })\n .then(function () {\n return _this.remoteStore.start();\n });\n };\n FirestoreClient.prototype.handleUserChange = function (user) {\n this.asyncQueue.verifyOperationInProgress();\n debug(firestore_client_LOG_TAG, 'User Changed: ' + user.uid);\n return this.syncEngine.handleUserChange(user);\n };\n /** Disables the network connection. Pending operations will not complete. */\n FirestoreClient.prototype.disableNetwork = function () {\n var _this = this;\n return this.asyncQueue.schedule(function () {\n return _this.remoteStore.disableNetwork();\n });\n };\n FirestoreClient.prototype.shutdown = function () {\n var _this = this;\n return this.asyncQueue\n .schedule(function () {\n _this.credentials.removeUserChangeListener();\n return _this.remoteStore.shutdown();\n })\n .then(function () {\n // PORTING NOTE: LocalStore does not need an explicit shutdown on web.\n return _this.persistence.shutdown();\n });\n };\n FirestoreClient.prototype.listen = function (query, observer, options) {\n var _this = this;\n var listener = new event_manager_QueryListener(query, observer, options);\n this.asyncQueue.schedule(function () {\n return _this.eventMgr.listen(listener);\n });\n return listener;\n };\n FirestoreClient.prototype.unlisten = function (listener) {\n var _this = this;\n this.asyncQueue.schedule(function () {\n return _this.eventMgr.unlisten(listener);\n });\n };\n FirestoreClient.prototype.write = function (mutations) {\n var _this = this;\n var deferred = new Deferred();\n this.asyncQueue.schedule(function () { return _this.syncEngine.write(mutations, deferred); });\n return deferred.promise;\n };\n FirestoreClient.prototype.databaseId = function () {\n return this.databaseInfo.databaseId;\n };\n FirestoreClient.prototype.transaction = function (updateFunction) {\n var _this = this;\n // We have to wait for the async queue to be sure syncEngine is initialized.\n return this.asyncQueue\n .schedule(function () {\n return Promise.resolve();\n })\n .then(function () {\n return _this.syncEngine.runTransaction(updateFunction);\n });\n };\n return FirestoreClient;\n}());\n\n\n//# sourceMappingURL=firestore_client.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/async_observer.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/*\n * A wrapper implementation of Observer that will dispatch events\n * asynchronously. To allow immediate silencing, a mute call is added which\n * causes events scheduled to no longer be raised.\n */\nvar AsyncObserver = /** @class */ (function () {\n function AsyncObserver(observer) {\n this.observer = observer;\n /**\n * When set to true, will not raise future events. Necessary to deal with\n * async detachment of listener.\n */\n this.muted = false;\n }\n AsyncObserver.prototype.next = function (value) {\n this.scheduleEvent(this.observer.next, value);\n };\n AsyncObserver.prototype.error = function (error) {\n this.scheduleEvent(this.observer.error, error);\n };\n AsyncObserver.prototype.mute = function () {\n this.muted = true;\n };\n AsyncObserver.prototype.scheduleEvent = function (eventHandler, event) {\n var _this = this;\n if (!this.muted) {\n setTimeout(function () {\n if (!_this.muted) {\n eventHandler(event);\n }\n }, 0);\n }\n };\n return AsyncObserver;\n}());\n\n\n//# sourceMappingURL=async_observer.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/async_queue.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n\nvar async_queue_AsyncQueue = /** @class */ (function () {\n function AsyncQueue() {\n // The last promise in the queue.\n this.tail = Promise.resolve();\n // A list with timeout handles and their respective deferred promises.\n // Contains an entry for each operation that is queued to run in the future\n // (i.e. it has a delay that has not yet elapsed). Prior to cleanup, this list\n // may also contain entries that have already been run (in which case `handle` is\n // null).\n this.delayedOperations = [];\n // The number of operations that are queued to be run in the future (i.e. they\n // have a delay that has not yet elapsed). Unlike `delayedOperations`, this\n // is guaranteed to only contain operations that have not yet been run.\n //\n // Visible for testing.\n this.delayedOperationsCount = 0;\n // Flag set while there's an outstanding AsyncQueue operation, used for\n // assertion sanity-checks.\n this.operationInProgress = false;\n }\n /**\n * Adds a new operation to the queue. Returns a promise that will be resolved\n * when the promise returned by the new operation is (with its value).\n *\n * Can optionally specify a delay (in milliseconds) to wait before queuing the\n * operation.\n */\n AsyncQueue.prototype.schedule = function (op, delay) {\n var _this = this;\n if (this.failure) {\n fail('AsyncQueue is already failed: ' +\n (this.failure.stack || this.failure.message));\n }\n if ((delay || 0) > 0) {\n this.delayedOperationsCount++;\n var delayedOp_1 = {\n handle: null,\n op: op,\n deferred: new Deferred()\n };\n delayedOp_1.handle = setTimeout(function () {\n _this.scheduleInternal(function () {\n return delayedOp_1.op().then(function (result) {\n delayedOp_1.deferred.resolve(result);\n });\n });\n delayedOp_1.handle = null;\n _this.delayedOperationsCount--;\n if (_this.delayedOperationsCount === 0) {\n _this.delayedOperations = [];\n }\n }, delay);\n this.delayedOperations.push(delayedOp_1);\n return delayedOp_1.deferred.promise;\n }\n else {\n return this.scheduleInternal(op);\n }\n };\n AsyncQueue.prototype.scheduleInternal = function (op) {\n var _this = this;\n this.tail = this.tail.then(function () {\n _this.operationInProgress = true;\n return op()\n .catch(function (error) {\n _this.failure = error;\n _this.operationInProgress = false;\n var message = error.stack || error.message || '';\n log_error('INTERNAL UNHANDLED ERROR: ', message);\n // Escape the promise chain and throw the error globally so that\n // e.g. any global crash reporting library detects and reports it.\n // (but not for simulated errors in our tests since this breaks mocha)\n if (message.indexOf('Firestore Test Simulated Error') < 0) {\n setTimeout(function () {\n throw error;\n }, 0);\n }\n // Re-throw the error so that this.tail becomes a rejected Promise and\n // all further attempts to chain (via .then) will just short-circuit\n // and return the rejected Promise.\n throw error;\n })\n .then(function () {\n _this.operationInProgress = false;\n });\n });\n return this.tail;\n };\n /**\n * Verifies there's an operation currently in-progress on the AsyncQueue.\n * Unfortunately we can't verify that the running code is in the promise chain\n * of that operation, so this isn't a foolproof check, but it should be enough\n * to catch some bugs.\n */\n AsyncQueue.prototype.verifyOperationInProgress = function () {\n assert(this.operationInProgress, 'verifyOpInProgress() called when no op in progress on this queue.');\n };\n /**\n * Waits until all currently scheduled tasks are finished executing. Tasks\n * scheduled with a delay can be rejected or queued for immediate execution.\n */\n AsyncQueue.prototype.drain = function (executeDelayedTasks) {\n var _this = this;\n this.delayedOperations.forEach(function (entry) {\n if (entry.handle) {\n clearTimeout(entry.handle);\n if (executeDelayedTasks) {\n _this.scheduleInternal(entry.op).then(entry.deferred.resolve, entry.deferred.reject);\n }\n else {\n entry.deferred.reject(new FirestoreError(Code.CANCELLED, 'Operation cancelled by shutdown'));\n }\n }\n });\n this.delayedOperations = [];\n this.delayedOperationsCount = 0;\n return this.schedule(function () { return Promise.resolve(); });\n };\n return AsyncQueue;\n}());\n\n\n//# sourceMappingURL=async_queue.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/auth/user.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Simple wrapper around a nullable UID. Mostly exists to make code more\n * readable.\n */\nvar User = /** @class */ (function () {\n function User(uid) {\n this.uid = uid;\n }\n User.prototype.isUnauthenticated = function () {\n return this.uid == null;\n };\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */\n User.prototype.toKey = function () {\n if (this.isUnauthenticated()) {\n return 'anonymous-user';\n }\n else {\n return 'uid:' + this.uid;\n }\n };\n User.prototype.isEqual = function (otherUser) {\n return otherUser.uid === this.uid;\n };\n /** A user with a null UID. */\n User.UNAUTHENTICATED = new User(null);\n // TODO(mikelehen): Look into getting a proper uid-equivalent for\n // non-FirebaseAuth providers.\n User.GOOGLE_CREDENTIALS = new User('google-credentials-uid');\n User.FIRST_PARTY = new User('first-party-uid');\n return User;\n}());\n\n\n//# sourceMappingURL=user.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/api/credentials.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\nvar OAuthToken = /** @class */ (function () {\n function OAuthToken(value, user) {\n this.user = user;\n this.type = 'OAuth';\n this.authHeaders = { Authorization: \"Bearer \" + value };\n }\n return OAuthToken;\n}());\n\n/** A CredentialsProvider that always yields an empty token. */\nvar credentials_EmptyCredentialsProvider = /** @class */ (function () {\n function EmptyCredentialsProvider() {\n /**\n * Stores the User listener registered with setUserChangeListener()\n * This isn't actually necessary since the UID never changes, but we use this\n * to verify the listen contract is adhered to in tests.\n */\n this.userListener = null;\n }\n EmptyCredentialsProvider.prototype.getToken = function (forceRefresh) {\n return Promise.resolve(null);\n };\n EmptyCredentialsProvider.prototype.setUserChangeListener = function (listener) {\n assert(!this.userListener, 'Can only call setUserChangeListener() once.');\n this.userListener = listener;\n // Fire with initial user.\n listener(User.UNAUTHENTICATED);\n };\n EmptyCredentialsProvider.prototype.removeUserChangeListener = function () {\n assert(this.userListener !== null, 'removeUserChangeListener() when no listener registered');\n this.userListener = null;\n };\n return EmptyCredentialsProvider;\n}());\n\nvar credentials_FirebaseCredentialsProvider = /** @class */ (function () {\n function FirebaseCredentialsProvider(app) {\n var _this = this;\n this.app = app;\n /**\n * The auth token listener registered with FirebaseApp, retained here so we\n * can unregister it.\n */\n this.tokenListener = null;\n /**\n * Counter used to detect if the user changed while a getToken request was\n * outstanding.\n */\n this.userCounter = 0;\n /** The User listener registered with setUserChangeListener(). */\n this.userListener = null;\n // We listen for token changes but all we really care about is knowing when\n // the uid may have changed.\n this.tokenListener = function () {\n var newUser = _this.getUser();\n if (!_this.currentUser || !newUser.isEqual(_this.currentUser)) {\n _this.currentUser = newUser;\n _this.userCounter++;\n if (_this.userListener) {\n _this.userListener(_this.currentUser);\n }\n }\n };\n this.userCounter = 0;\n // Will fire at least once where we set this.currentUser\n this.app.INTERNAL.addAuthTokenListener(this.tokenListener);\n }\n FirebaseCredentialsProvider.prototype.getToken = function (forceRefresh) {\n var _this = this;\n assert(this.tokenListener != null, 'getToken cannot be called after listener removed.');\n // Take note of the current value of the userCounter so that this method can\n // fail (with an ABORTED error) if there is a user change while the request\n // is outstanding.\n var initialUserCounter = this.userCounter;\n return this.app.INTERNAL.getToken(forceRefresh).then(function (tokenData) {\n // Cancel the request since the user changed while the request was\n // outstanding so the response is likely for a previous user (which\n // user, we can't be sure).\n if (_this.userCounter !== initialUserCounter) {\n throw new FirestoreError(Code.ABORTED, 'getToken aborted due to uid change.');\n }\n else {\n if (tokenData) {\n assert(typeof tokenData.accessToken === 'string', 'Invalid tokenData returned from getToken():' + tokenData);\n return new OAuthToken(tokenData.accessToken, _this.currentUser);\n }\n else {\n return null;\n }\n }\n });\n };\n FirebaseCredentialsProvider.prototype.setUserChangeListener = function (listener) {\n assert(!this.userListener, 'Can only call setUserChangeListener() once.');\n this.userListener = listener;\n // Fire the initial event, but only if we received the initial user\n if (this.currentUser) {\n listener(this.currentUser);\n }\n };\n FirebaseCredentialsProvider.prototype.removeUserChangeListener = function () {\n assert(this.tokenListener != null, 'removeUserChangeListener() called twice');\n assert(this.userListener !== null, 'removeUserChangeListener() called when no listener registered');\n this.app.INTERNAL.removeAuthTokenListener(this.tokenListener);\n this.tokenListener = null;\n this.userListener = null;\n };\n FirebaseCredentialsProvider.prototype.getUser = function () {\n // TODO(mikelehen): Remove this check once we're shipping with firebase.js.\n if (typeof this.app.INTERNAL.getUid !== 'function') {\n fail('This version of the Firestore SDK requires at least version' +\n ' 3.7.0 of firebase.js.');\n }\n var currentUid = this.app.INTERNAL.getUid();\n assert(currentUid === null || typeof currentUid === 'string', 'Received invalid UID: ' + currentUid);\n return new User(currentUid);\n };\n return FirebaseCredentialsProvider;\n}());\n\n/*\n * FirstPartyToken provides a fresh token each time its value\n * is requested, because if the token is too old, requests will be rejected.\n * TODO(b/33147818) this implementation violates the current assumption that\n * tokens are immutable. We need to either revisit this assumption or come\n * up with some way for FPA to use the listen/unlisten interface.\n */\nvar credentials_FirstPartyToken = /** @class */ (function () {\n function FirstPartyToken(gapi, sessionIndex) {\n this.gapi = gapi;\n this.sessionIndex = sessionIndex;\n this.type = 'FirstParty';\n this.user = User.FIRST_PARTY;\n assert(this.gapi &&\n this.gapi['auth'] &&\n this.gapi['auth']['getAuthHeaderValueForFirstParty'], 'unexpected gapi interface');\n }\n Object.defineProperty(FirstPartyToken.prototype, \"authHeaders\", {\n get: function () {\n return {\n Authorization: this.gapi['auth']['getAuthHeaderValueForFirstParty']([]),\n 'X-Goog-AuthUser': this.sessionIndex\n };\n },\n enumerable: true,\n configurable: true\n });\n return FirstPartyToken;\n}());\n\n/*\n * Provides user credentials required for the Firestore JavaScript SDK\n * to authenticate the user, using technique that is only available\n * to applications hosted by Google.\n */\nvar credentials_FirstPartyCredentialsProvider = /** @class */ (function () {\n function FirstPartyCredentialsProvider(gapi, sessionIndex) {\n this.gapi = gapi;\n this.sessionIndex = sessionIndex;\n assert(this.gapi &&\n this.gapi['auth'] &&\n this.gapi['auth']['getAuthHeaderValueForFirstParty'], 'unexpected gapi interface');\n }\n FirstPartyCredentialsProvider.prototype.getToken = function (forceRefresh) {\n return Promise.resolve(new credentials_FirstPartyToken(this.gapi, this.sessionIndex));\n };\n // TODO(33108925): can someone switch users w/o a page refresh?\n // TODO(33110621): need to understand token/session lifecycle\n FirstPartyCredentialsProvider.prototype.setUserChangeListener = function (listener) {\n // Fire with initial uid.\n listener(User.FIRST_PARTY);\n };\n FirstPartyCredentialsProvider.prototype.removeUserChangeListener = function () { };\n return FirstPartyCredentialsProvider;\n}());\n\n/**\n * Builds a CredentialsProvider depending on the type of\n * the credentials passed in.\n */\nfunction makeCredentialsProvider(credentials) {\n if (!credentials) {\n return new credentials_EmptyCredentialsProvider();\n }\n switch (credentials.type) {\n case 'gapi':\n return new credentials_FirstPartyCredentialsProvider(credentials.client, credentials.sessionIndex || '0');\n case 'provider':\n return credentials.client;\n default:\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'makeCredentialsProvider failed due to invalid credential type');\n }\n}\n\n//# sourceMappingURL=credentials.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/api/observer.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction isPartialObserver(obj) {\n return implementsAnyMethods(obj, ['next', 'error', 'complete']);\n}\n/**\n * Returns true if obj is an object and contains at least one of the specified\n * methods.\n */\nfunction implementsAnyMethods(obj, methods) {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n var object = obj;\n for (var _i = 0, methods_1 = methods; _i < methods_1.length; _i++) {\n var method = methods_1[_i];\n if (method in object && typeof object[method] === 'function') {\n return true;\n }\n }\n return false;\n}\n\n//# sourceMappingURL=observer.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/api/field_value.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar api_field_value___extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n\n/**\n * An opaque base class for FieldValue sentinel objects in our public API,\n * with public static methods for creating said sentinel objects.\n */\n// tslint:disable-next-line:class-as-namespace We use this as a base class.\nvar FieldValueImpl = /** @class */ (function () {\n function FieldValueImpl() {\n }\n FieldValueImpl.delete = function () {\n return DeleteFieldValueImpl.instance;\n };\n FieldValueImpl.serverTimestamp = function () {\n return ServerTimestampFieldValueImpl.instance;\n };\n FieldValueImpl.prototype.isEqual = function (other) {\n return this === other;\n };\n return FieldValueImpl;\n}());\n\nvar DeleteFieldValueImpl = /** @class */ (function (_super) {\n api_field_value___extends(DeleteFieldValueImpl, _super);\n function DeleteFieldValueImpl() {\n return _super.call(this) || this;\n }\n /** Singleton instance. */\n DeleteFieldValueImpl.instance = new DeleteFieldValueImpl();\n return DeleteFieldValueImpl;\n}(FieldValueImpl));\n\nvar ServerTimestampFieldValueImpl = /** @class */ (function (_super) {\n api_field_value___extends(ServerTimestampFieldValueImpl, _super);\n function ServerTimestampFieldValueImpl() {\n return _super.call(this) || this;\n }\n /** Singleton instance. */\n ServerTimestampFieldValueImpl.instance = new ServerTimestampFieldValueImpl();\n return ServerTimestampFieldValueImpl;\n}(FieldValueImpl));\n\n// Public instance that disallows construction at runtime. This constructor is\n// used when exporting FieldValueImpl on firebase.firestore.FieldValue and will\n// be called FieldValue publicly. Internally we still use FieldValueImpl which\n// has a type-checked private constructor. Note that FieldValueImpl and\n// PublicFieldValue can be used interchangeably in instanceof checks.\n// For our internal TypeScript code PublicFieldValue doesn't exist as a type,\n// and so we need to use FieldValueImpl as type and export it too.\n// tslint:disable-next-line:variable-name We treat this as a class name.\nvar PublicFieldValue = makeConstructorPrivate(FieldValueImpl, 'Use FieldValue.() instead.');\n\n//# sourceMappingURL=field_value.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/api/user_data_converter.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nvar RESERVED_FIELD_REGEX = /^__.*__$/;\n/** The result of parsing document data (e.g. for a setData call). */\nvar user_data_converter_ParsedSetData = /** @class */ (function () {\n function ParsedSetData(data, fieldMask, fieldTransforms) {\n this.data = data;\n this.fieldMask = fieldMask;\n this.fieldTransforms = fieldTransforms;\n }\n ParsedSetData.prototype.toMutations = function (key, precondition) {\n var mutations = [];\n if (this.fieldMask !== null) {\n mutations.push(new mutation_PatchMutation(key, this.data, this.fieldMask, precondition));\n }\n else {\n mutations.push(new mutation_SetMutation(key, this.data, precondition));\n }\n if (this.fieldTransforms.length > 0) {\n mutations.push(new mutation_TransformMutation(key, this.fieldTransforms));\n }\n return mutations;\n };\n return ParsedSetData;\n}());\n\n/** The result of parsing \"update\" data (i.e. for an updateData call). */\nvar user_data_converter_ParsedUpdateData = /** @class */ (function () {\n function ParsedUpdateData(data, fieldMask, fieldTransforms) {\n this.data = data;\n this.fieldMask = fieldMask;\n this.fieldTransforms = fieldTransforms;\n }\n ParsedUpdateData.prototype.toMutations = function (key, precondition) {\n var mutations = [\n new mutation_PatchMutation(key, this.data, this.fieldMask, precondition)\n ];\n if (this.fieldTransforms.length > 0) {\n mutations.push(new mutation_TransformMutation(key, this.fieldTransforms));\n }\n return mutations;\n };\n return ParsedUpdateData;\n}());\n\n/*\n * Represents what type of API method provided the data being parsed; useful\n * for determining which error conditions apply during parsing and providing\n * better error messages.\n */\nvar UserDataSource;\n(function (UserDataSource) {\n UserDataSource[UserDataSource[\"Set\"] = 0] = \"Set\";\n UserDataSource[UserDataSource[\"Update\"] = 1] = \"Update\";\n UserDataSource[UserDataSource[\"MergeSet\"] = 2] = \"MergeSet\";\n UserDataSource[UserDataSource[\"QueryValue\"] = 3] = \"QueryValue\"; // from a where clause or cursor bound\n})(UserDataSource || (UserDataSource = {}));\nfunction isWrite(dataSource) {\n switch (dataSource) {\n case UserDataSource.Set: // fall through\n case UserDataSource.MergeSet: // fall through\n case UserDataSource.Update:\n return true;\n case UserDataSource.QueryValue:\n return false;\n default:\n throw fail(\"Unexpected case for UserDataSource: \" + dataSource);\n }\n}\n/** A \"context\" object passed around while parsing user data. */\nvar user_data_converter_ParseContext = /** @class */ (function () {\n /**\n * Initializes a ParseContext with the given source and path.\n *\n * @param dataSource Indicates what kind of API method this data came from.\n * @param methodName The name of the method the user called to create this\n * ParseContext.\n * @param path A path within the object being parsed. This could be an empty\n * path (in which case the context represents the root of the data being\n * parsed), or a nonempty path (indicating the context represents a nested\n * location within the data).\n * @param arrayElement Whether or not this context corresponds to an element\n * of an array.\n * @param fieldTransforms A mutable list of field transforms encountered while\n * parsing the data.\n * @param fieldMask A mutable list of field paths encountered while parsing\n * the data.\n *\n * TODO(b/34871131): We don't support array paths right now, so path can be\n * null to indicate the context represents any location within an array (in\n * which case certain features will not work and errors will be somewhat\n * compromised).\n */\n function ParseContext(dataSource, methodName, path, arrayElement, fieldTransforms, fieldMask) {\n this.dataSource = dataSource;\n this.methodName = methodName;\n this.path = path;\n this.arrayElement = arrayElement;\n // Minor hack: If fieldTransforms is undefined, we assume this is an\n // external call and we need to validate the entire path.\n if (fieldTransforms === undefined) {\n this.validatePath();\n }\n this.arrayElement = arrayElement !== undefined ? arrayElement : false;\n this.fieldTransforms = fieldTransforms || [];\n this.fieldMask = fieldMask || [];\n }\n ParseContext.prototype.childContextForField = function (field) {\n var childPath = this.path == null ? null : this.path.child(field);\n var context = new ParseContext(this.dataSource, this.methodName, childPath, \n /*arrayElement=*/ false, this.fieldTransforms, this.fieldMask);\n context.validatePathSegment(field);\n return context;\n };\n ParseContext.prototype.childContextForFieldPath = function (field) {\n var childPath = this.path == null ? null : this.path.child(field);\n var context = new ParseContext(this.dataSource, this.methodName, childPath, \n /*arrayElement=*/ false, this.fieldTransforms, this.fieldMask);\n context.validatePath();\n return context;\n };\n ParseContext.prototype.childContextForArray = function (index) {\n // TODO(b/34871131): We don't support array paths right now; so make path\n // null.\n return new ParseContext(this.dataSource, this.methodName, \n /*path=*/ null, \n /*arrayElement=*/ true, this.fieldTransforms, this.fieldMask);\n };\n ParseContext.prototype.createError = function (reason) {\n var fieldDescription = this.path === null || this.path.isEmpty()\n ? ''\n : \" (found in field \" + this.path.toString() + \")\";\n return new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + this.methodName + \"() called with invalid data. \" +\n reason +\n fieldDescription);\n };\n ParseContext.prototype.validatePath = function () {\n // TODO(b/34871131): Remove null check once we have proper paths for fields\n // within arrays.\n if (this.path === null) {\n return;\n }\n for (var i = 0; i < this.path.length; i++) {\n this.validatePathSegment(this.path.get(i));\n }\n };\n ParseContext.prototype.validatePathSegment = function (segment) {\n if (isWrite(this.dataSource) && RESERVED_FIELD_REGEX.test(segment)) {\n throw this.createError('Document fields cannot begin and end with __');\n }\n };\n ParseContext.prototype.isWrite = function () {\n return (this.dataSource === UserDataSource.Set ||\n this.dataSource === UserDataSource.Update);\n };\n return ParseContext;\n}());\n/**\n * A placeholder object for DocumentReferences in this file, in order to\n * avoid a circular dependency. See the comments for `DataPreConverter` for\n * the full context.\n */\nvar DocumentKeyReference = /** @class */ (function () {\n function DocumentKeyReference(databaseId, key) {\n this.databaseId = databaseId;\n this.key = key;\n }\n return DocumentKeyReference;\n}());\n\n/**\n * Helper for parsing raw user input (provided via the API) into internal model\n * classes.\n */\nvar user_data_converter_UserDataConverter = /** @class */ (function () {\n function UserDataConverter(preConverter) {\n this.preConverter = preConverter;\n }\n /** Parse document data from a non-merge set() call. */\n UserDataConverter.prototype.parseSetData = function (methodName, input) {\n var context = new user_data_converter_ParseContext(UserDataSource.Set, methodName, path_FieldPath.EMPTY_PATH);\n validatePlainObject('Data must be an object, but it was:', context, input);\n var updateData = this.parseData(input, context);\n return new user_data_converter_ParsedSetData(updateData, \n /* fieldMask= */ null, context.fieldTransforms);\n };\n /** Parse document data from a set() call with '{merge:true}'. */\n UserDataConverter.prototype.parseMergeData = function (methodName, input) {\n var context = new user_data_converter_ParseContext(UserDataSource.MergeSet, methodName, path_FieldPath.EMPTY_PATH);\n validatePlainObject('Data must be an object, but it was:', context, input);\n var updateData = this.parseData(input, context);\n var fieldMask = new mutation_FieldMask(context.fieldMask);\n return new user_data_converter_ParsedSetData(updateData, fieldMask, context.fieldTransforms);\n };\n /** Parse update data from an update() call. */\n UserDataConverter.prototype.parseUpdateData = function (methodName, input) {\n var _this = this;\n var context = new user_data_converter_ParseContext(UserDataSource.Update, methodName, path_FieldPath.EMPTY_PATH);\n validatePlainObject('Data must be an object, but it was:', context, input);\n var fieldMaskPaths = [];\n var updateData = field_value_ObjectValue.EMPTY;\n forEach(input, function (key, value) {\n var path = fieldPathFromDotSeparatedString(methodName, key);\n var childContext = context.childContextForFieldPath(path);\n value = _this.runPreConverter(value, childContext);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n }\n else {\n var parsedValue = _this.parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData = updateData.set(path, parsedValue);\n }\n }\n });\n var mask = new mutation_FieldMask(fieldMaskPaths);\n return new user_data_converter_ParsedUpdateData(updateData, mask, context.fieldTransforms);\n };\n /** Parse update data from a list of field/value arguments. */\n UserDataConverter.prototype.parseUpdateVarargs = function (methodName, field, value, moreFieldsAndValues) {\n var context = new user_data_converter_ParseContext(UserDataSource.Update, methodName, path_FieldPath.EMPTY_PATH);\n var keys = [fieldPathFromArgument(methodName, field)];\n var values = [value];\n if (moreFieldsAndValues.length % 2 !== 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + methodName + \"() needs to be called with an even number \" +\n 'of arguments that alternate between field names and values.');\n }\n for (var i = 0; i < moreFieldsAndValues.length; i += 2) {\n keys.push(fieldPathFromArgument(methodName, moreFieldsAndValues[i]));\n values.push(moreFieldsAndValues[i + 1]);\n }\n var fieldMaskPaths = [];\n var updateData = field_value_ObjectValue.EMPTY;\n for (var i = 0; i < keys.length; ++i) {\n var path = keys[i];\n var childContext = context.childContextForFieldPath(path);\n var value_1 = this.runPreConverter(values[i], childContext);\n if (value_1 instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n }\n else {\n var parsedValue = this.parseData(value_1, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData = updateData.set(path, parsedValue);\n }\n }\n }\n var mask = new mutation_FieldMask(fieldMaskPaths);\n return new user_data_converter_ParsedUpdateData(updateData, mask, context.fieldTransforms);\n };\n /**\n * Parse a \"query value\" (e.g. value in a where filter or a value in a cursor\n * bound).\n */\n UserDataConverter.prototype.parseQueryValue = function (methodName, input) {\n var context = new user_data_converter_ParseContext(UserDataSource.QueryValue, methodName, path_FieldPath.EMPTY_PATH);\n var parsed = this.parseData(input, context);\n assert(parsed != null, 'Parsed data should not be null.');\n assert(context.fieldTransforms.length === 0, 'Field transforms should have been disallowed.');\n return parsed;\n };\n /** Sends data through this.preConverter, handling any thrown errors. */\n UserDataConverter.prototype.runPreConverter = function (input, context) {\n try {\n return this.preConverter(input);\n }\n catch (e) {\n var message = errorMessage(e);\n throw context.createError(message);\n }\n };\n /**\n * Internal helper for parsing user data.\n *\n * @param input Data to be parsed.\n * @param context A context object representing the current path being parsed,\n * the source of the data being parsed, etc.\n * @return The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */\n UserDataConverter.prototype.parseData = function (input, context) {\n input = this.runPreConverter(input, context);\n if (input instanceof Array) {\n // TODO(b/34871131): Include the path containing the array in the error\n // message.\n if (context.arrayElement) {\n throw context.createError('Nested arrays are not supported');\n }\n // If context.path is null we are already inside an array and we don't\n // support field mask paths more granular than the top-level array.\n if (context.path) {\n context.fieldMask.push(context.path);\n }\n return this.parseArray(input, context);\n }\n else if (looksLikeJsonObject(input)) {\n validatePlainObject('Unsupported field value:', context, input);\n return this.parseObject(input, context);\n }\n else {\n // If context.path is null, we are inside an array and we should have\n // already added the root of the array to the field mask.\n if (context.path) {\n context.fieldMask.push(context.path);\n }\n return this.parseScalarValue(input, context);\n }\n };\n UserDataConverter.prototype.parseArray = function (array, context) {\n var result = [];\n var entryIndex = 0;\n for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {\n var entry = array_1[_i];\n var parsedEntry = this.parseData(entry, context.childContextForArray(entryIndex));\n if (parsedEntry == null) {\n // Just include nulls in the array for fields being replaced with a\n // sentinel.\n parsedEntry = NullValue.INSTANCE;\n }\n result.push(parsedEntry);\n entryIndex++;\n }\n return new field_value_ArrayValue(result);\n };\n UserDataConverter.prototype.parseObject = function (obj, context) {\n var _this = this;\n var result = new sorted_map_SortedMap(primitiveComparator);\n forEach(obj, function (key, val) {\n var parsedValue = _this.parseData(val, context.childContextForField(key));\n if (parsedValue != null) {\n result = result.insert(key, parsedValue);\n }\n });\n return new field_value_ObjectValue(result);\n };\n /**\n * Helper to parse a scalar value (i.e. not an Object or Array)\n *\n * @return The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */\n UserDataConverter.prototype.parseScalarValue = function (value, context) {\n if (value === null) {\n return NullValue.INSTANCE;\n }\n else if (typeof value === 'number') {\n if (isSafeInteger(value)) {\n return new IntegerValue(value);\n }\n else {\n return new DoubleValue(value);\n }\n }\n else if (typeof value === 'boolean') {\n return field_value_BooleanValue.of(value);\n }\n else if (typeof value === 'string') {\n return new field_value_StringValue(value);\n }\n else if (value instanceof Date) {\n return new TimestampValue(timestamp_Timestamp.fromDate(value));\n }\n else if (value instanceof geo_point_GeoPoint) {\n return new GeoPointValue(value);\n }\n else if (value instanceof blob_Blob) {\n return new BlobValue(value);\n }\n else if (value instanceof DocumentKeyReference) {\n return new field_value_RefValue(value.databaseId, value.key);\n }\n else if (value instanceof FieldValueImpl) {\n if (value instanceof DeleteFieldValueImpl) {\n if (context.dataSource === UserDataSource.MergeSet) {\n return null;\n }\n else if (context.dataSource === UserDataSource.Update) {\n assert(context.path == null || context.path.length > 0, 'FieldValue.delete() at the top level should have already' +\n ' been handled.');\n throw context.createError('FieldValue.delete() can only appear at the top level ' +\n 'of your update data');\n }\n else {\n // We shouldn't encounter delete sentinels for queries or non-merge set() calls.\n throw context.createError('FieldValue.delete() can only be used with update() and set() with {merge:true}');\n }\n }\n else if (value instanceof ServerTimestampFieldValueImpl) {\n if (!isWrite(context.dataSource)) {\n throw context.createError('FieldValue.serverTimestamp() can only be used with set()' +\n ' and update()');\n }\n if (context.path === null) {\n throw context.createError('FieldValue.serverTimestamp() is not currently' +\n ' supported inside arrays');\n }\n context.fieldTransforms.push(new FieldTransform(context.path, ServerTimestampTransform.instance));\n // Return null so this value is omitted from the parsed result.\n return null;\n }\n else {\n return fail('Unknown FieldValue type: ' + value);\n }\n }\n else {\n throw context.createError(\"Unsupported field value: \" + valueDescription(value));\n }\n };\n return UserDataConverter;\n}());\n\n/**\n * Checks whether an object looks like a JSON object that should be converted\n * into a struct. Normal class/prototype instances are considered to look like\n * JSON objects since they should be converted to a struct value. Arrays, Dates,\n * GeoPoints, etc. are not considered to look like JSON objects since they map\n * to specific FieldValue types other than ObjectValue.\n */\nfunction looksLikeJsonObject(input) {\n return (typeof input === 'object' &&\n input !== null &&\n !(input instanceof Array) &&\n !(input instanceof Date) &&\n !(input instanceof geo_point_GeoPoint) &&\n !(input instanceof blob_Blob) &&\n !(input instanceof DocumentKeyReference) &&\n !(input instanceof FieldValueImpl));\n}\nfunction validatePlainObject(message, context, input) {\n if (!looksLikeJsonObject(input) || !isPlainObject(input)) {\n var description = valueDescription(input);\n if (description === 'an object') {\n // Massage the error if it was an object.\n throw context.createError(message + ' a custom object');\n }\n else {\n throw context.createError(message + ' ' + description);\n }\n }\n}\n/**\n * Helper that calls fromDotSeparatedString() but wraps any error thrown.\n */\nfunction fieldPathFromArgument(methodName, path) {\n if (path instanceof field_path_FieldPath) {\n return path._internalPath;\n }\n else if (typeof path === 'string') {\n return fieldPathFromDotSeparatedString(methodName, path);\n }\n else {\n var message = 'Field path arguments must be of type string or FieldPath.';\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + methodName + \"() called with invalid data. \" + message);\n }\n}\n/**\n * Wraps fromDotSeparatedString with an error message about the method that\n * was thrown.\n * @param methodName The publicly visible method name\n * @param path The dot-separated string form of a field path which will be split\n * on dots.\n */\nfunction fieldPathFromDotSeparatedString(methodName, path) {\n try {\n return fromDotSeparatedString(path)._internalPath;\n }\n catch (e) {\n var message = errorMessage(e);\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + methodName + \"() called with invalid data. \" + message);\n }\n}\n/**\n * Extracts the message from a caught exception, which should be an Error object\n * though JS doesn't guarantee that.\n */\nfunction errorMessage(error) {\n return error instanceof Error ? error.message : error.toString();\n}\n\n//# sourceMappingURL=user_data_converter.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/api/database.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar database___extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n// The objects that are a part of this API are exposed to third-parties as\n// compiled javascript so we want to flag our private members with a leading\n// underscore to discourage their use.\n// tslint:disable:strip-private-property-underscore\nvar DEFAULT_HOST = 'firestore.googleapis.com';\nvar DEFAULT_SSL = true;\n/**\n * A concrete type describing all the values that can be applied via a\n * user-supplied firestore.Settings object. This is a separate type so that\n * defaults can be supplied and the value can be checked for equality.\n */\nvar database_FirestoreSettings = /** @class */ (function () {\n function FirestoreSettings(settings) {\n if (settings.host === undefined) {\n if (settings.ssl !== undefined) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Can't provide ssl option if host option is not set\");\n }\n this.host = DEFAULT_HOST;\n this.ssl = DEFAULT_SSL;\n }\n else {\n validateNamedType('settings', 'string', 'host', settings.host);\n this.host = settings.host;\n validateNamedOptionalType('settings', 'boolean', 'ssl', settings.ssl);\n this.ssl = defaulted(settings.ssl, DEFAULT_SSL);\n }\n validateOptionNames('settings', settings, ['host', 'ssl', 'credentials']);\n validateNamedOptionalType('settings', 'object', 'credentials', settings.credentials);\n this.credentials = settings.credentials;\n }\n FirestoreSettings.prototype.isEqual = function (other) {\n return (this.host === other.host &&\n this.ssl === other.ssl &&\n this.credentials === other.credentials);\n };\n return FirestoreSettings;\n}());\nvar FirestoreConfig = /** @class */ (function () {\n function FirestoreConfig() {\n }\n return FirestoreConfig;\n}());\n/**\n * The root reference to the database.\n */\nvar database_Firestore = /** @class */ (function () {\n function Firestore(databaseIdOrApp) {\n var _this = this;\n this._queue = new async_queue_AsyncQueue();\n this.INTERNAL = {\n delete: function () {\n if (_this._firestoreClient) {\n return _this._firestoreClient.shutdown();\n }\n else {\n return Promise.resolve();\n }\n },\n // Exposed via INTERNAL for use in tests.\n drainAsyncQueue: function (executeDelayedTasks) {\n return _this._queue.drain(executeDelayedTasks);\n }\n };\n var config = new FirestoreConfig();\n if (typeof databaseIdOrApp.options === 'object') {\n // This is very likely a Firebase app object\n // TODO(b/34177605): Can we somehow use instanceof?\n var app = databaseIdOrApp;\n config.firebaseApp = app;\n config.databaseId = Firestore.databaseIdFromApp(app);\n config.persistenceKey = config.firebaseApp.name;\n config.credentials = new credentials_FirebaseCredentialsProvider(app);\n }\n else {\n var external_1 = databaseIdOrApp;\n if (!external_1.projectId) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Must provide projectId');\n }\n config.databaseId = new database_info_DatabaseId(external_1.projectId, external_1.database);\n // Use a default persistenceKey that lines up with FirebaseApp.\n config.persistenceKey = '[DEFAULT]';\n config.credentials = new credentials_EmptyCredentialsProvider();\n }\n config.settings = new database_FirestoreSettings({});\n this._config = config;\n this._databaseId = config.databaseId;\n }\n Firestore.prototype.settings = function (settingsLiteral) {\n validateExactNumberOfArgs('Firestore.settings', arguments, 1);\n validateArgType('Firestore.settings', 'object', 1, settingsLiteral);\n if (contains(settingsLiteral, 'persistence')) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, '\"persistence\" is now specified with a separate call to ' +\n 'firestore.enablePersistence().');\n }\n var newSettings = new database_FirestoreSettings(settingsLiteral);\n if (this._firestoreClient && !this._config.settings.isEqual(newSettings)) {\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore has already been started and its settings can no longer ' +\n 'be changed. You can only call settings() before calling any other ' +\n 'methods on a Firestore object.');\n }\n this._config.settings = newSettings;\n if (newSettings.credentials !== undefined) {\n this._config.credentials = makeCredentialsProvider(newSettings.credentials);\n }\n };\n Firestore.prototype.enableNetwork = function () {\n this.ensureClientConfigured();\n return this._firestoreClient.enableNetwork();\n };\n Firestore.prototype.disableNetwork = function () {\n this.ensureClientConfigured();\n return this._firestoreClient.disableNetwork();\n };\n Firestore.prototype.enablePersistence = function () {\n if (this._firestoreClient) {\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore has already been started and persistence can no longer ' +\n 'be enabled. You can only call enablePersistence() before calling ' +\n 'any other methods on a Firestore object.');\n }\n return this.configureClient(/* persistence= */ true);\n };\n Firestore.prototype.ensureClientConfigured = function () {\n if (!this._firestoreClient) {\n this.configureClient(/* persistence= */ false);\n }\n return this._firestoreClient;\n };\n Firestore.prototype.configureClient = function (persistence) {\n var _this = this;\n assert(!!this._config.settings.host, 'FirestoreSettings.host cannot be falsey');\n assert(!this._firestoreClient, 'configureClient() called multiple times');\n var databaseInfo = new DatabaseInfo(this._config.databaseId, this._config.persistenceKey, this._config.settings.host, this._config.settings.ssl);\n var preConverter = function (value) {\n if (value instanceof database_DocumentReference) {\n var thisDb = _this._config.databaseId;\n var otherDb = value.firestore._config.databaseId;\n if (!otherDb.isEqual(thisDb)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Document reference is for database ' +\n (otherDb.projectId + \"/\" + otherDb.database + \" but should be \") +\n (\"for database \" + thisDb.projectId + \"/\" + thisDb.database));\n }\n return new DocumentKeyReference(_this._config.databaseId, value._key);\n }\n else {\n return value;\n }\n };\n this._dataConverter = new user_data_converter_UserDataConverter(preConverter);\n this._firestoreClient = new firestore_client_FirestoreClient(platform_PlatformSupport.getPlatform(), databaseInfo, this._config.credentials, this._queue);\n return this._firestoreClient.start(persistence);\n };\n Firestore.databaseIdFromApp = function (app) {\n var options = app.options;\n if (!contains(options, 'projectId')) {\n // TODO(b/62673263): We can safely remove the special handling of\n // 'firestoreId' once alpha testers have upgraded.\n if (contains(options, 'firestoreId')) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, '\"firestoreId\" is now specified as \"projectId\" in ' +\n 'firebase.initializeApp.');\n }\n throw new FirestoreError(Code.INVALID_ARGUMENT, '\"projectId\" not provided in firebase.initializeApp.');\n }\n if (contains(options, 'firestoreOptions')) {\n // TODO(b/62673263): We can safely remove the special handling of\n // 'firestoreOptions' once alpha testers have upgraded.\n throw new FirestoreError(Code.INVALID_ARGUMENT, '\"firestoreOptions\" values are now specified with ' +\n 'Firestore.settings()');\n }\n var projectId = options['projectId'];\n if (!projectId || typeof projectId !== 'string') {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'projectId must be a string in FirebaseApp.options');\n }\n return new database_info_DatabaseId(projectId);\n };\n Object.defineProperty(Firestore.prototype, \"app\", {\n get: function () {\n if (!this._config.firebaseApp) {\n throw new FirestoreError(Code.FAILED_PRECONDITION, \"Firestore was not initialized using the Firebase SDK. 'app' is \" +\n 'not available');\n }\n return this._config.firebaseApp;\n },\n enumerable: true,\n configurable: true\n });\n Firestore.prototype.collection = function (pathString) {\n validateExactNumberOfArgs('Firestore.collection', arguments, 1);\n validateArgType('Firestore.collection', 'string', 1, pathString);\n if (!pathString) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Must provide a non-empty collection path to collection()');\n }\n this.ensureClientConfigured();\n return new database_CollectionReference(path_ResourcePath.fromString(pathString), this);\n };\n Firestore.prototype.doc = function (pathString) {\n validateExactNumberOfArgs('Firestore.doc', arguments, 1);\n validateArgType('Firestore.doc', 'string', 1, pathString);\n if (!pathString) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Must provide a non-empty document path to doc()');\n }\n this.ensureClientConfigured();\n return database_DocumentReference.forPath(path_ResourcePath.fromString(pathString), this);\n };\n Firestore.prototype.runTransaction = function (updateFunction) {\n var _this = this;\n validateExactNumberOfArgs('Firestore.runTransaction', arguments, 1);\n validateArgType('Firestore.runTransaction', 'function', 1, updateFunction);\n return this.ensureClientConfigured().transaction(function (transaction) {\n return updateFunction(new database_Transaction(_this, transaction));\n });\n };\n Firestore.prototype.batch = function () {\n this.ensureClientConfigured();\n return new database_WriteBatch(this);\n };\n Object.defineProperty(Firestore, \"logLevel\", {\n get: function () {\n switch (getLogLevel()) {\n case LogLevel.DEBUG:\n return 'debug';\n case LogLevel.ERROR:\n return 'error';\n case LogLevel.SILENT:\n return 'silent';\n default:\n return fail('Unknown log level: ' + getLogLevel());\n }\n },\n enumerable: true,\n configurable: true\n });\n Firestore.setLogLevel = function (level) {\n validateExactNumberOfArgs('Firestore.setLogLevel', arguments, 1);\n validateArgType('Firestore.setLogLevel', 'string', 1, level);\n switch (level) {\n case 'debug':\n setLogLevel(LogLevel.DEBUG);\n break;\n case 'error':\n setLogLevel(LogLevel.ERROR);\n break;\n case 'silent':\n setLogLevel(LogLevel.SILENT);\n break;\n default:\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid log level: ' + level);\n }\n };\n return Firestore;\n}());\n\n/**\n * A reference to a transaction.\n */\nvar database_Transaction = /** @class */ (function () {\n function Transaction(_firestore, _transaction) {\n this._firestore = _firestore;\n this._transaction = _transaction;\n }\n Transaction.prototype.get = function (documentRef) {\n var _this = this;\n validateExactNumberOfArgs('Transaction.get', arguments, 1);\n var ref = validateReference('Transaction.get', documentRef, this._firestore);\n return this._transaction\n .lookup([ref._key])\n .then(function (docs) {\n if (!docs || docs.length !== 1) {\n return fail('Mismatch in docs returned from document lookup.');\n }\n var doc = docs[0];\n if (doc instanceof document_NoDocument) {\n return new database_DocumentSnapshot(_this._firestore, ref._key, null, false);\n }\n return new database_DocumentSnapshot(_this._firestore, ref._key, doc, false);\n });\n };\n Transaction.prototype.set = function (documentRef, value, options) {\n validateBetweenNumberOfArgs('Transaction.set', arguments, 2, 3);\n var ref = validateReference('Transaction.set', documentRef, this._firestore);\n options = validateSetOptions('Transaction.set', options);\n var parsed = options.merge\n ? this._firestore._dataConverter.parseMergeData('Transaction.set', value)\n : this._firestore._dataConverter.parseSetData('Transaction.set', value);\n this._transaction.set(ref._key, parsed);\n return this;\n };\n Transaction.prototype.update = function (documentRef, fieldOrUpdateData, value) {\n var moreFieldsAndValues = [];\n for (var _i = 3; _i < arguments.length; _i++) {\n moreFieldsAndValues[_i - 3] = arguments[_i];\n }\n var ref;\n var parsed;\n if (typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof field_path_FieldPath) {\n validateAtLeastNumberOfArgs('Transaction.update', arguments, 3);\n ref = validateReference('Transaction.update', documentRef, this._firestore);\n parsed = this._firestore._dataConverter.parseUpdateVarargs('Transaction.update', fieldOrUpdateData, value, moreFieldsAndValues);\n }\n else {\n validateExactNumberOfArgs('Transaction.update', arguments, 2);\n ref = validateReference('Transaction.update', documentRef, this._firestore);\n parsed = this._firestore._dataConverter.parseUpdateData('Transaction.update', fieldOrUpdateData);\n }\n this._transaction.update(ref._key, parsed);\n return this;\n };\n Transaction.prototype.delete = function (documentRef) {\n validateExactNumberOfArgs('Transaction.delete', arguments, 1);\n var ref = validateReference('Transaction.delete', documentRef, this._firestore);\n this._transaction.delete(ref._key);\n return this;\n };\n return Transaction;\n}());\n\nvar database_WriteBatch = /** @class */ (function () {\n function WriteBatch(_firestore) {\n this._firestore = _firestore;\n this._mutations = [];\n this._committed = false;\n }\n WriteBatch.prototype.set = function (documentRef, value, options) {\n validateBetweenNumberOfArgs('WriteBatch.set', arguments, 2, 3);\n this.verifyNotCommitted();\n var ref = validateReference('WriteBatch.set', documentRef, this._firestore);\n options = validateSetOptions('WriteBatch.set', options);\n var parsed = options.merge\n ? this._firestore._dataConverter.parseMergeData('WriteBatch.set', value)\n : this._firestore._dataConverter.parseSetData('WriteBatch.set', value);\n this._mutations = this._mutations.concat(parsed.toMutations(ref._key, mutation_Precondition.NONE));\n return this;\n };\n WriteBatch.prototype.update = function (documentRef, fieldOrUpdateData, value) {\n var moreFieldsAndValues = [];\n for (var _i = 3; _i < arguments.length; _i++) {\n moreFieldsAndValues[_i - 3] = arguments[_i];\n }\n this.verifyNotCommitted();\n var ref;\n var parsed;\n if (typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof field_path_FieldPath) {\n validateAtLeastNumberOfArgs('WriteBatch.update', arguments, 3);\n ref = validateReference('WriteBatch.update', documentRef, this._firestore);\n parsed = this._firestore._dataConverter.parseUpdateVarargs('WriteBatch.update', fieldOrUpdateData, value, moreFieldsAndValues);\n }\n else {\n validateExactNumberOfArgs('WriteBatch.update', arguments, 2);\n ref = validateReference('WriteBatch.update', documentRef, this._firestore);\n parsed = this._firestore._dataConverter.parseUpdateData('WriteBatch.update', fieldOrUpdateData);\n }\n this._mutations = this._mutations.concat(parsed.toMutations(ref._key, mutation_Precondition.exists(true)));\n return this;\n };\n WriteBatch.prototype.delete = function (documentRef) {\n validateExactNumberOfArgs('WriteBatch.delete', arguments, 1);\n this.verifyNotCommitted();\n var ref = validateReference('WriteBatch.delete', documentRef, this._firestore);\n this._mutations = this._mutations.concat(new mutation_DeleteMutation(ref._key, mutation_Precondition.NONE));\n return this;\n };\n WriteBatch.prototype.commit = function () {\n this.verifyNotCommitted();\n this._committed = true;\n if (this._mutations.length > 0) {\n return this._firestore.ensureClientConfigured().write(this._mutations);\n }\n else {\n return Promise.resolve();\n }\n };\n WriteBatch.prototype.verifyNotCommitted = function () {\n if (this._committed) {\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'A write batch can no longer be used after commit() ' +\n 'has been called.');\n }\n };\n return WriteBatch;\n}());\n\n/**\n * A reference to a particular document in a collection in the database.\n */\nvar database_DocumentReference = /** @class */ (function () {\n function DocumentReference(_key, firestore) {\n this._key = _key;\n this.firestore = firestore;\n this._firestoreClient = this.firestore.ensureClientConfigured();\n }\n DocumentReference.forPath = function (path, firestore) {\n if (path.length % 2 !== 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid document reference. Document ' +\n 'references must have an even number of segments, but ' +\n (path.canonicalString() + \" has \" + path.length));\n }\n return new DocumentReference(new document_key_DocumentKey(path), firestore);\n };\n Object.defineProperty(DocumentReference.prototype, \"id\", {\n get: function () {\n return this._key.path.lastSegment();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentReference.prototype, \"parent\", {\n get: function () {\n return new database_CollectionReference(this._key.path.popLast(), this.firestore);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentReference.prototype, \"path\", {\n get: function () {\n return this._key.path.canonicalString();\n },\n enumerable: true,\n configurable: true\n });\n DocumentReference.prototype.collection = function (pathString) {\n validateExactNumberOfArgs('DocumentReference.collection', arguments, 1);\n validateArgType('DocumentReference.collection', 'string', 1, pathString);\n if (!pathString) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Must provide a non-empty collection name to collection()');\n }\n var path = path_ResourcePath.fromString(pathString);\n return new database_CollectionReference(this._key.path.child(path), this.firestore);\n };\n DocumentReference.prototype.isEqual = function (other) {\n if (!(other instanceof DocumentReference)) {\n throw invalidClassError('isEqual', 'DocumentReference', 1, other);\n }\n return this.firestore === other.firestore && this._key.isEqual(other._key);\n };\n DocumentReference.prototype.set = function (value, options) {\n validateBetweenNumberOfArgs('DocumentReference.set', arguments, 1, 2);\n options = validateSetOptions('DocumentReference.set', options);\n var parsed = options.merge\n ? this.firestore._dataConverter.parseMergeData('DocumentReference.set', value)\n : this.firestore._dataConverter.parseSetData('DocumentReference.set', value);\n return this._firestoreClient.write(parsed.toMutations(this._key, mutation_Precondition.NONE));\n };\n DocumentReference.prototype.update = function (fieldOrUpdateData, value) {\n var moreFieldsAndValues = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n moreFieldsAndValues[_i - 2] = arguments[_i];\n }\n var parsed;\n if (typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof field_path_FieldPath) {\n validateAtLeastNumberOfArgs('DocumentReference.update', arguments, 2);\n parsed = this.firestore._dataConverter.parseUpdateVarargs('DocumentReference.update', fieldOrUpdateData, value, moreFieldsAndValues);\n }\n else {\n validateExactNumberOfArgs('DocumentReference.update', arguments, 1);\n parsed = this.firestore._dataConverter.parseUpdateData('DocumentReference.update', fieldOrUpdateData);\n }\n return this._firestoreClient.write(parsed.toMutations(this._key, mutation_Precondition.exists(true)));\n };\n DocumentReference.prototype.delete = function () {\n validateExactNumberOfArgs('DocumentReference.delete', arguments, 0);\n return this._firestoreClient.write([\n new mutation_DeleteMutation(this._key, mutation_Precondition.NONE)\n ]);\n };\n DocumentReference.prototype.onSnapshot = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n validateBetweenNumberOfArgs('DocumentReference.onSnapshot', arguments, 1, 4);\n var options = {\n includeMetadataChanges: false\n };\n var observer;\n var currArg = 0;\n if (typeof args[currArg] === 'object' &&\n !isPartialObserver(args[currArg])) {\n options = args[currArg];\n validateOptionNames('DocumentReference.onSnapshot', options, [\n 'includeMetadataChanges'\n ]);\n validateNamedOptionalType('DocumentReference.onSnapshot', 'boolean', 'includeMetadataChanges', options.includeMetadataChanges);\n currArg++;\n }\n var internalOptions = {\n includeDocumentMetadataChanges: options.includeMetadataChanges,\n includeQueryMetadataChanges: options.includeMetadataChanges\n };\n if (isPartialObserver(args[currArg])) {\n observer = args[currArg];\n }\n else {\n validateArgType('DocumentReference.onSnapshot', 'function', currArg, args[currArg]);\n validateOptionalArgType('DocumentReference.onSnapshot', 'function', currArg + 1, args[currArg + 1]);\n validateOptionalArgType('DocumentReference.onSnapshot', 'function', currArg + 2, args[currArg + 2]);\n observer = {\n next: args[currArg],\n error: args[currArg + 1],\n complete: args[currArg + 2]\n };\n }\n return this.onSnapshotInternal(internalOptions, observer);\n };\n DocumentReference.prototype.onSnapshotInternal = function (options, observer) {\n var _this = this;\n var errHandler = function (err) {\n console.error('Uncaught Error in onSnapshot:', err);\n };\n if (observer.error) {\n errHandler = observer.error.bind(observer);\n }\n var asyncObserver = new AsyncObserver({\n next: function (snapshot) {\n if (observer.next) {\n assert(snapshot.docs.size <= 1, 'Too many documents returned on a document query');\n var doc = snapshot.docs.get(_this._key);\n observer.next(new database_DocumentSnapshot(_this.firestore, _this._key, doc, snapshot.fromCache));\n }\n },\n error: errHandler\n });\n var internalListener = this._firestoreClient.listen(query_Query.atPath(this._key.path), asyncObserver, options);\n return function () {\n asyncObserver.mute();\n _this._firestoreClient.unlisten(internalListener);\n };\n };\n DocumentReference.prototype.get = function () {\n var _this = this;\n validateExactNumberOfArgs('DocumentReference.get', arguments, 0);\n return new Promise(function (resolve, reject) {\n var unlisten = _this.onSnapshotInternal({\n includeQueryMetadataChanges: true,\n includeDocumentMetadataChanges: true,\n waitForSyncWhenOnline: true\n }, {\n next: function (snap) {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n unlisten();\n if (!snap.exists && snap.metadata.fromCache) {\n // TODO(dimond): If we're online and the document doesn't\n // exist then we resolve with a doc.exists set to false. If\n // we're offline however, we reject the Promise in this\n // case. Two options: 1) Cache the negative response from\n // the server so we can deliver that even when you're\n // offline 2) Actually reject the Promise in the online case\n // if the document doesn't exist.\n reject(new FirestoreError(Code.ABORTED, 'Failed to get document because the client is ' + 'offline.'));\n }\n else {\n resolve(snap);\n }\n },\n error: reject\n });\n });\n };\n return DocumentReference;\n}());\n\nvar SnapshotMetadata = /** @class */ (function () {\n function SnapshotMetadata(hasPendingWrites, fromCache) {\n this.hasPendingWrites = hasPendingWrites;\n this.fromCache = fromCache;\n }\n SnapshotMetadata.prototype.isEqual = function (other) {\n return (this.hasPendingWrites === other.hasPendingWrites &&\n this.fromCache === other.fromCache);\n };\n return SnapshotMetadata;\n}());\nvar database_DocumentSnapshot = /** @class */ (function () {\n function DocumentSnapshot(_firestore, _key, _document, _fromCache) {\n this._firestore = _firestore;\n this._key = _key;\n this._document = _document;\n this._fromCache = _fromCache;\n }\n DocumentSnapshot.prototype.data = function (options) {\n validateBetweenNumberOfArgs('DocumentSnapshot.data', arguments, 0, 1);\n options = validateSnapshotOptions('DocumentSnapshot.data', options);\n return !this._document\n ? undefined\n : this.convertObject(this._document.data, field_value_FieldValueOptions.fromSnapshotOptions(options));\n };\n DocumentSnapshot.prototype.get = function (fieldPath, options) {\n validateBetweenNumberOfArgs('DocumentSnapshot.get', arguments, 1, 2);\n options = validateSnapshotOptions('DocumentSnapshot.get', options);\n if (this._document) {\n var value = this._document.data.field(fieldPathFromArgument('DocumentSnapshot.get', fieldPath));\n if (value !== undefined) {\n return this.convertValue(value, field_value_FieldValueOptions.fromSnapshotOptions(options));\n }\n }\n return undefined;\n };\n Object.defineProperty(DocumentSnapshot.prototype, \"id\", {\n get: function () {\n return this._key.path.lastSegment();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentSnapshot.prototype, \"ref\", {\n get: function () {\n return new database_DocumentReference(this._key, this._firestore);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentSnapshot.prototype, \"exists\", {\n get: function () {\n return this._document !== null;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentSnapshot.prototype, \"metadata\", {\n get: function () {\n return new SnapshotMetadata(this._document !== null && this._document.hasLocalMutations, this._fromCache);\n },\n enumerable: true,\n configurable: true\n });\n DocumentSnapshot.prototype.isEqual = function (other) {\n if (!(other instanceof DocumentSnapshot)) {\n throw invalidClassError('isEqual', 'DocumentSnapshot', 1, other);\n }\n return (this._firestore === other._firestore &&\n this._fromCache === other._fromCache &&\n this._key.isEqual(other._key) &&\n (this._document === null\n ? other._document === null\n : this._document.isEqual(other._document)));\n };\n DocumentSnapshot.prototype.convertObject = function (data, options) {\n var _this = this;\n var result = {};\n data.forEach(function (key, value) {\n result[key] = _this.convertValue(value, options);\n });\n return result;\n };\n DocumentSnapshot.prototype.convertValue = function (value, options) {\n if (value instanceof field_value_ObjectValue) {\n return this.convertObject(value, options);\n }\n else if (value instanceof field_value_ArrayValue) {\n return this.convertArray(value, options);\n }\n else if (value instanceof field_value_RefValue) {\n var key = value.value(options);\n var database = this._firestore.ensureClientConfigured().databaseId();\n if (!value.databaseId.isEqual(database)) {\n // TODO(b/64130202): Somehow support foreign references.\n log_error(\"Document \" + this._key.path + \" contains a document \" +\n \"reference within a different database (\" +\n (value.databaseId.projectId + \"/\" + value.databaseId.database + \") which is not \") +\n \"supported. It will be treated as a reference in the current \" +\n (\"database (\" + database.projectId + \"/\" + database.database + \") \") +\n \"instead.\");\n }\n return new database_DocumentReference(key, this._firestore);\n }\n else {\n return value.value(options);\n }\n };\n DocumentSnapshot.prototype.convertArray = function (data, options) {\n var _this = this;\n return data.internalValue.map(function (value) {\n return _this.convertValue(value, options);\n });\n };\n return DocumentSnapshot;\n}());\n\nvar database_QueryDocumentSnapshot = /** @class */ (function (_super) {\n database___extends(QueryDocumentSnapshot, _super);\n function QueryDocumentSnapshot(firestore, key, document, fromCache) {\n return _super.call(this, firestore, key, document, fromCache) || this;\n }\n QueryDocumentSnapshot.prototype.data = function (options) {\n var data = _super.prototype.data.call(this, options);\n assert(typeof data === 'object', 'Document in a QueryDocumentSnapshot should exist');\n return data;\n };\n return QueryDocumentSnapshot;\n}(database_DocumentSnapshot));\n\nvar database_Query = /** @class */ (function () {\n function Query(_query, firestore) {\n this._query = _query;\n this.firestore = firestore;\n }\n Query.prototype.where = function (field, opStr, value) {\n validateExactNumberOfArgs('Query.where', arguments, 3);\n validateArgType('Query.where', 'string', 2, opStr);\n validateDefined('Query.where', 3, value);\n var fieldValue;\n var fieldPath = fieldPathFromArgument('Query.where', field);\n if (fieldPath.isKeyField()) {\n if (typeof value === 'string') {\n if (value.indexOf('/') !== -1) {\n // TODO(dimond): Allow slashes once ancestor queries are supported\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Function Query.where() requires its third parameter to be a ' +\n 'valid document ID if the first parameter is ' +\n 'FieldPath.documentId(), but it contains a slash.');\n }\n if (value === '') {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Function Query.where() requires its third parameter to be a ' +\n 'valid document ID if the first parameter is ' +\n 'FieldPath.documentId(), but it was an empty string.');\n }\n var path = this._query.path.child(new path_ResourcePath([value]));\n assert(path.length % 2 === 0, 'Path should be a document key');\n fieldValue = new field_value_RefValue(this.firestore._databaseId, new document_key_DocumentKey(path));\n }\n else if (value instanceof database_DocumentReference) {\n var ref = value;\n fieldValue = new field_value_RefValue(this.firestore._databaseId, ref._key);\n }\n else {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function Query.where() requires its third parameter to be a \" +\n \"string or a DocumentReference if the first parameter is \" +\n \"FieldPath.documentId(), but it was: \" +\n (valueDescription(value) + \".\"));\n }\n }\n else {\n fieldValue = this.firestore._dataConverter.parseQueryValue('Query.where', value);\n }\n var filter = fieldFilter(fieldPath, query_RelationOp.fromString(opStr), fieldValue);\n this.validateNewFilter(filter);\n return new Query(this._query.addFilter(filter), this.firestore);\n };\n Query.prototype.orderBy = function (field, directionStr) {\n validateBetweenNumberOfArgs('Query.orderBy', arguments, 1, 2);\n validateOptionalArgType('Query.orderBy', 'string', 2, directionStr);\n var direction;\n if (directionStr === undefined || directionStr === 'asc') {\n direction = Direction.ASCENDING;\n }\n else if (directionStr === 'desc') {\n direction = Direction.DESCENDING;\n }\n else {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function Query.orderBy() has unknown direction '\" + directionStr + \"', \" +\n \"expected 'asc' or 'desc'.\");\n }\n if (this._query.startAt !== null) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call Query.startAt() or ' +\n 'Query.startAfter() before calling Query.orderBy().');\n }\n if (this._query.endAt !== null) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call Query.endAt() or ' +\n 'Query.endBefore() before calling Query.orderBy().');\n }\n var fieldPath = fieldPathFromArgument('Query.orderBy', field);\n var orderBy = new query_OrderBy(fieldPath, direction);\n this.validateNewOrderBy(orderBy);\n return new Query(this._query.addOrderBy(orderBy), this.firestore);\n };\n Query.prototype.limit = function (n) {\n validateExactNumberOfArgs('Query.limit', arguments, 1);\n validateArgType('Query.limit', 'number', 1, n);\n if (n <= 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid Query. Query limit (\" + n + \") is invalid. Limit must be \" +\n 'positive.');\n }\n return new Query(this._query.withLimit(n), this.firestore);\n };\n Query.prototype.startAt = function (docOrField) {\n var fields = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n fields[_i - 1] = arguments[_i];\n }\n validateAtLeastNumberOfArgs('Query.startAt', arguments, 1);\n var bound = this.boundFromDocOrFields('Query.startAt', docOrField, fields, \n /*before=*/ true);\n return new Query(this._query.withStartAt(bound), this.firestore);\n };\n Query.prototype.startAfter = function (docOrField) {\n var fields = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n fields[_i - 1] = arguments[_i];\n }\n validateAtLeastNumberOfArgs('Query.startAfter', arguments, 1);\n var bound = this.boundFromDocOrFields('Query.startAfter', docOrField, fields, \n /*before=*/ false);\n return new Query(this._query.withStartAt(bound), this.firestore);\n };\n Query.prototype.endBefore = function (docOrField) {\n var fields = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n fields[_i - 1] = arguments[_i];\n }\n validateAtLeastNumberOfArgs('Query.endBefore', arguments, 1);\n var bound = this.boundFromDocOrFields('Query.endBefore', docOrField, fields, \n /*before=*/ true);\n return new Query(this._query.withEndAt(bound), this.firestore);\n };\n Query.prototype.endAt = function (docOrField) {\n var fields = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n fields[_i - 1] = arguments[_i];\n }\n validateAtLeastNumberOfArgs('Query.endAt', arguments, 1);\n var bound = this.boundFromDocOrFields('Query.endAt', docOrField, fields, \n /*before=*/ false);\n return new Query(this._query.withEndAt(bound), this.firestore);\n };\n Query.prototype.isEqual = function (other) {\n if (!(other instanceof Query)) {\n throw invalidClassError('isEqual', 'Query', 1, other);\n }\n return (this.firestore === other.firestore && this._query.isEqual(other._query));\n };\n /** Helper function to create a bound from a document or fields */\n Query.prototype.boundFromDocOrFields = function (methodName, docOrField, fields, before) {\n validateDefined(methodName, 1, docOrField);\n if (docOrField instanceof database_DocumentSnapshot) {\n if (fields.length > 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Too many arguments provided to \" + methodName + \"().\");\n }\n var snap = docOrField;\n if (!snap.exists) {\n throw new FirestoreError(Code.NOT_FOUND, \"Can't use a DocumentSnapshot that doesn't exist for \" +\n (methodName + \"().\"));\n }\n return this.boundFromDocument(methodName, snap._document, before);\n }\n else {\n var allFields = [docOrField].concat(fields);\n return this.boundFromFields(methodName, allFields, before);\n }\n };\n /**\n * Create a Bound from a query and a document.\n *\n * Note that the Bound will always include the key of the document\n * and so only the provided document will compare equal to the returned\n * position.\n *\n * Will throw if the document does not contain all fields of the order by\n * of the query.\n */\n Query.prototype.boundFromDocument = function (methodName, doc, before) {\n var components = [];\n // Because people expect to continue/end a query at the exact document\n // provided, we need to use the implicit sort order rather than the explicit\n // sort order, because it's guaranteed to contain the document key. That way\n // the position becomes unambiguous and the query continues/ends exactly at\n // the provided document. Without the key (by using the explicit sort\n // orders), multiple documents could match the position, yielding duplicate\n // results.\n for (var _i = 0, _a = this._query.orderBy; _i < _a.length; _i++) {\n var orderBy = _a[_i];\n if (orderBy.field.isKeyField()) {\n components.push(new field_value_RefValue(this.firestore._databaseId, doc.key));\n }\n else {\n var value = doc.field(orderBy.field);\n if (value !== undefined) {\n components.push(value);\n }\n else {\n var field = orderBy.field.canonicalString();\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. You are trying to start or end a query using a \" +\n (\"document for which the field '\" + field + \"' (used as the \") +\n \"orderBy) does not exist.\");\n }\n }\n }\n return new query_Bound(components, before);\n };\n /**\n * Converts a list of field values to a Bound for the given query.\n */\n Query.prototype.boundFromFields = function (methodName, values, before) {\n // Use explicit order by's because it has to match the query the user made\n var orderBy = this._query.explicitOrderBy;\n if (values.length > orderBy.length) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Too many arguments provided to \" + methodName + \"(). \" +\n \"The number of arguments must be less than or equal to the \" +\n \"number of Query.orderBy() clauses\");\n }\n var components = [];\n for (var i = 0; i < values.length; i++) {\n var rawValue = values[i];\n var orderByComponent = orderBy[i];\n if (orderByComponent.field.isKeyField()) {\n if (typeof rawValue !== 'string') {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. Expected a string for document ID in \" +\n (methodName + \"(), but got a \" + typeof rawValue));\n }\n if (rawValue.indexOf('/') !== -1) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. Document ID '\" + rawValue + \"' contains a slash in \" +\n (methodName + \"()\"));\n }\n var key = new document_key_DocumentKey(this._query.path.child(rawValue));\n components.push(new field_value_RefValue(this.firestore._databaseId, key));\n }\n else {\n var wrapped = this.firestore._dataConverter.parseQueryValue(methodName, rawValue);\n components.push(wrapped);\n }\n }\n return new query_Bound(components, before);\n };\n Query.prototype.onSnapshot = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n validateBetweenNumberOfArgs('Query.onSnapshot', arguments, 1, 4);\n var options = {};\n var observer;\n var currArg = 0;\n if (typeof args[currArg] === 'object' &&\n !isPartialObserver(args[currArg])) {\n options = args[currArg];\n validateOptionNames('Query.onSnapshot', options, [\n 'includeQueryMetadataChanges',\n 'includeDocumentMetadataChanges'\n ]);\n validateNamedOptionalType('Query.onSnapshot', 'boolean', 'includeDocumentMetadataChanges', options.includeDocumentMetadataChanges);\n validateNamedOptionalType('Query.onSnapshot', 'boolean', 'includeQueryMetadataChanges', options.includeQueryMetadataChanges);\n currArg++;\n }\n if (isPartialObserver(args[currArg])) {\n observer = args[currArg];\n }\n else {\n validateArgType('Query.onSnapshot', 'function', currArg, args[currArg]);\n validateOptionalArgType('Query.onSnapshot', 'function', currArg + 1, args[currArg + 1]);\n validateOptionalArgType('Query.onSnapshot', 'function', currArg + 2, args[currArg + 2]);\n observer = {\n next: args[currArg],\n error: args[currArg + 1],\n complete: args[currArg + 2]\n };\n }\n return this.onSnapshotInternal(options, observer);\n };\n Query.prototype.onSnapshotInternal = function (options, observer) {\n var _this = this;\n var errHandler = function (err) {\n console.error('Uncaught Error in onSnapshot:', err);\n };\n if (observer.error) {\n errHandler = observer.error.bind(observer);\n }\n var asyncObserver = new AsyncObserver({\n next: function (result) {\n if (observer.next) {\n observer.next(new database_QuerySnapshot(_this.firestore, _this._query, result));\n }\n },\n error: errHandler\n });\n var firestoreClient = this.firestore.ensureClientConfigured();\n var internalListener = firestoreClient.listen(this._query, asyncObserver, options);\n return function () {\n asyncObserver.mute();\n firestoreClient.unlisten(internalListener);\n };\n };\n Query.prototype.get = function () {\n var _this = this;\n validateExactNumberOfArgs('Query.get', arguments, 0);\n return new Promise(function (resolve, reject) {\n var unlisten = _this.onSnapshotInternal({\n includeDocumentMetadataChanges: false,\n includeQueryMetadataChanges: true,\n waitForSyncWhenOnline: true\n }, {\n next: function (result) {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n unlisten();\n resolve(result);\n },\n error: reject\n });\n });\n };\n Query.prototype.validateNewFilter = function (filter) {\n if (filter instanceof query_RelationFilter && filter.isInequality()) {\n var existingField = this._query.getInequalityFilterField();\n if (existingField !== null && !existingField.isEqual(filter.field)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. All where filters with an inequality' +\n ' (<, <=, >, or >=) must be on the same field. But you have' +\n (\" inequality filters on '\" + existingField.toString() + \"'\") +\n (\" and '\" + filter.field.toString() + \"'\"));\n }\n var firstOrderByField = this._query.getFirstOrderByField();\n if (firstOrderByField !== null) {\n this.validateOrderByAndInequalityMatch(filter.field, firstOrderByField);\n }\n }\n };\n Query.prototype.validateNewOrderBy = function (orderBy) {\n if (this._query.getFirstOrderByField() === null) {\n // This is the first order by. It must match any inequality.\n var inequalityField = this._query.getInequalityFilterField();\n if (inequalityField !== null) {\n this.validateOrderByAndInequalityMatch(inequalityField, orderBy.field);\n }\n }\n };\n Query.prototype.validateOrderByAndInequalityMatch = function (inequality, orderBy) {\n if (!orderBy.isEqual(inequality)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. You have a where filter with an inequality \" +\n (\"(<, <=, >, or >=) on field '\" + inequality.toString() + \"' \") +\n (\"and so you must also use '\" + inequality.toString() + \"' \") +\n \"as your first Query.orderBy(), but your first Query.orderBy() \" +\n (\"is on field '\" + orderBy.toString() + \"' instead.\"));\n }\n };\n return Query;\n}());\n\nvar database_QuerySnapshot = /** @class */ (function () {\n function QuerySnapshot(_firestore, _originalQuery, _snapshot) {\n this._firestore = _firestore;\n this._originalQuery = _originalQuery;\n this._snapshot = _snapshot;\n this._cachedChanges = null;\n this.metadata = new SnapshotMetadata(_snapshot.hasPendingWrites, _snapshot.fromCache);\n }\n Object.defineProperty(QuerySnapshot.prototype, \"docs\", {\n get: function () {\n var result = [];\n this.forEach(function (doc) { return result.push(doc); });\n return result;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(QuerySnapshot.prototype, \"empty\", {\n get: function () {\n return this._snapshot.docs.isEmpty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(QuerySnapshot.prototype, \"size\", {\n get: function () {\n return this._snapshot.docs.size;\n },\n enumerable: true,\n configurable: true\n });\n QuerySnapshot.prototype.forEach = function (callback, thisArg) {\n var _this = this;\n validateBetweenNumberOfArgs('QuerySnapshot.forEach', arguments, 1, 2);\n validateArgType('QuerySnapshot.forEach', 'function', 1, callback);\n this._snapshot.docs.forEach(function (doc) {\n callback.call(thisArg, _this.convertToDocumentImpl(doc));\n });\n };\n Object.defineProperty(QuerySnapshot.prototype, \"query\", {\n get: function () {\n return new database_Query(this._originalQuery, this._firestore);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(QuerySnapshot.prototype, \"docChanges\", {\n get: function () {\n if (!this._cachedChanges) {\n this._cachedChanges = changesFromSnapshot(this._firestore, this._snapshot);\n }\n return this._cachedChanges;\n },\n enumerable: true,\n configurable: true\n });\n /** Check the equality. The call can be very expensive. */\n QuerySnapshot.prototype.isEqual = function (other) {\n if (!(other instanceof QuerySnapshot)) {\n throw invalidClassError('isEqual', 'QuerySnapshot', 1, other);\n }\n return (this._firestore === other._firestore &&\n this._originalQuery.isEqual(other._originalQuery) &&\n this._snapshot.isEqual(other._snapshot));\n };\n QuerySnapshot.prototype.convertToDocumentImpl = function (doc) {\n return new database_QueryDocumentSnapshot(this._firestore, doc.key, doc, this.metadata.fromCache);\n };\n return QuerySnapshot;\n}());\n\nvar database_CollectionReference = /** @class */ (function (_super) {\n database___extends(CollectionReference, _super);\n function CollectionReference(path, firestore) {\n var _this = _super.call(this, query_Query.atPath(path), firestore) || this;\n if (path.length % 2 !== 1) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid collection reference. Collection ' +\n 'references must have an odd number of segments, but ' +\n (path.canonicalString() + \" has \" + path.length));\n }\n return _this;\n }\n Object.defineProperty(CollectionReference.prototype, \"id\", {\n get: function () {\n return this._query.path.lastSegment();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(CollectionReference.prototype, \"parent\", {\n get: function () {\n var parentPath = this._query.path.popLast();\n if (parentPath.isEmpty()) {\n return null;\n }\n else {\n return new database_DocumentReference(new document_key_DocumentKey(parentPath), this.firestore);\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(CollectionReference.prototype, \"path\", {\n get: function () {\n return this._query.path.canonicalString();\n },\n enumerable: true,\n configurable: true\n });\n CollectionReference.prototype.doc = function (pathString) {\n validateBetweenNumberOfArgs('CollectionReference.doc', arguments, 0, 1);\n // We allow omission of 'pathString' but explicitly prohibit passing in both\n // 'undefined' and 'null'.\n if (arguments.length === 0) {\n pathString = misc_AutoId.newId();\n }\n validateArgType('CollectionReference.doc', 'string', 1, pathString);\n if (pathString === '') {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Document path must be a non-empty string');\n }\n var path = path_ResourcePath.fromString(pathString);\n return database_DocumentReference.forPath(this._query.path.child(path), this.firestore);\n };\n CollectionReference.prototype.add = function (value) {\n validateExactNumberOfArgs('CollectionReference.add', arguments, 1);\n validateArgType('CollectionReference.add', 'object', 1, value);\n var docRef = this.doc();\n return docRef.set(value).then(function () { return docRef; });\n };\n return CollectionReference;\n}(database_Query));\n\nfunction validateSetOptions(methodName, options) {\n if (options === undefined) {\n return {\n merge: false\n };\n }\n validateOptionNames(methodName, options, ['merge']);\n validateNamedOptionalType(methodName, 'boolean', 'merge', options.merge);\n return options;\n}\nfunction validateSnapshotOptions(methodName, options) {\n if (options === undefined) {\n return {};\n }\n validateOptionNames(methodName, options, ['serverTimestamps']);\n validateNamedOptionalPropertyEquals(methodName, 'options', 'serverTimestamps', options.serverTimestamps, ['estimate', 'previous', 'none']);\n return options;\n}\nfunction validateReference(methodName, documentRef, firestore) {\n if (!(documentRef instanceof database_DocumentReference)) {\n throw invalidClassError(methodName, 'DocumentReference', 1, documentRef);\n }\n else if (documentRef.firestore !== firestore) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Provided document reference is from a different Firestore instance.');\n }\n else {\n return documentRef;\n }\n}\n/**\n * Calculates the array of firestore.DocumentChange's for a given ViewSnapshot.\n *\n * Exported for testing.\n */\nfunction changesFromSnapshot(firestore, snapshot) {\n if (snapshot.oldDocs.isEmpty()) {\n // Special case the first snapshot because index calculation is easy and\n // fast\n var lastDoc_1;\n var index_1 = 0;\n return snapshot.docChanges.map(function (change) {\n var doc = new database_QueryDocumentSnapshot(firestore, change.doc.key, change.doc, snapshot.fromCache);\n assert(change.type === ChangeType.Added, 'Invalid event type for first snapshot');\n assert(!lastDoc_1 || snapshot.query.docComparator(lastDoc_1, change.doc) < 0, 'Got added events in wrong order');\n lastDoc_1 = change.doc;\n return {\n type: 'added',\n doc: doc,\n oldIndex: -1,\n newIndex: index_1++\n };\n });\n }\n else {\n // A DocumentSet that is updated incrementally as changes are applied to use\n // to lookup the index of a document.\n var indexTracker_1 = snapshot.oldDocs;\n return snapshot.docChanges.map(function (change) {\n var doc = new database_QueryDocumentSnapshot(firestore, change.doc.key, change.doc, snapshot.fromCache);\n var oldIndex = -1;\n var newIndex = -1;\n if (change.type !== ChangeType.Added) {\n oldIndex = indexTracker_1.indexOf(change.doc.key);\n assert(oldIndex >= 0, 'Index for document not found');\n indexTracker_1 = indexTracker_1.delete(change.doc.key);\n }\n if (change.type !== ChangeType.Removed) {\n indexTracker_1 = indexTracker_1.add(change.doc);\n newIndex = indexTracker_1.indexOf(change.doc.key);\n }\n return { type: resultChangeType(change.type), doc: doc, oldIndex: oldIndex, newIndex: newIndex };\n });\n }\n}\nfunction resultChangeType(type) {\n switch (type) {\n case ChangeType.Added:\n return 'added';\n case ChangeType.Modified:\n case ChangeType.Metadata:\n return 'modified';\n case ChangeType.Removed:\n return 'removed';\n default:\n return fail('Unknown change type: ' + type);\n }\n}\n// Export the classes with a private constructor (it will fail if invoked\n// at runtime). Note that this still allows instanceof checks.\n// We're treating the variables as class names, so disable checking for lower\n// case variable names.\n// tslint:disable:variable-name\nvar PublicFirestore = makeConstructorPrivate(database_Firestore, 'Use firebase.firestore() instead.');\nvar PublicTransaction = makeConstructorPrivate(database_Transaction, 'Use firebase.firestore().runTransaction() instead.');\nvar PublicWriteBatch = makeConstructorPrivate(database_WriteBatch, 'Use firebase.firestore().batch() instead.');\nvar PublicDocumentReference = makeConstructorPrivate(database_DocumentReference, 'Use firebase.firestore().doc() instead.');\nvar PublicDocumentSnapshot = makeConstructorPrivate(database_DocumentSnapshot);\nvar PublicQueryDocumentSnapshot = makeConstructorPrivate(database_QueryDocumentSnapshot);\nvar PublicQuery = makeConstructorPrivate(database_Query);\nvar PublicQuerySnapshot = makeConstructorPrivate(database_QuerySnapshot);\nvar PublicCollectionReference = makeConstructorPrivate(database_CollectionReference, 'Use firebase.firestore().collection() instead.');\n// tslint:enable:variable-name\n\n//# sourceMappingURL=database.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/platform/config.js\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\n\n\n\nvar firestoreNamespace = {\n Firestore: PublicFirestore,\n GeoPoint: geo_point_GeoPoint,\n Blob: PublicBlob,\n Transaction: PublicTransaction,\n WriteBatch: PublicWriteBatch,\n DocumentReference: PublicDocumentReference,\n DocumentSnapshot: PublicDocumentSnapshot,\n Query: PublicQuery,\n QueryDocumentSnapshot: PublicQueryDocumentSnapshot,\n QuerySnapshot: PublicQuerySnapshot,\n CollectionReference: PublicCollectionReference,\n FieldPath: field_path_FieldPath,\n FieldValue: PublicFieldValue,\n setLogLevel: database_Firestore.setLogLevel\n};\n/**\n * Configures Firestore as part of the Firebase SDK by calling registerService.\n */\nfunction configureForFirebase(firebase) {\n firebase.INTERNAL.registerService('firestore', function (app) { return new database_Firestore(app); }, shallowCopy(firestoreNamespace));\n}\n/**\n * Exports the Firestore namespace into the provided `exportObject` object under\n * the key 'firestore'. This is used for wrapped binary that exposes Firestore\n * as a goog module.\n */\nfunction configureForStandalone(exportObject) {\n var copiedNamespace = shallowCopy(firestoreNamespace);\n // Unlike the use with Firebase, the standalone allows the use of the\n // constructor, so export it's internal class\n copiedNamespace['Firestore'] = database_Firestore;\n exportObject['firestore'] = copiedNamespace;\n}\n\n//# sourceMappingURL=config.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/index.js\n/* harmony export (immutable) */ __webpack_exports__[\"registerFirestore\"] = registerFirestore;\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n\nfunction registerFirestore(instance) {\n configureForFirebase(instance);\n}\nregisterFirestore(esm[\"default\"]);\n\n//# sourceMappingURL=index.js.map\n\n\n/***/ }),\n\n/***/ 115:\n/***/ (function(module, exports, __webpack_require__) {\n\n/* WEBPACK VAR INJECTION */(function(global) {(function() {var g,goog=goog||{},k=this;function l(a){return\"string\"==typeof a}function aa(){}\nfunction ba(a){var b=typeof a;if(\"object\"==b)if(a){if(a instanceof Array)return\"array\";if(a instanceof Object)return b;var c=Object.prototype.toString.call(a);if(\"[object Window]\"==c)return\"object\";if(\"[object Array]\"==c||\"number\"==typeof a.length&&\"undefined\"!=typeof a.splice&&\"undefined\"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable(\"splice\"))return\"array\";if(\"[object Function]\"==c||\"undefined\"!=typeof a.call&&\"undefined\"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable(\"call\"))return\"function\"}else return\"null\";\nelse if(\"function\"==b&&\"undefined\"==typeof a.call)return\"object\";return b}function n(a){return\"array\"==ba(a)}function ca(a){var b=ba(a);return\"array\"==b||\"object\"==b&&\"number\"==typeof a.length}function da(a){return\"function\"==ba(a)}function p(a){var b=typeof a;return\"object\"==b&&null!=a||\"function\"==b}var q=\"closure_uid_\"+(1E9*Math.random()>>>0),ea=0;function fa(a,b,c){return a.call.apply(a.bind,arguments)}\nfunction ha(a,b,c){if(!a)throw Error();if(2b?1:0};function na(a,b){b.unshift(a);ja.call(this,ka.apply(null,b));b.shift()}u(na,ja);na.prototype.name=\"AssertionError\";function oa(a,b){throw new na(\"Failure\"+(a?\": \"+a:\"\"),Array.prototype.slice.call(arguments,1));};function w(){0!=qa&&(ra[this[q]||(this[q]=++ea)]=this);this.i=this.i;this.w=this.w}var qa=0,ra={};w.prototype.i=!1;w.prototype.Z=function(){if(!this.i&&(this.i=!0,this.A(),0!=qa)){var a=this[q]||(this[q]=++ea);delete ra[a]}};w.prototype.A=function(){if(this.w)for(;this.w.length;)this.w.shift()()};var sa=Array.prototype.indexOf?function(a,b){return Array.prototype.indexOf.call(a,b,void 0)}:function(a,b){if(l(a))return l(b)&&1==b.length?a.indexOf(b,0):-1;for(var c=0;cb?null:l(a)?a.charAt(b):a[b]}function wa(a){if(!n(a))for(var b=a.length-1;0<=b;b--)delete a[b];a.length=0}function xa(a){return Array.prototype.concat.apply([],arguments)}function ya(a){var b=a.length;if(0parseFloat(Qa)){Pa=String(Sa);break a}}Pa=Qa}var Ja={};\nfunction Ta(a){return Ia(a,function(){for(var b=0,c=la(String(Pa)).split(\".\"),d=la(String(a)).split(\".\"),e=Math.max(c.length,d.length),f=0;0==b&&f=a.keyCode)a.keyCode=-1}catch(b){}};var bb=\"closure_listenable_\"+(1E6*Math.random()|0);function cb(a){return!(!a||!a[bb])}var db=0;function eb(a,b,c,d,e){this.listener=a;this.a=null;this.src=b;this.type=c;this.capture=!!d;this.ga=e;this.key=++db;this.Y=this.ca=!1}function fb(a){a.Y=!0;a.listener=null;a.a=null;a.src=null;a.ga=null};function gb(a){this.src=a;this.a={};this.b=0}gb.prototype.add=function(a,b,c,d,e){var f=a.toString();a=this.a[f];a||(a=this.a[f]=[],this.b++);var h=hb(a,b,d,e);-1d.keyCode||void 0!=d.returnValue)){a:{var e=!1;if(0==d.keyCode)try{d.keyCode=-1;break a}catch(h){e=!0}if(e||void 0==d.returnValue)d.returnValue=!0}d=[];for(e=b.a;e;e=e.parentNode)d.push(e);a=a.type;for(e=d.length-1;0<=e;e--){b.a=d[e];var f=xb(d[e],a,!0,b);c=c&&f}for(e=0;e>>0);function pb(a){if(da(a))return a;a[zb]||(a[zb]=function(b){return a.handleEvent(b)});return a[zb]};function B(){w.call(this);this.c=new gb(this);this.P=this;this.K=null}u(B,w);B.prototype[bb]=!0;g=B.prototype;g.addEventListener=function(a,b,c,d){nb(this,a,b,c,d)};g.removeEventListener=function(a,b,c,d){vb(this,a,b,c,d)};\ng.dispatchEvent=function(a){var b,c=this.K;if(c)for(b=[];c;c=c.K)b.push(c);c=this.P;var d=a.type||a;if(l(a))a=new A(a,c);else if(a instanceof A)a.target=a.target||c;else{var e=a;a=new A(d,c);Ga(a,e)}e=!0;if(b)for(var f=b.length-1;0<=f;f--){var h=a.a=b[f];e=Ab(h,d,!0,a)&&e}h=a.a=c;e=Ab(h,d,!0,a)&&e;e=Ab(h,d,!1,a)&&e;if(b)for(f=0;fb.b&&(b.b++,a.next=b.a,b.a=a)}Wb=!1};function Xb(a,b){B.call(this);this.b=a||1;this.a=b||k;this.f=r(this.kb,this);this.g=t()}u(Xb,B);g=Xb.prototype;g.$=!1;g.L=null;g.kb=function(){if(this.$){var a=t()-this.g;0=lc(this).value)for(da(b)&&(b=b()),a=new dc(a,String(b),this.f),c&&(a.a=c),c=this;c;)c=c.a};\nvar mc={},nc=null;function oc(a){nc||(nc=new fc(\"\"),mc[\"\"]=nc,nc.c=jc);var b;if(!(b=mc[a])){b=new fc(a);var c=a.lastIndexOf(\".\"),d=a.substr(c+1);c=oc(a.substr(0,c));c.b||(c.b={});c.b[d]=b;b.a=c;mc[a]=b}return b};function E(a,b){a&&a.log(hc,b,void 0)}function pc(a,b){a&&a.log(ic,b,void 0)}function F(a,b){a&&a.log(kc,b,void 0)};function qc(){this.a=oc(\"goog.labs.net.webChannel.WebChannelDebug\");this.b=!0}qc.prototype.Ea=function(){this.b=!1};function rc(a,b,c,d,e,f){H(a,function(){if(a.b)if(f){var h=\"\";for(var m=f.split(\"&\"),v=0;ve.length)){var f=e[1];if(n(f)&&!(1>f.length)){var h=f[0];if(\"noop\"!=h&&\"stop\"!=h&&\"close\"!=h)for(var m=1;mb||3==b&&!Ka&&!a.a.V())){a.B||4!=b||7==c||(8==c||0>=d?Ac(3):Ac(2));Zc(a);var e=a.a.W();a.C=e;(c=a.a.V())||I(a.b,function(){return\"No response text for uri \"+a.g+\" status \"+e});a.c=200==e;sc(a.b,a.o,a.g,a.f,a.T,b,e);a.c?(a.M?($c(a,b,c),Ka&&a.c&&3==b&&ad(a)):(tc(a.b,a.f,c,null),bd(a,c)),4==b&&cd(a),a.c&&!a.B&&(4==b?a.i.ua(a):(a.c=!1,Wc(a)))):(400==e&&0b.length)return Rc;b=b.substr(d,c);a.F=d+c;return b}g.cancel=function(){this.B=!0;cd(this)};function Wc(a){a.U=t()+a.S;fd(a,a.S)}\nfunction fd(a,b){if(null!=a.w)throw Error(\"WatchDog timer not null\");a.w=Ec(r(a.fb,a),b)}function Zc(a){a.w&&(k.clearTimeout(a.w),a.w=null)}g.fb=function(){this.w=null;var a=t();0<=a-this.U?(this.c&&xc(this.b,\"Received watchdog timeout even though request loaded successfully\"),vc(this.b,this.g),2!=this.K&&(Ac(3),J(17)),cd(this),this.l=2,dd(this)):(E(this.b.a,\"WatchDog timer called too early\"),fd(this,this.U-a))};function dd(a){a.i.Ja()||a.B||a.i.ua(a)}\nfunction cd(a){Zc(a);var b=a.J;b&&\"function\"==typeof b.Z&&b.Z();a.J=null;Yb(a.I);cc(a.N);a.a&&(b=a.a,a.a=null,b.abort(),b.Z())}function bd(a,b){try{a.i.Ma(a,b),Ac(4)}catch(c){wc(a.b,c,\"Error in httprequest callback\")}};function gd(a){if(a.v&&\"function\"==typeof a.v)return a.v();if(l(a))return a.split(\"\");if(ca(a)){for(var b=[],c=a.length,d=0;d2*a.c&&id(a),!0):!1}function id(a){if(a.c!=a.a.length){for(var b=0,c=0;bb)throw Error(\"Bad port number \"+b);a.i=b}else a.i=null}function qd(a,b,c){b instanceof td?(a.c=b,zd(a.c,a.h)):(c||(b=ud(b,Ad)),a.c=new td(b,a.h))}\nfunction Q(a,b,c){a.c.set(b,c)}function Xc(a,b,c){n(c)||(c=[String(c)]);Bd(a.c,b,c)}function Tc(a){Q(a,\"zx\",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^t()).toString(36));return a}function Cd(a){return a instanceof P?L(a):new P(a,void 0)}function Dd(a,b,c,d){var e=new P(null,void 0);a&&nd(e,a);b&&od(e,b);c&&pd(e,c);d&&(e.a=d);return e}function sd(a,b){return a?b?decodeURI(a.replace(/%25/g,\"%2525\")):decodeURIComponent(a):\"\"}\nfunction ud(a,b,c){return l(a)?(a=encodeURI(a).replace(b,Ed),c&&(a=a.replace(/%25([0-9a-fA-F]{2})/g,\"%$1\")),a):null}function Ed(a){a=a.charCodeAt(0);return\"%\"+(a>>4&15).toString(16)+(a&15).toString(16)}var vd=/[#\\/\\?@]/g,xd=/[#\\?:]/g,wd=/[#\\?]/g,Ad=/[#\\?@]/g,yd=/#/g;function td(a,b){this.b=this.a=null;this.c=a||null;this.f=!!b}function R(a){a.a||(a.a=new N,a.b=0,a.c&&md(a.c,function(b,c){a.add(decodeURIComponent(b.replace(/\\+/g,\" \")),c)}))}g=td.prototype;g.s=function(){R(this);return this.b};\ng.add=function(a,b){R(this);this.c=null;a=Fd(this,a);var c=this.a.get(a);c||this.a.set(a,c=[]);c.push(b);this.b+=1;return this};function Gd(a,b){R(a);b=Fd(a,b);O(a.a.b,b)&&(a.c=null,a.b-=a.a.get(b).length,kd(a.a,b))}function Hd(a,b){R(a);b=Fd(a,b);return O(a.a.b,b)}g.forEach=function(a,b){R(this);this.a.forEach(function(c,d){ta(c,function(c){a.call(b,c,d,this)},this)},this)};\ng.O=function(){R(this);for(var a=this.a.v(),b=this.a.O(),c=[],d=0;d=a.f:!1}function ce(a,b){return a.b?a.b==b:a.a?a.a.contains(b):!1}function ae(a,b){a.a?a.a.add(b):a.b=b}\nfunction de(a,b){a.b&&a.b==b?a.b=null:a.a&&a.a.contains(b)&&kd(a.a.a,Wd(b))}Yd.prototype.cancel=function(){this.c=ee(this);this.b?(this.b.cancel(),this.b=null):this.a&&0!=this.a.a.c&&(ta(this.a.v(),function(a){a.cancel()}),jd(this.a.a))};function ee(a){if(null!=a.b)return a.c.concat(a.b.u);if(null!=a.a&&0!=a.a.a.c){var b=a.c;ta(a.a.v(),function(a){b=b.concat(a.u)});return b}return ya(a.c)}function fe(a,b){a.c=a.c.concat(b)};function ge(){}ge.prototype.stringify=function(a){return k.JSON.stringify(a,void 0)};ge.prototype.parse=function(a){return k.JSON.parse(a,void 0)};function he(){this.a=new ge}function ie(a,b,c){var d=c||\"\";try{hd(a,function(a,c){var e=a;p(a)&&(e=Db(a));b.push(d+c+\"=\"+encodeURIComponent(e))})}catch(e){throw b.push(d+\"type=\"+encodeURIComponent(\"_badmap\")),e;}};function je(a,b){var c=new qc;I(c,\"TestLoadImage: loading \"+a);var d=new Image;d.onload=ia(ke,c,d,\"TestLoadImage: loaded\",!0,b);d.onerror=ia(ke,c,d,\"TestLoadImage: error\",!1,b);d.onabort=ia(ke,c,d,\"TestLoadImage: abort\",!1,b);d.ontimeout=ia(ke,c,d,\"TestLoadImage: timeout\",!1,b);k.setTimeout(function(){if(d.ontimeout)d.ontimeout()},1E4);d.src=a}function ke(a,b,c,d,e){try{I(a,c),b.onload=null,b.onerror=null,b.onabort=null,b.ontimeout=null,e(d)}catch(f){wc(a,f)}};function T(a){B.call(this);this.headers=new N;this.F=a||null;this.f=!1;this.D=this.a=null;this.M=this.u=\"\";this.j=0;this.g=\"\";this.h=this.J=this.o=this.I=!1;this.l=0;this.B=null;this.N=le;this.C=this.m=!1}u(T,B);var le=\"\";T.prototype.b=oc(\"goog.net.XhrIo\");var me=/^https?$/i,ne=[\"POST\",\"PUT\"];g=T.prototype;\ng.fa=function(a,b,c,d){if(this.a)throw Error(\"[goog.net.XhrIo] Object is active with another request=\"+this.u+\"; newUri=\"+a);b=b?b.toUpperCase():\"GET\";this.u=a;this.g=\"\";this.j=0;this.M=b;this.I=!1;this.f=!0;this.a=this.F?Mc(this.F):Mc(Kc);this.D=this.F?Ic(this.F):Ic(Kc);this.a.onreadystatechange=r(this.La,this);try{F(this.b,U(this,\"Opening Xhr\")),this.J=!0,this.a.open(b,String(a),!0),this.J=!1}catch(f){F(this.b,U(this,\"Error opening Xhr: \"+f.message));oe(this,f);return}a=c||\"\";var e=new N(this.headers);\nd&&hd(d,function(a,b){e.set(b,a)});d=ua(e.O());c=k.FormData&&a instanceof k.FormData;!(0<=sa(ne,b))||d||c||e.set(\"Content-Type\",\"application/x-www-form-urlencoded;charset=utf-8\");e.forEach(function(a,b){this.a.setRequestHeader(b,a)},this);this.N&&(this.a.responseType=this.N);\"withCredentials\"in this.a&&this.a.withCredentials!==this.m&&(this.a.withCredentials=this.m);try{pe(this),0c&&(c=a.length);d=a.indexOf(\"?\");if(0>d||d>c){d=c;var e=\"\"}else e=a.substring(d+1,c);a=[a.substr(0,d),e,a.substr(c)];c=a[1];a[1]=b?c?c+\"&\"+b:b:c;a=a[0]+(a[1]?\"?\"+a[1]:\"\")+a[2]}return a}Q(a,b,c);return a};function we(a){this.ya=0;this.g=[];this.a=new qc;this.I=new Vd;this.ja=this.wa=this.F=this.ka=this.b=this.K=this.j=this.U=this.h=this.M=this.i=null;this.Ua=this.P=0;this.la=this.B=this.o=this.m=this.l=this.f=null;this.u=this.xa=this.N=-1;this.T=this.w=this.C=0;this.S=a&&a.supportsCrossDomainXhr||!1;this.J=\"\";this.c=new Yd(a&&a.concurrentRequestLimit);this.ma=new he;this.D=a&&void 0!==a.backgroundChannelTest?a.backgroundChannelTest:!0;this.Ta=a&&a.fastHandshake||!1;a&&a.Ea&&this.a.Ea()}g=we.prototype;\ng.oa=8;g.G=1;function xe(a){I(a.a,\"disconnect()\");ye(a);if(3==a.G){var b=a.P++,c=L(a.F);Q(c,\"SID\",a.J);Q(c,\"RID\",b);Q(c,\"TYPE\",\"terminate\");ze(a,c);b=new K(a,a.a,b,void 0);b.K=2;b.h=Tc(L(c));c=!1;k.navigator&&k.navigator.sendBeacon&&(c=k.navigator.sendBeacon(b.h.toString(),\"\"));!c&&k.Image&&((new Image).src=b.h,c=!0);c||(b.a=b.i.da(null),b.a.fa(b.h));b.D=t();Wc(b)}Ae(a)}\nfunction ye(a){a.B&&(a.B.abort(),a.B=null);a.b&&(a.b.cancel(),a.b=null);a.m&&(k.clearTimeout(a.m),a.m=null);Be(a);a.c.cancel();a.l&&(k.clearTimeout(a.l),a.l=null)}function Ce(a,b){1E3==a.g.length&&xc(a.a,function(){return\"Already have 1000 queued maps upon queueing \"+Db(b)});a.g.push(new Xd(a.Ua++,b));3==a.G&&De(a)}g.Ja=function(){return 0==this.G};function De(a){be(a.c)||a.l||(a.l=Ec(r(a.Oa,a),0),a.C=0)}\nfunction Ee(a,b){var c=a.c;if((c.b?1:c.a?c.a.s():0)>=a.c.f-(a.l?1:0))return xc(a.a,\"Unexpected retry request is scheduled.\"),!1;if(a.l)return I(a.a,\"Use the retry request that is already scheduled.\"),a.g=b.u.concat(a.g),!0;if(1==a.G||2==a.G||2<=a.C)return!1;I(a.a,\"Going to retry POST\");a.l=Ec(r(a.Oa,a,b),Fe(a,a.C));a.C++;return!0}\ng.Oa=function(a){this.l=null;I(this.a,\"startForwardChannel_\");if(1==this.G)if(a)xc(this.a,\"Not supposed to retry the open\");else{I(this.a,\"open_()\");this.P=Math.floor(1E5*Math.random());a=this.P++;var b=new K(this,this.a,a,void 0),c=this.i;this.M&&(c?(c=Ea(c),Ga(c,this.M)):c=this.M);null===this.h&&(b.j=c);var d=Ge(this,b),e=L(this.F);Q(e,\"RID\",a);Q(e,\"CVER\",21);this.D&&this.j&&Q(e,\"X-HTTP-Session-Id\",this.j);ze(this,e);this.h&&c&&ve(e,this.h,c);ae(this.c,b);this.Ta?(Q(e,\"$req\",d),Sc(b,e,null)):Sc(b,\ne,d);this.G=2}else 3==this.G&&(a?He(this,a):0==this.g.length?I(this.a,\"startForwardChannel_ returned: nothing to send\"):be(this.c)?xc(this.a,\"startForwardChannel_ returned: connection already in progress\"):(He(this),I(this.a,\"startForwardChannel_ finished, sent request\")))};\nfunction He(a,b){var c;b?c=b.f:c=a.P++;var d=L(a.F);Q(d,\"SID\",a.J);Q(d,\"RID\",c);Q(d,\"AID\",a.N);ze(a,d);a.h&&a.i&&ve(d,a.h,a.i);c=new K(a,a.a,c,a.C+1);null===a.h&&(c.j=a.i);b&&(a.g=b.u.concat(a.g));b=Ge(a,c);c.setTimeout(1E4+Math.round(1E4*Math.random()));ae(a.c,c);Sc(c,d,b)}function ze(a,b){a.f&&hd({},function(a,d){Q(b,d,a)})}\nfunction Ge(a,b){var c=Math.min(a.g.length,1E3),d=a.f?r(a.f.Va,a.f,a):null;a:for(var e=a.g,f=-1;;){var h=[\"count=\"+c];-1==f?0G)f=Math.max(0,e[v].a-100),m=!1;else try{ie(Z,h,\"req\"+G+\"_\")}catch(Mb){d&&d(Z)}}if(m){d=h.join(\"&\");break a}}a=a.g.splice(0,c);b.u=a;return d}function Ie(a){if(!a.b&&!a.m){a.T=1;var b=a.Na;Tb||Ub();Wb||(Tb(),Wb=!0);Pb.add(b,a);a.w=0}}\nfunction Je(a){if(a.b||a.m)return xc(a.a,\"Request already in progress\"),!1;if(3<=a.w)return!1;I(a.a,\"Going to retry GET\");a.T++;a.m=Ec(r(a.Na,a),Fe(a,a.w));a.w++;return!0}\ng.Na=function(){this.m=null;I(this.a,\"Creating new HttpRequest\");this.b=new K(this,this.a,\"rpc\",this.T);null===this.h&&(this.b.j=this.i);this.b.P=0;var a=L(this.wa);Q(a,\"RID\",\"rpc\");Q(a,\"SID\",this.J);Q(a,\"CI\",this.la?\"0\":\"1\");Q(a,\"AID\",this.N);ze(this,a);Q(a,\"TYPE\",\"xmlhttp\");this.h&&this.i&&ve(a,this.h,this.i);Vc(this.b,a,!0,this.ja);I(this.a,\"New Request created\")};\nfunction Sd(a,b,c){I(a.a,\"Test Connection Finished\");var d=b.m;d&&$d(a.c,d);a.la=c;a.u=b.f;I(a.a,\"connectChannel_()\");a.F=Ke(a,a.ka);De(a)}function Ud(a,b){I(a.a,\"Test Connection Failed\");a.u=b.f;V(a,2)}\ng.Ma=function(a,b){if(0!=this.G&&(this.b==a||ce(this.c,a)))if(this.u=a.C,ce(this.c,a)&&3==this.G){try{var c=this.ma.a.parse(b)}catch(f){c=null}if(n(c)&&3==c.length)if(b=c,0==b[0])a:if(I(this.a,\"Server claims our backchannel is missing.\"),this.m)I(this.a,\"But we are currently starting the request.\");else{if(this.b)if(this.b.D+3E3b&&this.la&&0==this.w&&!this.o&&(this.o=Ec(r(this.bb,this),6E3)));else I(this.a,\"Bad POST response data returned\"),V(this,11)}else if(this.b==a&&Be(this),!/^[\\s\\xa0]*$/.test(b))for(b=c=this.ma.a.parse(b),c=0;cthis.c)throw Error(We);this.a=new Te;this.b=new S;this.g=null;this.ba()}u(Ve,w);var We=\"[goog.structs.Pool] Min can not be greater than max\";g=Ve.prototype;g.ea=function(){var a=t();if(!(null!=this.g&&0>a-this.g)){for(var b;0this.c&&0=this.s()){for(var c=this.a,d=0;d>1,a[d].a>c.a)a[b]=a[d],b=d;else break;a[b]=c}Ze.prototype.v=function(){for(var a=this.a,b=[],c=a.length,d=0;d=e)f=void 0;else{if(1==e)wa(d);else{d[0]=d.pop();d=0;c=c.a;e=c.length;for(var h=c[d];d>1;){var m=2*d+1,v=2*d+2;m=vh.a)break;c[d]=c[m];d=m}c[d]=h}f=f.b}f.apply(this,[b])}else break}};\ng.na=function(a){X.H.na.call(this,a);this.sa()};g.ba=function(){X.H.ba.call(this);this.sa()};g.A=function(){X.H.A.call(this);k.clearTimeout(void 0);wa(this.f.a);this.f=null};function Y(a,b,c,d){this.l=a;this.j=!!d;X.call(this,b,c)}u(Y,X);Y.prototype.qa=function(){var a=new T,b=this.l;b&&b.forEach(function(b,d){a.headers.set(d,b)});this.j&&(a.m=!0);return a};Y.prototype.ta=function(a){return!a.i&&!a.a};Oe.prototype.createWebChannel=Oe.prototype.a;W.prototype.send=W.prototype.$a;W.prototype.open=W.prototype.Za;W.prototype.close=W.prototype.close;Fc.NO_ERROR=0;Fc.TIMEOUT=8;Fc.HTTP_ERROR=6;Gc.COMPLETE=\"complete\";Md.EventType=Nd;Nd.OPEN=\"a\";Nd.CLOSE=\"b\";Nd.ERROR=\"c\";Nd.MESSAGE=\"d\";B.prototype.listen=B.prototype.aa;Y.prototype.getObject=Y.prototype.ea;Y.prototype.releaseObject=Y.prototype.ib;T.prototype.listenOnce=T.prototype.Ha;T.prototype.getLastError=T.prototype.ab;T.prototype.getLastErrorCode=T.prototype.Fa;\nT.prototype.getStatus=T.prototype.W;T.prototype.getStatusText=T.prototype.Ga;T.prototype.getResponseJson=T.prototype.Ya;T.prototype.getResponseText=T.prototype.V;T.prototype.getResponseText=T.prototype.V;T.prototype.send=T.prototype.fa;module.exports={createWebChannelTransport:Se,ErrorCode:Fc,EventType:Gc,WebChannel:Md,XhrIoPool:Y};}).call(typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : {})\n\n/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(12)))\n\n/***/ })\n\n},[113]);\n } catch(error) {\n throw new Error(\n 'Cannot instantiate firebase-firestore.js - ' +\n 'be sure to load firebase-app.js first.'\n )\n }\n\n\n// WEBPACK FOOTER //\n// firebase-firestore.js","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nrequire('@firebase/firestore');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./firestore/index.js\n// module id = 113\n// module chunks = 1","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/* tslint:disable:no-console */\nimport { SDK_VERSION } from '../core/version';\nimport { PlatformSupport } from '../platform/platform';\nexport var LogLevel;\n(function (LogLevel) {\n LogLevel[LogLevel[\"DEBUG\"] = 0] = \"DEBUG\";\n LogLevel[LogLevel[\"ERROR\"] = 1] = \"ERROR\";\n LogLevel[LogLevel[\"SILENT\"] = 2] = \"SILENT\";\n})(LogLevel || (LogLevel = {}));\nvar logLevel = LogLevel.ERROR;\n// Helper methods are needed because variables can't be exported as read/write\nexport function getLogLevel() {\n return logLevel;\n}\nexport function setLogLevel(newLevel) {\n logLevel = newLevel;\n}\nexport function debug(tag, msg) {\n var obj = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n obj[_i - 2] = arguments[_i];\n }\n if (logLevel <= LogLevel.DEBUG) {\n var time = new Date().toISOString();\n var args = obj.map(argToString);\n console.log.apply(console, [\"Firestore (\" + SDK_VERSION + \") \" + time + \" [\" + tag + \"]: \" + msg].concat(args));\n }\n}\nexport function error(msg) {\n var obj = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n obj[_i - 1] = arguments[_i];\n }\n if (logLevel <= LogLevel.ERROR) {\n var time = new Date().toISOString();\n var args = obj.map(argToString);\n console.error.apply(console, [\"Firestore (\" + SDK_VERSION + \") \" + time + \": \" + msg].concat(args));\n }\n}\n/**\n * Converts an additional log parameter to a string representation.\n */\nfunction argToString(obj) {\n if (typeof obj === 'string') {\n return obj;\n }\n else {\n var platform = PlatformSupport.getPlatform();\n try {\n return platform.formatJSON(obj);\n }\n catch (e) {\n // Converting to JSON failed, just log the object directly\n return obj;\n }\n }\n}\n\n//# sourceMappingURL=log.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/log.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { SDK_VERSION } from '../core/version';\nimport { error } from './log';\n/**\n * Unconditionally fails, throwing an Error with the given message.\n *\n * Returns any so it can be used in expressions:\n * @example\n * let futureVar = fail('not implemented yet');\n */\nexport function fail(failure) {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n var message = \"FIRESTORE (\" + SDK_VERSION + \") INTERNAL ASSERTION FAILED: \" + failure;\n error(message);\n // NOTE: We don't use FirestoreError here because these are internal failures\n // that cannot be handled by the user. (Also it would create a circular\n // dependency between the error and assert modules which doesn't work.)\n throw new Error(message);\n}\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n */\nexport function assert(assertion, message) {\n if (!assertion) {\n fail(message);\n }\n}\n\n//# sourceMappingURL=assert.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/assert.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { fail } from '../util/assert';\n/**\n * Provides singleton helpers where setup code can inject a platform at runtime.\n * setPlatform needs to be set before Firestore is used and must be set exactly\n * once.\n */\nvar PlatformSupport = /** @class */ (function () {\n function PlatformSupport() {\n }\n PlatformSupport.setPlatform = function (platform) {\n if (PlatformSupport.platform) {\n fail('Platform already defined');\n }\n PlatformSupport.platform = platform;\n };\n PlatformSupport.getPlatform = function () {\n if (!PlatformSupport.platform) {\n fail('Platform not set');\n }\n return PlatformSupport.platform;\n };\n return PlatformSupport;\n}());\nexport { PlatformSupport };\n/**\n * Returns the representation of an empty \"proto\" byte string for the\n * platform.\n */\nexport function emptyByteString() {\n return PlatformSupport.getPlatform().emptyByteString;\n}\n\n//# sourceMappingURL=platform.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/platform/platform.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// We are doing some heavy reflective stuff, lots of any casting necessary\n/* tslint:disable:no-any */\nimport { Code, FirestoreError } from './error';\n/**\n * Helper function to prevent instantiation through the constructor.\n *\n * This method creates a new constructor that throws when it's invoked.\n * The prototype of that constructor is then set to the prototype of the hidden\n * \"class\" to expose all the prototype methods and allow for instanceof\n * checks.\n *\n * To also make all the static methods available, all properties of the\n * original constructor are copied to the new constructor.\n */\nexport function makeConstructorPrivate(cls, optionalMessage) {\n function PublicConstructor() {\n var error = 'This constructor is private.';\n if (optionalMessage) {\n error += ' ';\n error += optionalMessage;\n }\n throw new FirestoreError(Code.INVALID_ARGUMENT, error);\n }\n // Make sure instanceof checks work and all methods are exposed on the public\n // constructor\n PublicConstructor.prototype = cls.prototype;\n // Copy any static methods/members\n for (var staticProperty in cls) {\n if (cls.hasOwnProperty(staticProperty)) {\n PublicConstructor[staticProperty] = cls[staticProperty];\n }\n }\n return PublicConstructor;\n}\n\n//# sourceMappingURL=api.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/api.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { assert } from './assert';\nexport function contains(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\nexport function get(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key) ? obj[key] : null;\n}\nexport function size(obj) {\n var count = 0;\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n count++;\n }\n }\n return count;\n}\n/** Returns the given value if it's defined or the defaultValue otherwise. */\nexport function defaulted(value, defaultValue) {\n return value !== undefined ? value : defaultValue;\n}\nexport function forEachNumber(obj, fn) {\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n var num = Number(key);\n if (!isNaN(num)) {\n fn(num, obj[key]);\n }\n }\n }\n}\nexport function forEach(obj, fn) {\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn(key, obj[key]);\n }\n }\n}\nexport function lookupOrInsert(obj, key, valFn) {\n if (!contains(obj, key)) {\n obj[key] = valFn();\n }\n return obj[key];\n}\nexport function isEmpty(obj) {\n assert(obj != null && typeof obj === 'object', 'isEmpty() expects object parameter.');\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return false;\n }\n }\n return true;\n}\nexport function shallowCopy(obj) {\n assert(obj && typeof obj === 'object', 'shallowCopy() expects object parameter.');\n var result = {};\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n result[key] = obj[key];\n }\n }\n return result;\n}\n\n//# sourceMappingURL=obj.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/obj.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { fail } from './assert';\nimport { Code, FirestoreError } from './error';\nimport * as obj from './obj';\n/**\n * Validates the invocation of functionName has the exact number of arguments.\n *\n * Forward the magic \"arguments\" variable as second parameter on which the\n * parameter validation is performed:\n * validateExactNumberOfArgs('myFunction', arguments, 2);\n */\nexport function validateExactNumberOfArgs(functionName, args, numberOfArgs) {\n if (args.length !== numberOfArgs) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires \" +\n formatPlural(numberOfArgs, 'argument') +\n ', but was called with ' +\n formatPlural(args.length, 'argument') +\n '.');\n }\n}\n/**\n * Validates the invocation of functionName has at least the provided number of\n * arguments (but can have many more).\n *\n * Forward the magic \"arguments\" variable as second parameter on which the\n * parameter validation is performed:\n * validateAtLeastNumberOfArgs('myFunction', arguments, 2);\n */\nexport function validateAtLeastNumberOfArgs(functionName, args, minNumberOfArgs) {\n if (args.length < minNumberOfArgs) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires at least \" +\n formatPlural(minNumberOfArgs, 'argument') +\n ', but was called with ' +\n formatPlural(args.length, 'argument') +\n '.');\n }\n}\n/**\n * Validates the invocation of functionName has number of arguments between\n * the values provided.\n *\n * Forward the magic \"arguments\" variable as second parameter on which the\n * parameter validation is performed:\n * validateBetweenNumberOfArgs('myFunction', arguments, 2, 3);\n */\nexport function validateBetweenNumberOfArgs(functionName, args, minNumberOfArgs, maxNumberOfArgs) {\n if (args.length < minNumberOfArgs || args.length > maxNumberOfArgs) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires between \" + minNumberOfArgs + \" and \" +\n (maxNumberOfArgs + \" arguments, but was called with \") +\n formatPlural(args.length, 'argument') +\n '.');\n }\n}\n/**\n * Validates the provided argument is an array and has as least the expected\n * number of elements.\n */\nexport function validateNamedArrayAtLeastNumberOfElements(functionName, value, name, minNumberOfElements) {\n if (!(value instanceof Array) || value.length < minNumberOfElements) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires its \" + name + \" argument to be an \" +\n 'array with at least ' +\n (formatPlural(minNumberOfElements, 'element') + \".\"));\n }\n}\n/**\n * Validates the provided positional argument has the native JavaScript type\n * using typeof checks.\n */\nexport function validateArgType(functionName, type, position, argument) {\n validateType(functionName, type, ordinal(position) + \" argument\", argument);\n}\n/**\n * Validates the provided argument has the native JavaScript type using\n * typeof checks or is undefined.\n */\nexport function validateOptionalArgType(functionName, type, position, argument) {\n if (argument !== undefined) {\n validateArgType(functionName, type, position, argument);\n }\n}\n/**\n * Validates the provided named option has the native JavaScript type using\n * typeof checks.\n */\nexport function validateNamedType(functionName, type, optionName, argument) {\n validateType(functionName, type, optionName + \" option\", argument);\n}\n/**\n * Validates the provided named option has the native JavaScript type using\n * typeof checks or is undefined.\n */\nexport function validateNamedOptionalType(functionName, type, optionName, argument) {\n if (argument !== undefined) {\n validateNamedType(functionName, type, optionName, argument);\n }\n}\n/**\n * Validates that the provided named option equals one of the expected values.\n */\nexport function validateNamedPropertyEquals(functionName, inputName, optionName, input, expected) {\n var expectedDescription = [];\n for (var _i = 0, expected_1 = expected; _i < expected_1.length; _i++) {\n var val = expected_1[_i];\n if (val === input) {\n return;\n }\n expectedDescription.push(valueDescription(val));\n }\n var actualDescription = valueDescription(input);\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid value \" + actualDescription + \" provided to function \" + functionName + \"() for option \\\"serverTimestamps\\\". Acceptable values: \" + expectedDescription.join(', '));\n}\n/**\n * Validates that the provided named option equals one of the expected values or\n * is undefined.\n */\nexport function validateNamedOptionalPropertyEquals(functionName, inputName, optionName, input, expected) {\n if (input !== undefined) {\n validateNamedPropertyEquals(functionName, inputName, optionName, input, expected);\n }\n}\n/** Helper to validate the type of a provided input. */\nfunction validateType(functionName, type, inputName, input) {\n if (typeof input !== type || (type === 'object' && !isPlainObject(input))) {\n var description = valueDescription(input);\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires its \" + inputName + \" \" +\n (\"to be of type \" + type + \", but it was: \" + description));\n }\n}\n/**\n * Returns true iff it's a non-null object without a custom prototype\n * (i.e. excludes Array, Date, etc.).\n */\nexport function isPlainObject(input) {\n return (typeof input === 'object' &&\n input !== null &&\n Object.getPrototypeOf(input) === Object.prototype);\n}\n/** Returns a string describing the type / value of the provided input. */\nexport function valueDescription(input) {\n if (input === undefined) {\n return 'undefined';\n }\n else if (input === null) {\n return 'null';\n }\n else if (typeof input === 'string') {\n if (input.length > 20) {\n input = input.substring(0, 20) + \"...\";\n }\n return JSON.stringify(input);\n }\n else if (typeof input === 'number' || typeof input === 'boolean') {\n return '' + input;\n }\n else if (typeof input === 'object') {\n if (input instanceof Array) {\n return 'an array';\n }\n else {\n var customObjectName = tryGetCustomObjectType(input);\n if (customObjectName) {\n return \"a custom \" + customObjectName + \" object\";\n }\n else {\n return 'an object';\n }\n }\n }\n else if (typeof input === 'function') {\n return 'a function';\n }\n else {\n return fail('Unknown wrong type: ' + typeof input);\n }\n}\n/** Hacky method to try to get the constructor name for an object. */\nexport function tryGetCustomObjectType(input) {\n if (input.constructor) {\n var funcNameRegex = /function\\s+([^\\s(]+)\\s*\\(/;\n var results = funcNameRegex.exec(input.constructor.toString());\n if (results && results.length > 1) {\n return results[1];\n }\n }\n return null;\n}\n/** Validates the provided argument is defined. */\nexport function validateDefined(functionName, position, argument) {\n if (argument === undefined) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires a valid \" + ordinal(position) + \" \" +\n \"argument, but it was undefined.\");\n }\n}\n/**\n * Validates the provided positional argument is an object, and its keys and\n * values match the expected keys and types provided in optionTypes.\n */\nexport function validateOptionNames(functionName, options, optionNames) {\n obj.forEach(options, function (key, _) {\n if (optionNames.indexOf(key) < 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Unknown option '\" + key + \"' passed to function \" + functionName + \"(). \" +\n 'Available options: ' +\n optionNames.join(', '));\n }\n });\n}\n/**\n * Helper method to throw an error that the provided argument did not pass\n * an instanceof check.\n */\nexport function invalidClassError(functionName, type, position, argument) {\n var description = valueDescription(argument);\n return new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires its \" + ordinal(position) + \" \" +\n (\"argument to be a \" + type + \", but it was: \" + description));\n}\n/** Converts a number to its english word representation */\nfunction ordinal(num) {\n switch (num) {\n case 1:\n return 'first';\n case 2:\n return 'second';\n case 3:\n return 'third';\n default:\n return num + 'th';\n }\n}\n/**\n * Formats the given word as plural conditionally given the preceding number.\n */\nfunction formatPlural(num, str) {\n return num + \" \" + str + (num === 1 ? '' : 's');\n}\n\n//# sourceMappingURL=input_validation.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/input_validation.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { assert } from './assert';\n// tslint:disable-next-line:class-as-namespace\nvar AutoId = /** @class */ (function () {\n function AutoId() {\n }\n AutoId.newId = function () {\n // Alphanumeric characters\n var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n var autoId = '';\n for (var i = 0; i < 20; i++) {\n autoId += chars.charAt(Math.floor(Math.random() * chars.length));\n }\n assert(autoId.length === 20, 'Invalid auto ID: ' + autoId);\n return autoId;\n };\n return AutoId;\n}());\nexport { AutoId };\nexport function primitiveComparator(left, right) {\n if (left < right)\n return -1;\n if (left > right)\n return 1;\n return 0;\n}\n/** Helper to compare nullable (or undefined-able) objects using isEqual(). */\nexport function equals(left, right) {\n if (left !== null && left !== undefined) {\n return !!(right && left.isEqual(right));\n }\n else {\n // HACK: Explicitly cast since TypeScript's type narrowing apparently isn't\n // smart enough.\n return left === right;\n }\n}\n/** Helper to compare arrays using isEqual(). */\nexport function arrayEquals(left, right) {\n if (left.length !== right.length) {\n return false;\n }\n for (var i = 0; i < left.length; i++) {\n if (!left[i].isEqual(right[i])) {\n return false;\n }\n }\n return true;\n}\n/**\n * Returns the largest lexicographically smaller string of equal or smaller\n * length. Returns an empty string if there is no such predecessor (if the input\n * is empty).\n *\n * Strings returned from this method can be invalid UTF-16 but this is sufficent\n * in use for indexeddb because that depends on lexicographical ordering but\n * shouldn't be used elsewhere.\n */\nexport function immediatePredecessor(s) {\n // We can decrement the last character in the string and be done\n // unless that character is 0 (0x0000), in which case we have to erase the\n // last character.\n var lastIndex = s.length - 1;\n if (s.length === 0) {\n // Special case the empty string.\n return '';\n }\n else if (s.charAt(lastIndex) === '\\0') {\n return s.substring(0, lastIndex);\n }\n else {\n return (s.substring(0, lastIndex) +\n String.fromCharCode(s.charCodeAt(lastIndex) - 1));\n }\n}\n/**\n * Returns the immediate lexicographically-following string. This is useful to\n * construct an inclusive range for indexeddb iterators.\n */\nexport function immediateSuccessor(s) {\n // Return the input string, with an additional NUL byte appended.\n return s + '\\0';\n}\n\n//# sourceMappingURL=misc.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/misc.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { PlatformSupport } from '../platform/platform';\nimport { makeConstructorPrivate } from '../util/api';\nimport { Code, FirestoreError } from '../util/error';\nimport { invalidClassError, validateArgType, validateExactNumberOfArgs } from '../util/input_validation';\nimport { primitiveComparator } from '../util/misc';\n/** Helper function to assert Uint8Array is available at runtime. */\nfunction assertUint8ArrayAvailable() {\n if (typeof Uint8Array === 'undefined') {\n throw new FirestoreError(Code.UNIMPLEMENTED, 'Uint8Arrays are not available in this environment.');\n }\n}\n/** Helper function to assert Base64 functions are available at runtime. */\nfunction assertBase64Available() {\n if (!PlatformSupport.getPlatform().base64Available) {\n throw new FirestoreError(Code.UNIMPLEMENTED, 'Blobs are unavailable in Firestore in this environment.');\n }\n}\n/**\n * Immutable class holding a blob (binary data).\n * This class is directly exposed in the public API.\n *\n * Note that while you can't hide the constructor in JavaScript code, we are\n * using the hack above to make sure no-one outside this module can call it.\n */\nvar Blob = /** @class */ (function () {\n function Blob(binaryString) {\n assertBase64Available();\n this._binaryString = binaryString;\n }\n Blob.fromBase64String = function (base64) {\n validateExactNumberOfArgs('Blob.fromBase64String', arguments, 1);\n validateArgType('Blob.fromBase64String', 'string', 1, base64);\n assertBase64Available();\n try {\n var binaryString = PlatformSupport.getPlatform().atob(base64);\n return new Blob(binaryString);\n }\n catch (e) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Failed to construct Blob from Base64 string: ' + e);\n }\n };\n Blob.fromUint8Array = function (array) {\n validateExactNumberOfArgs('Blob.fromUint8Array', arguments, 1);\n assertUint8ArrayAvailable();\n if (!(array instanceof Uint8Array)) {\n throw invalidClassError('Blob.fromUint8Array', 'Uint8Array', 1, array);\n }\n // We can't call array.map directly because it expects the return type to\n // be a Uint8Array, whereas we can convert it to a regular array by invoking\n // map on the Array prototype.\n var binaryString = Array.prototype.map\n .call(array, function (char) {\n return String.fromCharCode(char);\n })\n .join('');\n return new Blob(binaryString);\n };\n Blob.prototype.toBase64 = function () {\n validateExactNumberOfArgs('Blob.toBase64', arguments, 0);\n assertBase64Available();\n return PlatformSupport.getPlatform().btoa(this._binaryString);\n };\n Blob.prototype.toUint8Array = function () {\n validateExactNumberOfArgs('Blob.toUint8Array', arguments, 0);\n assertUint8ArrayAvailable();\n var buffer = new Uint8Array(this._binaryString.length);\n for (var i = 0; i < this._binaryString.length; i++) {\n buffer[i] = this._binaryString.charCodeAt(i);\n }\n return buffer;\n };\n Blob.prototype.toString = function () {\n return 'Blob(base64: ' + this.toBase64() + ')';\n };\n Blob.prototype.isEqual = function (other) {\n return this._binaryString === other._binaryString;\n };\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */\n Blob.prototype._compareTo = function (other) {\n return primitiveComparator(this._binaryString, other._binaryString);\n };\n return Blob;\n}());\nexport { Blob };\n// Public instance that disallows construction at runtime. This constructor is\n// used when exporting Blob on firebase.firestore.Blob and will be called Blob\n// publicly. Internally we still use Blob which has a type checked private\n// constructor. Note that Blob and PublicBlob can be used interchangeably in\n// instanceof checks.\n// For our internal TypeScript code PublicBlob doesn't exist as a type, and so\n// we need to use Blob as type and export it too.\n// tslint:disable-next-line:variable-name We're treating this as a class name.\nexport var PublicBlob = makeConstructorPrivate(Blob, 'Use Blob.fromUint8Array() or Blob.fromBase64String() instead.');\n\n//# sourceMappingURL=blob.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/api/blob.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { assert, fail } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { DocumentKey } from './document_key';\nexport var TypeOrder;\n(function (TypeOrder) {\n // This order is defined by the backend.\n TypeOrder[TypeOrder[\"NullValue\"] = 0] = \"NullValue\";\n TypeOrder[TypeOrder[\"BooleanValue\"] = 1] = \"BooleanValue\";\n TypeOrder[TypeOrder[\"NumberValue\"] = 2] = \"NumberValue\";\n TypeOrder[TypeOrder[\"TimestampValue\"] = 3] = \"TimestampValue\";\n TypeOrder[TypeOrder[\"StringValue\"] = 4] = \"StringValue\";\n TypeOrder[TypeOrder[\"BlobValue\"] = 5] = \"BlobValue\";\n TypeOrder[TypeOrder[\"RefValue\"] = 6] = \"RefValue\";\n TypeOrder[TypeOrder[\"GeoPointValue\"] = 7] = \"GeoPointValue\";\n TypeOrder[TypeOrder[\"ArrayValue\"] = 8] = \"ArrayValue\";\n TypeOrder[TypeOrder[\"ObjectValue\"] = 9] = \"ObjectValue\";\n})(TypeOrder || (TypeOrder = {}));\n/** Defines the return value for pending server timestamps. */\nexport var ServerTimestampBehavior;\n(function (ServerTimestampBehavior) {\n ServerTimestampBehavior[ServerTimestampBehavior[\"Default\"] = 0] = \"Default\";\n ServerTimestampBehavior[ServerTimestampBehavior[\"Estimate\"] = 1] = \"Estimate\";\n ServerTimestampBehavior[ServerTimestampBehavior[\"Previous\"] = 2] = \"Previous\";\n})(ServerTimestampBehavior || (ServerTimestampBehavior = {}));\n/** Holds properties that define field value deserialization options. */\nvar FieldValueOptions = /** @class */ (function () {\n function FieldValueOptions(serverTimestampBehavior) {\n this.serverTimestampBehavior = serverTimestampBehavior;\n }\n FieldValueOptions.fromSnapshotOptions = function (options) {\n switch (options.serverTimestamps) {\n case 'estimate':\n return new FieldValueOptions(ServerTimestampBehavior.Estimate);\n case 'previous':\n return new FieldValueOptions(ServerTimestampBehavior.Previous);\n case 'none': // Fall-through intended.\n case undefined:\n return FieldValueOptions.defaultOptions;\n default:\n return fail('fromSnapshotOptions() called with invalid options.');\n }\n };\n FieldValueOptions.defaultOptions = new FieldValueOptions(ServerTimestampBehavior.Default);\n return FieldValueOptions;\n}());\nexport { FieldValueOptions };\n/**\n * A field value represents a datatype as stored by Firestore.\n */\nvar FieldValue = /** @class */ (function () {\n function FieldValue() {\n }\n FieldValue.prototype.toString = function () {\n var val = this.value();\n return val === null ? 'null' : val.toString();\n };\n FieldValue.prototype.defaultCompareTo = function (other) {\n assert(this.typeOrder !== other.typeOrder, 'Default compareTo should not be used for values of same type.');\n var cmp = primitiveComparator(this.typeOrder, other.typeOrder);\n return cmp;\n };\n return FieldValue;\n}());\nexport { FieldValue };\nvar NullValue = /** @class */ (function (_super) {\n __extends(NullValue, _super);\n function NullValue() {\n var _this = _super.call(this) || this;\n _this.typeOrder = TypeOrder.NullValue;\n // internalValue is unused but we add it to work around\n // https://github.com/Microsoft/TypeScript/issues/15585\n _this.internalValue = null;\n return _this;\n }\n NullValue.prototype.value = function (options) {\n return null;\n };\n NullValue.prototype.isEqual = function (other) {\n return other instanceof NullValue;\n };\n NullValue.prototype.compareTo = function (other) {\n if (other instanceof NullValue) {\n return 0;\n }\n return this.defaultCompareTo(other);\n };\n NullValue.INSTANCE = new NullValue();\n return NullValue;\n}(FieldValue));\nexport { NullValue };\nvar BooleanValue = /** @class */ (function (_super) {\n __extends(BooleanValue, _super);\n function BooleanValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.BooleanValue;\n return _this;\n }\n BooleanValue.prototype.value = function (options) {\n return this.internalValue;\n };\n BooleanValue.prototype.isEqual = function (other) {\n return (other instanceof BooleanValue &&\n this.internalValue === other.internalValue);\n };\n BooleanValue.prototype.compareTo = function (other) {\n if (other instanceof BooleanValue) {\n return primitiveComparator(this, other);\n }\n return this.defaultCompareTo(other);\n };\n BooleanValue.of = function (value) {\n return value ? BooleanValue.TRUE : BooleanValue.FALSE;\n };\n BooleanValue.TRUE = new BooleanValue(true);\n BooleanValue.FALSE = new BooleanValue(false);\n return BooleanValue;\n}(FieldValue));\nexport { BooleanValue };\n/** Base class for IntegerValue and DoubleValue. */\nvar NumberValue = /** @class */ (function (_super) {\n __extends(NumberValue, _super);\n function NumberValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.NumberValue;\n return _this;\n }\n NumberValue.prototype.value = function (options) {\n return this.internalValue;\n };\n NumberValue.prototype.compareTo = function (other) {\n if (other instanceof NumberValue) {\n return numericComparator(this.internalValue, other.internalValue);\n }\n return this.defaultCompareTo(other);\n };\n return NumberValue;\n}(FieldValue));\nexport { NumberValue };\n/** Utility function to compare doubles (using Firestore semantics for NaN). */\nfunction numericComparator(left, right) {\n if (left < right) {\n return -1;\n }\n else if (left > right) {\n return 1;\n }\n else if (left === right) {\n return 0;\n }\n else {\n // one or both are NaN.\n if (isNaN(left)) {\n return isNaN(right) ? 0 : -1;\n }\n else {\n return 1;\n }\n }\n}\n/**\n * Utility function to check numbers for equality using Firestore semantics\n * (NaN === NaN, -0.0 !== 0.0).\n */\nfunction numericEquals(left, right) {\n // Implemented based on Object.is() polyfill from\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n if (left === right) {\n // +0 != -0\n return left !== 0 || 1 / left === 1 / right;\n }\n else {\n // NaN == NaN\n return left !== left && right !== right;\n }\n}\nvar IntegerValue = /** @class */ (function (_super) {\n __extends(IntegerValue, _super);\n function IntegerValue(internalValue) {\n return _super.call(this, internalValue) || this;\n }\n IntegerValue.prototype.isEqual = function (other) {\n // NOTE: DoubleValue and IntegerValue instances may compareTo() the same,\n // but that doesn't make them equal via isEqual().\n if (other instanceof IntegerValue) {\n return numericEquals(this.internalValue, other.internalValue);\n }\n else {\n return false;\n }\n };\n return IntegerValue;\n}(NumberValue));\nexport { IntegerValue };\nvar DoubleValue = /** @class */ (function (_super) {\n __extends(DoubleValue, _super);\n function DoubleValue(internalValue) {\n var _this = _super.call(this, internalValue) || this;\n _this.internalValue = internalValue;\n return _this;\n }\n DoubleValue.prototype.isEqual = function (other) {\n // NOTE: DoubleValue and IntegerValue instances may compareTo() the same,\n // but that doesn't make them equal via isEqual().\n if (other instanceof DoubleValue) {\n return numericEquals(this.internalValue, other.internalValue);\n }\n else {\n return false;\n }\n };\n DoubleValue.NAN = new DoubleValue(NaN);\n DoubleValue.POSITIVE_INFINITY = new DoubleValue(Infinity);\n DoubleValue.NEGATIVE_INFINITY = new DoubleValue(-Infinity);\n return DoubleValue;\n}(NumberValue));\nexport { DoubleValue };\n// TODO(b/37267885): Add truncation support\nvar StringValue = /** @class */ (function (_super) {\n __extends(StringValue, _super);\n function StringValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.StringValue;\n return _this;\n }\n StringValue.prototype.value = function (options) {\n return this.internalValue;\n };\n StringValue.prototype.isEqual = function (other) {\n return (other instanceof StringValue && this.internalValue === other.internalValue);\n };\n StringValue.prototype.compareTo = function (other) {\n if (other instanceof StringValue) {\n return primitiveComparator(this.internalValue, other.internalValue);\n }\n return this.defaultCompareTo(other);\n };\n return StringValue;\n}(FieldValue));\nexport { StringValue };\nvar TimestampValue = /** @class */ (function (_super) {\n __extends(TimestampValue, _super);\n function TimestampValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.TimestampValue;\n return _this;\n }\n TimestampValue.prototype.value = function (options) {\n return this.internalValue.toDate();\n };\n TimestampValue.prototype.isEqual = function (other) {\n return (other instanceof TimestampValue &&\n this.internalValue.isEqual(other.internalValue));\n };\n TimestampValue.prototype.compareTo = function (other) {\n if (other instanceof TimestampValue) {\n return this.internalValue.compareTo(other.internalValue);\n }\n else if (other instanceof ServerTimestampValue) {\n // Concrete timestamps come before server timestamps.\n return -1;\n }\n else {\n return this.defaultCompareTo(other);\n }\n };\n return TimestampValue;\n}(FieldValue));\nexport { TimestampValue };\n/**\n * Represents a locally-applied ServerTimestamp.\n *\n * Notes:\n * - ServerTimestampValue instances are created as the result of applying a\n * TransformMutation (see TransformMutation.applyTo()). They can only exist in\n * the local view of a document. Therefore they do not need to be parsed or\n * serialized.\n * - When evaluated locally (e.g. for snapshot.data()), they by default\n * evaluate to `null`. This behavior can be configured by passing custom\n * FieldValueOptions to value().\n * - With respect to other ServerTimestampValues, they sort by their\n * localWriteTime.\n */\nvar ServerTimestampValue = /** @class */ (function (_super) {\n __extends(ServerTimestampValue, _super);\n function ServerTimestampValue(localWriteTime, previousValue) {\n var _this = _super.call(this) || this;\n _this.localWriteTime = localWriteTime;\n _this.previousValue = previousValue;\n _this.typeOrder = TypeOrder.TimestampValue;\n return _this;\n }\n ServerTimestampValue.prototype.value = function (options) {\n if (options &&\n options.serverTimestampBehavior === ServerTimestampBehavior.Estimate) {\n return this.localWriteTime.toDate();\n }\n else if (options &&\n options.serverTimestampBehavior === ServerTimestampBehavior.Previous) {\n return this.previousValue ? this.previousValue.value(options) : null;\n }\n else {\n return null;\n }\n };\n ServerTimestampValue.prototype.isEqual = function (other) {\n return (other instanceof ServerTimestampValue &&\n this.localWriteTime.isEqual(other.localWriteTime));\n };\n ServerTimestampValue.prototype.compareTo = function (other) {\n if (other instanceof ServerTimestampValue) {\n return this.localWriteTime.compareTo(other.localWriteTime);\n }\n else if (other instanceof TimestampValue) {\n // Server timestamps come after all concrete timestamps.\n return 1;\n }\n else {\n return this.defaultCompareTo(other);\n }\n };\n ServerTimestampValue.prototype.toString = function () {\n return '';\n };\n return ServerTimestampValue;\n}(FieldValue));\nexport { ServerTimestampValue };\nvar BlobValue = /** @class */ (function (_super) {\n __extends(BlobValue, _super);\n function BlobValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.BlobValue;\n return _this;\n }\n BlobValue.prototype.value = function (options) {\n return this.internalValue;\n };\n BlobValue.prototype.isEqual = function (other) {\n return (other instanceof BlobValue &&\n this.internalValue.isEqual(other.internalValue));\n };\n BlobValue.prototype.compareTo = function (other) {\n if (other instanceof BlobValue) {\n return this.internalValue._compareTo(other.internalValue);\n }\n return this.defaultCompareTo(other);\n };\n return BlobValue;\n}(FieldValue));\nexport { BlobValue };\nvar RefValue = /** @class */ (function (_super) {\n __extends(RefValue, _super);\n function RefValue(databaseId, key) {\n var _this = _super.call(this) || this;\n _this.databaseId = databaseId;\n _this.key = key;\n _this.typeOrder = TypeOrder.RefValue;\n return _this;\n }\n RefValue.prototype.value = function (options) {\n return this.key;\n };\n RefValue.prototype.isEqual = function (other) {\n if (other instanceof RefValue) {\n return (this.key.isEqual(other.key) && this.databaseId.isEqual(other.databaseId));\n }\n else {\n return false;\n }\n };\n RefValue.prototype.compareTo = function (other) {\n if (other instanceof RefValue) {\n var cmp = this.databaseId.compareTo(other.databaseId);\n return cmp !== 0 ? cmp : DocumentKey.comparator(this.key, other.key);\n }\n return this.defaultCompareTo(other);\n };\n return RefValue;\n}(FieldValue));\nexport { RefValue };\nvar GeoPointValue = /** @class */ (function (_super) {\n __extends(GeoPointValue, _super);\n function GeoPointValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.GeoPointValue;\n return _this;\n }\n GeoPointValue.prototype.value = function (options) {\n return this.internalValue;\n };\n GeoPointValue.prototype.isEqual = function (other) {\n return (other instanceof GeoPointValue &&\n this.internalValue.isEqual(other.internalValue));\n };\n GeoPointValue.prototype.compareTo = function (other) {\n if (other instanceof GeoPointValue) {\n return this.internalValue._compareTo(other.internalValue);\n }\n return this.defaultCompareTo(other);\n };\n return GeoPointValue;\n}(FieldValue));\nexport { GeoPointValue };\nvar ObjectValue = /** @class */ (function (_super) {\n __extends(ObjectValue, _super);\n function ObjectValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.ObjectValue;\n return _this;\n }\n ObjectValue.prototype.value = function (options) {\n var result = {};\n this.internalValue.inorderTraversal(function (key, val) {\n result[key] = val.value(options);\n });\n return result;\n };\n ObjectValue.prototype.forEach = function (action) {\n this.internalValue.inorderTraversal(action);\n };\n ObjectValue.prototype.isEqual = function (other) {\n if (other instanceof ObjectValue) {\n var it1 = this.internalValue.getIterator();\n var it2 = other.internalValue.getIterator();\n while (it1.hasNext() && it2.hasNext()) {\n var next1 = it1.getNext();\n var next2 = it2.getNext();\n if (next1.key !== next2.key || !next1.value.isEqual(next2.value)) {\n return false;\n }\n }\n return !it1.hasNext() && !it2.hasNext();\n }\n return false;\n };\n ObjectValue.prototype.compareTo = function (other) {\n if (other instanceof ObjectValue) {\n var it1 = this.internalValue.getIterator();\n var it2 = other.internalValue.getIterator();\n while (it1.hasNext() && it2.hasNext()) {\n var next1 = it1.getNext();\n var next2 = it2.getNext();\n var cmp = primitiveComparator(next1.key, next2.key) ||\n next1.value.compareTo(next2.value);\n if (cmp) {\n return cmp;\n }\n }\n // Only equal if both iterators are exhausted\n return primitiveComparator(it1.hasNext(), it2.hasNext());\n }\n else {\n return this.defaultCompareTo(other);\n }\n };\n ObjectValue.prototype.set = function (path, to) {\n assert(!path.isEmpty(), 'Cannot set field for empty path on ObjectValue');\n if (path.length === 1) {\n return this.setChild(path.firstSegment(), to);\n }\n else {\n var child = this.child(path.firstSegment());\n if (!(child instanceof ObjectValue)) {\n child = ObjectValue.EMPTY;\n }\n var newChild = child.set(path.popFirst(), to);\n return this.setChild(path.firstSegment(), newChild);\n }\n };\n ObjectValue.prototype.delete = function (path) {\n assert(!path.isEmpty(), 'Cannot delete field for empty path on ObjectValue');\n if (path.length === 1) {\n return new ObjectValue(this.internalValue.remove(path.firstSegment()));\n }\n else {\n // nested field\n var child = this.child(path.firstSegment());\n if (child instanceof ObjectValue) {\n var newChild = child.delete(path.popFirst());\n return new ObjectValue(this.internalValue.insert(path.firstSegment(), newChild));\n }\n else {\n // Don't actually change a primitive value to an object for a delete\n return this;\n }\n }\n };\n ObjectValue.prototype.contains = function (path) {\n return this.field(path) !== undefined;\n };\n ObjectValue.prototype.field = function (path) {\n assert(!path.isEmpty(), \"Can't get field of empty path\");\n var field = this;\n path.forEach(function (pathSegment) {\n if (field instanceof ObjectValue) {\n field = field.internalValue.get(pathSegment) || undefined;\n }\n else {\n field = undefined;\n }\n });\n return field;\n };\n ObjectValue.prototype.toString = function () {\n return JSON.stringify(this.value());\n };\n ObjectValue.prototype.child = function (childName) {\n return this.internalValue.get(childName) || undefined;\n };\n ObjectValue.prototype.setChild = function (childName, value) {\n return new ObjectValue(this.internalValue.insert(childName, value));\n };\n ObjectValue.EMPTY = new ObjectValue(new SortedMap(primitiveComparator));\n return ObjectValue;\n}(FieldValue));\nexport { ObjectValue };\nvar ArrayValue = /** @class */ (function (_super) {\n __extends(ArrayValue, _super);\n function ArrayValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.ArrayValue;\n return _this;\n }\n ArrayValue.prototype.value = function (options) {\n return this.internalValue.map(function (v) { return v.value(options); });\n };\n ArrayValue.prototype.forEach = function (action) {\n this.internalValue.forEach(action);\n };\n ArrayValue.prototype.isEqual = function (other) {\n if (other instanceof ArrayValue) {\n if (this.internalValue.length !== other.internalValue.length) {\n return false;\n }\n for (var i = 0; i < this.internalValue.length; i++) {\n if (!this.internalValue[i].isEqual(other.internalValue[i])) {\n return false;\n }\n }\n return true;\n }\n return false;\n };\n ArrayValue.prototype.compareTo = function (other) {\n if (other instanceof ArrayValue) {\n var minLength = Math.min(this.internalValue.length, other.internalValue.length);\n for (var i = 0; i < minLength; i++) {\n var cmp = this.internalValue[i].compareTo(other.internalValue[i]);\n if (cmp) {\n return cmp;\n }\n }\n return primitiveComparator(this.internalValue.length, other.internalValue.length);\n }\n else {\n return this.defaultCompareTo(other);\n }\n };\n ArrayValue.prototype.toString = function () {\n return JSON.stringify(this.value());\n };\n return ArrayValue;\n}(FieldValue));\nexport { ArrayValue };\n\n//# sourceMappingURL=field_value.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/model/field_value.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Untyped Number alias we can use to check for ES6 methods / properties.\n// tslint:disable-next-line:no-any variable-name\nvar NumberAsAny = Number;\n/**\n * Minimum safe integer in Javascript because of floating point precision.\n * Added to not rely on ES6 features.\n */\nexport var MIN_SAFE_INTEGER = NumberAsAny.MIN_SAFE_INTEGER || -(Math.pow(2, 53) - 1);\n/**\n * Maximum safe integer in Javascript because of floating point precision.\n * Added to not rely on ES6 features.\n */\nexport var MAX_SAFE_INTEGER = NumberAsAny.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1;\n/**\n * Returns whether an number is an integer, uses native implementation if\n * available.\n * Added to not rely on ES6 features.\n * @param value The value to test for being an integer\n */\nexport var isInteger = NumberAsAny.isInteger ||\n (function (value) {\n return typeof value === 'number' &&\n isFinite(value) &&\n Math.floor(value) === value;\n });\n/**\n * Returns whether a variable is either undefined or null.\n */\nexport function isNullOrUndefined(value) {\n return value === null || value === undefined;\n}\n/**\n * Returns whether a value is an integer and in the safe integer range\n * @param value The value to test for being an integer and in the safe range\n */\nexport function isSafeInteger(value) {\n return (isInteger(value) &&\n value <= MAX_SAFE_INTEGER &&\n value >= MIN_SAFE_INTEGER);\n}\n/**\n * Safely checks if the number is NaN.\n */\nexport function safeIsNaN(value) {\n if (NumberAsAny.IsNaN) {\n return NumberAsAny.IsNaN(value);\n }\n else {\n return typeof value === 'number' && isNaN(value);\n }\n}\n\n//# sourceMappingURL=types.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/types.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { DoubleValue, NullValue, RefValue } from '../model/field_value';\nimport { FieldPath } from '../model/path';\nimport { assert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { isNullOrUndefined } from '../util/types';\nvar Query = /** @class */ (function () {\n function Query(path, explicitOrderBy, filters, limit, startAt, endAt) {\n if (explicitOrderBy === void 0) { explicitOrderBy = []; }\n if (filters === void 0) { filters = []; }\n if (limit === void 0) { limit = null; }\n if (startAt === void 0) { startAt = null; }\n if (endAt === void 0) { endAt = null; }\n this.path = path;\n this.explicitOrderBy = explicitOrderBy;\n this.filters = filters;\n this.limit = limit;\n this.startAt = startAt;\n this.endAt = endAt;\n this.memoizedCanonicalId = null;\n this.memoizedOrderBy = null;\n if (this.startAt) {\n this.assertValidBound(this.startAt);\n }\n if (this.endAt) {\n this.assertValidBound(this.endAt);\n }\n }\n Query.atPath = function (path) {\n return new Query(path);\n };\n Object.defineProperty(Query.prototype, \"orderBy\", {\n get: function () {\n if (this.memoizedOrderBy === null) {\n var inequalityField = this.getInequalityFilterField();\n var firstOrderByField = this.getFirstOrderByField();\n if (inequalityField !== null && firstOrderByField === null) {\n // In order to implicitly add key ordering, we must also add the\n // inequality filter field for it to be a valid query.\n // Note that the default inequality field and key ordering is ascending.\n if (inequalityField.isKeyField()) {\n this.memoizedOrderBy = [KEY_ORDERING_ASC];\n }\n else {\n this.memoizedOrderBy = [\n new OrderBy(inequalityField),\n KEY_ORDERING_ASC\n ];\n }\n }\n else {\n assert(inequalityField === null ||\n (firstOrderByField !== null &&\n inequalityField.isEqual(firstOrderByField)), 'First orderBy should match inequality field.');\n this.memoizedOrderBy = [];\n var foundKeyOrdering = false;\n for (var _i = 0, _a = this.explicitOrderBy; _i < _a.length; _i++) {\n var orderBy = _a[_i];\n this.memoizedOrderBy.push(orderBy);\n if (orderBy.field.isKeyField()) {\n foundKeyOrdering = true;\n }\n }\n if (!foundKeyOrdering) {\n // The order of the implicit key ordering always matches the last\n // explicit order by\n var lastDirection = this.explicitOrderBy.length > 0\n ? this.explicitOrderBy[this.explicitOrderBy.length - 1].dir\n : Direction.ASCENDING;\n this.memoizedOrderBy.push(lastDirection === Direction.ASCENDING\n ? KEY_ORDERING_ASC\n : KEY_ORDERING_DESC);\n }\n }\n }\n return this.memoizedOrderBy;\n },\n enumerable: true,\n configurable: true\n });\n Query.prototype.addFilter = function (filter) {\n assert(this.getInequalityFilterField() == null ||\n !(filter instanceof RelationFilter) ||\n !filter.isInequality() ||\n filter.field.isEqual(this.getInequalityFilterField()), 'Query must only have one inequality field.');\n assert(!DocumentKey.isDocumentKey(this.path), 'No filtering allowed for document query');\n var newFilters = this.filters.concat([filter]);\n return new Query(this.path, this.explicitOrderBy.slice(), newFilters, this.limit, this.startAt, this.endAt);\n };\n Query.prototype.addOrderBy = function (orderBy) {\n assert(!DocumentKey.isDocumentKey(this.path), 'No ordering allowed for document query');\n assert(!this.startAt && !this.endAt, 'Bounds must be set after orderBy');\n // TODO(dimond): validate that orderBy does not list the same key twice.\n var newOrderBy = this.explicitOrderBy.concat([orderBy]);\n return new Query(this.path, newOrderBy, this.filters.slice(), this.limit, this.startAt, this.endAt);\n };\n Query.prototype.withLimit = function (limit) {\n return new Query(this.path, this.explicitOrderBy.slice(), this.filters.slice(), limit, this.startAt, this.endAt);\n };\n Query.prototype.withStartAt = function (bound) {\n return new Query(this.path, this.explicitOrderBy.slice(), this.filters.slice(), this.limit, bound, this.endAt);\n };\n Query.prototype.withEndAt = function (bound) {\n return new Query(this.path, this.explicitOrderBy.slice(), this.filters.slice(), this.limit, this.startAt, bound);\n };\n // TODO(b/29183165): This is used to get a unique string from a query to, for\n // example, use as a dictionary key, but the implementation is subject to\n // collisions. Make it collision-free.\n Query.prototype.canonicalId = function () {\n if (this.memoizedCanonicalId === null) {\n var canonicalId = this.path.canonicalString();\n canonicalId += '|f:';\n for (var _i = 0, _a = this.filters; _i < _a.length; _i++) {\n var filter = _a[_i];\n canonicalId += filter.canonicalId();\n canonicalId += ',';\n }\n canonicalId += '|ob:';\n // TODO(dimond): make this collision resistant\n for (var _b = 0, _c = this.orderBy; _b < _c.length; _b++) {\n var orderBy = _c[_b];\n canonicalId += orderBy.canonicalId();\n canonicalId += ',';\n }\n if (!isNullOrUndefined(this.limit)) {\n canonicalId += '|l:';\n canonicalId += this.limit;\n }\n if (this.startAt) {\n canonicalId += '|lb:';\n canonicalId += this.startAt.canonicalId();\n }\n if (this.endAt) {\n canonicalId += '|ub:';\n canonicalId += this.endAt.canonicalId();\n }\n this.memoizedCanonicalId = canonicalId;\n }\n return this.memoizedCanonicalId;\n };\n Query.prototype.toString = function () {\n var str = 'Query(' + this.path.canonicalString();\n if (this.filters.length > 0) {\n str += \", filters: [\" + this.filters.join(', ') + \"]\";\n }\n if (!isNullOrUndefined(this.limit)) {\n str += ', limit: ' + this.limit;\n }\n if (this.explicitOrderBy.length > 0) {\n str += \", orderBy: [\" + this.explicitOrderBy.join(', ') + \"]\";\n }\n if (this.startAt) {\n str += ', startAt: ' + this.startAt.canonicalId();\n }\n if (this.endAt) {\n str += ', endAt: ' + this.endAt.canonicalId();\n }\n return str + ')';\n };\n Query.prototype.isEqual = function (other) {\n if (this.limit !== other.limit) {\n return false;\n }\n if (this.orderBy.length !== other.orderBy.length) {\n return false;\n }\n for (var i = 0; i < this.orderBy.length; i++) {\n if (!this.orderBy[i].isEqual(other.orderBy[i])) {\n return false;\n }\n }\n if (this.filters.length !== other.filters.length) {\n return false;\n }\n for (var i = 0; i < this.filters.length; i++) {\n if (!this.filters[i].isEqual(other.filters[i])) {\n return false;\n }\n }\n if (!this.path.isEqual(other.path)) {\n return false;\n }\n if (this.startAt !== null\n ? !this.startAt.isEqual(other.startAt)\n : other.startAt !== null) {\n return false;\n }\n return this.endAt !== null\n ? this.endAt.isEqual(other.endAt)\n : other.endAt === null;\n };\n Query.prototype.docComparator = function (d1, d2) {\n var comparedOnKeyField = false;\n for (var _i = 0, _a = this.orderBy; _i < _a.length; _i++) {\n var orderBy = _a[_i];\n var comp = orderBy.compare(d1, d2);\n if (comp !== 0)\n return comp;\n comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField();\n }\n // Assert that we actually compared by key\n assert(comparedOnKeyField, \"orderBy used that doesn't compare on key field\");\n return 0;\n };\n Query.prototype.matches = function (doc) {\n return (this.matchesAncestor(doc) &&\n this.matchesOrderBy(doc) &&\n this.matchesFilters(doc) &&\n this.matchesBounds(doc));\n };\n Query.prototype.hasLimit = function () {\n return !isNullOrUndefined(this.limit);\n };\n Query.prototype.getFirstOrderByField = function () {\n return this.explicitOrderBy.length > 0\n ? this.explicitOrderBy[0].field\n : null;\n };\n Query.prototype.getInequalityFilterField = function () {\n for (var _i = 0, _a = this.filters; _i < _a.length; _i++) {\n var filter = _a[_i];\n if (filter instanceof RelationFilter && filter.isInequality()) {\n return filter.field;\n }\n }\n return null;\n };\n Query.prototype.isDocumentQuery = function () {\n return DocumentKey.isDocumentKey(this.path) && this.filters.length === 0;\n };\n Query.prototype.matchesAncestor = function (doc) {\n var docPath = doc.key.path;\n if (DocumentKey.isDocumentKey(this.path)) {\n // exact match for document queries\n return this.path.isEqual(docPath);\n }\n else {\n // shallow ancestor queries by default\n return (this.path.isPrefixOf(docPath) && this.path.length === docPath.length - 1);\n }\n };\n /**\n * A document must have a value for every ordering clause in order to show up\n * in the results.\n */\n Query.prototype.matchesOrderBy = function (doc) {\n for (var _i = 0, _a = this.explicitOrderBy; _i < _a.length; _i++) {\n var orderBy = _a[_i];\n // order by key always matches\n if (!orderBy.field.isKeyField() &&\n doc.field(orderBy.field) === undefined) {\n return false;\n }\n }\n return true;\n };\n Query.prototype.matchesFilters = function (doc) {\n for (var _i = 0, _a = this.filters; _i < _a.length; _i++) {\n var filter = _a[_i];\n if (!filter.matches(doc)) {\n return false;\n }\n }\n return true;\n };\n /**\n * Makes sure a document is within the bounds, if provided.\n */\n Query.prototype.matchesBounds = function (doc) {\n if (this.startAt && !this.startAt.sortsBeforeDocument(this.orderBy, doc)) {\n return false;\n }\n if (this.endAt && this.endAt.sortsBeforeDocument(this.orderBy, doc)) {\n return false;\n }\n return true;\n };\n Query.prototype.assertValidBound = function (bound) {\n assert(bound.position.length <= this.orderBy.length, 'Bound is longer than orderBy');\n };\n return Query;\n}());\nexport { Query };\nvar RelationOp = /** @class */ (function () {\n function RelationOp(name) {\n this.name = name;\n }\n RelationOp.fromString = function (op) {\n switch (op) {\n case '<':\n return RelationOp.LESS_THAN;\n case '<=':\n return RelationOp.LESS_THAN_OR_EQUAL;\n case '==':\n return RelationOp.EQUAL;\n case '>=':\n return RelationOp.GREATER_THAN_OR_EQUAL;\n case '>':\n return RelationOp.GREATER_THAN;\n default:\n return fail('Unknown relation: ' + op);\n }\n };\n RelationOp.prototype.toString = function () {\n return this.name;\n };\n RelationOp.prototype.isEqual = function (other) {\n return this.name === other.name;\n };\n RelationOp.LESS_THAN = new RelationOp('<');\n RelationOp.LESS_THAN_OR_EQUAL = new RelationOp('<=');\n RelationOp.EQUAL = new RelationOp('==');\n RelationOp.GREATER_THAN = new RelationOp('>');\n RelationOp.GREATER_THAN_OR_EQUAL = new RelationOp('>=');\n return RelationOp;\n}());\nexport { RelationOp };\nvar RelationFilter = /** @class */ (function () {\n function RelationFilter(field, op, value) {\n this.field = field;\n this.op = op;\n this.value = value;\n }\n RelationFilter.prototype.matches = function (doc) {\n if (this.field.isKeyField()) {\n assert(this.value instanceof RefValue, 'Comparing on key, but filter value not a RefValue');\n var refValue = this.value;\n var comparison = DocumentKey.comparator(doc.key, refValue.key);\n return this.matchesComparison(comparison);\n }\n else {\n var val = doc.field(this.field);\n return val !== undefined && this.matchesValue(val);\n }\n };\n RelationFilter.prototype.matchesValue = function (value) {\n // Only compare types with matching backend order (such as double and int).\n if (this.value.typeOrder !== value.typeOrder) {\n return false;\n }\n return this.matchesComparison(value.compareTo(this.value));\n };\n RelationFilter.prototype.matchesComparison = function (comparison) {\n switch (this.op) {\n case RelationOp.LESS_THAN:\n return comparison < 0;\n case RelationOp.LESS_THAN_OR_EQUAL:\n return comparison <= 0;\n case RelationOp.EQUAL:\n return comparison === 0;\n case RelationOp.GREATER_THAN:\n return comparison > 0;\n case RelationOp.GREATER_THAN_OR_EQUAL:\n return comparison >= 0;\n default:\n return fail('Unknown relation op' + this.op);\n }\n };\n RelationFilter.prototype.isInequality = function () {\n return this.op !== RelationOp.EQUAL;\n };\n RelationFilter.prototype.canonicalId = function () {\n // TODO(b/29183165): Technically, this won't be unique if two values have\n // the same description, such as the int 3 and the string \"3\". So we should\n // add the types in here somehow, too.\n return (this.field.canonicalString() + this.op.toString() + this.value.toString());\n };\n RelationFilter.prototype.isEqual = function (other) {\n if (other instanceof RelationFilter) {\n return (this.op.isEqual(other.op) &&\n this.field.isEqual(other.field) &&\n this.value.isEqual(other.value));\n }\n else {\n return false;\n }\n };\n RelationFilter.prototype.toString = function () {\n return this.field.canonicalString() + \" \" + this.op + \" \" + this.value.value();\n };\n return RelationFilter;\n}());\nexport { RelationFilter };\n/**\n * Filter that matches 'null' values.\n */\nvar NullFilter = /** @class */ (function () {\n function NullFilter(field) {\n this.field = field;\n }\n NullFilter.prototype.matches = function (doc) {\n var val = doc.field(this.field);\n return val !== undefined && val.value() === null;\n };\n NullFilter.prototype.canonicalId = function () {\n return this.field.canonicalString() + ' IS null';\n };\n NullFilter.prototype.toString = function () {\n return this.field.canonicalString() + \" IS null\";\n };\n NullFilter.prototype.isEqual = function (other) {\n if (other instanceof NullFilter) {\n return this.field.isEqual(other.field);\n }\n else {\n return false;\n }\n };\n return NullFilter;\n}());\nexport { NullFilter };\n/**\n * Filter that matches 'NaN' values.\n */\nvar NanFilter = /** @class */ (function () {\n function NanFilter(field) {\n this.field = field;\n }\n NanFilter.prototype.matches = function (doc) {\n var val = doc.field(this.field).value();\n return typeof val === 'number' && isNaN(val);\n };\n NanFilter.prototype.canonicalId = function () {\n return this.field.canonicalString() + ' IS NaN';\n };\n NanFilter.prototype.toString = function () {\n return this.field.canonicalString() + \" IS NaN\";\n };\n NanFilter.prototype.isEqual = function (other) {\n if (other instanceof NanFilter) {\n return this.field.isEqual(other.field);\n }\n else {\n return false;\n }\n };\n return NanFilter;\n}());\nexport { NanFilter };\n/**\n * Creates a filter based on the provided arguments.\n */\nexport function fieldFilter(field, op, value) {\n if (value.isEqual(NullValue.INSTANCE)) {\n if (op !== RelationOp.EQUAL) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You can only perform equals ' + 'comparisons on null.');\n }\n return new NullFilter(field);\n }\n else if (value.isEqual(DoubleValue.NAN)) {\n if (op !== RelationOp.EQUAL) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You can only perform equals ' + 'comparisons on NaN.');\n }\n return new NanFilter(field);\n }\n else {\n return new RelationFilter(field, op, value);\n }\n}\n/**\n * The direction of sorting in an order by.\n */\nvar Direction = /** @class */ (function () {\n function Direction(name) {\n this.name = name;\n }\n Direction.prototype.toString = function () {\n return this.name;\n };\n Direction.ASCENDING = new Direction('asc');\n Direction.DESCENDING = new Direction('desc');\n return Direction;\n}());\nexport { Direction };\n/**\n * Represents a bound of a query.\n *\n * The bound is specified with the given components representing a position and\n * whether it's just before or just after the position (relative to whatever the\n * query order is).\n *\n * The position represents a logical index position for a query. It's a prefix\n * of values for the (potentially implicit) order by clauses of a query.\n *\n * Bound provides a function to determine whether a document comes before or\n * after a bound. This is influenced by whether the position is just before or\n * just after the provided values.\n */\nvar Bound = /** @class */ (function () {\n function Bound(position, before) {\n this.position = position;\n this.before = before;\n }\n Bound.prototype.canonicalId = function () {\n // TODO(b/29183165): Make this collision robust.\n var canonicalId = this.before ? 'b:' : 'a:';\n for (var _i = 0, _a = this.position; _i < _a.length; _i++) {\n var component = _a[_i];\n canonicalId += component.toString();\n }\n return canonicalId;\n };\n /**\n * Returns true if a document sorts before a bound using the provided sort\n * order.\n */\n Bound.prototype.sortsBeforeDocument = function (orderBy, doc) {\n assert(this.position.length <= orderBy.length, \"Bound has more components than query's orderBy\");\n var comparison = 0;\n for (var i = 0; i < this.position.length; i++) {\n var orderByComponent = orderBy[i];\n var component = this.position[i];\n if (orderByComponent.field.isKeyField()) {\n assert(component instanceof RefValue, 'Bound has a non-key value where the key path is being used.');\n comparison = DocumentKey.comparator(component.key, doc.key);\n }\n else {\n var docValue = doc.field(orderByComponent.field);\n assert(docValue !== undefined, 'Field should exist since document matched the orderBy already.');\n comparison = component.compareTo(docValue);\n }\n if (orderByComponent.dir === Direction.DESCENDING) {\n comparison = comparison * -1;\n }\n if (comparison !== 0) {\n break;\n }\n }\n return this.before ? comparison <= 0 : comparison < 0;\n };\n Bound.prototype.isEqual = function (other) {\n if (other === null) {\n return false;\n }\n if (this.before !== other.before ||\n this.position.length !== other.position.length) {\n return false;\n }\n for (var i = 0; i < this.position.length; i++) {\n var thisPosition = this.position[i];\n var otherPosition = other.position[i];\n return thisPosition.isEqual(otherPosition);\n }\n return true;\n };\n return Bound;\n}());\nexport { Bound };\n/**\n * An ordering on a field, in some Direction. Direction defaults to ASCENDING.\n */\nvar OrderBy = /** @class */ (function () {\n function OrderBy(field, dir) {\n this.field = field;\n if (dir === undefined) {\n dir = Direction.ASCENDING;\n }\n this.dir = dir;\n this.isKeyOrderBy = field.isKeyField();\n }\n OrderBy.prototype.compare = function (d1, d2) {\n var comparison = this.isKeyOrderBy\n ? Document.compareByKey(d1, d2)\n : Document.compareByField(this.field, d1, d2);\n switch (this.dir) {\n case Direction.ASCENDING:\n return comparison;\n case Direction.DESCENDING:\n return -1 * comparison;\n default:\n return fail('Unknown direction: ' + this.dir);\n }\n };\n OrderBy.prototype.canonicalId = function () {\n // TODO(b/29183165): Make this collision robust.\n return this.field.canonicalString() + this.dir.toString();\n };\n OrderBy.prototype.toString = function () {\n return this.field.canonicalString() + \" (\" + this.dir + \")\";\n };\n OrderBy.prototype.isEqual = function (other) {\n return this.dir === other.dir && this.field.isEqual(other.field);\n };\n return OrderBy;\n}());\nexport { OrderBy };\nvar KEY_ORDERING_ASC = new OrderBy(FieldPath.keyField(), Direction.ASCENDING);\nvar KEY_ORDERING_DESC = new OrderBy(FieldPath.keyField(), Direction.DESCENDING);\n\n//# sourceMappingURL=query.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/query.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { fail } from '../util/assert';\nimport { Code } from '../util/error';\nimport * as log from '../util/log';\n/**\n * Error Codes describing the different ways GRPC can fail. These are copied\n * directly from GRPC's sources here:\n *\n * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n *\n * Important! The names of these identifiers matter because the string forms\n * are used for reverse lookups from the webchannel stream. Do NOT change the\n * names of these identifiers.\n */\nvar RpcCode;\n(function (RpcCode) {\n RpcCode[RpcCode[\"OK\"] = 0] = \"OK\";\n RpcCode[RpcCode[\"CANCELLED\"] = 1] = \"CANCELLED\";\n RpcCode[RpcCode[\"UNKNOWN\"] = 2] = \"UNKNOWN\";\n RpcCode[RpcCode[\"INVALID_ARGUMENT\"] = 3] = \"INVALID_ARGUMENT\";\n RpcCode[RpcCode[\"DEADLINE_EXCEEDED\"] = 4] = \"DEADLINE_EXCEEDED\";\n RpcCode[RpcCode[\"NOT_FOUND\"] = 5] = \"NOT_FOUND\";\n RpcCode[RpcCode[\"ALREADY_EXISTS\"] = 6] = \"ALREADY_EXISTS\";\n RpcCode[RpcCode[\"PERMISSION_DENIED\"] = 7] = \"PERMISSION_DENIED\";\n RpcCode[RpcCode[\"UNAUTHENTICATED\"] = 16] = \"UNAUTHENTICATED\";\n RpcCode[RpcCode[\"RESOURCE_EXHAUSTED\"] = 8] = \"RESOURCE_EXHAUSTED\";\n RpcCode[RpcCode[\"FAILED_PRECONDITION\"] = 9] = \"FAILED_PRECONDITION\";\n RpcCode[RpcCode[\"ABORTED\"] = 10] = \"ABORTED\";\n RpcCode[RpcCode[\"OUT_OF_RANGE\"] = 11] = \"OUT_OF_RANGE\";\n RpcCode[RpcCode[\"UNIMPLEMENTED\"] = 12] = \"UNIMPLEMENTED\";\n RpcCode[RpcCode[\"INTERNAL\"] = 13] = \"INTERNAL\";\n RpcCode[RpcCode[\"UNAVAILABLE\"] = 14] = \"UNAVAILABLE\";\n RpcCode[RpcCode[\"DATA_LOSS\"] = 15] = \"DATA_LOSS\";\n})(RpcCode || (RpcCode = {}));\nexport function isPermanentError(code) {\n switch (code) {\n case Code.OK:\n return fail('Treated status OK as error');\n case Code.CANCELLED:\n case Code.UNKNOWN:\n case Code.DEADLINE_EXCEEDED:\n case Code.RESOURCE_EXHAUSTED:\n case Code.INTERNAL:\n case Code.UNAVAILABLE:\n // Unauthenticated means something went wrong with our token and we need\n // to retry with new credentials which will happen automatically.\n // TODO(b/37325376): Give up after second unauthenticated error.\n case Code.UNAUTHENTICATED:\n return false;\n case Code.INVALID_ARGUMENT:\n case Code.NOT_FOUND:\n case Code.ALREADY_EXISTS:\n case Code.PERMISSION_DENIED:\n case Code.FAILED_PRECONDITION:\n // Aborted might be retried in some scenarios, but that is dependant on\n // the context and should handled individually by the calling code.\n // See https://cloud.google.com/apis/design/errors.\n case Code.ABORTED:\n case Code.OUT_OF_RANGE:\n case Code.UNIMPLEMENTED:\n case Code.DATA_LOSS:\n return true;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n/**\n * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.\n *\n * @returns The Code equivalent to the given status string or undefined if\n * there is no match.\n */\nexport function mapCodeFromRpcStatus(status) {\n // tslint:disable-next-line:no-any lookup by string\n var code = RpcCode[status];\n if (code === undefined) {\n return undefined;\n }\n return mapCodeFromRpcCode(code);\n}\n/**\n * Maps an error Code from GRPC status code number, like 0, 1, or 14. These\n * are not the same as HTTP status codes.\n *\n * @returns The Code equivalent to the given GRPC status code. Fails if there\n * is no match.\n */\nexport function mapCodeFromRpcCode(code) {\n if (code === undefined) {\n // This shouldn't normally happen, but in certain error cases (like trying\n // to send invalid proto messages) we may get an error with no GRPC code.\n log.error('GRPC error has no .code');\n return Code.UNKNOWN;\n }\n switch (code) {\n case RpcCode.OK:\n return Code.OK;\n case RpcCode.CANCELLED:\n return Code.CANCELLED;\n case RpcCode.UNKNOWN:\n return Code.UNKNOWN;\n case RpcCode.DEADLINE_EXCEEDED:\n return Code.DEADLINE_EXCEEDED;\n case RpcCode.RESOURCE_EXHAUSTED:\n return Code.RESOURCE_EXHAUSTED;\n case RpcCode.INTERNAL:\n return Code.INTERNAL;\n case RpcCode.UNAVAILABLE:\n return Code.UNAVAILABLE;\n case RpcCode.UNAUTHENTICATED:\n return Code.UNAUTHENTICATED;\n case RpcCode.INVALID_ARGUMENT:\n return Code.INVALID_ARGUMENT;\n case RpcCode.NOT_FOUND:\n return Code.NOT_FOUND;\n case RpcCode.ALREADY_EXISTS:\n return Code.ALREADY_EXISTS;\n case RpcCode.PERMISSION_DENIED:\n return Code.PERMISSION_DENIED;\n case RpcCode.FAILED_PRECONDITION:\n return Code.FAILED_PRECONDITION;\n case RpcCode.ABORTED:\n return Code.ABORTED;\n case RpcCode.OUT_OF_RANGE:\n return Code.OUT_OF_RANGE;\n case RpcCode.UNIMPLEMENTED:\n return Code.UNIMPLEMENTED;\n case RpcCode.DATA_LOSS:\n return Code.DATA_LOSS;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n/**\n * Maps an RPC code from a Code. This is the reverse operation from\n * mapCodeFromRpcCode and should really only be used in tests.\n */\nexport function mapRpcCodeFromCode(code) {\n if (code === undefined) {\n return RpcCode.OK;\n }\n switch (code) {\n case Code.OK:\n return RpcCode.OK;\n case Code.CANCELLED:\n return RpcCode.CANCELLED;\n case Code.UNKNOWN:\n return RpcCode.UNKNOWN;\n case Code.DEADLINE_EXCEEDED:\n return RpcCode.DEADLINE_EXCEEDED;\n case Code.RESOURCE_EXHAUSTED:\n return RpcCode.RESOURCE_EXHAUSTED;\n case Code.INTERNAL:\n return RpcCode.INTERNAL;\n case Code.UNAVAILABLE:\n return RpcCode.UNAVAILABLE;\n case Code.UNAUTHENTICATED:\n return RpcCode.UNAUTHENTICATED;\n case Code.INVALID_ARGUMENT:\n return RpcCode.INVALID_ARGUMENT;\n case Code.NOT_FOUND:\n return RpcCode.NOT_FOUND;\n case Code.ALREADY_EXISTS:\n return RpcCode.ALREADY_EXISTS;\n case Code.PERMISSION_DENIED:\n return RpcCode.PERMISSION_DENIED;\n case Code.FAILED_PRECONDITION:\n return RpcCode.FAILED_PRECONDITION;\n case Code.ABORTED:\n return RpcCode.ABORTED;\n case Code.OUT_OF_RANGE:\n return RpcCode.OUT_OF_RANGE;\n case Code.UNIMPLEMENTED:\n return RpcCode.UNIMPLEMENTED;\n case Code.DATA_LOSS:\n return RpcCode.DATA_LOSS;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n/**\n * Converts an HTTP Status Code to the equivalent error code.\n *\n * @param status An HTTP Status Code, like 200, 404, 503, etc.\n * @returns The equivalent Code. Unknown status codes are mapped to\n * Code.UNKNOWN.\n */\nexport function mapCodeFromHttpStatus(status) {\n // The canonical error codes for Google APIs [1] specify mapping onto HTTP\n // status codes but the mapping is not bijective. In each case of ambiguity\n // this function chooses a primary error.\n //\n // [1]\n // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\n switch (status) {\n case 200:// OK\n return Code.OK;\n case 400:// Bad Request\n return Code.INVALID_ARGUMENT;\n // Other possibilities based on the forward mapping\n // return Code.FAILED_PRECONDITION;\n // return Code.OUT_OF_RANGE;\n case 401:// Unauthorized\n return Code.UNAUTHENTICATED;\n case 403:// Forbidden\n return Code.PERMISSION_DENIED;\n case 404:// Not Found\n return Code.NOT_FOUND;\n case 409:// Conflict\n return Code.ABORTED;\n // Other possibilities:\n // return Code.ALREADY_EXISTS;\n case 416:// Range Not Satisfiable\n return Code.OUT_OF_RANGE;\n case 429:// Too Many Requests\n return Code.RESOURCE_EXHAUSTED;\n case 499:// Client Closed Request\n return Code.CANCELLED;\n case 500:// Internal Server Error\n return Code.UNKNOWN;\n // Other possibilities:\n // return Code.INTERNAL;\n // return Code.DATA_LOSS;\n case 501:// Unimplemented\n return Code.UNIMPLEMENTED;\n case 503:// Service Unavailable\n return Code.UNAVAILABLE;\n case 504:// Gateway Timeout\n return Code.DEADLINE_EXCEEDED;\n default:\n if (status >= 200 && status < 300)\n return Code.OK;\n if (status >= 400 && status < 500)\n return Code.FAILED_PRECONDITION;\n if (status >= 500 && status < 600)\n return Code.INTERNAL;\n return Code.UNKNOWN;\n }\n}\n\n//# sourceMappingURL=rpc_error.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/remote/rpc_error.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport { DocumentKey } from './document_key';\nvar EMPTY_MAYBE_DOCUMENT_MAP = new SortedMap(DocumentKey.comparator);\nexport function maybeDocumentMap() {\n return EMPTY_MAYBE_DOCUMENT_MAP;\n}\nvar EMPTY_DOCUMENT_MAP = new SortedMap(DocumentKey.comparator);\nexport function documentMap() {\n return EMPTY_DOCUMENT_MAP;\n}\nvar EMPTY_DOCUMENT_VERSION_MAP = new SortedMap(DocumentKey.comparator);\nexport function documentVersionMap() {\n return EMPTY_DOCUMENT_VERSION_MAP;\n}\nvar EMPTY_DOCUMENT_KEY_SET = new SortedSet(DocumentKey.comparator);\nexport function documentKeySet() {\n return EMPTY_DOCUMENT_KEY_SET;\n}\n\n//# sourceMappingURL=collections.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/model/collections.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { maybeDocumentMap } from '../model/collections';\nimport { emptyByteString } from '../platform/platform';\nimport { assert, fail } from '../util/assert';\nimport * as objUtils from '../util/obj';\nimport { CurrentStatusUpdate, RemoteEvent, ResetMapping, UpdateMapping } from './remote_event';\n/**\n * Represents a changed document and a list of target ids to which this change\n * applies.\n *\n * If document has been deleted NoDocument will be provided.\n */\nvar DocumentWatchChange = /** @class */ (function () {\n function DocumentWatchChange(\n /** The new document applies to all of these targets. */\n updatedTargetIds, \n /** The new document is removed from all of these targets. */\n removedTargetIds, \n /** The key of the document for this change. */\n key, \n /**\n * The new document or NoDocument if it was deleted. Is null if the\n * document went out of view without the server sending a new document.\n */\n newDoc) {\n this.updatedTargetIds = updatedTargetIds;\n this.removedTargetIds = removedTargetIds;\n this.key = key;\n this.newDoc = newDoc;\n }\n return DocumentWatchChange;\n}());\nexport { DocumentWatchChange };\nvar ExistenceFilterChange = /** @class */ (function () {\n function ExistenceFilterChange(targetId, existenceFilter) {\n this.targetId = targetId;\n this.existenceFilter = existenceFilter;\n }\n return ExistenceFilterChange;\n}());\nexport { ExistenceFilterChange };\nexport var WatchTargetChangeState;\n(function (WatchTargetChangeState) {\n WatchTargetChangeState[WatchTargetChangeState[\"NoChange\"] = 0] = \"NoChange\";\n WatchTargetChangeState[WatchTargetChangeState[\"Added\"] = 1] = \"Added\";\n WatchTargetChangeState[WatchTargetChangeState[\"Removed\"] = 2] = \"Removed\";\n WatchTargetChangeState[WatchTargetChangeState[\"Current\"] = 3] = \"Current\";\n WatchTargetChangeState[WatchTargetChangeState[\"Reset\"] = 4] = \"Reset\";\n})(WatchTargetChangeState || (WatchTargetChangeState = {}));\nvar WatchTargetChange = /** @class */ (function () {\n function WatchTargetChange(\n /** What kind of change occurred to the watch target. */\n state, \n /** The target IDs that were added/removed/set. */\n targetIds, \n /**\n * An opaque, server-assigned token that allows watching a query to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the query. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */\n resumeToken, \n /** An RPC error indicating why the watch failed. */\n cause) {\n if (resumeToken === void 0) { resumeToken = emptyByteString(); }\n if (cause === void 0) { cause = null; }\n this.state = state;\n this.targetIds = targetIds;\n this.resumeToken = resumeToken;\n this.cause = cause;\n }\n return WatchTargetChange;\n}());\nexport { WatchTargetChange };\n/**\n * A helper class to accumulate watch changes into a RemoteEvent and other\n * target information.\n */\nvar WatchChangeAggregator = /** @class */ (function () {\n function WatchChangeAggregator(snapshotVersion, listenTargets, pendingTargetResponses) {\n this.snapshotVersion = snapshotVersion;\n this.listenTargets = listenTargets;\n /** The existence filter - if any - for the given target IDs. */\n this.existenceFilters = {};\n /** Keeps track of the current target mappings */\n this.targetChanges = {};\n /** Keeps track of document to update */\n this.documentUpdates = maybeDocumentMap();\n /** Whether this aggregator was frozen and can no longer be modified */\n this.frozen = false;\n this.pendingTargetResponses = objUtils.shallowCopy(pendingTargetResponses);\n }\n /** Aggregates a watch change into the current state */\n WatchChangeAggregator.prototype.add = function (watchChange) {\n assert(!this.frozen, 'Trying to modify frozen WatchChangeAggregator.');\n if (watchChange instanceof DocumentWatchChange) {\n this.addDocumentChange(watchChange);\n }\n else if (watchChange instanceof WatchTargetChange) {\n this.addTargetChange(watchChange);\n }\n else if (watchChange instanceof ExistenceFilterChange) {\n this.addExistenceFilterChange(watchChange);\n }\n else {\n fail('Unknown watch change: ' + watchChange);\n }\n };\n /** Aggregates all provided watch changes to the current state in order */\n WatchChangeAggregator.prototype.addChanges = function (watchChanges) {\n var _this = this;\n assert(!this.frozen, 'Trying to modify frozen WatchChangeAggregator.');\n watchChanges.forEach(function (change) { return _this.add(change); });\n };\n /**\n * Converts the current state into a remote event with the snapshot version\n * provided via the constructor.\n */\n WatchChangeAggregator.prototype.createRemoteEvent = function () {\n var _this = this;\n var targetChanges = this.targetChanges;\n // Remove all the non-active targets from the remote event.\n objUtils.forEachNumber(this.targetChanges, function (targetId) {\n if (!_this.isActiveTarget(targetId)) {\n delete targetChanges[targetId];\n }\n });\n // Mark this aggregator as frozen so no further modifications are made\n this.frozen = true;\n return new RemoteEvent(this.snapshotVersion, targetChanges, this.documentUpdates);\n };\n WatchChangeAggregator.prototype.ensureTargetChange = function (targetId) {\n var change = this.targetChanges[targetId];\n if (!change) {\n // Create an UpdateMapping by default, since resets are always explicit.\n change = {\n currentStatusUpdate: CurrentStatusUpdate.None,\n snapshotVersion: this.snapshotVersion,\n mapping: new UpdateMapping(),\n resumeToken: emptyByteString()\n };\n this.targetChanges[targetId] = change;\n }\n return change;\n };\n /**\n * We need to wait for watch to ack targets before we process those events,\n * so to know if a target is active, there must be no pending acks we're\n * waiting for and it must be in the current list of targets that the client\n * cares about.\n *\n * This method is visible for testing.\n */\n WatchChangeAggregator.prototype.isActiveTarget = function (targetId) {\n return (!objUtils.contains(this.pendingTargetResponses, targetId) &&\n objUtils.contains(this.listenTargets, targetId));\n };\n WatchChangeAggregator.prototype.addDocumentChange = function (docChange) {\n var relevant = false;\n for (var _i = 0, _a = docChange.updatedTargetIds; _i < _a.length; _i++) {\n var targetId = _a[_i];\n if (this.isActiveTarget(targetId)) {\n var change = this.ensureTargetChange(targetId);\n change.mapping.add(docChange.key);\n relevant = true;\n }\n }\n for (var _b = 0, _c = docChange.removedTargetIds; _b < _c.length; _b++) {\n var targetId = _c[_b];\n if (this.isActiveTarget(targetId)) {\n var change = this.ensureTargetChange(targetId);\n change.mapping.delete(docChange.key);\n relevant = true;\n }\n }\n // Only update the document if there is a new document to replace to an\n // active target that is being listened to, this might be just a target\n // update instead.\n if (docChange.newDoc && relevant) {\n this.documentUpdates = this.documentUpdates.insert(docChange.key, docChange.newDoc);\n }\n };\n WatchChangeAggregator.prototype.addTargetChange = function (targetChange) {\n var _this = this;\n targetChange.targetIds.forEach(function (targetId) {\n var change = _this.ensureTargetChange(targetId);\n switch (targetChange.state) {\n case WatchTargetChangeState.NoChange:\n if (_this.isActiveTarget(targetId)) {\n // Creating the change above satisfies the semantics of no-change.\n applyResumeToken(change, targetChange.resumeToken);\n }\n break;\n case WatchTargetChangeState.Added:\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n _this.recordTargetResponse(targetId);\n if (!objUtils.contains(_this.pendingTargetResponses, targetId)) {\n // We have a freshly added target, so we need to reset any state\n // that we had previously This can happen e.g. when remove and add\n // back a target for existence filter mismatches.\n change.mapping = new UpdateMapping();\n change.currentStatusUpdate = CurrentStatusUpdate.None;\n delete _this.existenceFilters[targetId];\n }\n applyResumeToken(change, targetChange.resumeToken);\n break;\n case WatchTargetChangeState.Removed:\n // We need to keep track of removed targets to we can\n // post-filter and remove any target changes.\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n _this.recordTargetResponse(targetId);\n assert(!targetChange.cause, 'WatchChangeAggregator does not handle errored targets');\n break;\n case WatchTargetChangeState.Current:\n if (_this.isActiveTarget(targetId)) {\n change.currentStatusUpdate = CurrentStatusUpdate.MarkCurrent;\n applyResumeToken(change, targetChange.resumeToken);\n }\n break;\n case WatchTargetChangeState.Reset:\n if (_this.isActiveTarget(targetId)) {\n // Overwrite any existing target mapping with a reset\n // mapping. Every subsequent update will modify the reset\n // mapping, not an update mapping.\n change.mapping = new ResetMapping();\n applyResumeToken(change, targetChange.resumeToken);\n }\n break;\n default:\n fail('Unknown target watch change state: ' + targetChange.state);\n }\n });\n };\n /**\n * Record that we get a watch target add/remove by decrementing the number of\n * pending target responses that we have.\n */\n WatchChangeAggregator.prototype.recordTargetResponse = function (targetId) {\n var newCount = (this.pendingTargetResponses[targetId] || 0) - 1;\n if (newCount === 0) {\n delete this.pendingTargetResponses[targetId];\n }\n else {\n this.pendingTargetResponses[targetId] = newCount;\n }\n };\n WatchChangeAggregator.prototype.addExistenceFilterChange = function (change) {\n if (this.isActiveTarget(change.targetId)) {\n this.existenceFilters[change.targetId] = change.existenceFilter;\n }\n };\n return WatchChangeAggregator;\n}());\nexport { WatchChangeAggregator };\n/**\n * Applies the resume token to the TargetChange, but only when it has a new\n * value. null and empty resumeTokens are discarded.\n */\nfunction applyResumeToken(change, resumeToken) {\n if (resumeToken.length > 0) {\n change.resumeToken = resumeToken;\n }\n}\n\n//# sourceMappingURL=watch_change.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/remote/watch_change.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Blob } from '../api/blob';\nimport { GeoPoint } from '../api/geo_point';\nimport { DatabaseId } from '../core/database_info';\nimport { Bound, Direction, NanFilter, NullFilter, OrderBy, Query, RelationFilter, RelationOp } from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Timestamp } from '../core/timestamp';\nimport { QueryPurpose } from '../local/query_data';\nimport { Document, NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport * as fieldValue from '../model/field_value';\nimport { DeleteMutation, FieldMask, FieldTransform, MutationResult, PatchMutation, Precondition, ServerTimestampTransform, SetMutation, TransformMutation } from '../model/mutation';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport { assert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport * as obj from '../util/obj';\nimport * as typeUtils from '../util/types';\nimport { ExistenceFilter } from './existence_filter';\nimport { mapCodeFromRpcCode, mapRpcCodeFromCode } from './rpc_error';\nimport { DocumentWatchChange, ExistenceFilterChange, WatchTargetChange, WatchTargetChangeState } from './watch_change';\nvar DIRECTIONS = (function () {\n var dirs = {};\n dirs[Direction.ASCENDING.name] = 'ASCENDING';\n dirs[Direction.DESCENDING.name] = 'DESCENDING';\n return dirs;\n})();\nvar OPERATORS = (function () {\n var ops = {};\n ops[RelationOp.LESS_THAN.name] = 'LESS_THAN';\n ops[RelationOp.LESS_THAN_OR_EQUAL.name] = 'LESS_THAN_OR_EQUAL';\n ops[RelationOp.GREATER_THAN.name] = 'GREATER_THAN';\n ops[RelationOp.GREATER_THAN_OR_EQUAL.name] = 'GREATER_THAN_OR_EQUAL';\n ops[RelationOp.EQUAL.name] = 'EQUAL';\n return ops;\n})();\nfunction assertPresent(value, description) {\n assert(!typeUtils.isNullOrUndefined(value), description + ' is missing');\n}\nfunction parseInt64(value) {\n // TODO(bjornick): Handle int64 greater than 53 bits.\n if (typeof value === 'number') {\n return value;\n }\n else if (typeof value === 'string') {\n return Number(value);\n }\n else {\n return fail(\"can't parse \" + value);\n }\n}\n/**\n * Generates JsonObject values for the Datastore API suitable for sending to\n * either GRPC stub methods or via the JSON/HTTP REST API.\n * TODO(klimt): We can remove the databaseId argument if we keep the full\n * resource name in documents.\n */\nvar JsonProtoSerializer = /** @class */ (function () {\n function JsonProtoSerializer(databaseId, options) {\n this.databaseId = databaseId;\n this.options = options;\n }\n JsonProtoSerializer.prototype.emptyByteString = function () {\n if (this.options.useProto3Json) {\n return '';\n }\n else {\n return new Uint8Array(0);\n }\n };\n JsonProtoSerializer.prototype.unsafeCastProtoByteString = function (byteString) {\n // byteStrings can be either string or UInt8Array, but the typings say\n // it's always a string. Cast as string to avoid type check failing\n return byteString;\n };\n JsonProtoSerializer.prototype.fromRpcStatus = function (status) {\n var code = status.code === undefined\n ? Code.UNKNOWN\n : mapCodeFromRpcCode(status.code);\n return new FirestoreError(code, status.message || '');\n };\n /**\n * Returns a value for a number (or undefined) that's appropriate to put into\n * a google.protobuf.Int32Value proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"number\" because that's what\n * our generated proto interfaces say Int32Value must be. But GRPC actually\n * expects a { value: } struct.\n */\n JsonProtoSerializer.prototype.toInt32Value = function (val) {\n if (!typeUtils.isNullOrUndefined(val)) {\n // tslint:disable-next-line:no-any We need to match generated Proto types.\n return { value: val };\n }\n else {\n return undefined;\n }\n };\n /**\n * Returns a number (or null) from a google.protobuf.Int32Value proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as accepting \"number\" because that's what\n * our generated proto interfaces say Int32Value must be, but it actually\n * accepts { value: number } to match our serialization in toInt32Value().\n */\n JsonProtoSerializer.prototype.fromInt32Value = function (val) {\n var result;\n if (typeof val === 'object') {\n // tslint:disable-next-line:no-any We need to match generated Proto types.\n result = val.value;\n }\n else {\n // We accept raw numbers (without the {value: ... } wrapper) for\n // compatibility with legacy persisted data.\n result = val;\n }\n return typeUtils.isNullOrUndefined(result) ? null : result;\n };\n /**\n * Returns a value for a Date that's appropriate to put into a proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"string\" because that's what\n * our generated proto interfaces say dates must be. But it's easier and safer\n * to actually return a Timestamp proto.\n */\n JsonProtoSerializer.prototype.toTimestamp = function (timestamp) {\n return {\n seconds: timestamp.seconds,\n nanos: timestamp.nanos\n // tslint:disable-next-line:no-any\n };\n };\n JsonProtoSerializer.prototype.fromTimestamp = function (date) {\n // The json interface (for the browser) will return an iso timestamp string,\n // while the proto js library (for node) will return a\n // google.protobuf.Timestamp instance.\n if (typeof date === 'string') {\n // TODO(b/37282237): Use strings for Proto3 timestamps\n // assert(this.options.useProto3Json,\n // 'The timestamp string format requires Proto3.');\n return Timestamp.fromISOString(date);\n }\n else {\n assert(!!date, 'Cannot deserialize null or undefined timestamp.');\n // TODO(b/37282237): Use strings for Proto3 timestamps\n // assert(!this.options.useProto3Json,\n // 'The timestamp instance format requires Proto JS.');\n var seconds = parseInt64(date.seconds || '0');\n var nanos = date.nanos || 0;\n return new Timestamp(seconds, nanos);\n }\n };\n /**\n * Returns a value for bytes that's appropriate to put in a proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"string\" because that's what\n * our generated proto interfaces say bytes must be. But it should return\n * an Uint8Array in Node.\n */\n JsonProtoSerializer.prototype.toBytes = function (bytes) {\n if (this.options.useProto3Json) {\n return bytes.toBase64();\n }\n else {\n // The typings say it's a string, but it needs to be a Uint8Array in Node.\n return this.unsafeCastProtoByteString(bytes.toUint8Array());\n }\n };\n /**\n * Parse the blob from the protos into the internal Blob class. Note that the\n * typings assume all blobs are strings, but they are actually Uint8Arrays\n * on Node.\n */\n JsonProtoSerializer.prototype.fromBlob = function (blob) {\n if (typeof blob === 'string') {\n assert(this.options.useProto3Json, 'Expected bytes to be passed in as Uint8Array, but got a string instead.');\n return Blob.fromBase64String(blob);\n }\n else {\n assert(!this.options.useProto3Json, 'Expected bytes to be passed in as string, but got something else instead.');\n return Blob.fromUint8Array(blob);\n }\n };\n JsonProtoSerializer.prototype.toVersion = function (version) {\n return this.toTimestamp(version.toTimestamp());\n };\n JsonProtoSerializer.prototype.fromVersion = function (version) {\n assert(!!version, \"Trying to deserialize version that isn't set\");\n return SnapshotVersion.fromTimestamp(this.fromTimestamp(version));\n };\n JsonProtoSerializer.prototype.toResourceName = function (databaseId, path) {\n return this.fullyQualifiedPrefixPath(databaseId)\n .child('documents')\n .child(path)\n .canonicalString();\n };\n JsonProtoSerializer.prototype.fromResourceName = function (name) {\n var resource = ResourcePath.fromString(name);\n assert(this.isValidResourceName(resource), 'Tried to deserialize invalid key ' + resource.toString());\n return resource;\n };\n JsonProtoSerializer.prototype.toName = function (key) {\n return this.toResourceName(this.databaseId, key.path);\n };\n JsonProtoSerializer.prototype.fromName = function (name) {\n var resource = this.fromResourceName(name);\n assert(resource.get(1) === this.databaseId.projectId, 'Tried to deserialize key from different project: ' +\n resource.get(1) +\n ' vs ' +\n this.databaseId.projectId);\n assert((!resource.get(3) && !this.databaseId.database) ||\n resource.get(3) === this.databaseId.database, 'Tried to deserialize key from different database: ' +\n resource.get(3) +\n ' vs ' +\n this.databaseId.database);\n return new DocumentKey(this.extractLocalPathFromResourceName(resource));\n };\n JsonProtoSerializer.prototype.toQueryPath = function (path) {\n if (path.length === 0) {\n // If the path is empty, the backend requires we leave off the /documents\n // at the end.\n return this.encodedDatabaseId;\n }\n return this.toResourceName(this.databaseId, path);\n };\n JsonProtoSerializer.prototype.fromQueryPath = function (name) {\n var resourceName = this.fromResourceName(name);\n if (resourceName.length === 4) {\n return ResourcePath.EMPTY_PATH;\n }\n return this.extractLocalPathFromResourceName(resourceName);\n };\n Object.defineProperty(JsonProtoSerializer.prototype, \"encodedDatabaseId\", {\n get: function () {\n var path = new ResourcePath([\n 'projects',\n this.databaseId.projectId,\n 'databases',\n this.databaseId.database\n ]);\n return path.canonicalString();\n },\n enumerable: true,\n configurable: true\n });\n JsonProtoSerializer.prototype.fullyQualifiedPrefixPath = function (databaseId) {\n return new ResourcePath([\n 'projects',\n databaseId.projectId,\n 'databases',\n databaseId.database\n ]);\n };\n JsonProtoSerializer.prototype.extractLocalPathFromResourceName = function (resourceName) {\n assert(resourceName.length > 4 && resourceName.get(4) === 'documents', 'tried to deserialize invalid key ' + resourceName.toString());\n return resourceName.popFirst(5);\n };\n JsonProtoSerializer.prototype.isValidResourceName = function (path) {\n // Resource names have at least 4 components (project ID, database ID)\n return (path.length >= 4 &&\n path.get(0) === 'projects' &&\n path.get(2) === 'databases');\n };\n JsonProtoSerializer.prototype.toValue = function (val) {\n if (val instanceof fieldValue.NullValue) {\n return { nullValue: 'NULL_VALUE' };\n }\n else if (val instanceof fieldValue.BooleanValue) {\n return { booleanValue: val.value() };\n }\n else if (val instanceof fieldValue.IntegerValue) {\n return { integerValue: '' + val.value() };\n }\n else if (val instanceof fieldValue.DoubleValue) {\n var doubleValue = val.value();\n if (this.options.useProto3Json) {\n // Proto 3 let's us encode NaN and Infinity as string values as\n // expected by the backend. This is currently not checked by our unit\n // tests because they rely on protobuf.js.\n if (isNaN(doubleValue)) {\n return { doubleValue: 'NaN' };\n }\n else if (doubleValue === Infinity) {\n return { doubleValue: 'Infinity' };\n }\n else if (doubleValue === -Infinity) {\n return { doubleValue: '-Infinity' };\n }\n }\n return { doubleValue: val.value() };\n }\n else if (val instanceof fieldValue.StringValue) {\n return { stringValue: val.value() };\n }\n else if (val instanceof fieldValue.ObjectValue) {\n return { mapValue: this.toMapValue(val) };\n }\n else if (val instanceof fieldValue.ArrayValue) {\n return { arrayValue: this.toArrayValue(val) };\n }\n else if (val instanceof fieldValue.TimestampValue) {\n return {\n timestampValue: this.toTimestamp(val.internalValue)\n };\n }\n else if (val instanceof fieldValue.GeoPointValue) {\n return {\n geoPointValue: {\n latitude: val.value().latitude,\n longitude: val.value().longitude\n }\n };\n }\n else if (val instanceof fieldValue.BlobValue) {\n return {\n bytesValue: this.toBytes(val.value())\n };\n }\n else if (val instanceof fieldValue.RefValue) {\n return {\n referenceValue: this.toResourceName(val.databaseId, val.key.path)\n };\n }\n else {\n return fail('Unknown FieldValue ' + JSON.stringify(val));\n }\n };\n JsonProtoSerializer.prototype.fromValue = function (obj) {\n var _this = this;\n // tslint:disable-next-line:no-any\n var type = obj['value_type'];\n if (hasTag(obj, type, 'nullValue')) {\n return fieldValue.NullValue.INSTANCE;\n }\n else if (hasTag(obj, type, 'booleanValue')) {\n return fieldValue.BooleanValue.of(obj.booleanValue);\n }\n else if (hasTag(obj, type, 'integerValue')) {\n return new fieldValue.IntegerValue(parseInt64(obj.integerValue));\n }\n else if (hasTag(obj, type, 'doubleValue')) {\n if (this.options.useProto3Json) {\n // Proto 3 uses the string values 'NaN' and 'Infinity'.\n if (obj.doubleValue === 'NaN') {\n return fieldValue.DoubleValue.NAN;\n }\n else if (obj.doubleValue === 'Infinity') {\n return fieldValue.DoubleValue.POSITIVE_INFINITY;\n }\n else if (obj.doubleValue === '-Infinity') {\n return fieldValue.DoubleValue.NEGATIVE_INFINITY;\n }\n }\n return new fieldValue.DoubleValue(obj.doubleValue);\n }\n else if (hasTag(obj, type, 'stringValue')) {\n return new fieldValue.StringValue(obj.stringValue);\n }\n else if (hasTag(obj, type, 'mapValue')) {\n return this.fromFields(obj.mapValue.fields || {});\n }\n else if (hasTag(obj, type, 'arrayValue')) {\n // \"values\" is not present if the array is empty\n assertPresent(obj.arrayValue, 'arrayValue');\n var values = obj.arrayValue.values || [];\n return new fieldValue.ArrayValue(values.map(function (v) { return _this.fromValue(v); }));\n }\n else if (hasTag(obj, type, 'timestampValue')) {\n assertPresent(obj.timestampValue, 'timestampValue');\n return new fieldValue.TimestampValue(this.fromTimestamp(obj.timestampValue));\n }\n else if (hasTag(obj, type, 'geoPointValue')) {\n assertPresent(obj.geoPointValue, 'geoPointValue');\n var latitude = obj.geoPointValue.latitude || 0;\n var longitude = obj.geoPointValue.longitude || 0;\n return new fieldValue.GeoPointValue(new GeoPoint(latitude, longitude));\n }\n else if (hasTag(obj, type, 'bytesValue')) {\n assertPresent(obj.bytesValue, 'bytesValue');\n var blob = this.fromBlob(obj.bytesValue);\n return new fieldValue.BlobValue(blob);\n }\n else if (hasTag(obj, type, 'referenceValue')) {\n assertPresent(obj.referenceValue, 'referenceValue');\n var resourceName = this.fromResourceName(obj.referenceValue);\n var dbId = new DatabaseId(resourceName.get(1), resourceName.get(3));\n var key = new DocumentKey(this.extractLocalPathFromResourceName(resourceName));\n return new fieldValue.RefValue(dbId, key);\n }\n else {\n return fail('Unknown Value proto ' + JSON.stringify(obj));\n }\n };\n /** Creates an api.Document from key and fields (but no create/update time) */\n JsonProtoSerializer.prototype.toMutationDocument = function (key, fields) {\n return {\n name: this.toName(key),\n fields: this.toFields(fields)\n };\n };\n JsonProtoSerializer.prototype.toDocument = function (document) {\n assert(!document.hasLocalMutations, \"Can't serialize documents with mutations.\");\n return {\n name: this.toName(document.key),\n fields: this.toFields(document.data),\n updateTime: this.toTimestamp(document.version.toTimestamp())\n };\n };\n JsonProtoSerializer.prototype.fromDocument = function (document) {\n return new Document(this.fromName(document.name), this.fromVersion(document.updateTime), this.fromFields(document.fields || {}), { hasLocalMutations: false });\n };\n JsonProtoSerializer.prototype.toFields = function (fields) {\n var _this = this;\n var result = {};\n fields.forEach(function (key, value) {\n result[key] = _this.toValue(value);\n });\n return result;\n };\n JsonProtoSerializer.prototype.fromFields = function (object) {\n var _this = this;\n // Proto map gets mapped to Object, so cast it.\n var map = object;\n var result = fieldValue.ObjectValue.EMPTY;\n obj.forEach(map, function (key, value) {\n result = result.set(new FieldPath([key]), _this.fromValue(value));\n });\n return result;\n };\n JsonProtoSerializer.prototype.toMapValue = function (map) {\n return {\n fields: this.toFields(map)\n };\n };\n JsonProtoSerializer.prototype.toArrayValue = function (array) {\n var _this = this;\n var result = [];\n array.forEach(function (value) {\n result.push(_this.toValue(value));\n });\n return { values: result };\n };\n JsonProtoSerializer.prototype.fromFound = function (doc) {\n assert(!!doc.found, 'Tried to deserialize a found document from a missing document.');\n assertPresent(doc.found.name, 'doc.found.name');\n assertPresent(doc.found.updateTime, 'doc.found.updateTime');\n var key = this.fromName(doc.found.name);\n var version = this.fromVersion(doc.found.updateTime);\n var fields = this.fromFields(doc.found.fields || {});\n return new Document(key, version, fields, { hasLocalMutations: false });\n };\n JsonProtoSerializer.prototype.fromMissing = function (result) {\n assert(!!result.missing, 'Tried to deserialize a missing document from a found document.');\n assert(!!result.readTime, 'Tried to deserialize a missing document without a read time.');\n var key = this.fromName(result.missing);\n var version = this.fromVersion(result.readTime);\n return new NoDocument(key, version);\n };\n JsonProtoSerializer.prototype.fromMaybeDocument = function (result) {\n // tslint:disable-next-line:no-any\n var type = result['result'];\n if (hasTag(result, type, 'found')) {\n return this.fromFound(result);\n }\n else if (hasTag(result, type, 'missing')) {\n return this.fromMissing(result);\n }\n return fail('invalid batch get response: ' + JSON.stringify(result));\n };\n JsonProtoSerializer.prototype.toWatchTargetChangeState = function (state) {\n switch (state) {\n case WatchTargetChangeState.Added:\n return 'ADD';\n case WatchTargetChangeState.Current:\n return 'CURRENT';\n case WatchTargetChangeState.NoChange:\n return 'NO_CHANGE';\n case WatchTargetChangeState.Removed:\n return 'REMOVE';\n case WatchTargetChangeState.Reset:\n return 'RESET';\n default:\n return fail('Unknown WatchTargetChangeState: ' + state);\n }\n };\n JsonProtoSerializer.prototype.toTestWatchChange = function (watchChange) {\n if (watchChange instanceof ExistenceFilterChange) {\n return {\n filter: {\n count: watchChange.existenceFilter.count,\n targetId: watchChange.targetId\n }\n };\n }\n if (watchChange instanceof DocumentWatchChange) {\n if (watchChange.newDoc instanceof Document) {\n var doc = watchChange.newDoc;\n return {\n documentChange: {\n document: {\n name: this.toName(doc.key),\n fields: this.toFields(doc.data),\n updateTime: this.toVersion(doc.version)\n },\n targetIds: watchChange.updatedTargetIds,\n removedTargetIds: watchChange.removedTargetIds\n }\n };\n }\n else if (watchChange.newDoc instanceof NoDocument) {\n var doc = watchChange.newDoc;\n return {\n documentDelete: {\n document: this.toName(doc.key),\n readTime: this.toVersion(doc.version),\n removedTargetIds: watchChange.removedTargetIds\n }\n };\n }\n else if (watchChange.newDoc === null) {\n return {\n documentRemove: {\n document: this.toName(watchChange.key),\n removedTargetIds: watchChange.removedTargetIds\n }\n };\n }\n }\n if (watchChange instanceof WatchTargetChange) {\n var cause = undefined;\n if (watchChange.cause) {\n cause = {\n code: mapRpcCodeFromCode(watchChange.cause.code),\n message: watchChange.cause.message\n };\n }\n return {\n targetChange: {\n targetChangeType: this.toWatchTargetChangeState(watchChange.state),\n targetIds: watchChange.targetIds,\n resumeToken: this.unsafeCastProtoByteString(watchChange.resumeToken),\n cause: cause\n }\n };\n }\n return fail('Unrecognized watch change: ' + JSON.stringify(watchChange));\n };\n JsonProtoSerializer.prototype.fromWatchChange = function (change) {\n // tslint:disable-next-line:no-any\n var type = change['response_type'];\n var watchChange;\n if (hasTag(change, type, 'targetChange')) {\n assertPresent(change.targetChange, 'targetChange');\n // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'\n // if unset\n var state = this.fromWatchTargetChangeState(change.targetChange.targetChangeType || 'NO_CHANGE');\n var targetIds = change.targetChange.targetIds || [];\n var resumeToken = change.targetChange.resumeToken || this.emptyByteString();\n var causeProto = change.targetChange.cause;\n var cause = causeProto && this.fromRpcStatus(causeProto);\n watchChange = new WatchTargetChange(state, targetIds, resumeToken, cause || null);\n }\n else if (hasTag(change, type, 'documentChange')) {\n assertPresent(change.documentChange, 'documentChange');\n assertPresent(change.documentChange.document, 'documentChange.name');\n assertPresent(change.documentChange.document.name, 'documentChange.document.name');\n assertPresent(change.documentChange.document.updateTime, 'documentChange.document.updateTime');\n var entityChange = change.documentChange;\n var key = this.fromName(entityChange.document.name);\n var version = this.fromVersion(entityChange.document.updateTime);\n var fields = this.fromFields(entityChange.document.fields || {});\n var doc = new Document(key, version, fields, {\n hasLocalMutations: false\n });\n var updatedTargetIds = entityChange.targetIds || [];\n var removedTargetIds = entityChange.removedTargetIds || [];\n watchChange = new DocumentWatchChange(updatedTargetIds, removedTargetIds, doc.key, doc);\n }\n else if (hasTag(change, type, 'documentDelete')) {\n assertPresent(change.documentDelete, 'documentDelete');\n assertPresent(change.documentDelete.document, 'documentDelete.document');\n var docDelete = change.documentDelete;\n var key = this.fromName(docDelete.document);\n var version = docDelete.readTime\n ? this.fromVersion(docDelete.readTime)\n : SnapshotVersion.forDeletedDoc();\n var doc = new NoDocument(key, version);\n var removedTargetIds = docDelete.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, doc.key, doc);\n }\n else if (hasTag(change, type, 'documentRemove')) {\n assertPresent(change.documentRemove, 'documentRemove');\n assertPresent(change.documentRemove.document, 'documentRemove');\n var docRemove = change.documentRemove;\n var key = this.fromName(docRemove.document);\n var removedTargetIds = docRemove.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, key, null);\n }\n else if (hasTag(change, type, 'filter')) {\n // TODO(dimond): implement existence filter parsing with strategy.\n assertPresent(change.filter, 'filter');\n assertPresent(change.filter.targetId, 'filter.targetId');\n var filter = change.filter;\n var count = filter.count || 0;\n var existenceFilter = new ExistenceFilter(count);\n var targetId = filter.targetId;\n watchChange = new ExistenceFilterChange(targetId, existenceFilter);\n }\n else {\n return fail('Unknown change type ' + JSON.stringify(change));\n }\n return watchChange;\n };\n JsonProtoSerializer.prototype.fromWatchTargetChangeState = function (state) {\n if (state === 'NO_CHANGE') {\n return WatchTargetChangeState.NoChange;\n }\n else if (state === 'ADD') {\n return WatchTargetChangeState.Added;\n }\n else if (state === 'REMOVE') {\n return WatchTargetChangeState.Removed;\n }\n else if (state === 'CURRENT') {\n return WatchTargetChangeState.Current;\n }\n else if (state === 'RESET') {\n return WatchTargetChangeState.Reset;\n }\n else {\n return fail('Got unexpected TargetChange.state: ' + state);\n }\n };\n JsonProtoSerializer.prototype.versionFromListenResponse = function (change) {\n // We have only reached a consistent snapshot for the entire stream if there\n // is a read_time set and it applies to all targets (i.e. the list of\n // targets is empty). The backend is guaranteed to send such responses.\n // tslint:disable-next-line:no-any\n var type = change['response_type'];\n if (!hasTag(change, type, 'targetChange')) {\n return SnapshotVersion.MIN;\n }\n var targetChange = change.targetChange;\n if (targetChange.targetIds && targetChange.targetIds.length) {\n return SnapshotVersion.MIN;\n }\n if (!targetChange.readTime) {\n return SnapshotVersion.MIN;\n }\n return this.fromVersion(targetChange.readTime);\n };\n JsonProtoSerializer.prototype.toMutation = function (mutation) {\n var _this = this;\n var result;\n if (mutation instanceof SetMutation) {\n result = {\n update: this.toMutationDocument(mutation.key, mutation.value)\n };\n }\n else if (mutation instanceof DeleteMutation) {\n result = { delete: this.toName(mutation.key) };\n }\n else if (mutation instanceof PatchMutation) {\n result = {\n update: this.toMutationDocument(mutation.key, mutation.data),\n updateMask: this.toDocumentMask(mutation.fieldMask)\n };\n }\n else if (mutation instanceof TransformMutation) {\n result = {\n transform: {\n document: this.toName(mutation.key),\n fieldTransforms: mutation.fieldTransforms.map(function (transform) {\n return _this.toFieldTransform(transform);\n })\n }\n };\n }\n else {\n return fail('Unknown mutation type ' + mutation.type);\n }\n if (!mutation.precondition.isNone) {\n result.currentDocument = this.toPrecondition(mutation.precondition);\n }\n return result;\n };\n JsonProtoSerializer.prototype.fromMutation = function (proto) {\n var _this = this;\n var precondition = proto.currentDocument\n ? this.fromPrecondition(proto.currentDocument)\n : Precondition.NONE;\n if (proto.update) {\n assertPresent(proto.update.name, 'name');\n var key = this.fromName(proto.update.name);\n var value = this.fromFields(proto.update.fields || {});\n if (proto.updateMask) {\n var fieldMask = this.fromDocumentMask(proto.updateMask);\n return new PatchMutation(key, value, fieldMask, precondition);\n }\n else {\n return new SetMutation(key, value, precondition);\n }\n }\n else if (proto.delete) {\n var key = this.fromName(proto.delete);\n return new DeleteMutation(key, precondition);\n }\n else if (proto.transform) {\n var key = this.fromName(proto.transform.document);\n var fieldTransforms = proto.transform.fieldTransforms.map(function (transform) {\n return _this.fromFieldTransform(transform);\n });\n assert(precondition.exists === true, 'Transforms only support precondition \"exists == true\"');\n return new TransformMutation(key, fieldTransforms);\n }\n else {\n return fail('unknown mutation proto: ' + JSON.stringify(proto));\n }\n };\n JsonProtoSerializer.prototype.toPrecondition = function (precondition) {\n assert(!precondition.isNone, \"Can't serialize an empty precondition\");\n if (precondition.updateTime !== undefined) {\n return {\n updateTime: this.toVersion(precondition.updateTime)\n };\n }\n else if (precondition.exists !== undefined) {\n return { exists: precondition.exists };\n }\n else {\n return fail('Unknown precondition');\n }\n };\n JsonProtoSerializer.prototype.fromPrecondition = function (precondition) {\n if (precondition.updateTime !== undefined) {\n return Precondition.updateTime(this.fromVersion(precondition.updateTime));\n }\n else if (precondition.exists !== undefined) {\n return Precondition.exists(precondition.exists);\n }\n else {\n return Precondition.NONE;\n }\n };\n JsonProtoSerializer.prototype.fromWriteResult = function (proto) {\n var _this = this;\n // NOTE: Deletes don't have an updateTime.\n var version = proto.updateTime\n ? this.fromVersion(proto.updateTime)\n : null;\n var transformResults = null;\n if (proto.transformResults && proto.transformResults.length > 0) {\n transformResults = proto.transformResults.map(function (result) {\n return _this.fromValue(result);\n });\n }\n return new MutationResult(version, transformResults);\n };\n JsonProtoSerializer.prototype.fromWriteResults = function (protos) {\n var _this = this;\n return (protos || []).map(function (proto) { return _this.fromWriteResult(proto); });\n };\n JsonProtoSerializer.prototype.toFieldTransform = function (fieldTransform) {\n assert(fieldTransform.transform instanceof ServerTimestampTransform, 'Unknown transform: ' + fieldTransform.transform);\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n setToServerValue: 'REQUEST_TIME'\n };\n };\n JsonProtoSerializer.prototype.fromFieldTransform = function (proto) {\n assert(proto.setToServerValue === 'REQUEST_TIME', 'Unknown transform proto: ' + JSON.stringify(proto));\n var fieldPath = FieldPath.fromServerFormat(proto.fieldPath);\n return new FieldTransform(fieldPath, ServerTimestampTransform.instance);\n };\n JsonProtoSerializer.prototype.toDocumentsTarget = function (query) {\n return { documents: [this.toQueryPath(query.path)] };\n };\n JsonProtoSerializer.prototype.fromDocumentsTarget = function (documentsTarget) {\n var count = documentsTarget.documents.length;\n assert(count === 1, 'DocumentsTarget contained other than 1 document: ' + count);\n var name = documentsTarget.documents[0];\n return Query.atPath(this.fromQueryPath(name));\n };\n JsonProtoSerializer.prototype.toQueryTarget = function (query) {\n // Dissect the path into parent, collectionId, and optional key filter.\n var result = { structuredQuery: {} };\n if (query.path.isEmpty()) {\n result.parent = this.toQueryPath(ResourcePath.EMPTY_PATH);\n }\n else {\n var path = query.path;\n assert(path.length % 2 !== 0, 'Document queries with filters are not supported.');\n result.parent = this.toQueryPath(path.popLast());\n result.structuredQuery.from = [{ collectionId: path.lastSegment() }];\n }\n var where = this.toFilter(query.filters);\n if (where) {\n result.structuredQuery.where = where;\n }\n var orderBy = this.toOrder(query.orderBy);\n if (orderBy) {\n result.structuredQuery.orderBy = orderBy;\n }\n var limit = this.toInt32Value(query.limit);\n if (limit !== undefined) {\n result.structuredQuery.limit = limit;\n }\n if (query.startAt) {\n result.structuredQuery.startAt = this.toCursor(query.startAt);\n }\n if (query.endAt) {\n result.structuredQuery.endAt = this.toCursor(query.endAt);\n }\n return result;\n };\n JsonProtoSerializer.prototype.fromQueryTarget = function (target) {\n var path = this.fromQueryPath(target.parent);\n var query = target.structuredQuery;\n var fromCount = query.from ? query.from.length : 0;\n if (fromCount > 0) {\n assert(fromCount === 1, 'StructuredQuery.from with more than one collection is not supported.');\n var from = query.from[0];\n path = path.child(from.collectionId);\n }\n var filterBy = [];\n if (query.where) {\n filterBy = this.fromFilter(query.where);\n }\n var orderBy = [];\n if (query.orderBy) {\n orderBy = this.fromOrder(query.orderBy);\n }\n var limit = null;\n if (query.limit) {\n limit = this.fromInt32Value(query.limit);\n }\n var startAt = null;\n if (query.startAt) {\n startAt = this.fromCursor(query.startAt);\n }\n var endAt = null;\n if (query.endAt) {\n endAt = this.fromCursor(query.endAt);\n }\n return new Query(path, orderBy, filterBy, limit, startAt, endAt);\n };\n JsonProtoSerializer.prototype.toListenRequestLabels = function (queryData) {\n var value = this.toLabel(queryData.purpose);\n if (value == null) {\n return null;\n }\n else {\n return {\n 'goog-listen-tags': value\n };\n }\n };\n JsonProtoSerializer.prototype.toLabel = function (purpose) {\n switch (purpose) {\n case QueryPurpose.Listen:\n return null;\n case QueryPurpose.ExistenceFilterMismatch:\n return 'existence-filter-mismatch';\n case QueryPurpose.LimboResolution:\n return 'limbo-document';\n default:\n return fail('Unrecognized query purpose: ' + purpose);\n }\n };\n JsonProtoSerializer.prototype.toTarget = function (queryData) {\n var result;\n var query = queryData.query;\n if (query.isDocumentQuery()) {\n result = { documents: this.toDocumentsTarget(query) };\n }\n else {\n result = { query: this.toQueryTarget(query) };\n }\n result.targetId = queryData.targetId;\n if (queryData.resumeToken.length > 0) {\n result.resumeToken = this.unsafeCastProtoByteString(queryData.resumeToken);\n }\n return result;\n };\n JsonProtoSerializer.prototype.toFilter = function (filters) {\n var _this = this;\n if (filters.length === 0)\n return;\n var protos = filters.map(function (filter) {\n return filter instanceof RelationFilter\n ? _this.toRelationFilter(filter)\n : _this.toUnaryFilter(filter);\n });\n if (protos.length === 1) {\n return protos[0];\n }\n return { compositeFilter: { op: 'AND', filters: protos } };\n };\n JsonProtoSerializer.prototype.fromFilter = function (filter) {\n var _this = this;\n if (!filter) {\n return [];\n }\n else if (filter.unaryFilter !== undefined) {\n return [this.fromUnaryFilter(filter)];\n }\n else if (filter.fieldFilter !== undefined) {\n return [this.fromRelationFilter(filter)];\n }\n else if (filter.compositeFilter !== undefined) {\n return filter.compositeFilter.filters\n .map(function (f) { return _this.fromFilter(f); })\n .reduce(function (accum, current) { return accum.concat(current); });\n }\n else {\n return fail('Unknown filter: ' + JSON.stringify(filter));\n }\n };\n JsonProtoSerializer.prototype.toOrder = function (orderBys) {\n var _this = this;\n if (orderBys.length === 0)\n return;\n return orderBys.map(function (order) { return _this.toPropertyOrder(order); });\n };\n JsonProtoSerializer.prototype.fromOrder = function (orderBys) {\n var _this = this;\n return orderBys.map(function (order) { return _this.fromPropertyOrder(order); });\n };\n JsonProtoSerializer.prototype.toCursor = function (cursor) {\n var _this = this;\n return {\n before: cursor.before,\n values: cursor.position.map(function (component) { return _this.toValue(component); })\n };\n };\n JsonProtoSerializer.prototype.fromCursor = function (cursor) {\n var _this = this;\n var before = !!cursor.before;\n var position = cursor.values.map(function (component) { return _this.fromValue(component); });\n return new Bound(position, before);\n };\n // visible for testing\n JsonProtoSerializer.prototype.toDirection = function (dir) {\n return DIRECTIONS[dir.name];\n };\n // visible for testing\n JsonProtoSerializer.prototype.fromDirection = function (dir) {\n switch (dir) {\n case 'ASCENDING':\n return Direction.ASCENDING;\n case 'DESCENDING':\n return Direction.DESCENDING;\n default:\n return undefined;\n }\n };\n // visible for testing\n JsonProtoSerializer.prototype.toOperatorName = function (op) {\n return OPERATORS[op.name];\n };\n JsonProtoSerializer.prototype.fromOperatorName = function (op) {\n switch (op) {\n case 'EQUAL':\n return RelationOp.EQUAL;\n case 'GREATER_THAN':\n return RelationOp.GREATER_THAN;\n case 'GREATER_THAN_OR_EQUAL':\n return RelationOp.GREATER_THAN_OR_EQUAL;\n case 'LESS_THAN':\n return RelationOp.LESS_THAN;\n case 'LESS_THAN_OR_EQUAL':\n return RelationOp.LESS_THAN_OR_EQUAL;\n case 'OPERATOR_UNSPECIFIED':\n return fail('Unspecified relation');\n default:\n return fail('Unknown relation');\n }\n };\n JsonProtoSerializer.prototype.toFieldPathReference = function (path) {\n return { fieldPath: path.canonicalString() };\n };\n JsonProtoSerializer.prototype.fromFieldPathReference = function (fieldReference) {\n return FieldPath.fromServerFormat(fieldReference.fieldPath);\n };\n // visible for testing\n JsonProtoSerializer.prototype.toPropertyOrder = function (orderBy) {\n return {\n field: this.toFieldPathReference(orderBy.field),\n direction: this.toDirection(orderBy.dir)\n };\n };\n JsonProtoSerializer.prototype.fromPropertyOrder = function (orderBy) {\n return new OrderBy(this.fromFieldPathReference(orderBy.field), this.fromDirection(orderBy.direction));\n };\n // visible for testing\n JsonProtoSerializer.prototype.toRelationFilter = function (filter) {\n if (filter instanceof RelationFilter) {\n return {\n fieldFilter: {\n field: this.toFieldPathReference(filter.field),\n op: this.toOperatorName(filter.op),\n value: this.toValue(filter.value)\n }\n };\n }\n else {\n return fail('Unrecognized filter: ' + JSON.stringify(filter));\n }\n };\n JsonProtoSerializer.prototype.fromRelationFilter = function (filter) {\n return new RelationFilter(this.fromFieldPathReference(filter.fieldFilter.field), this.fromOperatorName(filter.fieldFilter.op), this.fromValue(filter.fieldFilter.value));\n };\n // visible for testing\n JsonProtoSerializer.prototype.toUnaryFilter = function (filter) {\n if (filter instanceof NanFilter) {\n return {\n unaryFilter: {\n field: this.toFieldPathReference(filter.field),\n op: 'IS_NAN'\n }\n };\n }\n else if (filter instanceof NullFilter) {\n return {\n unaryFilter: {\n field: this.toFieldPathReference(filter.field),\n op: 'IS_NULL'\n }\n };\n }\n else {\n return fail('Unrecognized filter: ' + JSON.stringify(filter));\n }\n };\n JsonProtoSerializer.prototype.fromUnaryFilter = function (filter) {\n switch (filter.unaryFilter.op) {\n case 'IS_NAN':\n var nanField = this.fromFieldPathReference(filter.unaryFilter.field);\n return new NanFilter(nanField);\n case 'IS_NULL':\n var nullField = this.fromFieldPathReference(filter.unaryFilter.field);\n return new NullFilter(nullField);\n case 'OPERATOR_UNSPECIFIED':\n return fail('Unspecified filter');\n default:\n return fail('Unknown filter');\n }\n };\n JsonProtoSerializer.prototype.toDocumentMask = function (fieldMask) {\n return {\n fieldPaths: fieldMask.fields.map(function (field) { return field.canonicalString(); })\n };\n };\n JsonProtoSerializer.prototype.fromDocumentMask = function (proto) {\n var paths = proto.fieldPaths || [];\n var fields = paths.map(function (path) { return FieldPath.fromServerFormat(path); });\n return new FieldMask(fields);\n };\n return JsonProtoSerializer;\n}());\nexport { JsonProtoSerializer };\n/**\n * Checks for a specific oneof tag in a protocol buffer message.\n *\n * This intentionally accommodates two distinct cases:\n *\n * 1) Messages containing a type tag: these are the format produced by GRPC in\n * return values. These may contain default-value mappings for all tags in the\n * oneof but the type tag specifies which one was actually set.\n *\n * 2) Messages that don't contain a type tag: these are the format required by\n * GRPC as inputs. If we emitted objects with type tags, ProtoBuf.js would\n * choke claiming that the tags aren't fields in the Message.\n *\n * Allowing both formats here makes the serializer able to consume the outputs\n * it produces: for all messages it supports, fromX(toX(value)) == value.\n *\n * Note that case 2 suffers from ambiguity: if multiple tags are present\n * without a type tag then the callers are structured in such a way that the\n * first invocation will win. Since we only parse in this mode when parsing\n * the output of a serialize method this works, but it's not a general\n * solution.\n *\n * Unfortunately there is no general solution here because proto3 makes it\n * impossible to distinguish unset from explicitly set fields: both have the\n * default value for the type. Without the type tag but multiple value tags\n * it's possible to have default values for each tag in the oneof and not be\n * able to know which was actually in effect.\n */\nfunction hasTag(obj, type, tag) {\n return type === tag || (!type && tag in obj);\n}\n\n//# sourceMappingURL=serializer.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/remote/serializer.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { Code, FirestoreError } from '../util/error';\nimport { invalidClassError, validateArgType, validateNamedArrayAtLeastNumberOfElements } from '../util/input_validation';\n// The objects that are a part of this API are exposed to third-parties as\n// compiled javascript so we want to flag our private members with a leading\n// underscore to discourage their use.\n// tslint:disable:strip-private-property-underscore\n/**\n * A FieldPath refers to a field in a document. The path may consist of a single\n * field name (referring to a top-level field in the document), or a list of\n * field names (referring to a nested field in the document).\n */\nvar FieldPath = /** @class */ (function () {\n /**\n * Creates a FieldPath from the provided field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n *\n * @param fieldNames A list of field names.\n */\n function FieldPath() {\n var fieldNames = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n fieldNames[_i] = arguments[_i];\n }\n validateNamedArrayAtLeastNumberOfElements('FieldPath', fieldNames, 'fieldNames', 1);\n for (var i = 0; i < fieldNames.length; ++i) {\n validateArgType('FieldPath', 'string', i, fieldNames[i]);\n if (fieldNames[i].length === 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field name at argument $(i + 1). \" +\n 'Field names must not be empty.');\n }\n }\n this._internalPath = new InternalFieldPath(fieldNames);\n }\n FieldPath.documentId = function () {\n return FieldPath._DOCUMENT_ID;\n };\n FieldPath.prototype.isEqual = function (other) {\n if (!(other instanceof FieldPath)) {\n throw invalidClassError('isEqual', 'FieldPath', 1, other);\n }\n return this._internalPath.isEqual(other._internalPath);\n };\n /**\n * Internal Note: The backend doesn't technically support querying by\n * document ID. Instead it queries by the entire document name (full path\n * included), but in the cases we currently support documentId(), the net\n * effect is the same.\n */\n FieldPath._DOCUMENT_ID = new FieldPath(InternalFieldPath.keyField().canonicalString());\n return FieldPath;\n}());\nexport { FieldPath };\n/**\n * Matches any characters in a field path string that are reserved.\n */\nvar RESERVED = new RegExp('[~\\\\*/\\\\[\\\\]]');\n/**\n * Parses a field path string into a FieldPath, treating dots as separators.\n */\nexport function fromDotSeparatedString(path) {\n var found = path.search(RESERVED);\n if (found >= 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field path (\" + path + \"). Paths must not contain \" +\n \"'~', '*', '/', '[', or ']'\");\n }\n try {\n return new (FieldPath.bind.apply(FieldPath, [void 0].concat(path.split('.'))))();\n }\n catch (e) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field path (\" + path + \"). Paths must not be empty, \" +\n \"begin with '.', end with '.', or contain '..'\");\n }\n}\n\n//# sourceMappingURL=field_path.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/api/field_path.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { documentKeySet } from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentSet } from '../model/document_set';\nimport { CurrentStatusUpdate, ResetMapping, UpdateMapping } from '../remote/remote_event';\nimport { assert, fail } from '../util/assert';\nimport { OnlineState } from './types';\nimport { ChangeType, DocumentChangeSet, SyncState, ViewSnapshot } from './view_snapshot';\nvar AddedLimboDocument = /** @class */ (function () {\n function AddedLimboDocument(key) {\n this.key = key;\n }\n return AddedLimboDocument;\n}());\nexport { AddedLimboDocument };\nvar RemovedLimboDocument = /** @class */ (function () {\n function RemovedLimboDocument(key) {\n this.key = key;\n }\n return RemovedLimboDocument;\n}());\nexport { RemovedLimboDocument };\n/**\n * View is responsible for computing the final merged truth of what docs are in\n * a query. It gets notified of local and remote changes to docs, and applies\n * the query filters and limits to determine the most correct possible results.\n */\nvar View = /** @class */ (function () {\n function View(query, \n /** Documents included in the remote target */\n syncedDocuments) {\n this.query = query;\n this.syncedDocuments = syncedDocuments;\n this.syncState = null;\n /**\n * A flag whether the view is current with the backend. A view is considered\n * current after it has seen the current flag from the backend and did not\n * lose consistency within the watch stream (e.g. because of an existence\n * filter mismatch).\n */\n this.current = false;\n /** Documents in the view but not in the remote target */\n this.limboDocuments = documentKeySet();\n /** Document Keys that have local changes */\n this.mutatedKeys = documentKeySet();\n this.documentSet = new DocumentSet(query.docComparator.bind(query));\n }\n /**\n * Iterates over a set of doc changes, applies the query limit, and computes\n * what the new results should be, what the changes were, and whether we may\n * need to go back to the local cache for more results. Does not make any\n * changes to the view.\n * @param docChanges The doc changes to apply to this view.\n * @param previousChanges If this is being called with a refill, then start\n * with this set of docs and changes instead of the current view.\n * @return a new set of docs, changes, and refill flag.\n */\n View.prototype.computeDocChanges = function (docChanges, previousChanges) {\n var _this = this;\n var changeSet = previousChanges\n ? previousChanges.changeSet\n : new DocumentChangeSet();\n var oldDocumentSet = previousChanges\n ? previousChanges.documentSet\n : this.documentSet;\n var newMutatedKeys = previousChanges\n ? previousChanges.mutatedKeys\n : this.mutatedKeys;\n var newDocumentSet = oldDocumentSet;\n var needsRefill = false;\n // Track the last doc in a (full) limit. This is necessary, because some\n // update (a delete, or an update moving a doc past the old limit) might\n // mean there is some other document in the local cache that either should\n // come (1) between the old last limit doc and the new last document, in the\n // case of updates, or (2) after the new last document, in the case of\n // deletes. So we keep this doc at the old limit to compare the updates to.\n //\n // Note that this should never get used in a refill (when previousChanges is\n // set), because there will only be adds -- no deletes or updates.\n var lastDocInLimit = this.query.hasLimit() && oldDocumentSet.size === this.query.limit\n ? oldDocumentSet.last()\n : null;\n docChanges.inorderTraversal(function (key, newMaybeDoc) {\n var oldDoc = oldDocumentSet.get(key);\n var newDoc = newMaybeDoc instanceof Document ? newMaybeDoc : null;\n if (newDoc) {\n assert(key.isEqual(newDoc.key), 'Mismatching keys found in document changes: ' +\n key +\n ' != ' +\n newDoc.key);\n newDoc = _this.query.matches(newDoc) ? newDoc : null;\n }\n if (newDoc) {\n newDocumentSet = newDocumentSet.add(newDoc);\n if (newDoc.hasLocalMutations) {\n newMutatedKeys = newMutatedKeys.add(key);\n }\n else {\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n }\n else {\n newDocumentSet = newDocumentSet.delete(key);\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n // Calculate change\n if (oldDoc && newDoc) {\n var docsEqual = oldDoc.data.isEqual(newDoc.data);\n if (!docsEqual ||\n oldDoc.hasLocalMutations !== newDoc.hasLocalMutations) {\n // only report a change if document actually changed\n if (docsEqual) {\n changeSet.track({ type: ChangeType.Metadata, doc: newDoc });\n }\n else {\n changeSet.track({ type: ChangeType.Modified, doc: newDoc });\n }\n if (lastDocInLimit &&\n _this.query.docComparator(newDoc, lastDocInLimit) > 0) {\n // This doc moved from inside the limit to after the limit.\n // That means there may be some doc in the local cache that's\n // actually less than this one.\n needsRefill = true;\n }\n }\n }\n else if (!oldDoc && newDoc) {\n changeSet.track({ type: ChangeType.Added, doc: newDoc });\n }\n else if (oldDoc && !newDoc) {\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc });\n if (lastDocInLimit) {\n // A doc was removed from a full limit query. We'll need to\n // requery from the local cache to see if we know about some other\n // doc that should be in the results.\n needsRefill = true;\n }\n }\n });\n if (this.query.hasLimit()) {\n // TODO(klimt): Make DocumentSet size be constant time.\n while (newDocumentSet.size > this.query.limit) {\n var oldDoc = newDocumentSet.last();\n newDocumentSet = newDocumentSet.delete(oldDoc.key);\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc });\n }\n }\n assert(!needsRefill || !previousChanges, 'View was refilled using docs that themselves needed refilling.');\n return {\n documentSet: newDocumentSet,\n changeSet: changeSet,\n needsRefill: needsRefill,\n mutatedKeys: newMutatedKeys\n };\n };\n /**\n * Updates the view with the given ViewDocumentChanges and updates limbo docs\n * and sync state from the given (optional) target change.\n * @param docChanges The set of changes to make to the view's docs.\n * @param targetChange A target change to apply for computing limbo docs and\n * sync state.\n * @return A new ViewChange with the given docs, changes, and sync state.\n */\n View.prototype.applyChanges = function (docChanges, targetChange) {\n var _this = this;\n assert(!docChanges.needsRefill, 'Cannot apply changes that need a refill');\n var oldDocs = this.documentSet;\n this.documentSet = docChanges.documentSet;\n this.mutatedKeys = docChanges.mutatedKeys;\n // Sort changes based on type and query comparator\n var changes = docChanges.changeSet.getChanges();\n changes.sort(function (c1, c2) {\n return (compareChangeType(c1.type, c2.type) ||\n _this.query.docComparator(c1.doc, c2.doc));\n });\n var limboChanges = this.applyTargetChange(targetChange);\n var synced = this.limboDocuments.size === 0 && this.current;\n var newSyncState = synced ? SyncState.Synced : SyncState.Local;\n var syncStateChanged = newSyncState !== this.syncState;\n this.syncState = newSyncState;\n if (changes.length === 0 && !syncStateChanged) {\n // no changes\n return { limboChanges: limboChanges };\n }\n else {\n var snap = new ViewSnapshot(this.query, docChanges.documentSet, oldDocs, changes, newSyncState === SyncState.Local, !docChanges.mutatedKeys.isEmpty(), syncStateChanged);\n return {\n snapshot: snap,\n limboChanges: limboChanges\n };\n }\n };\n /**\n * Applies an OnlineState change to the view, potentially generating a\n * ViewChange if the view's syncState changes as a result.\n */\n View.prototype.applyOnlineStateChange = function (onlineState) {\n if (this.current && onlineState === OnlineState.Failed) {\n // If we're offline, set `current` to false and then call applyChanges()\n // to refresh our syncState and generate a ViewChange as appropriate. We\n // are guaranteed to get a new TargetChange that sets `current` back to\n // true once the client is back online.\n this.current = false;\n return this.applyChanges({\n documentSet: this.documentSet,\n changeSet: new DocumentChangeSet(),\n mutatedKeys: this.mutatedKeys,\n needsRefill: false\n });\n }\n else {\n // No effect, just return a no-op ViewChange.\n return { limboChanges: [] };\n }\n };\n /**\n * Returns whether the doc for the given key should be in limbo.\n */\n View.prototype.shouldBeInLimbo = function (key) {\n // If the remote end says it's part of this query, it's not in limbo.\n if (this.syncedDocuments.has(key)) {\n return false;\n }\n // The local store doesn't think it's a result, so it shouldn't be in limbo.\n if (!this.documentSet.has(key)) {\n return false;\n }\n // If there are local changes to the doc, they might explain why the server\n // doesn't know that it's part of the query. So don't put it in limbo.\n // TODO(klimt): Ideally, we would only consider changes that might actually\n // affect this specific query.\n if (this.documentSet.get(key).hasLocalMutations) {\n return false;\n }\n // Everything else is in limbo.\n return true;\n };\n /**\n * Updates syncedDocuments, current, and limbo docs based on the given change.\n * Returns the list of changes to which docs are in limbo.\n */\n View.prototype.applyTargetChange = function (targetChange) {\n var _this = this;\n if (targetChange) {\n var targetMapping = targetChange.mapping;\n if (targetMapping instanceof ResetMapping) {\n this.syncedDocuments = targetMapping.documents;\n }\n else if (targetMapping instanceof UpdateMapping) {\n this.syncedDocuments = targetMapping.applyToKeySet(this.syncedDocuments);\n }\n switch (targetChange.currentStatusUpdate) {\n case CurrentStatusUpdate.MarkCurrent:\n this.current = true;\n break;\n case CurrentStatusUpdate.MarkNotCurrent:\n this.current = false;\n break;\n case CurrentStatusUpdate.None:\n break;\n default:\n fail('Unknown current status update: ' + targetChange.currentStatusUpdate);\n }\n }\n // Recompute the set of limbo docs.\n // TODO(klimt): Do this incrementally so that it's not quadratic when\n // updating many documents.\n var oldLimboDocuments = this.limboDocuments;\n this.limboDocuments = documentKeySet();\n if (this.current) {\n this.documentSet.forEach(function (doc) {\n if (_this.shouldBeInLimbo(doc.key)) {\n _this.limboDocuments = _this.limboDocuments.add(doc.key);\n }\n });\n }\n // Diff the new limbo docs with the old limbo docs.\n var changes = [];\n oldLimboDocuments.forEach(function (key) {\n if (!_this.limboDocuments.has(key)) {\n changes.push(new RemovedLimboDocument(key));\n }\n });\n this.limboDocuments.forEach(function (key) {\n if (!oldLimboDocuments.has(key)) {\n changes.push(new AddedLimboDocument(key));\n }\n });\n return changes;\n };\n return View;\n}());\nexport { View };\nfunction compareChangeType(c1, c2) {\n var order = function (change) {\n switch (change) {\n case ChangeType.Added:\n return 1;\n case ChangeType.Modified:\n return 2;\n case ChangeType.Metadata:\n // A metadata change is converted to a modified change at the public\n // api layer. Since we sort by document key and then change type,\n // metadata and modified changes must be sorted equivalently.\n return 2;\n case ChangeType.Removed:\n return 0;\n default:\n return fail('Unknown ChangeType: ' + change);\n }\n };\n return order(c1) - order(c2);\n}\n\n//# sourceMappingURL=view.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/view.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { ResourcePath } from '../model/path';\nimport { assert, fail } from '../util/assert';\nvar escapeChar = '\\u0001';\nvar encodedSeparatorChar = '\\u0001';\nvar encodedNul = '\\u0010';\nvar encodedEscape = '\\u0011';\n/**\n * Encodes a resource path into a IndexedDb-compatible string form.\n */\nexport function encode(path) {\n var result = '';\n for (var i = 0; i < path.length; i++) {\n if (result.length > 0) {\n result = encodeSeparator(result);\n }\n result = encodeSegment(path.get(i), result);\n }\n return encodeSeparator(result);\n}\n/** Encodes a single segment of a resource path into the given result */\nfunction encodeSegment(segment, resultBuf) {\n var result = resultBuf;\n var length = segment.length;\n for (var i = 0; i < length; i++) {\n var c = segment.charAt(i);\n switch (c) {\n case '\\0':\n result += escapeChar + encodedNul;\n break;\n case escapeChar:\n result += escapeChar + encodedEscape;\n break;\n default:\n result += c;\n }\n }\n return result;\n}\n/** Encodes a path separator into the given result */\nfunction encodeSeparator(result) {\n return result + escapeChar + encodedSeparatorChar;\n}\n/**\n * Decodes the given IndexedDb-compatible string form of a resource path into\n * a ResourcePath instance. Note that this method is not suitable for use with\n * decoding resource names from the server; those are One Platform format\n * strings.\n */\nexport function decode(path) {\n // Event the empty path must encode as a path of at least length 2. A path\n // with exactly 2 must be the empty path.\n var length = path.length;\n assert(length >= 2, 'Invalid path ' + path);\n if (length === 2) {\n assert(path.charAt(0) === escapeChar && path.charAt(1) === encodedSeparatorChar, 'Non-empty path ' + path + ' had length 2');\n return ResourcePath.EMPTY_PATH;\n }\n // Escape characters cannot exist past the second-to-last position in the\n // source value.\n var lastReasonableEscapeIndex = length - 2;\n var segments = [];\n var segmentBuilder = '';\n for (var start = 0; start < length;) {\n // The last two characters of a valid encoded path must be a separator, so\n // there must be an end to this segment.\n var end = path.indexOf(escapeChar, start);\n if (end < 0 || end > lastReasonableEscapeIndex) {\n fail('Invalid encoded resource path: \"' + path + '\"');\n }\n var next = path.charAt(end + 1);\n switch (next) {\n case encodedSeparatorChar:\n var currentPiece = path.substring(start, end);\n var segment = void 0;\n if (segmentBuilder.length === 0) {\n // Avoid copying for the common case of a segment that excludes \\0\n // and \\001\n segment = currentPiece;\n }\n else {\n segmentBuilder += currentPiece;\n segment = segmentBuilder;\n segmentBuilder = '';\n }\n segments.push(segment);\n break;\n case encodedNul:\n segmentBuilder += path.substring(start, end);\n segmentBuilder += '\\0';\n break;\n case encodedEscape:\n // The escape character can be used in the output to encode itself.\n segmentBuilder += path.substring(start, end + 1);\n break;\n default:\n fail('Invalid encoded resource path: \"' + path + '\"');\n }\n start = end + 2;\n }\n return new ResourcePath(segments);\n}\n/**\n * Computes the prefix successor of the given path, computed by encode above.\n * A prefix successor is the first key that cannot be prefixed by the given\n * path. It's useful for defining the end of a prefix scan such that all keys\n * in the scan have the same prefix.\n *\n * Note that this is not a general prefix successor implementation, which is\n * tricky to get right with Strings, given that they encode down to UTF-8.\n * Instead this relies on the fact that all paths encoded by this class are\n * always terminated with a separator, and so a successor can always be\n * cheaply computed by incrementing the last character of the path.\n */\nexport function prefixSuccessor(path) {\n var c = path.charCodeAt(path.length - 1);\n // TODO(mcg): this really should be a general thing, but not worth it right\n // now\n assert(c === 1, 'successor may only operate on paths generated by encode');\n return path.substring(0, path.length - 1) + String.fromCharCode(c + 1);\n}\n\n//# sourceMappingURL=encoded_resource_path.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/encoded_resource_path.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { assert } from '../util/assert';\nimport { encode } from './encoded_resource_path';\nexport var SCHEMA_VERSION = 1;\n/** Performs database creation and (in the future) upgrades between versions. */\nexport function createOrUpgradeDb(db, oldVersion) {\n assert(oldVersion === 0, 'Unexpected upgrade from version ' + oldVersion);\n db.createObjectStore(DbMutationQueue.store, {\n keyPath: DbMutationQueue.keyPath\n });\n // TODO(mikelehen): Get rid of \"as any\" if/when TypeScript fixes their\n // types. https://github.com/Microsoft/TypeScript/issues/14322\n db.createObjectStore(DbMutationBatch.store, \n // tslint:disable-next-line:no-any\n { keyPath: DbMutationBatch.keyPath });\n var targetDocumentsStore = db.createObjectStore(DbTargetDocument.store, \n // tslint:disable-next-line:no-any\n { keyPath: DbTargetDocument.keyPath });\n targetDocumentsStore.createIndex(DbTargetDocument.documentTargetsIndex, DbTargetDocument.documentTargetsKeyPath, { unique: true });\n var targetStore = db.createObjectStore(DbTarget.store, {\n keyPath: DbTarget.keyPath\n });\n // NOTE: This is unique only because the TargetId is the suffix.\n targetStore.createIndex(DbTarget.queryTargetsIndexName, DbTarget.queryTargetsKeyPath, { unique: true });\n // NOTE: keys for these stores are specified explicitly rather than using a\n // keyPath.\n db.createObjectStore(DbDocumentMutation.store);\n db.createObjectStore(DbRemoteDocument.store);\n db.createObjectStore(DbOwner.store);\n db.createObjectStore(DbTargetGlobal.store);\n}\n/**\n * Wrapper class to store timestamps (seconds and nanos) in IndexedDb objects.\n */\nvar DbTimestamp = /** @class */ (function () {\n function DbTimestamp(seconds, nanos) {\n this.seconds = seconds;\n this.nanos = nanos;\n }\n return DbTimestamp;\n}());\nexport { DbTimestamp };\n/**\n * A singleton object to be stored in the 'owner' store in IndexedDb.\n *\n * A given database can be owned by a single tab at a given time. That tab\n * must validate that it is still the owner before every write operation and\n * should regularly write an updated timestamp to prevent other tabs from\n * \"stealing\" ownership of the db.\n */\nvar DbOwner = /** @class */ (function () {\n function DbOwner(ownerId, leaseTimestampMs) {\n this.ownerId = ownerId;\n this.leaseTimestampMs = leaseTimestampMs;\n }\n /** Name of the IndexedDb object store. */\n DbOwner.store = 'owner';\n return DbOwner;\n}());\nexport { DbOwner };\n/**\n * An object to be stored in the 'mutationQueues' store in IndexedDb.\n *\n * Each user gets a single queue of MutationBatches to apply to the server.\n * DbMutationQueue tracks the metadata about the queue.\n */\nvar DbMutationQueue = /** @class */ (function () {\n function DbMutationQueue(\n /**\n * The normalized user ID to which this queue belongs.\n */\n userId, \n /**\n * An identifier for the highest numbered batch that has been acknowledged\n * by the server. All MutationBatches in this queue with batchIds less\n * than or equal to this value are considered to have been acknowledged by\n * the server.\n */\n lastAcknowledgedBatchId, \n /**\n * A stream token that was previously sent by the server.\n *\n * See StreamingWriteRequest in datastore.proto for more details about\n * usage.\n *\n * After sending this token, earlier tokens may not be used anymore so\n * only a single stream token is retained.\n */\n lastStreamToken) {\n this.userId = userId;\n this.lastAcknowledgedBatchId = lastAcknowledgedBatchId;\n this.lastStreamToken = lastStreamToken;\n }\n /** Name of the IndexedDb object store. */\n DbMutationQueue.store = 'mutationQueues';\n /** Keys are automatically assigned via the userId property. */\n DbMutationQueue.keyPath = 'userId';\n return DbMutationQueue;\n}());\nexport { DbMutationQueue };\n/**\n * An object to be stored in the 'mutations' store in IndexedDb.\n *\n * Represents a batch of user-level mutations intended to be sent to the server\n * in a single write. Each user-level batch gets a separate DbMutationBatch\n * with a new batchId.\n */\nvar DbMutationBatch = /** @class */ (function () {\n function DbMutationBatch(\n /**\n * The normalized user ID to which this batch belongs.\n */\n userId, \n /**\n * An identifier for this batch, allocated by the mutation queue in a\n * monotonically increasing manner.\n */\n batchId, \n /**\n * The local write time of the batch, stored as milliseconds since the\n * epoch.\n */\n localWriteTimeMs, \n /**\n * A list of mutations to apply. All mutations will be applied atomically.\n *\n * Mutations are serialized via JsonProtoSerializer.toMutation().\n */\n mutations) {\n this.userId = userId;\n this.batchId = batchId;\n this.localWriteTimeMs = localWriteTimeMs;\n this.mutations = mutations;\n }\n /** Name of the IndexedDb object store. */\n DbMutationBatch.store = 'mutations';\n /** Keys are automatically assigned via the userId, batchId properties. */\n DbMutationBatch.keyPath = ['userId', 'batchId'];\n return DbMutationBatch;\n}());\nexport { DbMutationBatch };\n/**\n * An object to be stored in the 'documentMutations' store in IndexedDb.\n *\n * A manually maintained index of all the mutation batches that affect a given\n * document key. The rows in this table are references based on the contents of\n * DbMutationBatch.mutations.\n */\nvar DbDocumentMutation = /** @class */ (function () {\n function DbDocumentMutation() {\n }\n /**\n * Creates a [userId] key for use in the DbDocumentMutations index to iterate\n * over all of a user's document mutations.\n */\n DbDocumentMutation.prefixForUser = function (userId) {\n return [userId];\n };\n /**\n * Creates a [userId, encodedPath] key for use in the DbDocumentMutations\n * index to iterate over all at document mutations for a given path or lower.\n */\n DbDocumentMutation.prefixForPath = function (userId, path) {\n return [userId, encode(path)];\n };\n /**\n * Creates a full index key of [userId, encodedPath, batchId] for inserting\n * and deleting into the DbDocumentMutations index.\n */\n DbDocumentMutation.key = function (userId, path, batchId) {\n return [userId, encode(path), batchId];\n };\n DbDocumentMutation.store = 'documentMutations';\n /**\n * Because we store all the useful information for this store in the key,\n * there is no useful information to store as the value. The raw (unencoded)\n * path cannot be stored because IndexedDb doesn't store prototype\n * information.\n */\n DbDocumentMutation.PLACEHOLDER = new DbDocumentMutation();\n return DbDocumentMutation;\n}());\nexport { DbDocumentMutation };\n/**\n * Represents the known absence of a document at a particular version.\n * Stored in IndexedDb as part of a DbRemoteDocument object.\n */\nvar DbNoDocument = /** @class */ (function () {\n function DbNoDocument(path, readTime) {\n this.path = path;\n this.readTime = readTime;\n }\n return DbNoDocument;\n}());\nexport { DbNoDocument };\n/**\n * An object to be stored in the 'remoteDocuments' store in IndexedDb. It\n * represents either a cached document (if it exists) or a cached \"no-document\"\n * (if it is known to not exist).\n *\n * Note: This is the persisted equivalent of a MaybeDocument and could perhaps\n * be made more general if necessary.\n */\nvar DbRemoteDocument = /** @class */ (function () {\n function DbRemoteDocument(\n /**\n * Set to an instance of a DbNoDocument if it is known that no document\n * exists.\n */\n noDocument, \n /**\n * Set to an instance of a Document if there's a cached version of the\n * document.\n */\n document) {\n this.noDocument = noDocument;\n this.document = document;\n }\n DbRemoteDocument.store = 'remoteDocuments';\n return DbRemoteDocument;\n}());\nexport { DbRemoteDocument };\n/**\n * An object to be stored in the 'targets' store in IndexedDb.\n *\n * This is based on and should be kept in sync with the proto used in the iOS\n * client.\n *\n * Each query the client listens to against the server is tracked on disk so\n * that the query can be efficiently resumed on restart.\n */\nvar DbTarget = /** @class */ (function () {\n function DbTarget(\n /**\n * An auto-generated sequential numeric identifier for the query.\n *\n * Queries are stored using their canonicalId as the key, but these\n * canonicalIds can be quite long so we additionally assign a unique\n * queryId which can be used by referenced data structures (e.g.\n * indexes) to minimize the on-disk cost.\n */\n targetId, \n /**\n * The canonical string representing this query. This is not unique.\n */\n canonicalId, \n /**\n * The last readTime received from the Watch Service for this query.\n *\n * This is the same value as TargetChange.read_time in the protos.\n */\n readTime, \n /**\n * An opaque, server-assigned token that allows watching a query to be\n * resumed after disconnecting without retransmitting all the data\n * that matches the query. The resume token essentially identifies a\n * point in time from which the server should resume sending results.\n *\n * This is related to the snapshotVersion in that the resumeToken\n * effectively also encodes that value, but the resumeToken is opaque\n * and sometimes encodes additional information.\n *\n * A consequence of this is that the resumeToken should be used when\n * asking the server to reason about where this client is in the watch\n * stream, but the client should use the snapshotVersion for its own\n * purposes.\n *\n * This is the same value as TargetChange.resume_token in the protos.\n */\n resumeToken, \n /**\n * A sequence number representing the last time this query was\n * listened to, used for garbage collection purposes.\n *\n * Conventionally this would be a timestamp value, but device-local\n * clocks are unreliable and they must be able to create new listens\n * even while disconnected. Instead this should be a monotonically\n * increasing number that's incremented on each listen call.\n *\n * This is different from the queryId since the queryId is an\n * immutable identifier assigned to the Query on first use while\n * lastListenSequenceNumber is updated every time the query is\n * listened to.\n */\n lastListenSequenceNumber, \n /**\n * The query for this target.\n *\n * Because canonical ids are not unique we must store the actual query. We\n * use the proto to have an object we can persist without having to\n * duplicate translation logic to and from a `Query` object.\n */\n query) {\n this.targetId = targetId;\n this.canonicalId = canonicalId;\n this.readTime = readTime;\n this.resumeToken = resumeToken;\n this.lastListenSequenceNumber = lastListenSequenceNumber;\n this.query = query;\n }\n DbTarget.store = 'targets';\n /** Keys are automatically assigned via the targetId property. */\n DbTarget.keyPath = 'targetId';\n /** The name of the queryTargets index. */\n DbTarget.queryTargetsIndexName = 'queryTargetsIndex';\n /**\n * The index of all canonicalIds to the targets that they match. This is not\n * a unique mapping because canonicalId does not promise a unique name for all\n * possible queries, so we append the targetId to make the mapping unique.\n */\n DbTarget.queryTargetsKeyPath = ['canonicalId', 'targetId'];\n return DbTarget;\n}());\nexport { DbTarget };\n/**\n * An object representing an association between a target and a document.\n * Stored in the targetDocument object store to store the documents tracked by a\n * particular target.\n */\nvar DbTargetDocument = /** @class */ (function () {\n function DbTargetDocument(\n /**\n * The targetId identifying a target.\n */\n targetId, \n /**\n * The path to the document, as encoded in the key.\n */\n path) {\n this.targetId = targetId;\n this.path = path;\n }\n /** Name of the IndexedDb object store. */\n DbTargetDocument.store = 'targetDocuments';\n /** Keys are automatically assigned via the targetId, path properties. */\n DbTargetDocument.keyPath = ['targetId', 'path'];\n /** The index name for the reverse index. */\n DbTargetDocument.documentTargetsIndex = 'documentTargetsIndex';\n /** We also need to create the reverse index for these properties. */\n DbTargetDocument.documentTargetsKeyPath = ['path', 'targetId'];\n return DbTargetDocument;\n}());\nexport { DbTargetDocument };\n/**\n * A record of global state tracked across all Targets, tracked separately\n * to avoid the need for extra indexes.\n *\n * This should be kept in-sync with the proto used in the iOS client.\n */\nvar DbTargetGlobal = /** @class */ (function () {\n function DbTargetGlobal(\n /**\n * The highest numbered target id across all targets.\n *\n * See DbTarget.targetId.\n */\n highestTargetId, \n /**\n * The highest numbered lastListenSequenceNumber across all targets.\n *\n * See DbTarget.lastListenSequenceNumber.\n */\n highestListenSequenceNumber, \n /**\n * A global snapshot version representing the last consistent snapshot we\n * received from the backend. This is monotonically increasing and any\n * snapshots received from the backend prior to this version (e.g. for\n * targets resumed with a resumeToken) should be suppressed (buffered)\n * until the backend has caught up to this snapshot version again. This\n * prevents our cache from ever going backwards in time.\n */\n lastRemoteSnapshotVersion) {\n this.highestTargetId = highestTargetId;\n this.highestListenSequenceNumber = highestListenSequenceNumber;\n this.lastRemoteSnapshotVersion = lastRemoteSnapshotVersion;\n }\n /**\n * The key string used for the single object that exists in the\n * DbTargetGlobal store.\n */\n DbTargetGlobal.key = 'targetGlobalKey';\n DbTargetGlobal.store = 'targetGlobal';\n return DbTargetGlobal;\n}());\nexport { DbTargetGlobal };\n/**\n * The list of all IndexedDB stored used by the SDK. This is used when creating\n * transactions so that access across all stores is done atomically.\n */\nexport var ALL_STORES = [\n DbMutationQueue.store,\n DbMutationBatch.store,\n DbDocumentMutation.store,\n DbRemoteDocument.store,\n DbTarget.store,\n DbOwner.store,\n DbTargetGlobal.store,\n DbTargetDocument.store\n];\n\n//# sourceMappingURL=indexeddb_schema.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/indexeddb_schema.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { assert } from '../util/assert';\nimport { debug } from '../util/log';\nimport { PersistencePromise } from './persistence_promise';\nvar LOG_TAG = 'SimpleDb';\n/**\n * Provides a wrapper around IndexedDb with a simplified interface that uses\n * Promise-like return values to chain operations. Real promises cannot be used\n * since .then() continuations are executed asynchronously (e.g. via\n * .setImmediate), which would cause IndexedDB to end the transaction.\n * See PersistencePromise for more details.\n */\nvar SimpleDb = /** @class */ (function () {\n function SimpleDb(db) {\n this.db = db;\n }\n /** Opens the specified database, creating or upgrading it if necessary. */\n SimpleDb.openOrCreate = function (name, version, runUpgrade) {\n assert(SimpleDb.isAvailable(), 'IndexedDB not supported in current environment.');\n debug(LOG_TAG, 'Opening database:', name);\n return new PersistencePromise(function (resolve, reject) {\n // TODO(mikelehen): Investigate browser compatibility.\n // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB\n // suggests IE9 and older WebKit browsers handle upgrade\n // differently.\n var request = window.indexedDB.open(name, version);\n request.onsuccess = function (event) {\n var db = event.target.result;\n resolve(new SimpleDb(db));\n };\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onupgradeneeded = function (event) {\n debug(LOG_TAG, 'Database \"' + name + '\" requires upgrade from version:', event.oldVersion);\n // TODO(mikelehen): If/when we need to do an actual data\n // migration, we'll want to wrap db in a SimpleDb and have the\n // runUpgrade function return a PersistencePromise, since we'll\n // likely need to do async reads and writes. For now we're\n // cheating and just passing the raw IndexedDB in, since\n // createObjectStore(), etc. are synchronous.\n var db = event.target.result;\n runUpgrade(db, event.oldVersion);\n };\n }).toPromise();\n };\n /** Deletes the specified database. */\n SimpleDb.delete = function (name) {\n debug(LOG_TAG, 'Removing database:', name);\n return wrapRequest(window.indexedDB.deleteDatabase(name)).toPromise();\n };\n /** Returns true if IndexedDB is available in the current environment. */\n SimpleDb.isAvailable = function () {\n if (typeof window === 'undefined' || window.indexedDB == null) {\n return false;\n }\n // We extensively use indexed array values and compound keys,\n // which IE and Edge do not support. However, they still have indexedDB\n // defined on the window, so we need to check for them here and make sure\n // to return that persistence is not enabled for those browsers.\n // For tracking support of this feature, see here:\n // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/\n // Check the UA string to find out the browser.\n var ua = window.navigator.userAgent;\n // IE 10\n // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';\n // IE 11\n // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';\n // Edge\n // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,\n // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';\n if (ua.indexOf('MSIE ') > 0 ||\n ua.indexOf('Trident/') > 0 ||\n ua.indexOf('Edge/') > 0) {\n return false;\n }\n else {\n return true;\n }\n };\n SimpleDb.prototype.runTransaction = function (mode, objectStores, transactionFn) {\n var transaction = new SimpleDbTransaction(this.db, mode, objectStores);\n var transactionFnResult = transactionFn(transaction)\n .catch(function (error) {\n // Abort the transaction if there was an\n // error.\n transaction.abort();\n return PersistencePromise.reject(error);\n })\n .toPromise();\n // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to\n // fire), but still return the original transactionFnResult back to the\n // caller.\n return transaction.completionPromise.then(function () { return transactionFnResult; });\n };\n SimpleDb.prototype.close = function () {\n this.db.close();\n };\n return SimpleDb;\n}());\nexport { SimpleDb };\n/**\n * A controller for iterating over a key range or index. It allows an iterate\n * callback to delete the currently-referenced object, or jump to a new key\n * within the key range or index.\n */\nvar IterationController = /** @class */ (function () {\n function IterationController(dbCursor) {\n this.dbCursor = dbCursor;\n this.shouldStop = false;\n this.nextKey = null;\n }\n Object.defineProperty(IterationController.prototype, \"isDone\", {\n get: function () {\n return this.shouldStop;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(IterationController.prototype, \"skipToKey\", {\n get: function () {\n return this.nextKey;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(IterationController.prototype, \"cursor\", {\n set: function (value) {\n this.dbCursor = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * This function can be called to stop iteration at any point.\n */\n IterationController.prototype.done = function () {\n this.shouldStop = true;\n };\n /**\n * This function can be called to skip to that next key, which could be\n * an index or a primary key.\n */\n IterationController.prototype.skip = function (key) {\n this.nextKey = key;\n };\n /**\n * Delete the current cursor value from the object store.\n *\n * NOTE: You CANNOT do this with a keysOnly query.\n */\n IterationController.prototype.delete = function () {\n return wrapRequest(this.dbCursor.delete());\n };\n return IterationController;\n}());\nexport { IterationController };\n/**\n * Wraps an IDBTransaction and exposes a store() method to get a handle to a\n * specific object store.\n */\nvar SimpleDbTransaction = /** @class */ (function () {\n function SimpleDbTransaction(db, mode, objectStoresNames) {\n var _this = this;\n this.aborted = false;\n this.transaction = db.transaction(objectStoresNames, mode);\n this.completionPromise = new Promise(function (resolve, reject) {\n // We consider aborting to be \"normal\" and just resolve the promise.\n // May need to revisit if/when we actually need to abort transactions.\n _this.transaction.onabort = _this.transaction.oncomplete = function (event) {\n resolve();\n };\n _this.transaction.onerror = function (event) {\n reject(event.target.error);\n };\n });\n }\n SimpleDbTransaction.prototype.abort = function () {\n if (!this.aborted) {\n debug(LOG_TAG, 'Aborting transaction.');\n this.aborted = true;\n this.transaction.abort();\n }\n };\n /**\n * Returns a SimpleDbStore for the specified store. All\n * operations performed on the SimpleDbStore happen within the context of this\n * transaction and it cannot be used anymore once the transaction is\n * completed.\n *\n * Note that we can't actually enforce that the KeyType and ValueType are\n * correct, but they allow type safety through the rest of the consuming code.\n */\n SimpleDbTransaction.prototype.store = function (storeName) {\n var store = this.transaction.objectStore(storeName);\n assert(!!store, 'Object store not part of transaction: ' + storeName);\n return new SimpleDbStore(store);\n };\n return SimpleDbTransaction;\n}());\nexport { SimpleDbTransaction };\n/**\n * A wrapper around an IDBObjectStore providing an API that:\n *\n * 1) Has generic KeyType / ValueType parameters to provide strongly-typed\n * methods for acting against the object store.\n * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every\n * method return a PersistencePromise instead.\n * 3) Provides a higher-level API to avoid needing to do excessive wrapping of\n * intermediate IndexedDB types (IDBCursorWithValue, etc.)\n */\nvar SimpleDbStore = /** @class */ (function () {\n function SimpleDbStore(store) {\n this.store = store;\n }\n SimpleDbStore.prototype.put = function (keyOrValue, value) {\n var request;\n if (value !== undefined) {\n debug(LOG_TAG, 'PUT', this.store.name, keyOrValue, value);\n request = this.store.put(value, keyOrValue);\n }\n else {\n debug(LOG_TAG, 'PUT', this.store.name, '', keyOrValue);\n request = this.store.put(keyOrValue);\n }\n return wrapRequest(request);\n };\n /**\n * Gets the object with the specified key from the specified store, or null\n * if no object exists with the specified key.\n *\n * @key The key of the object to get.\n * @return The object with the specified key or null if no object exists.\n */\n SimpleDbStore.prototype.get = function (key) {\n var _this = this;\n var request = this.store.get(key);\n // tslint:disable-next-line:no-any We're doing an unsafe cast to ValueType.\n return wrapRequest(request).next(function (result) {\n // Normalize nonexistence to null.\n if (result === undefined) {\n result = null;\n }\n debug(LOG_TAG, 'GET', _this.store.name, key, result);\n return result;\n });\n };\n SimpleDbStore.prototype.delete = function (key) {\n debug(LOG_TAG, 'DELETE', this.store.name, key);\n var request = this.store.delete(key);\n return wrapRequest(request);\n };\n SimpleDbStore.prototype.loadAll = function (indexOrRange, range) {\n var cursor = this.cursor(this.options(indexOrRange, range));\n var results = [];\n return this.iterateCursor(cursor, function (key, value) {\n results.push(value);\n }).next(function () {\n return results;\n });\n };\n SimpleDbStore.prototype.deleteAll = function (indexOrRange, range) {\n debug(LOG_TAG, 'DELETE ALL', this.store.name);\n var options = this.options(indexOrRange, range);\n options.keysOnly = false;\n var cursor = this.cursor(options);\n return this.iterateCursor(cursor, function (key, value, control) {\n // NOTE: Calling delete() on a cursor is documented as more efficient than\n // calling delete() on an object store with a single key\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete),\n // however, this requires us *not* to use a keysOnly cursor\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/delete). We\n // may want to compare the performance of each method.\n return control.delete();\n });\n };\n SimpleDbStore.prototype.iterate = function (optionsOrCallback, callback) {\n var options;\n if (!callback) {\n options = {};\n callback = optionsOrCallback;\n }\n else {\n options = optionsOrCallback;\n }\n var cursor = this.cursor(options);\n return this.iterateCursor(cursor, callback);\n };\n SimpleDbStore.prototype.iterateCursor = function (cursorRequest, fn) {\n var results = [];\n return new PersistencePromise(function (resolve, reject) {\n cursorRequest.onerror = function (event) {\n reject(event.target.error);\n };\n cursorRequest.onsuccess = function (event) {\n var cursor = event.target.result;\n if (!cursor) {\n resolve();\n return;\n }\n var controller = new IterationController(cursor);\n var userResult = fn(cursor.primaryKey, cursor.value, controller);\n if (userResult instanceof PersistencePromise) {\n results.push(userResult);\n }\n if (controller.isDone) {\n resolve();\n }\n else if (controller.skipToKey === null) {\n cursor.continue();\n }\n else {\n cursor.continue(controller.skipToKey);\n }\n };\n }).next(function () {\n return PersistencePromise.waitFor(results);\n });\n };\n SimpleDbStore.prototype.options = function (indexOrRange, range) {\n var indexName = undefined;\n if (indexOrRange !== undefined) {\n if (typeof indexOrRange === 'string') {\n indexName = indexOrRange;\n }\n else {\n assert(range === undefined, '3rd argument must not be defined if 2nd is a range.');\n range = indexOrRange;\n }\n }\n return { index: indexName, range: range };\n };\n SimpleDbStore.prototype.cursor = function (options) {\n var direction = 'next';\n if (options.reverse) {\n direction = 'prev';\n }\n if (options.index) {\n var index = this.store.index(options.index);\n if (options.keysOnly) {\n return index.openKeyCursor(options.range, direction);\n }\n else {\n return index.openCursor(options.range, direction);\n }\n }\n else {\n return this.store.openCursor(options.range, direction);\n }\n };\n return SimpleDbStore;\n}());\nexport { SimpleDbStore };\n/**\n * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror\n * handlers to resolve / reject the PersistencePromise as appropriate.\n */\nfunction wrapRequest(request) {\n return new PersistencePromise(function (resolve, reject) {\n request.onsuccess = function (event) {\n var result = event.target.result;\n resolve(result);\n };\n request.onerror = function (event) {\n reject(event.target.error);\n };\n });\n}\n\n//# sourceMappingURL=simple_db.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/simple_db.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { BATCHID_UNKNOWN, MutationBatch } from '../model/mutation_batch';\nimport { assert, fail } from '../util/assert';\nimport { immediatePredecessor, primitiveComparator } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\nimport * as EncodedResourcePath from './encoded_resource_path';\nimport { DbDocumentMutation, DbMutationBatch, DbMutationQueue } from './indexeddb_schema';\nimport { PersistencePromise } from './persistence_promise';\nimport { SimpleDbTransaction } from './simple_db';\n/** A mutation queue for a specific user, backed by IndexedDB. */\nvar IndexedDbMutationQueue = /** @class */ (function () {\n function IndexedDbMutationQueue(\n /**\n * The normalized userId (e.g. null UID => \"\" userId) used to store /\n * retrieve mutations.\n */\n userId, serializer) {\n this.userId = userId;\n this.serializer = serializer;\n this.garbageCollector = null;\n }\n /**\n * Creates a new mutation queue for the given user.\n * @param user The user for which to create a mutation queue.\n * @param serializer The serializer to use when persisting to IndexedDb.\n */\n IndexedDbMutationQueue.forUser = function (user, serializer) {\n // TODO(mcg): Figure out what constraints there are on userIDs\n // In particular, are there any reserved characters? are empty ids allowed?\n // For the moment store these together in the same mutations table assuming\n // that empty userIDs aren't allowed.\n assert(user.uid !== '', 'UserID must not be an empty string.');\n var userId = user.isUnauthenticated() ? '' : user.uid;\n return new IndexedDbMutationQueue(userId, serializer);\n };\n IndexedDbMutationQueue.prototype.start = function (transaction) {\n var _this = this;\n return IndexedDbMutationQueue.loadNextBatchIdFromDb(transaction)\n .next(function (nextBatchId) {\n _this.nextBatchId = nextBatchId;\n return mutationQueuesStore(transaction).get(_this.userId);\n })\n .next(function (metadata) {\n if (!metadata) {\n metadata = new DbMutationQueue(_this.userId, BATCHID_UNKNOWN, \n /*lastStreamToken=*/ '');\n }\n _this.metadata = metadata;\n // On restart, nextBatchId may end up lower than\n // lastAcknowledgedBatchId since it's computed from the queue\n // contents, and there may be no mutations in the queue. In this\n // case, we need to reset lastAcknowledgedBatchId (which is safe\n // since the queue must be empty).\n if (_this.metadata.lastAcknowledgedBatchId >= _this.nextBatchId) {\n return _this.checkEmpty(transaction).next(function (empty) {\n assert(empty, 'Reset nextBatchID is only possible when the queue is empty');\n _this.metadata.lastAcknowledgedBatchId = BATCHID_UNKNOWN;\n return mutationQueuesStore(transaction).put(_this.metadata);\n });\n }\n else {\n return PersistencePromise.resolve();\n }\n });\n };\n /**\n * Returns one larger than the largest batch ID that has been stored. If there\n * are no mutations returns 0. Note that batch IDs are global.\n */\n IndexedDbMutationQueue.loadNextBatchIdFromDb = function (txn) {\n var maxBatchId = BATCHID_UNKNOWN;\n return mutationsStore(txn)\n .iterate({ reverse: true }, function (key, batch, control) {\n var userId = key[0], batchId = key[1];\n if (batchId > maxBatchId) {\n maxBatchId = batch.batchId;\n }\n if (userId === '') {\n // We can't compute a predecessor for the empty string, since it\n // is lexographically first. That also means that no other\n // userIds can come before this one, so we can just exit early.\n control.done();\n }\n else {\n var nextUser = immediatePredecessor(userId);\n control.skip([nextUser]);\n }\n })\n .next(function () { return maxBatchId + 1; });\n };\n IndexedDbMutationQueue.prototype.checkEmpty = function (transaction) {\n var empty = true;\n var range = IDBKeyRange.bound(this.keyForBatchId(Number.NEGATIVE_INFINITY), this.keyForBatchId(Number.POSITIVE_INFINITY));\n return mutationsStore(transaction)\n .iterate({ range: range }, function (key, value, control) {\n empty = false;\n control.done();\n })\n .next(function () { return empty; });\n };\n IndexedDbMutationQueue.prototype.getNextBatchId = function (transaction) {\n return PersistencePromise.resolve(this.nextBatchId);\n };\n IndexedDbMutationQueue.prototype.getHighestAcknowledgedBatchId = function (transaction) {\n return PersistencePromise.resolve(this.metadata.lastAcknowledgedBatchId);\n };\n IndexedDbMutationQueue.prototype.acknowledgeBatch = function (transaction, batch, streamToken) {\n var batchId = batch.batchId;\n assert(batchId > this.metadata.lastAcknowledgedBatchId, 'Mutation batchIDs must be acknowledged in order');\n this.metadata.lastAcknowledgedBatchId = batchId;\n this.metadata.lastStreamToken = validateStreamToken(streamToken);\n return mutationQueuesStore(transaction).put(this.metadata);\n };\n IndexedDbMutationQueue.prototype.getLastStreamToken = function (transaction) {\n return PersistencePromise.resolve(this.metadata.lastStreamToken);\n };\n IndexedDbMutationQueue.prototype.setLastStreamToken = function (transaction, streamToken) {\n this.metadata.lastStreamToken = validateStreamToken(streamToken);\n return mutationQueuesStore(transaction).put(this.metadata);\n };\n IndexedDbMutationQueue.prototype.addMutationBatch = function (transaction, localWriteTime, mutations) {\n var _this = this;\n var batchId = this.nextBatchId;\n this.nextBatchId++;\n var batch = new MutationBatch(batchId, localWriteTime, mutations);\n var dbBatch = this.serializer.toDbMutationBatch(this.userId, batch);\n return mutationsStore(transaction)\n .put(dbBatch)\n .next(function () {\n var promises = [];\n for (var _i = 0, mutations_1 = mutations; _i < mutations_1.length; _i++) {\n var mutation = mutations_1[_i];\n var encodedPath = EncodedResourcePath.encode(mutation.key.path);\n var indexKey = DbDocumentMutation.key(_this.userId, mutation.key.path, batchId);\n documentMutationsStore(transaction).put(indexKey, DbDocumentMutation.PLACEHOLDER);\n }\n return PersistencePromise.waitFor(promises);\n })\n .next(function () {\n return batch;\n });\n };\n IndexedDbMutationQueue.prototype.lookupMutationBatch = function (transaction, batchId) {\n var _this = this;\n return mutationsStore(transaction)\n .get(this.keyForBatchId(batchId))\n .next(function (dbBatch) {\n return dbBatch ? _this.serializer.fromDbMutationBatch(dbBatch) : null;\n });\n };\n IndexedDbMutationQueue.prototype.getNextMutationBatchAfterBatchId = function (transaction, batchId) {\n var _this = this;\n var range = IDBKeyRange.lowerBound(this.keyForBatchId(batchId + 1));\n var foundBatch = null;\n return mutationsStore(transaction)\n .iterate({ range: range }, function (key, dbBatch, control) {\n if (dbBatch.userId === _this.userId) {\n assert(dbBatch.batchId > batchId, 'Should have found mutation after ' + batchId);\n foundBatch = _this.serializer.fromDbMutationBatch(dbBatch);\n }\n control.done();\n })\n .next(function () { return foundBatch; });\n };\n IndexedDbMutationQueue.prototype.getAllMutationBatches = function (transaction) {\n var _this = this;\n var range = IDBKeyRange.bound(this.keyForBatchId(BATCHID_UNKNOWN), this.keyForBatchId(Number.POSITIVE_INFINITY));\n return mutationsStore(transaction)\n .loadAll(range)\n .next(function (dbBatches) {\n return dbBatches.map(function (dbBatch) { return _this.serializer.fromDbMutationBatch(dbBatch); });\n });\n };\n IndexedDbMutationQueue.prototype.getAllMutationBatchesThroughBatchId = function (transaction, batchId) {\n var _this = this;\n var range = IDBKeyRange.bound(this.keyForBatchId(BATCHID_UNKNOWN), this.keyForBatchId(batchId));\n return mutationsStore(transaction)\n .loadAll(range)\n .next(function (dbBatches) {\n return dbBatches.map(function (dbBatch) { return _this.serializer.fromDbMutationBatch(dbBatch); });\n });\n };\n IndexedDbMutationQueue.prototype.getAllMutationBatchesAffectingDocumentKey = function (transaction, documentKey) {\n var _this = this;\n // Scan the document-mutation index starting with a prefix starting with\n // the given documentKey.\n var indexPrefix = DbDocumentMutation.prefixForPath(this.userId, documentKey.path);\n var indexStart = IDBKeyRange.lowerBound(indexPrefix);\n var results = [];\n return documentMutationsStore(transaction)\n .iterate({ range: indexStart }, function (indexKey, _, control) {\n var userID = indexKey[0], encodedPath = indexKey[1], batchID = indexKey[2];\n // Only consider rows matching exactly the specific key of\n // interest. Note that because we order by path first, and we\n // order terminators before path separators, we'll encounter all\n // the index rows for documentKey contiguously. In particular, all\n // the rows for documentKey will occur before any rows for\n // documents nested in a subcollection beneath documentKey so we\n // can stop as soon as we hit any such row.\n var path = EncodedResourcePath.decode(encodedPath);\n if (userID !== _this.userId || !documentKey.path.isEqual(path)) {\n control.done();\n return;\n }\n var mutationKey = _this.keyForBatchId(batchID);\n // Look up the mutation batch in the store.\n // PORTING NOTE: because iteration is callback driven in the web,\n // we just look up the key instead of keeping an open iterator\n // like iOS.\n return mutationsStore(transaction)\n .get(mutationKey)\n .next(function (dbBatch) {\n if (dbBatch === null) {\n fail('Dangling document-mutation reference found: ' +\n indexKey +\n ' which points to ' +\n mutationKey);\n }\n results.push(_this.serializer.fromDbMutationBatch(dbBatch));\n });\n })\n .next(function () { return results; });\n };\n IndexedDbMutationQueue.prototype.getAllMutationBatchesAffectingQuery = function (transaction, query) {\n var _this = this;\n assert(!query.isDocumentQuery(), \"Document queries shouldn't go down this path\");\n var queryPath = query.path;\n var immediateChildrenLength = queryPath.length + 1;\n // TODO(mcg): Actually implement a single-collection query\n //\n // This is actually executing an ancestor query, traversing the whole\n // subtree below the collection which can be horrifically inefficient for\n // some structures. The right way to solve this is to implement the full\n // value index, but that's not in the cards in the near future so this is\n // the best we can do for the moment.\n //\n // Since we don't yet index the actual properties in the mutations, our\n // current approach is to just return all mutation batches that affect\n // documents in the collection being queried.\n var indexPrefix = DbDocumentMutation.prefixForPath(this.userId, queryPath);\n var encodedQueryPath = indexPrefix[1];\n var indexStart = IDBKeyRange.lowerBound(indexPrefix);\n // Collect up unique batchIDs encountered during a scan of the index. Use a\n // SortedSet to accumulate batch IDs so they can be traversed in order in a\n // scan of the main table.\n var uniqueBatchIDs = new SortedSet(primitiveComparator);\n return documentMutationsStore(transaction)\n .iterate({ range: indexStart }, function (indexKey, _, control) {\n var userID = indexKey[0], encodedPath = indexKey[1], batchID = indexKey[2];\n var path = EncodedResourcePath.decode(encodedPath);\n if (userID !== _this.userId || !queryPath.isPrefixOf(path)) {\n control.done();\n return;\n }\n // Rows with document keys more than one segment longer than the\n // query path can't be matches. For example, a query on 'rooms'\n // can't match the document /rooms/abc/messages/xyx.\n // TODO(mcg): we'll need a different scanner when we implement\n // ancestor queries.\n if (path.length !== immediateChildrenLength) {\n return;\n }\n uniqueBatchIDs = uniqueBatchIDs.add(batchID);\n })\n .next(function () {\n var results = [];\n var promises = [];\n // TODO(rockwood): Implement this using iterate.\n uniqueBatchIDs.forEach(function (batchID) {\n var mutationKey = _this.keyForBatchId(batchID);\n promises.push(mutationsStore(transaction)\n .get(mutationKey)\n .next(function (mutation) {\n if (mutation === null) {\n fail('Dangling document-mutation reference found, ' +\n 'which points to ' +\n mutationKey);\n }\n results.push(_this.serializer.fromDbMutationBatch(mutation));\n }));\n });\n return PersistencePromise.waitFor(promises).next(function () { return results; });\n });\n };\n IndexedDbMutationQueue.prototype.removeMutationBatches = function (transaction, batches) {\n var txn = mutationsStore(transaction);\n var indexTxn = documentMutationsStore(transaction);\n var promises = [];\n var _loop_1 = function (batch) {\n var range = IDBKeyRange.only(this_1.keyForBatchId(batch.batchId));\n var numDeleted = 0;\n var removePromise = txn.iterate({ range: range }, function (key, value, control) {\n numDeleted++;\n return control.delete();\n });\n promises.push(removePromise.next(function () {\n assert(numDeleted === 1, 'Dangling document-mutation reference found: Missing batch ' +\n batch.batchId);\n }));\n for (var _i = 0, _a = batch.mutations; _i < _a.length; _i++) {\n var mutation = _a[_i];\n var indexKey = DbDocumentMutation.key(this_1.userId, mutation.key.path, batch.batchId);\n promises.push(indexTxn.delete(indexKey));\n if (this_1.garbageCollector !== null) {\n this_1.garbageCollector.addPotentialGarbageKey(mutation.key);\n }\n }\n };\n var this_1 = this;\n for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {\n var batch = batches_1[_i];\n _loop_1(batch);\n }\n return PersistencePromise.waitFor(promises);\n };\n IndexedDbMutationQueue.prototype.performConsistencyCheck = function (txn) {\n var _this = this;\n return this.checkEmpty(txn).next(function (empty) {\n if (!empty) {\n return PersistencePromise.resolve();\n }\n // Verify that there are no entries in the documentMutations index if\n // the queue is empty.\n var startRange = IDBKeyRange.lowerBound(DbDocumentMutation.prefixForUser(_this.userId));\n var danglingMutationReferences = [];\n return documentMutationsStore(txn)\n .iterate({ range: startRange }, function (key, _, control) {\n var userID = key[0];\n if (userID !== _this.userId) {\n control.done();\n return;\n }\n else {\n var path = EncodedResourcePath.decode(key[1]);\n danglingMutationReferences.push(path);\n }\n })\n .next(function () {\n assert(danglingMutationReferences.length === 0, 'Document leak -- detected dangling mutation references when queue is empty. Dangling keys: ' +\n danglingMutationReferences.map(function (p) { return p.canonicalString(); }));\n });\n });\n };\n IndexedDbMutationQueue.prototype.setGarbageCollector = function (gc) {\n this.garbageCollector = gc;\n };\n IndexedDbMutationQueue.prototype.containsKey = function (txn, key) {\n var _this = this;\n var indexKey = DbDocumentMutation.prefixForPath(this.userId, key.path);\n var encodedPath = indexKey[1];\n var startRange = IDBKeyRange.lowerBound(indexKey);\n var containsKey = false;\n return documentMutationsStore(txn)\n .iterate({ range: startRange, keysOnly: true }, function (key, _, control) {\n var userID = key[0], keyPath = key[1], batchID = key[2];\n if (userID === _this.userId && keyPath === encodedPath) {\n containsKey = true;\n }\n control.done();\n })\n .next(function () { return containsKey; });\n };\n /**\n * Creates a [userId, batchId] key for use with the DbMutationQueue object\n * store.\n */\n IndexedDbMutationQueue.prototype.keyForBatchId = function (batchId) {\n return [this.userId, batchId];\n };\n return IndexedDbMutationQueue;\n}());\nexport { IndexedDbMutationQueue };\nfunction validateStreamToken(token) {\n assert(typeof token === 'string', 'Persisting non-string stream token not supported.');\n return token;\n}\n/**\n * Helper to get a typed SimpleDbStore for the mutations object store.\n */\nfunction mutationsStore(txn) {\n return getStore(txn, DbMutationBatch.store);\n}\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */\nfunction documentMutationsStore(txn) {\n return getStore(txn, DbDocumentMutation.store);\n}\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */\nfunction mutationQueuesStore(txn) {\n return getStore(txn, DbMutationQueue.store);\n}\n/**\n * Helper to get a typed SimpleDbStore from a transaction.\n */\nfunction getStore(txn, store) {\n if (txn instanceof SimpleDbTransaction) {\n return txn.store(store);\n }\n else {\n return fail('Invalid transaction object provided!');\n }\n}\n\n//# sourceMappingURL=indexeddb_mutation_queue.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/indexeddb_mutation_queue.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Timestamp } from '../core/timestamp';\nimport { documentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { assert, fail } from '../util/assert';\nimport { immediateSuccessor } from '../util/misc';\nimport * as EncodedResourcePath from './encoded_resource_path';\nimport { DbTarget, DbTargetDocument, DbTargetGlobal } from './indexeddb_schema';\nimport { PersistencePromise } from './persistence_promise';\nimport { SimpleDbTransaction } from './simple_db';\nvar IndexedDbQueryCache = /** @class */ (function () {\n function IndexedDbQueryCache(serializer) {\n this.serializer = serializer;\n /**\n * The last received snapshot version. We store this seperately from the\n * metadata to avoid the extra conversion to/from DbTimestamp.\n */\n this.lastRemoteSnapshotVersion = SnapshotVersion.MIN;\n /**\n * A cached copy of the metadata for the query cache.\n */\n this.metadata = new DbTargetGlobal(\n /*highestTargetId=*/ 0, \n /*lastListenSequenceNumber=*/ 0, SnapshotVersion.MIN.toTimestamp());\n /** The garbage collector to notify about potential garbage keys. */\n this.garbageCollector = null;\n }\n IndexedDbQueryCache.prototype.start = function (transaction) {\n var _this = this;\n return globalTargetStore(transaction)\n .get(DbTargetGlobal.key)\n .next(function (metadata) {\n if (metadata !== null) {\n _this.metadata = metadata;\n var lastSavedVersion = metadata.lastRemoteSnapshotVersion;\n _this.lastRemoteSnapshotVersion = SnapshotVersion.fromTimestamp(new Timestamp(lastSavedVersion.seconds, lastSavedVersion.nanos));\n }\n return PersistencePromise.resolve();\n });\n };\n IndexedDbQueryCache.prototype.getHighestTargetId = function () {\n return this.metadata.highestTargetId;\n };\n IndexedDbQueryCache.prototype.getLastRemoteSnapshotVersion = function () {\n return this.lastRemoteSnapshotVersion;\n };\n IndexedDbQueryCache.prototype.setLastRemoteSnapshotVersion = function (transaction, snapshotVersion) {\n this.lastRemoteSnapshotVersion = snapshotVersion;\n this.metadata.lastRemoteSnapshotVersion = snapshotVersion.toTimestamp();\n return globalTargetStore(transaction).put(DbTargetGlobal.key, this.metadata);\n };\n IndexedDbQueryCache.prototype.addQueryData = function (transaction, queryData) {\n var _this = this;\n var targetId = queryData.targetId;\n var addedQueryPromise = targetsStore(transaction).put(this.serializer.toDbTarget(queryData));\n if (targetId > this.metadata.highestTargetId) {\n this.metadata.highestTargetId = targetId;\n return addedQueryPromise.next(function () {\n return globalTargetStore(transaction).put(DbTargetGlobal.key, _this.metadata);\n });\n }\n else {\n return addedQueryPromise;\n }\n };\n IndexedDbQueryCache.prototype.removeQueryData = function (transaction, queryData) {\n return this.removeMatchingKeysForTargetId(transaction, queryData.targetId).next(function () {\n targetsStore(transaction).delete(queryData.targetId);\n });\n };\n IndexedDbQueryCache.prototype.getQueryData = function (transaction, query) {\n var _this = this;\n // Iterating by the canonicalId may yield more than one result because\n // canonicalId values are not required to be unique per target. This query\n // depends on the queryTargets index to be efficent.\n var canonicalId = query.canonicalId();\n var range = IDBKeyRange.bound([canonicalId, Number.NEGATIVE_INFINITY], [canonicalId, Number.POSITIVE_INFINITY]);\n var result = null;\n return targetsStore(transaction)\n .iterate({ range: range, index: DbTarget.queryTargetsIndexName }, function (key, value, control) {\n var found = _this.serializer.fromDbTarget(value);\n // After finding a potential match, check that the query is\n // actually equal to the requested query.\n if (query.isEqual(found.query)) {\n result = found;\n control.done();\n }\n })\n .next(function () { return result; });\n };\n IndexedDbQueryCache.prototype.addMatchingKeys = function (txn, keys, targetId) {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // Indexeddb.\n var promises = [];\n var store = documentTargetStore(txn);\n keys.forEach(function (key) {\n var path = EncodedResourcePath.encode(key.path);\n promises.push(store.put(new DbTargetDocument(targetId, path)));\n });\n return PersistencePromise.waitFor(promises);\n };\n IndexedDbQueryCache.prototype.removeMatchingKeys = function (txn, keys, targetId) {\n var _this = this;\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n var promises = [];\n var store = documentTargetStore(txn);\n keys.forEach(function (key) {\n var path = EncodedResourcePath.encode(key.path);\n promises.push(store.delete([targetId, path]));\n if (_this.garbageCollector !== null) {\n _this.garbageCollector.addPotentialGarbageKey(key);\n }\n });\n return PersistencePromise.waitFor(promises);\n };\n IndexedDbQueryCache.prototype.removeMatchingKeysForTargetId = function (txn, targetId) {\n var store = documentTargetStore(txn);\n var range = IDBKeyRange.bound([targetId], [targetId + 1], \n /*lowerOpen=*/ false, \n /*upperOpen=*/ true);\n return this.notifyGCForRemovedKeys(txn, range).next(function () {\n return store.delete(range);\n });\n };\n IndexedDbQueryCache.prototype.notifyGCForRemovedKeys = function (txn, range) {\n var _this = this;\n var store = documentTargetStore(txn);\n if (this.garbageCollector !== null && this.garbageCollector.isEager) {\n // In order to generate garbage events properly, we need to read these\n // keys before deleting.\n return store.iterate({ range: range, keysOnly: true }, function (key, _, control) {\n var path = EncodedResourcePath.decode(key[1]);\n var docKey = new DocumentKey(path);\n // Paranoid assertion in case the the collector is set to null\n // during the iteration.\n assert(_this.garbageCollector !== null, 'GarbageCollector for query cache set to null during key removal.');\n _this.garbageCollector.addPotentialGarbageKey(docKey);\n });\n }\n else {\n return PersistencePromise.resolve();\n }\n };\n IndexedDbQueryCache.prototype.getMatchingKeysForTargetId = function (txn, targetId) {\n var promises = [];\n var range = IDBKeyRange.bound([targetId], [targetId + 1], \n /*lowerOpen=*/ false, \n /*upperOpen=*/ true);\n var store = documentTargetStore(txn);\n var result = documentKeySet();\n return store\n .iterate({ range: range, keysOnly: true }, function (key, _, control) {\n var path = EncodedResourcePath.decode(key[1]);\n var docKey = new DocumentKey(path);\n result = result.add(docKey);\n })\n .next(function () { return result; });\n };\n IndexedDbQueryCache.prototype.setGarbageCollector = function (gc) {\n this.garbageCollector = gc;\n };\n IndexedDbQueryCache.prototype.containsKey = function (txn, key) {\n assert(txn !== null, 'Persistence Transaction cannot be null for query cache containsKey');\n var path = EncodedResourcePath.encode(key.path);\n var range = IDBKeyRange.bound([path], [immediateSuccessor(path)], \n /*lowerOpen=*/ false, \n /*upperOpen=*/ true);\n var count = 0;\n return documentTargetStore(txn)\n .iterate({\n index: DbTargetDocument.documentTargetsIndex,\n keysOnly: true,\n range: range\n }, function (key, _, control) {\n count++;\n control.done();\n })\n .next(function () { return count > 0; });\n };\n return IndexedDbQueryCache;\n}());\nexport { IndexedDbQueryCache };\n/**\n * Helper to get a typed SimpleDbStore for the queries object store.\n */\nfunction targetsStore(txn) {\n return getStore(txn, DbTarget.store);\n}\n/**\n * Helper to get a typed SimpleDbStore for the target globals object store.\n */\nfunction globalTargetStore(txn) {\n return getStore(txn, DbTargetGlobal.store);\n}\n/**\n * Helper to get a typed SimpleDbStore for the document target object store.\n */\nfunction documentTargetStore(txn) {\n return getStore(txn, DbTargetDocument.store);\n}\n/**\n * Helper to get a typed SimpleDbStore from a transaction.\n */\nfunction getStore(txn, store) {\n if (txn instanceof SimpleDbTransaction) {\n return txn.store(store);\n }\n else {\n return fail('Invalid transaction object provided!');\n }\n}\n\n//# sourceMappingURL=indexeddb_query_cache.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/indexeddb_query_cache.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { documentMap } from '../model/collections';\nimport { Document } from '../model/document';\nimport { fail } from '../util/assert';\nimport { DbRemoteDocument } from './indexeddb_schema';\nimport { SimpleDbTransaction } from './simple_db';\nvar IndexedDbRemoteDocumentCache = /** @class */ (function () {\n function IndexedDbRemoteDocumentCache(serializer) {\n this.serializer = serializer;\n }\n IndexedDbRemoteDocumentCache.prototype.addEntry = function (transaction, maybeDocument) {\n return remoteDocumentsStore(transaction).put(dbKey(maybeDocument.key), this.serializer.toDbRemoteDocument(maybeDocument));\n };\n IndexedDbRemoteDocumentCache.prototype.removeEntry = function (transaction, documentKey) {\n return remoteDocumentsStore(transaction).delete(dbKey(documentKey));\n };\n IndexedDbRemoteDocumentCache.prototype.getEntry = function (transaction, documentKey) {\n var _this = this;\n return remoteDocumentsStore(transaction)\n .get(dbKey(documentKey))\n .next(function (dbRemoteDoc) {\n return dbRemoteDoc\n ? _this.serializer.fromDbRemoteDocument(dbRemoteDoc)\n : null;\n });\n };\n IndexedDbRemoteDocumentCache.prototype.getDocumentsMatchingQuery = function (transaction, query) {\n var _this = this;\n var results = documentMap();\n // Documents are ordered by key, so we can use a prefix scan to narrow down\n // the documents we need to match the query against.\n var startKey = query.path.toArray();\n var range = IDBKeyRange.lowerBound(startKey);\n return remoteDocumentsStore(transaction)\n .iterate({ range: range }, function (key, dbRemoteDoc, control) {\n var maybeDoc = _this.serializer.fromDbRemoteDocument(dbRemoteDoc);\n if (!query.path.isPrefixOf(maybeDoc.key.path)) {\n control.done();\n }\n else if (maybeDoc instanceof Document && query.matches(maybeDoc)) {\n results = results.insert(maybeDoc.key, maybeDoc);\n }\n })\n .next(function () { return results; });\n };\n return IndexedDbRemoteDocumentCache;\n}());\nexport { IndexedDbRemoteDocumentCache };\n/**\n * Helper to get a typed SimpleDbStore for the remoteDocuments object store.\n */\nfunction remoteDocumentsStore(txn) {\n if (txn instanceof SimpleDbTransaction) {\n return txn.store(DbRemoteDocument.store);\n }\n else {\n return fail('Invalid transaction object provided!');\n }\n}\nfunction dbKey(docKey) {\n return docKey.path.toArray();\n}\n\n//# sourceMappingURL=indexeddb_remote_document_cache.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/indexeddb_remote_document_cache.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Timestamp } from '../core/timestamp';\nimport { Document, NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { MutationBatch } from '../model/mutation_batch';\nimport { assert, fail } from '../util/assert';\nimport { DbMutationBatch, DbNoDocument, DbRemoteDocument, DbTarget, DbTimestamp } from './indexeddb_schema';\nimport { QueryData, QueryPurpose } from './query_data';\n/** Serializer for values stored in the LocalStore. */\nvar LocalSerializer = /** @class */ (function () {\n function LocalSerializer(remoteSerializer) {\n this.remoteSerializer = remoteSerializer;\n }\n /** Decodes a remote document from storage locally to a Document. */\n LocalSerializer.prototype.fromDbRemoteDocument = function (remoteDoc) {\n if (remoteDoc.document) {\n return this.remoteSerializer.fromDocument(remoteDoc.document);\n }\n else if (remoteDoc.noDocument) {\n var key = DocumentKey.fromSegments(remoteDoc.noDocument.path);\n var readTime = remoteDoc.noDocument.readTime;\n var timestamp = new Timestamp(readTime.seconds, readTime.nanos);\n return new NoDocument(key, SnapshotVersion.fromTimestamp(timestamp));\n }\n else {\n return fail('Unexpected DbRemoteDocument');\n }\n };\n /** Encodes a document for storage locally. */\n LocalSerializer.prototype.toDbRemoteDocument = function (maybeDoc) {\n if (maybeDoc instanceof Document) {\n var doc = this.remoteSerializer.toDocument(maybeDoc);\n return new DbRemoteDocument(null, doc);\n }\n else {\n var path = maybeDoc.key.path.toArray();\n var timestamp = maybeDoc.version.toTimestamp();\n var readTime = new DbTimestamp(timestamp.seconds, timestamp.nanos);\n return new DbRemoteDocument(new DbNoDocument(path, readTime), null);\n }\n };\n /** Encodes a batch of mutations into a DbMutationBatch for local storage. */\n LocalSerializer.prototype.toDbMutationBatch = function (userId, batch) {\n var _this = this;\n var serializedMutations = batch.mutations.map(function (m) {\n return _this.remoteSerializer.toMutation(m);\n });\n return new DbMutationBatch(userId, batch.batchId, batch.localWriteTime.toEpochMilliseconds(), serializedMutations);\n };\n /** Decodes a DbMutationBatch into a MutationBatch */\n LocalSerializer.prototype.fromDbMutationBatch = function (dbBatch) {\n var _this = this;\n var mutations = dbBatch.mutations.map(function (m) {\n return _this.remoteSerializer.fromMutation(m);\n });\n var timestamp = Timestamp.fromEpochMilliseconds(dbBatch.localWriteTimeMs);\n return new MutationBatch(dbBatch.batchId, timestamp, mutations);\n };\n /** Decodes a DbTarget into QueryData */\n LocalSerializer.prototype.fromDbTarget = function (dbTarget) {\n var readTime = new Timestamp(dbTarget.readTime.seconds, dbTarget.readTime.nanos);\n var version = SnapshotVersion.fromTimestamp(readTime);\n var query;\n if (isDocumentQuery(dbTarget.query)) {\n query = this.remoteSerializer.fromDocumentsTarget(dbTarget.query);\n }\n else {\n query = this.remoteSerializer.fromQueryTarget(dbTarget.query);\n }\n return new QueryData(query, dbTarget.targetId, QueryPurpose.Listen, version, dbTarget.resumeToken);\n };\n /** Encodes QueryData into a DbTarget for storage locally. */\n LocalSerializer.prototype.toDbTarget = function (queryData) {\n assert(QueryPurpose.Listen === queryData.purpose, 'Only queries with purpose ' +\n QueryPurpose.Listen +\n ' may be stored, got ' +\n queryData.purpose);\n var timestamp = queryData.snapshotVersion.toTimestamp();\n var dbTimestamp = new DbTimestamp(timestamp.seconds, timestamp.nanos);\n var queryProto;\n if (queryData.query.isDocumentQuery()) {\n queryProto = this.remoteSerializer.toDocumentsTarget(queryData.query);\n }\n else {\n queryProto = this.remoteSerializer.toQueryTarget(queryData.query);\n }\n assert(typeof queryData.resumeToken === 'string', 'Persisting non-string resume token not supported.');\n var resumeToken = queryData.resumeToken;\n // lastListenSequenceNumber is always 0 until we do real GC.\n return new DbTarget(queryData.targetId, queryData.query.canonicalId(), dbTimestamp, resumeToken, 0, queryProto);\n };\n return LocalSerializer;\n}());\nexport { LocalSerializer };\n/**\n * A helper function for figuring out what kind of query has been stored.\n */\nfunction isDocumentQuery(dbQuery) {\n return dbQuery.documents !== undefined;\n}\n\n//# sourceMappingURL=local_serializer.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/local_serializer.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { User } from '../auth/user';\nimport { assert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nvar OAuthToken = /** @class */ (function () {\n function OAuthToken(value, user) {\n this.user = user;\n this.type = 'OAuth';\n this.authHeaders = { Authorization: \"Bearer \" + value };\n }\n return OAuthToken;\n}());\nexport { OAuthToken };\n/** A CredentialsProvider that always yields an empty token. */\nvar EmptyCredentialsProvider = /** @class */ (function () {\n function EmptyCredentialsProvider() {\n /**\n * Stores the User listener registered with setUserChangeListener()\n * This isn't actually necessary since the UID never changes, but we use this\n * to verify the listen contract is adhered to in tests.\n */\n this.userListener = null;\n }\n EmptyCredentialsProvider.prototype.getToken = function (forceRefresh) {\n return Promise.resolve(null);\n };\n EmptyCredentialsProvider.prototype.setUserChangeListener = function (listener) {\n assert(!this.userListener, 'Can only call setUserChangeListener() once.');\n this.userListener = listener;\n // Fire with initial user.\n listener(User.UNAUTHENTICATED);\n };\n EmptyCredentialsProvider.prototype.removeUserChangeListener = function () {\n assert(this.userListener !== null, 'removeUserChangeListener() when no listener registered');\n this.userListener = null;\n };\n return EmptyCredentialsProvider;\n}());\nexport { EmptyCredentialsProvider };\nvar FirebaseCredentialsProvider = /** @class */ (function () {\n function FirebaseCredentialsProvider(app) {\n var _this = this;\n this.app = app;\n /**\n * The auth token listener registered with FirebaseApp, retained here so we\n * can unregister it.\n */\n this.tokenListener = null;\n /**\n * Counter used to detect if the user changed while a getToken request was\n * outstanding.\n */\n this.userCounter = 0;\n /** The User listener registered with setUserChangeListener(). */\n this.userListener = null;\n // We listen for token changes but all we really care about is knowing when\n // the uid may have changed.\n this.tokenListener = function () {\n var newUser = _this.getUser();\n if (!_this.currentUser || !newUser.isEqual(_this.currentUser)) {\n _this.currentUser = newUser;\n _this.userCounter++;\n if (_this.userListener) {\n _this.userListener(_this.currentUser);\n }\n }\n };\n this.userCounter = 0;\n // Will fire at least once where we set this.currentUser\n this.app.INTERNAL.addAuthTokenListener(this.tokenListener);\n }\n FirebaseCredentialsProvider.prototype.getToken = function (forceRefresh) {\n var _this = this;\n assert(this.tokenListener != null, 'getToken cannot be called after listener removed.');\n // Take note of the current value of the userCounter so that this method can\n // fail (with an ABORTED error) if there is a user change while the request\n // is outstanding.\n var initialUserCounter = this.userCounter;\n return this.app.INTERNAL.getToken(forceRefresh).then(function (tokenData) {\n // Cancel the request since the user changed while the request was\n // outstanding so the response is likely for a previous user (which\n // user, we can't be sure).\n if (_this.userCounter !== initialUserCounter) {\n throw new FirestoreError(Code.ABORTED, 'getToken aborted due to uid change.');\n }\n else {\n if (tokenData) {\n assert(typeof tokenData.accessToken === 'string', 'Invalid tokenData returned from getToken():' + tokenData);\n return new OAuthToken(tokenData.accessToken, _this.currentUser);\n }\n else {\n return null;\n }\n }\n });\n };\n FirebaseCredentialsProvider.prototype.setUserChangeListener = function (listener) {\n assert(!this.userListener, 'Can only call setUserChangeListener() once.');\n this.userListener = listener;\n // Fire the initial event, but only if we received the initial user\n if (this.currentUser) {\n listener(this.currentUser);\n }\n };\n FirebaseCredentialsProvider.prototype.removeUserChangeListener = function () {\n assert(this.tokenListener != null, 'removeUserChangeListener() called twice');\n assert(this.userListener !== null, 'removeUserChangeListener() called when no listener registered');\n this.app.INTERNAL.removeAuthTokenListener(this.tokenListener);\n this.tokenListener = null;\n this.userListener = null;\n };\n FirebaseCredentialsProvider.prototype.getUser = function () {\n // TODO(mikelehen): Remove this check once we're shipping with firebase.js.\n if (typeof this.app.INTERNAL.getUid !== 'function') {\n fail('This version of the Firestore SDK requires at least version' +\n ' 3.7.0 of firebase.js.');\n }\n var currentUid = this.app.INTERNAL.getUid();\n assert(currentUid === null || typeof currentUid === 'string', 'Received invalid UID: ' + currentUid);\n return new User(currentUid);\n };\n return FirebaseCredentialsProvider;\n}());\nexport { FirebaseCredentialsProvider };\n/*\n * FirstPartyToken provides a fresh token each time its value\n * is requested, because if the token is too old, requests will be rejected.\n * TODO(b/33147818) this implementation violates the current assumption that\n * tokens are immutable. We need to either revisit this assumption or come\n * up with some way for FPA to use the listen/unlisten interface.\n */\nvar FirstPartyToken = /** @class */ (function () {\n function FirstPartyToken(gapi, sessionIndex) {\n this.gapi = gapi;\n this.sessionIndex = sessionIndex;\n this.type = 'FirstParty';\n this.user = User.FIRST_PARTY;\n assert(this.gapi &&\n this.gapi['auth'] &&\n this.gapi['auth']['getAuthHeaderValueForFirstParty'], 'unexpected gapi interface');\n }\n Object.defineProperty(FirstPartyToken.prototype, \"authHeaders\", {\n get: function () {\n return {\n Authorization: this.gapi['auth']['getAuthHeaderValueForFirstParty']([]),\n 'X-Goog-AuthUser': this.sessionIndex\n };\n },\n enumerable: true,\n configurable: true\n });\n return FirstPartyToken;\n}());\nexport { FirstPartyToken };\n/*\n * Provides user credentials required for the Firestore JavaScript SDK\n * to authenticate the user, using technique that is only available\n * to applications hosted by Google.\n */\nvar FirstPartyCredentialsProvider = /** @class */ (function () {\n function FirstPartyCredentialsProvider(gapi, sessionIndex) {\n this.gapi = gapi;\n this.sessionIndex = sessionIndex;\n assert(this.gapi &&\n this.gapi['auth'] &&\n this.gapi['auth']['getAuthHeaderValueForFirstParty'], 'unexpected gapi interface');\n }\n FirstPartyCredentialsProvider.prototype.getToken = function (forceRefresh) {\n return Promise.resolve(new FirstPartyToken(this.gapi, this.sessionIndex));\n };\n // TODO(33108925): can someone switch users w/o a page refresh?\n // TODO(33110621): need to understand token/session lifecycle\n FirstPartyCredentialsProvider.prototype.setUserChangeListener = function (listener) {\n // Fire with initial uid.\n listener(User.FIRST_PARTY);\n };\n FirstPartyCredentialsProvider.prototype.removeUserChangeListener = function () { };\n return FirstPartyCredentialsProvider;\n}());\nexport { FirstPartyCredentialsProvider };\n/**\n * Builds a CredentialsProvider depending on the type of\n * the credentials passed in.\n */\nexport function makeCredentialsProvider(credentials) {\n if (!credentials) {\n return new EmptyCredentialsProvider();\n }\n switch (credentials.type) {\n case 'gapi':\n return new FirstPartyCredentialsProvider(credentials.client, credentials.sessionIndex || '0');\n case 'provider':\n return credentials.client;\n default:\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'makeCredentialsProvider failed due to invalid credential type');\n }\n}\n\n//# sourceMappingURL=credentials.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/api/credentials.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport function isPartialObserver(obj) {\n return implementsAnyMethods(obj, ['next', 'error', 'complete']);\n}\n/**\n * Returns true if obj is an object and contains at least one of the specified\n * methods.\n */\nfunction implementsAnyMethods(obj, methods) {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n var object = obj;\n for (var _i = 0, methods_1 = methods; _i < methods_1.length; _i++) {\n var method = methods_1[_i];\n if (method in object && typeof object[method] === 'function') {\n return true;\n }\n }\n return false;\n}\n\n//# sourceMappingURL=observer.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/api/observer.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Timestamp } from '../core/timestamp';\nimport { ObjectValue } from '../model/field_value';\nimport { ArrayValue, BlobValue, BooleanValue, DoubleValue, GeoPointValue, IntegerValue, NullValue, RefValue, StringValue, TimestampValue } from '../model/field_value';\nimport { FieldMask, FieldTransform, PatchMutation, ServerTimestampTransform, SetMutation, TransformMutation } from '../model/mutation';\nimport { FieldPath } from '../model/path';\nimport { assert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { isPlainObject, valueDescription } from '../util/input_validation';\nimport { primitiveComparator } from '../util/misc';\nimport * as objUtils from '../util/obj';\nimport { SortedMap } from '../util/sorted_map';\nimport * as typeUtils from '../util/types';\nimport { Blob } from './blob';\nimport { FieldPath as ExternalFieldPath, fromDotSeparatedString } from './field_path';\nimport { DeleteFieldValueImpl, FieldValueImpl, ServerTimestampFieldValueImpl } from './field_value';\nimport { GeoPoint } from './geo_point';\nvar RESERVED_FIELD_REGEX = /^__.*__$/;\n/** The result of parsing document data (e.g. for a setData call). */\nvar ParsedSetData = /** @class */ (function () {\n function ParsedSetData(data, fieldMask, fieldTransforms) {\n this.data = data;\n this.fieldMask = fieldMask;\n this.fieldTransforms = fieldTransforms;\n }\n ParsedSetData.prototype.toMutations = function (key, precondition) {\n var mutations = [];\n if (this.fieldMask !== null) {\n mutations.push(new PatchMutation(key, this.data, this.fieldMask, precondition));\n }\n else {\n mutations.push(new SetMutation(key, this.data, precondition));\n }\n if (this.fieldTransforms.length > 0) {\n mutations.push(new TransformMutation(key, this.fieldTransforms));\n }\n return mutations;\n };\n return ParsedSetData;\n}());\nexport { ParsedSetData };\n/** The result of parsing \"update\" data (i.e. for an updateData call). */\nvar ParsedUpdateData = /** @class */ (function () {\n function ParsedUpdateData(data, fieldMask, fieldTransforms) {\n this.data = data;\n this.fieldMask = fieldMask;\n this.fieldTransforms = fieldTransforms;\n }\n ParsedUpdateData.prototype.toMutations = function (key, precondition) {\n var mutations = [\n new PatchMutation(key, this.data, this.fieldMask, precondition)\n ];\n if (this.fieldTransforms.length > 0) {\n mutations.push(new TransformMutation(key, this.fieldTransforms));\n }\n return mutations;\n };\n return ParsedUpdateData;\n}());\nexport { ParsedUpdateData };\n/*\n * Represents what type of API method provided the data being parsed; useful\n * for determining which error conditions apply during parsing and providing\n * better error messages.\n */\nvar UserDataSource;\n(function (UserDataSource) {\n UserDataSource[UserDataSource[\"Set\"] = 0] = \"Set\";\n UserDataSource[UserDataSource[\"Update\"] = 1] = \"Update\";\n UserDataSource[UserDataSource[\"MergeSet\"] = 2] = \"MergeSet\";\n UserDataSource[UserDataSource[\"QueryValue\"] = 3] = \"QueryValue\"; // from a where clause or cursor bound\n})(UserDataSource || (UserDataSource = {}));\nfunction isWrite(dataSource) {\n switch (dataSource) {\n case UserDataSource.Set: // fall through\n case UserDataSource.MergeSet: // fall through\n case UserDataSource.Update:\n return true;\n case UserDataSource.QueryValue:\n return false;\n default:\n throw fail(\"Unexpected case for UserDataSource: \" + dataSource);\n }\n}\n/** A \"context\" object passed around while parsing user data. */\nvar ParseContext = /** @class */ (function () {\n /**\n * Initializes a ParseContext with the given source and path.\n *\n * @param dataSource Indicates what kind of API method this data came from.\n * @param methodName The name of the method the user called to create this\n * ParseContext.\n * @param path A path within the object being parsed. This could be an empty\n * path (in which case the context represents the root of the data being\n * parsed), or a nonempty path (indicating the context represents a nested\n * location within the data).\n * @param arrayElement Whether or not this context corresponds to an element\n * of an array.\n * @param fieldTransforms A mutable list of field transforms encountered while\n * parsing the data.\n * @param fieldMask A mutable list of field paths encountered while parsing\n * the data.\n *\n * TODO(b/34871131): We don't support array paths right now, so path can be\n * null to indicate the context represents any location within an array (in\n * which case certain features will not work and errors will be somewhat\n * compromised).\n */\n function ParseContext(dataSource, methodName, path, arrayElement, fieldTransforms, fieldMask) {\n this.dataSource = dataSource;\n this.methodName = methodName;\n this.path = path;\n this.arrayElement = arrayElement;\n // Minor hack: If fieldTransforms is undefined, we assume this is an\n // external call and we need to validate the entire path.\n if (fieldTransforms === undefined) {\n this.validatePath();\n }\n this.arrayElement = arrayElement !== undefined ? arrayElement : false;\n this.fieldTransforms = fieldTransforms || [];\n this.fieldMask = fieldMask || [];\n }\n ParseContext.prototype.childContextForField = function (field) {\n var childPath = this.path == null ? null : this.path.child(field);\n var context = new ParseContext(this.dataSource, this.methodName, childPath, \n /*arrayElement=*/ false, this.fieldTransforms, this.fieldMask);\n context.validatePathSegment(field);\n return context;\n };\n ParseContext.prototype.childContextForFieldPath = function (field) {\n var childPath = this.path == null ? null : this.path.child(field);\n var context = new ParseContext(this.dataSource, this.methodName, childPath, \n /*arrayElement=*/ false, this.fieldTransforms, this.fieldMask);\n context.validatePath();\n return context;\n };\n ParseContext.prototype.childContextForArray = function (index) {\n // TODO(b/34871131): We don't support array paths right now; so make path\n // null.\n return new ParseContext(this.dataSource, this.methodName, \n /*path=*/ null, \n /*arrayElement=*/ true, this.fieldTransforms, this.fieldMask);\n };\n ParseContext.prototype.createError = function (reason) {\n var fieldDescription = this.path === null || this.path.isEmpty()\n ? ''\n : \" (found in field \" + this.path.toString() + \")\";\n return new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + this.methodName + \"() called with invalid data. \" +\n reason +\n fieldDescription);\n };\n ParseContext.prototype.validatePath = function () {\n // TODO(b/34871131): Remove null check once we have proper paths for fields\n // within arrays.\n if (this.path === null) {\n return;\n }\n for (var i = 0; i < this.path.length; i++) {\n this.validatePathSegment(this.path.get(i));\n }\n };\n ParseContext.prototype.validatePathSegment = function (segment) {\n if (isWrite(this.dataSource) && RESERVED_FIELD_REGEX.test(segment)) {\n throw this.createError('Document fields cannot begin and end with __');\n }\n };\n ParseContext.prototype.isWrite = function () {\n return (this.dataSource === UserDataSource.Set ||\n this.dataSource === UserDataSource.Update);\n };\n return ParseContext;\n}());\n/**\n * A placeholder object for DocumentReferences in this file, in order to\n * avoid a circular dependency. See the comments for `DataPreConverter` for\n * the full context.\n */\nvar DocumentKeyReference = /** @class */ (function () {\n function DocumentKeyReference(databaseId, key) {\n this.databaseId = databaseId;\n this.key = key;\n }\n return DocumentKeyReference;\n}());\nexport { DocumentKeyReference };\n/**\n * Helper for parsing raw user input (provided via the API) into internal model\n * classes.\n */\nvar UserDataConverter = /** @class */ (function () {\n function UserDataConverter(preConverter) {\n this.preConverter = preConverter;\n }\n /** Parse document data from a non-merge set() call. */\n UserDataConverter.prototype.parseSetData = function (methodName, input) {\n var context = new ParseContext(UserDataSource.Set, methodName, FieldPath.EMPTY_PATH);\n validatePlainObject('Data must be an object, but it was:', context, input);\n var updateData = this.parseData(input, context);\n return new ParsedSetData(updateData, \n /* fieldMask= */ null, context.fieldTransforms);\n };\n /** Parse document data from a set() call with '{merge:true}'. */\n UserDataConverter.prototype.parseMergeData = function (methodName, input) {\n var context = new ParseContext(UserDataSource.MergeSet, methodName, FieldPath.EMPTY_PATH);\n validatePlainObject('Data must be an object, but it was:', context, input);\n var updateData = this.parseData(input, context);\n var fieldMask = new FieldMask(context.fieldMask);\n return new ParsedSetData(updateData, fieldMask, context.fieldTransforms);\n };\n /** Parse update data from an update() call. */\n UserDataConverter.prototype.parseUpdateData = function (methodName, input) {\n var _this = this;\n var context = new ParseContext(UserDataSource.Update, methodName, FieldPath.EMPTY_PATH);\n validatePlainObject('Data must be an object, but it was:', context, input);\n var fieldMaskPaths = [];\n var updateData = ObjectValue.EMPTY;\n objUtils.forEach(input, function (key, value) {\n var path = fieldPathFromDotSeparatedString(methodName, key);\n var childContext = context.childContextForFieldPath(path);\n value = _this.runPreConverter(value, childContext);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n }\n else {\n var parsedValue = _this.parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData = updateData.set(path, parsedValue);\n }\n }\n });\n var mask = new FieldMask(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n };\n /** Parse update data from a list of field/value arguments. */\n UserDataConverter.prototype.parseUpdateVarargs = function (methodName, field, value, moreFieldsAndValues) {\n var context = new ParseContext(UserDataSource.Update, methodName, FieldPath.EMPTY_PATH);\n var keys = [fieldPathFromArgument(methodName, field)];\n var values = [value];\n if (moreFieldsAndValues.length % 2 !== 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + methodName + \"() needs to be called with an even number \" +\n 'of arguments that alternate between field names and values.');\n }\n for (var i = 0; i < moreFieldsAndValues.length; i += 2) {\n keys.push(fieldPathFromArgument(methodName, moreFieldsAndValues[i]));\n values.push(moreFieldsAndValues[i + 1]);\n }\n var fieldMaskPaths = [];\n var updateData = ObjectValue.EMPTY;\n for (var i = 0; i < keys.length; ++i) {\n var path = keys[i];\n var childContext = context.childContextForFieldPath(path);\n var value_1 = this.runPreConverter(values[i], childContext);\n if (value_1 instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n }\n else {\n var parsedValue = this.parseData(value_1, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData = updateData.set(path, parsedValue);\n }\n }\n }\n var mask = new FieldMask(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n };\n /**\n * Parse a \"query value\" (e.g. value in a where filter or a value in a cursor\n * bound).\n */\n UserDataConverter.prototype.parseQueryValue = function (methodName, input) {\n var context = new ParseContext(UserDataSource.QueryValue, methodName, FieldPath.EMPTY_PATH);\n var parsed = this.parseData(input, context);\n assert(parsed != null, 'Parsed data should not be null.');\n assert(context.fieldTransforms.length === 0, 'Field transforms should have been disallowed.');\n return parsed;\n };\n /** Sends data through this.preConverter, handling any thrown errors. */\n UserDataConverter.prototype.runPreConverter = function (input, context) {\n try {\n return this.preConverter(input);\n }\n catch (e) {\n var message = errorMessage(e);\n throw context.createError(message);\n }\n };\n /**\n * Internal helper for parsing user data.\n *\n * @param input Data to be parsed.\n * @param context A context object representing the current path being parsed,\n * the source of the data being parsed, etc.\n * @return The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */\n UserDataConverter.prototype.parseData = function (input, context) {\n input = this.runPreConverter(input, context);\n if (input instanceof Array) {\n // TODO(b/34871131): Include the path containing the array in the error\n // message.\n if (context.arrayElement) {\n throw context.createError('Nested arrays are not supported');\n }\n // If context.path is null we are already inside an array and we don't\n // support field mask paths more granular than the top-level array.\n if (context.path) {\n context.fieldMask.push(context.path);\n }\n return this.parseArray(input, context);\n }\n else if (looksLikeJsonObject(input)) {\n validatePlainObject('Unsupported field value:', context, input);\n return this.parseObject(input, context);\n }\n else {\n // If context.path is null, we are inside an array and we should have\n // already added the root of the array to the field mask.\n if (context.path) {\n context.fieldMask.push(context.path);\n }\n return this.parseScalarValue(input, context);\n }\n };\n UserDataConverter.prototype.parseArray = function (array, context) {\n var result = [];\n var entryIndex = 0;\n for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {\n var entry = array_1[_i];\n var parsedEntry = this.parseData(entry, context.childContextForArray(entryIndex));\n if (parsedEntry == null) {\n // Just include nulls in the array for fields being replaced with a\n // sentinel.\n parsedEntry = NullValue.INSTANCE;\n }\n result.push(parsedEntry);\n entryIndex++;\n }\n return new ArrayValue(result);\n };\n UserDataConverter.prototype.parseObject = function (obj, context) {\n var _this = this;\n var result = new SortedMap(primitiveComparator);\n objUtils.forEach(obj, function (key, val) {\n var parsedValue = _this.parseData(val, context.childContextForField(key));\n if (parsedValue != null) {\n result = result.insert(key, parsedValue);\n }\n });\n return new ObjectValue(result);\n };\n /**\n * Helper to parse a scalar value (i.e. not an Object or Array)\n *\n * @return The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */\n UserDataConverter.prototype.parseScalarValue = function (value, context) {\n if (value === null) {\n return NullValue.INSTANCE;\n }\n else if (typeof value === 'number') {\n if (typeUtils.isSafeInteger(value)) {\n return new IntegerValue(value);\n }\n else {\n return new DoubleValue(value);\n }\n }\n else if (typeof value === 'boolean') {\n return BooleanValue.of(value);\n }\n else if (typeof value === 'string') {\n return new StringValue(value);\n }\n else if (value instanceof Date) {\n return new TimestampValue(Timestamp.fromDate(value));\n }\n else if (value instanceof GeoPoint) {\n return new GeoPointValue(value);\n }\n else if (value instanceof Blob) {\n return new BlobValue(value);\n }\n else if (value instanceof DocumentKeyReference) {\n return new RefValue(value.databaseId, value.key);\n }\n else if (value instanceof FieldValueImpl) {\n if (value instanceof DeleteFieldValueImpl) {\n if (context.dataSource === UserDataSource.MergeSet) {\n return null;\n }\n else if (context.dataSource === UserDataSource.Update) {\n assert(context.path == null || context.path.length > 0, 'FieldValue.delete() at the top level should have already' +\n ' been handled.');\n throw context.createError('FieldValue.delete() can only appear at the top level ' +\n 'of your update data');\n }\n else {\n // We shouldn't encounter delete sentinels for queries or non-merge set() calls.\n throw context.createError('FieldValue.delete() can only be used with update() and set() with {merge:true}');\n }\n }\n else if (value instanceof ServerTimestampFieldValueImpl) {\n if (!isWrite(context.dataSource)) {\n throw context.createError('FieldValue.serverTimestamp() can only be used with set()' +\n ' and update()');\n }\n if (context.path === null) {\n throw context.createError('FieldValue.serverTimestamp() is not currently' +\n ' supported inside arrays');\n }\n context.fieldTransforms.push(new FieldTransform(context.path, ServerTimestampTransform.instance));\n // Return null so this value is omitted from the parsed result.\n return null;\n }\n else {\n return fail('Unknown FieldValue type: ' + value);\n }\n }\n else {\n throw context.createError(\"Unsupported field value: \" + valueDescription(value));\n }\n };\n return UserDataConverter;\n}());\nexport { UserDataConverter };\n/**\n * Checks whether an object looks like a JSON object that should be converted\n * into a struct. Normal class/prototype instances are considered to look like\n * JSON objects since they should be converted to a struct value. Arrays, Dates,\n * GeoPoints, etc. are not considered to look like JSON objects since they map\n * to specific FieldValue types other than ObjectValue.\n */\nfunction looksLikeJsonObject(input) {\n return (typeof input === 'object' &&\n input !== null &&\n !(input instanceof Array) &&\n !(input instanceof Date) &&\n !(input instanceof GeoPoint) &&\n !(input instanceof Blob) &&\n !(input instanceof DocumentKeyReference) &&\n !(input instanceof FieldValueImpl));\n}\nfunction validatePlainObject(message, context, input) {\n if (!looksLikeJsonObject(input) || !isPlainObject(input)) {\n var description = valueDescription(input);\n if (description === 'an object') {\n // Massage the error if it was an object.\n throw context.createError(message + ' a custom object');\n }\n else {\n throw context.createError(message + ' ' + description);\n }\n }\n}\n/**\n * Helper that calls fromDotSeparatedString() but wraps any error thrown.\n */\nexport function fieldPathFromArgument(methodName, path) {\n if (path instanceof ExternalFieldPath) {\n return path._internalPath;\n }\n else if (typeof path === 'string') {\n return fieldPathFromDotSeparatedString(methodName, path);\n }\n else {\n var message = 'Field path arguments must be of type string or FieldPath.';\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + methodName + \"() called with invalid data. \" + message);\n }\n}\n/**\n * Wraps fromDotSeparatedString with an error message about the method that\n * was thrown.\n * @param methodName The publicly visible method name\n * @param path The dot-separated string form of a field path which will be split\n * on dots.\n */\nfunction fieldPathFromDotSeparatedString(methodName, path) {\n try {\n return fromDotSeparatedString(path)._internalPath;\n }\n catch (e) {\n var message = errorMessage(e);\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + methodName + \"() called with invalid data. \" + message);\n }\n}\n/**\n * Extracts the message from a caught exception, which should be an Error object\n * though JS doesn't guarantee that.\n */\nfunction errorMessage(error) {\n return error instanceof Error ? error.message : error.toString();\n}\n\n//# sourceMappingURL=user_data_converter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/api/user_data_converter.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { FieldPath as ExternalFieldPath } from './field_path';\nimport { DatabaseId, DatabaseInfo } from '../core/database_info';\nimport { FirestoreClient } from '../core/firestore_client';\nimport { Bound, Direction, fieldFilter, OrderBy, Query as InternalQuery, RelationFilter, RelationOp } from '../core/query';\nimport { ChangeType } from '../core/view_snapshot';\nimport { NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { ArrayValue, FieldValueOptions, ObjectValue, RefValue } from '../model/field_value';\nimport { DeleteMutation, Precondition } from '../model/mutation';\nimport { ResourcePath } from '../model/path';\nimport { PlatformSupport } from '../platform/platform';\nimport { makeConstructorPrivate } from '../util/api';\nimport { assert, fail } from '../util/assert';\nimport { AsyncObserver } from '../util/async_observer';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { invalidClassError, validateArgType, validateAtLeastNumberOfArgs, validateBetweenNumberOfArgs, validateDefined, validateExactNumberOfArgs, validateNamedOptionalType, validateNamedOptionalPropertyEquals, validateNamedType, validateOptionalArgType, validateOptionNames, valueDescription } from '../util/input_validation';\nimport * as log from '../util/log';\nimport { LogLevel } from '../util/log';\nimport { AutoId } from '../util/misc';\nimport * as objUtils from '../util/obj';\nimport { EmptyCredentialsProvider, FirebaseCredentialsProvider, makeCredentialsProvider } from './credentials';\nimport { isPartialObserver } from './observer';\nimport { DocumentKeyReference, fieldPathFromArgument, UserDataConverter } from './user_data_converter';\n// The objects that are a part of this API are exposed to third-parties as\n// compiled javascript so we want to flag our private members with a leading\n// underscore to discourage their use.\n// tslint:disable:strip-private-property-underscore\nvar DEFAULT_HOST = 'firestore.googleapis.com';\nvar DEFAULT_SSL = true;\n/**\n * A concrete type describing all the values that can be applied via a\n * user-supplied firestore.Settings object. This is a separate type so that\n * defaults can be supplied and the value can be checked for equality.\n */\nvar FirestoreSettings = /** @class */ (function () {\n function FirestoreSettings(settings) {\n if (settings.host === undefined) {\n if (settings.ssl !== undefined) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Can't provide ssl option if host option is not set\");\n }\n this.host = DEFAULT_HOST;\n this.ssl = DEFAULT_SSL;\n }\n else {\n validateNamedType('settings', 'string', 'host', settings.host);\n this.host = settings.host;\n validateNamedOptionalType('settings', 'boolean', 'ssl', settings.ssl);\n this.ssl = objUtils.defaulted(settings.ssl, DEFAULT_SSL);\n }\n validateOptionNames('settings', settings, ['host', 'ssl', 'credentials']);\n validateNamedOptionalType('settings', 'object', 'credentials', settings.credentials);\n this.credentials = settings.credentials;\n }\n FirestoreSettings.prototype.isEqual = function (other) {\n return (this.host === other.host &&\n this.ssl === other.ssl &&\n this.credentials === other.credentials);\n };\n return FirestoreSettings;\n}());\nvar FirestoreConfig = /** @class */ (function () {\n function FirestoreConfig() {\n }\n return FirestoreConfig;\n}());\n/**\n * The root reference to the database.\n */\nvar Firestore = /** @class */ (function () {\n function Firestore(databaseIdOrApp) {\n var _this = this;\n this._queue = new AsyncQueue();\n this.INTERNAL = {\n delete: function () {\n if (_this._firestoreClient) {\n return _this._firestoreClient.shutdown();\n }\n else {\n return Promise.resolve();\n }\n },\n // Exposed via INTERNAL for use in tests.\n drainAsyncQueue: function (executeDelayedTasks) {\n return _this._queue.drain(executeDelayedTasks);\n }\n };\n var config = new FirestoreConfig();\n if (typeof databaseIdOrApp.options === 'object') {\n // This is very likely a Firebase app object\n // TODO(b/34177605): Can we somehow use instanceof?\n var app = databaseIdOrApp;\n config.firebaseApp = app;\n config.databaseId = Firestore.databaseIdFromApp(app);\n config.persistenceKey = config.firebaseApp.name;\n config.credentials = new FirebaseCredentialsProvider(app);\n }\n else {\n var external_1 = databaseIdOrApp;\n if (!external_1.projectId) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Must provide projectId');\n }\n config.databaseId = new DatabaseId(external_1.projectId, external_1.database);\n // Use a default persistenceKey that lines up with FirebaseApp.\n config.persistenceKey = '[DEFAULT]';\n config.credentials = new EmptyCredentialsProvider();\n }\n config.settings = new FirestoreSettings({});\n this._config = config;\n this._databaseId = config.databaseId;\n }\n Firestore.prototype.settings = function (settingsLiteral) {\n validateExactNumberOfArgs('Firestore.settings', arguments, 1);\n validateArgType('Firestore.settings', 'object', 1, settingsLiteral);\n if (objUtils.contains(settingsLiteral, 'persistence')) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, '\"persistence\" is now specified with a separate call to ' +\n 'firestore.enablePersistence().');\n }\n var newSettings = new FirestoreSettings(settingsLiteral);\n if (this._firestoreClient && !this._config.settings.isEqual(newSettings)) {\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore has already been started and its settings can no longer ' +\n 'be changed. You can only call settings() before calling any other ' +\n 'methods on a Firestore object.');\n }\n this._config.settings = newSettings;\n if (newSettings.credentials !== undefined) {\n this._config.credentials = makeCredentialsProvider(newSettings.credentials);\n }\n };\n Firestore.prototype.enableNetwork = function () {\n this.ensureClientConfigured();\n return this._firestoreClient.enableNetwork();\n };\n Firestore.prototype.disableNetwork = function () {\n this.ensureClientConfigured();\n return this._firestoreClient.disableNetwork();\n };\n Firestore.prototype.enablePersistence = function () {\n if (this._firestoreClient) {\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore has already been started and persistence can no longer ' +\n 'be enabled. You can only call enablePersistence() before calling ' +\n 'any other methods on a Firestore object.');\n }\n return this.configureClient(/* persistence= */ true);\n };\n Firestore.prototype.ensureClientConfigured = function () {\n if (!this._firestoreClient) {\n this.configureClient(/* persistence= */ false);\n }\n return this._firestoreClient;\n };\n Firestore.prototype.configureClient = function (persistence) {\n var _this = this;\n assert(!!this._config.settings.host, 'FirestoreSettings.host cannot be falsey');\n assert(!this._firestoreClient, 'configureClient() called multiple times');\n var databaseInfo = new DatabaseInfo(this._config.databaseId, this._config.persistenceKey, this._config.settings.host, this._config.settings.ssl);\n var preConverter = function (value) {\n if (value instanceof DocumentReference) {\n var thisDb = _this._config.databaseId;\n var otherDb = value.firestore._config.databaseId;\n if (!otherDb.isEqual(thisDb)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Document reference is for database ' +\n (otherDb.projectId + \"/\" + otherDb.database + \" but should be \") +\n (\"for database \" + thisDb.projectId + \"/\" + thisDb.database));\n }\n return new DocumentKeyReference(_this._config.databaseId, value._key);\n }\n else {\n return value;\n }\n };\n this._dataConverter = new UserDataConverter(preConverter);\n this._firestoreClient = new FirestoreClient(PlatformSupport.getPlatform(), databaseInfo, this._config.credentials, this._queue);\n return this._firestoreClient.start(persistence);\n };\n Firestore.databaseIdFromApp = function (app) {\n var options = app.options;\n if (!objUtils.contains(options, 'projectId')) {\n // TODO(b/62673263): We can safely remove the special handling of\n // 'firestoreId' once alpha testers have upgraded.\n if (objUtils.contains(options, 'firestoreId')) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, '\"firestoreId\" is now specified as \"projectId\" in ' +\n 'firebase.initializeApp.');\n }\n throw new FirestoreError(Code.INVALID_ARGUMENT, '\"projectId\" not provided in firebase.initializeApp.');\n }\n if (objUtils.contains(options, 'firestoreOptions')) {\n // TODO(b/62673263): We can safely remove the special handling of\n // 'firestoreOptions' once alpha testers have upgraded.\n throw new FirestoreError(Code.INVALID_ARGUMENT, '\"firestoreOptions\" values are now specified with ' +\n 'Firestore.settings()');\n }\n var projectId = options['projectId'];\n if (!projectId || typeof projectId !== 'string') {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'projectId must be a string in FirebaseApp.options');\n }\n return new DatabaseId(projectId);\n };\n Object.defineProperty(Firestore.prototype, \"app\", {\n get: function () {\n if (!this._config.firebaseApp) {\n throw new FirestoreError(Code.FAILED_PRECONDITION, \"Firestore was not initialized using the Firebase SDK. 'app' is \" +\n 'not available');\n }\n return this._config.firebaseApp;\n },\n enumerable: true,\n configurable: true\n });\n Firestore.prototype.collection = function (pathString) {\n validateExactNumberOfArgs('Firestore.collection', arguments, 1);\n validateArgType('Firestore.collection', 'string', 1, pathString);\n if (!pathString) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Must provide a non-empty collection path to collection()');\n }\n this.ensureClientConfigured();\n return new CollectionReference(ResourcePath.fromString(pathString), this);\n };\n Firestore.prototype.doc = function (pathString) {\n validateExactNumberOfArgs('Firestore.doc', arguments, 1);\n validateArgType('Firestore.doc', 'string', 1, pathString);\n if (!pathString) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Must provide a non-empty document path to doc()');\n }\n this.ensureClientConfigured();\n return DocumentReference.forPath(ResourcePath.fromString(pathString), this);\n };\n Firestore.prototype.runTransaction = function (updateFunction) {\n var _this = this;\n validateExactNumberOfArgs('Firestore.runTransaction', arguments, 1);\n validateArgType('Firestore.runTransaction', 'function', 1, updateFunction);\n return this.ensureClientConfigured().transaction(function (transaction) {\n return updateFunction(new Transaction(_this, transaction));\n });\n };\n Firestore.prototype.batch = function () {\n this.ensureClientConfigured();\n return new WriteBatch(this);\n };\n Object.defineProperty(Firestore, \"logLevel\", {\n get: function () {\n switch (log.getLogLevel()) {\n case LogLevel.DEBUG:\n return 'debug';\n case LogLevel.ERROR:\n return 'error';\n case LogLevel.SILENT:\n return 'silent';\n default:\n return fail('Unknown log level: ' + log.getLogLevel());\n }\n },\n enumerable: true,\n configurable: true\n });\n Firestore.setLogLevel = function (level) {\n validateExactNumberOfArgs('Firestore.setLogLevel', arguments, 1);\n validateArgType('Firestore.setLogLevel', 'string', 1, level);\n switch (level) {\n case 'debug':\n log.setLogLevel(log.LogLevel.DEBUG);\n break;\n case 'error':\n log.setLogLevel(log.LogLevel.ERROR);\n break;\n case 'silent':\n log.setLogLevel(log.LogLevel.SILENT);\n break;\n default:\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid log level: ' + level);\n }\n };\n return Firestore;\n}());\nexport { Firestore };\n/**\n * A reference to a transaction.\n */\nvar Transaction = /** @class */ (function () {\n function Transaction(_firestore, _transaction) {\n this._firestore = _firestore;\n this._transaction = _transaction;\n }\n Transaction.prototype.get = function (documentRef) {\n var _this = this;\n validateExactNumberOfArgs('Transaction.get', arguments, 1);\n var ref = validateReference('Transaction.get', documentRef, this._firestore);\n return this._transaction\n .lookup([ref._key])\n .then(function (docs) {\n if (!docs || docs.length !== 1) {\n return fail('Mismatch in docs returned from document lookup.');\n }\n var doc = docs[0];\n if (doc instanceof NoDocument) {\n return new DocumentSnapshot(_this._firestore, ref._key, null, false);\n }\n return new DocumentSnapshot(_this._firestore, ref._key, doc, false);\n });\n };\n Transaction.prototype.set = function (documentRef, value, options) {\n validateBetweenNumberOfArgs('Transaction.set', arguments, 2, 3);\n var ref = validateReference('Transaction.set', documentRef, this._firestore);\n options = validateSetOptions('Transaction.set', options);\n var parsed = options.merge\n ? this._firestore._dataConverter.parseMergeData('Transaction.set', value)\n : this._firestore._dataConverter.parseSetData('Transaction.set', value);\n this._transaction.set(ref._key, parsed);\n return this;\n };\n Transaction.prototype.update = function (documentRef, fieldOrUpdateData, value) {\n var moreFieldsAndValues = [];\n for (var _i = 3; _i < arguments.length; _i++) {\n moreFieldsAndValues[_i - 3] = arguments[_i];\n }\n var ref;\n var parsed;\n if (typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof ExternalFieldPath) {\n validateAtLeastNumberOfArgs('Transaction.update', arguments, 3);\n ref = validateReference('Transaction.update', documentRef, this._firestore);\n parsed = this._firestore._dataConverter.parseUpdateVarargs('Transaction.update', fieldOrUpdateData, value, moreFieldsAndValues);\n }\n else {\n validateExactNumberOfArgs('Transaction.update', arguments, 2);\n ref = validateReference('Transaction.update', documentRef, this._firestore);\n parsed = this._firestore._dataConverter.parseUpdateData('Transaction.update', fieldOrUpdateData);\n }\n this._transaction.update(ref._key, parsed);\n return this;\n };\n Transaction.prototype.delete = function (documentRef) {\n validateExactNumberOfArgs('Transaction.delete', arguments, 1);\n var ref = validateReference('Transaction.delete', documentRef, this._firestore);\n this._transaction.delete(ref._key);\n return this;\n };\n return Transaction;\n}());\nexport { Transaction };\nvar WriteBatch = /** @class */ (function () {\n function WriteBatch(_firestore) {\n this._firestore = _firestore;\n this._mutations = [];\n this._committed = false;\n }\n WriteBatch.prototype.set = function (documentRef, value, options) {\n validateBetweenNumberOfArgs('WriteBatch.set', arguments, 2, 3);\n this.verifyNotCommitted();\n var ref = validateReference('WriteBatch.set', documentRef, this._firestore);\n options = validateSetOptions('WriteBatch.set', options);\n var parsed = options.merge\n ? this._firestore._dataConverter.parseMergeData('WriteBatch.set', value)\n : this._firestore._dataConverter.parseSetData('WriteBatch.set', value);\n this._mutations = this._mutations.concat(parsed.toMutations(ref._key, Precondition.NONE));\n return this;\n };\n WriteBatch.prototype.update = function (documentRef, fieldOrUpdateData, value) {\n var moreFieldsAndValues = [];\n for (var _i = 3; _i < arguments.length; _i++) {\n moreFieldsAndValues[_i - 3] = arguments[_i];\n }\n this.verifyNotCommitted();\n var ref;\n var parsed;\n if (typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof ExternalFieldPath) {\n validateAtLeastNumberOfArgs('WriteBatch.update', arguments, 3);\n ref = validateReference('WriteBatch.update', documentRef, this._firestore);\n parsed = this._firestore._dataConverter.parseUpdateVarargs('WriteBatch.update', fieldOrUpdateData, value, moreFieldsAndValues);\n }\n else {\n validateExactNumberOfArgs('WriteBatch.update', arguments, 2);\n ref = validateReference('WriteBatch.update', documentRef, this._firestore);\n parsed = this._firestore._dataConverter.parseUpdateData('WriteBatch.update', fieldOrUpdateData);\n }\n this._mutations = this._mutations.concat(parsed.toMutations(ref._key, Precondition.exists(true)));\n return this;\n };\n WriteBatch.prototype.delete = function (documentRef) {\n validateExactNumberOfArgs('WriteBatch.delete', arguments, 1);\n this.verifyNotCommitted();\n var ref = validateReference('WriteBatch.delete', documentRef, this._firestore);\n this._mutations = this._mutations.concat(new DeleteMutation(ref._key, Precondition.NONE));\n return this;\n };\n WriteBatch.prototype.commit = function () {\n this.verifyNotCommitted();\n this._committed = true;\n if (this._mutations.length > 0) {\n return this._firestore.ensureClientConfigured().write(this._mutations);\n }\n else {\n return Promise.resolve();\n }\n };\n WriteBatch.prototype.verifyNotCommitted = function () {\n if (this._committed) {\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'A write batch can no longer be used after commit() ' +\n 'has been called.');\n }\n };\n return WriteBatch;\n}());\nexport { WriteBatch };\n/**\n * A reference to a particular document in a collection in the database.\n */\nvar DocumentReference = /** @class */ (function () {\n function DocumentReference(_key, firestore) {\n this._key = _key;\n this.firestore = firestore;\n this._firestoreClient = this.firestore.ensureClientConfigured();\n }\n DocumentReference.forPath = function (path, firestore) {\n if (path.length % 2 !== 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid document reference. Document ' +\n 'references must have an even number of segments, but ' +\n (path.canonicalString() + \" has \" + path.length));\n }\n return new DocumentReference(new DocumentKey(path), firestore);\n };\n Object.defineProperty(DocumentReference.prototype, \"id\", {\n get: function () {\n return this._key.path.lastSegment();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentReference.prototype, \"parent\", {\n get: function () {\n return new CollectionReference(this._key.path.popLast(), this.firestore);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentReference.prototype, \"path\", {\n get: function () {\n return this._key.path.canonicalString();\n },\n enumerable: true,\n configurable: true\n });\n DocumentReference.prototype.collection = function (pathString) {\n validateExactNumberOfArgs('DocumentReference.collection', arguments, 1);\n validateArgType('DocumentReference.collection', 'string', 1, pathString);\n if (!pathString) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Must provide a non-empty collection name to collection()');\n }\n var path = ResourcePath.fromString(pathString);\n return new CollectionReference(this._key.path.child(path), this.firestore);\n };\n DocumentReference.prototype.isEqual = function (other) {\n if (!(other instanceof DocumentReference)) {\n throw invalidClassError('isEqual', 'DocumentReference', 1, other);\n }\n return this.firestore === other.firestore && this._key.isEqual(other._key);\n };\n DocumentReference.prototype.set = function (value, options) {\n validateBetweenNumberOfArgs('DocumentReference.set', arguments, 1, 2);\n options = validateSetOptions('DocumentReference.set', options);\n var parsed = options.merge\n ? this.firestore._dataConverter.parseMergeData('DocumentReference.set', value)\n : this.firestore._dataConverter.parseSetData('DocumentReference.set', value);\n return this._firestoreClient.write(parsed.toMutations(this._key, Precondition.NONE));\n };\n DocumentReference.prototype.update = function (fieldOrUpdateData, value) {\n var moreFieldsAndValues = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n moreFieldsAndValues[_i - 2] = arguments[_i];\n }\n var parsed;\n if (typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof ExternalFieldPath) {\n validateAtLeastNumberOfArgs('DocumentReference.update', arguments, 2);\n parsed = this.firestore._dataConverter.parseUpdateVarargs('DocumentReference.update', fieldOrUpdateData, value, moreFieldsAndValues);\n }\n else {\n validateExactNumberOfArgs('DocumentReference.update', arguments, 1);\n parsed = this.firestore._dataConverter.parseUpdateData('DocumentReference.update', fieldOrUpdateData);\n }\n return this._firestoreClient.write(parsed.toMutations(this._key, Precondition.exists(true)));\n };\n DocumentReference.prototype.delete = function () {\n validateExactNumberOfArgs('DocumentReference.delete', arguments, 0);\n return this._firestoreClient.write([\n new DeleteMutation(this._key, Precondition.NONE)\n ]);\n };\n DocumentReference.prototype.onSnapshot = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n validateBetweenNumberOfArgs('DocumentReference.onSnapshot', arguments, 1, 4);\n var options = {\n includeMetadataChanges: false\n };\n var observer;\n var currArg = 0;\n if (typeof args[currArg] === 'object' &&\n !isPartialObserver(args[currArg])) {\n options = args[currArg];\n validateOptionNames('DocumentReference.onSnapshot', options, [\n 'includeMetadataChanges'\n ]);\n validateNamedOptionalType('DocumentReference.onSnapshot', 'boolean', 'includeMetadataChanges', options.includeMetadataChanges);\n currArg++;\n }\n var internalOptions = {\n includeDocumentMetadataChanges: options.includeMetadataChanges,\n includeQueryMetadataChanges: options.includeMetadataChanges\n };\n if (isPartialObserver(args[currArg])) {\n observer = args[currArg];\n }\n else {\n validateArgType('DocumentReference.onSnapshot', 'function', currArg, args[currArg]);\n validateOptionalArgType('DocumentReference.onSnapshot', 'function', currArg + 1, args[currArg + 1]);\n validateOptionalArgType('DocumentReference.onSnapshot', 'function', currArg + 2, args[currArg + 2]);\n observer = {\n next: args[currArg],\n error: args[currArg + 1],\n complete: args[currArg + 2]\n };\n }\n return this.onSnapshotInternal(internalOptions, observer);\n };\n DocumentReference.prototype.onSnapshotInternal = function (options, observer) {\n var _this = this;\n var errHandler = function (err) {\n console.error('Uncaught Error in onSnapshot:', err);\n };\n if (observer.error) {\n errHandler = observer.error.bind(observer);\n }\n var asyncObserver = new AsyncObserver({\n next: function (snapshot) {\n if (observer.next) {\n assert(snapshot.docs.size <= 1, 'Too many documents returned on a document query');\n var doc = snapshot.docs.get(_this._key);\n observer.next(new DocumentSnapshot(_this.firestore, _this._key, doc, snapshot.fromCache));\n }\n },\n error: errHandler\n });\n var internalListener = this._firestoreClient.listen(InternalQuery.atPath(this._key.path), asyncObserver, options);\n return function () {\n asyncObserver.mute();\n _this._firestoreClient.unlisten(internalListener);\n };\n };\n DocumentReference.prototype.get = function () {\n var _this = this;\n validateExactNumberOfArgs('DocumentReference.get', arguments, 0);\n return new Promise(function (resolve, reject) {\n var unlisten = _this.onSnapshotInternal({\n includeQueryMetadataChanges: true,\n includeDocumentMetadataChanges: true,\n waitForSyncWhenOnline: true\n }, {\n next: function (snap) {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n unlisten();\n if (!snap.exists && snap.metadata.fromCache) {\n // TODO(dimond): If we're online and the document doesn't\n // exist then we resolve with a doc.exists set to false. If\n // we're offline however, we reject the Promise in this\n // case. Two options: 1) Cache the negative response from\n // the server so we can deliver that even when you're\n // offline 2) Actually reject the Promise in the online case\n // if the document doesn't exist.\n reject(new FirestoreError(Code.ABORTED, 'Failed to get document because the client is ' + 'offline.'));\n }\n else {\n resolve(snap);\n }\n },\n error: reject\n });\n });\n };\n return DocumentReference;\n}());\nexport { DocumentReference };\nvar SnapshotMetadata = /** @class */ (function () {\n function SnapshotMetadata(hasPendingWrites, fromCache) {\n this.hasPendingWrites = hasPendingWrites;\n this.fromCache = fromCache;\n }\n SnapshotMetadata.prototype.isEqual = function (other) {\n return (this.hasPendingWrites === other.hasPendingWrites &&\n this.fromCache === other.fromCache);\n };\n return SnapshotMetadata;\n}());\nvar DocumentSnapshot = /** @class */ (function () {\n function DocumentSnapshot(_firestore, _key, _document, _fromCache) {\n this._firestore = _firestore;\n this._key = _key;\n this._document = _document;\n this._fromCache = _fromCache;\n }\n DocumentSnapshot.prototype.data = function (options) {\n validateBetweenNumberOfArgs('DocumentSnapshot.data', arguments, 0, 1);\n options = validateSnapshotOptions('DocumentSnapshot.data', options);\n return !this._document\n ? undefined\n : this.convertObject(this._document.data, FieldValueOptions.fromSnapshotOptions(options));\n };\n DocumentSnapshot.prototype.get = function (fieldPath, options) {\n validateBetweenNumberOfArgs('DocumentSnapshot.get', arguments, 1, 2);\n options = validateSnapshotOptions('DocumentSnapshot.get', options);\n if (this._document) {\n var value = this._document.data.field(fieldPathFromArgument('DocumentSnapshot.get', fieldPath));\n if (value !== undefined) {\n return this.convertValue(value, FieldValueOptions.fromSnapshotOptions(options));\n }\n }\n return undefined;\n };\n Object.defineProperty(DocumentSnapshot.prototype, \"id\", {\n get: function () {\n return this._key.path.lastSegment();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentSnapshot.prototype, \"ref\", {\n get: function () {\n return new DocumentReference(this._key, this._firestore);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentSnapshot.prototype, \"exists\", {\n get: function () {\n return this._document !== null;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentSnapshot.prototype, \"metadata\", {\n get: function () {\n return new SnapshotMetadata(this._document !== null && this._document.hasLocalMutations, this._fromCache);\n },\n enumerable: true,\n configurable: true\n });\n DocumentSnapshot.prototype.isEqual = function (other) {\n if (!(other instanceof DocumentSnapshot)) {\n throw invalidClassError('isEqual', 'DocumentSnapshot', 1, other);\n }\n return (this._firestore === other._firestore &&\n this._fromCache === other._fromCache &&\n this._key.isEqual(other._key) &&\n (this._document === null\n ? other._document === null\n : this._document.isEqual(other._document)));\n };\n DocumentSnapshot.prototype.convertObject = function (data, options) {\n var _this = this;\n var result = {};\n data.forEach(function (key, value) {\n result[key] = _this.convertValue(value, options);\n });\n return result;\n };\n DocumentSnapshot.prototype.convertValue = function (value, options) {\n if (value instanceof ObjectValue) {\n return this.convertObject(value, options);\n }\n else if (value instanceof ArrayValue) {\n return this.convertArray(value, options);\n }\n else if (value instanceof RefValue) {\n var key = value.value(options);\n var database = this._firestore.ensureClientConfigured().databaseId();\n if (!value.databaseId.isEqual(database)) {\n // TODO(b/64130202): Somehow support foreign references.\n log.error(\"Document \" + this._key.path + \" contains a document \" +\n \"reference within a different database (\" +\n (value.databaseId.projectId + \"/\" + value.databaseId.database + \") which is not \") +\n \"supported. It will be treated as a reference in the current \" +\n (\"database (\" + database.projectId + \"/\" + database.database + \") \") +\n \"instead.\");\n }\n return new DocumentReference(key, this._firestore);\n }\n else {\n return value.value(options);\n }\n };\n DocumentSnapshot.prototype.convertArray = function (data, options) {\n var _this = this;\n return data.internalValue.map(function (value) {\n return _this.convertValue(value, options);\n });\n };\n return DocumentSnapshot;\n}());\nexport { DocumentSnapshot };\nvar QueryDocumentSnapshot = /** @class */ (function (_super) {\n __extends(QueryDocumentSnapshot, _super);\n function QueryDocumentSnapshot(firestore, key, document, fromCache) {\n return _super.call(this, firestore, key, document, fromCache) || this;\n }\n QueryDocumentSnapshot.prototype.data = function (options) {\n var data = _super.prototype.data.call(this, options);\n assert(typeof data === 'object', 'Document in a QueryDocumentSnapshot should exist');\n return data;\n };\n return QueryDocumentSnapshot;\n}(DocumentSnapshot));\nexport { QueryDocumentSnapshot };\nvar Query = /** @class */ (function () {\n function Query(_query, firestore) {\n this._query = _query;\n this.firestore = firestore;\n }\n Query.prototype.where = function (field, opStr, value) {\n validateExactNumberOfArgs('Query.where', arguments, 3);\n validateArgType('Query.where', 'string', 2, opStr);\n validateDefined('Query.where', 3, value);\n var fieldValue;\n var fieldPath = fieldPathFromArgument('Query.where', field);\n if (fieldPath.isKeyField()) {\n if (typeof value === 'string') {\n if (value.indexOf('/') !== -1) {\n // TODO(dimond): Allow slashes once ancestor queries are supported\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Function Query.where() requires its third parameter to be a ' +\n 'valid document ID if the first parameter is ' +\n 'FieldPath.documentId(), but it contains a slash.');\n }\n if (value === '') {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Function Query.where() requires its third parameter to be a ' +\n 'valid document ID if the first parameter is ' +\n 'FieldPath.documentId(), but it was an empty string.');\n }\n var path = this._query.path.child(new ResourcePath([value]));\n assert(path.length % 2 === 0, 'Path should be a document key');\n fieldValue = new RefValue(this.firestore._databaseId, new DocumentKey(path));\n }\n else if (value instanceof DocumentReference) {\n var ref = value;\n fieldValue = new RefValue(this.firestore._databaseId, ref._key);\n }\n else {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function Query.where() requires its third parameter to be a \" +\n \"string or a DocumentReference if the first parameter is \" +\n \"FieldPath.documentId(), but it was: \" +\n (valueDescription(value) + \".\"));\n }\n }\n else {\n fieldValue = this.firestore._dataConverter.parseQueryValue('Query.where', value);\n }\n var filter = fieldFilter(fieldPath, RelationOp.fromString(opStr), fieldValue);\n this.validateNewFilter(filter);\n return new Query(this._query.addFilter(filter), this.firestore);\n };\n Query.prototype.orderBy = function (field, directionStr) {\n validateBetweenNumberOfArgs('Query.orderBy', arguments, 1, 2);\n validateOptionalArgType('Query.orderBy', 'string', 2, directionStr);\n var direction;\n if (directionStr === undefined || directionStr === 'asc') {\n direction = Direction.ASCENDING;\n }\n else if (directionStr === 'desc') {\n direction = Direction.DESCENDING;\n }\n else {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function Query.orderBy() has unknown direction '\" + directionStr + \"', \" +\n \"expected 'asc' or 'desc'.\");\n }\n if (this._query.startAt !== null) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call Query.startAt() or ' +\n 'Query.startAfter() before calling Query.orderBy().');\n }\n if (this._query.endAt !== null) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call Query.endAt() or ' +\n 'Query.endBefore() before calling Query.orderBy().');\n }\n var fieldPath = fieldPathFromArgument('Query.orderBy', field);\n var orderBy = new OrderBy(fieldPath, direction);\n this.validateNewOrderBy(orderBy);\n return new Query(this._query.addOrderBy(orderBy), this.firestore);\n };\n Query.prototype.limit = function (n) {\n validateExactNumberOfArgs('Query.limit', arguments, 1);\n validateArgType('Query.limit', 'number', 1, n);\n if (n <= 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid Query. Query limit (\" + n + \") is invalid. Limit must be \" +\n 'positive.');\n }\n return new Query(this._query.withLimit(n), this.firestore);\n };\n Query.prototype.startAt = function (docOrField) {\n var fields = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n fields[_i - 1] = arguments[_i];\n }\n validateAtLeastNumberOfArgs('Query.startAt', arguments, 1);\n var bound = this.boundFromDocOrFields('Query.startAt', docOrField, fields, \n /*before=*/ true);\n return new Query(this._query.withStartAt(bound), this.firestore);\n };\n Query.prototype.startAfter = function (docOrField) {\n var fields = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n fields[_i - 1] = arguments[_i];\n }\n validateAtLeastNumberOfArgs('Query.startAfter', arguments, 1);\n var bound = this.boundFromDocOrFields('Query.startAfter', docOrField, fields, \n /*before=*/ false);\n return new Query(this._query.withStartAt(bound), this.firestore);\n };\n Query.prototype.endBefore = function (docOrField) {\n var fields = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n fields[_i - 1] = arguments[_i];\n }\n validateAtLeastNumberOfArgs('Query.endBefore', arguments, 1);\n var bound = this.boundFromDocOrFields('Query.endBefore', docOrField, fields, \n /*before=*/ true);\n return new Query(this._query.withEndAt(bound), this.firestore);\n };\n Query.prototype.endAt = function (docOrField) {\n var fields = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n fields[_i - 1] = arguments[_i];\n }\n validateAtLeastNumberOfArgs('Query.endAt', arguments, 1);\n var bound = this.boundFromDocOrFields('Query.endAt', docOrField, fields, \n /*before=*/ false);\n return new Query(this._query.withEndAt(bound), this.firestore);\n };\n Query.prototype.isEqual = function (other) {\n if (!(other instanceof Query)) {\n throw invalidClassError('isEqual', 'Query', 1, other);\n }\n return (this.firestore === other.firestore && this._query.isEqual(other._query));\n };\n /** Helper function to create a bound from a document or fields */\n Query.prototype.boundFromDocOrFields = function (methodName, docOrField, fields, before) {\n validateDefined(methodName, 1, docOrField);\n if (docOrField instanceof DocumentSnapshot) {\n if (fields.length > 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Too many arguments provided to \" + methodName + \"().\");\n }\n var snap = docOrField;\n if (!snap.exists) {\n throw new FirestoreError(Code.NOT_FOUND, \"Can't use a DocumentSnapshot that doesn't exist for \" +\n (methodName + \"().\"));\n }\n return this.boundFromDocument(methodName, snap._document, before);\n }\n else {\n var allFields = [docOrField].concat(fields);\n return this.boundFromFields(methodName, allFields, before);\n }\n };\n /**\n * Create a Bound from a query and a document.\n *\n * Note that the Bound will always include the key of the document\n * and so only the provided document will compare equal to the returned\n * position.\n *\n * Will throw if the document does not contain all fields of the order by\n * of the query.\n */\n Query.prototype.boundFromDocument = function (methodName, doc, before) {\n var components = [];\n // Because people expect to continue/end a query at the exact document\n // provided, we need to use the implicit sort order rather than the explicit\n // sort order, because it's guaranteed to contain the document key. That way\n // the position becomes unambiguous and the query continues/ends exactly at\n // the provided document. Without the key (by using the explicit sort\n // orders), multiple documents could match the position, yielding duplicate\n // results.\n for (var _i = 0, _a = this._query.orderBy; _i < _a.length; _i++) {\n var orderBy = _a[_i];\n if (orderBy.field.isKeyField()) {\n components.push(new RefValue(this.firestore._databaseId, doc.key));\n }\n else {\n var value = doc.field(orderBy.field);\n if (value !== undefined) {\n components.push(value);\n }\n else {\n var field = orderBy.field.canonicalString();\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. You are trying to start or end a query using a \" +\n (\"document for which the field '\" + field + \"' (used as the \") +\n \"orderBy) does not exist.\");\n }\n }\n }\n return new Bound(components, before);\n };\n /**\n * Converts a list of field values to a Bound for the given query.\n */\n Query.prototype.boundFromFields = function (methodName, values, before) {\n // Use explicit order by's because it has to match the query the user made\n var orderBy = this._query.explicitOrderBy;\n if (values.length > orderBy.length) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Too many arguments provided to \" + methodName + \"(). \" +\n \"The number of arguments must be less than or equal to the \" +\n \"number of Query.orderBy() clauses\");\n }\n var components = [];\n for (var i = 0; i < values.length; i++) {\n var rawValue = values[i];\n var orderByComponent = orderBy[i];\n if (orderByComponent.field.isKeyField()) {\n if (typeof rawValue !== 'string') {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. Expected a string for document ID in \" +\n (methodName + \"(), but got a \" + typeof rawValue));\n }\n if (rawValue.indexOf('/') !== -1) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. Document ID '\" + rawValue + \"' contains a slash in \" +\n (methodName + \"()\"));\n }\n var key = new DocumentKey(this._query.path.child(rawValue));\n components.push(new RefValue(this.firestore._databaseId, key));\n }\n else {\n var wrapped = this.firestore._dataConverter.parseQueryValue(methodName, rawValue);\n components.push(wrapped);\n }\n }\n return new Bound(components, before);\n };\n Query.prototype.onSnapshot = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n validateBetweenNumberOfArgs('Query.onSnapshot', arguments, 1, 4);\n var options = {};\n var observer;\n var currArg = 0;\n if (typeof args[currArg] === 'object' &&\n !isPartialObserver(args[currArg])) {\n options = args[currArg];\n validateOptionNames('Query.onSnapshot', options, [\n 'includeQueryMetadataChanges',\n 'includeDocumentMetadataChanges'\n ]);\n validateNamedOptionalType('Query.onSnapshot', 'boolean', 'includeDocumentMetadataChanges', options.includeDocumentMetadataChanges);\n validateNamedOptionalType('Query.onSnapshot', 'boolean', 'includeQueryMetadataChanges', options.includeQueryMetadataChanges);\n currArg++;\n }\n if (isPartialObserver(args[currArg])) {\n observer = args[currArg];\n }\n else {\n validateArgType('Query.onSnapshot', 'function', currArg, args[currArg]);\n validateOptionalArgType('Query.onSnapshot', 'function', currArg + 1, args[currArg + 1]);\n validateOptionalArgType('Query.onSnapshot', 'function', currArg + 2, args[currArg + 2]);\n observer = {\n next: args[currArg],\n error: args[currArg + 1],\n complete: args[currArg + 2]\n };\n }\n return this.onSnapshotInternal(options, observer);\n };\n Query.prototype.onSnapshotInternal = function (options, observer) {\n var _this = this;\n var errHandler = function (err) {\n console.error('Uncaught Error in onSnapshot:', err);\n };\n if (observer.error) {\n errHandler = observer.error.bind(observer);\n }\n var asyncObserver = new AsyncObserver({\n next: function (result) {\n if (observer.next) {\n observer.next(new QuerySnapshot(_this.firestore, _this._query, result));\n }\n },\n error: errHandler\n });\n var firestoreClient = this.firestore.ensureClientConfigured();\n var internalListener = firestoreClient.listen(this._query, asyncObserver, options);\n return function () {\n asyncObserver.mute();\n firestoreClient.unlisten(internalListener);\n };\n };\n Query.prototype.get = function () {\n var _this = this;\n validateExactNumberOfArgs('Query.get', arguments, 0);\n return new Promise(function (resolve, reject) {\n var unlisten = _this.onSnapshotInternal({\n includeDocumentMetadataChanges: false,\n includeQueryMetadataChanges: true,\n waitForSyncWhenOnline: true\n }, {\n next: function (result) {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n unlisten();\n resolve(result);\n },\n error: reject\n });\n });\n };\n Query.prototype.validateNewFilter = function (filter) {\n if (filter instanceof RelationFilter && filter.isInequality()) {\n var existingField = this._query.getInequalityFilterField();\n if (existingField !== null && !existingField.isEqual(filter.field)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. All where filters with an inequality' +\n ' (<, <=, >, or >=) must be on the same field. But you have' +\n (\" inequality filters on '\" + existingField.toString() + \"'\") +\n (\" and '\" + filter.field.toString() + \"'\"));\n }\n var firstOrderByField = this._query.getFirstOrderByField();\n if (firstOrderByField !== null) {\n this.validateOrderByAndInequalityMatch(filter.field, firstOrderByField);\n }\n }\n };\n Query.prototype.validateNewOrderBy = function (orderBy) {\n if (this._query.getFirstOrderByField() === null) {\n // This is the first order by. It must match any inequality.\n var inequalityField = this._query.getInequalityFilterField();\n if (inequalityField !== null) {\n this.validateOrderByAndInequalityMatch(inequalityField, orderBy.field);\n }\n }\n };\n Query.prototype.validateOrderByAndInequalityMatch = function (inequality, orderBy) {\n if (!orderBy.isEqual(inequality)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. You have a where filter with an inequality \" +\n (\"(<, <=, >, or >=) on field '\" + inequality.toString() + \"' \") +\n (\"and so you must also use '\" + inequality.toString() + \"' \") +\n \"as your first Query.orderBy(), but your first Query.orderBy() \" +\n (\"is on field '\" + orderBy.toString() + \"' instead.\"));\n }\n };\n return Query;\n}());\nexport { Query };\nvar QuerySnapshot = /** @class */ (function () {\n function QuerySnapshot(_firestore, _originalQuery, _snapshot) {\n this._firestore = _firestore;\n this._originalQuery = _originalQuery;\n this._snapshot = _snapshot;\n this._cachedChanges = null;\n this.metadata = new SnapshotMetadata(_snapshot.hasPendingWrites, _snapshot.fromCache);\n }\n Object.defineProperty(QuerySnapshot.prototype, \"docs\", {\n get: function () {\n var result = [];\n this.forEach(function (doc) { return result.push(doc); });\n return result;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(QuerySnapshot.prototype, \"empty\", {\n get: function () {\n return this._snapshot.docs.isEmpty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(QuerySnapshot.prototype, \"size\", {\n get: function () {\n return this._snapshot.docs.size;\n },\n enumerable: true,\n configurable: true\n });\n QuerySnapshot.prototype.forEach = function (callback, thisArg) {\n var _this = this;\n validateBetweenNumberOfArgs('QuerySnapshot.forEach', arguments, 1, 2);\n validateArgType('QuerySnapshot.forEach', 'function', 1, callback);\n this._snapshot.docs.forEach(function (doc) {\n callback.call(thisArg, _this.convertToDocumentImpl(doc));\n });\n };\n Object.defineProperty(QuerySnapshot.prototype, \"query\", {\n get: function () {\n return new Query(this._originalQuery, this._firestore);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(QuerySnapshot.prototype, \"docChanges\", {\n get: function () {\n if (!this._cachedChanges) {\n this._cachedChanges = changesFromSnapshot(this._firestore, this._snapshot);\n }\n return this._cachedChanges;\n },\n enumerable: true,\n configurable: true\n });\n /** Check the equality. The call can be very expensive. */\n QuerySnapshot.prototype.isEqual = function (other) {\n if (!(other instanceof QuerySnapshot)) {\n throw invalidClassError('isEqual', 'QuerySnapshot', 1, other);\n }\n return (this._firestore === other._firestore &&\n this._originalQuery.isEqual(other._originalQuery) &&\n this._snapshot.isEqual(other._snapshot));\n };\n QuerySnapshot.prototype.convertToDocumentImpl = function (doc) {\n return new QueryDocumentSnapshot(this._firestore, doc.key, doc, this.metadata.fromCache);\n };\n return QuerySnapshot;\n}());\nexport { QuerySnapshot };\nvar CollectionReference = /** @class */ (function (_super) {\n __extends(CollectionReference, _super);\n function CollectionReference(path, firestore) {\n var _this = _super.call(this, InternalQuery.atPath(path), firestore) || this;\n if (path.length % 2 !== 1) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid collection reference. Collection ' +\n 'references must have an odd number of segments, but ' +\n (path.canonicalString() + \" has \" + path.length));\n }\n return _this;\n }\n Object.defineProperty(CollectionReference.prototype, \"id\", {\n get: function () {\n return this._query.path.lastSegment();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(CollectionReference.prototype, \"parent\", {\n get: function () {\n var parentPath = this._query.path.popLast();\n if (parentPath.isEmpty()) {\n return null;\n }\n else {\n return new DocumentReference(new DocumentKey(parentPath), this.firestore);\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(CollectionReference.prototype, \"path\", {\n get: function () {\n return this._query.path.canonicalString();\n },\n enumerable: true,\n configurable: true\n });\n CollectionReference.prototype.doc = function (pathString) {\n validateBetweenNumberOfArgs('CollectionReference.doc', arguments, 0, 1);\n // We allow omission of 'pathString' but explicitly prohibit passing in both\n // 'undefined' and 'null'.\n if (arguments.length === 0) {\n pathString = AutoId.newId();\n }\n validateArgType('CollectionReference.doc', 'string', 1, pathString);\n if (pathString === '') {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Document path must be a non-empty string');\n }\n var path = ResourcePath.fromString(pathString);\n return DocumentReference.forPath(this._query.path.child(path), this.firestore);\n };\n CollectionReference.prototype.add = function (value) {\n validateExactNumberOfArgs('CollectionReference.add', arguments, 1);\n validateArgType('CollectionReference.add', 'object', 1, value);\n var docRef = this.doc();\n return docRef.set(value).then(function () { return docRef; });\n };\n return CollectionReference;\n}(Query));\nexport { CollectionReference };\nfunction validateSetOptions(methodName, options) {\n if (options === undefined) {\n return {\n merge: false\n };\n }\n validateOptionNames(methodName, options, ['merge']);\n validateNamedOptionalType(methodName, 'boolean', 'merge', options.merge);\n return options;\n}\nfunction validateSnapshotOptions(methodName, options) {\n if (options === undefined) {\n return {};\n }\n validateOptionNames(methodName, options, ['serverTimestamps']);\n validateNamedOptionalPropertyEquals(methodName, 'options', 'serverTimestamps', options.serverTimestamps, ['estimate', 'previous', 'none']);\n return options;\n}\nfunction validateReference(methodName, documentRef, firestore) {\n if (!(documentRef instanceof DocumentReference)) {\n throw invalidClassError(methodName, 'DocumentReference', 1, documentRef);\n }\n else if (documentRef.firestore !== firestore) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Provided document reference is from a different Firestore instance.');\n }\n else {\n return documentRef;\n }\n}\n/**\n * Calculates the array of firestore.DocumentChange's for a given ViewSnapshot.\n *\n * Exported for testing.\n */\nexport function changesFromSnapshot(firestore, snapshot) {\n if (snapshot.oldDocs.isEmpty()) {\n // Special case the first snapshot because index calculation is easy and\n // fast\n var lastDoc_1;\n var index_1 = 0;\n return snapshot.docChanges.map(function (change) {\n var doc = new QueryDocumentSnapshot(firestore, change.doc.key, change.doc, snapshot.fromCache);\n assert(change.type === ChangeType.Added, 'Invalid event type for first snapshot');\n assert(!lastDoc_1 || snapshot.query.docComparator(lastDoc_1, change.doc) < 0, 'Got added events in wrong order');\n lastDoc_1 = change.doc;\n return {\n type: 'added',\n doc: doc,\n oldIndex: -1,\n newIndex: index_1++\n };\n });\n }\n else {\n // A DocumentSet that is updated incrementally as changes are applied to use\n // to lookup the index of a document.\n var indexTracker_1 = snapshot.oldDocs;\n return snapshot.docChanges.map(function (change) {\n var doc = new QueryDocumentSnapshot(firestore, change.doc.key, change.doc, snapshot.fromCache);\n var oldIndex = -1;\n var newIndex = -1;\n if (change.type !== ChangeType.Added) {\n oldIndex = indexTracker_1.indexOf(change.doc.key);\n assert(oldIndex >= 0, 'Index for document not found');\n indexTracker_1 = indexTracker_1.delete(change.doc.key);\n }\n if (change.type !== ChangeType.Removed) {\n indexTracker_1 = indexTracker_1.add(change.doc);\n newIndex = indexTracker_1.indexOf(change.doc.key);\n }\n return { type: resultChangeType(change.type), doc: doc, oldIndex: oldIndex, newIndex: newIndex };\n });\n }\n}\nfunction resultChangeType(type) {\n switch (type) {\n case ChangeType.Added:\n return 'added';\n case ChangeType.Modified:\n case ChangeType.Metadata:\n return 'modified';\n case ChangeType.Removed:\n return 'removed';\n default:\n return fail('Unknown change type: ' + type);\n }\n}\n// Export the classes with a private constructor (it will fail if invoked\n// at runtime). Note that this still allows instanceof checks.\n// We're treating the variables as class names, so disable checking for lower\n// case variable names.\n// tslint:disable:variable-name\nexport var PublicFirestore = makeConstructorPrivate(Firestore, 'Use firebase.firestore() instead.');\nexport var PublicTransaction = makeConstructorPrivate(Transaction, 'Use firebase.firestore().runTransaction() instead.');\nexport var PublicWriteBatch = makeConstructorPrivate(WriteBatch, 'Use firebase.firestore().batch() instead.');\nexport var PublicDocumentReference = makeConstructorPrivate(DocumentReference, 'Use firebase.firestore().doc() instead.');\nexport var PublicDocumentSnapshot = makeConstructorPrivate(DocumentSnapshot);\nexport var PublicQueryDocumentSnapshot = makeConstructorPrivate(QueryDocumentSnapshot);\nexport var PublicQuery = makeConstructorPrivate(Query);\nexport var PublicQuerySnapshot = makeConstructorPrivate(QuerySnapshot);\nexport var PublicCollectionReference = makeConstructorPrivate(CollectionReference, 'Use firebase.firestore().collection() instead.');\n// tslint:enable:variable-name\n\n//# sourceMappingURL=database.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/api/database.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { PublicBlob } from '../api/blob';\nimport { Firestore, PublicCollectionReference, PublicDocumentReference, PublicDocumentSnapshot, PublicFirestore, PublicQuery, PublicQueryDocumentSnapshot, PublicQuerySnapshot, PublicTransaction, PublicWriteBatch } from '../api/database';\nimport { FieldPath } from '../api/field_path';\nimport { PublicFieldValue } from '../api/field_value';\nimport { GeoPoint } from '../api/geo_point';\nimport { shallowCopy } from '../util/obj';\nvar firestoreNamespace = {\n Firestore: PublicFirestore,\n GeoPoint: GeoPoint,\n Blob: PublicBlob,\n Transaction: PublicTransaction,\n WriteBatch: PublicWriteBatch,\n DocumentReference: PublicDocumentReference,\n DocumentSnapshot: PublicDocumentSnapshot,\n Query: PublicQuery,\n QueryDocumentSnapshot: PublicQueryDocumentSnapshot,\n QuerySnapshot: PublicQuerySnapshot,\n CollectionReference: PublicCollectionReference,\n FieldPath: FieldPath,\n FieldValue: PublicFieldValue,\n setLogLevel: Firestore.setLogLevel\n};\n/**\n * Configures Firestore as part of the Firebase SDK by calling registerService.\n */\nexport function configureForFirebase(firebase) {\n firebase.INTERNAL.registerService('firestore', function (app) { return new Firestore(app); }, shallowCopy(firestoreNamespace));\n}\n/**\n * Exports the Firestore namespace into the provided `exportObject` object under\n * the key 'firestore'. This is used for wrapped binary that exposes Firestore\n * as a goog module.\n */\nexport function configureForStandalone(exportObject) {\n var copiedNamespace = shallowCopy(firestoreNamespace);\n // Unlike the use with Firebase, the standalone allows the use of the\n // constructor, so export it's internal class\n copiedNamespace['Firestore'] = Firestore;\n exportObject['firestore'] = copiedNamespace;\n}\n\n//# sourceMappingURL=config.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/platform/config.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport firebase from '@firebase/app';\nimport './src/platform_browser/browser_init';\nimport { configureForFirebase } from './src/platform/config';\nexport function registerFirestore(instance) {\n configureForFirebase(instance);\n}\nregisterFirestore(firebase);\n\n//# sourceMappingURL=index.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/index.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport firebase from '@firebase/app';\n/** The semver (www.semver.org) version of the SDK. */\nexport var SDK_VERSION = firebase.SDK_VERSION;\n\n//# sourceMappingURL=version.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/version.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n// TODO(mcg): Change to a string enum once we've upgraded to typescript 2.4.\n// tslint:disable-next-line:variable-name Intended to look like a TS 2.4 enum\nexport var Code = {\n // Causes are copied from:\n // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n /** Not an error; returned on success. */\n OK: 'ok',\n /** The operation was cancelled (typically by the caller). */\n CANCELLED: 'cancelled',\n /** Unknown error or an error from a different error domain. */\n UNKNOWN: 'unknown',\n /**\n * Client specified an invalid argument. Note that this differs from\n * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are\n * problematic regardless of the state of the system (e.g., a malformed file\n * name).\n */\n INVALID_ARGUMENT: 'invalid-argument',\n /**\n * Deadline expired before operation could complete. For operations that\n * change the state of the system, this error may be returned even if the\n * operation has completed successfully. For example, a successful response\n * from a server could have been delayed long enough for the deadline to\n * expire.\n */\n DEADLINE_EXCEEDED: 'deadline-exceeded',\n /** Some requested entity (e.g., file or directory) was not found. */\n NOT_FOUND: 'not-found',\n /**\n * Some entity that we attempted to create (e.g., file or directory) already\n * exists.\n */\n ALREADY_EXISTS: 'already-exists',\n /**\n * The caller does not have permission to execute the specified operation.\n * PERMISSION_DENIED must not be used for rejections caused by exhausting\n * some resource (use RESOURCE_EXHAUSTED instead for those errors).\n * PERMISSION_DENIED must not be used if the caller can not be identified\n * (use UNAUTHENTICATED instead for those errors).\n */\n PERMISSION_DENIED: 'permission-denied',\n /**\n * The request does not have valid authentication credentials for the\n * operation.\n */\n UNAUTHENTICATED: 'unauthenticated',\n /**\n * Some resource has been exhausted, perhaps a per-user quota, or perhaps the\n * entire file system is out of space.\n */\n RESOURCE_EXHAUSTED: 'resource-exhausted',\n /**\n * Operation was rejected because the system is not in a state required for\n * the operation's execution. For example, directory to be deleted may be\n * non-empty, an rmdir operation is applied to a non-directory, etc.\n *\n * A litmus test that may help a service implementor in deciding\n * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:\n * (a) Use UNAVAILABLE if the client can retry just the failing call.\n * (b) Use ABORTED if the client should retry at a higher-level\n * (e.g., restarting a read-modify-write sequence).\n * (c) Use FAILED_PRECONDITION if the client should not retry until\n * the system state has been explicitly fixed. E.g., if an \"rmdir\"\n * fails because the directory is non-empty, FAILED_PRECONDITION\n * should be returned since the client should not retry unless\n * they have first fixed up the directory by deleting files from it.\n * (d) Use FAILED_PRECONDITION if the client performs conditional\n * REST Get/Update/Delete on a resource and the resource on the\n * server does not match the condition. E.g., conflicting\n * read-modify-write on the same resource.\n */\n FAILED_PRECONDITION: 'failed-precondition',\n /**\n * The operation was aborted, typically due to a concurrency issue like\n * sequencer check failures, transaction aborts, etc.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n ABORTED: 'aborted',\n /**\n * Operation was attempted past the valid range. E.g., seeking or reading\n * past end of file.\n *\n * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed\n * if the system state changes. For example, a 32-bit file system will\n * generate INVALID_ARGUMENT if asked to read at an offset that is not in the\n * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from\n * an offset past the current file size.\n *\n * There is a fair bit of overlap between FAILED_PRECONDITION and\n * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)\n * when it applies so that callers who are iterating through a space can\n * easily look for an OUT_OF_RANGE error to detect when they are done.\n */\n OUT_OF_RANGE: 'out-of-range',\n /** Operation is not implemented or not supported/enabled in this service. */\n UNIMPLEMENTED: 'unimplemented',\n /**\n * Internal errors. Means some invariants expected by underlying System has\n * been broken. If you see one of these errors, Something is very broken.\n */\n INTERNAL: 'internal',\n /**\n * The service is currently unavailable. This is a most likely a transient\n * condition and may be corrected by retrying with a backoff.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n UNAVAILABLE: 'unavailable',\n /** Unrecoverable data loss or corruption. */\n DATA_LOSS: 'data-loss'\n};\n/**\n * An error class used for Firestore-generated errors. Ideally we should be\n * using FirebaseError, but integrating with it is overly arduous at the moment,\n * so we define our own compatible error class (with a `name` of 'FirebaseError'\n * and compatible `code` and `message` fields.)\n */\nvar FirestoreError = /** @class */ (function (_super) {\n __extends(FirestoreError, _super);\n function FirestoreError(code, message) {\n var _this = _super.call(this, message) || this;\n _this.code = code;\n _this.message = message;\n _this.name = 'FirebaseError';\n // HACK: We write a toString property directly because Error is not a real\n // class and so inheritance does not work correctly. We could alternatively\n // do the same \"back-door inheritance\" trick that FirebaseError does.\n _this.toString = function () { return _this.name + \": [code=\" + _this.code + \"]: \" + _this.message; };\n return _this;\n }\n return FirestoreError;\n}(Error));\nexport { FirestoreError };\n\n//# sourceMappingURL=error.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/error.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Code, FirestoreError } from '../util/error';\nimport { validateArgType, validateExactNumberOfArgs } from '../util/input_validation';\nimport { primitiveComparator } from '../util/misc';\n/**\n * Immutable class representing a geo point as latitude-longitude pair.\n * This class is directly exposed in the public API, including its constructor.\n */\nvar GeoPoint = /** @class */ (function () {\n function GeoPoint(latitude, longitude) {\n validateExactNumberOfArgs('GeoPoint', arguments, 2);\n validateArgType('GeoPoint', 'number', 1, latitude);\n validateArgType('GeoPoint', 'number', 2, longitude);\n if (!isFinite(latitude) || latitude < -90 || latitude > 90) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Latitude must be a number between -90 and 90, but was: ' + latitude);\n }\n if (!isFinite(longitude) || longitude < -180 || longitude > 180) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Longitude must be a number between -180 and 180, but was: ' + longitude);\n }\n this._lat = latitude;\n this._long = longitude;\n }\n Object.defineProperty(GeoPoint.prototype, \"latitude\", {\n /**\n * Returns the latitude of this geo point, a number between -90 and 90.\n */\n get: function () {\n return this._lat;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GeoPoint.prototype, \"longitude\", {\n /**\n * Returns the longitude of this geo point, a number between -180 and 180.\n */\n get: function () {\n return this._long;\n },\n enumerable: true,\n configurable: true\n });\n GeoPoint.prototype.isEqual = function (other) {\n return this._lat === other._lat && this._long === other._long;\n };\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */\n GeoPoint.prototype._compareTo = function (other) {\n return (primitiveComparator(this._lat, other._lat) ||\n primitiveComparator(this._long, other._long));\n };\n return GeoPoint;\n}());\nexport { GeoPoint };\n\n//# sourceMappingURL=geo_point.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/api/geo_point.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { primitiveComparator } from '../util/misc';\nvar DatabaseInfo = /** @class */ (function () {\n /**\n * Constructs a DatabaseInfo using the provided host, databaseId and\n * persistenceKey.\n *\n * @param databaseId The database to use.\n * @param persistenceKey A unique identifier for this Firestore's local\n * storage (used in conjunction with the databaseId).\n * @param host The Firestore backend host to connect to.\n * @param ssl Whether to use SSL when connecting.\n */\n function DatabaseInfo(databaseId, persistenceKey, host, ssl) {\n this.databaseId = databaseId;\n this.persistenceKey = persistenceKey;\n this.host = host;\n this.ssl = ssl;\n }\n return DatabaseInfo;\n}());\nexport { DatabaseInfo };\n/** The default database name for a project. */\nvar DEFAULT_DATABASE_NAME = '(default)';\n/** Represents the database ID a Firestore client is associated with. */\nvar DatabaseId = /** @class */ (function () {\n function DatabaseId(projectId, database) {\n this.projectId = projectId;\n this.database = database ? database : DEFAULT_DATABASE_NAME;\n }\n Object.defineProperty(DatabaseId.prototype, \"isDefaultDatabase\", {\n get: function () {\n return this.database === DEFAULT_DATABASE_NAME;\n },\n enumerable: true,\n configurable: true\n });\n DatabaseId.prototype.isEqual = function (other) {\n return (other instanceof DatabaseId &&\n other.projectId === this.projectId &&\n other.database === this.database);\n };\n DatabaseId.prototype.compareTo = function (other) {\n return (primitiveComparator(this.projectId, other.projectId) ||\n primitiveComparator(this.database, other.database));\n };\n return DatabaseId;\n}());\nexport { DatabaseId };\n\n//# sourceMappingURL=database_info.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/database_info.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { assert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nexport var DOCUMENT_KEY_NAME = '__name__';\n/**\n * Path represents an ordered sequence of string segments.\n */\nvar Path = /** @class */ (function () {\n function Path(segments, offset, length) {\n this.init(segments, offset, length);\n }\n /**\n * An initialization method that can be called from outside the constructor.\n * We need this so that we can have a non-static construct method that returns\n * the polymorphic `this` type.\n */\n Path.prototype.init = function (segments, offset, length) {\n if (offset === undefined) {\n offset = 0;\n }\n else if (offset > segments.length) {\n fail('offset ' + offset + ' out of range ' + segments.length);\n }\n if (length === undefined) {\n length = segments.length - offset;\n }\n else if (length > segments.length - offset) {\n fail('length ' + length + ' out of range ' + (segments.length - offset));\n }\n this.segments = segments;\n this.offset = offset;\n this.len = length;\n };\n /**\n * Constructs a new instance of Path using the same concrete type as `this`.\n * We need this instead of using the normal constructor, because polymorphic\n * `this` doesn't work on static methods.\n */\n Path.prototype.construct = function (segments, offset, length) {\n var path = Object.create(Object.getPrototypeOf(this));\n path.init(segments, offset, length);\n return path;\n };\n Object.defineProperty(Path.prototype, \"length\", {\n get: function () {\n return this.len;\n },\n enumerable: true,\n configurable: true\n });\n Path.prototype.isEqual = function (other) {\n return Path.comparator(this, other) === 0;\n };\n Path.prototype.child = function (nameOrPath) {\n var segments = this.segments.slice(this.offset, this.limit());\n if (nameOrPath instanceof Path) {\n nameOrPath.forEach(function (segment) {\n segments.push(segment);\n });\n }\n else if (typeof nameOrPath === 'string') {\n segments.push(nameOrPath);\n }\n else {\n fail('Unknown parameter type for Path.child(): ' + nameOrPath);\n }\n return this.construct(segments);\n };\n /** The index of one past the last segment of the path. */\n Path.prototype.limit = function () {\n return this.offset + this.length;\n };\n Path.prototype.popFirst = function (size) {\n size = size === undefined ? 1 : size;\n assert(this.length >= size, \"Can't call popFirst() with less segments\");\n return this.construct(this.segments, this.offset + size, this.length - size);\n };\n Path.prototype.popLast = function () {\n assert(!this.isEmpty(), \"Can't call popLast() on empty path\");\n return this.construct(this.segments, this.offset, this.length - 1);\n };\n Path.prototype.firstSegment = function () {\n assert(!this.isEmpty(), \"Can't call firstSegment() on empty path\");\n return this.segments[this.offset];\n };\n Path.prototype.lastSegment = function () {\n assert(!this.isEmpty(), \"Can't call lastSegment() on empty path\");\n return this.segments[this.limit() - 1];\n };\n Path.prototype.get = function (index) {\n assert(index < this.length, 'Index out of range');\n return this.segments[this.offset + index];\n };\n Path.prototype.isEmpty = function () {\n return this.length === 0;\n };\n Path.prototype.isPrefixOf = function (other) {\n if (other.length < this.length) {\n return false;\n }\n for (var i = 0; i < this.length; i++) {\n if (this.get(i) !== other.get(i)) {\n return false;\n }\n }\n return true;\n };\n Path.prototype.forEach = function (fn) {\n for (var i = this.offset, end = this.limit(); i < end; i++) {\n fn(this.segments[i]);\n }\n };\n Path.prototype.toArray = function () {\n return this.segments.slice(this.offset, this.limit());\n };\n Path.comparator = function (p1, p2) {\n var len = Math.min(p1.length, p2.length);\n for (var i = 0; i < len; i++) {\n var left = p1.get(i);\n var right = p2.get(i);\n if (left < right)\n return -1;\n if (left > right)\n return 1;\n }\n if (p1.length < p2.length)\n return -1;\n if (p1.length > p2.length)\n return 1;\n return 0;\n };\n return Path;\n}());\nexport { Path };\n/**\n * A slash-separated path for navigating resources (documents and collections)\n * within Firestore.\n */\nvar ResourcePath = /** @class */ (function (_super) {\n __extends(ResourcePath, _super);\n function ResourcePath() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n ResourcePath.prototype.canonicalString = function () {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n return this.toArray().join('/');\n };\n ResourcePath.prototype.toString = function () {\n return this.canonicalString();\n };\n /**\n * Creates a resource path from the given slash-delimited string.\n */\n ResourcePath.fromString = function (path) {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n if (path.indexOf('//') >= 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid path (\" + path + \"). Paths must not contain // in them.\");\n }\n // We may still have an empty segment at the beginning or end if they had a\n // leading or trailing slash (which we allow).\n var segments = path.split('/').filter(function (segment) { return segment.length > 0; });\n return new ResourcePath(segments);\n };\n ResourcePath.EMPTY_PATH = new ResourcePath([]);\n return ResourcePath;\n}(Path));\nexport { ResourcePath };\nvar identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/;\n/** A dot-separated path for navigating sub-objects within a document. */\nvar FieldPath = /** @class */ (function (_super) {\n __extends(FieldPath, _super);\n function FieldPath() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Returns true if the string could be used as a segment in a field path\n * without escaping.\n */\n FieldPath.isValidIdentifier = function (segment) {\n return identifierRegExp.test(segment);\n };\n FieldPath.prototype.canonicalString = function () {\n return this.toArray()\n .map(function (str) {\n str = str.replace('\\\\', '\\\\\\\\').replace('`', '\\\\`');\n if (!FieldPath.isValidIdentifier(str)) {\n str = '`' + str + '`';\n }\n return str;\n })\n .join('.');\n };\n FieldPath.prototype.toString = function () {\n return this.canonicalString();\n };\n /**\n * Returns true if this field references the key of a document.\n */\n FieldPath.prototype.isKeyField = function () {\n return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME;\n };\n /**\n * The field designating the key of a document.\n */\n FieldPath.keyField = function () {\n return new FieldPath([DOCUMENT_KEY_NAME]);\n };\n /**\n * Parses a field string from the given server-formatted string.\n *\n * - Splitting the empty string is not allowed (for now at least).\n * - Empty segments within the string (e.g. if there are two consecutive\n * separators) are not allowed.\n *\n * TODO(b/37244157): we should make this more strict. Right now, it allows\n * non-identifier path components, even if they aren't escaped.\n */\n FieldPath.fromServerFormat = function (path) {\n var segments = [];\n var current = '';\n var i = 0;\n var addCurrentSegment = function () {\n if (current.length === 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field path (\" + path + \"). Paths must not be empty, begin \" +\n \"with '.', end with '.', or contain '..'\");\n }\n segments.push(current);\n current = '';\n };\n var inBackticks = false;\n while (i < path.length) {\n var c = path[i];\n if (c === '\\\\') {\n if (i + 1 === path.length) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has trailing escape character: ' + path);\n }\n var next = path[i + 1];\n if (!(next === '\\\\' || next === '.' || next === '`')) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has invalid escape sequence: ' + path);\n }\n current += next;\n i += 2;\n }\n else if (c === '`') {\n inBackticks = !inBackticks;\n i++;\n }\n else if (c === '.' && !inBackticks) {\n addCurrentSegment();\n i++;\n }\n else {\n current += c;\n i++;\n }\n }\n addCurrentSegment();\n if (inBackticks) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Unterminated ` in path: ' + path);\n }\n return new FieldPath(segments);\n };\n FieldPath.EMPTY_PATH = new FieldPath([]);\n return FieldPath;\n}(Path));\nexport { FieldPath };\n\n//# sourceMappingURL=path.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/model/path.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { assert } from '../util/assert';\nimport { ResourcePath } from './path';\nvar DocumentKey = /** @class */ (function () {\n function DocumentKey(path) {\n this.path = path;\n assert(DocumentKey.isDocumentKey(path), 'Invalid DocumentKey with an odd number of segments: ' +\n path.toArray().join('/'));\n }\n DocumentKey.prototype.isEqual = function (other) {\n return (other !== null && ResourcePath.comparator(this.path, other.path) === 0);\n };\n DocumentKey.prototype.toString = function () {\n return this.path.toString();\n };\n DocumentKey.comparator = function (k1, k2) {\n return ResourcePath.comparator(k1.path, k2.path);\n };\n DocumentKey.isDocumentKey = function (path) {\n return path.length % 2 === 0;\n };\n /**\n * Creates and returns a new document key with the given segments.\n *\n * @param path The segments of the path to the document\n * @return A new instance of DocumentKey\n */\n DocumentKey.fromSegments = function (segments) {\n return new DocumentKey(new ResourcePath(segments.slice()));\n };\n /**\n * Creates and returns a new document key using '/' to split the string into\n * segments.\n *\n * @param path The slash-separated path string to the document\n * @return A new instance of DocumentKey\n */\n DocumentKey.fromPathString = function (path) {\n return new DocumentKey(ResourcePath.fromString(path));\n };\n DocumentKey.EMPTY = new DocumentKey(new ResourcePath([]));\n return DocumentKey;\n}());\nexport { DocumentKey };\n\n//# sourceMappingURL=document_key.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/model/document_key.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { fail } from '../util/assert';\nimport { DocumentKey } from './document_key';\nvar Document = /** @class */ (function () {\n function Document(key, version, data, options) {\n this.key = key;\n this.version = version;\n this.data = data;\n this.hasLocalMutations = options.hasLocalMutations;\n }\n Document.prototype.field = function (path) {\n return this.data.field(path);\n };\n Document.prototype.fieldValue = function (path) {\n var field = this.field(path);\n return field ? field.value() : undefined;\n };\n Document.prototype.value = function () {\n return this.data.value();\n };\n Document.prototype.isEqual = function (other) {\n return (other instanceof Document &&\n this.key.isEqual(other.key) &&\n this.version.isEqual(other.version) &&\n this.data.isEqual(other.data) &&\n this.hasLocalMutations === other.hasLocalMutations);\n };\n Document.prototype.toString = function () {\n return (\"Document(\" + this.key + \", \" + this.version + \", \" + this.data.toString() + \", \" +\n (\"{hasLocalMutations: \" + this.hasLocalMutations + \"})\"));\n };\n Document.compareByKey = function (d1, d2) {\n return DocumentKey.comparator(d1.key, d2.key);\n };\n Document.compareByField = function (field, d1, d2) {\n var v1 = d1.field(field);\n var v2 = d2.field(field);\n if (v1 !== undefined && v2 !== undefined) {\n return v1.compareTo(v2);\n }\n else {\n return fail(\"Trying to compare documents on fields that don't exist\");\n }\n };\n return Document;\n}());\nexport { Document };\n/**\n * A class representing a deleted document.\n * Version is set to 0 if we don't point to any specific time, otherwise it\n * denotes time we know it didn't exist at.\n */\nvar NoDocument = /** @class */ (function () {\n function NoDocument(key, version) {\n this.key = key;\n this.version = version;\n }\n NoDocument.prototype.toString = function () {\n return \"NoDocument(\" + this.key + \", \" + this.version + \")\";\n };\n NoDocument.prototype.isEqual = function (other) {\n return (other &&\n other.version.isEqual(this.version) &&\n other.key.isEqual(this.key));\n };\n NoDocument.compareByKey = function (d1, d2) {\n return DocumentKey.comparator(d1.key, d2.key);\n };\n return NoDocument;\n}());\nexport { NoDocument };\n\n//# sourceMappingURL=document.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/model/document.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { assert, fail } from './assert';\n// An immutable sorted map implementation, based on a Left-leaning Red-Black\n// tree.\nvar SortedMap = /** @class */ (function () {\n function SortedMap(comparator, root) {\n this.comparator = comparator;\n this.root = root ? root : LLRBNode.EMPTY;\n }\n // Returns a copy of the map, with the specified key/value added or replaced.\n SortedMap.prototype.insert = function (key, value) {\n return new SortedMap(this.comparator, this.root\n .insert(key, value, this.comparator)\n .copy(null, null, LLRBNode.BLACK, null, null));\n };\n // Returns a copy of the map, with the specified key removed.\n SortedMap.prototype.remove = function (key) {\n return new SortedMap(this.comparator, this.root\n .remove(key, this.comparator)\n .copy(null, null, LLRBNode.BLACK, null, null));\n };\n // Returns the value of the node with the given key, or null.\n SortedMap.prototype.get = function (key) {\n var node = this.root;\n while (!node.isEmpty()) {\n var cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return node.value;\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else if (cmp > 0) {\n node = node.right;\n }\n }\n return null;\n };\n // Returns the key of the item *before* the specified key, or null if key is\n // the first item.\n SortedMap.prototype.getPredecessorKey = function (key) {\n var node = this.root;\n var rightParent = null;\n while (!node.isEmpty()) {\n var cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n if (!node.left.isEmpty()) {\n node = node.left;\n while (!node.right.isEmpty())\n node = node.right;\n return node.key;\n }\n else if (rightParent) {\n return rightParent.key;\n }\n else {\n return null; // first item.\n }\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else if (cmp > 0) {\n rightParent = node;\n node = node.right;\n }\n }\n throw fail('Attempted to find predecessor key for a nonexistent key.' +\n ' What gives?');\n };\n // Returns the index of the element in this sorted map, or -1 if it doesn't\n // exist.\n SortedMap.prototype.indexOf = function (key) {\n // Number of nodes that were pruned when descending right\n var prunedNodes = 0;\n var node = this.root;\n while (!node.isEmpty()) {\n var cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return prunedNodes + node.left.size;\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else {\n // Count all nodes left of the node plus the node itself\n prunedNodes += node.left.size + 1;\n node = node.right;\n }\n }\n // Node not found\n return -1;\n };\n SortedMap.prototype.isEmpty = function () {\n return this.root.isEmpty();\n };\n Object.defineProperty(SortedMap.prototype, \"size\", {\n // Returns the total number of nodes in the map.\n get: function () {\n return this.root.size;\n },\n enumerable: true,\n configurable: true\n });\n // Returns the minimum key in the map.\n SortedMap.prototype.minKey = function () {\n return this.root.minKey();\n };\n // Returns the maximum key in the map.\n SortedMap.prototype.maxKey = function () {\n return this.root.maxKey();\n };\n // Traverses the map in key order and calls the specified action function\n // for each key/value pair. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n SortedMap.prototype.inorderTraversal = function (action) {\n return this.root.inorderTraversal(action);\n };\n SortedMap.prototype.forEach = function (fn) {\n this.inorderTraversal(function (k, v) {\n fn(k, v);\n return false;\n });\n };\n // Traverses the map in reverse key order and calls the specified action\n // function for each key/value pair. If action returns true, traversal is\n // aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n SortedMap.prototype.reverseTraversal = function (action) {\n return this.root.reverseTraversal(action);\n };\n // Returns an iterator over the SortedMap.\n SortedMap.prototype.getIterator = function () {\n return new SortedMapIterator(this.root, null, this.comparator, false);\n };\n SortedMap.prototype.getIteratorFrom = function (key) {\n return new SortedMapIterator(this.root, key, this.comparator, false);\n };\n SortedMap.prototype.getReverseIterator = function () {\n return new SortedMapIterator(this.root, null, this.comparator, true);\n };\n SortedMap.prototype.getReverseIteratorFrom = function (key) {\n return new SortedMapIterator(this.root, key, this.comparator, true);\n };\n return SortedMap;\n}()); // end SortedMap\nexport { SortedMap };\n// An iterator over an LLRBNode.\nvar SortedMapIterator = /** @class */ (function () {\n function SortedMapIterator(node, startKey, comparator, isReverse) {\n this.isReverse = isReverse;\n this.nodeStack = [];\n var cmp = 1;\n while (!node.isEmpty()) {\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (isReverse)\n cmp *= -1;\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse) {\n node = node.left;\n }\n else {\n node = node.right;\n }\n }\n else if (cmp === 0) {\n // This node is exactly equal to our start key. Push it on the stack,\n // but stop iterating;\n this.nodeStack.push(node);\n break;\n }\n else {\n // This node is greater than our start key, add it to the stack and move\n // to the next one\n this.nodeStack.push(node);\n if (this.isReverse) {\n node = node.right;\n }\n else {\n node = node.left;\n }\n }\n }\n }\n SortedMapIterator.prototype.getNext = function () {\n assert(this.nodeStack.length > 0, 'getNext() called on iterator when hasNext() is false.');\n var node = this.nodeStack.pop();\n var result = { key: node.key, value: node.value };\n if (this.isReverse) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.right;\n }\n }\n else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.left;\n }\n }\n return result;\n };\n SortedMapIterator.prototype.hasNext = function () {\n return this.nodeStack.length > 0;\n };\n SortedMapIterator.prototype.peek = function () {\n if (this.nodeStack.length === 0)\n return null;\n var node = this.nodeStack[this.nodeStack.length - 1];\n return { key: node.key, value: node.value };\n };\n return SortedMapIterator;\n}()); // end SortedMapIterator\nexport { SortedMapIterator };\n// Represents a node in a Left-leaning Red-Black tree.\nvar LLRBNode = /** @class */ (function () {\n function LLRBNode(key, value, color, left, right) {\n this.key = key;\n this.value = value;\n this.color = color != null ? color : LLRBNode.RED;\n this.left = left != null ? left : LLRBNode.EMPTY;\n this.right = right != null ? right : LLRBNode.EMPTY;\n this.size = this.left.size + 1 + this.right.size;\n }\n // Returns a copy of the current node, optionally replacing pieces of it.\n LLRBNode.prototype.copy = function (key, value, color, left, right) {\n return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);\n };\n LLRBNode.prototype.isEmpty = function () {\n return false;\n };\n // Traverses the tree in key order and calls the specified action function\n // for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n LLRBNode.prototype.inorderTraversal = function (action) {\n return (this.left.inorderTraversal(action) ||\n action(this.key, this.value) ||\n this.right.inorderTraversal(action));\n };\n // Traverses the tree in reverse key order and calls the specified action\n // function for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n LLRBNode.prototype.reverseTraversal = function (action) {\n return (this.right.reverseTraversal(action) ||\n action(this.key, this.value) ||\n this.left.reverseTraversal(action));\n };\n // Returns the minimum node in the tree.\n LLRBNode.prototype.min = function () {\n if (this.left.isEmpty()) {\n return this;\n }\n else {\n return this.left.min();\n }\n };\n // Returns the maximum key in the tree.\n LLRBNode.prototype.minKey = function () {\n return this.min().key;\n };\n // Returns the maximum key in the tree.\n LLRBNode.prototype.maxKey = function () {\n if (this.right.isEmpty()) {\n return this.key;\n }\n else {\n return this.right.maxKey();\n }\n };\n // Returns new tree, with the key/value added.\n LLRBNode.prototype.insert = function (key, value, comparator) {\n var n = this;\n var cmp = comparator(key, n.key);\n if (cmp < 0) {\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n }\n else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n }\n else {\n n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));\n }\n return n.fixUp();\n };\n LLRBNode.prototype.removeMin = function () {\n if (this.left.isEmpty()) {\n return LLRBNode.EMPTY;\n }\n var n = this;\n if (!n.left.isRed() && !n.left.left.isRed())\n n = n.moveRedLeft();\n n = n.copy(null, null, null, n.left.removeMin(), null);\n return n.fixUp();\n };\n // Returns new tree, with the specified item removed.\n LLRBNode.prototype.remove = function (key, comparator) {\n var smallest;\n var n = this;\n if (comparator(key, n.key) < 0) {\n if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {\n n = n.moveRedLeft();\n }\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n }\n else {\n if (n.left.isRed())\n n = n.rotateRight();\n if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {\n n = n.moveRedRight();\n }\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return LLRBNode.EMPTY;\n }\n else {\n smallest = n.right.min();\n n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin());\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp();\n };\n LLRBNode.prototype.isRed = function () {\n return this.color;\n };\n // Returns new tree after performing any needed rotations.\n LLRBNode.prototype.fixUp = function () {\n var n = this;\n if (n.right.isRed() && !n.left.isRed())\n n = n.rotateLeft();\n if (n.left.isRed() && n.left.left.isRed())\n n = n.rotateRight();\n if (n.left.isRed() && n.right.isRed())\n n = n.colorFlip();\n return n;\n };\n LLRBNode.prototype.moveRedLeft = function () {\n var n = this.colorFlip();\n if (n.right.left.isRed()) {\n n = n.copy(null, null, null, null, n.right.rotateRight());\n n = n.rotateLeft();\n n = n.colorFlip();\n }\n return n;\n };\n LLRBNode.prototype.moveRedRight = function () {\n var n = this.colorFlip();\n if (n.left.left.isRed()) {\n n = n.rotateRight();\n n = n.colorFlip();\n }\n return n;\n };\n LLRBNode.prototype.rotateLeft = function () {\n var nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return this.right.copy(null, null, this.color, nl, null);\n };\n LLRBNode.prototype.rotateRight = function () {\n var nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return this.left.copy(null, null, this.color, null, nr);\n };\n LLRBNode.prototype.colorFlip = function () {\n var left = this.left.copy(null, null, !this.left.color, null, null);\n var right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n };\n // For testing.\n LLRBNode.prototype.checkMaxDepth = function () {\n var blackDepth = this.check();\n if (Math.pow(2.0, blackDepth) <= this.size + 1) {\n return true;\n }\n else {\n return false;\n }\n };\n // In a balanced RB tree, the black-depth (number of black nodes) from root to\n // leaves is equal on both sides. This function verifies that or asserts.\n LLRBNode.prototype.check = function () {\n if (this.isRed() && this.left.isRed()) {\n throw fail('Red node has red child(' + this.key + ',' + this.value + ')');\n }\n if (this.right.isRed()) {\n throw fail('Right child of (' + this.key + ',' + this.value + ') is red');\n }\n var blackDepth = this.left.check();\n if (blackDepth !== this.right.check()) {\n throw fail('Black depths differ');\n }\n else {\n return blackDepth + (this.isRed() ? 0 : 1);\n }\n };\n // tslint:disable-next-line:no-any Empty node is shared between all LLRB trees.\n LLRBNode.EMPTY = null;\n LLRBNode.RED = true;\n LLRBNode.BLACK = false;\n return LLRBNode;\n}()); // end LLRBNode\nexport { LLRBNode };\n// Represents an empty node (a leaf node in the Red-Black Tree).\nvar LLRBEmptyNode = /** @class */ (function () {\n function LLRBEmptyNode() {\n this.size = 0;\n }\n // Returns a copy of the current node.\n LLRBEmptyNode.prototype.copy = function (key, value, color, left, right) {\n return this;\n };\n // Returns a copy of the tree, with the specified key/value added.\n LLRBEmptyNode.prototype.insert = function (key, value, comparator) {\n return new LLRBNode(key, value);\n };\n // Returns a copy of the tree, with the specified key removed.\n LLRBEmptyNode.prototype.remove = function (key, comparator) {\n return this;\n };\n LLRBEmptyNode.prototype.isEmpty = function () {\n return true;\n };\n LLRBEmptyNode.prototype.inorderTraversal = function (action) {\n return false;\n };\n LLRBEmptyNode.prototype.reverseTraversal = function (action) {\n return false;\n };\n LLRBEmptyNode.prototype.minKey = function () {\n return null;\n };\n LLRBEmptyNode.prototype.maxKey = function () {\n return null;\n };\n LLRBEmptyNode.prototype.isRed = function () {\n return false;\n };\n // For testing.\n LLRBEmptyNode.prototype.checkMaxDepth = function () {\n return true;\n };\n LLRBEmptyNode.prototype.check = function () {\n return 0;\n };\n return LLRBEmptyNode;\n}()); // end LLRBEmptyNode\nexport { LLRBEmptyNode };\nLLRBNode.EMPTY = new LLRBEmptyNode();\n\n//# sourceMappingURL=sorted_map.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/sorted_map.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { emptyByteString } from '../platform/platform';\n/** An enumeration of the different purposes we have for queries. */\nexport var QueryPurpose;\n(function (QueryPurpose) {\n /** A regular, normal query. */\n QueryPurpose[QueryPurpose[\"Listen\"] = 0] = \"Listen\";\n /**\n * The query was used to refill a query after an existence filter mismatch.\n */\n QueryPurpose[QueryPurpose[\"ExistenceFilterMismatch\"] = 1] = \"ExistenceFilterMismatch\";\n /** The query was used to resolve a limbo document. */\n QueryPurpose[QueryPurpose[\"LimboResolution\"] = 2] = \"LimboResolution\";\n})(QueryPurpose || (QueryPurpose = {}));\n/**\n * An immutable set of metadata that the local store tracks for each query.\n */\nvar QueryData = /** @class */ (function () {\n function QueryData(\n /** The query being listened to. */\n query, \n /**\n * The target ID to which the query corresponds; Assigned by the\n * LocalStore for user listens and by the SyncEngine for limbo watches.\n */\n targetId, \n /** The purpose of the query. */\n purpose, \n /** The latest snapshot version seen for this target. */\n snapshotVersion, \n /**\n * An opaque, server-assigned token that allows watching a query to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the query. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */\n resumeToken) {\n if (snapshotVersion === void 0) { snapshotVersion = SnapshotVersion.MIN; }\n if (resumeToken === void 0) { resumeToken = emptyByteString(); }\n this.query = query;\n this.targetId = targetId;\n this.purpose = purpose;\n this.snapshotVersion = snapshotVersion;\n this.resumeToken = resumeToken;\n }\n /**\n * Creates a new query data instance with an updated snapshot version and\n * resume token.\n */\n QueryData.prototype.update = function (updated) {\n return new QueryData(this.query, this.targetId, this.purpose, updated.snapshotVersion, updated.resumeToken);\n };\n QueryData.prototype.isEqual = function (other) {\n return (this.targetId === other.targetId &&\n this.purpose === other.purpose &&\n this.snapshotVersion.isEqual(other.snapshotVersion) &&\n this.resumeToken === other.resumeToken &&\n this.query.isEqual(other.query));\n };\n return QueryData;\n}());\nexport { QueryData };\n\n//# sourceMappingURL=query_data.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/query_data.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { assert } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\n// A RegExp matching ISO 8601 UTC timestamps with optional fraction.\nvar isoRegExp = new RegExp(/^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.(\\d+))?Z$/);\nvar Timestamp = /** @class */ (function () {\n function Timestamp(seconds, nanos) {\n this.seconds = seconds;\n this.nanos = nanos;\n assert(nanos >= 0, 'timestamp nanoseconds out of range: ' + nanos);\n assert(nanos < 1e9, 'timestamp nanoseconds out of range' + nanos);\n // Midnight at the beginning of 1/1/1 is the earliest Firestore supports.\n assert(seconds >= -62135596800, 'timestamp seconds out of range: ' + seconds);\n // This will break in the year 10,000.\n assert(seconds < 253402300800, 'timestamp seconds out of range' + seconds);\n }\n Timestamp.now = function () {\n return Timestamp.fromEpochMilliseconds(Date.now());\n };\n Timestamp.fromDate = function (date) {\n return Timestamp.fromEpochMilliseconds(date.getTime());\n };\n Timestamp.fromEpochMilliseconds = function (milliseconds) {\n var seconds = Math.floor(milliseconds / 1000);\n var nanos = (milliseconds - seconds * 1000) * 1e6;\n return new Timestamp(seconds, nanos);\n };\n Timestamp.fromISOString = function (utc) {\n // The date string can have higher precision (nanos) than the Date class\n // (millis), so we do some custom parsing here.\n // Parse the nanos right out of the string.\n var nanos = 0;\n var fraction = isoRegExp.exec(utc);\n assert(!!fraction, 'invalid timestamp: ' + utc);\n if (fraction[1]) {\n // Pad the fraction out to 9 digits (nanos).\n var nanoStr = fraction[1];\n nanoStr = (nanoStr + '000000000').substr(0, 9);\n nanos = Number(nanoStr);\n }\n // Parse the date to get the seconds.\n var date = new Date(utc);\n var seconds = Math.floor(date.getTime() / 1000);\n return new Timestamp(seconds, nanos);\n };\n Timestamp.prototype.toDate = function () {\n return new Date(this.toEpochMilliseconds());\n };\n Timestamp.prototype.toEpochMilliseconds = function () {\n return this.seconds * 1000 + this.nanos / 1e6;\n };\n Timestamp.prototype.compareTo = function (other) {\n if (this.seconds === other.seconds) {\n return primitiveComparator(this.nanos, other.nanos);\n }\n return primitiveComparator(this.seconds, other.seconds);\n };\n Timestamp.prototype.isEqual = function (other) {\n return other.seconds === this.seconds && other.nanos === this.nanos;\n };\n Timestamp.prototype.toString = function () {\n return 'Timestamp(seconds=' + this.seconds + ', nanos=' + this.nanos + ')';\n };\n return Timestamp;\n}());\nexport { Timestamp };\n\n//# sourceMappingURL=timestamp.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/timestamp.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Timestamp } from './timestamp';\n/**\n * A version of a document in Firestore. This corresponds to the version\n * timestamp, such as update_time or read_time.\n */\nvar SnapshotVersion = /** @class */ (function () {\n function SnapshotVersion(timestamp) {\n this.timestamp = timestamp;\n }\n // TODO(b/34176344): Once we no longer need to use the old alpha protos,\n // delete this constructor and use a timestamp-backed version everywhere.\n SnapshotVersion.fromMicroseconds = function (value) {\n var seconds = Math.floor(value / 1e6);\n var nanos = (value % 1e6) * 1e3;\n return new SnapshotVersion(new Timestamp(seconds, nanos));\n };\n SnapshotVersion.fromTimestamp = function (value) {\n return new SnapshotVersion(value);\n };\n SnapshotVersion.forDeletedDoc = function () {\n return SnapshotVersion.MIN;\n };\n SnapshotVersion.prototype.compareTo = function (other) {\n return this.timestamp.compareTo(other.timestamp);\n };\n SnapshotVersion.prototype.isEqual = function (other) {\n return this.timestamp.isEqual(other.timestamp);\n };\n /** Returns a number representation of the version for use in spec tests. */\n SnapshotVersion.prototype.toMicroseconds = function () {\n // Convert to microseconds.\n return this.timestamp.seconds * 1e6 + this.timestamp.nanos / 1000;\n };\n SnapshotVersion.prototype.toString = function () {\n return 'SnapshotVersion(' + this.timestamp.toString() + ')';\n };\n SnapshotVersion.prototype.toTimestamp = function () {\n return this.timestamp;\n };\n SnapshotVersion.MIN = new SnapshotVersion(new Timestamp(0, 0));\n return SnapshotVersion;\n}());\nexport { SnapshotVersion };\n\n//# sourceMappingURL=snapshot_version.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/snapshot_version.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { assert, fail } from '../util/assert';\nimport * as misc from '../util/misc';\nimport { Document, NoDocument } from './document';\nimport { ObjectValue, ServerTimestampValue } from './field_value';\n/**\n * Provides a set of fields that can be used to partially patch a document.\n * FieldMask is used in conjunction with ObjectValue.\n * Examples:\n * foo - Overwrites foo entirely with the provided value. If foo is not\n * present in the companion ObjectValue, the field is deleted.\n * foo.bar - Overwrites only the field bar of the object foo.\n * If foo is not an object, foo is replaced with an object\n * containing foo\n */\nvar FieldMask = /** @class */ (function () {\n function FieldMask(fields) {\n this.fields = fields;\n // TODO(dimond): validation of FieldMask\n }\n FieldMask.prototype.isEqual = function (other) {\n return misc.arrayEquals(this.fields, other.fields);\n };\n return FieldMask;\n}());\nexport { FieldMask };\n/** Transforms a value into a server-generated timestamp. */\nvar ServerTimestampTransform = /** @class */ (function () {\n function ServerTimestampTransform() {\n }\n ServerTimestampTransform.prototype.isEqual = function (other) {\n return other instanceof ServerTimestampTransform;\n };\n ServerTimestampTransform.instance = new ServerTimestampTransform();\n return ServerTimestampTransform;\n}());\nexport { ServerTimestampTransform };\n/** A field path and the TransformOperation to perform upon it. */\nvar FieldTransform = /** @class */ (function () {\n function FieldTransform(field, transform) {\n this.field = field;\n this.transform = transform;\n }\n FieldTransform.prototype.isEqual = function (other) {\n return (this.field.isEqual(other.field) && this.transform.isEqual(other.transform));\n };\n return FieldTransform;\n}());\nexport { FieldTransform };\n/** The result of successfully applying a mutation to the backend. */\nvar MutationResult = /** @class */ (function () {\n function MutationResult(\n /**\n * The version at which the mutation was committed or null for a delete.\n */\n version, \n /**\n * The resulting fields returned from the backend after a\n * TransformMutation has been committed. Contains one FieldValue for each\n * FieldTransform that was in the mutation.\n *\n * Will be null if the mutation was not a TransformMutation.\n */\n transformResults) {\n this.version = version;\n this.transformResults = transformResults;\n }\n return MutationResult;\n}());\nexport { MutationResult };\nexport var MutationType;\n(function (MutationType) {\n MutationType[MutationType[\"Set\"] = 0] = \"Set\";\n MutationType[MutationType[\"Patch\"] = 1] = \"Patch\";\n MutationType[MutationType[\"Transform\"] = 2] = \"Transform\";\n MutationType[MutationType[\"Delete\"] = 3] = \"Delete\";\n})(MutationType || (MutationType = {}));\n/**\n * Encodes a precondition for a mutation. This follows the model that the\n * backend accepts with the special case of an explicit \"empty\" precondition\n * (meaning no precondition).\n */\nvar Precondition = /** @class */ (function () {\n function Precondition(updateTime, exists) {\n this.updateTime = updateTime;\n this.exists = exists;\n assert(updateTime === undefined || exists === undefined, 'Precondition can specify \"exists\" or \"updateTime\" but not both');\n }\n /** Creates a new Precondition with an exists flag. */\n Precondition.exists = function (exists) {\n return new Precondition(undefined, exists);\n };\n /** Creates a new Precondition based on a version a document exists at. */\n Precondition.updateTime = function (version) {\n return new Precondition(version);\n };\n Object.defineProperty(Precondition.prototype, \"isNone\", {\n /** Returns whether this Precondition is empty. */\n get: function () {\n return this.updateTime === undefined && this.exists === undefined;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns true if the preconditions is valid for the given document\n * (or null if no document is available).\n */\n Precondition.prototype.isValidFor = function (maybeDoc) {\n if (this.updateTime !== undefined) {\n return (maybeDoc instanceof Document &&\n maybeDoc.version.isEqual(this.updateTime));\n }\n else if (this.exists !== undefined) {\n if (this.exists) {\n return maybeDoc instanceof Document;\n }\n else {\n return maybeDoc === null || maybeDoc instanceof NoDocument;\n }\n }\n else {\n assert(this.isNone, 'Precondition should be empty');\n return true;\n }\n };\n Precondition.prototype.isEqual = function (other) {\n return (misc.equals(this.updateTime, other.updateTime) &&\n this.exists === other.exists);\n };\n Precondition.NONE = new Precondition();\n return Precondition;\n}());\nexport { Precondition };\n/**\n * A mutation describes a self-contained change to a document. Mutations can\n * create, replace, delete, and update subsets of documents.\n *\n * Mutations not only act on the value of the document but also it version.\n * In the case of Set, Patch, and Transform mutations we preserve the existing\n * version. In the case of Delete mutations, we reset the version to 0.\n *\n * Here's the expected transition table.\n *\n * MUTATION APPLIED TO RESULTS IN\n *\n * SetMutation Document(v3) Document(v3)\n * SetMutation NoDocument(v3) Document(v0)\n * SetMutation null Document(v0)\n * PatchMutation Document(v3) Document(v3)\n * PatchMutation NoDocument(v3) NoDocument(v3)\n * PatchMutation null null\n * TransformMutation Document(v3) Document(v3)\n * TransformMutation NoDocument(v3) NoDocument(v3)\n * TransformMutation null null\n * DeleteMutation Document(v3) NoDocument(v0)\n * DeleteMutation NoDocument(v3) NoDocument(v0)\n * DeleteMutation null NoDocument(v0)\n *\n * Note that TransformMutations don't create Documents (in the case of being\n * applied to a NoDocument), even though they would on the backend. This is\n * because the client always combines the TransformMutation with a SetMutation\n * or PatchMutation and we only want to apply the transform if the prior\n * mutation resulted in a Document (always true for a SetMutation, but not\n * necessarily for a PatchMutation).\n *\n * ## Subclassing Notes\n *\n * Subclasses of Mutation need to implement applyToRemoteDocument() and\n * applyToLocalView() to implement the actual behavior of applying the mutation\n * to some source document.\n */\nvar Mutation = /** @class */ (function () {\n function Mutation() {\n }\n Mutation.prototype.verifyKeyMatches = function (maybeDoc) {\n if (maybeDoc != null) {\n assert(maybeDoc.key.isEqual(this.key), 'Can only apply a mutation to a document with the same key');\n }\n };\n /**\n * Returns the version from the given document for use as the result of a\n * mutation. Mutations are defined to return the version of the base document\n * only if it is an existing document. Deleted and unknown documents have a\n * post-mutation version of SnapshotVersion.MIN.\n */\n Mutation.getPostMutationVersion = function (maybeDoc) {\n if (maybeDoc instanceof Document) {\n return maybeDoc.version;\n }\n else {\n return SnapshotVersion.MIN;\n }\n };\n return Mutation;\n}());\nexport { Mutation };\n/**\n * A mutation that creates or replaces the document at the given key with the\n * object value contents.\n */\nvar SetMutation = /** @class */ (function (_super) {\n __extends(SetMutation, _super);\n function SetMutation(key, value, precondition) {\n var _this = _super.call(this) || this;\n _this.key = key;\n _this.value = value;\n _this.precondition = precondition;\n _this.type = MutationType.Set;\n return _this;\n }\n SetMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\n this.verifyKeyMatches(maybeDoc);\n assert(mutationResult.transformResults == null, 'Transform results received by SetMutation.');\n // Unlike applyToLocalView, if we're applying a mutation to a remote\n // document the server has accepted the mutation so the precondition must\n // have held.\n var version = Mutation.getPostMutationVersion(maybeDoc);\n return new Document(this.key, version, this.value, {\n hasLocalMutations: false\n });\n };\n SetMutation.prototype.applyToLocalView = function (maybeDoc, baseDoc, localWriteTime) {\n this.verifyKeyMatches(maybeDoc);\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n var version = Mutation.getPostMutationVersion(maybeDoc);\n return new Document(this.key, version, this.value, {\n hasLocalMutations: true\n });\n };\n SetMutation.prototype.isEqual = function (other) {\n return (other instanceof SetMutation &&\n this.key.isEqual(other.key) &&\n this.value.isEqual(other.value) &&\n this.precondition.isEqual(other.precondition));\n };\n return SetMutation;\n}(Mutation));\nexport { SetMutation };\n/**\n * A mutation that modifies fields of the document at the given key with the\n * given values. The values are applied through a field mask:\n *\n * * When a field is in both the mask and the values, the corresponding field\n * is updated.\n * * When a field is in neither the mask nor the values, the corresponding\n * field is unmodified.\n * * When a field is in the mask but not in the values, the corresponding field\n * is deleted.\n * * When a field is not in the mask but is in the values, the values map is\n * ignored.\n */\nvar PatchMutation = /** @class */ (function (_super) {\n __extends(PatchMutation, _super);\n function PatchMutation(key, data, fieldMask, precondition) {\n var _this = _super.call(this) || this;\n _this.key = key;\n _this.data = data;\n _this.fieldMask = fieldMask;\n _this.precondition = precondition;\n _this.type = MutationType.Patch;\n return _this;\n }\n PatchMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\n this.verifyKeyMatches(maybeDoc);\n assert(mutationResult.transformResults == null, 'Transform results received by PatchMutation.');\n // TODO(mcg): Relax enforcement of this precondition\n //\n // We shouldn't actually enforce the precondition since it already passed on\n // the backend, but we may not have a local version of the document to\n // patch, so we use the precondition to prevent incorrectly putting a\n // partial document into our cache.\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n var version = Mutation.getPostMutationVersion(maybeDoc);\n var newData = this.patchDocument(maybeDoc);\n return new Document(this.key, version, newData, {\n hasLocalMutations: false\n });\n };\n PatchMutation.prototype.applyToLocalView = function (maybeDoc, baseDoc, localWriteTime) {\n this.verifyKeyMatches(maybeDoc);\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n var version = Mutation.getPostMutationVersion(maybeDoc);\n var newData = this.patchDocument(maybeDoc);\n return new Document(this.key, version, newData, {\n hasLocalMutations: true\n });\n };\n PatchMutation.prototype.isEqual = function (other) {\n return (other instanceof PatchMutation &&\n this.key.isEqual(other.key) &&\n this.fieldMask.isEqual(other.fieldMask) &&\n this.precondition.isEqual(other.precondition));\n };\n /**\n * Patches the data of document if available or creates a new document. Note\n * that this does not check whether or not the precondition of this patch\n * holds.\n */\n PatchMutation.prototype.patchDocument = function (maybeDoc) {\n var data;\n if (maybeDoc instanceof Document) {\n data = maybeDoc.data;\n }\n else {\n data = ObjectValue.EMPTY;\n }\n return this.patchObject(data);\n };\n PatchMutation.prototype.patchObject = function (data) {\n for (var _i = 0, _a = this.fieldMask.fields; _i < _a.length; _i++) {\n var fieldPath = _a[_i];\n var newValue = this.data.field(fieldPath);\n if (newValue !== undefined) {\n data = data.set(fieldPath, newValue);\n }\n else {\n data = data.delete(fieldPath);\n }\n }\n return data;\n };\n return PatchMutation;\n}(Mutation));\nexport { PatchMutation };\n/**\n * A mutation that modifies specific fields of the document with transform\n * operations. Currently the only supported transform is a server timestamp, but\n * IP Address, increment(n), etc. could be supported in the future.\n *\n * It is somewhat similar to a PatchMutation in that it patches specific fields\n * and has no effect when applied to a null or NoDocument (see comment on\n * Mutation for rationale).\n */\nvar TransformMutation = /** @class */ (function (_super) {\n __extends(TransformMutation, _super);\n function TransformMutation(key, fieldTransforms) {\n var _this = _super.call(this) || this;\n _this.key = key;\n _this.fieldTransforms = fieldTransforms;\n _this.type = MutationType.Transform;\n // NOTE: We set a precondition of exists: true as a safety-check, since we\n // always combine TransformMutations with a SetMutation or PatchMutation which\n // (if successful) should end up with an existing document.\n _this.precondition = Precondition.exists(true);\n return _this;\n }\n TransformMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\n this.verifyKeyMatches(maybeDoc);\n assert(mutationResult.transformResults != null, 'Transform results missing for TransformMutation.');\n var transformResults = mutationResult.transformResults;\n // TODO(mcg): Relax enforcement of this precondition\n //\n // We shouldn't actually enforce the precondition since it already passed on\n // the backend, but we may not have a local version of the document to\n // patch, so we use the precondition to prevent incorrectly putting a\n // partial document into our cache.\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n var doc = this.requireDocument(maybeDoc);\n var newData = this.transformObject(doc.data, transformResults);\n return new Document(this.key, doc.version, newData, {\n hasLocalMutations: false\n });\n };\n TransformMutation.prototype.applyToLocalView = function (maybeDoc, baseDoc, localWriteTime) {\n this.verifyKeyMatches(maybeDoc);\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n var doc = this.requireDocument(maybeDoc);\n var transformResults = this.localTransformResults(localWriteTime, baseDoc);\n var newData = this.transformObject(doc.data, transformResults);\n return new Document(this.key, doc.version, newData, {\n hasLocalMutations: true\n });\n };\n TransformMutation.prototype.isEqual = function (other) {\n return (other instanceof TransformMutation &&\n this.key.isEqual(other.key) &&\n misc.arrayEquals(this.fieldTransforms, other.fieldTransforms) &&\n this.precondition.isEqual(other.precondition));\n };\n /**\n * Asserts that the given MaybeDocument is actually a Document and verifies\n * that it matches the key for this mutation. Since we only support\n * transformations with precondition exists this method is guaranteed to be\n * safe.\n */\n TransformMutation.prototype.requireDocument = function (maybeDoc) {\n assert(maybeDoc instanceof Document, 'Unknown MaybeDocument type ' + maybeDoc);\n var doc = maybeDoc;\n assert(doc.key.isEqual(this.key), 'Can only transform a document with the same key');\n return doc;\n };\n /**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use when applying a\n * TransformMutation locally.\n *\n * @param localWriteTime The local time of the transform mutation (used to\n * generate ServerTimestampValues).\n * @param baseDoc The document prior to applying this mutation batch.\n * @return The transform results list.\n */\n TransformMutation.prototype.localTransformResults = function (localWriteTime, baseDoc) {\n var transformResults = [];\n for (var _i = 0, _a = this.fieldTransforms; _i < _a.length; _i++) {\n var fieldTransform = _a[_i];\n var transform = fieldTransform.transform;\n if (transform instanceof ServerTimestampTransform) {\n var previousValue = null;\n if (baseDoc instanceof Document) {\n previousValue = baseDoc.field(fieldTransform.field) || null;\n }\n transformResults.push(new ServerTimestampValue(localWriteTime, previousValue));\n }\n else {\n return fail('Encountered unknown transform: ' + transform);\n }\n }\n return transformResults;\n };\n TransformMutation.prototype.transformObject = function (data, transformResults) {\n assert(transformResults.length === this.fieldTransforms.length, 'TransformResults length mismatch.');\n for (var i = 0; i < this.fieldTransforms.length; i++) {\n var fieldTransform = this.fieldTransforms[i];\n var transform = fieldTransform.transform;\n var fieldPath = fieldTransform.field;\n if (transform instanceof ServerTimestampTransform) {\n data = data.set(fieldPath, transformResults[i]);\n }\n else {\n return fail('Encountered unknown transform: ' + transform);\n }\n }\n return data;\n };\n return TransformMutation;\n}(Mutation));\nexport { TransformMutation };\n/** A mutation that deletes the document at the given key. */\nvar DeleteMutation = /** @class */ (function (_super) {\n __extends(DeleteMutation, _super);\n function DeleteMutation(key, precondition) {\n var _this = _super.call(this) || this;\n _this.key = key;\n _this.precondition = precondition;\n _this.type = MutationType.Delete;\n return _this;\n }\n DeleteMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\n this.verifyKeyMatches(maybeDoc);\n assert(mutationResult.transformResults == null, 'Transform results received by DeleteMutation.');\n // Unlike applyToLocalView, if we're applying a mutation to a remote\n // document the server has accepted the mutation so the precondition must\n // have held.\n return new NoDocument(this.key, SnapshotVersion.MIN);\n };\n DeleteMutation.prototype.applyToLocalView = function (maybeDoc, baseDoc, localWriteTime) {\n this.verifyKeyMatches(maybeDoc);\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n if (maybeDoc) {\n assert(maybeDoc.key.isEqual(this.key), 'Can only apply mutation to document with same key');\n }\n return new NoDocument(this.key, SnapshotVersion.forDeletedDoc());\n };\n DeleteMutation.prototype.isEqual = function (other) {\n return (other instanceof DeleteMutation &&\n this.key.isEqual(other.key) &&\n this.precondition.isEqual(other.precondition));\n };\n return DeleteMutation;\n}(Mutation));\nexport { DeleteMutation };\n\n//# sourceMappingURL=mutation.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/model/mutation.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar ExistenceFilter = /** @class */ (function () {\n // TODO(b/33078163): just use simplest form of existence filter for now\n function ExistenceFilter(count) {\n this.count = count;\n }\n ExistenceFilter.prototype.isEqual = function (other) {\n return other && other.count === this.count;\n };\n return ExistenceFilter;\n}());\nexport { ExistenceFilter };\n\n//# sourceMappingURL=existence_filter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/remote/existence_filter.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { SortedMap } from './sorted_map';\n/**\n * SortedSet is an immutable (copy-on-write) collection that holds elements\n * in order specified by the provided comparator.\n *\n * NOTE: if provided comparator returns 0 for two elements, we consider them to\n * be equal!\n */\nvar SortedSet = /** @class */ (function () {\n function SortedSet(comparator) {\n this.comparator = comparator;\n this.data = new SortedMap(this.comparator);\n }\n /**\n * Creates a SortedSet from the keys of the map.\n * This is currently implemented as an O(n) copy.\n */\n SortedSet.fromMapKeys = function (map) {\n var keys = new SortedSet(map.comparator);\n map.forEach(function (key) {\n keys = keys.add(key);\n });\n return keys;\n };\n SortedSet.prototype.has = function (elem) {\n return this.data.get(elem) !== null;\n };\n SortedSet.prototype.first = function () {\n return this.data.minKey();\n };\n SortedSet.prototype.last = function () {\n return this.data.maxKey();\n };\n Object.defineProperty(SortedSet.prototype, \"size\", {\n get: function () {\n return this.data.size;\n },\n enumerable: true,\n configurable: true\n });\n SortedSet.prototype.indexOf = function (elem) {\n return this.data.indexOf(elem);\n };\n /** Iterates elements in order defined by \"comparator\" */\n SortedSet.prototype.forEach = function (cb) {\n this.data.inorderTraversal(function (k, v) {\n cb(k);\n return false;\n });\n };\n /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */\n SortedSet.prototype.forEachInRange = function (range, cb) {\n var iter = this.data.getIteratorFrom(range[0]);\n while (iter.hasNext()) {\n var elem = iter.getNext();\n if (this.comparator(elem.key, range[1]) >= 0)\n return;\n cb(elem.key);\n }\n };\n /**\n * Iterates over `elem`s such that: start <= elem until false is returned.\n */\n SortedSet.prototype.forEachWhile = function (cb, start) {\n var iter;\n if (start !== undefined) {\n iter = this.data.getIteratorFrom(start);\n }\n else {\n iter = this.data.getIterator();\n }\n while (iter.hasNext()) {\n var elem = iter.getNext();\n var result = cb(elem.key);\n if (!result)\n return;\n }\n };\n /** Finds the least element greater than or equal to `elem`. */\n SortedSet.prototype.firstAfterOrEqual = function (elem) {\n var iter = this.data.getIteratorFrom(elem);\n return iter.hasNext() ? iter.getNext().key : null;\n };\n /** Inserts or updates an element */\n SortedSet.prototype.add = function (elem) {\n return this.copy(this.data.remove(elem).insert(elem, true));\n };\n /** Deletes an element */\n SortedSet.prototype.delete = function (elem) {\n if (!this.has(elem))\n return this;\n return this.copy(this.data.remove(elem));\n };\n SortedSet.prototype.isEmpty = function () {\n return this.data.isEmpty();\n };\n SortedSet.prototype.unionWith = function (other) {\n var result = this;\n other.forEach(function (elem) {\n result = result.add(elem);\n });\n return result;\n };\n SortedSet.prototype.isEqual = function (other) {\n if (!(other instanceof SortedSet))\n return false;\n if (this.size !== other.size)\n return false;\n var thisIt = this.data.getIterator();\n var otherIt = other.data.getIterator();\n while (thisIt.hasNext()) {\n var thisElem = thisIt.getNext().key;\n var otherElem = otherIt.getNext().key;\n if (this.comparator(thisElem, otherElem) !== 0)\n return false;\n }\n return true;\n };\n SortedSet.prototype.toString = function () {\n var result = [];\n this.forEach(function (elem) { return result.push(elem); });\n return 'SortedSet(' + result.toString() + ')';\n };\n SortedSet.prototype.copy = function (data) {\n var result = new SortedSet(this.comparator);\n result.data = data;\n return result;\n };\n return SortedSet;\n}());\nexport { SortedSet };\n\n//# sourceMappingURL=sorted_set.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/sorted_set.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { documentKeySet } from '../model/collections';\nimport { emptyByteString } from '../platform/platform';\n/**\n * An event from the RemoteStore. It is split into targetChanges (changes to the\n * state or the set of documents in our watched targets) and documentUpdates\n * (changes to the actual documents).\n */\nvar RemoteEvent = /** @class */ (function () {\n function RemoteEvent(\n /**\n * The snapshot version this event brings us up to, or MIN if not set.\n */\n snapshotVersion, \n /**\n * A map from target to changes to the target. See TargetChange.\n */\n targetChanges, \n /**\n * A set of which documents have changed or been deleted, along with the\n * doc's new values (if not deleted).\n */\n documentUpdates) {\n this.snapshotVersion = snapshotVersion;\n this.targetChanges = targetChanges;\n this.documentUpdates = documentUpdates;\n }\n RemoteEvent.prototype.addDocumentUpdate = function (doc) {\n this.documentUpdates = this.documentUpdates.insert(doc.key, doc);\n };\n RemoteEvent.prototype.handleExistenceFilterMismatch = function (targetId) {\n /*\n * An existence filter mismatch will reset the query and we need to reset\n * the mapping to contain no documents and an empty resume token.\n *\n * Note:\n * * The reset mapping is empty, specifically forcing the consumer of the\n * change to forget all keys for this targetID;\n * * The resume snapshot for this target must be reset\n * * The target must be unacked because unwatching and rewatching\n * introduces a race for changes.\n */\n this.targetChanges[targetId] = {\n mapping: new ResetMapping(),\n snapshotVersion: SnapshotVersion.MIN,\n currentStatusUpdate: CurrentStatusUpdate.MarkNotCurrent,\n resumeToken: emptyByteString()\n };\n };\n return RemoteEvent;\n}());\nexport { RemoteEvent };\n/**\n * Represents an update to the current status of a target, either explicitly\n * having no new state, or the new value to set. Note \"current\" has special\n * meaning for in the RPC protocol that implies that a target is both up-to-date\n * and consistent with the rest of the watch stream.\n */\nexport var CurrentStatusUpdate;\n(function (CurrentStatusUpdate) {\n /** The current status is not affected and should not be modified. */\n CurrentStatusUpdate[CurrentStatusUpdate[\"None\"] = 0] = \"None\";\n /** The target must be marked as no longer \"current\". */\n CurrentStatusUpdate[CurrentStatusUpdate[\"MarkNotCurrent\"] = 1] = \"MarkNotCurrent\";\n /** The target must be marked as \"current\". */\n CurrentStatusUpdate[CurrentStatusUpdate[\"MarkCurrent\"] = 2] = \"MarkCurrent\";\n})(CurrentStatusUpdate || (CurrentStatusUpdate = {}));\nvar EMPTY_KEY_SET = documentKeySet();\nvar ResetMapping = /** @class */ (function () {\n function ResetMapping() {\n this.docs = EMPTY_KEY_SET;\n }\n Object.defineProperty(ResetMapping.prototype, \"documents\", {\n get: function () {\n return this.docs;\n },\n enumerable: true,\n configurable: true\n });\n ResetMapping.prototype.add = function (key) {\n this.docs = this.docs.add(key);\n };\n ResetMapping.prototype.delete = function (key) {\n this.docs = this.docs.delete(key);\n };\n ResetMapping.prototype.isEqual = function (other) {\n return other !== null && this.docs.isEqual(other.docs);\n };\n return ResetMapping;\n}());\nexport { ResetMapping };\nvar UpdateMapping = /** @class */ (function () {\n function UpdateMapping() {\n this.addedDocuments = EMPTY_KEY_SET;\n this.removedDocuments = EMPTY_KEY_SET;\n }\n UpdateMapping.prototype.applyToKeySet = function (keys) {\n var result = keys;\n this.addedDocuments.forEach(function (key) { return (result = result.add(key)); });\n this.removedDocuments.forEach(function (key) { return (result = result.delete(key)); });\n return result;\n };\n UpdateMapping.prototype.add = function (key) {\n this.addedDocuments = this.addedDocuments.add(key);\n this.removedDocuments = this.removedDocuments.delete(key);\n };\n UpdateMapping.prototype.delete = function (key) {\n this.addedDocuments = this.addedDocuments.delete(key);\n this.removedDocuments = this.removedDocuments.add(key);\n };\n UpdateMapping.prototype.isEqual = function (other) {\n return (other !== null &&\n this.addedDocuments.isEqual(other.addedDocuments) &&\n this.removedDocuments.isEqual(other.removedDocuments));\n };\n return UpdateMapping;\n}());\nexport { UpdateMapping };\n\n//# sourceMappingURL=remote_event.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/remote/remote_event.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { assert } from '../util/assert';\n/**\n * Provides a simple helper class that implements the Stream interface to\n * bridge to other implementations that are streams but do not implement the\n * interface. The stream callbacks are invoked with the callOn... methods.\n */\nvar StreamBridge = /** @class */ (function () {\n function StreamBridge(args) {\n this.sendFn = args.sendFn;\n this.closeFn = args.closeFn;\n }\n StreamBridge.prototype.onOpen = function (callback) {\n assert(!this.wrappedOnOpen, 'Called onOpen on stream twice!');\n this.wrappedOnOpen = callback;\n };\n StreamBridge.prototype.onClose = function (callback) {\n assert(!this.wrappedOnClose, 'Called onClose on stream twice!');\n this.wrappedOnClose = callback;\n };\n StreamBridge.prototype.onMessage = function (callback) {\n assert(!this.wrappedOnMessage, 'Called onMessage on stream twice!');\n this.wrappedOnMessage = callback;\n };\n StreamBridge.prototype.close = function () {\n this.closeFn();\n };\n StreamBridge.prototype.send = function (msg) {\n this.sendFn(msg);\n };\n StreamBridge.prototype.callOnOpen = function () {\n assert(this.wrappedOnOpen !== undefined, 'Cannot call onOpen because no callback was set');\n this.wrappedOnOpen();\n };\n StreamBridge.prototype.callOnClose = function (err) {\n assert(this.wrappedOnClose !== undefined, 'Cannot call onClose because no callback was set');\n this.wrappedOnClose(err);\n };\n StreamBridge.prototype.callOnMessage = function (msg) {\n assert(this.wrappedOnMessage !== undefined, 'Cannot call onMessage because no callback was set');\n this.wrappedOnMessage(msg);\n };\n return StreamBridge;\n}());\nexport { StreamBridge };\n\n//# sourceMappingURL=stream_bridge.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/remote/stream_bridge.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { ErrorCode, EventType, WebChannel, XhrIoPool, createWebChannelTransport } from '@firebase/webchannel-wrapper';\nimport { SDK_VERSION } from '../core/version';\nimport { mapCodeFromHttpStatus, mapCodeFromRpcStatus } from '../remote/rpc_error';\nimport { StreamBridge } from '../remote/stream_bridge';\nimport { assert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport * as log from '../util/log';\nvar LOG_TAG = 'Connection';\nvar RPC_STREAM_SERVICE = 'google.firestore.v1beta1.Firestore';\nvar RPC_URL_VERSION = 'v1beta1';\n/** Maps RPC names to the corresponding REST endpoint name. */\nvar RPC_NAME_REST_MAPPING = {\n BatchGetDocuments: 'batchGet',\n Commit: 'commit'\n};\n// TODO(b/38203344): The SDK_VERSION is set independently from Firebase because\n// we are doing out-of-band releases. Once we release as part of Firebase, we\n// should use the Firebase version instead.\nvar X_GOOG_API_CLIENT_VALUE = 'gl-js/ fire/' + SDK_VERSION;\nvar XHR_TIMEOUT_SECS = 15;\nvar WebChannelConnection = /** @class */ (function () {\n function WebChannelConnection(info) {\n this.databaseId = info.databaseId;\n this.pool = new XhrIoPool();\n var proto = info.ssl ? 'https' : 'http';\n this.baseUrl = proto + '://' + info.host;\n }\n /**\n * Modifies the headers for a request, adding any authorization token if\n * present and any additional headers for the request.\n */\n WebChannelConnection.prototype.modifyHeadersForRequest = function (headers, token) {\n if (token) {\n for (var header in token.authHeaders) {\n if (token.authHeaders.hasOwnProperty(header)) {\n headers[header] = token.authHeaders[header];\n }\n }\n }\n headers['X-Goog-Api-Client'] = X_GOOG_API_CLIENT_VALUE;\n // This header is used to improve routing and project isolation by the\n // backend.\n headers['google-cloud-resource-prefix'] =\n \"projects/\" + this.databaseId.projectId + \"/\" +\n (\"databases/\" + this.databaseId.database);\n };\n WebChannelConnection.prototype.invokeRPC = function (rpcName, request, token) {\n var _this = this;\n var url = this.makeUrl(rpcName);\n return new Promise(function (resolve, reject) {\n // tslint:disable-next-line:no-any XhrIoPool doesn't have TS typings.\n _this.pool.getObject(function (xhr) {\n xhr.listenOnce(EventType.COMPLETE, function () {\n try {\n switch (xhr.getLastErrorCode()) {\n case ErrorCode.NO_ERROR:\n var json = xhr.getResponseJson();\n log.debug(LOG_TAG, 'XHR received:', JSON.stringify(json));\n resolve(json);\n break;\n case ErrorCode.TIMEOUT:\n log.debug(LOG_TAG, 'RPC \"' + rpcName + '\" timed out');\n reject(new FirestoreError(Code.DEADLINE_EXCEEDED, 'Request time out'));\n break;\n case ErrorCode.HTTP_ERROR:\n var status_1 = xhr.getStatus();\n log.debug(LOG_TAG, 'RPC \"' + rpcName + '\" failed with status:', status_1, 'response text:', xhr.getResponseText());\n if (status_1 > 0) {\n reject(new FirestoreError(mapCodeFromHttpStatus(status_1), 'Server responded with status ' + xhr.getStatusText()));\n }\n else {\n // If we received an HTTP_ERROR but there's no status code,\n // it's most probably a connection issue\n log.debug(LOG_TAG, 'RPC \"' + rpcName + '\" failed');\n reject(new FirestoreError(Code.UNAVAILABLE, 'Connection failed.'));\n }\n break;\n default:\n fail('RPC \"' +\n rpcName +\n '\" failed with unanticipated ' +\n 'webchannel error ' +\n xhr.getLastErrorCode() +\n ': ' +\n xhr.getLastError() +\n ', giving up.');\n }\n }\n finally {\n log.debug(LOG_TAG, 'RPC \"' + rpcName + '\" completed.');\n _this.pool.releaseObject(xhr);\n }\n });\n var requestString = JSON.stringify(request);\n log.debug(LOG_TAG, 'XHR sending: ', url + ' ' + requestString);\n // Content-Type: text/plain will avoid preflight requests which might\n // mess with CORS and redirects by proxies. If we add custom headers\n // we will need to change this code to potentially use the\n // $httpOverwrite parameter supported by ESF to avoid\n // triggering preflight requests.\n var headers = { 'Content-Type': 'text/plain' };\n _this.modifyHeadersForRequest(headers, token);\n xhr.send(url, 'POST', requestString, headers, XHR_TIMEOUT_SECS);\n });\n });\n };\n WebChannelConnection.prototype.invokeStreamingRPC = function (rpcName, request, token) {\n // The REST API automatically aggregates all of the streamed results, so we\n // can just use the normal invoke() method.\n return this.invokeRPC(rpcName, request, token);\n };\n WebChannelConnection.prototype.openStream = function (rpcName, token) {\n var urlParts = [\n this.baseUrl,\n '/',\n RPC_STREAM_SERVICE,\n '/',\n rpcName,\n '/channel'\n ];\n var webchannelTransport = createWebChannelTransport();\n var request = {\n // Background channel test avoids the initial two test calls and decreases\n // initial cold start time.\n // TODO(dimond): wenboz@ mentioned this might affect use with proxies and\n // we should monitor closely for any reports.\n backgroundChannelTest: true,\n // Required for backend stickiness, routing behavior is based on this\n // parameter.\n httpSessionIdParam: 'gsessionid',\n initMessageHeaders: {},\n // Send our custom headers as a '$httpHeaders=' url param to avoid CORS\n // preflight round-trip. This is formally defined here:\n // https://github.com/google/closure-library/blob/b0e1815b13fb92a46d7c9b3c30de5d6a396a3245/closure/goog/net/rpc/httpcors.js#L40\n httpHeadersOverwriteParam: '$httpHeaders',\n sendRawJson: true,\n supportsCrossDomainXhr: true\n };\n this.modifyHeadersForRequest(request.initMessageHeaders, token);\n var url = urlParts.join('');\n log.debug(LOG_TAG, 'Creating WebChannel: ' + url + ' ' + request);\n // tslint:disable-next-line:no-any Because listen isn't defined on it.\n var channel = webchannelTransport.createWebChannel(url, request);\n // WebChannel supports sending the first message with the handshake - saving\n // a network round trip. However, it will have to call send in the same\n // JS event loop as open. In order to enforce this, we delay actually\n // opening the WebChannel until send is called. Whether we have called\n // open is tracked with this variable.\n var opened = false;\n // A flag to determine whether the stream was closed (by us or through an\n // error/close event) to avoid delivering multiple close events or sending\n // on a closed stream\n var closed = false;\n var streamBridge = new StreamBridge({\n sendFn: function (msg) {\n if (!closed) {\n if (!opened) {\n log.debug(LOG_TAG, 'Opening WebChannel transport.');\n channel.open();\n opened = true;\n }\n log.debug(LOG_TAG, 'WebChannel sending:', msg);\n channel.send(msg);\n }\n else {\n log.debug(LOG_TAG, 'Not sending because WebChannel is closed:', msg);\n }\n },\n closeFn: function () { return channel.close(); }\n });\n // Closure events are guarded and exceptions are swallowed, so catch any\n // exception and rethrow using a setTimeout so they become visible again.\n // Note that eventually this function could go away if we are confident\n // enough the code is exception free.\n var unguardedEventListen = function (type, fn) {\n // TODO(dimond): closure typing seems broken because WebChannel does\n // not implement goog.events.Listenable\n channel.listen(type, function (param) {\n try {\n fn(param);\n }\n catch (e) {\n setTimeout(function () {\n throw e;\n }, 0);\n }\n });\n };\n unguardedEventListen(WebChannel.EventType.OPEN, function () {\n if (!closed) {\n log.debug(LOG_TAG, 'WebChannel transport opened.');\n }\n });\n unguardedEventListen(WebChannel.EventType.CLOSE, function () {\n if (!closed) {\n closed = true;\n log.debug(LOG_TAG, 'WebChannel transport closed');\n streamBridge.callOnClose();\n }\n });\n unguardedEventListen(WebChannel.EventType.ERROR, function (err) {\n if (!closed) {\n closed = true;\n log.debug(LOG_TAG, 'WebChannel transport errored:', err);\n streamBridge.callOnClose(new FirestoreError(Code.UNAVAILABLE, 'The operation could not be completed'));\n }\n });\n unguardedEventListen(WebChannel.EventType.MESSAGE, function (msg) {\n if (!closed) {\n var msgData = msg.data[0];\n assert(!!msgData, 'Got a webchannel message without data.');\n // TODO(b/35143891): There is a bug in One Platform that caused errors\n // (and only errors) to be wrapped in an extra array. To be forward\n // compatible with the bug we need to check either condition. The latter\n // can be removed once the fix has been rolled out.\n var error = \n // tslint:disable-next-line:no-any msgData.error is not typed.\n msgData.error || (msgData[0] && msgData[0].error);\n if (error) {\n log.debug(LOG_TAG, 'WebChannel received error:', error);\n // error.status will be a string like 'OK' or 'NOT_FOUND'.\n var status_2 = error.status;\n var code = mapCodeFromRpcStatus(status_2);\n var message = error.message;\n if (code === undefined) {\n code = Code.INTERNAL;\n message =\n 'Unknown error status: ' +\n status_2 +\n ' with message ' +\n error.message;\n }\n // Mark closed so no further events are propagated\n closed = true;\n streamBridge.callOnClose(new FirestoreError(code, message));\n channel.close();\n }\n else {\n log.debug(LOG_TAG, 'WebChannel received:', msgData);\n streamBridge.callOnMessage(msgData);\n }\n }\n });\n setTimeout(function () {\n // Technically we could/should wait for the WebChannel opened event,\n // but because we want to send the first message with the WebChannel\n // handshake we pretend the channel opened here (asynchronously), and\n // then delay the actual open until the first message is sent.\n streamBridge.callOnOpen();\n }, 0);\n return streamBridge;\n };\n // visible for testing\n WebChannelConnection.prototype.makeUrl = function (rpcName) {\n var urlRpcName = RPC_NAME_REST_MAPPING[rpcName];\n assert(urlRpcName !== undefined, 'Unknown REST mapping for: ' + rpcName);\n var url = [this.baseUrl, '/', RPC_URL_VERSION];\n url.push('/projects/');\n url.push(this.databaseId.projectId);\n url.push('/databases/');\n url.push(this.databaseId.database);\n url.push('/documents');\n url.push(':');\n url.push(urlRpcName);\n return url.join('');\n };\n return WebChannelConnection;\n}());\nexport { WebChannelConnection };\n\n//# sourceMappingURL=webchannel_connection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/platform_browser/webchannel_connection.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { WebChannelConnection } from './webchannel_connection';\nvar BrowserPlatform = /** @class */ (function () {\n function BrowserPlatform() {\n this.emptyByteString = '';\n this.base64Available = typeof atob !== 'undefined';\n }\n BrowserPlatform.prototype.loadConnection = function (databaseInfo) {\n return Promise.resolve(new WebChannelConnection(databaseInfo));\n };\n BrowserPlatform.prototype.newSerializer = function (databaseId) {\n return new JsonProtoSerializer(databaseId, { useProto3Json: true });\n };\n BrowserPlatform.prototype.formatJSON = function (value) {\n return JSON.stringify(value);\n };\n BrowserPlatform.prototype.atob = function (encoded) {\n return atob(encoded);\n };\n BrowserPlatform.prototype.btoa = function (raw) {\n return btoa(raw);\n };\n return BrowserPlatform;\n}());\nexport { BrowserPlatform };\n\n//# sourceMappingURL=browser_platform.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/platform_browser/browser_platform.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { PlatformSupport } from '../platform/platform';\nimport { BrowserPlatform } from './browser_platform';\n/**\n * This code needs to run before Firestore is used. This can be achieved in\n * several ways:\n * 1) Through the JSCompiler compiling this code and then (automatically)\n * executing it before exporting the Firestore symbols.\n * 2) Through importing this module first in a Firestore main module\n */\nPlatformSupport.setPlatform(new BrowserPlatform());\n\n//# sourceMappingURL=browser_init.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/platform_browser/browser_init.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Describes the online state of the Firestore client. Note that this does not\n * indicate whether or not the remote store is trying to connect or not. This is\n * primarily used by the View / EventManager code to change their behavior while\n * offline (e.g. get() calls shouldn't wait for data from the server and\n * snapshot events should set metadata.isFromCache=true).\n */\nexport var OnlineState;\n(function (OnlineState) {\n /**\n * The Firestore client is in an unknown online state. This means the client\n * is either not actively trying to establish a connection or it is currently\n * trying to establish a connection, but it has not succeeded or failed yet.\n * Higher-level components should not operate in offline mode.\n */\n OnlineState[OnlineState[\"Unknown\"] = 0] = \"Unknown\";\n /**\n * The client is connected and the connections are healthy. This state is\n * reached after a successful connection and there has been at least one\n * successful message received from the backends.\n */\n OnlineState[OnlineState[\"Healthy\"] = 1] = \"Healthy\";\n /**\n * The client is either trying to establish a connection but failing, or it\n * has been explicitly marked offline via a call to disableNetwork().\n * Higher-level components should operate in offline mode.\n */\n OnlineState[OnlineState[\"Failed\"] = 2] = \"Failed\";\n})(OnlineState || (OnlineState = {}));\n\n//# sourceMappingURL=types.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/types.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { DocumentKey } from '../model/document_key';\nimport { fail } from '../util/assert';\nimport { SortedMap } from '../util/sorted_map';\nexport var ChangeType;\n(function (ChangeType) {\n ChangeType[ChangeType[\"Added\"] = 0] = \"Added\";\n ChangeType[ChangeType[\"Removed\"] = 1] = \"Removed\";\n ChangeType[ChangeType[\"Modified\"] = 2] = \"Modified\";\n ChangeType[ChangeType[\"Metadata\"] = 3] = \"Metadata\";\n})(ChangeType || (ChangeType = {}));\nexport var SyncState;\n(function (SyncState) {\n SyncState[SyncState[\"Local\"] = 0] = \"Local\";\n SyncState[SyncState[\"Synced\"] = 1] = \"Synced\";\n})(SyncState || (SyncState = {}));\n/**\n * DocumentChangeSet keeps track of a set of changes to docs in a query, merging\n * duplicate events for the same doc.\n */\nvar DocumentChangeSet = /** @class */ (function () {\n function DocumentChangeSet() {\n this.changeMap = new SortedMap(DocumentKey.comparator);\n }\n DocumentChangeSet.prototype.track = function (change) {\n var key = change.doc.key;\n var oldChange = this.changeMap.get(key);\n if (!oldChange) {\n this.changeMap = this.changeMap.insert(key, change);\n return;\n }\n // Merge the new change with the existing change.\n if (change.type !== ChangeType.Added &&\n oldChange.type === ChangeType.Metadata) {\n this.changeMap = this.changeMap.insert(key, change);\n }\n else if (change.type === ChangeType.Metadata &&\n oldChange.type !== ChangeType.Removed) {\n this.changeMap = this.changeMap.insert(key, {\n type: oldChange.type,\n doc: change.doc\n });\n }\n else if (change.type === ChangeType.Modified &&\n oldChange.type === ChangeType.Modified) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Modified,\n doc: change.doc\n });\n }\n else if (change.type === ChangeType.Modified &&\n oldChange.type === ChangeType.Added) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Added,\n doc: change.doc\n });\n }\n else if (change.type === ChangeType.Removed &&\n oldChange.type === ChangeType.Added) {\n this.changeMap = this.changeMap.remove(key);\n }\n else if (change.type === ChangeType.Removed &&\n oldChange.type === ChangeType.Modified) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Removed,\n doc: oldChange.doc\n });\n }\n else if (change.type === ChangeType.Added &&\n oldChange.type === ChangeType.Removed) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Modified,\n doc: change.doc\n });\n }\n else {\n // This includes these cases, which don't make sense:\n // Added->Added\n // Removed->Removed\n // Modified->Added\n // Removed->Modified\n // Metadata->Added\n // Removed->Metadata\n fail('unsupported combination of changes: ' +\n JSON.stringify(change) +\n ' after ' +\n JSON.stringify(oldChange));\n }\n };\n DocumentChangeSet.prototype.getChanges = function () {\n var changes = [];\n this.changeMap.inorderTraversal(function (key, change) {\n changes.push(change);\n });\n return changes;\n };\n return DocumentChangeSet;\n}());\nexport { DocumentChangeSet };\nvar ViewSnapshot = /** @class */ (function () {\n function ViewSnapshot(query, docs, oldDocs, docChanges, fromCache, hasPendingWrites, syncStateChanged) {\n this.query = query;\n this.docs = docs;\n this.oldDocs = oldDocs;\n this.docChanges = docChanges;\n this.fromCache = fromCache;\n this.hasPendingWrites = hasPendingWrites;\n this.syncStateChanged = syncStateChanged;\n }\n ViewSnapshot.prototype.isEqual = function (other) {\n if (this.fromCache !== other.fromCache ||\n this.hasPendingWrites !== other.hasPendingWrites ||\n this.syncStateChanged !== other.syncStateChanged ||\n !this.query.isEqual(other.query) ||\n !this.docs.isEqual(other.docs) ||\n !this.oldDocs.isEqual(other.oldDocs)) {\n return false;\n }\n var changes = this.docChanges;\n var otherChanges = other.docChanges;\n if (changes.length !== otherChanges.length) {\n return false;\n }\n for (var i = 0; i < changes.length; i++) {\n if (changes[i].type !== otherChanges[i].type ||\n !changes[i].doc.isEqual(otherChanges[i].doc)) {\n return false;\n }\n }\n return true;\n };\n return ViewSnapshot;\n}());\nexport { ViewSnapshot };\n\n//# sourceMappingURL=view_snapshot.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/view_snapshot.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar RESERVED_BITS = 1;\nvar GeneratorIds;\n(function (GeneratorIds) {\n GeneratorIds[GeneratorIds[\"LocalStore\"] = 0] = \"LocalStore\";\n GeneratorIds[GeneratorIds[\"SyncEngine\"] = 1] = \"SyncEngine\";\n})(GeneratorIds || (GeneratorIds = {}));\n/**\n * TargetIdGenerator generates monotonically increasing integer IDs. There are\n * separate generators for different scopes. While these generators will operate\n * independently of each other, they are scoped, such that no two generators\n * will ever produce the same ID. This is useful, because sometimes the backend\n * may group IDs from separate parts of the client into the same ID space.\n */\nvar TargetIdGenerator = /** @class */ (function () {\n function TargetIdGenerator(generatorId, initAfter) {\n if (initAfter === void 0) { initAfter = 0; }\n this.generatorId = generatorId;\n // Replace the generator part of initAfter with this generator's ID.\n var afterWithoutGenerator = (initAfter >> RESERVED_BITS) << RESERVED_BITS;\n var afterGenerator = initAfter - afterWithoutGenerator;\n if (afterGenerator >= generatorId) {\n // For example, if:\n // this.generatorId = 0b0000\n // after = 0b1011\n // afterGenerator = 0b0001\n // Then:\n // previous = 0b1010\n // next = 0b1100\n this.previousId = afterWithoutGenerator | this.generatorId;\n }\n else {\n // For example, if:\n // this.generatorId = 0b0001\n // after = 0b1010\n // afterGenerator = 0b0000\n // Then:\n // previous = 0b1001\n // next = 0b1011\n this.previousId =\n (afterWithoutGenerator | this.generatorId) - (1 << RESERVED_BITS);\n }\n }\n TargetIdGenerator.prototype.next = function () {\n this.previousId += 1 << RESERVED_BITS;\n return this.previousId;\n };\n TargetIdGenerator.forLocalStore = function (initAfter) {\n if (initAfter === void 0) { initAfter = 0; }\n return new TargetIdGenerator(GeneratorIds.LocalStore, initAfter);\n };\n TargetIdGenerator.forSyncEngine = function () {\n return new TargetIdGenerator(GeneratorIds.SyncEngine);\n };\n return TargetIdGenerator;\n}());\nexport { TargetIdGenerator };\n\n//# sourceMappingURL=target_id_generator.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/target_id_generator.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { assert } from '../util/assert';\nimport { SortedMap } from '../util/sorted_map';\nimport { documentMap } from './collections';\nimport { DocumentKey } from './document_key';\n/**\n * DocumentSet is an immutable (copy-on-write) collection that holds documents\n * in order specified by the provided comparator. We always add a document key\n * comparator on top of what is provided to guarantee document equality based on\n * the key.\n */\nvar DocumentSet = /** @class */ (function () {\n /** The default ordering is by key if the comparator is omitted */\n function DocumentSet(comp) {\n // We are adding document key comparator to the end as it's the only\n // guaranteed unique property of a document.\n if (comp) {\n this.comparator = function (d1, d2) {\n return comp(d1, d2) || DocumentKey.comparator(d1.key, d2.key);\n };\n }\n else {\n this.comparator = function (d1, d2) {\n return DocumentKey.comparator(d1.key, d2.key);\n };\n }\n this.keyedMap = documentMap();\n this.sortedSet = new SortedMap(this.comparator);\n }\n /**\n * Returns an empty copy of the existing DocumentSet, using the same\n * comparator.\n */\n DocumentSet.emptySet = function (oldSet) {\n return new DocumentSet(oldSet.comparator);\n };\n DocumentSet.prototype.has = function (key) {\n return this.keyedMap.get(key) != null;\n };\n DocumentSet.prototype.get = function (key) {\n return this.keyedMap.get(key);\n };\n DocumentSet.prototype.first = function () {\n return this.sortedSet.minKey();\n };\n DocumentSet.prototype.last = function () {\n return this.sortedSet.maxKey();\n };\n DocumentSet.prototype.isEmpty = function () {\n return this.sortedSet.isEmpty();\n };\n /**\n * Returns previous document or null if it's a first doc.\n *\n * @param key A key that MUST be present in the DocumentSet.\n */\n DocumentSet.prototype.prevDoc = function (key) {\n assert(this.has(key), 'Trying to get a previous document to non-existing key: ' + key);\n var doc = this.keyedMap.get(key);\n return this.sortedSet.getPredecessorKey(doc);\n };\n /**\n * Returns the index of the provided key in the document set, or -1 if the\n * document key is not present in the set;\n */\n DocumentSet.prototype.indexOf = function (key) {\n var doc = this.keyedMap.get(key);\n return doc ? this.sortedSet.indexOf(doc) : -1;\n };\n Object.defineProperty(DocumentSet.prototype, \"size\", {\n get: function () {\n return this.sortedSet.size;\n },\n enumerable: true,\n configurable: true\n });\n /** Iterates documents in order defined by \"comparator\" */\n DocumentSet.prototype.forEach = function (cb) {\n this.sortedSet.inorderTraversal(function (k, v) {\n cb(k);\n return false;\n });\n };\n /** Inserts or updates a document with the same key */\n DocumentSet.prototype.add = function (doc) {\n // First remove the element if we have it.\n var set = this.delete(doc.key);\n return set.copy(set.keyedMap.insert(doc.key, doc), set.sortedSet.insert(doc, null));\n };\n /** Deletes a document with a given key */\n DocumentSet.prototype.delete = function (key) {\n var doc = this.get(key);\n if (!doc) {\n return this;\n }\n return this.copy(this.keyedMap.remove(key), this.sortedSet.remove(doc));\n };\n DocumentSet.prototype.isEqual = function (other) {\n if (!(other instanceof DocumentSet))\n return false;\n if (this.size !== other.size)\n return false;\n var thisIt = this.sortedSet.getIterator();\n var otherIt = other.sortedSet.getIterator();\n while (thisIt.hasNext()) {\n var thisDoc = thisIt.getNext().key;\n var otherDoc = otherIt.getNext().key;\n if (!thisDoc.isEqual(otherDoc))\n return false;\n }\n return true;\n };\n DocumentSet.prototype.toString = function () {\n var docStrings = [];\n this.forEach(function (doc) {\n docStrings.push(doc.toString());\n });\n if (docStrings.length === 0) {\n return 'DocumentSet ()';\n }\n else {\n return 'DocumentSet (\\n ' + docStrings.join(' \\n') + '\\n)';\n }\n };\n DocumentSet.prototype.copy = function (keyedMap, sortedSet) {\n var newSet = new DocumentSet();\n newSet.comparator = this.comparator;\n newSet.keyedMap = keyedMap;\n newSet.sortedSet = sortedSet;\n return newSet;\n };\n return DocumentSet;\n}());\nexport { DocumentSet };\n\n//# sourceMappingURL=document_set.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/model/document_set.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport * as objUtil from './obj';\n/**\n * A map implementation that uses objects as keys. Objects must implement the\n * Equatable interface and must be immutable. Entries in the map are stored\n * together with the key being produced from the mapKeyFn. This map\n * automatically handles collisions of keys.\n */\nvar ObjectMap = /** @class */ (function () {\n function ObjectMap(mapKeyFn) {\n this.mapKeyFn = mapKeyFn;\n /**\n * The inner map for a key -> value pair. Due to the possibility of\n * collisions we keep a list of entries that we do a linear search through\n * to find an actual match. Note that collisions should be rare, so we still\n * expect near constant time lookups in practice.\n */\n this.inner = {};\n }\n /** Get a value for this key, or undefined if it does not exist. */\n ObjectMap.prototype.get = function (key) {\n var id = this.mapKeyFn(key);\n var matches = this.inner[id];\n if (matches === undefined) {\n return undefined;\n }\n for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) {\n var _a = matches_1[_i], otherKey = _a[0], value = _a[1];\n if (otherKey.isEqual(key)) {\n return value;\n }\n }\n return undefined;\n };\n ObjectMap.prototype.has = function (key) {\n return this.get(key) !== undefined;\n };\n /** Put this key and value in the map. */\n ObjectMap.prototype.set = function (key, value) {\n var id = this.mapKeyFn(key);\n var matches = this.inner[id];\n if (matches === undefined) {\n this.inner[id] = [[key, value]];\n return;\n }\n for (var i = 0; i < matches.length; i++) {\n if (matches[i][0].isEqual(key)) {\n matches[i] = [key, value];\n return;\n }\n }\n matches.push([key, value]);\n };\n /**\n * Remove this key from the map. Returns a boolean if anything was deleted.\n */\n ObjectMap.prototype.delete = function (key) {\n var id = this.mapKeyFn(key);\n var matches = this.inner[id];\n if (matches === undefined) {\n return false;\n }\n for (var i = 0; i < matches.length; i++) {\n if (matches[i][0].isEqual(key)) {\n if (matches.length === 1) {\n delete this.inner[id];\n }\n else {\n matches.splice(i, 1);\n }\n return true;\n }\n }\n return false;\n };\n ObjectMap.prototype.forEach = function (fn) {\n objUtil.forEach(this.inner, function (_, entries) {\n for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {\n var _a = entries_1[_i], k = _a[0], v = _a[1];\n fn(k, v);\n }\n });\n };\n ObjectMap.prototype.isEmpty = function () {\n return objUtil.isEmpty(this.inner);\n };\n return ObjectMap;\n}());\nexport { ObjectMap };\n\n//# sourceMappingURL=obj_map.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/obj_map.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { OnlineState } from './types';\nimport { ChangeType, ViewSnapshot } from './view_snapshot';\nimport { DocumentSet } from '../model/document_set';\nimport { assert } from '../util/assert';\nimport { ObjectMap } from '../util/obj_map';\n/**\n * Holds the listeners and the last received ViewSnapshot for a query being\n * tracked by EventManager.\n */\nvar QueryListenersInfo = /** @class */ (function () {\n function QueryListenersInfo() {\n this.listeners = [];\n }\n return QueryListenersInfo;\n}());\n/**\n * EventManager is responsible for mapping queries to query event emitters.\n * It handles \"fan-out\". -- Identical queries will re-use the same watch on the\n * backend.\n */\nvar EventManager = /** @class */ (function () {\n function EventManager(syncEngine) {\n this.syncEngine = syncEngine;\n this.queries = new ObjectMap(function (q) {\n return q.canonicalId();\n });\n this.onlineState = OnlineState.Unknown;\n this.syncEngine.subscribe(this.onChange.bind(this), this.onError.bind(this));\n }\n EventManager.prototype.listen = function (listener) {\n var query = listener.query;\n var firstListen = false;\n var queryInfo = this.queries.get(query);\n if (!queryInfo) {\n firstListen = true;\n queryInfo = new QueryListenersInfo();\n this.queries.set(query, queryInfo);\n }\n queryInfo.listeners.push(listener);\n listener.applyOnlineStateChange(this.onlineState);\n if (queryInfo.viewSnap)\n listener.onViewSnapshot(queryInfo.viewSnap);\n if (firstListen) {\n return this.syncEngine.listen(query).then(function (targetId) {\n queryInfo.targetId = targetId;\n return targetId;\n });\n }\n else {\n return Promise.resolve(queryInfo.targetId);\n }\n };\n EventManager.prototype.unlisten = function (listener) {\n var query = listener.query;\n var lastListen = false;\n var queryInfo = this.queries.get(query);\n if (queryInfo) {\n var i = queryInfo.listeners.indexOf(listener);\n if (i >= 0) {\n queryInfo.listeners.splice(i, 1);\n lastListen = queryInfo.listeners.length === 0;\n }\n }\n if (lastListen) {\n this.queries.delete(query);\n return this.syncEngine.unlisten(query);\n }\n else {\n return Promise.resolve();\n }\n };\n EventManager.prototype.onChange = function (viewSnaps) {\n for (var _i = 0, viewSnaps_1 = viewSnaps; _i < viewSnaps_1.length; _i++) {\n var viewSnap = viewSnaps_1[_i];\n var query = viewSnap.query;\n var queryInfo = this.queries.get(query);\n if (queryInfo) {\n for (var _a = 0, _b = queryInfo.listeners; _a < _b.length; _a++) {\n var listener = _b[_a];\n listener.onViewSnapshot(viewSnap);\n }\n queryInfo.viewSnap = viewSnap;\n }\n }\n };\n EventManager.prototype.onError = function (query, error) {\n var queryInfo = this.queries.get(query);\n if (queryInfo) {\n for (var _i = 0, _a = queryInfo.listeners; _i < _a.length; _i++) {\n var listener = _a[_i];\n listener.onError(error);\n }\n }\n // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()\n // after an error.\n this.queries.delete(query);\n };\n EventManager.prototype.applyOnlineStateChange = function (onlineState) {\n this.onlineState = onlineState;\n this.queries.forEach(function (_, queryInfo) {\n for (var _i = 0, _a = queryInfo.listeners; _i < _a.length; _i++) {\n var listener = _a[_i];\n listener.applyOnlineStateChange(onlineState);\n }\n });\n };\n return EventManager;\n}());\nexport { EventManager };\n/**\n * QueryListener takes a series of internal view snapshots and determines\n * when to raise the event.\n *\n * It uses an Observer to dispatch events.\n */\nvar QueryListener = /** @class */ (function () {\n function QueryListener(query, queryObserver, options) {\n this.query = query;\n this.queryObserver = queryObserver;\n /**\n * Initial snapshots (e.g. from cache) may not be propagated to the wrapped\n * observer. This flag is set to true once we've actually raised an event.\n */\n this.raisedInitialEvent = false;\n this.onlineState = OnlineState.Unknown;\n this.options = options || {};\n }\n QueryListener.prototype.onViewSnapshot = function (snap) {\n assert(snap.docChanges.length > 0 || snap.syncStateChanged, 'We got a new snapshot with no changes?');\n if (!this.options.includeDocumentMetadataChanges) {\n // Remove the metadata only changes.\n var docChanges = [];\n for (var _i = 0, _a = snap.docChanges; _i < _a.length; _i++) {\n var docChange = _a[_i];\n if (docChange.type !== ChangeType.Metadata) {\n docChanges.push(docChange);\n }\n }\n snap = new ViewSnapshot(snap.query, snap.docs, snap.oldDocs, docChanges, snap.fromCache, snap.hasPendingWrites, snap.syncStateChanged);\n }\n if (!this.raisedInitialEvent) {\n if (this.shouldRaiseInitialEvent(snap, this.onlineState)) {\n this.raiseInitialEvent(snap);\n }\n }\n else if (this.shouldRaiseEvent(snap)) {\n this.queryObserver.next(snap);\n }\n this.snap = snap;\n };\n QueryListener.prototype.onError = function (error) {\n this.queryObserver.error(error);\n };\n QueryListener.prototype.applyOnlineStateChange = function (onlineState) {\n this.onlineState = onlineState;\n if (this.snap &&\n !this.raisedInitialEvent &&\n this.shouldRaiseInitialEvent(this.snap, onlineState)) {\n this.raiseInitialEvent(this.snap);\n }\n };\n QueryListener.prototype.shouldRaiseInitialEvent = function (snap, onlineState) {\n assert(!this.raisedInitialEvent, 'Determining whether to raise first event but already had first event');\n // Always raise the first event when we're synced\n if (!snap.fromCache) {\n return true;\n }\n // NOTE: We consider OnlineState.Unknown as online (it should become Failed\n // or Online if we wait long enough).\n var maybeOnline = onlineState !== OnlineState.Failed;\n // Don't raise the event if we're online, aren't synced yet (checked\n // above) and are waiting for a sync.\n if (this.options.waitForSyncWhenOnline && maybeOnline) {\n assert(snap.fromCache, 'Waiting for sync, but snapshot is not from cache');\n return false;\n }\n // Raise data from cache if we have any documents or we are offline\n return !snap.docs.isEmpty() || onlineState === OnlineState.Failed;\n };\n QueryListener.prototype.shouldRaiseEvent = function (snap) {\n // We don't need to handle includeDocumentMetadataChanges here because\n // the Metadata only changes have already been stripped out if needed.\n // At this point the only changes we will see are the ones we should\n // propagate.\n if (snap.docChanges.length > 0) {\n return true;\n }\n var hasPendingWritesChanged = this.snap && this.snap.hasPendingWrites !== snap.hasPendingWrites;\n if (snap.syncStateChanged || hasPendingWritesChanged) {\n return this.options.includeQueryMetadataChanges === true;\n }\n // Generally we should have hit one of the cases above, but it's possible\n // to get here if there were only metadata docChanges and they got\n // stripped out.\n return false;\n };\n QueryListener.prototype.raiseInitialEvent = function (snap) {\n assert(!this.raisedInitialEvent, 'Trying to raise initial events for second time');\n snap = new ViewSnapshot(snap.query, snap.docs, DocumentSet.emptySet(snap.docs), QueryListener.getInitialViewChanges(snap), snap.fromCache, snap.hasPendingWrites, true);\n this.raisedInitialEvent = true;\n this.queryObserver.next(snap);\n };\n /** Returns changes as if all documents in the snap were added. */\n QueryListener.getInitialViewChanges = function (snap) {\n var result = [];\n snap.docs.forEach(function (doc) {\n result.push({ type: ChangeType.Added, doc: doc });\n });\n return result;\n };\n return QueryListener;\n}());\nexport { QueryListener };\n\n//# sourceMappingURL=event_manager.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/event_manager.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { fail } from '../util/assert';\n/**\n * PersistencePromise<> is essentially a re-implementation of Promise<> except\n * it has a .next() method instead of .then() and .next() and .catch() callbacks\n * are executed synchronously when a PersistencePromise resolves rather than\n * asynchronously (Promise<> implementations use setImmediate() or similar).\n *\n * This is necessary to interoperate with IndexedDB which will automatically\n * commit transactions if control is returned to the event loop without\n * synchronously initiating another operation on the transaction.\n *\n * NOTE: .then() and .catch() only allow a single consumer, unlike normal\n * Promises.\n */\nvar PersistencePromise = /** @class */ (function () {\n function PersistencePromise(callback) {\n var _this = this;\n // NOTE: next/catchCallback will always point to our own wrapper functions,\n // not the user's raw next() or catch() callbacks.\n // tslint:disable-next-line:no-any Accept any result type for the next call in the Promise chain.\n this.nextCallback = null;\n // tslint:disable-next-line:no-any Accept any result type for the error handler.\n this.catchCallback = null;\n // When the operation resolves, we'll set result or error and mark isDone.\n this.result = undefined;\n this.error = undefined;\n this.isDone = false;\n // Set to true when .then() or .catch() are called and prevents additional\n // chaining.\n this.callbackAttached = false;\n callback(function (value) {\n _this.isDone = true;\n _this.result = value;\n if (_this.nextCallback) {\n // value should be defined unless T is Void, but we can't express\n // that in the type system.\n _this.nextCallback(value);\n }\n }, function (error) {\n _this.isDone = true;\n _this.error = error;\n if (_this.catchCallback) {\n _this.catchCallback(error);\n }\n });\n }\n PersistencePromise.prototype.catch = function (fn) {\n return this.next(undefined, fn);\n };\n PersistencePromise.prototype.next = function (nextFn, catchFn) {\n var _this = this;\n if (this.callbackAttached) {\n fail('Called next() or catch() twice for PersistencePromise');\n }\n this.callbackAttached = true;\n if (this.isDone) {\n if (!this.error) {\n return this.wrapSuccess(nextFn, this.result);\n }\n else {\n return this.wrapFailure(catchFn, this.error);\n }\n }\n else {\n return new PersistencePromise(function (resolve, reject) {\n _this.nextCallback = function (value) {\n _this.wrapSuccess(nextFn, value).next(resolve, reject);\n };\n _this.catchCallback = function (error) {\n _this.wrapFailure(catchFn, error).next(resolve, reject);\n };\n });\n }\n };\n PersistencePromise.prototype.toPromise = function () {\n var _this = this;\n return new Promise(function (resolve, reject) {\n _this.next(resolve, reject);\n });\n };\n PersistencePromise.prototype.wrapUserFunction = function (fn) {\n try {\n var result = fn();\n if (result instanceof PersistencePromise) {\n return result;\n }\n else {\n return PersistencePromise.resolve(result);\n }\n }\n catch (e) {\n return PersistencePromise.reject(e);\n }\n };\n PersistencePromise.prototype.wrapSuccess = function (nextFn, value) {\n if (nextFn) {\n return this.wrapUserFunction(function () { return nextFn(value); });\n }\n else {\n // If there's no nextFn, then R must be the same as T but we\n // can't express that in the type system.\n // tslint:disable-next-line:no-any\n return PersistencePromise.resolve(value);\n }\n };\n PersistencePromise.prototype.wrapFailure = function (catchFn, error) {\n if (catchFn) {\n return this.wrapUserFunction(function () { return catchFn(error); });\n }\n else {\n return PersistencePromise.reject(error);\n }\n };\n PersistencePromise.resolve = function (result) {\n return new PersistencePromise(function (resolve, reject) {\n resolve(result);\n });\n };\n PersistencePromise.reject = function (error) {\n return new PersistencePromise(function (resolve, reject) {\n reject(error);\n });\n };\n PersistencePromise.waitFor = function (\n // tslint:disable-next-line:no-any Accept all Promise types in waitFor().\n all) {\n return all.reduce(function (promise, nextPromise, idx) {\n return promise.next(function () {\n return nextPromise;\n });\n }, PersistencePromise.resolve());\n };\n PersistencePromise.map = function (all) {\n var results = [];\n var first = true;\n // initial is ignored, so we can cheat on the type.\n // tslint:disable-next-line:no-any\n var initial = PersistencePromise.resolve(null);\n return all\n .reduce(function (promise, nextPromise) {\n return promise.next(function (result) {\n if (!first) {\n results.push(result);\n }\n first = false;\n return nextPromise;\n });\n }, initial)\n .next(function (result) {\n results.push(result);\n return results;\n });\n };\n return PersistencePromise;\n}());\nexport { PersistencePromise };\n\n//# sourceMappingURL=persistence_promise.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/persistence_promise.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { documentKeySet } from '../model/collections';\nimport { PersistencePromise } from './persistence_promise';\n/**\n * A garbage collector implementation that eagerly collects documents as soon as\n * they're no longer referenced in any of its registered GarbageSources.\n *\n * This implementation keeps track of a set of keys that are potentially garbage\n * without keeping an exact reference count. During collectGarbage, the\n * collector verifies that all potential garbage keys actually have no\n * references by consulting its list of garbage sources.\n */\nvar EagerGarbageCollector = /** @class */ (function () {\n function EagerGarbageCollector() {\n this.isEager = true;\n /**\n * The garbage collectible sources to double-check during garbage collection.\n */\n this.sources = [];\n /**\n * A set of potentially garbage keys.\n * PORTING NOTE: This would be a mutable set if Javascript had one.\n */\n this.potentialGarbage = documentKeySet();\n }\n EagerGarbageCollector.prototype.addGarbageSource = function (garbageSource) {\n this.sources.push(garbageSource);\n garbageSource.setGarbageCollector(this);\n };\n EagerGarbageCollector.prototype.removeGarbageSource = function (garbageSource) {\n this.sources.splice(this.sources.indexOf(garbageSource), 1);\n garbageSource.setGarbageCollector(null);\n };\n EagerGarbageCollector.prototype.addPotentialGarbageKey = function (key) {\n this.potentialGarbage = this.potentialGarbage.add(key);\n };\n EagerGarbageCollector.prototype.collectGarbage = function (txn) {\n var _this = this;\n var promises = [];\n var garbageKeys = documentKeySet();\n this.potentialGarbage.forEach(function (key) {\n var hasRefsPromise = _this.documentHasAnyReferences(txn, key);\n promises.push(hasRefsPromise.next(function (hasRefs) {\n // If there are no references, get the key.\n if (!hasRefs) {\n garbageKeys = garbageKeys.add(key);\n }\n return PersistencePromise.resolve();\n }));\n });\n // Clear locally retained potential keys and returned confirmed garbage.\n this.potentialGarbage = documentKeySet();\n return PersistencePromise.waitFor(promises).next(function () { return garbageKeys; });\n };\n EagerGarbageCollector.prototype.documentHasAnyReferences = function (txn, key) {\n var initial = PersistencePromise.resolve(false);\n return this.sources\n .map(function (source) { return function () { return source.containsKey(txn, key); }; })\n .reduce(function (promise, nextPromise) {\n return promise.next(function (result) {\n if (result) {\n return PersistencePromise.resolve(true);\n }\n else {\n return nextPromise();\n }\n });\n }, initial);\n };\n return EagerGarbageCollector;\n}());\nexport { EagerGarbageCollector };\n\n//# sourceMappingURL=eager_garbage_collector.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/eager_garbage_collector.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { ChangeType } from '../core/view_snapshot';\nimport { documentKeySet } from '../model/collections';\n/**\n * A set of changes to what documents are currently in view and out of view for\n * a given query. These changes are sent to the LocalStore by the View (via\n * the SyncEngine) and are used to pin / unpin documents as appropriate.\n */\nvar LocalViewChanges = /** @class */ (function () {\n function LocalViewChanges(query, addedKeys, removedKeys) {\n this.query = query;\n this.addedKeys = addedKeys;\n this.removedKeys = removedKeys;\n }\n LocalViewChanges.fromSnapshot = function (viewSnapshot) {\n var addedKeys = documentKeySet();\n var removedKeys = documentKeySet();\n for (var _i = 0, _a = viewSnapshot.docChanges; _i < _a.length; _i++) {\n var docChange = _a[_i];\n switch (docChange.type) {\n case ChangeType.Added:\n addedKeys = addedKeys.add(docChange.doc.key);\n break;\n case ChangeType.Removed:\n removedKeys = removedKeys.add(docChange.doc.key);\n break;\n default:\n }\n }\n return new LocalViewChanges(viewSnapshot.query, addedKeys, removedKeys);\n };\n return LocalViewChanges;\n}());\nexport { LocalViewChanges };\n\n//# sourceMappingURL=local_view_changes.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/local_view_changes.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { documentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\nimport { PersistencePromise } from './persistence_promise';\n/**\n * A collection of references to a document from some kind of numbered entity\n * (either a target ID or batch ID). As references are added to or removed from\n * the set corresponding events are emitted to a registered garbage collector.\n *\n * Each reference is represented by a DocumentReference object. Each of them\n * contains enough information to uniquely identify the reference. They are all\n * stored primarily in a set sorted by key. A document is considered garbage if\n * there's no references in that set (this can be efficiently checked thanks to\n * sorting by key).\n *\n * ReferenceSet also keeps a secondary set that contains references sorted by\n * IDs. This one is used to efficiently implement removal of all references by\n * some target ID.\n */\nvar ReferenceSet = /** @class */ (function () {\n function ReferenceSet() {\n // A set of outstanding references to a document sorted by key.\n this.refsByKey = new SortedSet(DocReference.compareByKey);\n // A set of outstanding references to a document sorted by target id.\n this.refsByTarget = new SortedSet(DocReference.compareByTargetId);\n /** Keeps track of keys that have references */\n this.garbageCollector = null;\n }\n /** Returns true if the reference set contains no references. */\n ReferenceSet.prototype.isEmpty = function () {\n return this.refsByKey.isEmpty();\n };\n /** Adds a reference to the given document key for the given ID. */\n ReferenceSet.prototype.addReference = function (key, id) {\n var ref = new DocReference(key, id);\n this.refsByKey = this.refsByKey.add(ref);\n this.refsByTarget = this.refsByTarget.add(ref);\n };\n /** Add references to the given document keys for the given ID. */\n ReferenceSet.prototype.addReferences = function (keys, id) {\n var _this = this;\n keys.forEach(function (key) { return _this.addReference(key, id); });\n };\n /**\n * Removes a reference to the given document key for the given\n * ID.\n */\n ReferenceSet.prototype.removeReference = function (key, id) {\n this.removeRef(new DocReference(key, id));\n };\n ReferenceSet.prototype.removeReferences = function (keys, id) {\n var _this = this;\n keys.forEach(function (key) { return _this.removeReference(key, id); });\n };\n /**\n * Clears all references with a given ID. Calls removeRef() for each key\n * removed.\n */\n ReferenceSet.prototype.removeReferencesForId = function (id) {\n var _this = this;\n var emptyKey = DocumentKey.EMPTY;\n var startRef = new DocReference(emptyKey, id);\n var endRef = new DocReference(emptyKey, id + 1);\n this.refsByTarget.forEachInRange([startRef, endRef], function (ref) {\n _this.removeRef(ref);\n });\n };\n ReferenceSet.prototype.removeAllReferences = function () {\n var _this = this;\n this.refsByKey.forEach(function (ref) { return _this.removeRef(ref); });\n };\n ReferenceSet.prototype.removeRef = function (ref) {\n this.refsByKey = this.refsByKey.delete(ref);\n this.refsByTarget = this.refsByTarget.delete(ref);\n if (this.garbageCollector !== null) {\n this.garbageCollector.addPotentialGarbageKey(ref.key);\n }\n };\n ReferenceSet.prototype.referencesForId = function (id) {\n var emptyKey = DocumentKey.EMPTY;\n var startRef = new DocReference(emptyKey, id);\n var endRef = new DocReference(emptyKey, id + 1);\n var keys = documentKeySet();\n this.refsByTarget.forEachInRange([startRef, endRef], function (ref) {\n keys = keys.add(ref.key);\n });\n return keys;\n };\n ReferenceSet.prototype.setGarbageCollector = function (garbageCollector) {\n this.garbageCollector = garbageCollector;\n };\n ReferenceSet.prototype.containsKey = function (txn, key) {\n var ref = new DocReference(key, 0);\n var firstRef = this.refsByKey.firstAfterOrEqual(ref);\n return PersistencePromise.resolve(firstRef !== null && key.isEqual(firstRef.key));\n };\n return ReferenceSet;\n}());\nexport { ReferenceSet };\nvar DocReference = /** @class */ (function () {\n function DocReference(key, targetOrBatchId) {\n this.key = key;\n this.targetOrBatchId = targetOrBatchId;\n }\n /** Compare by key then by ID */\n DocReference.compareByKey = function (left, right) {\n return (DocumentKey.comparator(left.key, right.key) ||\n primitiveComparator(left.targetOrBatchId, right.targetOrBatchId));\n };\n /** Compare by ID then by key */\n DocReference.compareByTargetId = function (left, right) {\n return (primitiveComparator(left.targetOrBatchId, right.targetOrBatchId) ||\n DocumentKey.comparator(left.key, right.key));\n };\n return DocReference;\n}());\nexport { DocReference };\n\n//# sourceMappingURL=reference_set.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/reference_set.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { assert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport * as log from '../util/log';\nimport { ExponentialBackoff } from './backoff';\nimport { isNullOrUndefined } from '../util/types';\nvar LOG_TAG = 'PersistentStream';\nvar PersistentStreamState;\n(function (PersistentStreamState) {\n /**\n * The streaming RPC is not running and there's no error condition.\n * Calling `start` will start the stream immediately without backoff.\n * While in this state isStarted will return false.\n */\n PersistentStreamState[PersistentStreamState[\"Initial\"] = 0] = \"Initial\";\n /**\n * The stream is starting, and is waiting for an auth token to attach to\n * the initial request. While in this state, isStarted will return\n * true but isOpen will return false.\n */\n PersistentStreamState[PersistentStreamState[\"Auth\"] = 1] = \"Auth\";\n /**\n * The streaming RPC is up and running. Requests and responses can flow\n * freely. Both isStarted and isOpen will return true.\n */\n PersistentStreamState[PersistentStreamState[\"Open\"] = 2] = \"Open\";\n /**\n * The stream encountered an error. The next start attempt will back off.\n * While in this state isStarted() will return false.\n *\n */\n PersistentStreamState[PersistentStreamState[\"Error\"] = 3] = \"Error\";\n /**\n * An in-between state after an error where the stream is waiting before\n * re-starting. After\n * waiting is complete, the stream will try to open. While in this\n * state isStarted() will return YES but isOpen will return false.\n */\n PersistentStreamState[PersistentStreamState[\"Backoff\"] = 4] = \"Backoff\";\n /**\n * The stream has been explicitly stopped; no further events will be emitted.\n */\n PersistentStreamState[PersistentStreamState[\"Stopped\"] = 5] = \"Stopped\";\n})(PersistentStreamState || (PersistentStreamState = {}));\n/**\n * Initial backoff time in milliseconds after an error.\n * Set to 1s according to https://cloud.google.com/apis/design/errors.\n */\nvar BACKOFF_INITIAL_DELAY_MS = 1000;\n/** Maximum backoff time in milliseconds */\nvar BACKOFF_MAX_DELAY_MS = 60 * 1000;\nvar BACKOFF_FACTOR = 1.5;\n/** The time a stream stays open after it is marked idle. */\nvar IDLE_TIMEOUT_MS = 60 * 1000;\n/**\n * A PersistentStream is an abstract base class that represents a streaming RPC\n * to the Firestore backend. It's built on top of the connections own support\n * for streaming RPCs, and adds several critical features for our clients:\n *\n * - Exponential backoff on failure\n * - Authentication via CredentialsProvider\n * - Dispatching all callbacks into the shared worker queue\n *\n * Subclasses of PersistentStream implement serialization of models to and\n * from the JSON representation of the protocol buffers for a specific\n * streaming RPC.\n *\n * ## Starting and Stopping\n *\n * Streaming RPCs are stateful and need to be `start`ed before messages can\n * be sent and received. The PersistentStream will call the onOpen function\n * of the listener once the stream is ready to accept requests.\n *\n * Should a `start` fail, PersistentStream will call the registered\n * onClose with a FirestoreError indicating what went wrong.\n *\n * A PersistentStream can be started and stopped repeatedly.\n *\n * Generic types:\n * SendType: The type of the outgoing message of the underlying\n * connection stream\n * ReceiveType: The type of the incoming message of the underlying\n * connection stream\n * ListenerType: The type of the listener that will be used for callbacks\n */\nvar PersistentStream = /** @class */ (function () {\n function PersistentStream(queue, connection, credentialsProvider, \n // Used for faster retries in testing\n initialBackoffDelay) {\n this.queue = queue;\n this.connection = connection;\n this.credentialsProvider = credentialsProvider;\n this.idle = false;\n this.stream = null;\n this.listener = null;\n this.backoff = new ExponentialBackoff(initialBackoffDelay ? initialBackoffDelay : BACKOFF_INITIAL_DELAY_MS, BACKOFF_FACTOR, BACKOFF_MAX_DELAY_MS);\n this.state = PersistentStreamState.Initial;\n }\n /**\n * Returns true if `start` has been called and no error has occurred. True\n * indicates the stream is open or in the process of opening (which\n * encompasses respecting backoff, getting auth tokens, and starting the\n * actual RPC). Use `isOpen` to determine if the stream is open and ready for\n * outbound requests.\n */\n PersistentStream.prototype.isStarted = function () {\n return (this.state === PersistentStreamState.Backoff ||\n this.state === PersistentStreamState.Auth ||\n this.state === PersistentStreamState.Open);\n };\n /**\n * Returns true if the underlying RPC is open (the openHandler has been\n * called) and the stream is ready for outbound requests.\n */\n PersistentStream.prototype.isOpen = function () {\n return this.state === PersistentStreamState.Open;\n };\n /**\n * Starts the RPC. Only allowed if isStarted returns false. The stream is\n * not immediately ready for use: onOpen will be invoked when the RPC is ready\n * for outbound requests, at which point isOpen will return true.\n *\n * When start returns, isStarted will return true.\n */\n PersistentStream.prototype.start = function (listener) {\n if (this.state === PersistentStreamState.Error) {\n this.performBackoff(listener);\n return;\n }\n assert(this.state === PersistentStreamState.Initial, 'Already started');\n this.listener = listener;\n this.auth();\n };\n /**\n * Stops the RPC. This call is idempotent and allowed regardless of the\n * current isStarted state.\n *\n * When stop returns, isStarted and isOpen will both return false.\n */\n PersistentStream.prototype.stop = function () {\n if (this.isStarted()) {\n this.close(PersistentStreamState.Stopped);\n }\n };\n /**\n * After an error the stream will usually back off on the next attempt to\n * start it. If the error warrants an immediate restart of the stream, the\n * sender can use this to indicate that the receiver should not back off.\n *\n * Each error will call the onClose function. That function can decide to\n * inhibit backoff if required.\n */\n PersistentStream.prototype.inhibitBackoff = function () {\n assert(!this.isStarted(), 'Can only inhibit backoff in a stopped state');\n this.state = PersistentStreamState.Initial;\n this.backoff.reset();\n };\n /**\n * Initializes the idle timer. If no write takes place within one minute, the\n * WebChannel stream will be closed.\n */\n PersistentStream.prototype.markIdle = function () {\n var _this = this;\n this.idle = true;\n this.queue\n .schedule(function () {\n return _this.handleIdleCloseTimer();\n }, IDLE_TIMEOUT_MS)\n .catch(function (err) {\n // When the AsyncQueue gets drained during testing, pending Promises\n // (including these idle checks) will get rejected. We special-case\n // these cancelled idle checks to make sure that these specific Promise\n // rejections are not considered unhandled.\n assert(err.code === Code.CANCELLED, \"Received unexpected error in idle timeout closure. Expected CANCELLED, but was: \" + err);\n });\n };\n /** Sends a message to the underlying stream. */\n PersistentStream.prototype.sendRequest = function (msg) {\n this.cancelIdleCheck();\n this.stream.send(msg);\n };\n /** Called by the idle timer when the stream should close due to inactivity. */\n PersistentStream.prototype.handleIdleCloseTimer = function () {\n if (this.isOpen() && this.idle) {\n // When timing out an idle stream there's no reason to force the stream into backoff when\n // it restarts so set the stream state to Initial instead of Error.\n return this.close(PersistentStreamState.Initial);\n }\n return Promise.resolve();\n };\n /** Marks the stream as active again. */\n PersistentStream.prototype.cancelIdleCheck = function () {\n this.idle = false;\n };\n /**\n * Closes the stream and cleans up as necessary:\n *\n * * closes the underlying GRPC stream;\n * * calls the onClose handler with the given 'error';\n * * sets internal stream state to 'finalState';\n * * adjusts the backoff timer based on the error\n *\n * A new stream can be opened by calling `start` unless `finalState` is set to\n * `PersistentStreamState.Stopped`.\n *\n * @param finalState the intended state of the stream after closing.\n * @param error the error the connection was closed with.\n */\n PersistentStream.prototype.close = function (finalState, error) {\n assert(finalState === PersistentStreamState.Error || isNullOrUndefined(error), \"Can't provide an error when not in an error state.\");\n this.cancelIdleCheck();\n if (finalState !== PersistentStreamState.Error) {\n // If this is an intentional close ensure we don't delay our next connection attempt.\n this.backoff.reset();\n }\n else if (error && error.code === Code.RESOURCE_EXHAUSTED) {\n // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)\n log.error(error.toString());\n log.error('Using maximum backoff delay to prevent overloading the backend.');\n this.backoff.resetToMax();\n }\n // Clean up the underlying stream because we are no longer interested in events.\n if (this.stream !== null) {\n this.tearDown();\n this.stream.close();\n this.stream = null;\n }\n // This state must be assigned before calling onClose() to allow the callback to\n // inhibit backoff or otherwise manipulate the state in its non-started state.\n this.state = finalState;\n var listener = this.listener;\n // Clear the listener to avoid bleeding of events from the underlying streams.\n this.listener = null;\n // If the caller explicitly requested a stream stop, don't notify them of a closing stream (it\n // could trigger undesirable recovery logic, etc.).\n if (finalState !== PersistentStreamState.Stopped) {\n return listener.onClose(error);\n }\n else {\n return Promise.resolve();\n }\n };\n /**\n * Can be overridden to perform additional cleanup before the stream is closed.\n * Calling super.tearDown() is not required.\n */\n PersistentStream.prototype.tearDown = function () { };\n PersistentStream.prototype.auth = function () {\n var _this = this;\n assert(this.state === PersistentStreamState.Initial, 'Must be in initial state to auth');\n this.state = PersistentStreamState.Auth;\n this.credentialsProvider.getToken(/*forceRefresh=*/ false).then(function (token) {\n // Normally we'd have to schedule the callback on the AsyncQueue.\n // However, the following calls are safe to be called outside the\n // AsyncQueue since they don't chain asynchronous calls\n _this.startStream(token);\n }, function (error) {\n _this.queue.schedule(function () {\n if (_this.state !== PersistentStreamState.Stopped) {\n // Stream can be stopped while waiting for authorization.\n var rpcError = new FirestoreError(Code.UNKNOWN, 'Fetching auth token failed: ' + error.message);\n return _this.handleStreamClose(rpcError);\n }\n else {\n return Promise.resolve();\n }\n });\n });\n };\n PersistentStream.prototype.startStream = function (token) {\n var _this = this;\n if (this.state === PersistentStreamState.Stopped) {\n // Stream can be stopped while waiting for authorization.\n return;\n }\n assert(this.state === PersistentStreamState.Auth, 'Trying to start stream in a non-auth state');\n // Helper function to dispatch to AsyncQueue and make sure that any\n // close will seem instantaneous and events are prevented from being\n // raised after the close call\n var dispatchIfStillActive = function (stream, fn) {\n _this.queue.schedule(function () {\n // Only raise events if the stream instance has not changed\n if (_this.stream === stream) {\n return fn();\n }\n else {\n return Promise.resolve();\n }\n });\n };\n // Only start stream if listener has not changed\n if (this.listener !== null) {\n var currentStream_1 = this.startRpc(token);\n this.stream = currentStream_1;\n this.stream.onOpen(function () {\n dispatchIfStillActive(currentStream_1, function () {\n assert(_this.state === PersistentStreamState.Auth, 'Expected stream to be in state auth, but was ' + _this.state);\n _this.state = PersistentStreamState.Open;\n return _this.listener.onOpen();\n });\n });\n this.stream.onClose(function (error) {\n dispatchIfStillActive(currentStream_1, function () {\n return _this.handleStreamClose(error);\n });\n });\n this.stream.onMessage(function (msg) {\n dispatchIfStillActive(currentStream_1, function () {\n return _this.onMessage(msg);\n });\n });\n }\n };\n PersistentStream.prototype.performBackoff = function (listener) {\n var _this = this;\n assert(this.state === PersistentStreamState.Error, 'Should only perform backoff in an error case');\n this.state = PersistentStreamState.Backoff;\n this.backoff.backoffAndWait().then(function () {\n // Backoff does not run on the AsyncQueue, so we need to reschedule to\n // make sure the queue blocks\n _this.queue.schedule(function () {\n if (_this.state === PersistentStreamState.Stopped) {\n // Stream can be stopped while waiting for backoff to complete.\n return Promise.resolve();\n }\n _this.state = PersistentStreamState.Initial;\n _this.start(listener);\n assert(_this.isStarted(), 'PersistentStream should have started');\n return Promise.resolve();\n });\n });\n };\n PersistentStream.prototype.handleStreamClose = function (error) {\n assert(this.isStarted(), \"Can't handle server close on non-started stream\");\n log.debug(LOG_TAG, \"close with error: \" + error);\n this.stream = null;\n // In theory the stream could close cleanly, however, in our current model\n // we never expect this to happen because if we stop a stream ourselves,\n // this callback will never be called. To prevent cases where we retry\n // without a backoff accidentally, we set the stream to error in all cases.\n return this.close(PersistentStreamState.Error, error);\n };\n return PersistentStream;\n}());\nexport { PersistentStream };\n/**\n * A PersistentStream that implements the Listen RPC.\n *\n * Once the Listen stream has called the openHandler, any number of listen and\n * unlisten calls calls can be sent to control what changes will be sent from\n * the server for ListenResponses.\n */\nvar PersistentListenStream = /** @class */ (function (_super) {\n __extends(PersistentListenStream, _super);\n function PersistentListenStream(databaseInfo, queue, connection, credentials, serializer, initialBackoffDelay) {\n var _this = _super.call(this, queue, connection, credentials, initialBackoffDelay) || this;\n _this.databaseInfo = databaseInfo;\n _this.serializer = serializer;\n return _this;\n }\n PersistentListenStream.prototype.startRpc = function (token) {\n return this.connection.openStream('Listen', token);\n };\n PersistentListenStream.prototype.onMessage = function (watchChangeProto) {\n // A successful response means the stream is healthy\n this.backoff.reset();\n var watchChange = this.serializer.fromWatchChange(watchChangeProto);\n var snapshot = this.serializer.versionFromListenResponse(watchChangeProto);\n return this.listener.onWatchChange(watchChange, snapshot);\n };\n /**\n * Registers interest in the results of the given query. If the query\n * includes a resumeToken it will be included in the request. Results that\n * affect the query will be streamed back as WatchChange messages that\n * reference the targetId.\n */\n PersistentListenStream.prototype.watch = function (queryData) {\n var request = {};\n request.database = this.serializer.encodedDatabaseId;\n request.addTarget = this.serializer.toTarget(queryData);\n var labels = this.serializer.toListenRequestLabels(queryData);\n if (labels) {\n request.labels = labels;\n }\n this.sendRequest(request);\n };\n /**\n * Unregisters interest in the results of the query associated with the\n * given targetId.\n */\n PersistentListenStream.prototype.unwatch = function (targetId) {\n var request = {};\n request.database = this.serializer.encodedDatabaseId;\n request.removeTarget = targetId;\n this.sendRequest(request);\n };\n return PersistentListenStream;\n}(PersistentStream));\nexport { PersistentListenStream };\n/**\n * A Stream that implements the Write RPC.\n *\n * The Write RPC requires the caller to maintain special streamToken\n * state in between calls, to help the server understand which responses the\n * client has processed by the time the next request is made. Every response\n * will contain a streamToken; this value must be passed to the next\n * request.\n *\n * After calling start() on this stream, the next request must be a handshake,\n * containing whatever streamToken is on hand. Once a response to this\n * request is received, all pending mutations may be submitted. When\n * submitting multiple batches of mutations at the same time, it's\n * okay to use the same streamToken for the calls to writeMutations.\n *\n * TODO(b/33271235): Use proto types\n */\nvar PersistentWriteStream = /** @class */ (function (_super) {\n __extends(PersistentWriteStream, _super);\n function PersistentWriteStream(databaseInfo, queue, connection, credentials, serializer, initialBackoffDelay) {\n var _this = _super.call(this, queue, connection, credentials, initialBackoffDelay) || this;\n _this.databaseInfo = databaseInfo;\n _this.serializer = serializer;\n _this.handshakeComplete_ = false;\n return _this;\n }\n Object.defineProperty(PersistentWriteStream.prototype, \"handshakeComplete\", {\n /**\n * Tracks whether or not a handshake has been successfully exchanged and\n * the stream is ready to accept mutations.\n */\n get: function () {\n return this.handshakeComplete_;\n },\n enumerable: true,\n configurable: true\n });\n // Override of PersistentStream.start\n PersistentWriteStream.prototype.start = function (listener) {\n this.handshakeComplete_ = false;\n _super.prototype.start.call(this, listener);\n };\n PersistentWriteStream.prototype.tearDown = function () {\n if (this.handshakeComplete_) {\n this.writeMutations([]);\n }\n };\n PersistentWriteStream.prototype.startRpc = function (token) {\n return this.connection.openStream('Write', token);\n };\n PersistentWriteStream.prototype.onMessage = function (responseProto) {\n // Always capture the last stream token.\n assert(!!responseProto.streamToken, 'Got a write response without a stream token');\n this.lastStreamToken = responseProto.streamToken;\n if (!this.handshakeComplete_) {\n // The first response is always the handshake response\n assert(!responseProto.writeResults || responseProto.writeResults.length === 0, 'Got mutation results for handshake');\n this.handshakeComplete_ = true;\n return this.listener.onHandshakeComplete();\n }\n else {\n // A successful first write response means the stream is healthy,\n // Note, that we could consider a successful handshake healthy, however,\n // the write itself might be causing an error we want to back off from.\n this.backoff.reset();\n var results = this.serializer.fromWriteResults(responseProto.writeResults);\n var commitVersion = this.serializer.fromVersion(responseProto.commitTime);\n return this.listener.onMutationResult(commitVersion, results);\n }\n };\n /**\n * Sends an initial streamToken to the server, performing the handshake\n * required to make the StreamingWrite RPC work. Subsequent\n * calls should wait until onHandshakeComplete was called.\n */\n PersistentWriteStream.prototype.writeHandshake = function () {\n assert(this.isOpen(), 'Writing handshake requires an opened stream');\n assert(!this.handshakeComplete_, 'Handshake already completed');\n // TODO(dimond): Support stream resumption. We intentionally do not set the\n // stream token on the handshake, ignoring any stream token we might have.\n var request = {};\n request.database = this.serializer.encodedDatabaseId;\n this.sendRequest(request);\n };\n /** Sends a group of mutations to the Firestore backend to apply. */\n PersistentWriteStream.prototype.writeMutations = function (mutations) {\n var _this = this;\n assert(this.isOpen(), 'Writing mutations requires an opened stream');\n assert(this.handshakeComplete_, 'Handshake must be complete before writing mutations');\n assert(this.lastStreamToken.length > 0, 'Trying to write mutation without a token');\n var request = {\n // Protos are typed with string, but we support UInt8Array on Node\n // tslint:disable-next-line:no-any\n streamToken: this.lastStreamToken,\n writes: mutations.map(function (mutation) { return _this.serializer.toMutation(mutation); })\n };\n this.sendRequest(request);\n };\n return PersistentWriteStream;\n}(PersistentStream));\nexport { PersistentWriteStream };\n\n//# sourceMappingURL=persistent_stream.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/remote/persistent_stream.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { EagerGarbageCollector } from '../local/eager_garbage_collector';\nimport { LocalViewChanges } from '../local/local_view_changes';\nimport { QueryData, QueryPurpose } from '../local/query_data';\nimport { ReferenceSet } from '../local/reference_set';\nimport { NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { CurrentStatusUpdate, RemoteEvent } from '../remote/remote_event';\nimport { assert, fail } from '../util/assert';\nimport * as log from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport * as objUtils from '../util/obj';\nimport { ObjectMap } from '../util/obj_map';\nimport { SortedMap } from '../util/sorted_map';\nimport { isNullOrUndefined } from '../util/types';\nimport { Query } from './query';\nimport { SnapshotVersion } from './snapshot_version';\nimport { TargetIdGenerator } from './target_id_generator';\nimport { AddedLimboDocument, RemovedLimboDocument, View } from './view';\nvar LOG_TAG = 'SyncEngine';\n/**\n * QueryView contains all of the data that SyncEngine needs to keep track of for\n * a particular query.\n */\nvar QueryView = /** @class */ (function () {\n function QueryView(\n /**\n * The query itself.\n */\n query, \n /**\n * The target number created by the client that is used in the watch\n * stream to identify this query.\n */\n targetId, \n /**\n * An identifier from the datastore backend that indicates the last state\n * of the results that was received. This can be used to indicate where\n * to continue receiving new doc changes for the query.\n */\n resumeToken, \n /**\n * The view is responsible for computing the final merged truth of what\n * docs are in the query. It gets notified of local and remote changes,\n * and applies the query filters and limits to determine the most correct\n * possible results.\n */\n view) {\n this.query = query;\n this.targetId = targetId;\n this.resumeToken = resumeToken;\n this.view = view;\n }\n return QueryView;\n}());\n/**\n * SyncEngine is the central controller in the client SDK architecture. It is\n * the glue code between the EventManager, LocalStore, and RemoteStore. Some of\n * SyncEngine's responsibilities include:\n * 1. Coordinating client requests and remote events between the EventManager\n * and the local and remote data stores.\n * 2. Managing a View object for each query, providing the unified view between\n * the local and remote data stores.\n * 3. Notifying the RemoteStore when the LocalStore has new mutations in its\n * queue that need sending to the backend.\n *\n * The SyncEngine’s methods should only ever be called by methods running in the\n * global async queue.\n */\nvar SyncEngine = /** @class */ (function () {\n function SyncEngine(localStore, remoteStore, currentUser) {\n this.localStore = localStore;\n this.remoteStore = remoteStore;\n this.currentUser = currentUser;\n this.viewHandler = null;\n this.errorHandler = null;\n this.queryViewsByQuery = new ObjectMap(function (q) {\n return q.canonicalId();\n });\n this.queryViewsByTarget = {};\n this.limboTargetsByKey = new SortedMap(DocumentKey.comparator);\n this.limboKeysByTarget = {};\n this.limboDocumentRefs = new ReferenceSet();\n this.limboCollector = new EagerGarbageCollector();\n /** Stores user completion handlers, indexed by User and BatchId. */\n this.mutationUserCallbacks = {};\n this.targetIdGenerator = TargetIdGenerator.forSyncEngine();\n }\n /** Subscribes view and error handler. Can be called only once. */\n SyncEngine.prototype.subscribe = function (viewHandler, errorHandler) {\n assert(viewHandler !== null && errorHandler !== null, 'View and error handlers cannot be null');\n assert(this.viewHandler === null && this.errorHandler === null, 'SyncEngine already has a subscriber.');\n this.viewHandler = viewHandler;\n this.errorHandler = errorHandler;\n this.limboCollector.addGarbageSource(this.limboDocumentRefs);\n };\n /**\n * Initiates the new listen, resolves promise when listen enqueued to the\n * server. All the subsequent view snapshots or errors are sent to the\n * subscribed handlers. Returns the targetId of the query.\n */\n SyncEngine.prototype.listen = function (query) {\n var _this = this;\n this.assertSubscribed('listen()');\n assert(!this.queryViewsByQuery.has(query), 'We already listen to the query: ' + query);\n return this.localStore.allocateQuery(query).then(function (queryData) {\n return _this.localStore\n .executeQuery(query)\n .then(function (docs) {\n return _this.localStore\n .remoteDocumentKeys(queryData.targetId)\n .then(function (remoteKeys) {\n var view = new View(query, remoteKeys);\n var viewDocChanges = view.computeDocChanges(docs);\n var viewChange = view.applyChanges(viewDocChanges);\n assert(viewChange.limboChanges.length === 0, 'View returned limbo docs before target ack from the server.');\n assert(!!viewChange.snapshot, 'applyChanges for new view should always return a snapshot');\n var data = new QueryView(query, queryData.targetId, queryData.resumeToken, view);\n _this.queryViewsByQuery.set(query, data);\n _this.queryViewsByTarget[queryData.targetId] = data;\n _this.viewHandler([viewChange.snapshot]);\n _this.remoteStore.listen(queryData);\n });\n })\n .then(function () {\n return queryData.targetId;\n });\n });\n };\n /** Stops listening to the query. */\n SyncEngine.prototype.unlisten = function (query) {\n var _this = this;\n this.assertSubscribed('unlisten()');\n var queryView = this.queryViewsByQuery.get(query);\n assert(!!queryView, 'Trying to unlisten on query not found:' + query);\n return this.localStore.releaseQuery(query).then(function () {\n _this.remoteStore.unlisten(queryView.targetId);\n return _this.removeAndCleanupQuery(queryView).then(function () {\n return _this.localStore.collectGarbage();\n });\n });\n };\n /**\n * Initiates the write of local mutation batch which involves adding the\n * writes to the mutation queue, notifying the remote store about new\n * mutations and raising events for any changes this write caused.\n *\n * The promise returned by this call is resolved when the above steps\n * have completed, *not* when the write was acked by the backend. The\n * userCallback is resolved once the write was acked/rejected by the\n * backend (or failed locally for any other reason).\n */\n SyncEngine.prototype.write = function (batch, userCallback) {\n var _this = this;\n this.assertSubscribed('write()');\n return this.localStore\n .localWrite(batch)\n .then(function (result) {\n _this.addMutationCallback(result.batchId, userCallback);\n return _this.emitNewSnapsAndNotifyLocalStore(result.changes);\n })\n .then(function () {\n return _this.remoteStore.fillWritePipeline();\n });\n };\n // TODO(klimt): Wrap the given error in a standard Firestore error object.\n SyncEngine.prototype.wrapUpdateFunctionError = function (error) {\n return error;\n };\n /**\n * Takes an updateFunction in which a set of reads and writes can be performed\n * atomically. In the updateFunction, the client can read and write values\n * using the supplied transaction object. After the updateFunction, all\n * changes will be committed. If some other client has changed any of the data\n * referenced, then the updateFunction will be called again. If the\n * updateFunction still fails after the given number of retries, then the\n * transaction will be rejection.\n *\n * The transaction object passed to the updateFunction contains methods for\n * accessing documents and collections. Unlike other datastore access, data\n * accessed with the transaction will not reflect local changes that have not\n * been committed. For this reason, it is required that all reads are\n * performed before any writes. Transactions must be performed while online.\n *\n * The promise returned is resolved when the transaction is fully committed.\n */\n SyncEngine.prototype.runTransaction = function (updateFunction, retries) {\n var _this = this;\n if (retries === void 0) { retries = 5; }\n assert(retries >= 0, 'Got negative number of retries for transaction.');\n var transaction = this.remoteStore.createTransaction();\n var wrappedUpdateFunction = function () {\n try {\n var userPromise = updateFunction(transaction);\n if (isNullOrUndefined(userPromise) ||\n !userPromise.catch ||\n !userPromise.then) {\n return Promise.reject(Error('Transaction callback must return a Promise'));\n }\n return userPromise.catch(function (e) {\n return Promise.reject(_this.wrapUpdateFunctionError(e));\n });\n }\n catch (e) {\n return Promise.reject(_this.wrapUpdateFunctionError(e));\n }\n };\n return wrappedUpdateFunction().then(function (result) {\n return transaction\n .commit()\n .then(function () {\n return result;\n })\n .catch(function (error) {\n if (retries === 0) {\n return Promise.reject(error);\n }\n // TODO(klimt): Put in a retry delay?\n return _this.runTransaction(updateFunction, retries - 1);\n });\n });\n };\n SyncEngine.prototype.applyRemoteEvent = function (remoteEvent) {\n var _this = this;\n this.assertSubscribed('applyRemoteEvent()');\n // Make sure limbo documents are deleted if there were no results\n objUtils.forEachNumber(remoteEvent.targetChanges, function (targetId, targetChange) {\n var limboKey = _this.limboKeysByTarget[targetId];\n if (limboKey &&\n targetChange.currentStatusUpdate ===\n CurrentStatusUpdate.MarkCurrent &&\n !remoteEvent.documentUpdates.get(limboKey)) {\n // When listening to a query the server responds with a snapshot\n // containing documents matching the query and a current marker\n // telling us we're now in sync. It's possible for these to arrive\n // as separate remote events or as a single remote event.\n // For a document query, there will be no documents sent in the\n // response if the document doesn't exist.\n //\n // If the snapshot arrives separately from the current marker,\n // we handle it normally and updateTrackedLimbos will resolve the\n // limbo status of the document, removing it from limboDocumentRefs.\n // This works because clients only initiate limbo resolution when\n // a target is current and because all current targets are\n // always at a consistent snapshot.\n //\n // However, if the document doesn't exist and the current marker\n // arrives, the document is not present in the snapshot and our\n // normal view handling would consider the document to remain in\n // limbo indefinitely because there are no updates to the document.\n // To avoid this, we specially handle this just this case here:\n // synthesizing a delete.\n //\n // TODO(dimond): Ideally we would have an explicit lookup query\n // instead resulting in an explicit delete message and we could\n // remove this special logic.\n remoteEvent.addDocumentUpdate(new NoDocument(limboKey, remoteEvent.snapshotVersion));\n }\n });\n return this.localStore.applyRemoteEvent(remoteEvent).then(function (changes) {\n return _this.emitNewSnapsAndNotifyLocalStore(changes, remoteEvent);\n });\n };\n /**\n * Applies an OnlineState change to the sync engine and notifies any views of\n * the change.\n */\n SyncEngine.prototype.applyOnlineStateChange = function (onlineState) {\n var newViewSnapshots = [];\n this.queryViewsByQuery.forEach(function (query, queryView) {\n var viewChange = queryView.view.applyOnlineStateChange(onlineState);\n assert(viewChange.limboChanges.length === 0, 'OnlineState should not affect limbo documents.');\n if (viewChange.snapshot) {\n newViewSnapshots.push(viewChange.snapshot);\n }\n });\n this.viewHandler(newViewSnapshots);\n };\n SyncEngine.prototype.rejectListen = function (targetId, err) {\n var _this = this;\n this.assertSubscribed('rejectListens()');\n var limboKey = this.limboKeysByTarget[targetId];\n if (limboKey) {\n // Since this query failed, we won't want to manually unlisten to it.\n // So go ahead and remove it from bookkeeping.\n this.limboTargetsByKey = this.limboTargetsByKey.remove(limboKey);\n delete this.limboKeysByTarget[targetId];\n // TODO(klimt): We really only should do the following on permission\n // denied errors, but we don't have the cause code here.\n // It's a limbo doc. Create a synthetic event saying it was deleted.\n // This is kind of a hack. Ideally, we would have a method in the local\n // store to purge a document. However, it would be tricky to keep all of\n // the local store's invariants with another method.\n var docMap = new SortedMap(DocumentKey.comparator);\n docMap = docMap.insert(limboKey, new NoDocument(limboKey, SnapshotVersion.forDeletedDoc()));\n var event_1 = new RemoteEvent(SnapshotVersion.MIN, {}, docMap);\n return this.applyRemoteEvent(event_1);\n }\n else {\n var queryView_1 = this.queryViewsByTarget[targetId];\n assert(!!queryView_1, 'Unknown targetId: ' + targetId);\n return this.localStore.releaseQuery(queryView_1.query).then(function () {\n return _this.removeAndCleanupQuery(queryView_1).then(function () {\n _this.errorHandler(queryView_1.query, err);\n });\n });\n }\n };\n SyncEngine.prototype.applySuccessfulWrite = function (mutationBatchResult) {\n var _this = this;\n this.assertSubscribed('applySuccessfulWrite()');\n // The local store may or may not be able to apply the write result and\n // raise events immediately (depending on whether the watcher is caught\n // up), so we raise user callbacks first so that they consistently happen\n // before listen events.\n this.processUserCallback(mutationBatchResult.batch.batchId, \n /*error=*/ null);\n return this.localStore\n .acknowledgeBatch(mutationBatchResult)\n .then(function (changes) {\n return _this.emitNewSnapsAndNotifyLocalStore(changes);\n });\n };\n SyncEngine.prototype.rejectFailedWrite = function (batchId, error) {\n var _this = this;\n this.assertSubscribed('rejectFailedWrite()');\n // The local store may or may not be able to apply the write result and\n // raise events immediately (depending on whether the watcher is caught up),\n // so we raise user callbacks first so that they consistently happen before\n // listen events.\n this.processUserCallback(batchId, error);\n return this.localStore.rejectBatch(batchId).then(function (changes) {\n return _this.emitNewSnapsAndNotifyLocalStore(changes);\n });\n };\n SyncEngine.prototype.addMutationCallback = function (batchId, callback) {\n var newCallbacks = this.mutationUserCallbacks[this.currentUser.toKey()];\n if (!newCallbacks) {\n newCallbacks = new SortedMap(primitiveComparator);\n }\n newCallbacks = newCallbacks.insert(batchId, callback);\n this.mutationUserCallbacks[this.currentUser.toKey()] = newCallbacks;\n };\n /**\n * Resolves or rejects the user callback for the given batch and then discards\n * it.\n */\n SyncEngine.prototype.processUserCallback = function (batchId, error) {\n var newCallbacks = this.mutationUserCallbacks[this.currentUser.toKey()];\n // NOTE: Mutations restored from persistence won't have callbacks, so it's\n // okay for there to be no callback for this ID.\n if (newCallbacks) {\n var callback = newCallbacks.get(batchId);\n if (callback) {\n assert(batchId === newCallbacks.minKey(), 'Mutation callbacks processed out-of-order?');\n if (error) {\n callback.reject(error);\n }\n else {\n callback.resolve();\n }\n newCallbacks = newCallbacks.remove(batchId);\n }\n this.mutationUserCallbacks[this.currentUser.toKey()] = newCallbacks;\n }\n };\n SyncEngine.prototype.removeAndCleanupQuery = function (queryView) {\n this.queryViewsByQuery.delete(queryView.query);\n delete this.queryViewsByTarget[queryView.targetId];\n this.limboDocumentRefs.removeReferencesForId(queryView.targetId);\n return this.gcLimboDocuments();\n };\n SyncEngine.prototype.updateTrackedLimbos = function (targetId, limboChanges) {\n for (var _i = 0, limboChanges_1 = limboChanges; _i < limboChanges_1.length; _i++) {\n var limboChange = limboChanges_1[_i];\n if (limboChange instanceof AddedLimboDocument) {\n this.limboDocumentRefs.addReference(limboChange.key, targetId);\n this.trackLimboChange(limboChange);\n }\n else if (limboChange instanceof RemovedLimboDocument) {\n log.debug(LOG_TAG, 'Document no longer in limbo: ' + limboChange.key);\n this.limboDocumentRefs.removeReference(limboChange.key, targetId);\n }\n else {\n fail('Unknown limbo change: ' + JSON.stringify(limboChange));\n }\n }\n return this.gcLimboDocuments();\n };\n SyncEngine.prototype.trackLimboChange = function (limboChange) {\n var key = limboChange.key;\n if (!this.limboTargetsByKey.get(key)) {\n log.debug(LOG_TAG, 'New document in limbo: ' + key);\n var limboTargetId = this.targetIdGenerator.next();\n var query = Query.atPath(key.path);\n this.limboKeysByTarget[limboTargetId] = key;\n this.remoteStore.listen(new QueryData(query, limboTargetId, QueryPurpose.Listen));\n this.limboTargetsByKey = this.limboTargetsByKey.insert(key, limboTargetId);\n }\n };\n SyncEngine.prototype.gcLimboDocuments = function () {\n var _this = this;\n // HACK: We can use a null transaction here, because we know that the\n // reference set is entirely within memory and doesn't need a store engine.\n return this.limboCollector\n .collectGarbage(null)\n .next(function (keys) {\n keys.forEach(function (key) {\n var limboTargetId = _this.limboTargetsByKey.get(key);\n if (limboTargetId === null) {\n // This target already got removed, because the query failed.\n return;\n }\n _this.remoteStore.unlisten(limboTargetId);\n _this.limboTargetsByKey = _this.limboTargetsByKey.remove(key);\n delete _this.limboKeysByTarget[limboTargetId];\n });\n })\n .toPromise();\n };\n // Visible for testing\n SyncEngine.prototype.currentLimboDocs = function () {\n return this.limboTargetsByKey;\n };\n SyncEngine.prototype.emitNewSnapsAndNotifyLocalStore = function (changes, remoteEvent) {\n var _this = this;\n var newSnaps = [];\n var docChangesInAllViews = [];\n var queriesProcessed = [];\n this.queryViewsByQuery.forEach(function (_, queryView) {\n queriesProcessed.push(Promise.resolve()\n .then(function () {\n var viewDocChanges = queryView.view.computeDocChanges(changes);\n if (!viewDocChanges.needsRefill) {\n return viewDocChanges;\n }\n // The query has a limit and some docs were removed, so we need\n // to re-run the query against the local store to make sure we\n // didn't lose any good docs that had been past the limit.\n return _this.localStore.executeQuery(queryView.query).then(function (docs) {\n return queryView.view.computeDocChanges(docs, viewDocChanges);\n });\n })\n .then(function (viewDocChanges) {\n var targetChange = remoteEvent && remoteEvent.targetChanges[queryView.targetId];\n var viewChange = queryView.view.applyChanges(viewDocChanges, targetChange);\n return _this.updateTrackedLimbos(queryView.targetId, viewChange.limboChanges).then(function () {\n if (viewChange.snapshot) {\n newSnaps.push(viewChange.snapshot);\n var docChanges = LocalViewChanges.fromSnapshot(viewChange.snapshot);\n docChangesInAllViews.push(docChanges);\n }\n });\n }));\n });\n return Promise.all(queriesProcessed)\n .then(function () {\n _this.viewHandler(newSnaps);\n return _this.localStore.notifyLocalViewChanges(docChangesInAllViews);\n })\n .then(function () {\n return _this.localStore.collectGarbage();\n });\n };\n SyncEngine.prototype.assertSubscribed = function (fnName) {\n assert(this.viewHandler !== null && this.errorHandler !== null, 'Trying to call ' + fnName + ' before calling subscribe().');\n };\n SyncEngine.prototype.handleUserChange = function (user) {\n var _this = this;\n this.currentUser = user;\n return this.localStore\n .handleUserChange(user)\n .then(function (changes) {\n return _this.emitNewSnapsAndNotifyLocalStore(changes);\n })\n .then(function () {\n return _this.remoteStore.handleUserChange(user);\n });\n };\n return SyncEngine;\n}());\nexport { SyncEngine };\n\n//# sourceMappingURL=sync_engine.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/sync_engine.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { documentKeySet, documentVersionMap } from './collections';\nimport { assert } from '../util/assert';\nimport * as misc from '../util/misc';\nexport var BATCHID_UNKNOWN = -1;\n/**\n * A batch of mutations that will be sent as one unit to the backend.\n */\nvar MutationBatch = /** @class */ (function () {\n function MutationBatch(batchId, localWriteTime, mutations) {\n this.batchId = batchId;\n this.localWriteTime = localWriteTime;\n this.mutations = mutations;\n }\n /**\n * Applies all the mutations in this MutationBatch to the specified document\n * to create a new remote document\n *\n * @param docKey The key of the document to apply mutations to.\n * @param maybeDoc The document to apply mutations to.\n * @param batchResult The result of applying the MutationBatch to the\n * backend.\n */\n MutationBatch.prototype.applyToRemoteDocument = function (docKey, maybeDoc, batchResult) {\n if (maybeDoc) {\n assert(maybeDoc.key.isEqual(docKey), \"applyToRemoteDocument: key \" + docKey + \" should match maybeDoc key\\n \" + maybeDoc.key);\n }\n var mutationResults = batchResult.mutationResults;\n assert(mutationResults.length === this.mutations.length, \"Mismatch between mutations length\\n (\" + this.mutations.length + \") and mutation results length\\n (\" + mutationResults.length + \").\");\n for (var i = 0; i < this.mutations.length; i++) {\n var mutation = this.mutations[i];\n if (mutation.key.isEqual(docKey)) {\n var mutationResult = mutationResults[i];\n maybeDoc = mutation.applyToRemoteDocument(maybeDoc, mutationResult);\n }\n }\n return maybeDoc;\n };\n /**\n * Computes the local view of a document given all the mutations in this\n * batch.\n *\n * @param docKey The key of the document to apply mutations to.\n * @param maybeDoc The document to apply mutations to.\n */\n MutationBatch.prototype.applyToLocalView = function (docKey, maybeDoc) {\n if (maybeDoc) {\n assert(maybeDoc.key.isEqual(docKey), \"applyToLocalDocument: key \" + docKey + \" should match maybeDoc key\\n \" + maybeDoc.key);\n }\n var baseDoc = maybeDoc;\n for (var i = 0; i < this.mutations.length; i++) {\n var mutation = this.mutations[i];\n if (mutation.key.isEqual(docKey)) {\n maybeDoc = mutation.applyToLocalView(maybeDoc, baseDoc, this.localWriteTime);\n }\n }\n return maybeDoc;\n };\n MutationBatch.prototype.keys = function () {\n var keySet = documentKeySet();\n for (var _i = 0, _a = this.mutations; _i < _a.length; _i++) {\n var mutation = _a[_i];\n keySet = keySet.add(mutation.key);\n }\n return keySet;\n };\n MutationBatch.prototype.isEqual = function (other) {\n return (this.batchId === other.batchId &&\n misc.arrayEquals(this.mutations, other.mutations));\n };\n /**\n * Returns true if this mutation batch has already been removed from the\n * mutation queue.\n *\n * Note that not all implementations of the MutationQueue necessarily use\n * tombstones as part of their implementation and generally speaking no code\n * outside the mutation queues should really care about this.\n */\n MutationBatch.prototype.isTombstone = function () {\n return this.mutations.length === 0;\n };\n /** Converts this batch into a tombstone */\n MutationBatch.prototype.toTombstone = function () {\n return new MutationBatch(this.batchId, this.localWriteTime, []);\n };\n return MutationBatch;\n}());\nexport { MutationBatch };\n/** The result of applying a mutation batch to the backend. */\nvar MutationBatchResult = /** @class */ (function () {\n function MutationBatchResult(batch, commitVersion, mutationResults, streamToken, \n /**\n * A pre-computed mapping from each mutated document to the resulting\n * version.\n */\n docVersions) {\n this.batch = batch;\n this.commitVersion = commitVersion;\n this.mutationResults = mutationResults;\n this.streamToken = streamToken;\n this.docVersions = docVersions;\n }\n /**\n * Creates a new MutationBatchResult for the given batch and results. There\n * must be one result for each mutation in the batch. This static factory\n * caches a document=>version mapping (docVersions).\n */\n MutationBatchResult.from = function (batch, commitVersion, results, streamToken) {\n assert(batch.mutations.length === results.length, 'Mutations sent ' +\n batch.mutations.length +\n ' must equal results received ' +\n results.length);\n var versionMap = documentVersionMap();\n var mutations = batch.mutations;\n for (var i = 0; i < mutations.length; i++) {\n var version = results[i].version;\n if (version === null) {\n // deletes don't have a version, so we substitute the commitVersion\n // of the entire batch.\n version = commitVersion;\n }\n versionMap = versionMap.insert(mutations[i].key, version);\n }\n return new MutationBatchResult(batch, commitVersion, results, streamToken, versionMap);\n };\n return MutationBatchResult;\n}());\nexport { MutationBatchResult };\n\n//# sourceMappingURL=mutation_batch.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/model/mutation_batch.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { assert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport * as log from '../util/log';\nimport { AutoId } from '../util/misc';\nimport { IndexedDbMutationQueue } from './indexeddb_mutation_queue';\nimport { IndexedDbQueryCache } from './indexeddb_query_cache';\nimport { IndexedDbRemoteDocumentCache } from './indexeddb_remote_document_cache';\nimport { ALL_STORES, DbOwner } from './indexeddb_schema';\nimport { createOrUpgradeDb, SCHEMA_VERSION } from './indexeddb_schema';\nimport { LocalSerializer } from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { SimpleDb } from './simple_db';\nvar LOG_TAG = 'IndexedDbPersistence';\n/** If the owner lease is older than 5 seconds, try to take ownership. */\nvar OWNER_LEASE_MAX_AGE_MS = 5000;\n/** Refresh the owner lease every 4 seconds while owner. */\nvar OWNER_LEASE_REFRESH_INTERVAL_MS = 4000;\n/** LocalStorage location to indicate a zombied ownerId (see class comment). */\nvar ZOMBIE_OWNER_LOCALSTORAGE_SUFFIX = 'zombiedOwnerId';\n/** Error when the owner lease cannot be acquired or is lost. */\nvar EXISTING_OWNER_ERROR_MSG = 'There is another tab open with offline' +\n ' persistence enabled. Only one such tab is allowed at a time. The' +\n ' other tab must be closed or persistence must be disabled.';\nvar UNSUPPORTED_PLATFORM_ERROR_MSG = 'This platform is either missing' +\n ' IndexedDB or is known to have an incomplete implementation. Offline' +\n ' persistence has been disabled.';\n/**\n * An IndexedDB-backed instance of Persistence. Data is stored persistently\n * across sessions.\n *\n * Currently the Firestore SDK only supports a single consumer of the database,\n * but browsers obviously support multiple tabs. IndexedDbPersistence ensures a\n * single consumer of the database via an \"owner lease\" stored in the database.\n *\n * On startup, IndexedDbPersistence assigns itself a random \"ownerId\" and writes\n * it to a special \"owner\" object in the database (if no entry exists already or\n * the current entry is expired). This owner lease is then verified inside every\n * transaction to ensure the lease has not been lost.\n *\n * If a tab opts not to acquire the owner lease (because there's an existing\n * non-expired owner) or loses the owner lease, IndexedDbPersistence enters a\n * failed state and all subsequent operations will automatically fail.\n *\n * The current owner regularly refreshes the owner lease with new timestamps to\n * prevent newly-opened tabs from taking over ownership.\n *\n * Additionally there is an optimization so that when a tab is closed, the owner\n * lease is released immediately (this is especially important to make sure that\n * a refreshed tab is able to immediately re-acquire the owner lease).\n * Unfortunately, IndexedDB cannot be reliably used in window.unload since it is\n * an asynchronous API. So in addition to attempting to give up the lease,\n * the owner writes its ownerId to a \"zombiedOwnerId\" entry in LocalStorage\n * which acts as an indicator that another tab should go ahead and take the\n * owner lease immediately regardless of the current lease timestamp.\n */\nvar IndexedDbPersistence = /** @class */ (function () {\n function IndexedDbPersistence(prefix, serializer) {\n this.ownerId = this.generateOwnerId();\n this.dbName = prefix + IndexedDbPersistence.MAIN_DATABASE;\n this.serializer = new LocalSerializer(serializer);\n this.localStoragePrefix = prefix;\n }\n IndexedDbPersistence.prototype.start = function () {\n var _this = this;\n if (!IndexedDbPersistence.isAvailable()) {\n this.persistenceError = new FirestoreError(Code.UNIMPLEMENTED, UNSUPPORTED_PLATFORM_ERROR_MSG);\n return Promise.reject(this.persistenceError);\n }\n assert(!this.started, 'IndexedDbPersistence double-started!');\n this.started = true;\n return SimpleDb.openOrCreate(this.dbName, SCHEMA_VERSION, createOrUpgradeDb)\n .then(function (db) {\n _this.simpleDb = db;\n })\n .then(function () { return _this.tryAcquireOwnerLease(); })\n .then(function () {\n _this.scheduleOwnerLeaseRefreshes();\n _this.attachWindowUnloadHook();\n });\n };\n IndexedDbPersistence.prototype.shutdown = function () {\n var _this = this;\n assert(this.started, 'IndexedDbPersistence shutdown without start!');\n this.started = false;\n this.detachWindowUnloadHook();\n this.stopOwnerLeaseRefreshes();\n return this.releaseOwnerLease().then(function () {\n _this.simpleDb.close();\n });\n };\n IndexedDbPersistence.prototype.getMutationQueue = function (user) {\n return IndexedDbMutationQueue.forUser(user, this.serializer);\n };\n IndexedDbPersistence.prototype.getQueryCache = function () {\n return new IndexedDbQueryCache(this.serializer);\n };\n IndexedDbPersistence.prototype.getRemoteDocumentCache = function () {\n return new IndexedDbRemoteDocumentCache(this.serializer);\n };\n IndexedDbPersistence.prototype.runTransaction = function (action, operation) {\n var _this = this;\n if (this.persistenceError) {\n return Promise.reject(this.persistenceError);\n }\n log.debug(LOG_TAG, 'Starting transaction:', action);\n // Do all transactions as readwrite against all object stores, since we\n // are the only reader/writer.\n return this.simpleDb.runTransaction('readwrite', ALL_STORES, function (txn) {\n // Verify that we still have the owner lease as part of every transaction.\n return _this.ensureOwnerLease(txn).next(function () { return operation(txn); });\n });\n };\n IndexedDbPersistence.isAvailable = function () {\n return SimpleDb.isAvailable();\n };\n /**\n * Generates a string used as a prefix when storing data in IndexedDB and\n * LocalStorage.\n */\n IndexedDbPersistence.buildStoragePrefix = function (databaseInfo) {\n // Use two different prefix formats:\n //\n // * firestore / persistenceKey / projectID . databaseID / ...\n // * firestore / persistenceKey / projectID / ...\n //\n // projectIDs are DNS-compatible names and cannot contain dots\n // so there's no danger of collisions.\n var database = databaseInfo.databaseId.projectId;\n if (!databaseInfo.databaseId.isDefaultDatabase) {\n database += '.' + databaseInfo.databaseId.database;\n }\n return 'firestore/' + databaseInfo.persistenceKey + '/' + database + '/';\n };\n /**\n * Acquires the owner lease if there's no valid owner. Else returns a rejected\n * promise.\n */\n IndexedDbPersistence.prototype.tryAcquireOwnerLease = function () {\n var _this = this;\n // NOTE: Don't use this.runTransaction, since it requires us to already\n // have the lease.\n return this.simpleDb.runTransaction('readwrite', [DbOwner.store], function (txn) {\n var store = txn.store(DbOwner.store);\n return store.get('owner').next(function (dbOwner) {\n if (!_this.validOwner(dbOwner)) {\n var newDbOwner = new DbOwner(_this.ownerId, Date.now());\n log.debug(LOG_TAG, 'No valid owner. Acquiring owner lease. Current owner:', dbOwner, 'New owner:', newDbOwner);\n return store.put('owner', newDbOwner);\n }\n else {\n log.debug(LOG_TAG, 'Valid owner already. Failing. Current owner:', dbOwner);\n _this.persistenceError = new FirestoreError(Code.FAILED_PRECONDITION, EXISTING_OWNER_ERROR_MSG);\n return PersistencePromise.reject(_this.persistenceError);\n }\n });\n });\n };\n /** Checks the owner lease and deletes it if we are the current owner. */\n IndexedDbPersistence.prototype.releaseOwnerLease = function () {\n var _this = this;\n // NOTE: Don't use this.runTransaction, since it requires us to already\n // have the lease.\n return this.simpleDb.runTransaction('readwrite', [DbOwner.store], function (txn) {\n var store = txn.store(DbOwner.store);\n return store.get('owner').next(function (dbOwner) {\n if (dbOwner !== null && dbOwner.ownerId === _this.ownerId) {\n log.debug(LOG_TAG, 'Releasing owner lease.');\n return store.delete('owner');\n }\n else {\n return PersistencePromise.resolve();\n }\n });\n });\n };\n /**\n * Checks the owner lease and returns a rejected promise if we are not the\n * current owner. This should be included in every transaction to guard\n * against losing the owner lease.\n */\n IndexedDbPersistence.prototype.ensureOwnerLease = function (txn) {\n var _this = this;\n var store = txn.store(DbOwner.store);\n return store.get('owner').next(function (dbOwner) {\n if (dbOwner === null || dbOwner.ownerId !== _this.ownerId) {\n _this.persistenceError = new FirestoreError(Code.FAILED_PRECONDITION, EXISTING_OWNER_ERROR_MSG);\n return PersistencePromise.reject(_this.persistenceError);\n }\n else {\n return PersistencePromise.resolve();\n }\n });\n };\n /**\n * Returns true if the provided owner exists, has a recent timestamp, and\n * isn't zombied.\n *\n * NOTE: To determine if the owner is zombied, this method reads from\n * LocalStorage which could be mildly expensive.\n */\n IndexedDbPersistence.prototype.validOwner = function (dbOwner) {\n var now = Date.now();\n var minAcceptable = now - OWNER_LEASE_MAX_AGE_MS;\n var maxAcceptable = now;\n if (dbOwner === null) {\n return false; // no owner.\n }\n else if (dbOwner.leaseTimestampMs < minAcceptable) {\n return false; // owner lease has expired.\n }\n else if (dbOwner.leaseTimestampMs > maxAcceptable) {\n log.error('Persistence owner-lease is in the future. Discarding.', dbOwner);\n return false;\n }\n else if (dbOwner.ownerId === this.getZombiedOwnerId()) {\n return false; // owner's tab closed.\n }\n else {\n return true;\n }\n };\n /**\n * Schedules a recurring timer to update the owner lease timestamp to prevent\n * other tabs from taking the lease.\n */\n IndexedDbPersistence.prototype.scheduleOwnerLeaseRefreshes = function () {\n var _this = this;\n // NOTE: This doesn't need to be scheduled on the async queue and doing so\n // would increase the chances of us not refreshing on time if the queue is\n // backed up for some reason.\n this.ownerLeaseRefreshHandle = setInterval(function () {\n var txResult = _this.runTransaction('Refresh owner timestamp', function (txn) {\n // NOTE: We don't need to validate the current owner contents, since\n // runTransaction does that automatically.\n var store = txn.store(DbOwner.store);\n return store.put('owner', new DbOwner(_this.ownerId, Date.now()));\n });\n txResult.catch(function (reason) {\n // Probably means we lost the lease. Report the error and stop trying to\n // refresh the lease.\n log.error(reason);\n _this.stopOwnerLeaseRefreshes();\n });\n }, OWNER_LEASE_REFRESH_INTERVAL_MS);\n };\n IndexedDbPersistence.prototype.stopOwnerLeaseRefreshes = function () {\n if (this.ownerLeaseRefreshHandle) {\n clearInterval(this.ownerLeaseRefreshHandle);\n this.ownerLeaseRefreshHandle = null;\n }\n };\n /**\n * Attaches a window.unload handler that will synchronously write our\n * ownerId to a \"zombie owner id\" location in localstorage. This can be used\n * by tabs trying to acquire the lease to determine that the lease should be\n * acquired immediately even if the timestamp is recent. This is particularly\n * important for the refresh case (so the tab correctly re-acquires the owner\n * lease). LocalStorage is used for this rather than IndexedDb because it is\n * a synchronous API and so can be used reliably from an unload handler.\n */\n IndexedDbPersistence.prototype.attachWindowUnloadHook = function () {\n var _this = this;\n this.windowUnloadHandler = function () {\n // Record that we're zombied.\n _this.setZombiedOwnerId(_this.ownerId);\n // Attempt graceful shutdown (including releasing our owner lease), but\n // there's no guarantee it will complete.\n _this.shutdown();\n };\n window.addEventListener('unload', this.windowUnloadHandler);\n };\n IndexedDbPersistence.prototype.detachWindowUnloadHook = function () {\n if (this.windowUnloadHandler) {\n window.removeEventListener('unload', this.windowUnloadHandler);\n this.windowUnloadHandler = null;\n }\n };\n /**\n * Returns any recorded \"zombied owner\" (i.e. a previous owner that became\n * zombied due to their tab closing) from LocalStorage, or null if no such\n * record exists.\n */\n IndexedDbPersistence.prototype.getZombiedOwnerId = function () {\n try {\n var zombiedOwnerId = window.localStorage.getItem(this.zombiedOwnerLocalStorageKey());\n log.debug(LOG_TAG, 'Zombied ownerID from LocalStorage:', zombiedOwnerId);\n return zombiedOwnerId;\n }\n catch (e) {\n // Gracefully handle if LocalStorage isn't available / working.\n log.error('Failed to get zombie owner id.', e);\n return null;\n }\n };\n /**\n * Records a zombied owner (an owner that had its tab closed) in LocalStorage\n * or, if passed null, deletes any recorded zombied owner.\n */\n IndexedDbPersistence.prototype.setZombiedOwnerId = function (zombieOwnerId) {\n try {\n if (zombieOwnerId === null) {\n window.localStorage.removeItem(this.zombiedOwnerLocalStorageKey());\n }\n else {\n window.localStorage.setItem(this.zombiedOwnerLocalStorageKey(), zombieOwnerId);\n }\n }\n catch (e) {\n // Gracefully handle if LocalStorage isn't available / working.\n log.error('Failed to set zombie owner id.', e);\n }\n };\n IndexedDbPersistence.prototype.zombiedOwnerLocalStorageKey = function () {\n return this.localStoragePrefix + ZOMBIE_OWNER_LOCALSTORAGE_SUFFIX;\n };\n IndexedDbPersistence.prototype.generateOwnerId = function () {\n // For convenience, just use an AutoId.\n return AutoId.newId();\n };\n /**\n * The name of the main (and currently only) IndexedDB database. this name is\n * appended to the prefix provided to the IndexedDbPersistence constructor.\n */\n IndexedDbPersistence.MAIN_DATABASE = 'main';\n return IndexedDbPersistence;\n}());\nexport { IndexedDbPersistence };\n\n//# sourceMappingURL=indexeddb_persistence.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/indexeddb_persistence.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { documentKeySet, documentMap, maybeDocumentMap } from '../model/collections';\nimport { Document, NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { fail } from '../util/assert';\nimport { PersistencePromise } from './persistence_promise';\n/**\n * A readonly view of the local state of all documents we're tracking (i.e. we\n * have a cached version in remoteDocumentCache or local mutations for the\n * document). The view is computed by applying the mutations in the\n * MutationQueue to the RemoteDocumentCache.\n */\nvar LocalDocumentsView = /** @class */ (function () {\n function LocalDocumentsView(remoteDocumentCache, mutationQueue) {\n this.remoteDocumentCache = remoteDocumentCache;\n this.mutationQueue = mutationQueue;\n }\n /**\n * Get the local view of the document identified by `key`.\n *\n * @return Local view of the document or null if we don't have any cached\n * state for it.\n */\n LocalDocumentsView.prototype.getDocument = function (transaction, key) {\n var _this = this;\n return this.remoteDocumentCache\n .getEntry(transaction, key)\n .next(function (remoteDoc) {\n return _this.computeLocalDocument(transaction, key, remoteDoc);\n });\n };\n /**\n * Gets the local view of the documents identified by `keys`.\n *\n * If we don't have cached state for a document in `keys`, a NoDocument will\n * be stored for that key in the resulting set.\n */\n LocalDocumentsView.prototype.getDocuments = function (transaction, keys) {\n var _this = this;\n var promises = [];\n var results = maybeDocumentMap();\n keys.forEach(function (key) {\n promises.push(_this.getDocument(transaction, key).next(function (maybeDoc) {\n // TODO(http://b/32275378): Don't conflate missing / deleted.\n if (!maybeDoc) {\n maybeDoc = new NoDocument(key, SnapshotVersion.forDeletedDoc());\n }\n results = results.insert(key, maybeDoc);\n }));\n });\n return PersistencePromise.waitFor(promises).next(function () { return results; });\n };\n /** Performs a query against the local view of all documents. */\n LocalDocumentsView.prototype.getDocumentsMatchingQuery = function (transaction, query) {\n if (DocumentKey.isDocumentKey(query.path)) {\n return this.getDocumentsMatchingDocumentQuery(transaction, query.path);\n }\n else {\n return this.getDocumentsMatchingCollectionQuery(transaction, query);\n }\n };\n LocalDocumentsView.prototype.getDocumentsMatchingDocumentQuery = function (transaction, docPath) {\n // Just do a simple document lookup.\n return this.getDocument(transaction, new DocumentKey(docPath)).next(function (maybeDoc) {\n var result = documentMap();\n if (maybeDoc instanceof Document) {\n result = result.insert(maybeDoc.key, maybeDoc);\n }\n return result;\n });\n };\n LocalDocumentsView.prototype.getDocumentsMatchingCollectionQuery = function (transaction, query) {\n var _this = this;\n // Query the remote documents and overlay mutations.\n // TODO(mikelehen): There may be significant overlap between the mutations\n // affecting these remote documents and the\n // getAllMutationBatchesAffectingQuery() mutations. Consider optimizing.\n var results;\n return this.remoteDocumentCache\n .getDocumentsMatchingQuery(transaction, query)\n .next(function (queryResults) {\n return _this.computeLocalDocuments(transaction, queryResults);\n })\n .next(function (promisedResults) {\n results = promisedResults;\n // Now use the mutation queue to discover any other documents that may\n // match the query after applying mutations.\n return _this.mutationQueue.getAllMutationBatchesAffectingQuery(transaction, query);\n })\n .next(function (matchingMutationBatches) {\n var matchingKeys = documentKeySet();\n for (var _i = 0, matchingMutationBatches_1 = matchingMutationBatches; _i < matchingMutationBatches_1.length; _i++) {\n var batch = matchingMutationBatches_1[_i];\n for (var _a = 0, _b = batch.mutations; _a < _b.length; _a++) {\n var mutation = _b[_a];\n // TODO(mikelehen): PERF: Check if this mutation actually\n // affects the query to reduce work.\n if (!results.get(mutation.key)) {\n matchingKeys = matchingKeys.add(mutation.key);\n }\n }\n }\n // Now add in the results for the matchingKeys.\n var promises = [];\n matchingKeys.forEach(function (key) {\n promises.push(_this.getDocument(transaction, key).next(function (doc) {\n if (doc instanceof Document) {\n results = results.insert(doc.key, doc);\n }\n }));\n });\n return PersistencePromise.waitFor(promises);\n })\n .next(function () {\n // Finally, filter out any documents that don't actually match\n // the query.\n results.forEach(function (key, doc) {\n if (!query.matches(doc)) {\n results = results.remove(key);\n }\n });\n return results;\n });\n };\n /**\n * Takes a remote document and applies local mutations to generate the local\n * view of the document.\n * @param transaction The transaction in which to perform any persistence\n * operations.\n * @param documentKey The key of the document (necessary when remoteDocument\n * is null).\n * @param document The base remote document to apply mutations to or null.\n */\n LocalDocumentsView.prototype.computeLocalDocument = function (transaction, documentKey, document) {\n return this.mutationQueue\n .getAllMutationBatchesAffectingDocumentKey(transaction, documentKey)\n .next(function (batches) {\n for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {\n var batch = batches_1[_i];\n document = batch.applyToLocalView(documentKey, document);\n }\n return document;\n });\n };\n /**\n * Takes a set of remote documents and applies local mutations to generate the\n * local view of the documents.\n * @param transaction The transaction in which to perform any persistence\n * operations.\n * @param documents The base remote documents to apply mutations to.\n * @return The local view of the documents.\n */\n LocalDocumentsView.prototype.computeLocalDocuments = function (transaction, documents) {\n var _this = this;\n var promises = [];\n documents.forEach(function (key, doc) {\n promises.push(_this.computeLocalDocument(transaction, key, doc).next(function (mutatedDoc) {\n if (mutatedDoc instanceof Document) {\n documents = documents.insert(mutatedDoc.key, mutatedDoc);\n }\n else if (mutatedDoc instanceof NoDocument) {\n documents = documents.remove(mutatedDoc.key);\n }\n else {\n fail('Unknown MaybeDocument: ' + mutatedDoc);\n }\n }));\n });\n return PersistencePromise.waitFor(promises).next(function () { return documents; });\n };\n return LocalDocumentsView;\n}());\nexport { LocalDocumentsView };\n\n//# sourceMappingURL=local_documents_view.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/local_documents_view.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { maybeDocumentMap } from '../model/collections';\nimport { assert } from '../util/assert';\nimport { PersistencePromise } from './persistence_promise';\n/**\n * An in-memory buffer of entries to be written to a RemoteDocumentCache.\n * It can be used to batch up a set of changes to be written to the cache, but\n * additionally supports reading entries back with the `getEntry()` method,\n * falling back to the underlying RemoteDocumentCache if no entry is\n * buffered.\n *\n * NOTE: This class was introduced in iOS to work around a limitation in\n * LevelDB. Given IndexedDb has full transaction support with\n * read-your-own-writes capability, this class is not technically needed, but\n * has been preserved as a convenience and to aid portability.\n */\nvar RemoteDocumentChangeBuffer = /** @class */ (function () {\n function RemoteDocumentChangeBuffer(remoteDocumentCache) {\n this.remoteDocumentCache = remoteDocumentCache;\n this.changes = maybeDocumentMap();\n }\n /** Buffers a `RemoteDocumentCache.addEntry()` call. */\n RemoteDocumentChangeBuffer.prototype.addEntry = function (maybeDocument) {\n var changes = this.assertChanges();\n this.changes = changes.insert(maybeDocument.key, maybeDocument);\n };\n // NOTE: removeEntry() is not presently necessary and so is omitted.\n /**\n * Looks up an entry in the cache. The buffered changes will first be checked,\n * and if no buffered change applies, this will forward to\n * `RemoteDocumentCache.getEntry()`.\n *\n * @param transaction The transaction in which to perform any persistence\n * operations.\n * @param documentKey The key of the entry to look up.\n * @return The cached Document or NoDocument entry, or null if we have nothing\n * cached.\n */\n RemoteDocumentChangeBuffer.prototype.getEntry = function (transaction, documentKey) {\n var changes = this.assertChanges();\n var bufferedEntry = changes.get(documentKey);\n if (bufferedEntry) {\n return PersistencePromise.resolve(bufferedEntry);\n }\n else {\n return this.remoteDocumentCache.getEntry(transaction, documentKey);\n }\n };\n /**\n * Applies buffered changes to the underlying RemoteDocumentCache, using\n * the provided transaction.\n */\n RemoteDocumentChangeBuffer.prototype.apply = function (transaction) {\n var _this = this;\n var changes = this.assertChanges();\n var promises = [];\n changes.forEach(function (key, maybeDoc) {\n promises.push(_this.remoteDocumentCache.addEntry(transaction, maybeDoc));\n });\n // We should not be used to buffer any more changes.\n this.changes = null;\n return PersistencePromise.waitFor(promises);\n };\n /** Helper to assert this.changes is not null and return it. */\n RemoteDocumentChangeBuffer.prototype.assertChanges = function () {\n assert(this.changes !== null, 'Changes have already been applied.');\n return this.changes;\n };\n return RemoteDocumentChangeBuffer;\n}());\nexport { RemoteDocumentChangeBuffer };\n\n//# sourceMappingURL=remote_document_change_buffer.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/remote_document_change_buffer.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { TargetIdGenerator } from '../core/target_id_generator';\nimport { Timestamp } from '../core/timestamp';\nimport { documentKeySet } from '../model/collections';\nimport { BATCHID_UNKNOWN } from '../model/mutation_batch';\nimport { ResetMapping, UpdateMapping } from '../remote/remote_event';\nimport { assert, fail } from '../util/assert';\nimport * as log from '../util/log';\nimport * as objUtils from '../util/obj';\nimport { LocalDocumentsView } from './local_documents_view';\nimport { PersistencePromise } from './persistence_promise';\nimport { QueryData, QueryPurpose } from './query_data';\nimport { ReferenceSet } from './reference_set';\nimport { RemoteDocumentChangeBuffer } from './remote_document_change_buffer';\nvar LOG_TAG = 'LocalStore';\n/**\n * Local storage in the Firestore client. Coordinates persistence components\n * like the mutation queue and remote document cache to present a\n * latency-compensated view of stored data.\n *\n * The LocalStore is responsible for accepting mutations from the Sync Engine.\n * Writes from the client are put into a queue as provisional Mutations until\n * they are processed by the RemoteStore and confirmed as having been written\n * to the server.\n *\n * The local store provides the local version of documents that have been\n * modified locally. It maintains the constraint:\n *\n * LocalDocument = RemoteDocument + Active(LocalMutations)\n *\n * (Active mutations are those that are enqueued and have not been previously\n * acknowledged or rejected).\n *\n * The RemoteDocument (\"ground truth\") state is provided via the\n * applyChangeBatch method. It will be some version of a server-provided\n * document OR will be a server-provided document PLUS acknowledged mutations:\n *\n * RemoteDocument' = RemoteDocument + Acknowledged(LocalMutations)\n *\n * Note that this \"dirty\" version of a RemoteDocument will not be identical to a\n * server base version, since it has LocalMutations added to it pending getting\n * an authoritative copy from the server.\n *\n * Since LocalMutations can be rejected by the server, we have to be able to\n * revert a LocalMutation that has already been applied to the LocalDocument\n * (typically done by replaying all remaining LocalMutations to the\n * RemoteDocument to re-apply).\n *\n * The LocalStore is responsible for the garbage collection of the documents it\n * contains. For now, it every doc referenced by a view, the mutation queue, or\n * the RemoteStore.\n *\n * It also maintains the persistence of mapping queries to resume tokens and\n * target ids. It needs to know this data about queries to properly know what\n * docs it would be allowed to garbage collect.\n *\n * The LocalStore must be able to efficiently execute queries against its local\n * cache of the documents, to provide the initial set of results before any\n * remote changes have been received.\n *\n * Note: In TypeScript, most methods return Promises since the implementation\n * may rely on fetching data from IndexedDB which is async.\n * These Promises will only be rejected on an I/O error or other internal\n * (unexpected) failure (e.g. failed assert) and always represent an\n * unrecoverable error (should be caught / reported by the async_queue).\n */\nvar LocalStore = /** @class */ (function () {\n function LocalStore(\n /** Manages our in-memory or durable persistence. */\n persistence, initialUser, \n /**\n * The garbage collector collects documents that should no longer be\n * cached (e.g. if they are no longer retained by the above reference sets\n * and the garbage collector is performing eager collection).\n */\n garbageCollector) {\n this.persistence = persistence;\n this.garbageCollector = garbageCollector;\n /**\n * The set of document references maintained by any local views.\n */\n this.localViewReferences = new ReferenceSet();\n /** Maps a targetID to data about its query. */\n this.targetIds = {};\n /** Used to generate targetIDs for queries tracked locally. */\n this.targetIdGenerator = TargetIdGenerator.forLocalStore();\n /**\n * A heldBatchResult is a mutation batch result (from a write acknowledgement)\n * that arrived before the watch stream got notified of a snapshot that\n * includes the write. So we \"hold\" it until the watch stream catches up. It\n * ensures that the local write remains visible (latency compensation) and\n * doesn't temporarily appear reverted because the watch stream is slower than\n * the write stream and so wasn't reflecting it.\n *\n * NOTE: Eventually we want to move this functionality into the remote store.\n */\n this.heldBatchResults = [];\n this.mutationQueue = persistence.getMutationQueue(initialUser);\n this.remoteDocuments = persistence.getRemoteDocumentCache();\n this.queryCache = persistence.getQueryCache();\n this.localDocuments = new LocalDocumentsView(this.remoteDocuments, this.mutationQueue);\n this.garbageCollector.addGarbageSource(this.localViewReferences);\n this.garbageCollector.addGarbageSource(this.queryCache);\n this.garbageCollector.addGarbageSource(this.mutationQueue);\n }\n /** Performs any initial startup actions required by the local store. */\n LocalStore.prototype.start = function () {\n var _this = this;\n return this.persistence.runTransaction('Start LocalStore', function (txn) {\n return _this.startMutationQueue(txn).next(function () { return _this.startQueryCache(txn); });\n });\n };\n /**\n * Tells the LocalStore that the currently authenticated user has changed.\n *\n * In response the local store switches the mutation queue to the new user and\n * returns any resulting document changes.\n */\n LocalStore.prototype.handleUserChange = function (user) {\n var _this = this;\n return this.persistence.runTransaction('Handle user change', function (txn) {\n // Swap out the mutation queue, grabbing the pending mutation batches\n // before and after.\n var oldBatches;\n return _this.mutationQueue\n .getAllMutationBatches(txn)\n .next(function (promisedOldBatches) {\n oldBatches = promisedOldBatches;\n _this.garbageCollector.removeGarbageSource(_this.mutationQueue);\n _this.mutationQueue = _this.persistence.getMutationQueue(user);\n _this.garbageCollector.addGarbageSource(_this.mutationQueue);\n return _this.startMutationQueue(txn);\n })\n .next(function () {\n // Recreate our LocalDocumentsView using the new\n // MutationQueue.\n _this.localDocuments = new LocalDocumentsView(_this.remoteDocuments, _this.mutationQueue);\n return _this.mutationQueue.getAllMutationBatches(txn);\n })\n .next(function (newBatches) {\n // Union the old/new changed keys.\n var changedKeys = documentKeySet();\n for (var _i = 0, _a = [oldBatches, newBatches]; _i < _a.length; _i++) {\n var batches = _a[_i];\n for (var _b = 0, batches_1 = batches; _b < batches_1.length; _b++) {\n var batch = batches_1[_b];\n for (var _c = 0, _d = batch.mutations; _c < _d.length; _c++) {\n var mutation = _d[_c];\n changedKeys = changedKeys.add(mutation.key);\n }\n }\n }\n // Return the set of all (potentially) changed documents as the\n // result of the user change.\n return _this.localDocuments.getDocuments(txn, changedKeys);\n });\n });\n };\n LocalStore.prototype.startQueryCache = function (txn) {\n var _this = this;\n return this.queryCache.start(txn).next(function () {\n var targetId = _this.queryCache.getHighestTargetId();\n _this.targetIdGenerator = TargetIdGenerator.forLocalStore(targetId);\n });\n };\n LocalStore.prototype.startMutationQueue = function (txn) {\n var _this = this;\n return this.mutationQueue\n .start(txn)\n .next(function () {\n // If we have any leftover mutation batch results from a prior run,\n // just drop them.\n // TODO(http://b/33446471): We probably need to repopulate\n // heldBatchResults or similar instead, but that is not\n // straightforward since we're not persisting the write ack versions.\n _this.heldBatchResults = [];\n return _this.mutationQueue.getHighestAcknowledgedBatchId(txn);\n })\n .next(function (highestAck) {\n // TODO(mikelehen): This is the only usage of\n // getAllMutationBatchesThroughBatchId(). Consider removing it in\n // favor of a getAcknowledgedBatches() method.\n if (highestAck !== BATCHID_UNKNOWN) {\n return _this.mutationQueue.getAllMutationBatchesThroughBatchId(txn, highestAck);\n }\n else {\n return PersistencePromise.resolve([]);\n }\n })\n .next(function (ackedBatches) {\n if (ackedBatches.length > 0) {\n return _this.mutationQueue.removeMutationBatches(txn, ackedBatches);\n }\n else {\n return PersistencePromise.resolve();\n }\n });\n };\n /* Accept locally generated Mutations and commit them to storage. */\n LocalStore.prototype.localWrite = function (mutations) {\n var _this = this;\n return this.persistence.runTransaction('Locally write mutations', function (txn) {\n var batch;\n var localWriteTime = Timestamp.now();\n return _this.mutationQueue\n .addMutationBatch(txn, localWriteTime, mutations)\n .next(function (promisedBatch) {\n batch = promisedBatch;\n // TODO(koss): This is doing an N^2 update by replaying ALL the\n // mutations on each document (instead of just the ones added) in\n // this batch.\n var keys = batch.keys();\n return _this.localDocuments.getDocuments(txn, keys);\n })\n .next(function (changedDocuments) {\n return { batchId: batch.batchId, changes: changedDocuments };\n });\n });\n };\n /**\n * Acknowledge the given batch.\n *\n * On the happy path when a batch is acknowledged, the local store will\n *\n * + remove the batch from the mutation queue;\n * + apply the changes to the remote document cache;\n * + recalculate the latency compensated view implied by those changes (there\n * may be mutations in the queue that affect the documents but haven't been\n * acknowledged yet); and\n * + give the changed documents back the sync engine\n *\n * @returns The resulting (modified) documents.\n */\n LocalStore.prototype.acknowledgeBatch = function (batchResult) {\n var _this = this;\n return this.persistence.runTransaction('Acknowledge batch', function (txn) {\n var affected;\n return _this.mutationQueue\n .acknowledgeBatch(txn, batchResult.batch, batchResult.streamToken)\n .next(function () {\n if (_this.shouldHoldBatchResult(batchResult.commitVersion)) {\n _this.heldBatchResults.push(batchResult);\n affected = documentKeySet();\n return PersistencePromise.resolve();\n }\n else {\n var documentBuffer_1 = new RemoteDocumentChangeBuffer(_this.remoteDocuments);\n return _this.releaseBatchResults(txn, [batchResult], documentBuffer_1).next(function (promisedAffectedKeys) {\n affected = promisedAffectedKeys;\n return documentBuffer_1.apply(txn);\n });\n }\n })\n .next(function () {\n return _this.mutationQueue.performConsistencyCheck(txn);\n })\n .next(function () {\n return _this.localDocuments.getDocuments(txn, affected);\n });\n });\n };\n /**\n * Remove mutations from the MutationQueue for the specified batch;\n * LocalDocuments will be recalculated.\n *\n * @returns The resulting modified documents.\n */\n LocalStore.prototype.rejectBatch = function (batchId) {\n var _this = this;\n return this.persistence.runTransaction('Reject batch', function (txn) {\n var toReject;\n var affectedKeys;\n return _this.mutationQueue\n .lookupMutationBatch(txn, batchId)\n .next(function (promisedToReject) {\n assert(promisedToReject != null, 'Attempt to reject nonexistent batch!');\n toReject = promisedToReject;\n return _this.mutationQueue\n .getHighestAcknowledgedBatchId(txn)\n .next(function (lastAcked) {\n assert(batchId > lastAcked, \"Acknowledged batches can't be rejected.\");\n return toReject;\n });\n })\n .next(function () {\n return _this.removeMutationBatch(txn, toReject);\n })\n .next(function (promisedAffectedKeys) {\n affectedKeys = promisedAffectedKeys;\n return _this.mutationQueue.performConsistencyCheck(txn);\n })\n .next(function () {\n return _this.localDocuments.getDocuments(txn, affectedKeys);\n });\n });\n };\n /** Returns the last recorded stream token for the current user. */\n LocalStore.prototype.getLastStreamToken = function () {\n var _this = this;\n return this.persistence.runTransaction('Get last stream token', function (txn) {\n return _this.mutationQueue.getLastStreamToken(txn);\n });\n };\n /**\n * Sets the stream token for the current user without acknowledging any\n * mutation batch. This is usually only useful after a stream handshake or in\n * response to an error that requires clearing the stream token.\n */\n LocalStore.prototype.setLastStreamToken = function (streamToken) {\n var _this = this;\n return this.persistence.runTransaction('Set last stream token', function (txn) {\n return _this.mutationQueue.setLastStreamToken(txn, streamToken);\n });\n };\n /**\n * Returns the last consistent snapshot processed (used by the RemoteStore to\n * determine whether to buffer incoming snapshots from the backend).\n */\n LocalStore.prototype.getLastRemoteSnapshotVersion = function () {\n return this.queryCache.getLastRemoteSnapshotVersion();\n };\n /**\n * Update the \"ground-state\" (remote) documents. We assume that the remote\n * event reflects any write batches that have been acknowledged or rejected\n * (i.e. we do not re-apply local mutations to updates from this event).\n *\n * LocalDocuments are re-calculated if there are remaining mutations in the\n * queue.\n */\n LocalStore.prototype.applyRemoteEvent = function (remoteEvent) {\n var _this = this;\n var documentBuffer = new RemoteDocumentChangeBuffer(this.remoteDocuments);\n return this.persistence.runTransaction('Apply remote event', function (txn) {\n var promises = [];\n objUtils.forEachNumber(remoteEvent.targetChanges, function (targetId, change) {\n // Do not ref/unref unassigned targetIds - it may lead to leaks.\n var queryData = _this.targetIds[targetId];\n if (!queryData)\n return;\n var mapping = change.mapping;\n if (mapping) {\n // First make sure that all references are deleted\n if (mapping instanceof ResetMapping) {\n promises.push(_this.queryCache\n .removeMatchingKeysForTargetId(txn, targetId)\n .next(function () {\n return _this.queryCache.addMatchingKeys(txn, mapping.documents, targetId);\n }));\n }\n else if (mapping instanceof UpdateMapping) {\n promises.push(_this.queryCache\n .removeMatchingKeys(txn, mapping.removedDocuments, targetId)\n .next(function () {\n return _this.queryCache.addMatchingKeys(txn, mapping.addedDocuments, targetId);\n }));\n }\n else {\n return fail('Unknown mapping type: ' + JSON.stringify(mapping));\n }\n }\n // Update the resume token if the change includes one. Don't clear\n // any preexisting value.\n var resumeToken = change.resumeToken;\n if (resumeToken.length > 0) {\n queryData = queryData.update({\n resumeToken: resumeToken,\n snapshotVersion: change.snapshotVersion\n });\n _this.targetIds[targetId] = queryData;\n promises.push(_this.queryCache.addQueryData(txn, queryData));\n }\n });\n var changedDocKeys = documentKeySet();\n remoteEvent.documentUpdates.forEach(function (key, doc) {\n changedDocKeys = changedDocKeys.add(key);\n promises.push(documentBuffer.getEntry(txn, key).next(function (existingDoc) {\n // Make sure we don't apply an old document version to the remote\n // cache, though we make an exception for SnapshotVersion.MIN which\n // can happen for manufactured events (e.g. in the case of a limbo\n // document resolution failing).\n if (existingDoc == null ||\n doc.version.isEqual(SnapshotVersion.MIN) ||\n doc.version.compareTo(existingDoc.version) >= 0) {\n documentBuffer.addEntry(doc);\n }\n else {\n log.debug(LOG_TAG, 'Ignoring outdated watch update for ', key, '. Current version:', existingDoc.version, ' Watch version:', doc.version);\n }\n // The document might be garbage because it was unreferenced by\n // everything. Make sure to mark it as garbage if it is...\n _this.garbageCollector.addPotentialGarbageKey(key);\n }));\n });\n // HACK: The only reason we allow a null snapshot version is so that we\n // can synthesize remote events when we get permission denied errors while\n // trying to resolve the state of a locally cached document that is in\n // limbo.\n var lastRemoteVersion = _this.queryCache.getLastRemoteSnapshotVersion();\n var remoteVersion = remoteEvent.snapshotVersion;\n if (!remoteVersion.isEqual(SnapshotVersion.MIN)) {\n assert(remoteVersion.compareTo(lastRemoteVersion) >= 0, 'Watch stream reverted to previous snapshot?? ' +\n remoteVersion +\n ' < ' +\n lastRemoteVersion);\n promises.push(_this.queryCache.setLastRemoteSnapshotVersion(txn, remoteVersion));\n }\n var releasedWriteKeys;\n return PersistencePromise.waitFor(promises)\n .next(function () { return _this.releaseHeldBatchResults(txn, documentBuffer); })\n .next(function (promisedReleasedWriteKeys) {\n releasedWriteKeys = promisedReleasedWriteKeys;\n return documentBuffer.apply(txn);\n })\n .next(function () {\n return _this.localDocuments.getDocuments(txn, changedDocKeys.unionWith(releasedWriteKeys));\n });\n });\n };\n /**\n * Notify local store of the changed views to locally pin documents.\n */\n LocalStore.prototype.notifyLocalViewChanges = function (viewChanges) {\n var _this = this;\n return this.persistence.runTransaction('Notify local view changes', function (txn) {\n var promises = [];\n var _loop_1 = function (view) {\n promises.push(_this.queryCache\n .getQueryData(txn, view.query)\n .next(function (queryData) {\n assert(queryData !== null, 'Local view changes contain unallocated query.');\n var targetId = queryData.targetId;\n _this.localViewReferences.addReferences(view.addedKeys, targetId);\n _this.localViewReferences.removeReferences(view.removedKeys, targetId);\n }));\n };\n for (var _i = 0, viewChanges_1 = viewChanges; _i < viewChanges_1.length; _i++) {\n var view = viewChanges_1[_i];\n _loop_1(view);\n }\n return PersistencePromise.waitFor(promises);\n });\n };\n /**\n * Gets the mutation batch after the passed in batchId in the mutation queue\n * or null if empty.\n * @param afterBatchId If provided, the batch to search after.\n * @returns The next mutation or null if there wasn't one.\n */\n LocalStore.prototype.nextMutationBatch = function (afterBatchId) {\n var _this = this;\n return this.persistence.runTransaction('Get next mutation batch', function (txn) {\n if (afterBatchId === undefined) {\n afterBatchId = BATCHID_UNKNOWN;\n }\n return _this.mutationQueue.getNextMutationBatchAfterBatchId(txn, afterBatchId);\n });\n };\n /**\n * Read the current value of a Document with a given key or null if not\n * found - used for testing.\n */\n LocalStore.prototype.readDocument = function (key) {\n var _this = this;\n return this.persistence.runTransaction('read document', function (txn) {\n return _this.localDocuments.getDocument(txn, key);\n });\n };\n /**\n * Assigns the given query an internal ID so that its results can be pinned so\n * they don't get GC'd. A query must be allocated in the local store before\n * the store can be used to manage its view.\n */\n LocalStore.prototype.allocateQuery = function (query) {\n var _this = this;\n return this.persistence.runTransaction('Allocate query', function (txn) {\n var queryData;\n return _this.queryCache\n .getQueryData(txn, query)\n .next(function (cached) {\n if (cached) {\n // This query has been listened to previously, so reuse the\n // previous targetID.\n // TODO(mcg): freshen last accessed date?\n queryData = cached;\n return PersistencePromise.resolve();\n }\n else {\n var targetId = _this.targetIdGenerator.next();\n queryData = new QueryData(query, targetId, QueryPurpose.Listen);\n return _this.queryCache.addQueryData(txn, queryData);\n }\n })\n .next(function () {\n assert(!_this.targetIds[queryData.targetId], 'Tried to allocate an already allocated query: ' + query);\n _this.targetIds[queryData.targetId] = queryData;\n return queryData;\n });\n });\n };\n /** Unpin all the documents associated with the given query. */\n LocalStore.prototype.releaseQuery = function (query) {\n var _this = this;\n return this.persistence.runTransaction('Release query', function (txn) {\n return _this.queryCache\n .getQueryData(txn, query)\n .next(function (queryData) {\n assert(queryData != null, 'Tried to release nonexistent query: ' + query);\n _this.localViewReferences.removeReferencesForId(queryData.targetId);\n delete _this.targetIds[queryData.targetId];\n if (_this.garbageCollector.isEager) {\n return _this.queryCache.removeQueryData(txn, queryData);\n }\n else {\n return PersistencePromise.resolve();\n }\n })\n .next(function () {\n // If this was the last watch target, then we won't get any more\n // watch snapshots, so we should release any held batch results.\n if (objUtils.isEmpty(_this.targetIds)) {\n var documentBuffer_2 = new RemoteDocumentChangeBuffer(_this.remoteDocuments);\n return _this.releaseHeldBatchResults(txn, documentBuffer_2).next(function () {\n documentBuffer_2.apply(txn);\n });\n }\n else {\n return PersistencePromise.resolve();\n }\n });\n });\n };\n /**\n * Runs the specified query against all the documents in the local store and\n * returns the results.\n */\n LocalStore.prototype.executeQuery = function (query) {\n var _this = this;\n return this.persistence.runTransaction('Execute query', function (txn) {\n return _this.localDocuments.getDocumentsMatchingQuery(txn, query);\n });\n };\n /**\n * Returns the keys of the documents that are associated with the given\n * target id in the remote table.\n */\n LocalStore.prototype.remoteDocumentKeys = function (targetId) {\n var _this = this;\n return this.persistence.runTransaction('Remote document keys', function (txn) {\n return _this.queryCache.getMatchingKeysForTargetId(txn, targetId);\n });\n };\n /**\n * Collect garbage if necessary.\n * Should be called periodically by Sync Engine to recover resources. The\n * implementation must guarantee that GC won't happen in other places than\n * this method call.\n */\n LocalStore.prototype.collectGarbage = function () {\n var _this = this;\n // Call collectGarbage regardless of whether isGCEnabled so the referenceSet\n // doesn't continue to accumulate the garbage keys.\n return this.persistence.runTransaction('Garbage collection', function (txn) {\n return _this.garbageCollector.collectGarbage(txn).next(function (garbage) {\n var promises = [];\n garbage.forEach(function (key) {\n promises.push(_this.remoteDocuments.removeEntry(txn, key));\n });\n return PersistencePromise.waitFor(promises);\n });\n });\n };\n LocalStore.prototype.releaseHeldBatchResults = function (txn, documentBuffer) {\n var toRelease = [];\n for (var _i = 0, _a = this.heldBatchResults; _i < _a.length; _i++) {\n var batchResult = _a[_i];\n if (!this.isRemoteUpToVersion(batchResult.commitVersion)) {\n break;\n }\n toRelease.push(batchResult);\n }\n if (toRelease.length === 0) {\n return PersistencePromise.resolve(documentKeySet());\n }\n else {\n this.heldBatchResults.splice(0, toRelease.length);\n return this.releaseBatchResults(txn, toRelease, documentBuffer);\n }\n };\n LocalStore.prototype.isRemoteUpToVersion = function (version) {\n // If there are no watch targets, then we won't get remote snapshots, and\n // we are always \"up-to-date.\"\n var lastRemoteVersion = this.queryCache.getLastRemoteSnapshotVersion();\n return (version.compareTo(lastRemoteVersion) <= 0 ||\n objUtils.isEmpty(this.targetIds));\n };\n LocalStore.prototype.shouldHoldBatchResult = function (version) {\n // Check if watcher isn't up to date or prior results are already held.\n return (!this.isRemoteUpToVersion(version) || this.heldBatchResults.length > 0);\n };\n LocalStore.prototype.releaseBatchResults = function (txn, batchResults, documentBuffer) {\n var _this = this;\n var promiseChain = PersistencePromise.resolve();\n var _loop_2 = function (batchResult) {\n promiseChain = promiseChain.next(function () {\n return _this.applyWriteToRemoteDocuments(txn, batchResult, documentBuffer);\n });\n };\n for (var _i = 0, batchResults_1 = batchResults; _i < batchResults_1.length; _i++) {\n var batchResult = batchResults_1[_i];\n _loop_2(batchResult);\n }\n return promiseChain.next(function () {\n return _this.removeMutationBatches(txn, batchResults.map(function (result) { return result.batch; }));\n });\n };\n LocalStore.prototype.removeMutationBatch = function (txn, batch) {\n return this.removeMutationBatches(txn, [batch]);\n };\n /** Removes all the mutation batches named in the given array. */\n LocalStore.prototype.removeMutationBatches = function (txn, batches) {\n var affectedDocs = documentKeySet();\n for (var _i = 0, batches_2 = batches; _i < batches_2.length; _i++) {\n var batch = batches_2[_i];\n for (var _a = 0, _b = batch.mutations; _a < _b.length; _a++) {\n var mutation = _b[_a];\n var key = mutation.key;\n affectedDocs = affectedDocs.add(key);\n }\n }\n return this.mutationQueue\n .removeMutationBatches(txn, batches)\n .next(function () { return affectedDocs; });\n };\n LocalStore.prototype.applyWriteToRemoteDocuments = function (txn, batchResult, documentBuffer) {\n var batch = batchResult.batch;\n var docKeys = batch.keys();\n var promiseChain = PersistencePromise.resolve();\n docKeys.forEach(function (docKey) {\n promiseChain = promiseChain\n .next(function () {\n return documentBuffer.getEntry(txn, docKey);\n })\n .next(function (remoteDoc) {\n var doc = remoteDoc;\n var ackVersion = batchResult.docVersions.get(docKey);\n assert(ackVersion !== null, 'ackVersions should contain every doc in the write.');\n if (!doc || doc.version.compareTo(ackVersion) < 0) {\n doc = batch.applyToRemoteDocument(docKey, doc, batchResult);\n if (!doc) {\n assert(!remoteDoc, 'Mutation batch ' +\n batch +\n ' applied to document ' +\n remoteDoc +\n ' resulted in null');\n }\n else {\n documentBuffer.addEntry(doc);\n }\n }\n });\n });\n return promiseChain;\n };\n return LocalStore;\n}());\nexport { LocalStore };\n\n//# sourceMappingURL=local_store.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/local_store.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { DocumentKey } from '../model/document_key';\nimport { BATCHID_UNKNOWN, MutationBatch } from '../model/mutation_batch';\nimport { emptyByteString } from '../platform/platform';\nimport { assert } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\nimport { PersistencePromise } from './persistence_promise';\nimport { DocReference } from './reference_set';\nvar MemoryMutationQueue = /** @class */ (function () {\n function MemoryMutationQueue() {\n /**\n * The set of all mutations that have been sent but not yet been applied to\n * the backend.\n */\n this.mutationQueue = [];\n /** Next value to use when assigning sequential IDs to each mutation batch. */\n this.nextBatchId = 1;\n /** The highest acknowledged mutation in the queue. */\n this.highestAcknowledgedBatchId = BATCHID_UNKNOWN;\n /** The last received stream token from the server, used to acknowledge which\n * responses the client has processed. Stream tokens are opaque checkpoint\n * markers whose only real value is their inclusion in the next request.\n */\n this.lastStreamToken = emptyByteString();\n /** The garbage collector to notify about potential garbage keys. */\n this.garbageCollector = null;\n /** An ordered mapping between documents and the mutations batch IDs. */\n this.batchesByDocumentKey = new SortedSet(DocReference.compareByKey);\n }\n MemoryMutationQueue.prototype.start = function (transaction) {\n // NOTE: The queue may be shutdown / started multiple times, since we\n // maintain the queue for the duration of the app session in case a user\n // logs out / back in. To behave like the LevelDB-backed MutationQueue (and\n // accommodate tests that expect as much), we reset nextBatchId and\n // highestAcknowledgedBatchId if the queue is empty.\n if (this.mutationQueue.length === 0) {\n this.nextBatchId = 1;\n this.highestAcknowledgedBatchId = BATCHID_UNKNOWN;\n }\n assert(this.highestAcknowledgedBatchId < this.nextBatchId, 'highestAcknowledgedBatchId must be less than the nextBatchId');\n return PersistencePromise.resolve();\n };\n MemoryMutationQueue.prototype.checkEmpty = function (transaction) {\n return PersistencePromise.resolve(this.mutationQueue.length === 0);\n };\n MemoryMutationQueue.prototype.getNextBatchId = function (transaction) {\n return PersistencePromise.resolve(this.nextBatchId);\n };\n MemoryMutationQueue.prototype.getHighestAcknowledgedBatchId = function (transaction) {\n return PersistencePromise.resolve(this.highestAcknowledgedBatchId);\n };\n MemoryMutationQueue.prototype.acknowledgeBatch = function (transaction, batch, streamToken) {\n var batchId = batch.batchId;\n assert(batchId > this.highestAcknowledgedBatchId, 'Mutation batchIDs must be acknowledged in order');\n var batchIndex = this.indexOfExistingBatchId(batchId, 'acknowledged');\n // Verify that the batch in the queue is the one to be acknowledged.\n var check = this.mutationQueue[batchIndex];\n assert(batchId === check.batchId, 'Queue ordering failure: expected batch ' +\n batchId +\n ', got batch ' +\n check.batchId);\n assert(!check.isTombstone(), \"Can't acknowledge a previously removed batch\");\n this.highestAcknowledgedBatchId = batchId;\n this.lastStreamToken = streamToken;\n return PersistencePromise.resolve();\n };\n MemoryMutationQueue.prototype.getLastStreamToken = function (transaction) {\n return PersistencePromise.resolve(this.lastStreamToken);\n };\n MemoryMutationQueue.prototype.setLastStreamToken = function (transaction, streamToken) {\n this.lastStreamToken = streamToken;\n return PersistencePromise.resolve();\n };\n MemoryMutationQueue.prototype.addMutationBatch = function (transaction, localWriteTime, mutations) {\n assert(mutations.length !== 0, 'Mutation batches should not be empty');\n var batchId = this.nextBatchId;\n this.nextBatchId++;\n if (this.mutationQueue.length > 0) {\n var prior = this.mutationQueue[this.mutationQueue.length - 1];\n assert(prior.batchId < batchId, 'Mutation batchIDs must be monotonically increasing order');\n }\n var batch = new MutationBatch(batchId, localWriteTime, mutations);\n this.mutationQueue.push(batch);\n // Track references by document key.\n for (var _i = 0, mutations_1 = mutations; _i < mutations_1.length; _i++) {\n var mutation = mutations_1[_i];\n this.batchesByDocumentKey = this.batchesByDocumentKey.add(new DocReference(mutation.key, batchId));\n }\n return PersistencePromise.resolve(batch);\n };\n MemoryMutationQueue.prototype.lookupMutationBatch = function (transaction, batchId) {\n return PersistencePromise.resolve(this.findMutationBatch(batchId));\n };\n MemoryMutationQueue.prototype.getNextMutationBatchAfterBatchId = function (transaction, batchId) {\n var size = this.mutationQueue.length;\n // All batches with batchId <= this.highestAcknowledgedBatchId have been\n // acknowledged so the first unacknowledged batch after batchID will have a\n // batchID larger than both of these values.\n batchId = Math.max(batchId + 1, this.highestAcknowledgedBatchId);\n // The requested batchId may still be out of range so normalize it to the\n // start of the queue.\n var rawIndex = this.indexOfBatchId(batchId);\n var index = rawIndex < 0 ? 0 : rawIndex;\n // Finally return the first non-tombstone batch.\n for (; index < size; index++) {\n var batch = this.mutationQueue[index];\n if (!batch.isTombstone()) {\n return PersistencePromise.resolve(batch);\n }\n }\n return PersistencePromise.resolve(null);\n };\n MemoryMutationQueue.prototype.getAllMutationBatches = function (transaction) {\n return PersistencePromise.resolve(this.getAllLiveMutationBatchesBeforeIndex(this.mutationQueue.length));\n };\n MemoryMutationQueue.prototype.getAllMutationBatchesThroughBatchId = function (transaction, batchId) {\n var count = this.mutationQueue.length;\n var endIndex = this.indexOfBatchId(batchId);\n if (endIndex < 0) {\n endIndex = 0;\n }\n else if (endIndex >= count) {\n endIndex = count;\n }\n else {\n // The endIndex is in the queue so increment to pull everything in the\n // queue including it.\n endIndex++;\n }\n return PersistencePromise.resolve(this.getAllLiveMutationBatchesBeforeIndex(endIndex));\n };\n MemoryMutationQueue.prototype.getAllMutationBatchesAffectingDocumentKey = function (transaction, documentKey) {\n var _this = this;\n var start = new DocReference(documentKey, 0);\n var end = new DocReference(documentKey, Number.POSITIVE_INFINITY);\n var result = [];\n this.batchesByDocumentKey.forEachInRange([start, end], function (ref) {\n assert(documentKey.isEqual(ref.key), \"Should only iterate over a single key's batches\");\n var batch = _this.findMutationBatch(ref.targetOrBatchId);\n assert(batch !== null, 'Batches in the index must exist in the main table');\n result.push(batch);\n });\n return PersistencePromise.resolve(result);\n };\n MemoryMutationQueue.prototype.getAllMutationBatchesAffectingQuery = function (transaction, query) {\n var _this = this;\n // Use the query path as a prefix for testing if a document matches the\n // query.\n var prefix = query.path;\n var immediateChildrenPathLength = prefix.length + 1;\n // Construct a document reference for actually scanning the index. Unlike\n // the prefix the document key in this reference must have an even number of\n // segments. The empty segment can be used a suffix of the query path\n // because it precedes all other segments in an ordered traversal.\n var startPath = prefix;\n if (!DocumentKey.isDocumentKey(startPath)) {\n startPath = startPath.child('');\n }\n var start = new DocReference(new DocumentKey(startPath), 0);\n // Find unique batchIDs referenced by all documents potentially matching the\n // query.\n var uniqueBatchIDs = new SortedSet(primitiveComparator);\n this.batchesByDocumentKey.forEachWhile(function (ref) {\n var rowKeyPath = ref.key.path;\n if (!prefix.isPrefixOf(rowKeyPath)) {\n return false;\n }\n else {\n // Rows with document keys more than one segment longer than the query\n // path can't be matches. For example, a query on 'rooms' can't match\n // the document /rooms/abc/messages/xyx.\n // TODO(mcg): we'll need a different scanner when we implement\n // ancestor queries.\n if (rowKeyPath.length === immediateChildrenPathLength) {\n uniqueBatchIDs = uniqueBatchIDs.add(ref.targetOrBatchId);\n }\n return true;\n }\n }, start);\n // Construct an array of matching batches, sorted by batchID to ensure that\n // multiple mutations affecting the same document key are applied in order.\n var result = [];\n uniqueBatchIDs.forEach(function (batchId) {\n var batch = _this.findMutationBatch(batchId);\n if (batch !== null) {\n result.push(batch);\n }\n });\n return PersistencePromise.resolve(result);\n };\n MemoryMutationQueue.prototype.removeMutationBatches = function (transaction, batches) {\n var batchCount = batches.length;\n assert(batchCount > 0, 'Should not remove mutations when none exist.');\n var firstBatchId = batches[0].batchId;\n var queueCount = this.mutationQueue.length;\n // Find the position of the first batch for removal. This need not be the\n // first entry in the queue.\n var startIndex = this.indexOfExistingBatchId(firstBatchId, 'removed');\n assert(this.mutationQueue[startIndex].batchId === firstBatchId, 'Removed batches must exist in the queue');\n // Check that removed batches are contiguous (while excluding tombstones).\n var batchIndex = 1;\n var queueIndex = startIndex + 1;\n while (batchIndex < batchCount && queueIndex < queueCount) {\n var batch = this.mutationQueue[queueIndex];\n if (batch.isTombstone()) {\n queueIndex++;\n continue;\n }\n assert(batch.batchId === batches[batchIndex].batchId, 'Removed batches must be contiguous in the queue');\n batchIndex++;\n queueIndex++;\n }\n // Only actually remove batches if removing at the front of the queue.\n // Previously rejected batches may have left tombstones in the queue, so\n // expand the removal range to include any tombstones.\n if (startIndex === 0) {\n for (; queueIndex < queueCount; queueIndex++) {\n var batch = this.mutationQueue[queueIndex];\n if (!batch.isTombstone()) {\n break;\n }\n }\n var length_1 = queueIndex - startIndex;\n this.mutationQueue.splice(startIndex, length_1);\n }\n else {\n // Mark the tombstones\n for (var i = startIndex; i < queueIndex; i++) {\n this.mutationQueue[i] = this.mutationQueue[i].toTombstone();\n }\n }\n var references = this.batchesByDocumentKey;\n for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {\n var batch = batches_1[_i];\n var batchId = batch.batchId;\n for (var _a = 0, _b = batch.mutations; _a < _b.length; _a++) {\n var mutation = _b[_a];\n var key = mutation.key;\n if (this.garbageCollector !== null) {\n this.garbageCollector.addPotentialGarbageKey(key);\n }\n var ref = new DocReference(key, batchId);\n references = references.delete(ref);\n }\n }\n this.batchesByDocumentKey = references;\n return PersistencePromise.resolve();\n };\n MemoryMutationQueue.prototype.setGarbageCollector = function (garbageCollector) {\n this.garbageCollector = garbageCollector;\n };\n MemoryMutationQueue.prototype.containsKey = function (txn, key) {\n var ref = new DocReference(key, 0);\n var firstRef = this.batchesByDocumentKey.firstAfterOrEqual(ref);\n return PersistencePromise.resolve(key.isEqual(firstRef && firstRef.key));\n };\n MemoryMutationQueue.prototype.performConsistencyCheck = function (txn) {\n if (this.mutationQueue.length === 0) {\n assert(this.batchesByDocumentKey.isEmpty(), 'Document leak -- detected dangling mutation references when queue is empty.');\n }\n return PersistencePromise.resolve();\n };\n /**\n * A private helper that collects all the mutations batches in the queue up to\n * but not including the given endIndex. All tombstones in the queue are\n * excluded.\n */\n MemoryMutationQueue.prototype.getAllLiveMutationBatchesBeforeIndex = function (endIndex) {\n var result = [];\n for (var i = 0; i < endIndex; i++) {\n var batch = this.mutationQueue[i];\n if (!batch.isTombstone()) {\n result.push(batch);\n }\n }\n return result;\n };\n /**\n * Finds the index of the given batchId in the mutation queue and asserts that\n * the resulting index is within the bounds of the queue.\n *\n * @param batchId The batchId to search for\n * @param action A description of what the caller is doing, phrased in passive\n * form (e.g. \"acknowledged\" in a routine that acknowledges batches).\n */\n MemoryMutationQueue.prototype.indexOfExistingBatchId = function (batchId, action) {\n var index = this.indexOfBatchId(batchId);\n assert(index >= 0 && index < this.mutationQueue.length, 'Batches must exist to be ' + action);\n return index;\n };\n /**\n * Finds the index of the given batchId in the mutation queue. This operation\n * is O(1).\n *\n * @return The computed index of the batch with the given batchId, based on\n * the state of the queue. Note this index can be negative if the requested\n * batchId has already been remvoed from the queue or past the end of the\n * queue if the batchId is larger than the last added batch.\n */\n MemoryMutationQueue.prototype.indexOfBatchId = function (batchId) {\n if (this.mutationQueue.length === 0) {\n // As an index this is past the end of the queue\n return 0;\n }\n // Examine the front of the queue to figure out the difference between the\n // batchId and indexes in the array. Note that since the queue is ordered\n // by batchId, if the first batch has a larger batchId then the requested\n // batchId doesn't exist in the queue.\n var firstBatchId = this.mutationQueue[0].batchId;\n return batchId - firstBatchId;\n };\n /**\n * A version of lookupMutationBatch that doesn't return a promise, this makes\n * other functions that uses this code easier to read and more efficent.\n */\n MemoryMutationQueue.prototype.findMutationBatch = function (batchId) {\n var index = this.indexOfBatchId(batchId);\n if (index < 0 || index >= this.mutationQueue.length) {\n return null;\n }\n var batch = this.mutationQueue[index];\n assert(batch.batchId === batchId, 'If found batch must match');\n return batch.isTombstone() ? null : batch;\n };\n return MemoryMutationQueue;\n}());\nexport { MemoryMutationQueue };\n\n//# sourceMappingURL=memory_mutation_queue.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/memory_mutation_queue.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { ObjectMap } from '../util/obj_map';\nimport { PersistencePromise } from './persistence_promise';\nimport { ReferenceSet } from './reference_set';\nvar MemoryQueryCache = /** @class */ (function () {\n function MemoryQueryCache() {\n /**\n * Maps a query to the data about that query\n */\n this.queries = new ObjectMap(function (q) { return q.canonicalId(); });\n /** The last received snapshot version. */\n this.lastRemoteSnapshotVersion = SnapshotVersion.MIN;\n /** The highest numbered target ID encountered. */\n this.highestTargetId = 0;\n /**\n * A ordered bidirectional mapping between documents and the remote target\n * IDs.\n */\n this.references = new ReferenceSet();\n }\n MemoryQueryCache.prototype.start = function (transaction) {\n // Nothing to do.\n return PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.getLastRemoteSnapshotVersion = function () {\n return this.lastRemoteSnapshotVersion;\n };\n MemoryQueryCache.prototype.getHighestTargetId = function () {\n return this.highestTargetId;\n };\n MemoryQueryCache.prototype.setLastRemoteSnapshotVersion = function (transaction, snapshotVersion) {\n this.lastRemoteSnapshotVersion = snapshotVersion;\n return PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.addQueryData = function (transaction, queryData) {\n this.queries.set(queryData.query, queryData);\n var targetId = queryData.targetId;\n if (targetId > this.highestTargetId) {\n this.highestTargetId = targetId;\n }\n return PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.removeQueryData = function (transaction, queryData) {\n this.queries.delete(queryData.query);\n this.references.removeReferencesForId(queryData.targetId);\n return PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.getQueryData = function (transaction, query) {\n var queryData = this.queries.get(query) || null;\n return PersistencePromise.resolve(queryData);\n };\n MemoryQueryCache.prototype.addMatchingKeys = function (txn, keys, targetId) {\n this.references.addReferences(keys, targetId);\n return PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.removeMatchingKeys = function (txn, keys, targetId) {\n this.references.removeReferences(keys, targetId);\n return PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.removeMatchingKeysForTargetId = function (txn, targetId) {\n this.references.removeReferencesForId(targetId);\n return PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.getMatchingKeysForTargetId = function (txn, targetId) {\n var matchingKeys = this.references.referencesForId(targetId);\n return PersistencePromise.resolve(matchingKeys);\n };\n MemoryQueryCache.prototype.setGarbageCollector = function (gc) {\n this.references.setGarbageCollector(gc);\n };\n MemoryQueryCache.prototype.containsKey = function (txn, key) {\n return this.references.containsKey(txn, key);\n };\n return MemoryQueryCache;\n}());\nexport { MemoryQueryCache };\n\n//# sourceMappingURL=memory_query_cache.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/memory_query_cache.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { documentMap, maybeDocumentMap } from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { PersistencePromise } from './persistence_promise';\nvar MemoryRemoteDocumentCache = /** @class */ (function () {\n function MemoryRemoteDocumentCache() {\n this.docs = maybeDocumentMap();\n }\n MemoryRemoteDocumentCache.prototype.addEntry = function (transaction, maybeDocument) {\n this.docs = this.docs.insert(maybeDocument.key, maybeDocument);\n return PersistencePromise.resolve();\n };\n MemoryRemoteDocumentCache.prototype.removeEntry = function (transaction, documentKey) {\n this.docs = this.docs.remove(documentKey);\n return PersistencePromise.resolve();\n };\n MemoryRemoteDocumentCache.prototype.getEntry = function (transaction, documentKey) {\n return PersistencePromise.resolve(this.docs.get(documentKey));\n };\n MemoryRemoteDocumentCache.prototype.getDocumentsMatchingQuery = function (transaction, query) {\n var results = documentMap();\n // Documents are ordered by key, so we can use a prefix scan to narrow down\n // the documents we need to match the query against.\n var prefix = new DocumentKey(query.path.child(''));\n var iterator = this.docs.getIteratorFrom(prefix);\n while (iterator.hasNext()) {\n var _a = iterator.getNext(), key = _a.key, maybeDoc = _a.value;\n if (!query.path.isPrefixOf(key.path)) {\n break;\n }\n if (maybeDoc instanceof Document && query.matches(maybeDoc)) {\n results = results.insert(maybeDoc.key, maybeDoc);\n }\n }\n return PersistencePromise.resolve(results);\n };\n return MemoryRemoteDocumentCache;\n}());\nexport { MemoryRemoteDocumentCache };\n\n//# sourceMappingURL=memory_remote_document_cache.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/memory_remote_document_cache.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { assert } from '../util/assert';\nimport { debug } from '../util/log';\nimport { MemoryMutationQueue } from './memory_mutation_queue';\nimport { MemoryQueryCache } from './memory_query_cache';\nimport { MemoryRemoteDocumentCache } from './memory_remote_document_cache';\nvar LOG_TAG = 'MemoryPersistence';\n/**\n * A memory-backed instance of Persistence. Data is stored only in RAM and\n * not persisted across sessions.\n */\nvar MemoryPersistence = /** @class */ (function () {\n function MemoryPersistence() {\n /**\n * Note that these are retained here to make it easier to write tests\n * affecting both the in-memory and IndexedDB-backed persistence layers. Tests\n * can create a new LocalStore wrapping this Persistence instance and this\n * will make the in-memory persistence layer behave as if it were actually\n * persisting values.\n */\n this.mutationQueues = {};\n this.remoteDocumentCache = new MemoryRemoteDocumentCache();\n this.queryCache = new MemoryQueryCache();\n this.started = false;\n }\n MemoryPersistence.prototype.start = function () {\n assert(!this.started, 'MemoryPersistence double-started!');\n this.started = true;\n // No durable state to read on startup.\n return Promise.resolve();\n };\n MemoryPersistence.prototype.shutdown = function () {\n // No durable state to ensure is closed on shutdown.\n assert(this.started, 'MemoryPersistence shutdown without start!');\n this.started = false;\n return Promise.resolve();\n };\n MemoryPersistence.prototype.getMutationQueue = function (user) {\n var queue = this.mutationQueues[user.toKey()];\n if (!queue) {\n queue = new MemoryMutationQueue();\n this.mutationQueues[user.toKey()] = queue;\n }\n return queue;\n };\n MemoryPersistence.prototype.getQueryCache = function () {\n return this.queryCache;\n };\n MemoryPersistence.prototype.getRemoteDocumentCache = function () {\n return this.remoteDocumentCache;\n };\n MemoryPersistence.prototype.runTransaction = function (action, operation) {\n debug(LOG_TAG, 'Starting transaction:', action);\n return operation(new MemoryPersistenceTransaction()).toPromise();\n };\n return MemoryPersistence;\n}());\nexport { MemoryPersistence };\n/** Dummy class since memory persistence doesn't actually use transactions. */\nvar MemoryPersistenceTransaction = /** @class */ (function () {\n function MemoryPersistenceTransaction() {\n }\n return MemoryPersistenceTransaction;\n}());\n\n//# sourceMappingURL=memory_persistence.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/memory_persistence.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { documentKeySet } from '../model/collections';\nimport { PersistencePromise } from './persistence_promise';\n/**\n * A garbage collector implementation that does absolutely nothing. It ignores\n * all addGarbageSource and addPotentialGarbageKey messages and and never\n * produces any garbage.\n */\nvar NoOpGarbageCollector = /** @class */ (function () {\n function NoOpGarbageCollector() {\n this.isEager = false;\n }\n NoOpGarbageCollector.prototype.addGarbageSource = function (garbageSource) {\n // Not tracking garbage so don't track sources.\n };\n NoOpGarbageCollector.prototype.removeGarbageSource = function (garbageSource) {\n // Not tracking garbage so don't track sources.\n };\n NoOpGarbageCollector.prototype.addPotentialGarbageKey = function (key) {\n // Not tracking garbage so ignore.\n };\n NoOpGarbageCollector.prototype.collectGarbage = function (txn) {\n return PersistencePromise.resolve(documentKeySet());\n };\n return NoOpGarbageCollector;\n}());\nexport { NoOpGarbageCollector };\n\n//# sourceMappingURL=no_op_garbage_collector.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/no_op_garbage_collector.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar Deferred = /** @class */ (function () {\n function Deferred() {\n var _this = this;\n this.promise = new Promise(function (resolve, reject) {\n _this.resolve = resolve;\n _this.reject = reject;\n });\n }\n return Deferred;\n}());\nexport { Deferred };\n/**\n * Takes an array of values and sequences them using the promise (or value)\n * returned by the supplied callback. The callback for each item is called\n * after the promise is resolved for the previous item.\n * The function returns a promise which is resolved after the promise for\n * the last item is resolved.\n */\nexport function sequence(values, fn, initialValue) {\n var result = Promise.resolve(initialValue);\n values.forEach(function (value) {\n result = result.then(function (lastResult) { return fn(value, lastResult); });\n });\n return result;\n}\n\n//# sourceMappingURL=promise.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/promise.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport * as log from '../util/log';\nimport { Deferred } from '../util/promise';\nvar LOG_TAG = 'ExponentialBackoff';\n/**\n * A helper for running delayed tasks following an exponential backoff curve\n * between attempts.\n *\n * Each delay is made up of a \"base\" delay which follows the exponential\n * backoff curve, and a +/- 50% \"jitter\" that is calculated and added to the\n * base delay. This prevents clients from accidentally synchronizing their\n * delays causing spikes of load to the backend.\n */\nvar ExponentialBackoff = /** @class */ (function () {\n function ExponentialBackoff(\n /**\n * The initial delay (used as the base delay on the first retry attempt).\n * Note that jitter will still be applied, so the actual delay could be as\n * little as 0.5*initialDelayMs.\n */\n initialDelayMs, \n /**\n * The multiplier to use to determine the extended base delay after each\n * attempt.\n */\n backoffFactor, \n /**\n * The maximum base delay after which no further backoff is performed.\n * Note that jitter will still be applied, so the actual delay could be as\n * much as 1.5*maxDelayMs.\n */\n maxDelayMs) {\n this.initialDelayMs = initialDelayMs;\n this.backoffFactor = backoffFactor;\n this.maxDelayMs = maxDelayMs;\n this.reset();\n }\n /**\n * Resets the backoff delay.\n *\n * The very next backoffAndWait() will have no delay. If it is called again\n * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and\n * subsequent ones will increase according to the backoffFactor.\n */\n ExponentialBackoff.prototype.reset = function () {\n this.currentBaseMs = 0;\n };\n /**\n * Resets the backoff delay to the maximum delay (e.g. for use after a\n * RESOURCE_EXHAUSTED error).\n */\n ExponentialBackoff.prototype.resetToMax = function () {\n this.currentBaseMs = this.maxDelayMs;\n };\n /**\n * Returns a promise that resolves after currentDelayMs, and increases the\n * delay for any subsequent attempts.\n */\n ExponentialBackoff.prototype.backoffAndWait = function () {\n var def = new Deferred();\n // First schedule using the current base (which may be 0 and should be\n // honored as such).\n var delayWithJitterMs = this.currentBaseMs + this.jitterDelayMs();\n if (this.currentBaseMs > 0) {\n log.debug(LOG_TAG, \"Backing off for \" + delayWithJitterMs + \" ms \" +\n (\"(base delay: \" + this.currentBaseMs + \" ms)\"));\n }\n setTimeout(function () {\n def.resolve();\n }, delayWithJitterMs);\n // Apply backoff factor to determine next delay and ensure it is within\n // bounds.\n this.currentBaseMs *= this.backoffFactor;\n if (this.currentBaseMs < this.initialDelayMs) {\n this.currentBaseMs = this.initialDelayMs;\n }\n if (this.currentBaseMs > this.maxDelayMs) {\n this.currentBaseMs = this.maxDelayMs;\n }\n return def.promise;\n };\n /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */\n ExponentialBackoff.prototype.jitterDelayMs = function () {\n return (Math.random() - 0.5) * this.currentBaseMs;\n };\n return ExponentialBackoff;\n}());\nexport { ExponentialBackoff };\n\n//# sourceMappingURL=backoff.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/remote/backoff.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { maybeDocumentMap } from '../model/collections';\nimport { assert } from '../util/assert';\nimport { PersistentListenStream, PersistentWriteStream } from './persistent_stream';\n/**\n * Datastore is a wrapper around the external Google Cloud Datastore grpc API,\n * which provides an interface that is more convenient for the rest of the\n * client SDK architecture to consume.\n */\nvar Datastore = /** @class */ (function () {\n function Datastore(databaseInfo, queue, connection, credentials, serializer, initialBackoffDelay) {\n this.databaseInfo = databaseInfo;\n this.queue = queue;\n this.connection = connection;\n this.credentials = credentials;\n this.serializer = serializer;\n this.initialBackoffDelay = initialBackoffDelay;\n }\n Datastore.prototype.newPersistentWriteStream = function () {\n return new PersistentWriteStream(this.databaseInfo, this.queue, this.connection, this.credentials, this.serializer, this.initialBackoffDelay);\n };\n Datastore.prototype.newPersistentWatchStream = function () {\n return new PersistentListenStream(this.databaseInfo, this.queue, this.connection, this.credentials, this.serializer, this.initialBackoffDelay);\n };\n Datastore.prototype.commit = function (mutations) {\n var _this = this;\n var params = {\n database: this.serializer.encodedDatabaseId,\n writes: mutations.map(function (m) { return _this.serializer.toMutation(m); })\n };\n return this.invokeRPC('Commit', params).then(function (response) {\n return _this.serializer.fromWriteResults(response.writeResults);\n });\n };\n Datastore.prototype.lookup = function (keys) {\n var _this = this;\n var params = {\n database: this.serializer.encodedDatabaseId,\n documents: keys.map(function (k) { return _this.serializer.toName(k); })\n };\n return this.invokeStreamingRPC('BatchGetDocuments', params).then(function (response) {\n var docs = maybeDocumentMap();\n response.forEach(function (proto) {\n var doc = _this.serializer.fromMaybeDocument(proto);\n docs = docs.insert(doc.key, doc);\n });\n var result = [];\n keys.forEach(function (key) {\n var doc = docs.get(key);\n assert(!!doc, 'Missing entity in write response for ' + key);\n result.push(doc);\n });\n return result;\n });\n };\n /** Gets an auth token and invokes the provided RPC. */\n Datastore.prototype.invokeRPC = function (rpcName, request) {\n var _this = this;\n // TODO(mikelehen): Retry (with backoff) on token failures?\n return this.credentials.getToken(/*forceRefresh=*/ false).then(function (token) {\n return _this.connection.invokeRPC(rpcName, request, token);\n });\n };\n /** Gets an auth token and invokes the provided RPC with streamed results. */\n Datastore.prototype.invokeStreamingRPC = function (rpcName, request) {\n var _this = this;\n // TODO(mikelehen): Retry (with backoff) on token failures?\n return this.credentials.getToken(/*forceRefresh=*/ false).then(function (token) {\n return _this.connection.invokeStreamingRPC(rpcName, request, token);\n });\n };\n return Datastore;\n}());\nexport { Datastore };\n\n//# sourceMappingURL=datastore.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/remote/datastore.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { SnapshotVersion } from './snapshot_version';\nimport { documentVersionMap } from '../model/collections';\nimport { NoDocument } from '../model/document';\nimport { DeleteMutation, Precondition } from '../model/mutation';\nimport { Code, FirestoreError } from '../util/error';\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */\nvar Transaction = /** @class */ (function () {\n function Transaction(datastore) {\n this.datastore = datastore;\n // The version of each document that was read during this transaction.\n this.readVersions = documentVersionMap();\n this.mutations = [];\n this.committed = false;\n }\n Transaction.prototype.recordVersion = function (doc) {\n var docVersion = doc.version;\n if (doc instanceof NoDocument) {\n // For deleted docs, we must use baseVersion 0 when we overwrite them.\n docVersion = SnapshotVersion.forDeletedDoc();\n }\n var existingVersion = this.readVersions.get(doc.key);\n if (existingVersion !== null) {\n if (!docVersion.isEqual(existingVersion)) {\n // This transaction will fail no matter what.\n throw new FirestoreError(Code.ABORTED, 'Document version changed between two reads.');\n }\n }\n else {\n this.readVersions = this.readVersions.insert(doc.key, docVersion);\n }\n };\n Transaction.prototype.lookup = function (keys) {\n var _this = this;\n if (this.committed) {\n return Promise.reject('Transaction has already completed.');\n }\n if (this.mutations.length > 0) {\n return Promise.reject('Transactions lookups are invalid after writes.');\n }\n return this.datastore.lookup(keys).then(function (docs) {\n docs.forEach(function (doc) { return _this.recordVersion(doc); });\n return docs;\n });\n };\n Transaction.prototype.write = function (mutations) {\n if (this.committed) {\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'Transaction has already completed.');\n }\n this.mutations = this.mutations.concat(mutations);\n };\n /**\n * Returns the version of this document when it was read in this transaction,\n * as a precondition, or no precondition if it was not read.\n */\n Transaction.prototype.precondition = function (key) {\n var version = this.readVersions.get(key);\n if (version) {\n return Precondition.updateTime(version);\n }\n else {\n return Precondition.NONE;\n }\n };\n /**\n * Returns the precondition for a document if the operation is an update.\n */\n Transaction.prototype.preconditionForUpdate = function (key) {\n var version = this.readVersions.get(key);\n if (version && version.isEqual(SnapshotVersion.forDeletedDoc())) {\n // The document doesn't exist, so fail the transaction.\n throw new FirestoreError(Code.FAILED_PRECONDITION, \"Can't update a document that doesn't exist.\");\n }\n else if (version) {\n // Document exists, base precondition on document update time.\n return Precondition.updateTime(version);\n }\n else {\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return Precondition.exists(true);\n }\n };\n Transaction.prototype.set = function (key, data) {\n this.write(data.toMutations(key, this.precondition(key)));\n };\n Transaction.prototype.update = function (key, data) {\n this.write(data.toMutations(key, this.preconditionForUpdate(key)));\n };\n Transaction.prototype.delete = function (key) {\n this.write([new DeleteMutation(key, this.precondition(key))]);\n // Since the delete will be applied before all following writes, we need to\n // ensure that the precondition for the next write will be exists: false.\n this.readVersions = this.readVersions.insert(key, SnapshotVersion.forDeletedDoc());\n };\n Transaction.prototype.commit = function () {\n var _this = this;\n var unwritten = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach(function (mutation) {\n unwritten = unwritten.remove(mutation.key);\n });\n if (!unwritten.isEmpty()) {\n return Promise.reject(Error('Every document read in a transaction must also be written.'));\n }\n return this.datastore.commit(this.mutations).then(function () {\n _this.committed = true;\n });\n };\n return Transaction;\n}());\nexport { Transaction };\n\n//# sourceMappingURL=transaction.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/transaction.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Transaction } from '../core/transaction';\nimport { OnlineState } from '../core/types';\nimport { QueryData, QueryPurpose } from '../local/query_data';\nimport { NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { BATCHID_UNKNOWN, MutationBatchResult } from '../model/mutation_batch';\nimport { emptyByteString } from '../platform/platform';\nimport { assert } from '../util/assert';\nimport { Code } from '../util/error';\nimport * as log from '../util/log';\nimport * as objUtils from '../util/obj';\nimport { ResetMapping, UpdateMapping } from './remote_event';\nimport { isPermanentError } from './rpc_error';\nimport { WatchChangeAggregator, WatchTargetChange, WatchTargetChangeState } from './watch_change';\nvar LOG_TAG = 'RemoteStore';\n// TODO(b/35853402): Negotiate this with the stream.\nvar MAX_PENDING_WRITES = 10;\n// The RemoteStore notifies an onlineStateHandler with OnlineState.Failed if we\n// fail to connect to the backend. This subsequently triggers get() requests to\n// fail or use cached data, etc. Unfortunately, our connections have\n// historically been subject to various transient failures. So we wait for\n// multiple failures before notifying the onlineStateHandler.\nvar ONLINE_ATTEMPTS_BEFORE_FAILURE = 2;\n/**\n * RemoteStore - An interface to remotely stored data, basically providing a\n * wrapper around the Datastore that is more reliable for the rest of the\n * system.\n *\n * RemoteStore is responsible for maintaining the connection to the server.\n * - maintaining a list of active listens.\n * - reconnecting when the connection is dropped.\n * - resuming all the active listens on reconnect.\n *\n * RemoteStore handles all incoming events from the Datastore.\n * - listening to the watch stream and repackaging the events as RemoteEvents\n * - notifying SyncEngine of any changes to the active listens.\n *\n * RemoteStore takes writes from other components and handles them reliably.\n * - pulling pending mutations from LocalStore and sending them to Datastore.\n * - retrying mutations that failed because of network problems.\n * - acking mutations to the SyncEngine once they are accepted or rejected.\n */\nvar RemoteStore = /** @class */ (function () {\n function RemoteStore(\n /**\n * The local store, used to fill the write pipeline with outbound\n * mutations and resolve existence filter mismatches.\n */\n localStore, \n /** The client-side proxy for interacting with the backend. */\n datastore, onlineStateHandler) {\n this.localStore = localStore;\n this.datastore = datastore;\n this.onlineStateHandler = onlineStateHandler;\n this.pendingWrites = [];\n this.lastBatchSeen = BATCHID_UNKNOWN;\n /**\n * A mapping of watched targets that the client cares about tracking and the\n * user has explicitly called a 'listen' for this target.\n *\n * These targets may or may not have been sent to or acknowledged by the\n * server. On re-establishing the listen stream, these targets should be sent\n * to the server. The targets removed with unlistens are removed eagerly\n * without waiting for confirmation from the listen stream.\n */\n this.listenTargets = {};\n /**\n * A mapping of targetId to pending acks needed.\n *\n * If a targetId is present in this map, then we're waiting for watch to\n * acknowledge a removal or addition of the target. If a target is not in this\n * mapping, and it's in the listenTargets map, then we consider the target to\n * be active.\n *\n * We increment the count here every time we issue a request over the stream\n * to watch or unwatch. We then decrement the count every time we get a target\n * added or target removed message from the server. Once the count is equal to\n * 0 we know that the client and server are in the same state (once this state\n * is reached the targetId is removed from the map to free the memory).\n */\n this.pendingTargetResponses = {};\n this.accumulatedWatchChanges = [];\n this.watchStream = null;\n this.writeStream = null;\n /**\n * The online state of the watch stream. The state is set to healthy if and\n * only if there are messages received by the backend.\n */\n this.watchStreamOnlineState = OnlineState.Unknown;\n /** A count of consecutive failures to open the stream. */\n this.watchStreamFailures = 0;\n /** Whether the client should fire offline warning. */\n this.shouldWarnOffline = true;\n }\n /**\n * Starts up the remote store, creating streams, restoring state from\n * LocalStore, etc.\n */\n RemoteStore.prototype.start = function () {\n return this.enableNetwork();\n };\n /**\n * Updates our OnlineState to the new state, updating local state\n * and notifying the onlineStateHandler as appropriate. Idempotent.\n */\n RemoteStore.prototype.updateOnlineState = function (newState) {\n if (newState !== this.watchStreamOnlineState) {\n if (newState === OnlineState.Healthy) {\n // We've connected to watch at least once. Don't warn the developer about\n // being offline going forward.\n this.shouldWarnOffline = false;\n }\n else if (newState === OnlineState.Unknown) {\n // The state is set to unknown when a healthy stream is closed (e.g. due to\n // a token timeout) or when we have no active listens and therefore there's\n // no need to start the stream. Assuming there is (possibly in the future)\n // an active listen, then we will eventually move to state Online or Failed,\n // but we always want to make at least ONLINE_ATTEMPTS_BEFORE_FAILURE\n // attempts before failing, so we reset the count here.\n this.watchStreamFailures = 0;\n }\n this.watchStreamOnlineState = newState;\n this.onlineStateHandler(newState);\n }\n };\n /**\n * Updates our OnlineState as appropriate after the watch stream reports a\n * failure. The first failure moves us to the 'Unknown' state. We then may\n * allow multiple failures (based on ONLINE_ATTEMPTS_BEFORE_FAILURE) before we\n * actually transition to OnlineState.Failed.\n */\n RemoteStore.prototype.updateOnlineStateAfterFailure = function () {\n if (this.watchStreamOnlineState === OnlineState.Healthy) {\n this.updateOnlineState(OnlineState.Unknown);\n }\n else {\n this.watchStreamFailures++;\n if (this.watchStreamFailures >= ONLINE_ATTEMPTS_BEFORE_FAILURE) {\n if (this.shouldWarnOffline) {\n log.error('Could not reach Firestore backend.');\n this.shouldWarnOffline = false;\n }\n this.updateOnlineState(OnlineState.Failed);\n }\n }\n };\n RemoteStore.prototype.isNetworkEnabled = function () {\n assert((this.watchStream == null) === (this.writeStream == null), 'WatchStream and WriteStream should both be null or non-null');\n return this.watchStream != null;\n };\n /** Re-enables the network. Idempotent. */\n RemoteStore.prototype.enableNetwork = function () {\n var _this = this;\n if (this.isNetworkEnabled()) {\n return Promise.resolve();\n }\n // Create new streams (but note they're not started yet).\n this.watchStream = this.datastore.newPersistentWatchStream();\n this.writeStream = this.datastore.newPersistentWriteStream();\n // Load any saved stream token from persistent storage\n return this.localStore.getLastStreamToken().then(function (token) {\n _this.writeStream.lastStreamToken = token;\n if (_this.shouldStartWatchStream()) {\n _this.startWatchStream();\n }\n _this.updateOnlineState(OnlineState.Unknown);\n return _this.fillWritePipeline(); // This may start the writeStream.\n });\n };\n /**\n * Temporarily disables the network. The network can be re-enabled using\n * enableNetwork().\n */\n RemoteStore.prototype.disableNetwork = function () {\n this.disableNetworkInternal();\n // Set the OnlineState to failed so get()'s return from cache, etc.\n this.updateOnlineState(OnlineState.Failed);\n return Promise.resolve();\n };\n /**\n * Disables the network, if it is currently enabled.\n */\n RemoteStore.prototype.disableNetworkInternal = function () {\n if (this.isNetworkEnabled()) {\n // NOTE: We're guaranteed not to get any further events from these streams (not even a close\n // event).\n this.watchStream.stop();\n this.writeStream.stop();\n this.cleanUpWatchStreamState();\n this.cleanUpWriteStreamState();\n this.writeStream = null;\n this.watchStream = null;\n }\n };\n RemoteStore.prototype.shutdown = function () {\n log.debug(LOG_TAG, 'RemoteStore shutting down.');\n this.disableNetworkInternal();\n // Set the OnlineState to Unknown (rather than Failed) to avoid potentially\n // triggering spurious listener events with cached data, etc.\n this.updateOnlineState(OnlineState.Unknown);\n return Promise.resolve();\n };\n /** Starts new listen for the given query. Uses resume token if provided */\n RemoteStore.prototype.listen = function (queryData) {\n assert(!objUtils.contains(this.listenTargets, queryData.targetId), 'listen called with duplicate targetId!');\n // Mark this as something the client is currently listening for.\n this.listenTargets[queryData.targetId] = queryData;\n if (this.shouldStartWatchStream()) {\n // The listen will be sent in onWatchStreamOpen\n this.startWatchStream();\n }\n else if (this.isNetworkEnabled() && this.watchStream.isOpen()) {\n this.sendWatchRequest(queryData);\n }\n };\n /** Removes the listen from server */\n RemoteStore.prototype.unlisten = function (targetId) {\n assert(objUtils.contains(this.listenTargets, targetId), 'unlisten called without assigned target ID!');\n var queryData = this.listenTargets[targetId];\n delete this.listenTargets[targetId];\n if (this.isNetworkEnabled() && this.watchStream.isOpen()) {\n this.sendUnwatchRequest(targetId);\n if (objUtils.isEmpty(this.listenTargets)) {\n this.watchStream.markIdle();\n }\n }\n };\n /**\n * We need to increment the the expected number of pending responses we're due\n * from watch so we wait for the ack to process any messages from this target.\n */\n RemoteStore.prototype.sendWatchRequest = function (queryData) {\n this.recordPendingTargetRequest(queryData.targetId);\n this.watchStream.watch(queryData);\n };\n /**\n * We need to increment the expected number of pending responses we're due\n * from watch so we wait for the removal on the server before we process any\n * messages from this target.\n */\n RemoteStore.prototype.sendUnwatchRequest = function (targetId) {\n this.recordPendingTargetRequest(targetId);\n this.watchStream.unwatch(targetId);\n };\n /**\n * Increment the mapping of how many acks are needed from watch before we can\n * consider the server to be 'in-sync' with the client's active targets.\n */\n RemoteStore.prototype.recordPendingTargetRequest = function (targetId) {\n // For each request we get we need to record we need a response for it.\n this.pendingTargetResponses[targetId] =\n (this.pendingTargetResponses[targetId] || 0) + 1;\n };\n RemoteStore.prototype.startWatchStream = function () {\n assert(this.shouldStartWatchStream(), 'startWriteStream() called when shouldStartWatchStream() is false.');\n this.watchStream.start({\n onOpen: this.onWatchStreamOpen.bind(this),\n onClose: this.onWatchStreamClose.bind(this),\n onWatchChange: this.onWatchStreamChange.bind(this)\n });\n };\n /**\n * Returns whether the watch stream should be started because there are\n * active targets trying to be listened too\n */\n RemoteStore.prototype.shouldStartWatchStream = function () {\n return (this.isNetworkEnabled() &&\n !this.watchStream.isStarted() &&\n !objUtils.isEmpty(this.listenTargets));\n };\n RemoteStore.prototype.cleanUpWatchStreamState = function () {\n // If the connection is closed then we'll never get a snapshot version for\n // the accumulated changes and so we'll never be able to complete the batch.\n // When we start up again the server is going to resend these changes\n // anyway, so just toss the accumulated state.\n this.accumulatedWatchChanges = [];\n this.pendingTargetResponses = {};\n };\n RemoteStore.prototype.onWatchStreamOpen = function () {\n var _this = this;\n // TODO(b/35852690): close the stream again (with some timeout?) if no watch\n // targets are active\n objUtils.forEachNumber(this.listenTargets, function (targetId, queryData) {\n _this.sendWatchRequest(queryData);\n });\n return Promise.resolve();\n };\n RemoteStore.prototype.onWatchStreamClose = function (error) {\n assert(this.isNetworkEnabled(), 'onWatchStreamClose() should only be called when the network is enabled');\n this.cleanUpWatchStreamState();\n // If there was an error, retry the connection.\n if (this.shouldStartWatchStream()) {\n this.updateOnlineStateAfterFailure();\n this.startWatchStream();\n }\n else {\n // No need to restart watch stream because there are no active targets.\n // The online state is set to unknown because there is no active attempt\n // at establishing a connection\n this.updateOnlineState(OnlineState.Unknown);\n }\n return Promise.resolve();\n };\n RemoteStore.prototype.onWatchStreamChange = function (watchChange, snapshotVersion) {\n // Mark the connection as healthy because we got a message from the server\n this.updateOnlineState(OnlineState.Healthy);\n if (watchChange instanceof WatchTargetChange &&\n watchChange.state === WatchTargetChangeState.Removed &&\n watchChange.cause) {\n // There was an error on a target, don't wait for a consistent snapshot\n // to raise events\n return this.handleTargetError(watchChange);\n }\n // Accumulate watch changes but don't process them if there's no\n // snapshotVersion or it's older than a previous snapshot we've processed\n // (can happen after we resume a target using a resume token).\n this.accumulatedWatchChanges.push(watchChange);\n if (!snapshotVersion.isEqual(SnapshotVersion.MIN) &&\n snapshotVersion.compareTo(this.localStore.getLastRemoteSnapshotVersion()) >= 0) {\n var changes = this.accumulatedWatchChanges;\n this.accumulatedWatchChanges = [];\n return this.handleWatchChangeBatch(snapshotVersion, changes);\n }\n else {\n return Promise.resolve();\n }\n };\n /**\n * Takes a batch of changes from the Datastore, repackages them as a\n * RemoteEvent, and passes that on to the listener, which is typically the\n * SyncEngine.\n */\n RemoteStore.prototype.handleWatchChangeBatch = function (snapshotVersion, changes) {\n var _this = this;\n var aggregator = new WatchChangeAggregator(snapshotVersion, this.listenTargets, this.pendingTargetResponses);\n aggregator.addChanges(changes);\n var remoteEvent = aggregator.createRemoteEvent();\n // Get the new response counts from the aggregator\n this.pendingTargetResponses = aggregator.pendingTargetResponses;\n var promises = [];\n // Handle existence filters and existence filter mismatches.\n objUtils.forEachNumber(aggregator.existenceFilters, function (targetId, filter) {\n var queryData = _this.listenTargets[targetId];\n if (!queryData) {\n // A watched target might have been removed already.\n return;\n }\n var query = queryData.query;\n if (query.isDocumentQuery()) {\n if (filter.count === 0) {\n // The existence filter told us the document does not exist.\n // We need to deduce that this document does not exist and apply\n // a deleted document to our updates. Without applying a deleted\n // document there might be another query that will raise this\n // document as part of a snapshot until it is resolved,\n // essentially exposing inconsistency between queries.\n var key = new DocumentKey(query.path);\n var deletedDoc = new NoDocument(key, snapshotVersion);\n remoteEvent.addDocumentUpdate(deletedDoc);\n }\n else {\n assert(filter.count === 1, 'Single document existence filter with count: ' + filter.count);\n }\n }\n else {\n // Not a document query.\n var promise = _this.localStore\n .remoteDocumentKeys(targetId)\n .then(function (trackedRemote) {\n if (remoteEvent.targetChanges[targetId]) {\n var mapping = remoteEvent.targetChanges[targetId].mapping;\n if (mapping !== null) {\n if (mapping instanceof UpdateMapping) {\n trackedRemote = mapping.applyToKeySet(trackedRemote);\n }\n else {\n assert(mapping instanceof ResetMapping, 'Expected either reset or update mapping but got something else: ' +\n mapping);\n trackedRemote = mapping.documents;\n }\n }\n }\n if (trackedRemote.size !== filter.count) {\n // Existence filter mismatch, resetting mapping.\n // Make sure the mismatch is exposed in the remote event.\n remoteEvent.handleExistenceFilterMismatch(targetId);\n // Clear the resume token for the query, since we're in a\n // known mismatch state.\n var newQueryData = new QueryData(query, targetId, queryData.purpose);\n _this.listenTargets[targetId] = newQueryData;\n // Cause a hard reset by unwatching and rewatching\n // immediately, but deliberately don't send a resume token\n // so that we get a full update.\n // Make sure we expect that this acks are going to happen.\n _this.sendUnwatchRequest(targetId);\n // Mark the query we send as being on behalf of an existence\n // filter mismatch, but don't actually retain that in\n // listenTargets. This ensures that we flag the first\n // re-listen this way without impacting future listens of\n // this target (that might happen e.g. on reconnect).\n var requestQueryData = new QueryData(query, targetId, QueryPurpose.ExistenceFilterMismatch);\n _this.sendWatchRequest(requestQueryData);\n }\n });\n promises.push(promise);\n }\n });\n return Promise.all(promises).then(function () {\n // Update in-memory resume tokens. LocalStore will update the\n // persistent view of these when applying the completed RemoteEvent.\n objUtils.forEachNumber(remoteEvent.targetChanges, function (targetId, change) {\n if (change.resumeToken.length > 0) {\n var queryData = _this.listenTargets[targetId];\n // A watched target might have been removed already.\n if (queryData) {\n _this.listenTargets[targetId] = queryData.update({\n resumeToken: change.resumeToken,\n snapshotVersion: change.snapshotVersion\n });\n }\n }\n });\n // Finally handle remote event\n return _this.syncEngine.applyRemoteEvent(remoteEvent);\n });\n };\n /** Handles an error on a target */\n RemoteStore.prototype.handleTargetError = function (watchChange) {\n var _this = this;\n assert(!!watchChange.cause, 'Handling target error without a cause');\n var error = watchChange.cause;\n var promiseChain = Promise.resolve();\n watchChange.targetIds.forEach(function (targetId) {\n promiseChain = promiseChain.then(function () {\n if (objUtils.contains(_this.listenTargets, targetId)) {\n delete _this.listenTargets[targetId];\n return _this.syncEngine.rejectListen(targetId, error);\n }\n else {\n // A watched target might have been removed already.\n return Promise.resolve();\n }\n });\n });\n return promiseChain;\n };\n RemoteStore.prototype.cleanUpWriteStreamState = function () {\n this.lastBatchSeen = BATCHID_UNKNOWN;\n log.debug(LOG_TAG, 'Stopping write stream with ' +\n this.pendingWrites.length +\n ' pending writes');\n this.pendingWrites = [];\n };\n /**\n * Notifies that there are new mutations to process in the queue. This is\n * typically called by SyncEngine after it has sent mutations to LocalStore.\n */\n RemoteStore.prototype.fillWritePipeline = function () {\n var _this = this;\n if (!this.canWriteMutations()) {\n return Promise.resolve();\n }\n else {\n return this.localStore\n .nextMutationBatch(this.lastBatchSeen)\n .then(function (batch) {\n if (batch === null) {\n if (_this.pendingWrites.length === 0) {\n _this.writeStream.markIdle();\n }\n return Promise.resolve();\n }\n else {\n _this.commit(batch);\n return _this.fillWritePipeline();\n }\n });\n }\n };\n /**\n * Returns true if the backend can accept additional write requests.\n *\n * When sending mutations to the write stream (e.g. in fillWritePipeline),\n * call this method first to check if more mutations can be sent.\n *\n * Currently the only thing that can prevent the backend from accepting\n * write requests is if there are too many requests already outstanding. As\n * writes complete the backend will be able to accept more.\n */\n RemoteStore.prototype.canWriteMutations = function () {\n return (this.isNetworkEnabled() && this.pendingWrites.length < MAX_PENDING_WRITES);\n };\n // For testing\n RemoteStore.prototype.outstandingWrites = function () {\n return this.pendingWrites.length;\n };\n /**\n * Given mutations to commit, actually commits them to the Datastore. Note\n * that this does *not* return a Promise specifically because the AsyncQueue\n * should not block operations for this.\n */\n RemoteStore.prototype.commit = function (batch) {\n assert(this.canWriteMutations(), \"commit called when batches can't be written\");\n this.lastBatchSeen = batch.batchId;\n this.pendingWrites.push(batch);\n if (this.shouldStartWriteStream()) {\n this.startWriteStream();\n }\n else if (this.isNetworkEnabled() && this.writeStream.handshakeComplete) {\n this.writeStream.writeMutations(batch.mutations);\n }\n };\n RemoteStore.prototype.shouldStartWriteStream = function () {\n return (this.isNetworkEnabled() &&\n !this.writeStream.isStarted() &&\n this.pendingWrites.length > 0);\n };\n RemoteStore.prototype.startWriteStream = function () {\n assert(this.shouldStartWriteStream(), 'startWriteStream() called when shouldStartWriteStream() is false.');\n this.writeStream.start({\n onOpen: this.onWriteStreamOpen.bind(this),\n onClose: this.onWriteStreamClose.bind(this),\n onHandshakeComplete: this.onWriteHandshakeComplete.bind(this),\n onMutationResult: this.onMutationResult.bind(this)\n });\n };\n RemoteStore.prototype.onWriteStreamOpen = function () {\n this.writeStream.writeHandshake();\n return Promise.resolve();\n };\n RemoteStore.prototype.onWriteHandshakeComplete = function () {\n var _this = this;\n // Record the stream token.\n return this.localStore\n .setLastStreamToken(this.writeStream.lastStreamToken)\n .then(function () {\n // Drain any pending writes.\n //\n // Note that at this point pendingWrites contains mutations that\n // have already been accepted by fillWritePipeline/commitBatch. If\n // the pipeline is full, canWriteMutations will be false, despite\n // the fact that we actually need to send mutations over.\n //\n // This also means that this method indirectly respects the limits\n // imposed by canWriteMutations since writes can't be added to the\n // pendingWrites array when canWriteMutations is false. If the\n // limits imposed by canWriteMutations actually protect us from\n // DOSing ourselves then those limits won't be exceeded here and\n // we'll continue to make progress.\n for (var _i = 0, _a = _this.pendingWrites; _i < _a.length; _i++) {\n var batch = _a[_i];\n _this.writeStream.writeMutations(batch.mutations);\n }\n });\n };\n RemoteStore.prototype.onMutationResult = function (commitVersion, results) {\n var _this = this;\n // This is a response to a write containing mutations and should be\n // correlated to the first pending write.\n assert(this.pendingWrites.length > 0, 'Got result for empty pending writes');\n var batch = this.pendingWrites.shift();\n var success = MutationBatchResult.from(batch, commitVersion, results, this.writeStream.lastStreamToken);\n return this.syncEngine.applySuccessfulWrite(success).then(function () {\n // It's possible that with the completion of this mutation another\n // slot has freed up.\n return _this.fillWritePipeline();\n });\n };\n RemoteStore.prototype.onWriteStreamClose = function (error) {\n var _this = this;\n assert(this.isNetworkEnabled(), 'onWriteStreamClose() should only be called when the network is enabled');\n // If the write stream closed due to an error, invoke the error callbacks if\n // there are pending writes.\n if (error && this.pendingWrites.length > 0) {\n assert(!!error, 'We have pending writes, but the write stream closed without an error');\n // A promise that is resolved after we processed the error\n var errorHandling = void 0;\n if (this.writeStream.handshakeComplete) {\n // This error affects the actual write.\n errorHandling = this.handleWriteError(error);\n }\n else {\n // If there was an error before the handshake has finished, it's\n // possible that the server is unable to process the stream token\n // we're sending. (Perhaps it's too old?)\n errorHandling = this.handleHandshakeError(error);\n }\n return errorHandling.then(function () {\n // The write stream might have been started by refilling the write\n // pipeline for failed writes\n if (_this.shouldStartWriteStream()) {\n _this.startWriteStream();\n }\n });\n }\n else {\n // No pending writes, nothing to do\n return Promise.resolve();\n }\n };\n RemoteStore.prototype.handleHandshakeError = function (error) {\n // Reset the token if it's a permanent error or the error code is\n // ABORTED, signaling the write stream is no longer valid.\n if (isPermanentError(error.code) || error.code === Code.ABORTED) {\n log.debug(LOG_TAG, 'RemoteStore error before completed handshake; resetting stream token: ', this.writeStream.lastStreamToken);\n this.writeStream.lastStreamToken = emptyByteString();\n return this.localStore.setLastStreamToken(emptyByteString());\n }\n else {\n // Some other error, don't reset stream token. Our stream logic will\n // just retry with exponential backoff.\n return Promise.resolve();\n }\n };\n RemoteStore.prototype.handleWriteError = function (error) {\n var _this = this;\n if (isPermanentError(error.code)) {\n // This was a permanent error, the request itself was the problem\n // so it's not going to succeed if we resend it.\n var batch = this.pendingWrites.shift();\n // In this case it's also unlikely that the server itself is melting\n // down -- this was just a bad request so inhibit backoff on the next\n // restart.\n this.writeStream.inhibitBackoff();\n return this.syncEngine\n .rejectFailedWrite(batch.batchId, error)\n .then(function () {\n // It's possible that with the completion of this mutation\n // another slot has freed up.\n return _this.fillWritePipeline();\n });\n }\n else {\n // Transient error, just let the retry logic kick in.\n return Promise.resolve();\n }\n };\n RemoteStore.prototype.createTransaction = function () {\n return new Transaction(this.datastore);\n };\n RemoteStore.prototype.handleUserChange = function (user) {\n log.debug(LOG_TAG, 'RemoteStore changing users: uid=', user.uid);\n // If the network has been explicitly disabled, make sure we don't\n // accidentally re-enable it.\n if (this.isNetworkEnabled()) {\n // Tear down and re-create our network streams. This will ensure we get a fresh auth token\n // for the new user and re-fill the write pipeline with new mutations from the LocalStore\n // (since mutations are per-user).\n this.disableNetworkInternal();\n this.updateOnlineState(OnlineState.Unknown);\n return this.enableNetwork();\n }\n };\n return RemoteStore;\n}());\nexport { RemoteStore };\n\n//# sourceMappingURL=remote_store.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/remote/remote_store.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { EventManager, QueryListener } from './event_manager';\nimport { SyncEngine } from './sync_engine';\nimport { EagerGarbageCollector } from '../local/eager_garbage_collector';\nimport { IndexedDbPersistence } from '../local/indexeddb_persistence';\nimport { LocalStore } from '../local/local_store';\nimport { MemoryPersistence } from '../local/memory_persistence';\nimport { NoOpGarbageCollector } from '../local/no_op_garbage_collector';\nimport { Datastore } from '../remote/datastore';\nimport { RemoteStore } from '../remote/remote_store';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { Code } from '../util/error';\nimport { debug } from '../util/log';\nimport { Deferred } from '../util/promise';\nvar LOG_TAG = 'FirestoreClient';\n/**\n * FirestoreClient is a top-level class that constructs and owns all of the\n * pieces of the client SDK architecture. It is responsible for creating the\n * async queue that is shared by all of the other components in the system.\n */\nvar FirestoreClient = /** @class */ (function () {\n function FirestoreClient(platform, databaseInfo, credentials, \n /**\n * Asynchronous queue responsible for all of our internal processing. When\n * we get incoming work from the user (via public API) or the network\n * (incoming GRPC messages), we should always schedule onto this queue.\n * This ensures all of our work is properly serialized (e.g. we don't\n * start processing a new operation while the previous one is waiting for\n * an async I/O to complete).\n */\n asyncQueue) {\n this.platform = platform;\n this.databaseInfo = databaseInfo;\n this.credentials = credentials;\n this.asyncQueue = asyncQueue;\n }\n /**\n * Starts up the FirestoreClient, returning only whether or not enabling\n * persistence succeeded.\n *\n * The intent here is to \"do the right thing\" as far as users are concerned.\n * Namely, in cases where offline persistence is requested and possible,\n * enable it, but otherwise fall back to persistence disabled. For the most\n * part we expect this to succeed one way or the other so we don't expect our\n * users to actually wait on the firestore.enablePersistence Promise since\n * they generally won't care.\n *\n * Of course some users actually do care about whether or not persistence\n * was successfully enabled, so the Promise returned from this method\n * indicates this outcome.\n *\n * This presents a problem though: even before enablePersistence resolves or\n * rejects, users may have made calls to e.g. firestore.collection() which\n * means that the FirestoreClient in there will be available and will be\n * enqueuing actions on the async queue.\n *\n * Meanwhile any failure of an operation on the async queue causes it to\n * panic and reject any further work, on the premise that unhandled errors\n * are fatal.\n *\n * Consequently the fallback is handled internally here in start, and if the\n * fallback succeeds we signal success to the async queue even though the\n * start() itself signals failure.\n *\n * @param usePersistence Whether or not to attempt to enable persistence.\n * @returns A deferred result indicating the user-visible result of enabling\n * offline persistence. This method will reject this if IndexedDB fails to\n * start for any reason. If usePersistence is false this is\n * unconditionally resolved.\n */\n FirestoreClient.prototype.start = function (usePersistence) {\n var _this = this;\n // We defer our initialization until we get the current user from\n // setUserChangeListener(). We block the async queue until we got the\n // initial user and the initialization is completed. This will prevent\n // any scheduled work from happening before initialization is completed.\n //\n // If initializationDone resolved then the FirestoreClient is in a usable\n // state.\n var initializationDone = new Deferred();\n // If usePersistence is true, certain classes of errors while starting are\n // recoverable but only by falling back to persistence disabled.\n //\n // If there's an error in the first case but not in recovery we cannot\n // reject the promise blocking the async queue because this will cause the\n // async queue to panic.\n var persistenceResult = new Deferred();\n var initialized = false;\n this.credentials.setUserChangeListener(function (user) {\n if (!initialized) {\n initialized = true;\n _this.initializePersistence(usePersistence, persistenceResult)\n .then(function () { return _this.initializeRest(user); })\n .then(initializationDone.resolve, initializationDone.reject);\n }\n else {\n _this.asyncQueue.schedule(function () {\n return _this.handleUserChange(user);\n });\n }\n });\n // Block the async queue until initialization is done\n this.asyncQueue.schedule(function () {\n return initializationDone.promise;\n });\n // Return only the result of enabling persistence. Note that this does not\n // need to await the completion of initializationDone because the result of\n // this method should not reflect any other kind of failure to start.\n return persistenceResult.promise;\n };\n /** Enables the network connection and requeues all pending operations. */\n FirestoreClient.prototype.enableNetwork = function () {\n var _this = this;\n return this.asyncQueue.schedule(function () {\n return _this.remoteStore.enableNetwork();\n });\n };\n /**\n * Initializes persistent storage, attempting to use IndexedDB if\n * usePersistence is true or memory-only if false.\n *\n * If IndexedDB fails because it's already open in another tab or because the\n * platform can't possibly support our implementation then this method rejects\n * the persistenceResult and falls back on memory-only persistence.\n *\n * @param usePersistence indicates whether or not to use offline persistence\n * @param persistenceResult A deferred result indicating the user-visible\n * result of enabling offline persistence. This method will reject this if\n * IndexedDB fails to start for any reason. If usePersistence is false\n * this is unconditionally resolved.\n * @returns a Promise indicating whether or not initialization should\n * continue, i.e. that one of the persistence implementations actually\n * succeeded.\n */\n FirestoreClient.prototype.initializePersistence = function (usePersistence, persistenceResult) {\n var _this = this;\n if (usePersistence) {\n return this.startIndexedDbPersistence()\n .then(persistenceResult.resolve)\n .catch(function (error) {\n // Regardless of whether or not the retry succeeds, from an user\n // perspective, offline persistence has failed.\n persistenceResult.reject(error);\n // An unknown failure on the first stage shuts everything down.\n if (!_this.canFallback(error)) {\n return Promise.reject(error);\n }\n console.warn('Error enabling offline storage. Falling back to' +\n ' storage disabled: ' +\n error);\n return _this.startMemoryPersistence();\n });\n }\n else {\n // When usePersistence == false, enabling offline persistence is defined\n // to unconditionally succeed. This allows start() to have the same\n // signature for both cases, despite the fact that the returned promise\n // is only used in the enablePersistence call.\n persistenceResult.resolve();\n return this.startMemoryPersistence();\n }\n };\n FirestoreClient.prototype.canFallback = function (error) {\n return (error.code === Code.FAILED_PRECONDITION ||\n error.code === Code.UNIMPLEMENTED);\n };\n /**\n * Starts IndexedDB-based persistence.\n *\n * @returns A promise indicating success or failure.\n */\n FirestoreClient.prototype.startIndexedDbPersistence = function () {\n // TODO(http://b/33384523): For now we just disable garbage collection\n // when persistence is enabled.\n this.garbageCollector = new NoOpGarbageCollector();\n var storagePrefix = IndexedDbPersistence.buildStoragePrefix(this.databaseInfo);\n // Opt to use proto3 JSON in case the platform doesn't support Uint8Array.\n var serializer = new JsonProtoSerializer(this.databaseInfo.databaseId, {\n useProto3Json: true\n });\n this.persistence = new IndexedDbPersistence(storagePrefix, serializer);\n return this.persistence.start();\n };\n /**\n * Starts Memory-backed persistence. In practice this cannot fail.\n *\n * @returns A promise that will successfully resolve.\n */\n FirestoreClient.prototype.startMemoryPersistence = function () {\n this.garbageCollector = new EagerGarbageCollector();\n this.persistence = new MemoryPersistence();\n return this.persistence.start();\n };\n /**\n * Initializes the rest of the FirestoreClient, assuming the initial user\n * has been obtained from the credential provider and some persistence\n * implementation is available in this.persistence.\n */\n FirestoreClient.prototype.initializeRest = function (user) {\n var _this = this;\n return this.platform\n .loadConnection(this.databaseInfo)\n .then(function (connection) {\n _this.localStore = new LocalStore(_this.persistence, user, _this.garbageCollector);\n var serializer = _this.platform.newSerializer(_this.databaseInfo.databaseId);\n var datastore = new Datastore(_this.databaseInfo, _this.asyncQueue, connection, _this.credentials, serializer);\n var onlineStateChangedHandler = function (onlineState) {\n _this.syncEngine.applyOnlineStateChange(onlineState);\n _this.eventMgr.applyOnlineStateChange(onlineState);\n };\n _this.remoteStore = new RemoteStore(_this.localStore, datastore, onlineStateChangedHandler);\n _this.syncEngine = new SyncEngine(_this.localStore, _this.remoteStore, user);\n // Setup wiring between sync engine and remote store\n _this.remoteStore.syncEngine = _this.syncEngine;\n _this.eventMgr = new EventManager(_this.syncEngine);\n // NOTE: RemoteStore depends on LocalStore (for persisting stream\n // tokens, refilling mutation queue, etc.) so must be started after\n // LocalStore.\n return _this.localStore.start();\n })\n .then(function () {\n return _this.remoteStore.start();\n });\n };\n FirestoreClient.prototype.handleUserChange = function (user) {\n this.asyncQueue.verifyOperationInProgress();\n debug(LOG_TAG, 'User Changed: ' + user.uid);\n return this.syncEngine.handleUserChange(user);\n };\n /** Disables the network connection. Pending operations will not complete. */\n FirestoreClient.prototype.disableNetwork = function () {\n var _this = this;\n return this.asyncQueue.schedule(function () {\n return _this.remoteStore.disableNetwork();\n });\n };\n FirestoreClient.prototype.shutdown = function () {\n var _this = this;\n return this.asyncQueue\n .schedule(function () {\n _this.credentials.removeUserChangeListener();\n return _this.remoteStore.shutdown();\n })\n .then(function () {\n // PORTING NOTE: LocalStore does not need an explicit shutdown on web.\n return _this.persistence.shutdown();\n });\n };\n FirestoreClient.prototype.listen = function (query, observer, options) {\n var _this = this;\n var listener = new QueryListener(query, observer, options);\n this.asyncQueue.schedule(function () {\n return _this.eventMgr.listen(listener);\n });\n return listener;\n };\n FirestoreClient.prototype.unlisten = function (listener) {\n var _this = this;\n this.asyncQueue.schedule(function () {\n return _this.eventMgr.unlisten(listener);\n });\n };\n FirestoreClient.prototype.write = function (mutations) {\n var _this = this;\n var deferred = new Deferred();\n this.asyncQueue.schedule(function () { return _this.syncEngine.write(mutations, deferred); });\n return deferred.promise;\n };\n FirestoreClient.prototype.databaseId = function () {\n return this.databaseInfo.databaseId;\n };\n FirestoreClient.prototype.transaction = function (updateFunction) {\n var _this = this;\n // We have to wait for the async queue to be sure syncEngine is initialized.\n return this.asyncQueue\n .schedule(function () {\n return Promise.resolve();\n })\n .then(function () {\n return _this.syncEngine.runTransaction(updateFunction);\n });\n };\n return FirestoreClient;\n}());\nexport { FirestoreClient };\n\n//# sourceMappingURL=firestore_client.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/firestore_client.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/*\n * A wrapper implementation of Observer that will dispatch events\n * asynchronously. To allow immediate silencing, a mute call is added which\n * causes events scheduled to no longer be raised.\n */\nvar AsyncObserver = /** @class */ (function () {\n function AsyncObserver(observer) {\n this.observer = observer;\n /**\n * When set to true, will not raise future events. Necessary to deal with\n * async detachment of listener.\n */\n this.muted = false;\n }\n AsyncObserver.prototype.next = function (value) {\n this.scheduleEvent(this.observer.next, value);\n };\n AsyncObserver.prototype.error = function (error) {\n this.scheduleEvent(this.observer.error, error);\n };\n AsyncObserver.prototype.mute = function () {\n this.muted = true;\n };\n AsyncObserver.prototype.scheduleEvent = function (eventHandler, event) {\n var _this = this;\n if (!this.muted) {\n setTimeout(function () {\n if (!_this.muted) {\n eventHandler(event);\n }\n }, 0);\n }\n };\n return AsyncObserver;\n}());\nexport { AsyncObserver };\n\n//# sourceMappingURL=async_observer.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/async_observer.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { assert, fail } from './assert';\nimport * as log from './log';\nimport { Deferred } from './promise';\nimport { Code, FirestoreError } from './error';\nvar AsyncQueue = /** @class */ (function () {\n function AsyncQueue() {\n // The last promise in the queue.\n this.tail = Promise.resolve();\n // A list with timeout handles and their respective deferred promises.\n // Contains an entry for each operation that is queued to run in the future\n // (i.e. it has a delay that has not yet elapsed). Prior to cleanup, this list\n // may also contain entries that have already been run (in which case `handle` is\n // null).\n this.delayedOperations = [];\n // The number of operations that are queued to be run in the future (i.e. they\n // have a delay that has not yet elapsed). Unlike `delayedOperations`, this\n // is guaranteed to only contain operations that have not yet been run.\n //\n // Visible for testing.\n this.delayedOperationsCount = 0;\n // Flag set while there's an outstanding AsyncQueue operation, used for\n // assertion sanity-checks.\n this.operationInProgress = false;\n }\n /**\n * Adds a new operation to the queue. Returns a promise that will be resolved\n * when the promise returned by the new operation is (with its value).\n *\n * Can optionally specify a delay (in milliseconds) to wait before queuing the\n * operation.\n */\n AsyncQueue.prototype.schedule = function (op, delay) {\n var _this = this;\n if (this.failure) {\n fail('AsyncQueue is already failed: ' +\n (this.failure.stack || this.failure.message));\n }\n if ((delay || 0) > 0) {\n this.delayedOperationsCount++;\n var delayedOp_1 = {\n handle: null,\n op: op,\n deferred: new Deferred()\n };\n delayedOp_1.handle = setTimeout(function () {\n _this.scheduleInternal(function () {\n return delayedOp_1.op().then(function (result) {\n delayedOp_1.deferred.resolve(result);\n });\n });\n delayedOp_1.handle = null;\n _this.delayedOperationsCount--;\n if (_this.delayedOperationsCount === 0) {\n _this.delayedOperations = [];\n }\n }, delay);\n this.delayedOperations.push(delayedOp_1);\n return delayedOp_1.deferred.promise;\n }\n else {\n return this.scheduleInternal(op);\n }\n };\n AsyncQueue.prototype.scheduleInternal = function (op) {\n var _this = this;\n this.tail = this.tail.then(function () {\n _this.operationInProgress = true;\n return op()\n .catch(function (error) {\n _this.failure = error;\n _this.operationInProgress = false;\n var message = error.stack || error.message || '';\n log.error('INTERNAL UNHANDLED ERROR: ', message);\n // Escape the promise chain and throw the error globally so that\n // e.g. any global crash reporting library detects and reports it.\n // (but not for simulated errors in our tests since this breaks mocha)\n if (message.indexOf('Firestore Test Simulated Error') < 0) {\n setTimeout(function () {\n throw error;\n }, 0);\n }\n // Re-throw the error so that this.tail becomes a rejected Promise and\n // all further attempts to chain (via .then) will just short-circuit\n // and return the rejected Promise.\n throw error;\n })\n .then(function () {\n _this.operationInProgress = false;\n });\n });\n return this.tail;\n };\n /**\n * Verifies there's an operation currently in-progress on the AsyncQueue.\n * Unfortunately we can't verify that the running code is in the promise chain\n * of that operation, so this isn't a foolproof check, but it should be enough\n * to catch some bugs.\n */\n AsyncQueue.prototype.verifyOperationInProgress = function () {\n assert(this.operationInProgress, 'verifyOpInProgress() called when no op in progress on this queue.');\n };\n /**\n * Waits until all currently scheduled tasks are finished executing. Tasks\n * scheduled with a delay can be rejected or queued for immediate execution.\n */\n AsyncQueue.prototype.drain = function (executeDelayedTasks) {\n var _this = this;\n this.delayedOperations.forEach(function (entry) {\n if (entry.handle) {\n clearTimeout(entry.handle);\n if (executeDelayedTasks) {\n _this.scheduleInternal(entry.op).then(entry.deferred.resolve, entry.deferred.reject);\n }\n else {\n entry.deferred.reject(new FirestoreError(Code.CANCELLED, 'Operation cancelled by shutdown'));\n }\n }\n });\n this.delayedOperations = [];\n this.delayedOperationsCount = 0;\n return this.schedule(function () { return Promise.resolve(); });\n };\n return AsyncQueue;\n}());\nexport { AsyncQueue };\n\n//# sourceMappingURL=async_queue.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/async_queue.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Simple wrapper around a nullable UID. Mostly exists to make code more\n * readable.\n */\nvar User = /** @class */ (function () {\n function User(uid) {\n this.uid = uid;\n }\n User.prototype.isUnauthenticated = function () {\n return this.uid == null;\n };\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */\n User.prototype.toKey = function () {\n if (this.isUnauthenticated()) {\n return 'anonymous-user';\n }\n else {\n return 'uid:' + this.uid;\n }\n };\n User.prototype.isEqual = function (otherUser) {\n return otherUser.uid === this.uid;\n };\n /** A user with a null UID. */\n User.UNAUTHENTICATED = new User(null);\n // TODO(mikelehen): Look into getting a proper uid-equivalent for\n // non-FirebaseAuth providers.\n User.GOOGLE_CREDENTIALS = new User('google-credentials-uid');\n User.FIRST_PARTY = new User('first-party-uid');\n return User;\n}());\nexport { User };\n\n//# sourceMappingURL=user.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/auth/user.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { makeConstructorPrivate } from '../util/api';\n/**\n * An opaque base class for FieldValue sentinel objects in our public API,\n * with public static methods for creating said sentinel objects.\n */\n// tslint:disable-next-line:class-as-namespace We use this as a base class.\nvar FieldValueImpl = /** @class */ (function () {\n function FieldValueImpl() {\n }\n FieldValueImpl.delete = function () {\n return DeleteFieldValueImpl.instance;\n };\n FieldValueImpl.serverTimestamp = function () {\n return ServerTimestampFieldValueImpl.instance;\n };\n FieldValueImpl.prototype.isEqual = function (other) {\n return this === other;\n };\n return FieldValueImpl;\n}());\nexport { FieldValueImpl };\nvar DeleteFieldValueImpl = /** @class */ (function (_super) {\n __extends(DeleteFieldValueImpl, _super);\n function DeleteFieldValueImpl() {\n return _super.call(this) || this;\n }\n /** Singleton instance. */\n DeleteFieldValueImpl.instance = new DeleteFieldValueImpl();\n return DeleteFieldValueImpl;\n}(FieldValueImpl));\nexport { DeleteFieldValueImpl };\nvar ServerTimestampFieldValueImpl = /** @class */ (function (_super) {\n __extends(ServerTimestampFieldValueImpl, _super);\n function ServerTimestampFieldValueImpl() {\n return _super.call(this) || this;\n }\n /** Singleton instance. */\n ServerTimestampFieldValueImpl.instance = new ServerTimestampFieldValueImpl();\n return ServerTimestampFieldValueImpl;\n}(FieldValueImpl));\nexport { ServerTimestampFieldValueImpl };\n// Public instance that disallows construction at runtime. This constructor is\n// used when exporting FieldValueImpl on firebase.firestore.FieldValue and will\n// be called FieldValue publicly. Internally we still use FieldValueImpl which\n// has a type-checked private constructor. Note that FieldValueImpl and\n// PublicFieldValue can be used interchangeably in instanceof checks.\n// For our internal TypeScript code PublicFieldValue doesn't exist as a type,\n// and so we need to use FieldValueImpl as type and export it too.\n// tslint:disable-next-line:variable-name We treat this as a class name.\nexport var PublicFieldValue = makeConstructorPrivate(FieldValueImpl, 'Use FieldValue.() instead.');\n\n//# sourceMappingURL=field_value.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/api/field_value.js\n// module id = null\n// module chunks = ","(function() {var g,goog=goog||{},k=this;function l(a){return\"string\"==typeof a}function aa(){}\nfunction ba(a){var b=typeof a;if(\"object\"==b)if(a){if(a instanceof Array)return\"array\";if(a instanceof Object)return b;var c=Object.prototype.toString.call(a);if(\"[object Window]\"==c)return\"object\";if(\"[object Array]\"==c||\"number\"==typeof a.length&&\"undefined\"!=typeof a.splice&&\"undefined\"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable(\"splice\"))return\"array\";if(\"[object Function]\"==c||\"undefined\"!=typeof a.call&&\"undefined\"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable(\"call\"))return\"function\"}else return\"null\";\nelse if(\"function\"==b&&\"undefined\"==typeof a.call)return\"object\";return b}function n(a){return\"array\"==ba(a)}function ca(a){var b=ba(a);return\"array\"==b||\"object\"==b&&\"number\"==typeof a.length}function da(a){return\"function\"==ba(a)}function p(a){var b=typeof a;return\"object\"==b&&null!=a||\"function\"==b}var q=\"closure_uid_\"+(1E9*Math.random()>>>0),ea=0;function fa(a,b,c){return a.call.apply(a.bind,arguments)}\nfunction ha(a,b,c){if(!a)throw Error();if(2b?1:0};function na(a,b){b.unshift(a);ja.call(this,ka.apply(null,b));b.shift()}u(na,ja);na.prototype.name=\"AssertionError\";function oa(a,b){throw new na(\"Failure\"+(a?\": \"+a:\"\"),Array.prototype.slice.call(arguments,1));};function w(){0!=qa&&(ra[this[q]||(this[q]=++ea)]=this);this.i=this.i;this.w=this.w}var qa=0,ra={};w.prototype.i=!1;w.prototype.Z=function(){if(!this.i&&(this.i=!0,this.A(),0!=qa)){var a=this[q]||(this[q]=++ea);delete ra[a]}};w.prototype.A=function(){if(this.w)for(;this.w.length;)this.w.shift()()};var sa=Array.prototype.indexOf?function(a,b){return Array.prototype.indexOf.call(a,b,void 0)}:function(a,b){if(l(a))return l(b)&&1==b.length?a.indexOf(b,0):-1;for(var c=0;cb?null:l(a)?a.charAt(b):a[b]}function wa(a){if(!n(a))for(var b=a.length-1;0<=b;b--)delete a[b];a.length=0}function xa(a){return Array.prototype.concat.apply([],arguments)}function ya(a){var b=a.length;if(0parseFloat(Qa)){Pa=String(Sa);break a}}Pa=Qa}var Ja={};\nfunction Ta(a){return Ia(a,function(){for(var b=0,c=la(String(Pa)).split(\".\"),d=la(String(a)).split(\".\"),e=Math.max(c.length,d.length),f=0;0==b&&f=a.keyCode)a.keyCode=-1}catch(b){}};var bb=\"closure_listenable_\"+(1E6*Math.random()|0);function cb(a){return!(!a||!a[bb])}var db=0;function eb(a,b,c,d,e){this.listener=a;this.a=null;this.src=b;this.type=c;this.capture=!!d;this.ga=e;this.key=++db;this.Y=this.ca=!1}function fb(a){a.Y=!0;a.listener=null;a.a=null;a.src=null;a.ga=null};function gb(a){this.src=a;this.a={};this.b=0}gb.prototype.add=function(a,b,c,d,e){var f=a.toString();a=this.a[f];a||(a=this.a[f]=[],this.b++);var h=hb(a,b,d,e);-1d.keyCode||void 0!=d.returnValue)){a:{var e=!1;if(0==d.keyCode)try{d.keyCode=-1;break a}catch(h){e=!0}if(e||void 0==d.returnValue)d.returnValue=!0}d=[];for(e=b.a;e;e=e.parentNode)d.push(e);a=a.type;for(e=d.length-1;0<=e;e--){b.a=d[e];var f=xb(d[e],a,!0,b);c=c&&f}for(e=0;e>>0);function pb(a){if(da(a))return a;a[zb]||(a[zb]=function(b){return a.handleEvent(b)});return a[zb]};function B(){w.call(this);this.c=new gb(this);this.P=this;this.K=null}u(B,w);B.prototype[bb]=!0;g=B.prototype;g.addEventListener=function(a,b,c,d){nb(this,a,b,c,d)};g.removeEventListener=function(a,b,c,d){vb(this,a,b,c,d)};\ng.dispatchEvent=function(a){var b,c=this.K;if(c)for(b=[];c;c=c.K)b.push(c);c=this.P;var d=a.type||a;if(l(a))a=new A(a,c);else if(a instanceof A)a.target=a.target||c;else{var e=a;a=new A(d,c);Ga(a,e)}e=!0;if(b)for(var f=b.length-1;0<=f;f--){var h=a.a=b[f];e=Ab(h,d,!0,a)&&e}h=a.a=c;e=Ab(h,d,!0,a)&&e;e=Ab(h,d,!1,a)&&e;if(b)for(f=0;fb.b&&(b.b++,a.next=b.a,b.a=a)}Wb=!1};function Xb(a,b){B.call(this);this.b=a||1;this.a=b||k;this.f=r(this.kb,this);this.g=t()}u(Xb,B);g=Xb.prototype;g.$=!1;g.L=null;g.kb=function(){if(this.$){var a=t()-this.g;0=lc(this).value)for(da(b)&&(b=b()),a=new dc(a,String(b),this.f),c&&(a.a=c),c=this;c;)c=c.a};\nvar mc={},nc=null;function oc(a){nc||(nc=new fc(\"\"),mc[\"\"]=nc,nc.c=jc);var b;if(!(b=mc[a])){b=new fc(a);var c=a.lastIndexOf(\".\"),d=a.substr(c+1);c=oc(a.substr(0,c));c.b||(c.b={});c.b[d]=b;b.a=c;mc[a]=b}return b};function E(a,b){a&&a.log(hc,b,void 0)}function pc(a,b){a&&a.log(ic,b,void 0)}function F(a,b){a&&a.log(kc,b,void 0)};function qc(){this.a=oc(\"goog.labs.net.webChannel.WebChannelDebug\");this.b=!0}qc.prototype.Ea=function(){this.b=!1};function rc(a,b,c,d,e,f){H(a,function(){if(a.b)if(f){var h=\"\";for(var m=f.split(\"&\"),v=0;ve.length)){var f=e[1];if(n(f)&&!(1>f.length)){var h=f[0];if(\"noop\"!=h&&\"stop\"!=h&&\"close\"!=h)for(var m=1;mb||3==b&&!Ka&&!a.a.V())){a.B||4!=b||7==c||(8==c||0>=d?Ac(3):Ac(2));Zc(a);var e=a.a.W();a.C=e;(c=a.a.V())||I(a.b,function(){return\"No response text for uri \"+a.g+\" status \"+e});a.c=200==e;sc(a.b,a.o,a.g,a.f,a.T,b,e);a.c?(a.M?($c(a,b,c),Ka&&a.c&&3==b&&ad(a)):(tc(a.b,a.f,c,null),bd(a,c)),4==b&&cd(a),a.c&&!a.B&&(4==b?a.i.ua(a):(a.c=!1,Wc(a)))):(400==e&&0b.length)return Rc;b=b.substr(d,c);a.F=d+c;return b}g.cancel=function(){this.B=!0;cd(this)};function Wc(a){a.U=t()+a.S;fd(a,a.S)}\nfunction fd(a,b){if(null!=a.w)throw Error(\"WatchDog timer not null\");a.w=Ec(r(a.fb,a),b)}function Zc(a){a.w&&(k.clearTimeout(a.w),a.w=null)}g.fb=function(){this.w=null;var a=t();0<=a-this.U?(this.c&&xc(this.b,\"Received watchdog timeout even though request loaded successfully\"),vc(this.b,this.g),2!=this.K&&(Ac(3),J(17)),cd(this),this.l=2,dd(this)):(E(this.b.a,\"WatchDog timer called too early\"),fd(this,this.U-a))};function dd(a){a.i.Ja()||a.B||a.i.ua(a)}\nfunction cd(a){Zc(a);var b=a.J;b&&\"function\"==typeof b.Z&&b.Z();a.J=null;Yb(a.I);cc(a.N);a.a&&(b=a.a,a.a=null,b.abort(),b.Z())}function bd(a,b){try{a.i.Ma(a,b),Ac(4)}catch(c){wc(a.b,c,\"Error in httprequest callback\")}};function gd(a){if(a.v&&\"function\"==typeof a.v)return a.v();if(l(a))return a.split(\"\");if(ca(a)){for(var b=[],c=a.length,d=0;d2*a.c&&id(a),!0):!1}function id(a){if(a.c!=a.a.length){for(var b=0,c=0;bb)throw Error(\"Bad port number \"+b);a.i=b}else a.i=null}function qd(a,b,c){b instanceof td?(a.c=b,zd(a.c,a.h)):(c||(b=ud(b,Ad)),a.c=new td(b,a.h))}\nfunction Q(a,b,c){a.c.set(b,c)}function Xc(a,b,c){n(c)||(c=[String(c)]);Bd(a.c,b,c)}function Tc(a){Q(a,\"zx\",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^t()).toString(36));return a}function Cd(a){return a instanceof P?L(a):new P(a,void 0)}function Dd(a,b,c,d){var e=new P(null,void 0);a&&nd(e,a);b&&od(e,b);c&&pd(e,c);d&&(e.a=d);return e}function sd(a,b){return a?b?decodeURI(a.replace(/%25/g,\"%2525\")):decodeURIComponent(a):\"\"}\nfunction ud(a,b,c){return l(a)?(a=encodeURI(a).replace(b,Ed),c&&(a=a.replace(/%25([0-9a-fA-F]{2})/g,\"%$1\")),a):null}function Ed(a){a=a.charCodeAt(0);return\"%\"+(a>>4&15).toString(16)+(a&15).toString(16)}var vd=/[#\\/\\?@]/g,xd=/[#\\?:]/g,wd=/[#\\?]/g,Ad=/[#\\?@]/g,yd=/#/g;function td(a,b){this.b=this.a=null;this.c=a||null;this.f=!!b}function R(a){a.a||(a.a=new N,a.b=0,a.c&&md(a.c,function(b,c){a.add(decodeURIComponent(b.replace(/\\+/g,\" \")),c)}))}g=td.prototype;g.s=function(){R(this);return this.b};\ng.add=function(a,b){R(this);this.c=null;a=Fd(this,a);var c=this.a.get(a);c||this.a.set(a,c=[]);c.push(b);this.b+=1;return this};function Gd(a,b){R(a);b=Fd(a,b);O(a.a.b,b)&&(a.c=null,a.b-=a.a.get(b).length,kd(a.a,b))}function Hd(a,b){R(a);b=Fd(a,b);return O(a.a.b,b)}g.forEach=function(a,b){R(this);this.a.forEach(function(c,d){ta(c,function(c){a.call(b,c,d,this)},this)},this)};\ng.O=function(){R(this);for(var a=this.a.v(),b=this.a.O(),c=[],d=0;d=a.f:!1}function ce(a,b){return a.b?a.b==b:a.a?a.a.contains(b):!1}function ae(a,b){a.a?a.a.add(b):a.b=b}\nfunction de(a,b){a.b&&a.b==b?a.b=null:a.a&&a.a.contains(b)&&kd(a.a.a,Wd(b))}Yd.prototype.cancel=function(){this.c=ee(this);this.b?(this.b.cancel(),this.b=null):this.a&&0!=this.a.a.c&&(ta(this.a.v(),function(a){a.cancel()}),jd(this.a.a))};function ee(a){if(null!=a.b)return a.c.concat(a.b.u);if(null!=a.a&&0!=a.a.a.c){var b=a.c;ta(a.a.v(),function(a){b=b.concat(a.u)});return b}return ya(a.c)}function fe(a,b){a.c=a.c.concat(b)};function ge(){}ge.prototype.stringify=function(a){return k.JSON.stringify(a,void 0)};ge.prototype.parse=function(a){return k.JSON.parse(a,void 0)};function he(){this.a=new ge}function ie(a,b,c){var d=c||\"\";try{hd(a,function(a,c){var e=a;p(a)&&(e=Db(a));b.push(d+c+\"=\"+encodeURIComponent(e))})}catch(e){throw b.push(d+\"type=\"+encodeURIComponent(\"_badmap\")),e;}};function je(a,b){var c=new qc;I(c,\"TestLoadImage: loading \"+a);var d=new Image;d.onload=ia(ke,c,d,\"TestLoadImage: loaded\",!0,b);d.onerror=ia(ke,c,d,\"TestLoadImage: error\",!1,b);d.onabort=ia(ke,c,d,\"TestLoadImage: abort\",!1,b);d.ontimeout=ia(ke,c,d,\"TestLoadImage: timeout\",!1,b);k.setTimeout(function(){if(d.ontimeout)d.ontimeout()},1E4);d.src=a}function ke(a,b,c,d,e){try{I(a,c),b.onload=null,b.onerror=null,b.onabort=null,b.ontimeout=null,e(d)}catch(f){wc(a,f)}};function T(a){B.call(this);this.headers=new N;this.F=a||null;this.f=!1;this.D=this.a=null;this.M=this.u=\"\";this.j=0;this.g=\"\";this.h=this.J=this.o=this.I=!1;this.l=0;this.B=null;this.N=le;this.C=this.m=!1}u(T,B);var le=\"\";T.prototype.b=oc(\"goog.net.XhrIo\");var me=/^https?$/i,ne=[\"POST\",\"PUT\"];g=T.prototype;\ng.fa=function(a,b,c,d){if(this.a)throw Error(\"[goog.net.XhrIo] Object is active with another request=\"+this.u+\"; newUri=\"+a);b=b?b.toUpperCase():\"GET\";this.u=a;this.g=\"\";this.j=0;this.M=b;this.I=!1;this.f=!0;this.a=this.F?Mc(this.F):Mc(Kc);this.D=this.F?Ic(this.F):Ic(Kc);this.a.onreadystatechange=r(this.La,this);try{F(this.b,U(this,\"Opening Xhr\")),this.J=!0,this.a.open(b,String(a),!0),this.J=!1}catch(f){F(this.b,U(this,\"Error opening Xhr: \"+f.message));oe(this,f);return}a=c||\"\";var e=new N(this.headers);\nd&&hd(d,function(a,b){e.set(b,a)});d=ua(e.O());c=k.FormData&&a instanceof k.FormData;!(0<=sa(ne,b))||d||c||e.set(\"Content-Type\",\"application/x-www-form-urlencoded;charset=utf-8\");e.forEach(function(a,b){this.a.setRequestHeader(b,a)},this);this.N&&(this.a.responseType=this.N);\"withCredentials\"in this.a&&this.a.withCredentials!==this.m&&(this.a.withCredentials=this.m);try{pe(this),0c&&(c=a.length);d=a.indexOf(\"?\");if(0>d||d>c){d=c;var e=\"\"}else e=a.substring(d+1,c);a=[a.substr(0,d),e,a.substr(c)];c=a[1];a[1]=b?c?c+\"&\"+b:b:c;a=a[0]+(a[1]?\"?\"+a[1]:\"\")+a[2]}return a}Q(a,b,c);return a};function we(a){this.ya=0;this.g=[];this.a=new qc;this.I=new Vd;this.ja=this.wa=this.F=this.ka=this.b=this.K=this.j=this.U=this.h=this.M=this.i=null;this.Ua=this.P=0;this.la=this.B=this.o=this.m=this.l=this.f=null;this.u=this.xa=this.N=-1;this.T=this.w=this.C=0;this.S=a&&a.supportsCrossDomainXhr||!1;this.J=\"\";this.c=new Yd(a&&a.concurrentRequestLimit);this.ma=new he;this.D=a&&void 0!==a.backgroundChannelTest?a.backgroundChannelTest:!0;this.Ta=a&&a.fastHandshake||!1;a&&a.Ea&&this.a.Ea()}g=we.prototype;\ng.oa=8;g.G=1;function xe(a){I(a.a,\"disconnect()\");ye(a);if(3==a.G){var b=a.P++,c=L(a.F);Q(c,\"SID\",a.J);Q(c,\"RID\",b);Q(c,\"TYPE\",\"terminate\");ze(a,c);b=new K(a,a.a,b,void 0);b.K=2;b.h=Tc(L(c));c=!1;k.navigator&&k.navigator.sendBeacon&&(c=k.navigator.sendBeacon(b.h.toString(),\"\"));!c&&k.Image&&((new Image).src=b.h,c=!0);c||(b.a=b.i.da(null),b.a.fa(b.h));b.D=t();Wc(b)}Ae(a)}\nfunction ye(a){a.B&&(a.B.abort(),a.B=null);a.b&&(a.b.cancel(),a.b=null);a.m&&(k.clearTimeout(a.m),a.m=null);Be(a);a.c.cancel();a.l&&(k.clearTimeout(a.l),a.l=null)}function Ce(a,b){1E3==a.g.length&&xc(a.a,function(){return\"Already have 1000 queued maps upon queueing \"+Db(b)});a.g.push(new Xd(a.Ua++,b));3==a.G&&De(a)}g.Ja=function(){return 0==this.G};function De(a){be(a.c)||a.l||(a.l=Ec(r(a.Oa,a),0),a.C=0)}\nfunction Ee(a,b){var c=a.c;if((c.b?1:c.a?c.a.s():0)>=a.c.f-(a.l?1:0))return xc(a.a,\"Unexpected retry request is scheduled.\"),!1;if(a.l)return I(a.a,\"Use the retry request that is already scheduled.\"),a.g=b.u.concat(a.g),!0;if(1==a.G||2==a.G||2<=a.C)return!1;I(a.a,\"Going to retry POST\");a.l=Ec(r(a.Oa,a,b),Fe(a,a.C));a.C++;return!0}\ng.Oa=function(a){this.l=null;I(this.a,\"startForwardChannel_\");if(1==this.G)if(a)xc(this.a,\"Not supposed to retry the open\");else{I(this.a,\"open_()\");this.P=Math.floor(1E5*Math.random());a=this.P++;var b=new K(this,this.a,a,void 0),c=this.i;this.M&&(c?(c=Ea(c),Ga(c,this.M)):c=this.M);null===this.h&&(b.j=c);var d=Ge(this,b),e=L(this.F);Q(e,\"RID\",a);Q(e,\"CVER\",21);this.D&&this.j&&Q(e,\"X-HTTP-Session-Id\",this.j);ze(this,e);this.h&&c&&ve(e,this.h,c);ae(this.c,b);this.Ta?(Q(e,\"$req\",d),Sc(b,e,null)):Sc(b,\ne,d);this.G=2}else 3==this.G&&(a?He(this,a):0==this.g.length?I(this.a,\"startForwardChannel_ returned: nothing to send\"):be(this.c)?xc(this.a,\"startForwardChannel_ returned: connection already in progress\"):(He(this),I(this.a,\"startForwardChannel_ finished, sent request\")))};\nfunction He(a,b){var c;b?c=b.f:c=a.P++;var d=L(a.F);Q(d,\"SID\",a.J);Q(d,\"RID\",c);Q(d,\"AID\",a.N);ze(a,d);a.h&&a.i&&ve(d,a.h,a.i);c=new K(a,a.a,c,a.C+1);null===a.h&&(c.j=a.i);b&&(a.g=b.u.concat(a.g));b=Ge(a,c);c.setTimeout(1E4+Math.round(1E4*Math.random()));ae(a.c,c);Sc(c,d,b)}function ze(a,b){a.f&&hd({},function(a,d){Q(b,d,a)})}\nfunction Ge(a,b){var c=Math.min(a.g.length,1E3),d=a.f?r(a.f.Va,a.f,a):null;a:for(var e=a.g,f=-1;;){var h=[\"count=\"+c];-1==f?0G)f=Math.max(0,e[v].a-100),m=!1;else try{ie(Z,h,\"req\"+G+\"_\")}catch(Mb){d&&d(Z)}}if(m){d=h.join(\"&\");break a}}a=a.g.splice(0,c);b.u=a;return d}function Ie(a){if(!a.b&&!a.m){a.T=1;var b=a.Na;Tb||Ub();Wb||(Tb(),Wb=!0);Pb.add(b,a);a.w=0}}\nfunction Je(a){if(a.b||a.m)return xc(a.a,\"Request already in progress\"),!1;if(3<=a.w)return!1;I(a.a,\"Going to retry GET\");a.T++;a.m=Ec(r(a.Na,a),Fe(a,a.w));a.w++;return!0}\ng.Na=function(){this.m=null;I(this.a,\"Creating new HttpRequest\");this.b=new K(this,this.a,\"rpc\",this.T);null===this.h&&(this.b.j=this.i);this.b.P=0;var a=L(this.wa);Q(a,\"RID\",\"rpc\");Q(a,\"SID\",this.J);Q(a,\"CI\",this.la?\"0\":\"1\");Q(a,\"AID\",this.N);ze(this,a);Q(a,\"TYPE\",\"xmlhttp\");this.h&&this.i&&ve(a,this.h,this.i);Vc(this.b,a,!0,this.ja);I(this.a,\"New Request created\")};\nfunction Sd(a,b,c){I(a.a,\"Test Connection Finished\");var d=b.m;d&&$d(a.c,d);a.la=c;a.u=b.f;I(a.a,\"connectChannel_()\");a.F=Ke(a,a.ka);De(a)}function Ud(a,b){I(a.a,\"Test Connection Failed\");a.u=b.f;V(a,2)}\ng.Ma=function(a,b){if(0!=this.G&&(this.b==a||ce(this.c,a)))if(this.u=a.C,ce(this.c,a)&&3==this.G){try{var c=this.ma.a.parse(b)}catch(f){c=null}if(n(c)&&3==c.length)if(b=c,0==b[0])a:if(I(this.a,\"Server claims our backchannel is missing.\"),this.m)I(this.a,\"But we are currently starting the request.\");else{if(this.b)if(this.b.D+3E3b&&this.la&&0==this.w&&!this.o&&(this.o=Ec(r(this.bb,this),6E3)));else I(this.a,\"Bad POST response data returned\"),V(this,11)}else if(this.b==a&&Be(this),!/^[\\s\\xa0]*$/.test(b))for(b=c=this.ma.a.parse(b),c=0;cthis.c)throw Error(We);this.a=new Te;this.b=new S;this.g=null;this.ba()}u(Ve,w);var We=\"[goog.structs.Pool] Min can not be greater than max\";g=Ve.prototype;g.ea=function(){var a=t();if(!(null!=this.g&&0>a-this.g)){for(var b;0this.c&&0=this.s()){for(var c=this.a,d=0;d>1,a[d].a>c.a)a[b]=a[d],b=d;else break;a[b]=c}Ze.prototype.v=function(){for(var a=this.a,b=[],c=a.length,d=0;d=e)f=void 0;else{if(1==e)wa(d);else{d[0]=d.pop();d=0;c=c.a;e=c.length;for(var h=c[d];d>1;){var m=2*d+1,v=2*d+2;m=vh.a)break;c[d]=c[m];d=m}c[d]=h}f=f.b}f.apply(this,[b])}else break}};\ng.na=function(a){X.H.na.call(this,a);this.sa()};g.ba=function(){X.H.ba.call(this);this.sa()};g.A=function(){X.H.A.call(this);k.clearTimeout(void 0);wa(this.f.a);this.f=null};function Y(a,b,c,d){this.l=a;this.j=!!d;X.call(this,b,c)}u(Y,X);Y.prototype.qa=function(){var a=new T,b=this.l;b&&b.forEach(function(b,d){a.headers.set(d,b)});this.j&&(a.m=!0);return a};Y.prototype.ta=function(a){return!a.i&&!a.a};Oe.prototype.createWebChannel=Oe.prototype.a;W.prototype.send=W.prototype.$a;W.prototype.open=W.prototype.Za;W.prototype.close=W.prototype.close;Fc.NO_ERROR=0;Fc.TIMEOUT=8;Fc.HTTP_ERROR=6;Gc.COMPLETE=\"complete\";Md.EventType=Nd;Nd.OPEN=\"a\";Nd.CLOSE=\"b\";Nd.ERROR=\"c\";Nd.MESSAGE=\"d\";B.prototype.listen=B.prototype.aa;Y.prototype.getObject=Y.prototype.ea;Y.prototype.releaseObject=Y.prototype.ib;T.prototype.listenOnce=T.prototype.Ha;T.prototype.getLastError=T.prototype.ab;T.prototype.getLastErrorCode=T.prototype.Fa;\nT.prototype.getStatus=T.prototype.W;T.prototype.getStatusText=T.prototype.Ga;T.prototype.getResponseJson=T.prototype.Ya;T.prototype.getResponseText=T.prototype.V;T.prototype.getResponseText=T.prototype.V;T.prototype.send=T.prototype.fa;module.exports={createWebChannelTransport:Se,ErrorCode:Fc,EventType:Gc,WebChannel:Md,XhrIoPool:Y};}).call(typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : {})\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../webchannel-wrapper/dist/index.js\n// module id = 115\n// module chunks = 1"],"sourceRoot":""}