{"version":3,"sources":["webpack:///./node_modules/@firebase/functions/dist/index.cjs.js","webpack:///./src/gmap/gmaps.js","webpack:///./node_modules/@firebase/storage/dist/index.esm.js","webpack:///./node_modules/@firebase/database/dist/index.cjs.js","webpack:///./src/views/vesselTracking/VesselGroup.vue?b5f8","webpack:///src/views/vesselTracking/VesselGroup.vue","webpack:///./src/views/vesselTracking/VesselGroup.vue?8c35","webpack:///./src/views/vesselTracking/VesselGroup.vue","webpack:///./node_modules/@firebase/performance/dist/index.cjs.js","webpack:///./node_modules/@firebase/installations/dist/index.esm.js","webpack:///./node_modules/@firebase/messaging/dist/index.esm.js","webpack:///./node_modules/firebase/dist/index.cjs.js","webpack:///./node_modules/idb/build/idb.js","webpack:///./node_modules/@firebase/logger/dist/index.esm.js","webpack:///./node_modules/@firebase/webchannel-wrapper/dist/index.esm.js","webpack:///./node_modules/@firebase/firestore/dist/index.cjs.js"],"names":["_interopDefault","ex","Object","defineProperty","exports","value","firebase","tslib_1","errorCodeMap","OK","CANCELLED","UNKNOWN","INVALID_ARGUMENT","DEADLINE_EXCEEDED","NOT_FOUND","ALREADY_EXISTS","PERMISSION_DENIED","UNAUTHENTICATED","RESOURCE_EXHAUSTED","FAILED_PRECONDITION","ABORTED","OUT_OF_RANGE","UNIMPLEMENTED","INTERNAL","UNAVAILABLE","DATA_LOSS","HttpsErrorImpl","_super","code","message","details","_this","call","this","setPrototypeOf","prototype","__extends","Error","codeForHTTPStatus","status","_errorForResponse","bodyJSON","serializer","description","undefined","errorJSON","error","status_1","decode","e","ContextProvider","app","getAuthToken","__awaiter","token","__generator","_a","label","trys","push","getToken","sent","accessToken","getInstanceIdToken","messaging","getContext","authToken","instanceIdToken","LONG_TYPE","UNSIGNED_LONG_TYPE","mapValues","o","f","result","key","hasOwnProperty","Serializer","encode","data","Number","valueOf","isFinite","toString","Array","isArray","map","x","json","parseFloat","isNaN","failAfter","millis","Promise","_","reject","setTimeout","Service","app_","region_","emulatorOrigin","delete","deleteService","contextProvider","cancelAllRequests","resolve","get","enumerable","configurable","_url","name","projectId","options","region","origin_1","useFunctionsEmulator","origin","httpsCallable","callable","postJSON","url","body","headers","response","append","fetch","method","JSON","stringify","context","timeout","responseData","decodedData","Headers","race","FUNCTIONS_TYPE","factory","unused","registerFunctions","instance","namespaceExports","Functions","registerService","resolveInitPromise","rejectInitPromise","API_KEY","CALLBACK_NAME","initialized","window","google","initPromise","init","script","document","createElement","async","defer","src","concat","onerror","querySelector","appendChild","DEFAULT_HOST","CONFIG_STORAGE_BUCKET_KEY","DEFAULT_MAX_OPERATION_RETRY_TIME","DEFAULT_MAX_UPLOAD_RETRY_TIME","MIN_SAFE_INTEGER","FirebaseStorageError","code_","prependCode","message_","serverResponse_","name_","codeProp","codeEquals","serverResponseProp","setServerResponseProp","serverResponse","Code","OBJECT_NOT_FOUND","BUCKET_NOT_FOUND","PROJECT_NOT_FOUND","QUOTA_EXCEEDED","UNAUTHORIZED","RETRY_LIMIT_EXCEEDED","INVALID_CHECKSUM","CANCELED","INVALID_EVENT_NAME","INVALID_URL","INVALID_DEFAULT_BUCKET","NO_DEFAULT_BUCKET","CANNOT_SLICE_BLOB","SERVER_FILE_WRONG_SIZE","NO_DOWNLOAD_URL","INVALID_ARGUMENT_COUNT","APP_DELETED","INVALID_ROOT_OPERATION","INVALID_FORMAT","INTERNAL_ERROR","unknown","objectNotFound","path","quotaExceeded","bucket","unauthenticated","unauthorized","retryLimitExceeded","canceled","invalidUrl","invalidDefaultBucket","cannotSliceBlob","serverFileWrongSize","noDownloadURL","invalidArgument","index","fnName","invalidArgumentCount","argMin","argMax","real","countPart","plural","appDeleted","invalidRootOperation","invalidFormat","format","internalError","StringFormat","RAW","BASE64","BASE64URL","DATA_URL","formatValidator","stringFormat","StringData","opt_contentType","contentType","dataFromString","string","utf8Bytes_","base64Bytes_","dataURLBytes_","dataURLContentType_","b","i","length","c","charCodeAt","valid","hi","lo","Uint8Array","percentEncodedBytes_","decoded","decodeURIComponent","hasMinus","indexOf","hasUnder","invalidChar","hasPlus","hasSlash","replace","bytes","atob","array","DataURLParts","dataURL","base64","matches","match","middle","endsWith","substring","rest","parts","s","end","longEnough","ErrorCode","TaskEvent","STATE_CHANGED","InternalTaskState","RUNNING","PAUSING","PAUSED","SUCCESS","CANCELING","ERROR","TaskState","taskStateFromInternalTaskState","state","contains","obj","prop","forEach","clone","val","make","resolver","isDef","p","isJustDef","isFunction","isObject","isNonNullObject","isNonArrayObject","isString","String","isNumber","isNativeBlob","isNativeBlobDefined","Blob","NetworkXhrIo","sent_","xhr_","XMLHttpRequest","errorCode_","NO_ERROR","sendPromise_","addEventListener","event","ABORT","NETWORK_ERROR","send","opt_body","opt_headers","open","setRequestHeader","getErrorCode","getStatus","getResponseText","responseText","abort","getResponseHeader","header","addUploadProgressListener","listener","upload","removeUploadProgressListener","removeEventListener","XhrIoPool","createXhrIo","jsonObjectOrNull","parse","Location","path_","fullServerUrl","encodeURIComponent","bucketOnlyServerUrl","makeFromBucketSpec","bucketString","bucketLocation","makeFromUrl","location","bucketDomain","gsModify","loc","charAt","slice","gsPath","gsRegex","RegExp","gsIndices","httpModify","version","hostRegex","httpRegex","httpIndices","groups","regex","indices","postModify","group","captures","exec","bucketValue","pathValue","parent","lastIndexOf","newPath","child","childPath","canonicalChildPath","split","filter","component","join","lastComponent","makeUrl","urlPart","makeQueryString","params","queryPart","nextPart","noXform_","metadata","Mapping","server","opt_local","opt_writable","opt_xform","local","writable","xform","mappings_","xformPath","fullPath","getMappings","mappings","mappingsXformPath","nameMapping","xformSize","size","sizeMapping","addRef","authWrapper","generateRef","makeStorageReference","fromResource","resource","len","mapping","fromResourceString","resourceString","downloadUrlFromResourceString","tokens","tokensList","urls","base","queryString","alt","toResourceString","metadataValidator","validType","validate","specs","passed","minArgs","maxArgs","optional","validLength","validator","ArgSpec","opt_optional","self","and_","v1","v2","stringSpec","opt_validator","stringValidator","uploadDataSpec","ArrayBuffer","metadataSpec","nonNegativeNumberSpec","looseObjectSpec","isLooseObject","nullFunctionSpec","getBlobBuilder","BlobBuilder","WebKitBlobBuilder","getBlob","var_args","_i","arguments","bb","sliceBlob","blob","start","webkitSlice","mozSlice","FbsBlob","opt_elideCopy","blobType","data_","type","byteLength","set","size_","type_","startByte","endByte","realBlob","sliced","buffer","blobby","apply","uint8Arrays","finalLength_1","merged_1","index_1","uploadData","contains$1","elem","clone$1","arraylike","remove","splice","RequestInfo","handler","urlParams","errorHandler","progressCallback","successCodes","additionalRetryCodes","handlerCheck","cndn","metadataHandler","xhr","text","downloadUrlHandler","sharedErrorHandler","err","newErr","objectErrorHandler","shared","getMetadata","maxOperationRetryTime","requestInfo","getDownloadUrl","updateMetadata","deleteObject","determineContentType_","metadataForUpload_","opt_metadata","multipartUpload","genBoundary","str","Math","random","boundary","metadataString","preBlobPart","postBlobPart","maxUploadRetryTime","ResumableUploadStatus","current","total","finalized","checkResumeHeader_","opt_allowed","allowed","createResumableUpload","getResumableUploadStatus","sizeString","parseInt","resumableUploadChunkSize","continueResumableUpload","chunkSize","opt_status","opt_progressCallback","bytesLeft","bytesToUpload","min","uploadCommand","uploadStatus","newCurrent","Observer","nextOrObserver","opt_error","opt_complete","asFunctions","next","complete","observer","UploadTaskSnapshot","bytesTransferred","totalBytes","task","ref","argsToForward","then","UploadTask","transferred_","needToFetchStatus_","needToFetchMetadata_","observers_","error_","uploadUrl_","request_","chunkMultiplier_","resolve_","reject_","ref_","authWrapper_","location_","blob_","metadata_","resumable_","shouldDoResumable_","state_","errorHandler_","completeTransitions_","transition_","metadataErrorHandler_","promise_","start_","makeProgressCallback_","sizeBefore","loaded","updateProgress_","createResumable_","fetchStatus_","fetchMetadata_","continueUpload_","oneShotUpload_","resolveToken_","callback","createRequest","makeRequest","getPromise","statusRequest","uploadRequest","newStatus","increaseMultiplier_","currentSize","metadataRequest","multipartRequest","transferred","old","notifyObservers_","cancel","wasPaused","externalState","on","completed","typeValidator","_p","nextOrObserverMessage","nextValidator","observerValidator","nextOrObserverValidator","anyDefined","makeBinder","binder","addObserver_","removeObserver_","binderNextOrObserverValidator","binderSpecs","typeOnly","onFulfilled","onRejected","catch","notifyObserver_","finishPromise_","observers","triggered","bind","snapshot","toCall","resume","pause","Reference","newRef","service","put","throwIfRoot_","putString","getDownloadURL","FailRequest","appDelete","RequestMap","map_","id_","addRequest","r","id","unmap","clear","AuthWrapper","maker","requestMaker","pool","bucket_","deleted_","extractBucket_","storageRefMaker_","requestMaker_","pool_","service_","maxOperationRetryTime_","maxUploadRetryTime_","requestMap_","config","_error","request","deleteApp","setMaxUploadRetryTime","time","setMaxOperationRetryTime","waitSeconds","timeoutId","hitTimeout","cancelState","triggeredCallback","triggerCallback","callWithDelay","success","waitMillis","mustStop","stopped","stop","wasTimeout","clearTimeout","NetworkRequest","errorCallback","pendingXhr_","backoffId_","canceled_","appDelete_","url_","method_","headers_","body_","successCodes_","additionalRetryCodes_","callback_","errorCallback_","progressCallback_","timeout_","doTheRequest","backoffCallback","RequestEndStatus","progressListener","hitServer","isRetryStatusCode_","successCode","wasCanceled","progressEvent","lengthComputable","backoffDone","requestWentThrough","wasSuccessCode","isFiveHundredCode","extraRetryCodes","isExtraRetryCode","isRequestSpecificRetryCode","opt_canceled","addAuthHeader_","addVersionHeader_","number","SDK_VERSION","authWrapperBucket","internals_","ServiceInternals","test","refFromURL","STORAGE_TYPE","opt_url","registerStorage","Storage","util","logger$1","DOMStorageWrapper","domStorage_","prefix_","removeItem","prefixedName_","setItem","storedVal","getItem","jsonEval","MemoryStorage","cache_","isInMemoryStorage","createStoragefor","domStorageName","domStorage","PersistentStorage","SessionStorage","logClient","Logger","LUIDGenerator","sha1","utf8Bytes","stringToByteArray","Sha1","update","sha1Bytes","digest","encodeByteArray","buildLogMessage_","logger","firstLog_","enableLogging","logger_","persistent","assert","logLevel","LogLevel","VERBOSE","log","logWrapper","prefix","fatal","warn","warnIfPageIsSecure","protocol","isInvalidJSONNumber","POSITIVE_INFINITY","NEGATIVE_INFINITY","executeWhenDOMReady","fn","isNodeSdk","readyState","called_1","wrappedFn_1","floor","attachEvent","MIN_NAME","MAX_NAME","nameCompare","a","aAsInt","tryParseInt","bAsInt","stringCompare","requireKey","ObjectToUniqueKey","keys","k","sort","splitStringBySize","segsize","dataSegs","each","doubleToIEEE754String","v","ln","bits","ebits","fbits","bias","Infinity","abs","pow","LN2","round","reverse","hexByteString","hexByte","substr","toLowerCase","isChromeExtensionContentScript","href","isWindowsStoreApp","Windows","UI","errorForServerCode","query","reason","toUpperCase","INTEGER_REGEXP_","intVal","exceptionGuard","stack","beingCrawled","userAgent","search","setTimeoutNonBlocking","Path","pathOrString","pieceNum","pieces_","copyTo","pieceNum_","getFront","getLength","popFront","getBack","pathString","toUrlEncodedString","begin","pieces","childPathObj","childPieces","isEmpty","relativePath","outerPath","innerPath","outer","inner","comparePaths","left","right","leftKeys","rightKeys","cmp","equals","other","j","ValidationPath","errorPrefix_","parts_","byteLength_","max","stringLength","checkValid_","pop","last","MAX_PATH_LENGTH_BYTES","MAX_PATH_DEPTH","toErrorString","PROTOCOL_VERSION","VERSION_PARAM","TRANSPORT_SESSION_PARAM","REFERER_PARAM","FORGE_REF","FORGE_DOMAIN","LAST_SESSION_PARAM","WEBSOCKET","LONG_POLLING","RepoInfo","host","secure","namespace","webSocketOnly","persistenceKey","domain","internalHost","needsQueryParam","isCustomHost","isCacheableHost","isDemoHost","updateHost","newHost","connectionURL","connURL","pairs","toURLString","decodePath","pathStringDecoded","piece","decodeQuery","results","segment","kv","__EMPTY_NODE","MAX_NODE","parseRepoInfo","parsedUrl","parseURL","subdomain","scheme","repoInfo","port","colonInd","slashInd","questionMarkInd","queryParams","INVALID_KEY_REGEX_","INVALID_PATH_REGEX_","MAX_LEAF_SIZE_","isValidKey","isValidPathString","isValidRootPathString","isValidPriority","priority","validateFirebaseDataArg","argumentNumber","validateFirebaseData","errorPrefix","hasDotValue_1","hasActualChild_1","validateFirebaseMergePaths","mergePaths","curPath","prevPath","validateFirebaseMergeDataArg","validatePriority","validateEventType","eventType","validateKey","validatePathString","validateRootPathString","validateWritablePath","validateUrl","validateBoolean","bool","OnDisconnect","repo_","onComplete","validateArgCount","validateCallback","deferred","Deferred","onDisconnectCancel","wrapCallback","promise","onDisconnectSet","setWithPriority","onDisconnectSetWithPriority","objectToMerge","newObjectToMerge","onDisconnectUpdate","TransactionResult","committed","toJSON","nextPushId","PUSH_CHARS","lastPushTime","lastRandChars","now","duplicateTime","timeStampChars","NamedNode","node","Wrap","Index","getCompare","compare","indexedValueChanged","oldNode","newNode","oldWrapped","newWrapped","minPost","MIN","KeyIndex","isDefinedOn","assertionError","maxPost","makePost","indexValue","KEY_INDEX","setMaxNode","__childrenNodeConstructor","nodeFromJSON","MAX_NODE$1","priorityHashText","validatePriorityNode","priorityNode","isLeafNode","getPriority","LeafNode","value_","priorityNode_","EMPTY_NODE","lazyHash_","updatePriority","newPriorityNode","getImmediateChild","childName","getChild","hasChild","getPredecessorChildName","childNode","updateImmediateChild","newChildNode","updateChild","front","numChildren","forEachChild","action","exportFormat","getValue","hash","toHash","compareTo","compareToLeafNode_","otherLeaf","otherLeafType","thisLeafType","otherIndex","VALUE_TYPE_ORDER","thisIndex","withIndex","isIndexed","setNodeFromJSON","setMaxNode$1","_defaultIndexMap","PriorityIndex","aPriority","bPriority","indexCmp","PRIORITY_INDEX","SortedMapIterator","startKey","comparator","isReverse_","resultGenerator_","nodeStack_","getNext","hasNext","peek","LLRBNode","color","RED","SortedMap","copy","count","inorderTraversal","reverseTraversal","min_","minKey","maxKey","insert","n","fixUp_","removeMin_","isRed_","moveRedLeft_","smallest","rotateRight_","moveRedRight_","rotateLeft_","colorFlip_","nl","nr","checkMaxDepth_","blackDepth","check_","BLACK","LLRBEmptyNode","comparator_","root_","getPredecessorKey","rightParent","getIterator","resultGenerator","getIteratorFrom","getReverseIteratorFrom","getReverseIterator","LOG_2","Base12Num","logBase2","num","bitMask","current_","mask","bits_","nextBitIsOne","buildChildSet","childList","keyFn","mapSortFn","buildBalancedTree","low","high","namedNode","buildFrom12Array","base12","root","buildPennant","childTree","attachPennant","pennant","isOne","fallbackObject","IndexMap","indexes_","indexSet_","indexKey","sortedMap","safeGet","hasIndex","indexDefinition","addIndex","existingChildren","newIndex","sawIndexedValue","iter","indexName","newIndexSet","newIndexes","addToIndexes","indexedChildren","existingSnap","newChildren","removeFromIndexes","NAME_ONLY_COMPARATOR","NAME_COMPARATOR","ChildrenNode","children_","indexMap_","Default","newIndexMap","newPriority","newImmediateChild","numKeys","allIntegerKeys","toHash_1","childHash","idx","resolveIndex_","predecessor","getFirstChildName","getFirstChild","getLastChildName","getLastChild","wrappedNode","startPost","iterator","endPost","MAX_NODE$2","otherChildrenNode","thisIter","otherIter","thisCurrent","otherCurrent","MaxNode","defineProperties","MAX","USE_HINZE","nodeFromJSON$1","jsonLeaf","node_1","jsonObj_1","childData","children_1","childrenHavePriority_1","hinzeJsonObj_1","childSet","sortedChildSet","__referenceConstructor","OperationType","ValueIndex","valueNode","VALUE_INDEX","PathIndex","indexPath_","extractChild","snap","aChild","bChild","DataSnapshot","node_","index_","exportVal","exists","childPathString","childRef","childrenNode","hasChildren","getKey","getRef","DataEvent","eventRegistration","prevName","getPath","getParent","getEventType","getEventRunner","CancelEvent","ValueEventRegistration","cancelCallback_","context_","respondsTo","createEvent","change","getQueryParams","getIndex","snapshotNode","eventData","ctx","cancelCB_1","cb_1","createCancelEvent","hasAnyCallback","ChildEventRegistration","callbacks_","eventToCheck","cancelCB_2","cb_2","otherCount","getCount","thisCount","otherKey","getAnyKey","thisKey","every","cb","Query","repo","queryParams_","orderByCalled_","validateQueryEndpoints_","startNode","endNode","hasStart","getIndexStartValue","hasEnd","getIndexEndValue","tooManyArgsError","wrongArgTypeError","startName","getIndexStartName","endName","getIndexEndName","validateLimit_","hasLimit","hasAnchoredLimit","validateNoPreviousOrderByCall_","cancelCallbackOrContext","ret","getCancelAndContextArgs_","onValueEvent","callbacks","onChildEvent","cancelCallback","container","addEventCallbackForQuery","off","validateContextObject","valueCallback","removeEventCallbackForQuery","once","userCallback","cancelOrContext","firstCall","onceCallback","limitToFirst","limit","limitToLast","orderByChild","parsedPath","newParams","orderBy","orderByKey","orderByPriority","orderByValue","startAt","endAt","equalTo","queryObject","getQueryObject","queryIdentifier","isEqual","sameRepo","samePath","sameQueryIdentifier","CountedSet","add","item","SparseSnapshotTree","find","childKey","remember","forget","self_1","tree","safeToRemove","forEachTree","prefixPath","func","generateWithValues","values","Date","getTime","resolveDeferredValue","serverValues","resolveDeferredValueTree","resolvedTree","resolveDeferredValueSnapshot","rawPri","leafNode","emptyChildrenSingleton","__referenceConstructor$1","OperationSource","fromUser","fromServer","queryId","tagged","User","Server","forServerTaggedQuery","AckUserWrite","affectedTree","revert","ACK_USER_WRITE","source","operationForChild","children","subtree","Empty","EmptyChildren","ImmutableTree","fromObject","childSnap","findRootMostMatchingPathAndValue","predicate","childExistingPathAndValue","findRootMostValueAndPath","toSet","newChild","setTree","newTree","fold","fold_","pathSoFar","accum","findOnPath","findOnPath_","pathToFollow","nextChild","foreachOnPath","foreachOnPath_","currentRelativePath","foreach","foreach_","foreachChild","ListenComplete","LISTEN_COMPLETE","Overwrite","OVERWRITE","Merge","MERGE","CacheNode","fullyInitialized_","filtered_","isFullyInitialized","isFiltered","isCompleteForPath","isCompleteForChild","getNode","ViewCache","eventCache_","serverCache_","updateEventSnap","eventSnap","filtered","updateServerSnap","serverSnap","getEventCache","getCompleteEventSnap","getServerCache","getCompleteServerSnap","Change","oldSnap","valueChange","VALUE","childAddedChange","CHILD_ADDED","childRemovedChange","CHILD_REMOVED","childChangedChange","newSnapshot","oldSnapshot","CHILD_CHANGED","childMovedChange","CHILD_MOVED","IndexedFilter","affectedPath","optChangeAccumulator","oldChild","trackChildChange","updateFullNode","newSnap","filtersNodes","getIndexedFilter","ChildChangeAccumulator","changeMap_","oldChange","oldType","getChanges","getValues","NoCompleteChildSource_","getCompleteChild","getChildAfterChild","NO_COMPLETE_CHILD_SOURCE","WriteTreeCompleteChildSource","writes_","viewCache_","optCompleteServerCache_","serverNode","calcCompleteChild","completeServerData","nodes","calcIndexedSlice","ProcessorResult","viewCache","changes","ViewProcessor","filter_","assertIndexed","applyOperation","oldViewCache","operation","writesCache","completeCache","newViewCache","filterServerNode","accumulator","overwrite","applyUserOverwrite_","applyServerOverwrite_","merge","applyUserMerge_","applyServerMerge_","ackUserWrite","revertUserWrite_","ackUserWrite_","listenComplete_","maybeAddValueEvent_","isLeafOrEmpty","oldCompleteSnap","generateEventCacheAfterServerEvent_","changePath","oldEventSnap","shadowingWrite","newEventCache","serverCache","completeChildren","completeEventChildren","calcCompleteEventChildren","completeNode","calcCompleteEventCache","oldEventNode","updatedPriority","calcEventCacheAfterServerOverwrite","childChangePath","newEventChild","eventChildUpdate","changedSnap","newServerCache","oldServerSnap","serverFilter","newServerNode","newEventSnap","cacheHasChild_","changedChildren","curViewCache","writePath","applyMerge_","viewMergeTree","serverChild","childMergeTree","isUnknownDeepMerge","ackPath","changedChildren_1","changedChildren_2","mergePath","serverCachePath","oldServerNode","completeServerCache","oldEventCache","serverChildren","EventGenerator","query_","generateEventsForChanges","eventCache","eventRegistrations","events","moves","generateEventsForType_","registrations","filteredChanges","compareChanges_","materializedChange","materializeSingleChange_","registration","aWrapped","bWrapped","View","initialViewCache","eventRegistrations_","indexFilter","getNodeFilter","processor_","initialServerCache","initialEventCache","eventGenerator_","getQuery","getCompleteServerCache","cache","loadsAllData","addEventRegistration","removeEventRegistration","cancelError","cancelEvents","path_1","maybeEvent","remaining","existing","generateEventsForChanges_","getInitialEvents","initialChanges","eventNode","SyncPoint","views_","optCompleteServerCache","view","events_1","serverCacheComplete","eventCacheComplete","removed","hadCompleteView","hasCompleteView","viewQueryId","getQueryViews","viewForQuery","getCompleteView","viewExistsForQuery","completeView","findValue","CompoundWrite","writeTree_","addWrite","rootmost","rootMostPath","newWriteTree","addWrites","updates","newWrite","removeWrite","hasCompleteWrite","getCompleteNode","getCompleteChildren","childCompoundWrite","shadowingNode","applySubtreeWrite_","writeTree","priorityWrite_1","WriteTree","visibleWrites_","allWrites_","lastWriteId_","childWrites","WriteTreeRef","addOverwrite","writeId","visible","addMerge","getWrite","record","findIndex","writeToRemove","removedWriteWasVisible","removedWriteOverlapsWithOtherWrites","currentWrite","recordContainsPath_","resetTree_","getCompleteWriteData","treePath","writeIdsToExclude","includeHiddenWrites","write","mergeAtPath","layerTree_","layeredCache","subMerge","completeServerChildren","topLevelSet","merge_1","existingEventSnap","existingServerSnap","childMerge","toIterate","writeRecord","findKey","DefaultFilter_","writes","treeRoot","compoundWrite","deepNode","treePath_","existingServerCache","SyncTree","listenProvider_","syncPointTree_","pendingWriteTree_","tagToQueryMap_","queryToTagMap_","applyUserOverwrite","newData","applyOperationToSyncPoints_","applyUserMerge","changeTree","needToReevaluate","affectedTree_1","applyServerOverwrite","applyServerMerge","applyListenComplete","applyTaggedQueryOverwrite","tag","queryKey","queryKeyForTag_","parseQueryKey_","queryPath","op","applyTaggedOperation_","applyTaggedQueryMerge","applyTaggedListenComplete","foundAncestorDefaultView","pathToSyncPoint","sp","syncPoint","childSyncPoint","viewAlreadyExists","makeQueryKey_","getNextQueryTag_","setupListener_","maybeSyncPoint","removedAndEvents","removingDefault","covered","parentSyncPoint","newViews","collectDistinctViewsForSubTree_","newQuery","createListenerForView_","startListening","queryForListening_","tagForQuery_","hashFn","defaultTag","stopListening","queryToRemove","tagToRemove","removeTags_","includeHiddenSets","maybeChildSyncPoint","childMap","views_1","childViews","queries","removedQuery","removedQueryKey","removedQueryTag","isDefault","queriesToStop","queries_1","childQueries","queryToStop","splitIndex","nextQueryTag_","applyOperationHelper_","syncPointTree","applyOperationDescendantsHelper_","childOperation","childServerCache","childWritesCache","SnapshotHolder","rootNode_","updateSnapshot","newSnapshotNode","AuthTokenProvider","forceRefresh","addTokenChangeListener","removeTokenChangeListener","notifyForInvalidToken","errorMessage","StatsCollection","counters_","incrementCounter","amount","deepCopy","StatsManager","getCollection","hashString","collections_","getOrCreateReporter","creatorFunction","reporters_","StatsListener","collection_","last_","newStats","delta","stat","FIRST_STATS_MIN_TIME","FIRST_STATS_MAX_TIME","REPORT_STATS_INTERVAL","StatsReporter","collection","server_","statsToReport_","statsListener_","reportStats_","includeStat","stats","reportedStats","haveStatsToReport","reportStats","EventQueue","eventLists_","recursionDepth_","queueEvents","eventDataList","currList","eventPath","EventList","raiseEventsAtPath","raiseQueuedEventsMatchingPredicate_","raiseEventsForChangedPath","changedPath","sentAll","eventList","raise","events_","eventFn","EventEmitter","allowedEvents_","listeners_","trigger","listeners","validateEventType_","getInitialEvent","et","VisibilityMonitor","hidden","visibilityChange","visible_","getInstance","OnlineMonitor","online_","isMobileCordova","currentlyOnline","PacketReceiver","onMessage_","pendingResponses","currentResponseNum","closeAfterResponse","onClose","closeAfter","responseNum","handleResponse","requestNum","_loop_1","toProcess","this_1","_loop_2","state_1","FIREBASE_LONGPOLL_START_PARAM","FIREBASE_LONGPOLL_CLOSE_COMMAND","FIREBASE_LONGPOLL_COMMAND_CB_NAME","FIREBASE_LONGPOLL_DATA_CB_NAME","FIREBASE_LONGPOLL_ID_PARAM","FIREBASE_LONGPOLL_PW_PARAM","FIREBASE_LONGPOLL_SERIAL_PARAM","FIREBASE_LONGPOLL_CALLBACK_ID_PARAM","FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM","FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET","FIREBASE_LONGPOLL_DATA_PARAM","FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM","FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM","MAX_URL_DATA_SIZE","SEG_HEADER_SIZE","MAX_PAYLOAD_SIZE","KEEPALIVE_REQUEST_INTERVAL","LP_CONNECT_TIMEOUT","BrowserPollConnection","connId","transportSessionId","lastSessionId","bytesSent","bytesReceived","everConnected_","log_","stats_","urlFn","onMessage","onDisconnect","curSegmentNum","onDisconnect_","myPacketOrderer","isClosed_","connectTimeoutTimer_","onClosed_","scriptTagHolder","FirebaseIFrameScriptHolder","args","command","arg1","arg2","incrementIncomingBytes_","password","sendNewPolls","pN","uniqueCallbackIdentifier","connectURL","addTag","startLongPoll","addDisconnectPingFrame","forceAllow","forceAllow_","forceDisallow","forceDisallow_","isAvailable","markConnectionHealthy","shutdown_","close","myDisconnFrame","removeChild","dataStr","base64data","base64Encode","enqueueSegment","pw","style","display","commandCB","onMessageCB","outstandingRequests","pendingSegs","currentSerial","myIFrame","createIFrame_","currentDomain","iframeContents","doc","iframe","contentWindow","contentDocument","alive","innerHTML","myID","myPW","theURL","nodeRestRequest","newRequest_","curDataString","nextSeg","d","theSeg","shift","seg","ts","addLongPollTag_","segnum","totalsegs","serial","doNewRequest","keepaliveTimeout","readyStateCB","loadCB","doNodeLongPoll","newScript_1","onload","onreadystatechange","rstate","parentNode","WEBSOCKET_MAX_FRAME_SIZE","WEBSOCKET_KEEPALIVE_INTERVAL","WebSocketImpl","MozWebSocket","WebSocket","WebSocketConnection","keepaliveTimer","frames","totalFrames","connectionURL_","device","CONSTANTS","NODE_ADMIN","process","platform","env","proxy","mySock","onopen","onclose","onmessage","m","handleIncomingFrame","isOldAndroid","navigator","oldAndroidRegex","oldAndroidMatch","previouslyFailed","appendFrame_","fullMess","jsonMess","handleNewFrameCount_","frameCount","extractFrameCount_","mess","resetKeepAlive","remainingData","sendString_","clearInterval","setInterval","responsesRequiredToBeHealthy","healthyTimeout","TransportManager","initTransports_","isWebSocketsAvailable","isSkipPollConnection","transports_","transports_1","ALL_TRANSPORTS","transport","initialTransport","upgradeTransport","UPGRADE_TIMEOUT","DELAY_BEFORE_SENDING_EXTRA_REQUESTS","BYTES_SENT_HEALTHY_OVERRIDE","BYTES_RECEIVED_HEALTHY_OVERRIDE","MESSAGE_TYPE","MESSAGE_DATA","CONTROL_SHUTDOWN","CONTROL_RESET","CONTROL_ERROR","CONTROL_PONG","SWITCH_ACK","END_TRANSMISSION","PING","SERVER_HELLO","Connection","repoInfo_","onReady_","onKill_","connectionCount","pendingDataMessages","transportManager_","conn","conn_","nextTransportId_","primaryResponsesRequired_","onMessageReceived","connReceiver_","onConnectionLost","disconnReceiver_","tx_","rx_","secondaryConn_","isHealthy_","healthyTimeout_ms","healthyTimeout_","everConnected","onConnectionLost_","onSecondaryConnectionLost_","onPrimaryMessageReceived_","onSecondaryMessageReceived_","sendRequest","dataMsg","msg","t","sendData_","tryCleanupConnection","onSecondaryControl_","controlData","cmd","upgradeIfSecondaryHealthy_","secondaryResponsesRequired_","parsedData","layer","proceedWithUpgrade_","onControl_","onDataMessage_","onPrimaryResponse_","payload","onHandshake_","onConnectionShutdown_","onReset_","sendPingOnPrimaryIfNecessary_","handshake","timestamp","h","sessionId","onConnectionEstablished_","tryStartUpgrade_","startUpgrade_","closeConnections_","ServerActions","refreshAuthToken","onDisconnectPut","onDisconnectMerge","RECONNECT_MIN_DELAY","RECONNECT_MAX_DELAY_DEFAULT","RECONNECT_MAX_DELAY_FOR_ADMINS","RECONNECT_DELAY_MULTIPLIER","RECONNECT_DELAY_RESET_TIMEOUT","SERVER_KILL_INTERRUPT_REASON","INVALID_AUTH_TOKEN_THRESHOLD","PersistentConnection","onDataUpdate_","onConnectStatus_","onServerInfoUpdate_","authTokenProvider_","authOverride_","nextPersistentConnectionId_","interruptReasons_","listens_","outstandingPuts_","outstandingPutCount_","onDisconnectRequestQueue_","connected_","reconnectDelay_","maxReconnectDelay_","securityDebugCallback_","establishConnectionTimer_","requestCBHash_","requestNumber_","realtime_","authToken_","forceTokenRefresh_","invalidAuthTokenCount_","firstConnection_","lastConnectionAttemptTime_","lastConnectionEstablishedTime_","scheduleConnect_","onVisible_","onOnline_","onResponse","curReqNum","listen","currentHashFn","listenSpec","sendListen_","req","warnOnListenWarnings_","currentListenSpec","removeListen_","warnings","indexSpec","indexPath","tryAuth","reduceReconnectDelayIfAdminCredential_","credential","isFirebaseSecret","isAdmin","token_1","authMethod","isValidFormat","requestData","cred","res","onAuthRevoked_","unlisten","sendUnlisten_","queryObj","sendOnDisconnect_","putInternal","sendPut_","queued","errorReason","reqNum","onDataPush_","onListenRevoked_","onSecurityDebugPacket_","handleTimestamp_","sendConnectStats_","restoreState_","establishConnection_","online","onRealtimeDisconnect_","cancelSentTransactions_","shouldReconnect_","timeSinceLastConnectSucceeded","timeSinceLastConnectAttempt","reconnectDelay","onDataMessage_1","onReady_1","onDisconnect_1","connId_1","nextConnectionId_","lastSessionId_1","canceled_1","connection_1","closeFn_1","sendRequestFn","interrupt","serverTimeOffset","q","normalizedPathString","statusCode","explanation","console","clientName","NODE_CLIENT","isReactNative","ReadonlyRestClient","getListenId_","listenId","thisListen","queryStringParameters","toRestQueryStringParameters","restRequest_","authTokenData","querystring","INTERRUPT_REASON","Repo","forceRestClient","dataUpdateCount","eventQueue_","nextWriteId_","interceptServerDataCallback_","persistentConnection_","authTokenProvider","authOverride","statsReporter_","transactions_init_","infoData_","infoSyncTree_","infoEvents","updateInfo_","serverSyncTree_","serverTime","offsetNode","offset","generateServerValues","isMerge","taggedChildren","raw","taggedSnap","rerunTransactions_","interceptServerData_","connectStatus","runOnDisconnectEvents_","getNextWriteId_","newVal","newNodeUnresolved","clearEvents","callOnCompleteCallback","abortTransactions_","childrenToMerge","empty","changedKey","changedValue","writeId_1","resolvedOnDisconnectTree","showDelta","longestName","reduce","previousValue","currentValue","statsIncrementCounter","metric","__database","Database","RangedFilter","indexedFilter_","startPost_","getStartPost_","endPost_","getEndPost_","getStartPost","getEndPost","LimitedFilter","rangedFilter_","limit_","getLimit","reverse_","isViewFromLeft","fullLimitUpdateChild_","inRange","indexCompare_1","foundStartPost","changeAccumulator","indexCmp_1","newChildNamedNode","windowBoundary","oldChildSnap","compareNext","remainsInWindow","nextChildInRange","QueryParams","limitSet_","startSet_","startNameSet_","endSet_","endNameSet_","viewFrom_","indexStartValue_","indexStartName_","indexEndValue_","indexEndName_","WIRE_PROTOCOL_CONSTANTS_","VIEW_FROM_LEFT","copy_","newLimit","VIEW_FROM_RIGHT","WIRE_PROTOCOL_CONSTANTS","INDEX_START_VALUE","INDEX_START_NAME","INDEX_END_VALUE","INDEX_END_NAME","LIMIT","viewFrom","VIEW_FROM","INDEX","REST_CONSTANTS","REST_QUERY_CONSTANTS_","qs","ORDER_BY","START_AT","END_AT","LIMIT_TO_FIRST","LIMIT_TO_LAST","DEFAULT","parentPath","getRoot","databaseProp","database","transaction","transactionUpdate","applyLocally","promiseComplete","startTransaction","setPriority","thennablePushRef","pushRef","TransactionStatus","TreeNode","childCount","Tree","parent_","subTree","pathObj","setValue","updateParents_","forEachDescendant","includeSelf","childrenFirst","forEachAncestor","forEachImmediateDescendantWithValue","updateChild_","childEmpty","childExists","MAX_TRANSACTION_RETRIES_","transactionQueueTree_","watchRef","unwatcher","order","retryCount","abortReason","currentWriteId","currentInputSnapshot","currentOutputSnapshotRaw","currentOutputSnapshotResolved","currentState","getLatestState_","RUN","queueNode","nodeQueue","priorityForNode","currentNode","sendReadyTransactions_","excludeSets","pruneCompletedTransactionsBelowNode_","queue","buildTransactionQueue_","allRun","sendTransactionQueue_","setsToIgnore","txn","latestState","snapToSend","latestHash","SENT","dataToSend","pathToSend","COMPLETED","SENT_NEEDS_ABORT","NEEDS_ABORT","rootMostTransactionNode","getAncestorTransactionNode_","rerunTransactionQueue_","txnsToRerun","abortTransaction","newDataNode","hasExplicitPriority","oldWriteId","newNodeResolved","lastInput","transactionNode","transactionQueue","aggregateTransactionQueuesForNode_","to","from","abortTransactionsOnNode_","lastSent","_staticInstance","DATABASE_URL_OPTION","RepoManager","repos_","useRestClient_","appName","dbUrl","databaseFromApp","createRepo","deleteRepo","appRepos","DatabaseInternals","checkDeleted_","apiName","parsedURL","goOffline","goOnline","ServerValue","TIMESTAMP","forceLongPolling","forceWebSockets","setSecurityDebugCallback","interceptServerData","freeze","DataConnection","simpleListen","echo","onEcho","RealTimeConnection","hijackHash","newHash","oldPut","opt_onComplete","opt_hash","ConnectionTarget","listens","firebaseRef","TEST_ACCESS","registerDatabase","module","render","_vm","_h","$createElement","_c","_self","staticClass","attrs","vesselGroups","handleSearch","handleSort","handleChangePage","scopedSlots","_u","_l","tr","indextr","_v","_s","icon_type","model","$$v","selected","expression","slot","staticStyle","$event","popupActive","openConfirm","_e","edit","theVesselGroups","$set","popupActive2","editVesselGroup","staticRenderFns","mmsi_list","$store","vesselGroupsData","selectedVessel","excisemmsiList","excisemmsiListDetail","accessEmail","statusSearch","countdataExcise","mounted","$vs","loading","dispatch","localStorage","getVesselGroups","watch","getdataExciseTanker","methods","axios","API_BASE_URL","_getdataExciseTanker","_asyncToGenerator","regeneratorRuntime","mark","_callee","_this2","wrap","_context","prev","convertmmsiList","_x","ar","fineExciseTankerList","mmsi","_this3","_this4","post","unshift","routeData","$router","_this5","indexOfVesselGroup","dialog","title","accept","acceptAlert","_this6","notify","searching","page","active","apiInstance","windowInstance","settingsServiceInstance","TRACE_START_MARK_PREFIX","TRACE_STOP_MARK_PREFIX","TRACE_MEASURE_PREFIX","OOB_TRACE_PAGE_LOAD_PREFIX","FIRST_PAINT_COUNTER_NAME","FIRST_CONTENTFUL_PAINT_COUNTER_NAME","FIRST_INPUT_DELAY_COUNTER_NAME","CONFIG_LOCAL_STORAGE_KEY","CONFIG_EXPIRY_LOCAL_STORAGE_KEY","SERVICE","SERVICE_NAME","ERROR_DESCRIPTION_MAP","ERROR_FACTORY","ErrorFactory","Api","create","performance","PerformanceObserver","windowLocation","perfMetrics","onFirstInputDelay","getUrl","measure","measureName","mark1","mark2","getEntriesByType","getEntriesByName","getTimeOrigin","timeOrigin","timing","navigationStart","setupObserver","entryType","list","getEntries","entry","observe","entryTypes","setupApi","iid","VisibilityState","SettingsService","instrumentationEnabled","dataCollectionEnabled","loggingEnabled","tracesSamplingRate","networkRequestsSamplingRate","logEndPointUrl","logSource","logTraceAfterSampling","logNetworkAfterSampling","configTimeToLive","getAppId","appId","firebaseAppInstance","getProjectId","getApiKey","apiKey","getIidPromise","iidPromise","installations","getId","iidVal","getIid","getAuthTokenPromise","authTokenPromise","authTokenVal","getServiceWorkerStatus","serviceWorker","controller","getVisibilityState","visibilityState","VISIBLE","HIDDEN","PRERENDER","getEffectiveConnectionType","navigatorConnection","connection","effectiveType","consoleLogger","INFO","REMOTE_CONFIG_SDK_VERSION","SECONDARY_CONFIGS","FIS_AUTH_PREFIX","getConfig","getStoredConfig","processConfig","getRemoteConfig","storeConfig","expiryString","configValid","configStringified","configResponse","COULD_NOT_GET_CONFIG_MSG","configEndPoint","Request","Authorization","app_instance_id","app_instance_id_token","app_id","app_version","sdk_version","ok","info","entries","fpr_enabled","fpr_log_source","fpr_log_endpoint_url","fpr_vc_network_request_sampling_rate","fpr_vc_trace_sampling_rate","shouldLogAfterSampling","expiry","samplingRate","initializationPromise","initializationStatus","getInitializationPromise","initializePerf","isPerfInitialized","getDocumentReadyComplete","changeInitializationStatus","handler_1","DEFAULT_SEND_INTERVAL_MS","INITIAL_SEND_TIME_DELAY_MS","DEFAULT_REMAINING_TRIES","remainingTries","processQueue","timeOffset","staged","log_event","evt","source_extension_json","event_time_ms","eventTime","request_time_ms","client_info","client_type","js_client_info","log_source","requestOffset","next_request_wait_millis","addToQueue","ccHandler","_loggerInstance","_level","getLogger","ccLogger","logHandler","logTrace","trace","settingsService","isAuto","sendTraceLog","logNetworkRequest","networkRequest","resourceType","serializeNetworkRequest","serializeTrace","networkRequestMetric","http_method","http_response_code","response_payload_bytes","responsePayloadBytes","client_start_time_us","startTimeUs","time_to_response_initiated_us","timeToResponseInitiatedUs","time_to_response_completed_us","timeToResponseCompletedUs","perfMetric","application_info","getApplicationInfo","network_request_metric","traceMetric","is_auto","duration_us","durationUs","counters","convertToKeyValueArray","customAttributes","getAttributes","custom_attributes","trace_metric","google_app_id","web_app_info","page_url","service_worker_status","visibility_state","effective_connection_type","application_process_state","Trace","traceMeasureName","api","randomId","traceStartMark","traceStopMark","traceMeasure","calculateTraceMetrics","traceName","startTime","duration","attributes","__assign","metrics","incrementMetric","counter","putMetric","getMetric","putAttribute","attr","getAttribute","removeAttribute","setStartTime","setDuration","perfMeasureEntries","perfMeasureEntry","createOobTrace","navigationTimings","paintTimings","firstInputDelay","route","timeOriginUs","domInteractive","domContentLoadedEventEnd","loadEventEnd","FIRST_PAINT","FIRST_CONTENTFUL_PAINT","firstPaint","paintObject","firstContentfulPaint","createUserTimingTrace","createNetworkRequestEntry","performanceEntry","responseStart","responseEnd","transferSize","FID_WAIT_TIME_MS","setupOobResources","setupOobTraces","setupNetworkRequests","setupUserTimingTraces","resources","resources_1","timeoutId_1","fid","measures","measures_1","PerformanceController","DEFAULT_ENTRY_NAME","registerPerformance","factoryMethod","assign","thisArg","_arguments","P","generator","fulfilled","step","rejected","done","y","g","ops","verb","Symbol","TypeError","__read","__spread","PENDING_TIMEOUT_MS","PACKAGE_VERSION","INTERNAL_AUTH_VERSION","INSTALLATIONS_API_URL","TOKEN_EXPIRATION_BUFFER","isServerError","includes","extractAppConfig","getInstallationsEndpoint","extractAuthTokenInfoFromResponse","requestStatus","expiresIn","getExpiresInFromResponseExpiresIn","creationTime","getErrorFromResponse","requestName","responseJson","errorData","serverCode","serverMessage","serverStatus","getHeaders","Accept","getHeadersWithAuth","appConfig","refreshToken","getAuthorizationHeader","responseExpiresIn","createInstallation","endpoint","responseValue","registeredInstallationEntry","_b","authVersion","sdkVersion","registrationStatus","sleep","ms","bufferToBase64UrlSafe","b64","btoa","fromCharCode","generateFid","fidByteArray","crypto","getRandomValues","b64String","DATABASE_NAME","DATABASE_VERSION","OBJECT_STORE_NAME","dbPromise","upgradeDB","oldVersion","createObjectStore","db","tx","objectStore","updateFn","store","oldValue","newValue","getInstallationEntry","registrationPromise","oldEntry","installationEntry","updateOrCreateFid","entryWithPromise","triggerRegistrationIfNecessary","hasInstallationRequestTimedOut","onLine","registrationPromiseWithError","inProgressEntry","registrationTime","registerInstallation","waitUntilFidRegistration","e_1","updateInstallationRequest","generateAuthToken","completedAuthToken","getGenerateAuthTokenEndpoint","installation","completeInstallationRegistration","fetchAuthToken","tokenPromise","isEntryRegistered","oldAuthToken","isAuthTokenValid","waitUntilAuthTokenRequest","makeAuthTokenRequestInProgressEntry","fetchAuthTokenFromServer","updateAuthTokenRequest","hasAuthTokenRequestTimedOut","updatedInstallationEntry","isAuthTokenExpired","inProgressAuthToken","requestTime","deleteInstallation","getDeleteEndpoint","deleteInstallation$1","registerInstallations","installationsName","MessageParameter","MessageType","ERROR_MAP","errorFactory","DEFAULT_PUBLIC_VAPID_KEY","ENDPOINT","isArrayBufferEqual","viewA","DataView","viewB","getUint8","toBase64","arrayBuffer","uint8Version","arrayBufferToBase64","base64String","IidModel","senderId","subscription","publicVapidKey","p256dh","auth","fcmSubscribeBody","applicationPubKey","subscribeOptions","pushSet","updateToken","fcmToken","fcmPushSet","fcmUpdateBody","updateOptions","deleteToken","fcmUnsubscribeBody","unsubscribeOptions","base64ToArrayBuffer","padding","repeat","rawData","outputArray","OLD_DB_NAME","OLD_OBJECT_STORE_NAME","handleDb","objectStoreNames","iidModel","openCursorRequest","openCursor","onsuccess","cursor","tokenDetails","fcmSenderId","continue","indexedDB","deleteDatabase","cleanV1","DbInterface","createTransaction","runRequest","idbIndex","closeDatabase","mode","getDb","objectStoreName","promisify","oncomplete","dbName","dbVersion","onupgradeneeded","onDbUpgrade","TokenDetailsModel","keyPath","createIndex","unique","cursorRequest_1","createTime","vapidKey","getTokenDetailsFromToken","validateInputs","getTokenDetailsFromSWScope","swScope","saveTokenDetails","input","UNCOMPRESSED_PUBLIC_KEY_SIZE","VapidDetailsModel","getVapidFromSWScope","saveVapidDetails","deleteVapidDetails","SENDER_ID_OPTION_NAME","TOKEN_EXPIRATION_MILLIS","BaseController","messagingSenderId","tokenDetailsModel","vapidDetailsModel","currentPermission","swReg","pushSubscription","getNotificationPermission_","getSWRegistration_","getPublicVapidKey_","getPushSubscription","scope","manageExistingToken","getNewToken","isTokenValid","isTokenStillValid","deleteTokenFromDB","updatedToken","allDetails","pushManager","getSubscription","unsubscribe","swRegistration","subscribe","userVisibleOnly","applicationServerKey","requestPermission","useServiceWorker","usePublicVapidKey","b64PublicKey","onTokenRefresh","setBackgroundMessageHandler","all","Notification","permission","getTokenDetailsModel","getVapidDetailsModel","getIidModel","isEndpointEqual","isAuthEqual","isP256dhEqual","FCM_MSG","SwController","bgMessageHandler","onPush","onSubChange","onNotificationClick","waitUntil","onPush_","onSubChange_","onNotificationClick_","msgPayload","hasVisibleClients","notificationDetails","notificationTitle","reg","actions","maxActions","hasVisibleClients_","sendMessageToWindowClients_","getNotificationData_","showNotification","err_1","err_2","link","windowClient","internalMsg","notification","stopImmediatePropagation","fcmOptions","click_action","getWindowClient_","clients","openWindow","focus","createNewMsg","NOTIFICATION_CLICKED","attemptToMessageClient_","notificationInformation","clientList","suitableClient","parsedClientUrl","URL","getClientList","client","postMessage","some","startsWith","PUSH_MSG_RECEIVED","vapidKeyFromDatabase","matchAll","includeUncontrolled","msgType","msgData","TYPE_OF_MSG","DATA","DEFAULT_SW_PATH","DEFAULT_SW_SCOPE","WindowController","registrationToUse","publicVapidKeyToUse","manifestCheckPromise","messageObserver","tokenRefreshObserver","onMessageInternal","onTokenRefreshInternal","setupSWMessageListener_","manifestCheck","permissionResult","ServiceWorkerRegistration","publicKey","parsedKey","waitForRegistrationToActivate_","installing","waiting","stateChangeListener","register","browserErrorMessage","workerPageMessage","pushMessage","manifestTag","manifestContent","gcm_sender_id","registerMessaging","messagingName","isSupported","isSWControllerSupported","isWindowControllerSupported","cookieEnabled","PushSubscription","global","toArray","arr","promisifyRequest","promisifyRequestCall","promisifyCursorRequestCall","Cursor","proxyProperties","ProxyClass","targetProp","properties","proxyRequestMethods","Constructor","proxyMethods","proxyCursorRequestMethods","_index","_cursor","_request","ObjectStore","_store","Transaction","idbTransaction","_tx","onabort","UpgradeDB","_db","DB","openDb","upgradeCallback","deleteDb","IDBIndex","IDBCursor","methodName","IDBObjectStore","IDBTransaction","IDBDatabase","funcName","nativeObject","getAll","items","iterateCursor","instances","defaultLogLevel","defaultLogHandler","logType","toISOString","DEBUG","WARN","_logLevel","_logHandler","debug","setLogLevel","level","inst","commonjsGlobal","globalThis","goog","aa","ba","propertyIsEnumerable","ca","da","ea","fa","u","Function","w","N","constructor","yb","l","ha","la","G","ja","ma","na","oa","pa","qa","A","ra","trim","z","sa","ta","ua","va","wa","xa","ya","za","Aa","Ba","Ia","Ca","B","Da","Ea","Fa","Ga","Ha","documentMode","Ja","Ka","La","Na","Ma","Oa","compatMode","Pa","Qa","Ra","C","target","D","relatedTarget","button","screenY","screenX","clientY","clientX","metaKey","shiftKey","altKey","ctrlKey","pointerId","pointerType","changedTouches","srcElement","nodeName","fromElement","toElement","pageX","pageY","Sa","defaultPrevented","2","3","4","preventDefault","returnValue","keyCode","E","Ta","Ua","capture","X","Z","Va","Wa","Ya","Xa","Za","$a","eb","fb","gb","hb","addListener","removeListener","ib","jb","kb","detachEvent","lb","mb","handleEvent","J","nb","F","dispatchEvent","ob","pb","qb","xb","sb","rb","reset","tb","ub","vb","wb","zb","Ab","Cb","Db","L","Eb","Fb","ab","Gb","U","H","Hb","Ib","Jb","Kb","I","Lb","Mb","K","Nb","Ob","Pb","TIMEOUT","Qb","Rb","Sb","Tb","Wb","OPEN","Ub","Vb","Xb","M","W","V","O","Yb","R","S","Zb","$b","ac","bc","cc","dc","ec","fc","$","Y","kc","lc","ic","jc","mc","gc","nc","oc","Q","qc","rc","pc","T","hc","sc","tc","uc","vc","wc","xc","yc","zc","Ac","Gc","Bc","Hc","Ic","Jc","Kc","decodeURI","encodeURI","Lc","Cc","Dc","Ec","Fc","Mc","Nc","Qc","Rc","Sc","Uc","Vc","Wc","Xc","Yc","Zc","$c","ad","bd","PerformanceNavigationTiming","nextHopProtocol","ka","cd","dd","ed","fd","gd","hd","jd","kd","ld","md","Image","nd","ontimeout","od","pd","qd","rd","ud","sd","vd","wd","xd","td","yd","zd","Ad","ga","ia","supportsCrossDomainXhr","concurrentRequestLimit","backgroundChannelTest","fastHandshake","Bd","Cd","Dd","sendBeacon","Ed","Fd","Gd","Hd","Id","Jd","Ld","Kd","Bb","Tc","Ud","Md","Nd","hostname","Od","Pd","Qd","testUrl","messageUrlParams","messageHeaders","clientProtocolHeaderRequired","initMessageHeaders","messageContentType","httpHeadersOverwriteParam","sendRawJson","httpSessionIdParam","Rd","__sm__","Sd","FormData","responseType","withCredentials","statusText","__data__","Td","createWebChannel","HTTP_ERROR","COMPLETE","EventType","CLOSE","MESSAGE","listenOnce","getLastError","getLastErrorCode","getStatusText","getResponseJson","tmp","createWebChannelTransport","WebChannel","XhrIo","tmp_1","tmp_2","tmp_3","tmp_4","tmp_5","webchannelWrapper","getLogLevel","SILENT","newLevel","argToString","PlatformSupport","getPlatform","formatJSON","fail","failure","assertion","setPlatform","emptyByteString","FirestoreError","makeConstructorPrivate","cls","optionalMessage","PublicConstructor","staticProperty","defaulted","defaultValue","forEachNumber","vs","shallowCopy","validateNoArgs","functionName","formatPlural","validateExactNumberOfArgs","numberOfArgs","validateAtLeastNumberOfArgs","minNumberOfArgs","validateBetweenNumberOfArgs","maxNumberOfArgs","validateNamedArrayAtLeastNumberOfElements","minNumberOfElements","validateArgType","position","argument","validateType","ordinal","validateOptionalArgType","validateNamedType","optionName","validateNamedOptionalType","validateArrayElements","typeDescription","valueDescription","validateOptionalArrayElements","validateNamedPropertyEquals","inputName","expected","expectedDescription","expected_1","actualDescription","validateNamedOptionalPropertyEquals","validateStringEnum","enums","element","isPlainObject","getPrototypeOf","customObjectName","tryGetCustomObjectType","funcNameRegex","validateDefined","validateOptionNames","optionNames","invalidClassError","AutoId","newId","chars","autoId","primitiveComparator","arrayEquals","immediateSuccessor","assertUint8ArrayAvailable","assertBase64Available","base64Available","TypeOrder","ServerTimestampBehavior","binaryString","_binaryString","fromBase64String","fromUint8Array","char","toUint8Array","_compareTo","PublicBlob","GeoPoint","latitude","longitude","_lat","_long","Timestamp","seconds","nanoseconds","fromMillis","fromDate","date","milliseconds","nanos","toDate","toMillis","DatabaseInfo","databaseId","ssl","DEFAULT_DATABASE_NAME","DatabaseId","DOCUMENT_KEY_NAME","segments","construct","nameOrPath","popFirst","popLast","firstSegment","lastSegment","isPrefixOf","isImmediateParentOf","potentialChild","p1","p2","ResourcePath","canonicalString","fromString","EMPTY_PATH","identifierRegExp","FieldPath","isValidIdentifier","isKeyField","keyField","fromServerFormat","addCurrentSegment","inBackticks","DocumentKey","isDocumentKey","hasCollectionId","collectionId","k1","k2","fromSegments","fromPathString","EMPTY","MaybeDocument","compareByKey","d1","d2","Document","proto","hasLocalMutations","hasCommittedMutations","field","fieldValue","compareByField","NoDocument","UnknownDocument","prunedNodes","descriptions","isReverse","nodeStack","fixUp","removeMin","isRed","moveRedLeft","rotateRight","moveRedRight","rotateLeft","colorFlip","checkMaxDepth","check","FieldValueOptions","serverTimestampBehavior","timestampsInSnapshots","fromSnapshotOptions","serverTimestamps","Estimate","Previous","FieldValue","defaultCompareTo","typeOrder","NullValue","internalValue","INSTANCE","BooleanValue","of","TRUE","FALSE","NumberValue","numericComparator","numericEquals","IntegerValue","DoubleValue","NAN","NaN","StringValue","TimestampValue","ServerTimestampValue","localWriteTime","BlobValue","RefValue","GeoPointValue","ObjectValue","it1","it2","next1","next2","setChild","pathSegment","ArrayValue","minLength","NumberAsAny","MAX_SAFE_INTEGER","isInteger","isNullOrUndefined","isSafeInteger","QueryPurpose","collectionGroup","explicitOrderBy","filters","memoizedCanonicalId","memoizedOrderBy","assertValidBound","atPath","inequalityField","getInequalityFilterField","firstOrderByField","getFirstOrderByField","KEY_ORDERING_ASC","OrderBy","foundKeyOrdering","lastDirection","dir","Direction","ASCENDING","KEY_ORDERING_DESC","addFilter","RelationFilter","isInequality","isDocumentQuery","newFilters","addOrderBy","newOrderBy","withLimit","withStartAt","bound","withEndAt","asCollectionQueryAtPath","canonicalId","isCollectionGroupQuery","docComparator","comparedOnKeyField","comp","matchesPathAndCollectionGroup","matchesOrderBy","matchesFilters","matchesBounds","hasArrayContainsFilter","RelationOp","ARRAY_CONTAINS","docPath","sortsBeforeDocument","Filter","EQUAL","NullFilter","NanFilter","LESS_THAN","LESS_THAN_OR_EQUAL","GREATER_THAN_OR_EQUAL","GREATER_THAN","refValue","comparison","matchesComparison","matchesValue","DESCENDING","Bound","before","orderByComponent","docValue","thisPosition","otherPosition","isKeyOrderBy","SnapshotVersion","fromMicroseconds","fromTimestamp","forDeletedDoc","toMicroseconds","toTimestamp","MutationType","QueryData","targetId","purpose","sequenceNumber","snapshotVersion","resumeToken","SortedSet","fromMapKeys","has","first","forEachInRange","range","forEachWhile","firstAfterOrEqual","SortedSetIterator","unionWith","thisIt","otherIt","thisElem","otherElem","FieldMask","fields","fromSet","fromArray","fieldsAsSet","fieldPath","covers","found","fieldMaskPath","applyTo","filteredObject","FieldTransform","transform","isIdempotent","MutationResult","transformResults","Precondition","updateTime","isValidFor","maybeDoc","isNone","NONE","Mutation","verifyKeyMatches","getPostMutationVersion","SetMutation","precondition","Set","applyToRemoteDocument","mutationResult","applyToLocalView","baseDoc","PatchMutation","fieldMask","Patch","patchDocument","patchObject","TransformMutation","fieldTransforms","Transform","requireDocument","serverTransformResults","transformObject","localTransformResults","fieldTransform","DeleteMutation","Delete","ServerTimestampTransform","transformResult","ArrayUnionTransformOperation","elements","coercedFieldValuesArray","toUnion","ArrayRemoveTransformOperation","toRemove","NumericIncrementTransformOperation","operand","sum","RpcCode","ExistenceFilter","isPermanentError","isPermanentWriteError","mapCodeFromRpcStatus","mapCodeFromRpcCode","mapRpcCodeFromCode","mapCodeFromHttpStatus","EMPTY_MAYBE_DOCUMENT_MAP","maybeDocumentMap","nullableMaybeDocumentMap","EMPTY_DOCUMENT_MAP","documentMap","EMPTY_DOCUMENT_VERSION_MAP","documentVersionMap","EMPTY_DOCUMENT_KEY_SET","documentKeySet","keys_1","EMPTY_TARGET_ID_SET","targetIdSet","ChangeType","SyncState","DocumentSet","keyedMap","sortedSet","emptySet","oldSet","thisDoc","otherDoc","docStrings","newSet","WatchTargetChangeState","DocumentChangeSet","changeMap","track","Added","Metadata","Removed","Modified","ViewSnapshot","docs","oldDocs","docChanges","mutatedKeys","fromCache","syncStateChanged","excludesMetadataChanges","fromInitialDocuments","documents","otherChanges","RemoteEvent","targetChanges","targetMismatches","documentUpdates","resolvedLimboDocuments","createSynthesizedRemoteEventForCurrentChange","TargetChange","createSynthesizedTargetChangeForCurrentChange","addedDocuments","modifiedDocuments","removedDocuments","DocumentWatchChange","updatedTargetIds","removedTargetIds","newDoc","ExistenceFilterChange","existenceFilter","WatchTargetChange","targetIds","cause","TargetState","documentChanges","snapshotChangesMap","_resumeToken","_current","_hasPendingChanges","updateResumeToken","toTargetChange","changeType","clearPendingChanges","addDocumentChange","removeDocumentChange","recordPendingTargetRequest","recordTargetResponse","markCurrent","WatchChangeAggregator","metadataProvider","targetStates","pendingDocumentUpdates","pendingDocumentTargetMapping","documentTargetMap","pendingTargetResets","handleDocumentChange","docChange","addDocumentToTarget","removeDocumentFromTarget","handleTargetChange","targetChange","forEachTarget","targetState","ensureTargetState","NoChange","isActiveTarget","isPending","removeTarget","Current","Reset","resetTarget","handleExistenceFilter","watchChange","expectedCount","queryData","queryDataForActiveTarget","getCurrentDocumentCountForTarget","createRemoteEvent","targetContainsDocument","hasPendingChanges","targets","isOnlyLimboTarget","LimboResolution","remoteEvent","ensureDocumentTargetMapping","updatedDocument","getRemoteKeysForTarget","targetMapping","getQueryDataForTarget","existingKeys","DIRECTIONS","dirs","OPERATORS","ISO_REG_EXP","assertPresent","parseInt64","JsonProtoSerializer","useProto3Json","unsafeCastProtoByteString","byteString","fromRpcStatus","toInt32Value","fromInt32Value","fromIso8601String","utc","fraction","nanoStr","toBytes","fromBlob","toVersion","fromVersion","toResourceName","fullyQualifiedPrefixPath","fromResourceName","isValidResourceName","toName","fromName","extractLocalPathFromResourceName","toQueryPath","fromQueryPath","resourceName","toValue","nullValue","booleanValue","integerValue","doubleValue","stringValue","mapValue","toMapValue","arrayValue","toArrayValue","timestampValue","geoPointValue","bytesValue","referenceValue","fromValue","hasTag","fromFields","dbId","toMutationDocument","toFields","toDocument","fromDocument","object","fromFound","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","fromPrecondition","fromDocumentMask","fromFieldTransform","fromWriteResult","commitTime","fromWriteResults","protos","setToServerValue","appendMissingElements","removeAllFromArray","increment","toDocumentsTarget","fromDocumentsTarget","documentsTarget","toQueryTarget","structuredQuery","allDescendants","where","toFilter","toOrder","toCursor","fromQueryTarget","fromCount","filterBy","fromFilter","fromOrder","fromCursor","toListenRequestLabels","toLabel","Listen","ExistenceFilterMismatch","toTarget","toRelationFilter","toUnaryFilter","compositeFilter","unaryFilter","fromUnaryFilter","fieldFilter","fromRelationFilter","orderBys","toPropertyOrder","fromPropertyOrder","toDirection","fromDirection","toOperatorName","fromOperatorName","toFieldPathReference","fromFieldPathReference","fieldReference","direction","nanField","nullField","canonicalFields","fieldPaths","paths","StreamBridge","sendFn","closeFn","onOpen","wrappedOnOpen","wrappedOnClose","wrappedOnMessage","callOnOpen","callOnClose","callOnMessage","LOG_TAG","RPC_STREAM_SERVICE","RPC_URL_VERSION","RPC_NAME_REST_MAPPING","BatchGetDocuments","Commit","X_GOOG_API_CLIENT_VALUE","XHR_TIMEOUT_SECS","WebChannelConnection","baseUrl","modifyHeadersForRequest","authHeaders","invokeRPC","rpcName","requestString","invokeStreamingRPC","openStream","urlParts","webchannelTransport","internalChannelParams","forwardChannelRequestTimeoutMs","channel","opened","closed","streamBridge","unguardedEventListen","param","status_2","urlRpcName","BrowserPlatform","loadConnection","databaseInfo","newSerializer","encoded","TimerId","ListenSequence","sequenceNumberSyncer","sequenceNumberHandler","setPreviousValue","writeNewSequenceNumber","writeSequenceNumber","externalPreviousValue","nextValue","INVALID","DelayedOperation","asyncQueue","timerId","targetTimeMs","removalCallback","createAndSchedule","delayMs","targetTime","delayedOp","timerHandle","handleDelayElapsed","skipDelay","enqueueAndForget","AsyncQueue","tail","delayedOperations","operationInProgress","enqueue","verifyNotFailed","newTail","error$1","enqueueAfterDelay","containsDelayedOperation","removeDelayedOperation","verifyOperationInProgress","drain","runDelayedOperationsEarly","lastTimerId","All","escapeChar","encodedSeparatorChar","encodedNul","encodedEscape","encodeSeparator","encodeSegment","resultBuf","lastReasonableEscapeIndex","segmentBuilder","currentPiece","BATCHID_UNKNOWN","MutationBatch","batchId","baseMutations","mutations","docKey","batchResult","mutationResults","applyToLocalDocumentSet","maybeDocs","mutatedDocuments","mutatedDocument","MutationBatchResult","batch","commitVersion","streamToken","docVersions","versionMap","PersistencePromise","nextCallback","catchCallback","isDone","callbackAttached","nextFn","catchFn","wrapFailure","wrapSuccess","toPromise","wrapUserFunction","waitFor","resolvedCount","or","predicates","isTrue","predicates_1","promises","IndexedDbMutationQueue","userId","indexManager","referenceDelegate","documentKeysByBatchId","forUser","user","uid","isAuthenticated","checkEmpty","IDBKeyRange","mutationsStore","iterate","DbMutationBatch","userMutationsIndex","control","acknowledgeBatch","getMutationQueueMetadata","lastStreamToken","convertStreamToken","mutationQueuesStore","getLastStreamToken","setLastStreamToken","addMutationBatch","documentStore","documentMutationsStore","mutationStore","dbBatch","toDbMutationBatch","mutations_1","DbDocumentMutation","PLACEHOLDER","addToCollectionParentIndex","lookupMutationBatch","fromDbMutationBatch","lookupMutationKeys","getNextMutationBatchAfterBatchId","nextBatchId","lowerBound","foundBatch","getAllMutationBatches","loadAll","dbBatches","getAllMutationBatchesAffectingDocumentKey","documentKey","indexPrefix","prefixForPath","indexStart","userID","encodedPath","getAllMutationBatchesAffectingDocumentKeys","documentKeys","uniqueBatchIDs","batchID","lookupMutationBatches","getAllMutationBatchesAffectingQuery","immediateChildrenLength","batchIDs","removeMutationBatch","simpleDbTransaction","removeCachedMutationKeys","removeMutationReference","performConsistencyCheck","startRange","prefixForUser","danglingMutationReferences","containsKey","mutationQueueContainsKey","DbMutationQueue","keysOnly","mutationQueuesContainKey","iterateSerial","indexTxn","only","numDeleted","removePromise","USE_MOCK_PERSISTENCE","IndexedDbPersistence","getStore","GeneratorIds","RESERVED_BITS","TargetIdGenerator","generatorId","seed","seek","nextId","after","forQueryCache","targetIdGenerator","QueryCache","forSyncEngine","SyncEngine","LOG_TAG$1","SimpleDb","openOrCreate","schemaConverter","onblocked","SimpleDbTransaction","createOrUpgrade","SCHEMA_VERSION","wrapRequest","iOSVersion","getIOSVersion","isUnsupportedIOS","androidVersion","getAndroidVersion","isUnsupportedAndroid","iOSVersionRegex","androidVersionRegex","runTransaction","objectStores","transactionFn","transactionFnResult","completionPromise","IterationController","dbCursor","shouldStop","nextKey","skip","aborted","completionDeferred","storeName","SimpleDbStore","keyOrValue","indexOrRange","deleteAll","optionsOrCallback","cursorRequest","primaryKey","shouldContinue","userResult","userPromise","skipToKey","openKeyCursor","IndexedDbQueryCache","allocateTargetId","retrieveMetadata","highestTargetId","saveMetadata","getLastRemoteSnapshotVersion","lastRemoteSnapshotVersion","getHighestSequenceNumber","getHighestListenSequenceNumber","setTargetsMetadata","highestListenSequenceNumber","addQueryData","saveQueryData","targetCount","updateMetadataFromQueryData","updateQueryData","removeQueryData","removeMatchingKeysForTargetId","targetsStore","removeTargets","upperBound","activeTargetIds","fromDbTarget","globalTargetStore","DbTargetGlobal","toDbTarget","updated","getQueryCount","getQueryData","DbTarget","queryTargetsIndexName","addMatchingKeys","documentTargetStore","DbTargetDocument","addReference","removeMatchingKeys","removeReference","getMatchingKeysForTargetId","documentTargetsIndex","globalStore","targetGlobal","ObjectMap","mapKeyFn","matches_1","entries_1","RemoteDocumentChangeBuffer","documentSizes","addEntry","maybeDocument","assertChanges","getEntry","bufferedEntry","getFromCache","getResult","getAllFromCache","maybeDocuments","sizeMap","applyChanges","REMOTE_DOCUMENT_CHANGE_MISSING_ERR_MSG","IndexedDbRemoteDocumentCache","keepDocumentChangeLog","_lastProcessedDocumentChangeId","DbRemoteDocumentChanges","synchronizeLastDocumentChangeId","addEntries","sizeDelta","remoteDocumentsStore","changedKeys","dbKey","documentChangesStore","toDbResourcePaths","updateSize","removeEntry","dbDocumentSize","dbRemoteDoc","fromDbRemoteDocument","getSizedEntry","forEachDbEntry","getSizedEntries","keyIter","potentialKeyRaw","potentialKey","getDocumentsMatchingQuery","immediateChildrenPathLength","getNewDocumentChanges","changedDocs","firstIteration","changesStore","fromDbResourcePaths","documentPromises","removeDocumentChangesThroughChangeId","changeId","newChangeBuffer","IndexedDbRemoteDocumentChangeBuffer","getSize","byteSize","documentGlobalStore","DbRemoteDocumentGlobal","setMetadata","documentCache","toApply","toDbRemoteDocument","previousSize","isDocumentChangeMissingError","DbRemoteDocument","unknownDocument","noDocument","MemoryIndexManager","collectionParentIndex","MemoryCollectionParentIndex","collectionPath","getCollectionParents","existingParents","added","parentPaths","SchemaConverter","createPrimaryClientStore","createMutationQueue","createQueryCache","createRemoteDocumentCache","dropQueryCache","writeEmptyTargetGlobalEntry","upgradeMutationBatchSchemaAndMigrateData","createClientMetadataStore","createRemoteDocumentChangesStore","removeAcknowledgedMutations","createDocumentGlobalStore","addDocumentGlobal","ensureSequenceNumbers","createCollectionParentIndex","byteCount","queuesStore","queues","lastAcknowledgedBatchId","documentsStore","currentSequenceNumber","writeSentinelKey","docSentinelKey","sentinelKey","maybeSentinel","DbCollectionParent","collectionParentsStore","pathSegments","DbTimestamp","DbPrimaryClient","ownerId","allowTabSynchronization","leaseTimestampMs","localWriteTimeMs","userMutationsKeyPath","mutationBatchesStore","autoIncrement","v1MutationsStore","existingMutations","deleteObjectStore","v3MutationsStore","writeAll","DbNoDocument","DbUnknownDocument","lastListenSequenceNumber","queryTargetsKeyPath","documentTargetsKeyPath","targetDocumentsStore","targetStore","DbClientMetadata","clientId","updateTimeMs","networkEnabled","inForeground","lastProcessedDocumentChangeId","V1_STORES","V3_STORES","V4_STORES","V6_STORES","V8_STORES","ALL_STORES","IndexedDbIndexManager","collectionParentsCache","LocalSerializer","remoteSerializer","remoteDoc","fromDbTimestamp","toDbTimestamp","dbTimestamp","serializedBaseMutations","serializedMutations","encodedKeys","encodedPaths","encodedPaths_1","dbTarget","queryProto","dbQuery","bufferEntryComparator","aSequence","aIndex","bSequence","bIndex","seqCmp","RollingSequenceNumberBuffer","maxElements","previousIndex","nextIndex","addElement","highestValue","GC_DID_NOT_RUN","didRun","sequenceNumbersCollected","targetsRemoved","documentsRemoved","LruParams","cacheSizeCollectionThreshold","percentileToCollect","maximumSequenceNumbersToCollect","withCacheSize","cacheSize","DEFAULT_COLLECTION_PERCENTILE","DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT","COLLECTION_DISABLED","MINIMUM_CACHE_SIZE_BYTES","DEFAULT_CACHE_SIZE_BYTES","DISABLED","INITIAL_GC_DELAY_MS","REGULAR_GC_DELAY_MS","LruScheduler","garbageCollector","localStore","gcTask","scheduleGC","delay","hasRun","LruGarbageCollection","collectGarbage","ignoreIfPrimaryLeaseLoss","LruGarbageCollector","delegate","calculateTargetCount","percentile","getSequenceNumberCount","nthSequenceNumber","forEachOrphanedDocumentSequenceNumber","maxValue","removeOrphanedDocuments","collect","getCacheSize","runGarbageCollection","upperBoundSequenceNumber","sequenceNumbersToCollect","startTs","countedTargetsTs","foundUpperBoundTs","removedTargetsTs","removedDocumentsTs","sequenceNumbers","numTargetsRemoved","desc","PersistenceTransaction","LOG_TAG$2","MAX_CLIENT_AGE_MS","MAX_PRIMARY_ELIGIBLE_AGE_MS","CLIENT_METADATA_REFRESH_INTERVAL_MS","PRIMARY_LEASE_LOST_ERROR_MSG","PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG","UNSUPPORTED_PLATFORM_ERROR_MSG","ZOMBIED_CLIENTS_KEY_PREFIX","IndexedDbTransaction","lruParams","multiClientParams","_started","isPrimary","lastGarbageCollectionTime","primaryStateListener","IndexedDbLruDelegate","MAIN_DATABASE","queryCache","remoteDocumentCache","webStorage","createIndexedDbPersistence","persistence","createMultiClientIndexedDbPersistence","started","simpleDb","updateClientMetadataAndTryBecomePrimary","attachVisibilityHandler","attachWindowUnloadHook","scheduleClientMetadataAndPrimaryLeaseRefreshes","startRemoteDocumentCache","listenSequence","setPrimaryStateListener","primaryState","setNetworkEnabled","metadataStore","clientMetadataStore","verifyPrimaryLease","canActAsPrimary","wasPrimary","releasePrimaryLeaseIfHeld","acquireOrExtendPrimaryLease","primaryClientStore","primaryClient","isLocalClient","removeClientMetadata","maybeGarbageCollectMultiClientState","activeClients_1","inactiveClients_1","isWithinAge","existingClients","filterActiveClients","inactiveClient","processedChangeIds","oldestChangeId","zombiedClientLocalStorageKey","clientMetadataRefresher","ClientMetadataRefresh","currentPrimary","currentLeaseIsValid","isClientZombied","preferredCandidate","otherClient","otherClientHasBetterNetworkState","otherClientHasBetterVisibility","otherClientHasSameNetworkState","shutdown","markClientZombied","detachVisibilityHandler","detachWindowUnloadHook","removeClientZombiedEntry","activityThresholdMs","getActiveClients","clientMetadata","clearPersistence","getMutationQueue","getQueryCache","getRemoteDocumentCache","getIndexManager","transactionOperation","simpleDbTxn","verifyAllowTabSynchronization","newPrimary","buildStoragePrefix","isDefaultDatabase","maxAgeMs","minAcceptable","maxAcceptable","documentVisibilityHandler","windowUnloadHandler","isZombied","isPrimaryLeaseLostError","docCountPromise","orphanedDocmentCount","targetCountPromise","docCount","orphanedCount","forEachOrphanedDocument","setInMemoryPins","inMemoryPins","isPinned","bytesRemoved","iteration","removeOrphanedDocument","documentBytes","totalBytesRemoved","sentinelKey$1","updateLimboDocument","nextPath","nextToReport","sentinelRow","LocalDocumentsView","mutationQueue","getDocument","batches","getDocumentInternal","inBatches","inBatches_1","applyLocalMutationsToDocuments","localView","batches_1","getDocuments","getLocalViewOfDocuments","baseDocs","getDocumentsMatchingDocumentQuery","getDocumentsMatchingCollectionGroupQuery","getDocumentsMatchingCollectionQuery","parents","collectionQuery","queryResults","matchingMutationBatches","matchingMutationBatches_1","mutatedDoc","ReferenceSet","refsByKey","DocReference","refsByTarget","compareByTargetId","addReferences","removeRef","removeReferences","removeReferencesForId","emptyKey","startRef","endRef","removeAllReferences","referencesForId","firstRef","targetOrBatchId","LOG_TAG$3","LocalStore","initialUser","localViewReferences","queryDataByTarget","remoteDocuments","localDocuments","handleUserChange","oldBatches","promisedOldBatches","newBatches","removedBatchIds","addedBatchIds","oldBatches_1","newBatches_1","_d","affectedDocuments","localWrite","existingDocs","baseValues","lookupMutationDocuments","affected","documentBuffer","applyWriteToRemoteDocuments","rejectBatch","affectedKeys","applyRemoteEvent","authoritativeUpdates","oldQueryData","shouldPersistQueryData","updatedKeys","existingDoc","hasPendingWrites","remoteVersion","updateRemoteVersion","lastRemoteVersion","newQueryData","timeDelta","RESUME_TOKEN_MAX_AGE_MICROS","notifyLocalViewChanges","viewChanges","viewChange","addedKeys","removedKeys","nextMutationBatch","afterBatchId","readDocument","allocateQuery","cached","releaseQuery","keepPersistedQueryData","cachedQueryData","executeQuery","remoteDocumentKeys","removeCachedMutationBatchMetadata","docKeys","promiseChain","ackVersion","getQueryForTarget","MemoryMutationQueue","batchesByDocumentKey","batchIndex","indexOfExistingBatchId","prior","findMutationBatch","mutationBatch","rawIndex","indexOfBatchId","findMutationBatches","startPath","rowKeyPath","references","firstBatchId","MemoryQueryCache","highestSequenceNumber","getTargetCount","nextTargetId","removals","matchingKeys","documentSizeMap","PersistentStreamState","MemoryRemoteDocumentCache","sizer","newDocumentChanges","forEachDocumentKey","changedDoc","MemoryRemoteDocumentChangeBuffer","LOG_TAG$4","MemoryPersistence","referenceDelegateFactory","mutationQueues","documentSize","createLruPersistence","MemoryLruDelegate","createEagerPersistence","MemoryEagerDelegate","toKey","MemoryTransaction","onTransactionStarted","onTransactionCommitted","orphanedDocuments","isReferenced","orphanedSequenceNumbers","orphanedDocumentCount","remoteDocument","orphanedAt","LOG_TAG$5","ExponentialBackoff","initialDelayMs","backoffFactor","maxDelayMs","timerPromise","lastAttemptTime","currentBaseMs","resetToMax","backoffAndRun","desiredDelayWithJitterMs","jitterDelayMs","delaySoFarMs","remainingDelayMs","LOG_TAG$6","OnlineState","OnlineStateSource","BACKOFF_INITIAL_DELAY_MS","BACKOFF_MAX_DELAY_MS","BACKOFF_FACTOR","IDLE_TIMEOUT_MS","PersistentStream","connectionTimerId","idleTimerId","credentialsProvider","Initial","closeCount","idleTimer","stream","backoff","isStarted","Starting","Open","Backoff","isOpen","performBackoff","inhibitBackoff","markIdle","handleIdleCloseTimer","cancelIdleCheck","finalState","invalidateToken","tearDown","dispatchIfNotClosed","getCloseGuardedDispatcher","startStream","rpcError","handleStreamClose","startRpc","startCloseCount","PersistentListenStream","credentials","ListenStreamConnectionBackoff","ListenStreamIdle","watchChangeProto","onWatchChange","encodedDatabaseId","addTarget","labels","unwatch","PersistentWriteStream","WriteStreamConnectionBackoff","WriteStreamIdle","handshakeComplete_","writeMutations","responseProto","writeResults","onMutationResult","onHandshakeComplete","writeHandshake","Datastore","newPersistentWriteStream","newPersistentWatchStream","commit","lookup","datastore","readVersions","recordVersion","docVersion","existingVersion","preconditionForUpdate","toMutations","unwritten","LOG_TAG$7","MAX_WATCH_STREAM_FAILURES","ONLINE_STATE_TIMEOUT_MS","OnlineStateTracker","onlineStateHandler","Unknown","watchStreamFailures","onlineStateTimer","shouldWarnClientIsOffline","handleWatchStreamStart","setAndBroadcast","OnlineStateTimeout","logClientOfflineWarningIfNecessary","Offline","handleWatchStreamFailure","Online","clearOnlineStateTimer","newState","LOG_TAG$8","MAX_PENDING_WRITES","RemoteStore","writePipeline","listenTargets","watchChangeAggregator","onlineStateTracker","watchStream","onWatchStreamOpen","onWatchStreamClose","onWatchStreamChange","writeStream","onWriteStreamOpen","onWriteStreamClose","onWriteHandshakeComplete","enableNetwork","canUseNetwork","shouldStartWatchStream","startWatchStream","fillWritePipeline","disableNetwork","disableNetworkInternal","cleanUpWatchStreamState","sendWatchRequest","sendUnwatchRequest","syncEngine","handleTargetError","raiseWatchSnapshot","requestQueryData","rejectListen","lastBatchIdRetrieved","canAddToWritePipeline","addToWritePipeline","shouldStartWriteStream","startWriteStream","outstandingWrites","handshakeComplete","applySuccessfulWrite","errorHandling","handleWriteError","handleHandshakeError","rejectFailedWrite","handleCredentialChange","applyPrimaryState","QueryListenersInfo","EventManager","onlineState","firstListen","queryInfo","applyOnlineStateChange","viewSnap","onViewSnapshot","lastListen","viewSnaps","viewSnaps_1","onWatchError","onError","onOnlineStateChange","QueryListener","queryObserver","raisedInitialEvent","includeMetadataChanges","shouldRaiseEvent","shouldRaiseInitialEvent","raiseInitialEvent","maybeOnline","waitForSyncWhenOnline","hasPendingWritesChanged","LocalViewChanges","fromSnapshot","viewSnapshot","AddedLimboDocument","RemovedLimboDocument","_syncedDocuments","syncState","limboDocuments","documentSet","computeDocChanges","previousChanges","changeSet","oldDocumentSet","newMutatedKeys","newDocumentSet","needsRefill","lastDocInLimit","newMaybeDoc","oldDoc","oldDocHadPendingMutations","newDocHasPendingMutations","changeApplied","docsEqual","shouldWaitForSyncedDocument","updateLimboDocuments","c1","c2","compareChangeType","applyTargetChange","limboChanges","synced","newSyncState","Synced","Local","shouldBeInLimbo","oldLimboDocuments","synchronizeWithPersistedState","localDocs","remoteKeys","computeInitialSnapshot","LOG_TAG$9","QueryView","remoteStore","sharedClientState","currentUser","syncEngineListener","queryViewsByQuery","queryViewsByTarget","limboTargetsByKey","limboResolutionsByTarget","limboDocumentRefs","mutationUserCallbacks","limboTargetIdGenerator","queryView","assertSubscribed","addLocalQueryTarget","initializeViewAndComputeSnapshot","viewDocChanges","synthesizedTargetChange","synchronizeViewAndComputeSnapshot","updateTrackedLimbos","targetRemainsActive","removeLocalQueryTarget","isActiveQueryTarget","clearQueryState","removeAndCleanupQuery","addPendingMutation","addMutationCallback","emitNewSnapsAndNotifyLocalStore","wrapUpdateFunctionError","updateFunction","retries","wrappedUpdateFunction","limboResolution","receivedDocument","SharedClientState","newViewSnapshots_1","setOnlineState","limboKey","event_1","queryView_1","updateQueryState","applyBatchState","batchState","processUserCallback","mutationBatchResult","updateMutationState","newCallbacks","limboKeys","removeLimboTarget","limboTargetId","limboChanges_1","limboChange","trackLimboChange","currentLimboDocs","newSnaps","docChangesInAllViews","queriesProcessed","userChanged","activeTargets","activeQueries","activeQueries_1","activeTargets_1","p_1","getAllActiveQueryTargets","synchronizeQueryViewsAndRaiseSnapshots","isLocalQueryTarget","resetLimboDocuments","newViewSnapshots","targets_1","applyTargetState","synthesizedRemoteEvent","activeTargets_2","applyActiveTargetsChange","added_1","removed_1","syncedDocuments","otherUser","GOOGLE_CREDENTIALS","FIRST_PARTY","LOG_TAG$a","CLIENT_STATE_KEY_PREFIX","MUTATION_BATCH_KEY_PREFIX","QUERY_TARGET_KEY_PREFIX","ONLINE_STATE_KEY_PREFIX","SEQUENCE_NUMBER_KEY_PREFIX","MutationMetadata","fromWebStorageEntry","validData","firestoreError","toWebStorageJSON","batchMetadata","QueryTargetMetadata","RemoteClientState","clientState","activeTargetIdsSet","SharedOnlineState","LocalClientState","addQueryTarget","removeQueryTarget","WebStorageSharedClientState","localClientId","activeClients","storageListener","handleWebStorageEvent","earlyEvents","escapedPersistenceKey","storage","localClientStorageKey","toWebStorageClientStateKey","sequenceNumberKey","clientStateKeyRe","mutationBatchKeyRe","queryTargetKeyRe","onlineStateKey","existingClients_1","storageItem","onlineStateJSON","persistClientState","fromWebStorageOnlineState","handleOnlineStateEvent","persistMutationState","removeMutationState","queryState","toWebStorageQueryTargetMetadataKey","localClientState","persistQueryTargetState","persistOnlineState","storageArea","mutationMetadata","queryTargetMetadata","fromWebStorageClientStateKey","handleClientStateEvent","fromWebStorageClientState","fromWebStorageMutationMetadata","handleMutationBatchEvent","fromWebStorageQueryTargetMetadata","handleQueryTargetEvent","fromWebStorageSequenceNumber","mutationState","mutationKey","toWebStorageMutationBatchKey","targetKey","targetMetadata","existingTargets","newTargets","addedTargets","removedTargets","seqString","parsed","MemorySharedClientState","localState","LOG_TAG$b","DOM_EXCEPTION_ABORTED","DOM_EXCEPTION_QUOTA_EXCEEDED","IndexedDbPersistenceSettings","cacheSizeBytes","experimentalTabSynchronization","MemoryPersistenceSettings","FirestoreClient","isShutdown","persistenceSettings","verifyNotShutdown","initializationDone","persistenceResult","setChangeListener","initializePersistence","maybeLruGc","initializeRest","startIndexedDbPersistence","canFallback","startMemoryPersistence","DOMException","settings","storagePrefix","remoteStoreOnlineStateChangedHandler","sharedClientStateOnlineStateChangedHandler","lruScheduler","eventMgr","removeChangeListener","getDocumentFromLocalCache","getDocumentsFromLocalCache","AsyncObserver","muted","scheduleEvent","mute","eventHandler","FieldPath$1","fieldNames","_internalPath","documentId","_DOCUMENT_ID","RESERVED","fromDotSeparatedString","OAuthToken","EmptyCredentialsProvider","changeListener","FirebaseCredentialsProvider","tokenListener","tokenCounter","getUser","addAuthTokenListener","initialTokenCounter","tokenData","removeAuthTokenListener","currentUid","getUid","FirstPartyToken","gapi","sessionIndex","authHeader","getAuthHeaderValueForFirstParty","FirstPartyCredentialsProvider","makeCredentialsProvider","isPartialObserver","implementsAnyMethods","methods_1","UserDataSource","FieldValueImpl","_methodName","DeleteFieldValueImpl","serverTimestamp","ServerTimestampFieldValueImpl","arrayUnion","ArrayUnionFieldValueImpl","arrayRemove","ArrayRemoveFieldValueImpl","NumericIncrementFieldValueImpl","_elements","_operand","PublicFieldValue","RESERVED_FIELD_REGEX","ParsedSetData","ParsedUpdateData","isWrite","dataSource","MergeSet","Update","Argument","ParseContext","arrayElement","validatePath","childContextForField","validatePathSegment","childContextForFieldPath","childContextForArray","createError","fieldDescription","DocumentKeyReference","UserDataConverter","preConverter","parseSetData","validatePlainObject","updateData","parseData","parseMergeData","validatedFieldPaths","fieldPaths_1","stringOrFieldPath","fieldPathFromDotSeparatedString","parseUpdateData","fieldMaskPaths","childContext","runPreConverter","parsedValue","parseUpdateVarargs","moreFieldsAndValues","fieldPathFromArgument","value_1","parseQueryValue","looksLikeJsonObject","parseObject","parseSentinelFieldValue","parseArray","parseScalarValue","entryIndex","array_1","parsedEntry","parsedElements","parseArrayTransformElements","numericIncrement","DEFAULT_SSL","DEFAULT_TIMESTAMPS_IN_SNAPSHOTS","DEFAULT_FORCE_LONG_POLLING","CACHE_SIZE_UNLIMITED","DEFAULT_SYNCHRONIZE_TABS","FirestoreSettings","experimentalForceLongPolling","FirestoreConfig","Firestore","databaseIdOrApp","_queue","ensureClientConfigured","_firestoreClient","clientRunning","firebaseApp","databaseIdFromApp","external_1","_config","_databaseId","settingsLiteral","newSettings","enablePersistence","configureClient","_clearPersistence","makeDatabaseInfo","DocumentReference","thisDb","otherDb","firestore","_key","_dataConverter","CollectionReference","forPath","_collectionGroup","Query$1","Transaction$1","WriteBatch","_areTimestampsInSnapshotsEnabled","_firestore","_transaction","documentRef","validateReference","DocumentSnapshot","validateSetOptions","mergeFields","fieldOrUpdateData","_mutations","_committed","verifyNotCommitted","onSnapshot","currArg","internalOptions","onSnapshotInternal","errHandler","asyncObserver","internalListener","validateGetOptions","getViaSnapshotListener","SnapshotMetadata","_document","_fromCache","_hasPendingWrites","validateSnapshotOptions","convertObject","convertValue","convertArray","QueryDocumentSnapshot","_query","opStr","whereFilterOpEnums","relationOp","validateNewFilter","directionStr","validateNewOrderBy","docOrField","boundFromDocOrFields","startAfter","endBefore","boundFromDocument","allFields","boundFromFields","components","rawValue","wrapped","QuerySnapshot","firestoreClient","existingField","validateOrderByAndInequalityMatch","inequality","_originalQuery","_snapshot","_cachedChanges","_cachedChangesIncludeMetadataChanges","convertToDocumentImpl","changesFromSnapshot","throwDocChangesMethodError","docChangesPropertiesToOverride","property","docRef","lastDoc_1","oldIndex","indexTracker_1","resultChangeType","PublicFirestore","PublicTransaction","PublicWriteBatch","PublicDocumentReference","PublicDocumentSnapshot","PublicQueryDocumentSnapshot","PublicQuery","PublicQuerySnapshot","PublicCollectionReference","firestoreNamespace","configureForFirebase","registerFirestore"],"mappings":"kHAIA,SAASA,EAAiBC,GAAM,OAAQA,GAAqB,kBAAPA,GAAoB,YAAaA,EAAMA,EAAG,WAAaA,EA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GACbpE,WAAYqE,GACZhF,kBAAmBiF,GACnBhE,iBAAkBiE,GAClBplI,MAAOslI,GACP3C,sBAAuB0C,GACvBxB,cAAe0B,GACf/E,oBAAqBgF,GACrBn1D,UAAWsoD,GACXplD,WAAY+nD,GACZnnE,YAAa8qE,GAAU9qE,YACvByqE,qBAAsBA,IAK1B,SAAS8G,GAAqB30K,GAC1BA,EAASiB,SAASsH,gBAAgB,aAAa,SAAU1F,GAAO,OAAO,IAAIqrK,GAAUrrK,KAASm2G,EAAY07D;;;;;;;;;;;;;;;;GAmB9G,SAASE,GAAkBxsK,GACvBusK,GAAqBvsK,GAEzBwsK,GAAkB50K,GAElBF,EAAQ80K,kBAAoBA","file":"js/chunk-16c62e9b.de948ab1.js","sourcesContent":["'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nfunction _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }\n\nvar firebase = _interopDefault(require('@firebase/app'));\nvar tslib_1 = require('tslib');\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Standard error codes for different ways a request can fail, as defined by:\r\n * https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\r\n *\r\n * This map is used primarily to convert from a backend error code string to\r\n * a client SDK error code string, and make sure it's in the supported set.\r\n */\r\nvar errorCodeMap = {\r\n OK: 'ok',\r\n CANCELLED: 'cancelled',\r\n UNKNOWN: 'unknown',\r\n INVALID_ARGUMENT: 'invalid-argument',\r\n DEADLINE_EXCEEDED: 'deadline-exceeded',\r\n NOT_FOUND: 'not-found',\r\n ALREADY_EXISTS: 'already-exists',\r\n PERMISSION_DENIED: 'permission-denied',\r\n UNAUTHENTICATED: 'unauthenticated',\r\n RESOURCE_EXHAUSTED: 'resource-exhausted',\r\n FAILED_PRECONDITION: 'failed-precondition',\r\n ABORTED: 'aborted',\r\n OUT_OF_RANGE: 'out-of-range',\r\n UNIMPLEMENTED: 'unimplemented',\r\n INTERNAL: 'internal',\r\n UNAVAILABLE: 'unavailable',\r\n DATA_LOSS: 'data-loss'\r\n};\r\n/**\r\n * An explicit error that can be thrown from a handler to send an error to the\r\n * client that called the function.\r\n */\r\nvar HttpsErrorImpl = /** @class */ (function (_super) {\r\n tslib_1.__extends(HttpsErrorImpl, _super);\r\n function HttpsErrorImpl(code, message, details) {\r\n var _this = _super.call(this, message) || this;\r\n // This is a workaround for a bug in TypeScript when extending Error:\r\n // tslint:disable-next-line\r\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\r\n Object.setPrototypeOf(_this, HttpsErrorImpl.prototype);\r\n _this.code = code;\r\n _this.details = details;\r\n return _this;\r\n }\r\n return HttpsErrorImpl;\r\n}(Error));\r\n/**\r\n * Takes an HTTP status code and returns the corresponding ErrorCode.\r\n * This is the standard HTTP status code -> error mapping defined in:\r\n * https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\r\n *\r\n * @param status An HTTP status code.\r\n * @return The corresponding ErrorCode, or ErrorCode.UNKNOWN if none.\r\n */\r\nfunction codeForHTTPStatus(status) {\r\n // Make sure any successful status is OK.\r\n if (status >= 200 && status < 300) {\r\n return 'ok';\r\n }\r\n switch (status) {\r\n case 0:\r\n // This can happen if the server returns 500.\r\n return 'internal';\r\n case 400:\r\n return 'invalid-argument';\r\n case 401:\r\n return 'unauthenticated';\r\n case 403:\r\n return 'permission-denied';\r\n case 404:\r\n return 'not-found';\r\n case 409:\r\n return 'aborted';\r\n case 429:\r\n return 'resource-exhausted';\r\n case 499:\r\n return 'cancelled';\r\n case 500:\r\n return 'internal';\r\n case 501:\r\n return 'unimplemented';\r\n case 503:\r\n return 'unavailable';\r\n case 504:\r\n return 'deadline-exceeded';\r\n }\r\n return 'unknown';\r\n}\r\n/**\r\n * Takes an HTTP response and returns the corresponding Error, if any.\r\n */\r\nfunction _errorForResponse(status, bodyJSON, serializer) {\r\n var code = codeForHTTPStatus(status);\r\n // Start with reasonable defaults from the status code.\r\n var description = code;\r\n var details = undefined;\r\n // Then look through the body for explicit details.\r\n try {\r\n var errorJSON = bodyJSON.error;\r\n if (errorJSON) {\r\n var status_1 = errorJSON.status;\r\n if (typeof status_1 === 'string') {\r\n if (!errorCodeMap[status_1]) {\r\n // They must've included an unknown error code in the body.\r\n return new HttpsErrorImpl('internal', 'internal');\r\n }\r\n code = errorCodeMap[status_1];\r\n }\r\n // TODO(klimt): Add better default descriptions for error enums.\r\n // The default description needs to be updated for the new code.\r\n description = status_1;\r\n var message = errorJSON.message;\r\n if (typeof message === 'string') {\r\n description = message;\r\n }\r\n details = errorJSON.details;\r\n if (details !== undefined) {\r\n details = serializer.decode(details);\r\n }\r\n }\r\n }\r\n catch (e) {\r\n // If we couldn't parse explicit error data, that's fine.\r\n }\r\n if (code === 'ok') {\r\n // Technically, there's an edge case where a developer could explicitly\r\n // return an error code of OK, and we will treat it as success, but that\r\n // seems reasonable.\r\n return null;\r\n }\r\n return new HttpsErrorImpl(code, description, details);\r\n}\n\n/**\r\n * Helper class to get metadata that should be included with a function call.\r\n */\r\nvar ContextProvider = /** @class */ (function () {\r\n function ContextProvider(app) {\r\n this.app = app;\r\n }\r\n ContextProvider.prototype.getAuthToken = function () {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n var token, e_1;\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n _a.trys.push([0, 2, , 3]);\r\n return [4 /*yield*/, this.app.INTERNAL.getToken()];\r\n case 1:\r\n token = _a.sent();\r\n if (!token) {\r\n return [2 /*return*/, undefined];\r\n }\r\n return [2 /*return*/, token.accessToken];\r\n case 2:\r\n e_1 = _a.sent();\r\n // If there's any error when trying to get the auth token, leave it off.\r\n return [2 /*return*/, undefined];\r\n case 3: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n ContextProvider.prototype.getInstanceIdToken = function () {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n var messaging, token, e_2;\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n _a.trys.push([0, 2, , 3]);\r\n // HACK: Until we have a separate instanceId package, this is a quick way\r\n // to load in the messaging instance for this app.\r\n if (!this.app.messaging) {\r\n return [2 /*return*/, undefined];\r\n }\r\n messaging = this.app.messaging();\r\n return [4 /*yield*/, messaging.getToken()];\r\n case 1:\r\n token = _a.sent();\r\n if (!token) {\r\n return [2 /*return*/, undefined];\r\n }\r\n return [2 /*return*/, token];\r\n case 2:\r\n e_2 = _a.sent();\r\n // We don't warn on this, because it usually means messaging isn't set up.\r\n // console.warn('Failed to retrieve instance id token.', e);\r\n // If there's any error when trying to get the token, leave it off.\r\n return [2 /*return*/, undefined];\r\n case 3: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n ContextProvider.prototype.getContext = function () {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n var authToken, instanceIdToken;\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, this.getAuthToken()];\r\n case 1:\r\n authToken = _a.sent();\r\n return [4 /*yield*/, this.getInstanceIdToken()];\r\n case 2:\r\n instanceIdToken = _a.sent();\r\n return [2 /*return*/, { authToken: authToken, instanceIdToken: instanceIdToken }];\r\n }\r\n });\r\n });\r\n };\r\n return ContextProvider;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar LONG_TYPE = 'type.googleapis.com/google.protobuf.Int64Value';\r\nvar UNSIGNED_LONG_TYPE = 'type.googleapis.com/google.protobuf.UInt64Value';\r\nfunction mapValues(o, f) {\r\n var result = {};\r\n for (var key in o) {\r\n if (o.hasOwnProperty(key)) {\r\n result[key] = f(o[key]);\r\n }\r\n }\r\n return result;\r\n}\r\nvar Serializer = /** @class */ (function () {\r\n function Serializer() {\r\n }\r\n // Takes data and encodes it in a JSON-friendly way, such that types such as\r\n // Date are preserved.\r\n Serializer.prototype.encode = function (data) {\r\n var _this = this;\r\n if (data === null || data === undefined) {\r\n return null;\r\n }\r\n if (data instanceof Number) {\r\n data = data.valueOf();\r\n }\r\n if (typeof data === 'number' && isFinite(data)) {\r\n // Any number in JS is safe to put directly in JSON and parse as a double\r\n // without any loss of precision.\r\n return data;\r\n }\r\n if (data === true || data === false) {\r\n return data;\r\n }\r\n if (Object.prototype.toString.call(data) === '[object String]') {\r\n return data;\r\n }\r\n if (Array.isArray(data)) {\r\n return data.map(function (x) { return _this.encode(x); });\r\n }\r\n if (typeof data === 'function' || typeof data === 'object') {\r\n return mapValues(data, function (x) { return _this.encode(x); });\r\n }\r\n // If we got this far, the data is not encodable.\r\n throw new Error('Data cannot be encoded in JSON: ' + data);\r\n };\r\n // Takes data that's been encoded in a JSON-friendly form and returns a form\r\n // with richer datatypes, such as Dates, etc.\r\n Serializer.prototype.decode = function (json) {\r\n var _this = this;\r\n if (json === null) {\r\n return json;\r\n }\r\n if (json['@type']) {\r\n switch (json['@type']) {\r\n case LONG_TYPE:\r\n // Fall through and handle this the same as unsigned.\r\n case UNSIGNED_LONG_TYPE: {\r\n // Technically, this could work return a valid number for malformed\r\n // data if there was a number followed by garbage. But it's just not\r\n // worth all the extra code to detect that case.\r\n var value = parseFloat(json.value);\r\n if (isNaN(value)) {\r\n throw new Error('Data cannot be decoded from JSON: ' + json);\r\n }\r\n return value;\r\n }\r\n default: {\r\n throw new Error('Data cannot be decoded from JSON: ' + json);\r\n }\r\n }\r\n }\r\n if (Array.isArray(json)) {\r\n return json.map(function (x) { return _this.decode(x); });\r\n }\r\n if (typeof json === 'function' || typeof json === 'object') {\r\n return mapValues(json, function (x) { return _this.decode(x); });\r\n }\r\n // Anything else is safe to return.\r\n return json;\r\n };\r\n return Serializer;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a Promise that will be rejected after the given duration.\r\n * The error will be of type HttpsErrorImpl.\r\n *\r\n * @param millis Number of milliseconds to wait before rejecting.\r\n */\r\nfunction failAfter(millis) {\r\n return new Promise(function (_, reject) {\r\n setTimeout(function () {\r\n reject(new HttpsErrorImpl('deadline-exceeded', 'deadline-exceeded'));\r\n }, millis);\r\n });\r\n}\r\n/**\r\n * The main class for the Firebase Functions SDK.\r\n */\r\nvar Service = /** @class */ (function () {\r\n /**\r\n * Creates a new Functions service for the given app and (optional) region.\r\n * @param app_ The FirebaseApp to use.\r\n * @param region_ The region to call functions in.\r\n */\r\n function Service(app_, region_) {\r\n var _this = this;\r\n if (region_ === void 0) { region_ = 'us-central1'; }\r\n this.app_ = app_;\r\n this.region_ = region_;\r\n this.serializer = new Serializer();\r\n this.emulatorOrigin = null;\r\n this.INTERNAL = {\r\n delete: function () {\r\n return _this.deleteService();\r\n }\r\n };\r\n this.contextProvider = new ContextProvider(app_);\r\n // Cancels all ongoing requests when resolved.\r\n this.cancelAllRequests = new Promise(function (resolve) {\r\n _this.deleteService = function () {\r\n return resolve();\r\n };\r\n });\r\n }\r\n Object.defineProperty(Service.prototype, \"app\", {\r\n get: function () {\r\n return this.app_;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n /**\r\n * Returns the URL for a callable with the given name.\r\n * @param name The name of the callable.\r\n */\r\n Service.prototype._url = function (name) {\r\n var projectId = this.app_.options.projectId;\r\n var region = this.region_;\r\n if (this.emulatorOrigin !== null) {\r\n var origin_1 = this.emulatorOrigin;\r\n return origin_1 + \"/\" + projectId + \"/\" + region + \"/\" + name;\r\n }\r\n return \"https://\" + region + \"-\" + projectId + \".cloudfunctions.net/\" + name;\r\n };\r\n /**\r\n * Changes this instance to point to a Cloud Functions emulator running\r\n * locally. See https://firebase.google.com/docs/functions/local-emulator\r\n *\r\n * @param origin The origin of the local emulator, such as\r\n * \"http://localhost:5005\".\r\n */\r\n Service.prototype.useFunctionsEmulator = function (origin) {\r\n this.emulatorOrigin = origin;\r\n };\r\n /**\r\n * Returns a reference to the callable https trigger with the given name.\r\n * @param name The name of the trigger.\r\n */\r\n Service.prototype.httpsCallable = function (name, options) {\r\n var _this = this;\r\n var callable = function (data) {\r\n return _this.call(name, data, options || {});\r\n };\r\n return callable;\r\n };\r\n /**\r\n * Does an HTTP POST and returns the completed response.\r\n * @param url The url to post to.\r\n * @param body The JSON body of the post.\r\n * @param headers The HTTP headers to include in the request.\r\n * @return A Promise that will succeed when the request finishes.\r\n */\r\n Service.prototype.postJSON = function (url, body, headers) {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n var response, e_1, json, e_2;\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n headers.append('Content-Type', 'application/json');\r\n _a.label = 1;\r\n case 1:\r\n _a.trys.push([1, 3, , 4]);\r\n return [4 /*yield*/, fetch(url, {\r\n method: 'POST',\r\n body: JSON.stringify(body),\r\n headers: headers\r\n })];\r\n case 2:\r\n response = _a.sent();\r\n return [3 /*break*/, 4];\r\n case 3:\r\n e_1 = _a.sent();\r\n // This could be an unhandled error on the backend, or it could be a\r\n // network error. There's no way to know, since an unhandled error on the\r\n // backend will fail to set the proper CORS header, and thus will be\r\n // treated as a network error by fetch.\r\n return [2 /*return*/, {\r\n status: 0,\r\n json: null\r\n }];\r\n case 4:\r\n json = null;\r\n _a.label = 5;\r\n case 5:\r\n _a.trys.push([5, 7, , 8]);\r\n return [4 /*yield*/, response.json()];\r\n case 6:\r\n json = _a.sent();\r\n return [3 /*break*/, 8];\r\n case 7:\r\n e_2 = _a.sent();\r\n return [3 /*break*/, 8];\r\n case 8: return [2 /*return*/, {\r\n status: response.status,\r\n json: json\r\n }];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * Calls a callable function asynchronously and returns the result.\r\n * @param name The name of the callable trigger.\r\n * @param data The data to pass as params to the function.s\r\n */\r\n Service.prototype.call = function (name, data, options) {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n var url, body, headers, context, timeout, response, error, responseData, decodedData;\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n url = this._url(name);\r\n // Encode any special types, such as dates, in the input data.\r\n data = this.serializer.encode(data);\r\n body = { data: data };\r\n headers = new Headers();\r\n return [4 /*yield*/, this.contextProvider.getContext()];\r\n case 1:\r\n context = _a.sent();\r\n if (context.authToken) {\r\n headers.append('Authorization', 'Bearer ' + context.authToken);\r\n }\r\n if (context.instanceIdToken) {\r\n headers.append('Firebase-Instance-ID-Token', context.instanceIdToken);\r\n }\r\n timeout = options.timeout || 70000;\r\n return [4 /*yield*/, Promise.race([\r\n this.postJSON(url, body, headers),\r\n failAfter(timeout),\r\n this.cancelAllRequests\r\n ])];\r\n case 2:\r\n response = _a.sent();\r\n // If service was deleted, interrupted response throws an error.\r\n if (!response) {\r\n throw new HttpsErrorImpl('cancelled', 'Firebase Functions instance was deleted.');\r\n }\r\n error = _errorForResponse(response.status, response.json, this.serializer);\r\n if (error) {\r\n throw error;\r\n }\r\n if (!response.json) {\r\n throw new HttpsErrorImpl('internal', 'Response is not valid JSON object.');\r\n }\r\n responseData = response.json.data;\r\n // TODO(klimt): For right now, allow \"result\" instead of \"data\", for\r\n // backwards compatibility.\r\n if (typeof responseData === 'undefined') {\r\n responseData = response.json.result;\r\n }\r\n if (typeof responseData === 'undefined') {\r\n // Consider the response malformed.\r\n throw new HttpsErrorImpl('internal', 'Response is missing data field.');\r\n }\r\n decodedData = this.serializer.decode(responseData);\r\n return [2 /*return*/, { data: decodedData }];\r\n }\r\n });\r\n });\r\n };\r\n return Service;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Type constant for Firebase Functions.\r\n */\r\nvar FUNCTIONS_TYPE = 'functions';\r\nfunction factory(app, unused, region) {\r\n return new Service(app, region);\r\n}\r\nfunction registerFunctions(instance) {\r\n var namespaceExports = {\r\n // no-inline\r\n Functions: Service\r\n };\r\n instance.INTERNAL.registerService(FUNCTIONS_TYPE, factory, namespaceExports, \r\n // We don't need to wait on any AppHooks.\r\n undefined, \r\n // Allow multiple functions instances per app.\r\n true);\r\n}\r\nregisterFunctions(firebase);\n\nexports.registerFunctions = registerFunctions;\n//# sourceMappingURL=index.cjs.js.map\n","// Your personal API key.\n// Get it here: https://console.cloud.google.com/google/maps-apis\nconst API_KEY = 'AIzaSyBVQbyzhJI48DjloPxlD3Sc2R6L1sb7zJg'\nconst CALLBACK_NAME = `gmapsCallback`;\n\nlet initialized = !!window.google;\nlet resolveInitPromise;\nlet rejectInitPromise;\n// This promise handles the initialization\n// status of the google maps script.\nconst initPromise = new Promise((resolve, reject) => {\n resolveInitPromise = resolve;\n rejectInitPromise = reject;\n});\n\nexport default function init() {\n // If Google Maps already is initialized\n // the `initPromise` should be resolved\n // eventually.\n if (initialized) return initPromise;\n\n initialized = true;\n // The callback function is called by\n // the Google Maps script if it is\n // successfully loaded.\n window[CALLBACK_NAME] = () => resolveInitPromise(window.google);\n\n // We inject a new script tag into\n // the `` of our HTML to load\n // the Google Maps script.\n const script = document.createElement(`script`);\n script.async = true;\n script.defer = true;\n script.src = `https://maps.googleapis.com/maps/api/js?libraries=drawing&key=${API_KEY}&callback=${CALLBACK_NAME}`;\n script.onerror = rejectInitPromise;\n document.querySelector(`head`).appendChild(script);\n\n return initPromise;\n}","import firebase from '@firebase/app';\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview Constants used in the Firebase Storage library.\r\n */\r\n/**\r\n * Domain name for firebase storage.\r\n */\r\nvar DEFAULT_HOST = 'firebasestorage.googleapis.com';\r\n/**\r\n * The key in Firebase config json for the storage bucket.\r\n */\r\nvar CONFIG_STORAGE_BUCKET_KEY = 'storageBucket';\r\n/**\r\n * 2 minutes\r\n *\r\n * The timeout for all operations except upload.\r\n */\r\nvar DEFAULT_MAX_OPERATION_RETRY_TIME = 2 * 60 * 1000;\r\n/**\r\n * 10 minutes\r\n *\r\n * The timeout for upload.\r\n */\r\nvar DEFAULT_MAX_UPLOAD_RETRY_TIME = 10 * 60 * 100;\r\n/**\r\n * This is the value of Number.MIN_SAFE_INTEGER, which is not well supported\r\n * enough for us to use it directly.\r\n */\r\nvar MIN_SAFE_INTEGER = -9007199254740991;\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar FirebaseStorageError = /** @class */ (function () {\r\n function FirebaseStorageError(code, message) {\r\n this.code_ = prependCode(code);\r\n this.message_ = 'Firebase Storage: ' + message;\r\n this.serverResponse_ = null;\r\n this.name_ = 'FirebaseError';\r\n }\r\n FirebaseStorageError.prototype.codeProp = function () {\r\n return this.code;\r\n };\r\n FirebaseStorageError.prototype.codeEquals = function (code) {\r\n return prependCode(code) === this.codeProp();\r\n };\r\n FirebaseStorageError.prototype.serverResponseProp = function () {\r\n return this.serverResponse_;\r\n };\r\n FirebaseStorageError.prototype.setServerResponseProp = function (serverResponse) {\r\n this.serverResponse_ = serverResponse;\r\n };\r\n Object.defineProperty(FirebaseStorageError.prototype, \"name\", {\r\n get: function () {\r\n return this.name_;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(FirebaseStorageError.prototype, \"code\", {\r\n get: function () {\r\n return this.code_;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(FirebaseStorageError.prototype, \"message\", {\r\n get: function () {\r\n return this.message_;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(FirebaseStorageError.prototype, \"serverResponse\", {\r\n get: function () {\r\n return this.serverResponse_;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n return FirebaseStorageError;\r\n}());\r\nvar Code = {\r\n // Shared between all platforms\r\n UNKNOWN: 'unknown',\r\n OBJECT_NOT_FOUND: 'object-not-found',\r\n BUCKET_NOT_FOUND: 'bucket-not-found',\r\n PROJECT_NOT_FOUND: 'project-not-found',\r\n QUOTA_EXCEEDED: 'quota-exceeded',\r\n UNAUTHENTICATED: 'unauthenticated',\r\n UNAUTHORIZED: 'unauthorized',\r\n RETRY_LIMIT_EXCEEDED: 'retry-limit-exceeded',\r\n INVALID_CHECKSUM: 'invalid-checksum',\r\n CANCELED: 'canceled',\r\n // JS specific\r\n INVALID_EVENT_NAME: 'invalid-event-name',\r\n INVALID_URL: 'invalid-url',\r\n INVALID_DEFAULT_BUCKET: 'invalid-default-bucket',\r\n NO_DEFAULT_BUCKET: 'no-default-bucket',\r\n CANNOT_SLICE_BLOB: 'cannot-slice-blob',\r\n SERVER_FILE_WRONG_SIZE: 'server-file-wrong-size',\r\n NO_DOWNLOAD_URL: 'no-download-url',\r\n INVALID_ARGUMENT: 'invalid-argument',\r\n INVALID_ARGUMENT_COUNT: 'invalid-argument-count',\r\n APP_DELETED: 'app-deleted',\r\n INVALID_ROOT_OPERATION: 'invalid-root-operation',\r\n INVALID_FORMAT: 'invalid-format',\r\n INTERNAL_ERROR: 'internal-error'\r\n};\r\nfunction prependCode(code) {\r\n return 'storage/' + code;\r\n}\r\nfunction unknown() {\r\n var message = 'An unknown error occurred, please check the error payload for ' +\r\n 'server response.';\r\n return new FirebaseStorageError(Code.UNKNOWN, message);\r\n}\r\nfunction objectNotFound(path) {\r\n return new FirebaseStorageError(Code.OBJECT_NOT_FOUND, \"Object '\" + path + \"' does not exist.\");\r\n}\r\nfunction quotaExceeded(bucket) {\r\n return new FirebaseStorageError(Code.QUOTA_EXCEEDED, \"Quota for bucket '\" +\r\n bucket +\r\n \"' exceeded, please view quota on \" +\r\n 'https://firebase.google.com/pricing/.');\r\n}\r\nfunction unauthenticated() {\r\n var message = 'User is not authenticated, please authenticate using Firebase ' +\r\n 'Authentication and try again.';\r\n return new FirebaseStorageError(Code.UNAUTHENTICATED, message);\r\n}\r\nfunction unauthorized(path) {\r\n return new FirebaseStorageError(Code.UNAUTHORIZED, \"User does not have permission to access '\" + path + \"'.\");\r\n}\r\nfunction retryLimitExceeded() {\r\n return new FirebaseStorageError(Code.RETRY_LIMIT_EXCEEDED, 'Max retry time for operation exceeded, please try again.');\r\n}\r\nfunction canceled() {\r\n return new FirebaseStorageError(Code.CANCELED, 'User canceled the upload/download.');\r\n}\r\nfunction invalidUrl(url) {\r\n return new FirebaseStorageError(Code.INVALID_URL, \"Invalid URL '\" + url + \"'.\");\r\n}\r\nfunction invalidDefaultBucket(bucket) {\r\n return new FirebaseStorageError(Code.INVALID_DEFAULT_BUCKET, \"Invalid default bucket '\" + bucket + \"'.\");\r\n}\r\nfunction cannotSliceBlob() {\r\n return new FirebaseStorageError(Code.CANNOT_SLICE_BLOB, 'Cannot slice blob for upload. Please retry the upload.');\r\n}\r\nfunction serverFileWrongSize() {\r\n return new FirebaseStorageError(Code.SERVER_FILE_WRONG_SIZE, 'Server recorded incorrect upload file size, please retry the upload.');\r\n}\r\nfunction noDownloadURL() {\r\n return new FirebaseStorageError(Code.NO_DOWNLOAD_URL, 'The given file does not have any download URLs.');\r\n}\r\nfunction invalidArgument(index, fnName, message) {\r\n return new FirebaseStorageError(Code.INVALID_ARGUMENT, 'Invalid argument in `' + fnName + '` at index ' + index + ': ' + message);\r\n}\r\nfunction invalidArgumentCount(argMin, argMax, fnName, real) {\r\n var countPart;\r\n var plural;\r\n if (argMin === argMax) {\r\n countPart = argMin;\r\n plural = argMin === 1 ? 'argument' : 'arguments';\r\n }\r\n else {\r\n countPart = 'between ' + argMin + ' and ' + argMax;\r\n plural = 'arguments';\r\n }\r\n return new FirebaseStorageError(Code.INVALID_ARGUMENT_COUNT, 'Invalid argument count in `' +\r\n fnName +\r\n '`: Expected ' +\r\n countPart +\r\n ' ' +\r\n plural +\r\n ', received ' +\r\n real +\r\n '.');\r\n}\r\nfunction appDeleted() {\r\n return new FirebaseStorageError(Code.APP_DELETED, 'The Firebase app was deleted.');\r\n}\r\n/**\r\n * @param name The name of the operation that was invalid.\r\n */\r\nfunction invalidRootOperation(name) {\r\n return new FirebaseStorageError(Code.INVALID_ROOT_OPERATION, \"The operation '\" +\r\n name +\r\n \"' cannot be performed on a root reference, create a non-root \" +\r\n \"reference using child, such as .child('file.png').\");\r\n}\r\n/**\r\n * @param format The format that was not valid.\r\n * @param message A message describing the format violation.\r\n */\r\nfunction invalidFormat(format, message) {\r\n return new FirebaseStorageError(Code.INVALID_FORMAT, \"String does not match format '\" + format + \"': \" + message);\r\n}\r\n/**\r\n * @param message A message describing the internal error.\r\n */\r\nfunction internalError(message) {\r\n throw new FirebaseStorageError(Code.INTERNAL_ERROR, 'Internal error: ' + message);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar StringFormat = {\r\n RAW: 'raw',\r\n BASE64: 'base64',\r\n BASE64URL: 'base64url',\r\n DATA_URL: 'data_url'\r\n};\r\nfunction formatValidator(stringFormat) {\r\n switch (stringFormat) {\r\n case StringFormat.RAW:\r\n case StringFormat.BASE64:\r\n case StringFormat.BASE64URL:\r\n case StringFormat.DATA_URL:\r\n return;\r\n default:\r\n throw 'Expected one of the event types: [' +\r\n StringFormat.RAW +\r\n ', ' +\r\n StringFormat.BASE64 +\r\n ', ' +\r\n StringFormat.BASE64URL +\r\n ', ' +\r\n StringFormat.DATA_URL +\r\n '].';\r\n }\r\n}\r\n/**\r\n * @struct\r\n */\r\nvar StringData = /** @class */ (function () {\r\n function StringData(data, opt_contentType) {\r\n this.data = data;\r\n this.contentType = opt_contentType || null;\r\n }\r\n return StringData;\r\n}());\r\nfunction dataFromString(format, string) {\r\n switch (format) {\r\n case StringFormat.RAW:\r\n return new StringData(utf8Bytes_(string));\r\n case StringFormat.BASE64:\r\n case StringFormat.BASE64URL:\r\n return new StringData(base64Bytes_(format, string));\r\n case StringFormat.DATA_URL:\r\n return new StringData(dataURLBytes_(string), dataURLContentType_(string));\r\n }\r\n // assert(false);\r\n throw unknown();\r\n}\r\nfunction utf8Bytes_(string) {\r\n var b = [];\r\n for (var i = 0; i < string.length; i++) {\r\n var c = string.charCodeAt(i);\r\n if (c <= 127) {\r\n b.push(c);\r\n }\r\n else {\r\n if (c <= 2047) {\r\n b.push(192 | (c >> 6), 128 | (c & 63));\r\n }\r\n else {\r\n if ((c & 64512) == 55296) {\r\n // The start of a surrogate pair.\r\n var valid = i < string.length - 1 &&\r\n (string.charCodeAt(i + 1) & 64512) == 56320;\r\n if (!valid) {\r\n // The second surrogate wasn't there.\r\n b.push(239, 191, 189);\r\n }\r\n else {\r\n var hi = c;\r\n var lo = string.charCodeAt(++i);\r\n c = 65536 | ((hi & 1023) << 10) | (lo & 1023);\r\n b.push(240 | (c >> 18), 128 | ((c >> 12) & 63), 128 | ((c >> 6) & 63), 128 | (c & 63));\r\n }\r\n }\r\n else {\r\n if ((c & 64512) == 56320) {\r\n // Invalid low surrogate.\r\n b.push(239, 191, 189);\r\n }\r\n else {\r\n b.push(224 | (c >> 12), 128 | ((c >> 6) & 63), 128 | (c & 63));\r\n }\r\n }\r\n }\r\n }\r\n }\r\n return new Uint8Array(b);\r\n}\r\nfunction percentEncodedBytes_(string) {\r\n var decoded;\r\n try {\r\n decoded = decodeURIComponent(string);\r\n }\r\n catch (e) {\r\n throw invalidFormat(StringFormat.DATA_URL, 'Malformed data URL.');\r\n }\r\n return utf8Bytes_(decoded);\r\n}\r\nfunction base64Bytes_(format, string) {\r\n switch (format) {\r\n case StringFormat.BASE64: {\r\n var hasMinus = string.indexOf('-') !== -1;\r\n var hasUnder = string.indexOf('_') !== -1;\r\n if (hasMinus || hasUnder) {\r\n var invalidChar = hasMinus ? '-' : '_';\r\n throw invalidFormat(format, \"Invalid character '\" +\r\n invalidChar +\r\n \"' found: is it base64url encoded?\");\r\n }\r\n break;\r\n }\r\n case StringFormat.BASE64URL: {\r\n var hasPlus = string.indexOf('+') !== -1;\r\n var hasSlash = string.indexOf('/') !== -1;\r\n if (hasPlus || hasSlash) {\r\n var invalidChar = hasPlus ? '+' : '/';\r\n throw invalidFormat(format, \"Invalid character '\" + invalidChar + \"' found: is it base64 encoded?\");\r\n }\r\n string = string.replace(/-/g, '+').replace(/_/g, '/');\r\n break;\r\n }\r\n }\r\n var bytes;\r\n try {\r\n bytes = atob(string);\r\n }\r\n catch (e) {\r\n throw invalidFormat(format, 'Invalid character found');\r\n }\r\n var array = new Uint8Array(bytes.length);\r\n for (var i = 0; i < bytes.length; i++) {\r\n array[i] = bytes.charCodeAt(i);\r\n }\r\n return array;\r\n}\r\n/**\r\n * @struct\r\n */\r\nvar DataURLParts = /** @class */ (function () {\r\n function DataURLParts(dataURL) {\r\n this.base64 = false;\r\n this.contentType = null;\r\n var matches = dataURL.match(/^data:([^,]+)?,/);\r\n if (matches === null) {\r\n throw invalidFormat(StringFormat.DATA_URL, \"Must be formatted 'data:[][;base64],\");\r\n }\r\n var middle = matches[1] || null;\r\n if (middle != null) {\r\n this.base64 = endsWith(middle, ';base64');\r\n this.contentType = this.base64\r\n ? middle.substring(0, middle.length - ';base64'.length)\r\n : middle;\r\n }\r\n this.rest = dataURL.substring(dataURL.indexOf(',') + 1);\r\n }\r\n return DataURLParts;\r\n}());\r\nfunction dataURLBytes_(string) {\r\n var parts = new DataURLParts(string);\r\n if (parts.base64) {\r\n return base64Bytes_(StringFormat.BASE64, parts.rest);\r\n }\r\n else {\r\n return percentEncodedBytes_(parts.rest);\r\n }\r\n}\r\nfunction dataURLContentType_(string) {\r\n var parts = new DataURLParts(string);\r\n return parts.contentType;\r\n}\r\nfunction endsWith(s, end) {\r\n var longEnough = s.length >= end.length;\r\n if (!longEnough) {\r\n return false;\r\n }\r\n return s.substring(s.length - end.length) === end;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar TaskEvent = {\r\n /** Triggered whenever the task changes or progress is updated. */\r\n STATE_CHANGED: 'state_changed'\r\n};\r\nvar InternalTaskState = {\r\n RUNNING: 'running',\r\n PAUSING: 'pausing',\r\n PAUSED: 'paused',\r\n SUCCESS: 'success',\r\n CANCELING: 'canceling',\r\n CANCELED: 'canceled',\r\n ERROR: 'error'\r\n};\r\nvar TaskState = {\r\n /** The task is currently transferring data. */\r\n RUNNING: 'running',\r\n /** The task was paused by the user. */\r\n PAUSED: 'paused',\r\n /** The task completed successfully. */\r\n SUCCESS: 'success',\r\n /** The task was canceled. */\r\n CANCELED: 'canceled',\r\n /** The task failed with an error. */\r\n ERROR: 'error'\r\n};\r\nfunction taskStateFromInternalTaskState(state) {\r\n switch (state) {\r\n case InternalTaskState.RUNNING:\r\n case InternalTaskState.PAUSING:\r\n case InternalTaskState.CANCELING:\r\n return TaskState.RUNNING;\r\n case InternalTaskState.PAUSED:\r\n return TaskState.PAUSED;\r\n case InternalTaskState.SUCCESS:\r\n return TaskState.SUCCESS;\r\n case InternalTaskState.CANCELED:\r\n return TaskState.CANCELED;\r\n case InternalTaskState.ERROR:\r\n return TaskState.ERROR;\r\n default:\r\n // TODO(andysoto): assert(false);\r\n return TaskState.ERROR;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview Contains methods for working with objects.\r\n */\r\nfunction contains(obj, prop) {\r\n return Object.prototype.hasOwnProperty.call(obj, prop);\r\n}\r\nfunction forEach(obj, f) {\r\n for (var key in obj) {\r\n if (contains(obj, key)) {\r\n f(key, obj[key]);\r\n }\r\n }\r\n}\r\nfunction clone(obj) {\r\n if (obj == null) {\r\n return {};\r\n }\r\n var c = {};\r\n forEach(obj, function (key, val) {\r\n c[key] = val;\r\n });\r\n return c;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview Implements the promise abstraction interface for external\r\n * (public SDK) packaging, which just passes through to the firebase-app impl.\r\n */\r\n/**\r\n * @template T\r\n * @param {function((function(T): void),\r\n * (function(!Error): void))} resolver\r\n */\r\nfunction make(resolver) {\r\n return new Promise(resolver);\r\n}\r\n/**\r\n * @template T\r\n */\r\nfunction resolve(value) {\r\n return Promise.resolve(value);\r\n}\r\nfunction reject(error) {\r\n return Promise.reject(error);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @return False if the object is undefined or null, true otherwise.\r\n */\r\nfunction isDef(p) {\r\n return p != null;\r\n}\r\nfunction isJustDef(p) {\r\n return p !== void 0;\r\n}\r\nfunction isFunction(p) {\r\n return typeof p === 'function';\r\n}\r\nfunction isObject(p) {\r\n return typeof p === 'object';\r\n}\r\nfunction isNonNullObject(p) {\r\n return isObject(p) && p !== null;\r\n}\r\nfunction isNonArrayObject(p) {\r\n return isObject(p) && !Array.isArray(p);\r\n}\r\nfunction isString(p) {\r\n return typeof p === 'string' || p instanceof String;\r\n}\r\nfunction isNumber(p) {\r\n return typeof p === 'number' || p instanceof Number;\r\n}\r\nfunction isNativeBlob(p) {\r\n return isNativeBlobDefined() && p instanceof Blob;\r\n}\r\nfunction isNativeBlobDefined() {\r\n return typeof Blob !== 'undefined';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @enum{number}\r\n */\r\nvar ErrorCode;\r\n(function (ErrorCode) {\r\n ErrorCode[ErrorCode[\"NO_ERROR\"] = 0] = \"NO_ERROR\";\r\n ErrorCode[ErrorCode[\"NETWORK_ERROR\"] = 1] = \"NETWORK_ERROR\";\r\n ErrorCode[ErrorCode[\"ABORT\"] = 2] = \"ABORT\";\r\n})(ErrorCode || (ErrorCode = {}));\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * We use this instead of goog.net.XhrIo because goog.net.XhrIo is hyuuuuge and\r\n * doesn't work in React Native on Android.\r\n */\r\nvar NetworkXhrIo = /** @class */ (function () {\r\n function NetworkXhrIo() {\r\n var _this = this;\r\n this.sent_ = false;\r\n this.xhr_ = new XMLHttpRequest();\r\n this.errorCode_ = ErrorCode.NO_ERROR;\r\n this.sendPromise_ = make(function (resolve, reject) {\r\n _this.xhr_.addEventListener('abort', function (event) {\r\n _this.errorCode_ = ErrorCode.ABORT;\r\n resolve(_this);\r\n });\r\n _this.xhr_.addEventListener('error', function (event) {\r\n _this.errorCode_ = ErrorCode.NETWORK_ERROR;\r\n resolve(_this);\r\n });\r\n _this.xhr_.addEventListener('load', function (event) {\r\n resolve(_this);\r\n });\r\n });\r\n }\r\n /**\r\n * @override\r\n */\r\n NetworkXhrIo.prototype.send = function (url, method, opt_body, opt_headers) {\r\n var _this = this;\r\n if (this.sent_) {\r\n throw internalError('cannot .send() more than once');\r\n }\r\n this.sent_ = true;\r\n this.xhr_.open(method, url, true);\r\n if (isDef(opt_headers)) {\r\n var headers = opt_headers;\r\n forEach(headers, function (key, val) {\r\n _this.xhr_.setRequestHeader(key, val.toString());\r\n });\r\n }\r\n if (isDef(opt_body)) {\r\n this.xhr_.send(opt_body);\r\n }\r\n else {\r\n this.xhr_.send();\r\n }\r\n return this.sendPromise_;\r\n };\r\n /**\r\n * @override\r\n */\r\n NetworkXhrIo.prototype.getErrorCode = function () {\r\n if (!this.sent_) {\r\n throw internalError('cannot .getErrorCode() before sending');\r\n }\r\n return this.errorCode_;\r\n };\r\n /**\r\n * @override\r\n */\r\n NetworkXhrIo.prototype.getStatus = function () {\r\n if (!this.sent_) {\r\n throw internalError('cannot .getStatus() before sending');\r\n }\r\n try {\r\n return this.xhr_.status;\r\n }\r\n catch (e) {\r\n return -1;\r\n }\r\n };\r\n /**\r\n * @override\r\n */\r\n NetworkXhrIo.prototype.getResponseText = function () {\r\n if (!this.sent_) {\r\n throw internalError('cannot .getResponseText() before sending');\r\n }\r\n return this.xhr_.responseText;\r\n };\r\n /**\r\n * Aborts the request.\r\n * @override\r\n */\r\n NetworkXhrIo.prototype.abort = function () {\r\n this.xhr_.abort();\r\n };\r\n /**\r\n * @override\r\n */\r\n NetworkXhrIo.prototype.getResponseHeader = function (header) {\r\n return this.xhr_.getResponseHeader(header);\r\n };\r\n /**\r\n * @override\r\n */\r\n NetworkXhrIo.prototype.addUploadProgressListener = function (listener) {\r\n if (isDef(this.xhr_.upload)) {\r\n this.xhr_.upload.addEventListener('progress', listener);\r\n }\r\n };\r\n /**\r\n * @override\r\n */\r\n NetworkXhrIo.prototype.removeUploadProgressListener = function (listener) {\r\n if (isDef(this.xhr_.upload)) {\r\n this.xhr_.upload.removeEventListener('progress', listener);\r\n }\r\n };\r\n return NetworkXhrIo;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Factory-like class for creating XhrIo instances.\r\n */\r\nvar XhrIoPool = /** @class */ (function () {\r\n function XhrIoPool() {\r\n }\r\n XhrIoPool.prototype.createXhrIo = function () {\r\n return new NetworkXhrIo();\r\n };\r\n return XhrIoPool;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns the Object resulting from parsing the given JSON, or null if the\r\n * given string does not represent a JSON object.\r\n */\r\nfunction jsonObjectOrNull(s) {\r\n var obj;\r\n try {\r\n obj = JSON.parse(s);\r\n }\r\n catch (e) {\r\n return null;\r\n }\r\n if (isNonArrayObject(obj)) {\r\n return obj;\r\n }\r\n else {\r\n return null;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @struct\r\n */\r\nvar Location = /** @class */ (function () {\r\n function Location(bucket, path) {\r\n this.bucket = bucket;\r\n this.path_ = path;\r\n }\r\n Object.defineProperty(Location.prototype, \"path\", {\r\n get: function () {\r\n return this.path_;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Location.prototype.fullServerUrl = function () {\r\n var encode = encodeURIComponent;\r\n return '/b/' + encode(this.bucket) + '/o/' + encode(this.path);\r\n };\r\n Location.prototype.bucketOnlyServerUrl = function () {\r\n var encode = encodeURIComponent;\r\n return '/b/' + encode(this.bucket) + '/o';\r\n };\r\n Location.makeFromBucketSpec = function (bucketString) {\r\n var bucketLocation;\r\n try {\r\n bucketLocation = Location.makeFromUrl(bucketString);\r\n }\r\n catch (e) {\r\n // Not valid URL, use as-is. This lets you put bare bucket names in\r\n // config.\r\n return new Location(bucketString, '');\r\n }\r\n if (bucketLocation.path === '') {\r\n return bucketLocation;\r\n }\r\n else {\r\n throw invalidDefaultBucket(bucketString);\r\n }\r\n };\r\n Location.makeFromUrl = function (url) {\r\n var location = null;\r\n var bucketDomain = '([A-Za-z0-9.\\\\-_]+)';\r\n function gsModify(loc) {\r\n if (loc.path.charAt(loc.path.length - 1) === '/') {\r\n loc.path_ = loc.path_.slice(0, -1);\r\n }\r\n }\r\n var gsPath = '(/(.*))?$';\r\n var path = '(/([^?#]*).*)?$';\r\n var gsRegex = new RegExp('^gs://' + bucketDomain + gsPath, 'i');\r\n var gsIndices = { bucket: 1, path: 3 };\r\n function httpModify(loc) {\r\n loc.path_ = decodeURIComponent(loc.path);\r\n }\r\n var version = 'v[A-Za-z0-9_]+';\r\n var hostRegex = DEFAULT_HOST.replace(/[.]/g, '\\\\.');\r\n var httpRegex = new RegExp(\"^https?://\" + hostRegex + \"/\" + version + \"/b/\" + bucketDomain + \"/o\" + path, 'i');\r\n var httpIndices = { bucket: 1, path: 3 };\r\n var groups = [\r\n { regex: gsRegex, indices: gsIndices, postModify: gsModify },\r\n { regex: httpRegex, indices: httpIndices, postModify: httpModify }\r\n ];\r\n for (var i = 0; i < groups.length; i++) {\r\n var group = groups[i];\r\n var captures = group.regex.exec(url);\r\n if (captures) {\r\n var bucketValue = captures[group.indices.bucket];\r\n var pathValue = captures[group.indices.path];\r\n if (!pathValue) {\r\n pathValue = '';\r\n }\r\n location = new Location(bucketValue, pathValue);\r\n group.postModify(location);\r\n break;\r\n }\r\n }\r\n if (location == null) {\r\n throw invalidUrl(url);\r\n }\r\n return location;\r\n };\r\n return Location;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview Contains helper methods for manipulating paths.\r\n */\r\n/**\r\n * @return Null if the path is already at the root.\r\n */\r\nfunction parent(path) {\r\n if (path.length == 0) {\r\n return null;\r\n }\r\n var index = path.lastIndexOf('/');\r\n if (index === -1) {\r\n return '';\r\n }\r\n var newPath = path.slice(0, index);\r\n return newPath;\r\n}\r\nfunction child(path, childPath) {\r\n var canonicalChildPath = childPath\r\n .split('/')\r\n .filter(function (component) {\r\n return component.length > 0;\r\n })\r\n .join('/');\r\n if (path.length === 0) {\r\n return canonicalChildPath;\r\n }\r\n else {\r\n return path + '/' + canonicalChildPath;\r\n }\r\n}\r\n/**\r\n * Returns the last component of a path.\r\n * '/foo/bar' -> 'bar'\r\n * '/foo/bar/baz/' -> 'baz/'\r\n * '/a' -> 'a'\r\n */\r\nfunction lastComponent(path) {\r\n var index = path.lastIndexOf('/', path.length - 2);\r\n if (index === -1) {\r\n return path;\r\n }\r\n else {\r\n return path.slice(index + 1);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction makeUrl(urlPart) {\r\n return \"https://\" + DEFAULT_HOST + \"/v0\" + urlPart;\r\n}\r\nfunction makeQueryString(params) {\r\n var encode = encodeURIComponent;\r\n var queryPart = '?';\r\n forEach(params, function (key, val) {\r\n var nextPart = encode(key) + '=' + encode(val);\r\n queryPart = queryPart + nextPart + '&';\r\n });\r\n // Chop off the extra '&' or '?' on the end\r\n queryPart = queryPart.slice(0, -1);\r\n return queryPart;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction noXform_(metadata, value) {\r\n return value;\r\n}\r\n/**\r\n * @struct\r\n */\r\nvar Mapping = /** @class */ (function () {\r\n function Mapping(server, opt_local, opt_writable, opt_xform) {\r\n this.server = server;\r\n this.local = opt_local || server;\r\n this.writable = !!opt_writable;\r\n this.xform = opt_xform || noXform_;\r\n }\r\n return Mapping;\r\n}());\r\nvar mappings_ = null;\r\nfunction xformPath(fullPath) {\r\n var valid = isString(fullPath);\r\n if (!valid || fullPath.length < 2) {\r\n return fullPath;\r\n }\r\n else {\r\n fullPath = fullPath;\r\n return lastComponent(fullPath);\r\n }\r\n}\r\nfunction getMappings() {\r\n if (mappings_) {\r\n return mappings_;\r\n }\r\n var mappings = [];\r\n mappings.push(new Mapping('bucket'));\r\n mappings.push(new Mapping('generation'));\r\n mappings.push(new Mapping('metageneration'));\r\n mappings.push(new Mapping('name', 'fullPath', true));\r\n function mappingsXformPath(metadata, fullPath) {\r\n return xformPath(fullPath);\r\n }\r\n var nameMapping = new Mapping('name');\r\n nameMapping.xform = mappingsXformPath;\r\n mappings.push(nameMapping);\r\n /**\r\n * Coerces the second param to a number, if it is defined.\r\n */\r\n function xformSize(metadata, size) {\r\n if (isDef(size)) {\r\n return +size;\r\n }\r\n else {\r\n return size;\r\n }\r\n }\r\n var sizeMapping = new Mapping('size');\r\n sizeMapping.xform = xformSize;\r\n mappings.push(sizeMapping);\r\n mappings.push(new Mapping('timeCreated'));\r\n mappings.push(new Mapping('updated'));\r\n mappings.push(new Mapping('md5Hash', null, true));\r\n mappings.push(new Mapping('cacheControl', null, true));\r\n mappings.push(new Mapping('contentDisposition', null, true));\r\n mappings.push(new Mapping('contentEncoding', null, true));\r\n mappings.push(new Mapping('contentLanguage', null, true));\r\n mappings.push(new Mapping('contentType', null, true));\r\n mappings.push(new Mapping('metadata', 'customMetadata', true));\r\n mappings_ = mappings;\r\n return mappings_;\r\n}\r\nfunction addRef(metadata, authWrapper) {\r\n function generateRef() {\r\n var bucket = metadata['bucket'];\r\n var path = metadata['fullPath'];\r\n var loc = new Location(bucket, path);\r\n return authWrapper.makeStorageReference(loc);\r\n }\r\n Object.defineProperty(metadata, 'ref', { get: generateRef });\r\n}\r\nfunction fromResource(authWrapper, resource, mappings) {\r\n var metadata = {};\r\n metadata['type'] = 'file';\r\n var len = mappings.length;\r\n for (var i = 0; i < len; i++) {\r\n var mapping = mappings[i];\r\n metadata[mapping.local] = mapping.xform(metadata, resource[mapping.server]);\r\n }\r\n addRef(metadata, authWrapper);\r\n return metadata;\r\n}\r\nfunction fromResourceString(authWrapper, resourceString, mappings) {\r\n var obj = jsonObjectOrNull(resourceString);\r\n if (obj === null) {\r\n return null;\r\n }\r\n var resource = obj;\r\n return fromResource(authWrapper, resource, mappings);\r\n}\r\nfunction downloadUrlFromResourceString(metadata, resourceString) {\r\n var obj = jsonObjectOrNull(resourceString);\r\n if (obj === null) {\r\n return null;\r\n }\r\n if (!isString(obj['downloadTokens'])) {\r\n // This can happen if objects are uploaded through GCS and retrieved\r\n // through list, so we don't want to throw an Error.\r\n return null;\r\n }\r\n var tokens = obj['downloadTokens'];\r\n if (tokens.length === 0) {\r\n return null;\r\n }\r\n var encode = encodeURIComponent;\r\n var tokensList = tokens.split(',');\r\n var urls = tokensList.map(function (token) {\r\n var bucket = metadata['bucket'];\r\n var path = metadata['fullPath'];\r\n var urlPart = '/b/' + encode(bucket) + '/o/' + encode(path);\r\n var base = makeUrl(urlPart);\r\n var queryString = makeQueryString({\r\n alt: 'media',\r\n token: token\r\n });\r\n return base + queryString;\r\n });\r\n return urls[0];\r\n}\r\nfunction toResourceString(metadata, mappings) {\r\n var resource = {};\r\n var len = mappings.length;\r\n for (var i = 0; i < len; i++) {\r\n var mapping = mappings[i];\r\n if (mapping.writable) {\r\n resource[mapping.server] = metadata[mapping.local];\r\n }\r\n }\r\n return JSON.stringify(resource);\r\n}\r\nfunction metadataValidator(p) {\r\n var validType = p && isObject(p);\r\n if (!validType) {\r\n throw 'Expected Metadata object.';\r\n }\r\n for (var key in p) {\r\n var val = p[key];\r\n if (key === 'customMetadata') {\r\n if (!isObject(val)) {\r\n throw 'Expected object for \\'customMetadata\\' mapping.';\r\n }\r\n }\r\n else {\r\n if (isNonNullObject(val)) {\r\n throw \"Mapping for '\" + key + \"' cannot be an object.\";\r\n }\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @param name Name of the function.\r\n * @param specs Argument specs.\r\n * @param passed The actual arguments passed to the function.\r\n * @throws {fbs.Error} If the arguments are invalid.\r\n */\r\nfunction validate(name, specs, passed) {\r\n var minArgs = specs.length;\r\n var maxArgs = specs.length;\r\n for (var i = 0; i < specs.length; i++) {\r\n if (specs[i].optional) {\r\n minArgs = i;\r\n break;\r\n }\r\n }\r\n var validLength = minArgs <= passed.length && passed.length <= maxArgs;\r\n if (!validLength) {\r\n throw invalidArgumentCount(minArgs, maxArgs, name, passed.length);\r\n }\r\n for (var i = 0; i < passed.length; i++) {\r\n try {\r\n specs[i].validator(passed[i]);\r\n }\r\n catch (e) {\r\n if (e instanceof Error) {\r\n throw invalidArgument(i, name, e.message);\r\n }\r\n else {\r\n throw invalidArgument(i, name, e);\r\n }\r\n }\r\n }\r\n}\r\n/**\r\n * @struct\r\n */\r\nvar ArgSpec = /** @class */ (function () {\r\n function ArgSpec(validator, opt_optional) {\r\n var self = this;\r\n this.validator = function (p) {\r\n if (self.optional && !isJustDef(p)) {\r\n return;\r\n }\r\n validator(p);\r\n };\r\n this.optional = !!opt_optional;\r\n }\r\n return ArgSpec;\r\n}());\r\nfunction and_(v1, v2) {\r\n return function (p) {\r\n v1(p);\r\n v2(p);\r\n };\r\n}\r\nfunction stringSpec(opt_validator, opt_optional) {\r\n function stringValidator(p) {\r\n if (!isString(p)) {\r\n throw 'Expected string.';\r\n }\r\n }\r\n var validator;\r\n if (opt_validator) {\r\n validator = and_(stringValidator, opt_validator);\r\n }\r\n else {\r\n validator = stringValidator;\r\n }\r\n return new ArgSpec(validator, opt_optional);\r\n}\r\nfunction uploadDataSpec() {\r\n function validator(p) {\r\n var valid = p instanceof Uint8Array ||\r\n p instanceof ArrayBuffer ||\r\n (isNativeBlobDefined() && p instanceof Blob);\r\n if (!valid) {\r\n throw 'Expected Blob or File.';\r\n }\r\n }\r\n return new ArgSpec(validator);\r\n}\r\nfunction metadataSpec(opt_optional) {\r\n return new ArgSpec(metadataValidator, opt_optional);\r\n}\r\nfunction nonNegativeNumberSpec() {\r\n function validator(p) {\r\n var valid = isNumber(p) && p >= 0;\r\n if (!valid) {\r\n throw 'Expected a number 0 or greater.';\r\n }\r\n }\r\n return new ArgSpec(validator);\r\n}\r\nfunction looseObjectSpec(opt_validator, opt_optional) {\r\n function validator(p) {\r\n var isLooseObject = p === null || (isDef(p) && p instanceof Object);\r\n if (!isLooseObject) {\r\n throw 'Expected an Object.';\r\n }\r\n if (opt_validator !== undefined && opt_validator !== null) {\r\n opt_validator(p);\r\n }\r\n }\r\n return new ArgSpec(validator, opt_optional);\r\n}\r\nfunction nullFunctionSpec(opt_optional) {\r\n function validator(p) {\r\n var valid = p === null || isFunction(p);\r\n if (!valid) {\r\n throw 'Expected a Function.';\r\n }\r\n }\r\n return new ArgSpec(validator, opt_optional);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getBlobBuilder() {\r\n if (typeof BlobBuilder !== 'undefined') {\r\n return BlobBuilder;\r\n }\r\n else if (typeof WebKitBlobBuilder !== 'undefined') {\r\n return WebKitBlobBuilder;\r\n }\r\n else {\r\n return undefined;\r\n }\r\n}\r\n/**\r\n * Concatenates one or more values together and converts them to a Blob.\r\n *\r\n * @param var_args The values that will make up the resulting blob.\r\n * @return The blob.\r\n */\r\nfunction getBlob() {\r\n var var_args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n var_args[_i] = arguments[_i];\r\n }\r\n var BlobBuilder = getBlobBuilder();\r\n if (BlobBuilder !== undefined) {\r\n var bb = new BlobBuilder();\r\n for (var i = 0; i < var_args.length; i++) {\r\n bb.append(var_args[i]);\r\n }\r\n return bb.getBlob();\r\n }\r\n else {\r\n if (isNativeBlobDefined()) {\r\n return new Blob(var_args);\r\n }\r\n else {\r\n throw Error(\"This browser doesn't seem to support creating Blobs\");\r\n }\r\n }\r\n}\r\n/**\r\n * Slices the blob. The returned blob contains data from the start byte\r\n * (inclusive) till the end byte (exclusive). Negative indices cannot be used.\r\n *\r\n * @param blob The blob to be sliced.\r\n * @param start Index of the starting byte.\r\n * @param end Index of the ending byte.\r\n * @return The blob slice or null if not supported.\r\n */\r\nfunction sliceBlob(blob, start, end) {\r\n if (blob.webkitSlice) {\r\n return blob.webkitSlice(start, end);\r\n }\r\n else if (blob.mozSlice) {\r\n return blob.mozSlice(start, end);\r\n }\r\n else if (blob.slice) {\r\n return blob.slice(start, end);\r\n }\r\n return null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @param opt_elideCopy If true, doesn't copy mutable input data\r\n * (e.g. Uint8Arrays). Pass true only if you know the objects will not be\r\n * modified after this blob's construction.\r\n */\r\nvar FbsBlob = /** @class */ (function () {\r\n function FbsBlob(data, opt_elideCopy) {\r\n var size = 0;\r\n var blobType = '';\r\n if (isNativeBlob(data)) {\r\n this.data_ = data;\r\n size = data.size;\r\n blobType = data.type;\r\n }\r\n else if (data instanceof ArrayBuffer) {\r\n if (opt_elideCopy) {\r\n this.data_ = new Uint8Array(data);\r\n }\r\n else {\r\n this.data_ = new Uint8Array(data.byteLength);\r\n this.data_.set(new Uint8Array(data));\r\n }\r\n size = this.data_.length;\r\n }\r\n else if (data instanceof Uint8Array) {\r\n if (opt_elideCopy) {\r\n this.data_ = data;\r\n }\r\n else {\r\n this.data_ = new Uint8Array(data.length);\r\n this.data_.set(data);\r\n }\r\n size = data.length;\r\n }\r\n this.size_ = size;\r\n this.type_ = blobType;\r\n }\r\n FbsBlob.prototype.size = function () {\r\n return this.size_;\r\n };\r\n FbsBlob.prototype.type = function () {\r\n return this.type_;\r\n };\r\n FbsBlob.prototype.slice = function (startByte, endByte) {\r\n if (isNativeBlob(this.data_)) {\r\n var realBlob = this.data_;\r\n var sliced = sliceBlob(realBlob, startByte, endByte);\r\n if (sliced === null) {\r\n return null;\r\n }\r\n return new FbsBlob(sliced);\r\n }\r\n else {\r\n var slice = new Uint8Array(this.data_.buffer, startByte, endByte - startByte);\r\n return new FbsBlob(slice, true);\r\n }\r\n };\r\n FbsBlob.getBlob = function () {\r\n var var_args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n var_args[_i] = arguments[_i];\r\n }\r\n if (isNativeBlobDefined()) {\r\n var blobby = var_args.map(function (val) {\r\n if (val instanceof FbsBlob) {\r\n return val.data_;\r\n }\r\n else {\r\n return val;\r\n }\r\n });\r\n return new FbsBlob(getBlob.apply(null, blobby));\r\n }\r\n else {\r\n var uint8Arrays = var_args.map(function (val) {\r\n if (isString(val)) {\r\n return dataFromString(StringFormat.RAW, val).data;\r\n }\r\n else {\r\n // Blobs don't exist, so this has to be a Uint8Array.\r\n return val.data_;\r\n }\r\n });\r\n var finalLength_1 = 0;\r\n uint8Arrays.forEach(function (array) {\r\n finalLength_1 += array.byteLength;\r\n });\r\n var merged_1 = new Uint8Array(finalLength_1);\r\n var index_1 = 0;\r\n uint8Arrays.forEach(function (array) {\r\n for (var i = 0; i < array.length; i++) {\r\n merged_1[index_1++] = array[i];\r\n }\r\n });\r\n return new FbsBlob(merged_1, true);\r\n }\r\n };\r\n FbsBlob.prototype.uploadData = function () {\r\n return this.data_;\r\n };\r\n return FbsBlob;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns true if the object is contained in the array (compared with ===).\r\n * @template T\r\n */\r\nfunction contains$1(array, elem) {\r\n return array.indexOf(elem) !== -1;\r\n}\r\n/**\r\n * Returns a shallow copy of the array or array-like object (e.g. arguments).\r\n * @template T\r\n */\r\nfunction clone$1(arraylike) {\r\n return Array.prototype.slice.call(arraylike);\r\n}\r\n/**\r\n * Removes the given element from the given array, if it is contained.\r\n * Directly modifies the passed-in array.\r\n * @template T\r\n */\r\nfunction remove(array, elem) {\r\n var i = array.indexOf(elem);\r\n if (i !== -1) {\r\n array.splice(i, 1);\r\n }\r\n}\n\nvar RequestInfo = /** @class */ (function () {\r\n function RequestInfo(url, method, \r\n /**\r\n * Returns the value with which to resolve the request's promise. Only called\r\n * if the request is successful. Throw from this function to reject the\r\n * returned Request's promise with the thrown error.\r\n * Note: The XhrIo passed to this function may be reused after this callback\r\n * returns. Do not keep a reference to it in any way.\r\n */\r\n handler, timeout) {\r\n this.url = url;\r\n this.method = method;\r\n this.handler = handler;\r\n this.timeout = timeout;\r\n this.urlParams = {};\r\n this.headers = {};\r\n this.body = null;\r\n this.errorHandler = null;\r\n /**\r\n * Called with the current number of bytes uploaded and total size (-1 if not\r\n * computable) of the request body (i.e. used to report upload progress).\r\n */\r\n this.progressCallback = null;\r\n this.successCodes = [200];\r\n this.additionalRetryCodes = [];\r\n }\r\n return RequestInfo;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Throws the UNKNOWN FirebaseStorageError if cndn is false.\r\n */\r\nfunction handlerCheck(cndn) {\r\n if (!cndn) {\r\n throw unknown();\r\n }\r\n}\r\nfunction metadataHandler(authWrapper, mappings) {\r\n function handler(xhr, text) {\r\n var metadata = fromResourceString(authWrapper, text, mappings);\r\n handlerCheck(metadata !== null);\r\n return metadata;\r\n }\r\n return handler;\r\n}\r\nfunction downloadUrlHandler(authWrapper, mappings) {\r\n function handler(xhr, text) {\r\n var metadata = fromResourceString(authWrapper, text, mappings);\r\n handlerCheck(metadata !== null);\r\n return downloadUrlFromResourceString(metadata, text);\r\n }\r\n return handler;\r\n}\r\nfunction sharedErrorHandler(location) {\r\n function errorHandler(xhr, err) {\r\n var newErr;\r\n if (xhr.getStatus() === 401) {\r\n newErr = unauthenticated();\r\n }\r\n else {\r\n if (xhr.getStatus() === 402) {\r\n newErr = quotaExceeded(location.bucket);\r\n }\r\n else {\r\n if (xhr.getStatus() === 403) {\r\n newErr = unauthorized(location.path);\r\n }\r\n else {\r\n newErr = err;\r\n }\r\n }\r\n }\r\n newErr.setServerResponseProp(err.serverResponseProp());\r\n return newErr;\r\n }\r\n return errorHandler;\r\n}\r\nfunction objectErrorHandler(location) {\r\n var shared = sharedErrorHandler(location);\r\n function errorHandler(xhr, err) {\r\n var newErr = shared(xhr, err);\r\n if (xhr.getStatus() === 404) {\r\n newErr = objectNotFound(location.path);\r\n }\r\n newErr.setServerResponseProp(err.serverResponseProp());\r\n return newErr;\r\n }\r\n return errorHandler;\r\n}\r\nfunction getMetadata(authWrapper, location, mappings) {\r\n var urlPart = location.fullServerUrl();\r\n var url = makeUrl(urlPart);\r\n var method = 'GET';\r\n var timeout = authWrapper.maxOperationRetryTime();\r\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\r\n requestInfo.errorHandler = objectErrorHandler(location);\r\n return requestInfo;\r\n}\r\nfunction getDownloadUrl(authWrapper, location, mappings) {\r\n var urlPart = location.fullServerUrl();\r\n var url = makeUrl(urlPart);\r\n var method = 'GET';\r\n var timeout = authWrapper.maxOperationRetryTime();\r\n var requestInfo = new RequestInfo(url, method, downloadUrlHandler(authWrapper, mappings), timeout);\r\n requestInfo.errorHandler = objectErrorHandler(location);\r\n return requestInfo;\r\n}\r\nfunction updateMetadata(authWrapper, location, metadata, mappings) {\r\n var urlPart = location.fullServerUrl();\r\n var url = makeUrl(urlPart);\r\n var method = 'PATCH';\r\n var body = toResourceString(metadata, mappings);\r\n var headers = { 'Content-Type': 'application/json; charset=utf-8' };\r\n var timeout = authWrapper.maxOperationRetryTime();\r\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\r\n requestInfo.headers = headers;\r\n requestInfo.body = body;\r\n requestInfo.errorHandler = objectErrorHandler(location);\r\n return requestInfo;\r\n}\r\nfunction deleteObject(authWrapper, location) {\r\n var urlPart = location.fullServerUrl();\r\n var url = makeUrl(urlPart);\r\n var method = 'DELETE';\r\n var timeout = authWrapper.maxOperationRetryTime();\r\n function handler(xhr, text) { }\r\n var requestInfo = new RequestInfo(url, method, handler, timeout);\r\n requestInfo.successCodes = [200, 204];\r\n requestInfo.errorHandler = objectErrorHandler(location);\r\n return requestInfo;\r\n}\r\nfunction determineContentType_(metadata, blob) {\r\n return ((metadata && metadata['contentType']) ||\r\n (blob && blob.type()) ||\r\n 'application/octet-stream');\r\n}\r\nfunction metadataForUpload_(location, blob, opt_metadata) {\r\n var metadata = clone(opt_metadata);\r\n metadata['fullPath'] = location.path;\r\n metadata['size'] = blob.size();\r\n if (!metadata['contentType']) {\r\n metadata['contentType'] = determineContentType_(null, blob);\r\n }\r\n return metadata;\r\n}\r\nfunction multipartUpload(authWrapper, location, mappings, blob, opt_metadata) {\r\n var urlPart = location.bucketOnlyServerUrl();\r\n var headers = {\r\n 'X-Goog-Upload-Protocol': 'multipart'\r\n };\r\n function genBoundary() {\r\n var str = '';\r\n for (var i = 0; i < 2; i++) {\r\n str =\r\n str +\r\n Math.random()\r\n .toString()\r\n .slice(2);\r\n }\r\n return str;\r\n }\r\n var boundary = genBoundary();\r\n headers['Content-Type'] = 'multipart/related; boundary=' + boundary;\r\n var metadata = metadataForUpload_(location, blob, opt_metadata);\r\n var metadataString = toResourceString(metadata, mappings);\r\n var preBlobPart = '--' +\r\n boundary +\r\n '\\r\\n' +\r\n 'Content-Type: application/json; charset=utf-8\\r\\n\\r\\n' +\r\n metadataString +\r\n '\\r\\n--' +\r\n boundary +\r\n '\\r\\n' +\r\n 'Content-Type: ' +\r\n metadata['contentType'] +\r\n '\\r\\n\\r\\n';\r\n var postBlobPart = '\\r\\n--' + boundary + '--';\r\n var body = FbsBlob.getBlob(preBlobPart, blob, postBlobPart);\r\n if (body === null) {\r\n throw cannotSliceBlob();\r\n }\r\n var urlParams = { name: metadata['fullPath'] };\r\n var url = makeUrl(urlPart);\r\n var method = 'POST';\r\n var timeout = authWrapper.maxUploadRetryTime();\r\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\r\n requestInfo.urlParams = urlParams;\r\n requestInfo.headers = headers;\r\n requestInfo.body = body.uploadData();\r\n requestInfo.errorHandler = sharedErrorHandler(location);\r\n return requestInfo;\r\n}\r\n/**\r\n * @param current The number of bytes that have been uploaded so far.\r\n * @param total The total number of bytes in the upload.\r\n * @param opt_finalized True if the server has finished the upload.\r\n * @param opt_metadata The upload metadata, should\r\n * only be passed if opt_finalized is true.\r\n * @struct\r\n */\r\nvar ResumableUploadStatus = /** @class */ (function () {\r\n function ResumableUploadStatus(current, total, finalized, metadata) {\r\n this.current = current;\r\n this.total = total;\r\n this.finalized = !!finalized;\r\n this.metadata = metadata || null;\r\n }\r\n return ResumableUploadStatus;\r\n}());\r\nfunction checkResumeHeader_(xhr, opt_allowed) {\r\n var status;\r\n try {\r\n status = xhr.getResponseHeader('X-Goog-Upload-Status');\r\n }\r\n catch (e) {\r\n handlerCheck(false);\r\n }\r\n var allowed = opt_allowed || ['active'];\r\n handlerCheck(contains$1(allowed, status));\r\n return status;\r\n}\r\nfunction createResumableUpload(authWrapper, location, mappings, blob, opt_metadata) {\r\n var urlPart = location.bucketOnlyServerUrl();\r\n var metadata = metadataForUpload_(location, blob, opt_metadata);\r\n var urlParams = { name: metadata['fullPath'] };\r\n var url = makeUrl(urlPart);\r\n var method = 'POST';\r\n var headers = {\r\n 'X-Goog-Upload-Protocol': 'resumable',\r\n 'X-Goog-Upload-Command': 'start',\r\n 'X-Goog-Upload-Header-Content-Length': blob.size(),\r\n 'X-Goog-Upload-Header-Content-Type': metadata['contentType'],\r\n 'Content-Type': 'application/json; charset=utf-8'\r\n };\r\n var body = toResourceString(metadata, mappings);\r\n var timeout = authWrapper.maxUploadRetryTime();\r\n function handler(xhr, text) {\r\n checkResumeHeader_(xhr);\r\n var url;\r\n try {\r\n url = xhr.getResponseHeader('X-Goog-Upload-URL');\r\n }\r\n catch (e) {\r\n handlerCheck(false);\r\n }\r\n handlerCheck(isString(url));\r\n return url;\r\n }\r\n var requestInfo = new RequestInfo(url, method, handler, timeout);\r\n requestInfo.urlParams = urlParams;\r\n requestInfo.headers = headers;\r\n requestInfo.body = body;\r\n requestInfo.errorHandler = sharedErrorHandler(location);\r\n return requestInfo;\r\n}\r\n/**\r\n * @param url From a call to fbs.requests.createResumableUpload.\r\n */\r\nfunction getResumableUploadStatus(authWrapper, location, url, blob) {\r\n var headers = { 'X-Goog-Upload-Command': 'query' };\r\n function handler(xhr, text) {\r\n var status = checkResumeHeader_(xhr, ['active', 'final']);\r\n var sizeString;\r\n try {\r\n sizeString = xhr.getResponseHeader('X-Goog-Upload-Size-Received');\r\n }\r\n catch (e) {\r\n handlerCheck(false);\r\n }\r\n var size = parseInt(sizeString, 10);\r\n handlerCheck(!isNaN(size));\r\n return new ResumableUploadStatus(size, blob.size(), status === 'final');\r\n }\r\n var method = 'POST';\r\n var timeout = authWrapper.maxUploadRetryTime();\r\n var requestInfo = new RequestInfo(url, method, handler, timeout);\r\n requestInfo.headers = headers;\r\n requestInfo.errorHandler = sharedErrorHandler(location);\r\n return requestInfo;\r\n}\r\n/**\r\n * Any uploads via the resumable upload API must transfer a number of bytes\r\n * that is a multiple of this number.\r\n */\r\nvar resumableUploadChunkSize = 256 * 1024;\r\n/**\r\n * @param url From a call to fbs.requests.createResumableUpload.\r\n * @param chunkSize Number of bytes to upload.\r\n * @param opt_status The previous status.\r\n * If not passed or null, we start from the beginning.\r\n * @throws fbs.Error If the upload is already complete, the passed in status\r\n * has a final size inconsistent with the blob, or the blob cannot be sliced\r\n * for upload.\r\n */\r\nfunction continueResumableUpload(location, authWrapper, url, blob, chunkSize, mappings, opt_status, opt_progressCallback) {\r\n // TODO(andysoto): standardize on internal asserts\r\n // assert(!(opt_status && opt_status.finalized));\r\n var status = new ResumableUploadStatus(0, 0);\r\n if (opt_status) {\r\n status.current = opt_status.current;\r\n status.total = opt_status.total;\r\n }\r\n else {\r\n status.current = 0;\r\n status.total = blob.size();\r\n }\r\n if (blob.size() !== status.total) {\r\n throw serverFileWrongSize();\r\n }\r\n var bytesLeft = status.total - status.current;\r\n var bytesToUpload = bytesLeft;\r\n if (chunkSize > 0) {\r\n bytesToUpload = Math.min(bytesToUpload, chunkSize);\r\n }\r\n var startByte = status.current;\r\n var endByte = startByte + bytesToUpload;\r\n var uploadCommand = bytesToUpload === bytesLeft ? 'upload, finalize' : 'upload';\r\n var headers = {\r\n 'X-Goog-Upload-Command': uploadCommand,\r\n 'X-Goog-Upload-Offset': status.current\r\n };\r\n var body = blob.slice(startByte, endByte);\r\n if (body === null) {\r\n throw cannotSliceBlob();\r\n }\r\n function handler(xhr, text) {\r\n // TODO(andysoto): Verify the MD5 of each uploaded range:\r\n // the 'x-range-md5' header comes back with status code 308 responses.\r\n // We'll only be able to bail out though, because you can't re-upload a\r\n // range that you previously uploaded.\r\n var uploadStatus = checkResumeHeader_(xhr, ['active', 'final']);\r\n var newCurrent = status.current + bytesToUpload;\r\n var size = blob.size();\r\n var metadata;\r\n if (uploadStatus === 'final') {\r\n metadata = metadataHandler(authWrapper, mappings)(xhr, text);\r\n }\r\n else {\r\n metadata = null;\r\n }\r\n return new ResumableUploadStatus(newCurrent, size, uploadStatus === 'final', metadata);\r\n }\r\n var method = 'POST';\r\n var timeout = authWrapper.maxUploadRetryTime();\r\n var requestInfo = new RequestInfo(url, method, handler, timeout);\r\n requestInfo.headers = headers;\r\n requestInfo.body = body.uploadData();\r\n requestInfo.progressCallback = opt_progressCallback || null;\r\n requestInfo.errorHandler = sharedErrorHandler(location);\r\n return requestInfo;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @struct\r\n */\r\nvar Observer = /** @class */ (function () {\r\n function Observer(nextOrObserver, opt_error, opt_complete) {\r\n var asFunctions = isFunction(nextOrObserver) ||\r\n isDef(opt_error) ||\r\n isDef(opt_complete);\r\n if (asFunctions) {\r\n this.next = nextOrObserver;\r\n this.error = opt_error || null;\r\n this.complete = opt_complete || null;\r\n }\r\n else {\r\n var observer = nextOrObserver;\r\n this.next = observer.next || null;\r\n this.error = observer.error || null;\r\n this.complete = observer.complete || null;\r\n }\r\n }\r\n return Observer;\r\n}());\n\nvar UploadTaskSnapshot = /** @class */ (function () {\r\n function UploadTaskSnapshot(bytesTransferred, totalBytes, state, metadata, task, ref) {\r\n this.bytesTransferred = bytesTransferred;\r\n this.totalBytes = totalBytes;\r\n this.state = state;\r\n this.metadata = metadata;\r\n this.task = task;\r\n this.ref = ref;\r\n }\r\n return UploadTaskSnapshot;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a function that invokes f with its arguments asynchronously as a\r\n * microtask, i.e. as soon as possible after the current script returns back\r\n * into browser code.\r\n */\r\nfunction async(f) {\r\n return function () {\r\n var argsToForward = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n argsToForward[_i] = arguments[_i];\r\n }\r\n resolve(true).then(function () {\r\n f.apply(null, argsToForward);\r\n });\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Represents a blob being uploaded. Can be used to pause/resume/cancel the\r\n * upload and manage callbacks for various events.\r\n */\r\nvar UploadTask = /** @class */ (function () {\r\n /**\r\n * @param ref The firebaseStorage.Reference object this task came\r\n * from, untyped to avoid cyclic dependencies.\r\n * @param blob The blob to upload.\r\n */\r\n function UploadTask(ref, authWrapper, location, mappings, blob, metadata) {\r\n var _this = this;\r\n if (metadata === void 0) { metadata = null; }\r\n this.transferred_ = 0;\r\n this.needToFetchStatus_ = false;\r\n this.needToFetchMetadata_ = false;\r\n this.observers_ = [];\r\n this.error_ = null;\r\n this.uploadUrl_ = null;\r\n this.request_ = null;\r\n this.chunkMultiplier_ = 1;\r\n this.resolve_ = null;\r\n this.reject_ = null;\r\n this.ref_ = ref;\r\n this.authWrapper_ = authWrapper;\r\n this.location_ = location;\r\n this.blob_ = blob;\r\n this.metadata_ = metadata;\r\n this.mappings_ = mappings;\r\n this.resumable_ = this.shouldDoResumable_(this.blob_);\r\n this.state_ = InternalTaskState.RUNNING;\r\n this.errorHandler_ = function (error) {\r\n _this.request_ = null;\r\n _this.chunkMultiplier_ = 1;\r\n if (error.codeEquals(Code.CANCELED)) {\r\n _this.needToFetchStatus_ = true;\r\n _this.completeTransitions_();\r\n }\r\n else {\r\n _this.error_ = error;\r\n _this.transition_(InternalTaskState.ERROR);\r\n }\r\n };\r\n this.metadataErrorHandler_ = function (error) {\r\n _this.request_ = null;\r\n if (error.codeEquals(Code.CANCELED)) {\r\n _this.completeTransitions_();\r\n }\r\n else {\r\n _this.error_ = error;\r\n _this.transition_(InternalTaskState.ERROR);\r\n }\r\n };\r\n this.promise_ = make(function (resolve, reject) {\r\n _this.resolve_ = resolve;\r\n _this.reject_ = reject;\r\n _this.start_();\r\n });\r\n // Prevent uncaught rejections on the internal promise from bubbling out\r\n // to the top level with a dummy handler.\r\n this.promise_.then(null, function () { });\r\n }\r\n UploadTask.prototype.makeProgressCallback_ = function () {\r\n var _this = this;\r\n var sizeBefore = this.transferred_;\r\n return function (loaded, total) {\r\n _this.updateProgress_(sizeBefore + loaded);\r\n };\r\n };\r\n UploadTask.prototype.shouldDoResumable_ = function (blob) {\r\n return blob.size() > 256 * 1024;\r\n };\r\n UploadTask.prototype.start_ = function () {\r\n if (this.state_ !== InternalTaskState.RUNNING) {\r\n // This can happen if someone pauses us in a resume callback, for example.\r\n return;\r\n }\r\n if (this.request_ !== null) {\r\n return;\r\n }\r\n if (this.resumable_) {\r\n if (this.uploadUrl_ === null) {\r\n this.createResumable_();\r\n }\r\n else {\r\n if (this.needToFetchStatus_) {\r\n this.fetchStatus_();\r\n }\r\n else {\r\n if (this.needToFetchMetadata_) {\r\n // Happens if we miss the metadata on upload completion.\r\n this.fetchMetadata_();\r\n }\r\n else {\r\n this.continueUpload_();\r\n }\r\n }\r\n }\r\n }\r\n else {\r\n this.oneShotUpload_();\r\n }\r\n };\r\n UploadTask.prototype.resolveToken_ = function (callback) {\r\n var _this = this;\r\n this.authWrapper_.getAuthToken().then(function (authToken) {\r\n switch (_this.state_) {\r\n case InternalTaskState.RUNNING:\r\n callback(authToken);\r\n break;\r\n case InternalTaskState.CANCELING:\r\n _this.transition_(InternalTaskState.CANCELED);\r\n break;\r\n case InternalTaskState.PAUSING:\r\n _this.transition_(InternalTaskState.PAUSED);\r\n break;\r\n default:\r\n }\r\n });\r\n };\r\n // TODO(andysoto): assert false\r\n UploadTask.prototype.createResumable_ = function () {\r\n var _this = this;\r\n this.resolveToken_(function (authToken) {\r\n var requestInfo = createResumableUpload(_this.authWrapper_, _this.location_, _this.mappings_, _this.blob_, _this.metadata_);\r\n var createRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\r\n _this.request_ = createRequest;\r\n createRequest.getPromise().then(function (url) {\r\n _this.request_ = null;\r\n _this.uploadUrl_ = url;\r\n _this.needToFetchStatus_ = false;\r\n _this.completeTransitions_();\r\n }, _this.errorHandler_);\r\n });\r\n };\r\n UploadTask.prototype.fetchStatus_ = function () {\r\n var _this = this;\r\n // TODO(andysoto): assert(this.uploadUrl_ !== null);\r\n var url = this.uploadUrl_;\r\n this.resolveToken_(function (authToken) {\r\n var requestInfo = getResumableUploadStatus(_this.authWrapper_, _this.location_, url, _this.blob_);\r\n var statusRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\r\n _this.request_ = statusRequest;\r\n statusRequest.getPromise().then(function (status) {\r\n status = status;\r\n _this.request_ = null;\r\n _this.updateProgress_(status.current);\r\n _this.needToFetchStatus_ = false;\r\n if (status.finalized) {\r\n _this.needToFetchMetadata_ = true;\r\n }\r\n _this.completeTransitions_();\r\n }, _this.errorHandler_);\r\n });\r\n };\r\n UploadTask.prototype.continueUpload_ = function () {\r\n var _this = this;\r\n var chunkSize = resumableUploadChunkSize * this.chunkMultiplier_;\r\n var status = new ResumableUploadStatus(this.transferred_, this.blob_.size());\r\n // TODO(andysoto): assert(this.uploadUrl_ !== null);\r\n var url = this.uploadUrl_;\r\n this.resolveToken_(function (authToken) {\r\n var requestInfo;\r\n try {\r\n requestInfo = continueResumableUpload(_this.location_, _this.authWrapper_, url, _this.blob_, chunkSize, _this.mappings_, status, _this.makeProgressCallback_());\r\n }\r\n catch (e) {\r\n _this.error_ = e;\r\n _this.transition_(InternalTaskState.ERROR);\r\n return;\r\n }\r\n var uploadRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\r\n _this.request_ = uploadRequest;\r\n uploadRequest\r\n .getPromise()\r\n .then(function (newStatus) {\r\n _this.increaseMultiplier_();\r\n _this.request_ = null;\r\n _this.updateProgress_(newStatus.current);\r\n if (newStatus.finalized) {\r\n _this.metadata_ = newStatus.metadata;\r\n _this.transition_(InternalTaskState.SUCCESS);\r\n }\r\n else {\r\n _this.completeTransitions_();\r\n }\r\n }, _this.errorHandler_);\r\n });\r\n };\r\n UploadTask.prototype.increaseMultiplier_ = function () {\r\n var currentSize = resumableUploadChunkSize * this.chunkMultiplier_;\r\n // Max chunk size is 32M.\r\n if (currentSize < 32 * 1024 * 1024) {\r\n this.chunkMultiplier_ *= 2;\r\n }\r\n };\r\n UploadTask.prototype.fetchMetadata_ = function () {\r\n var _this = this;\r\n this.resolveToken_(function (authToken) {\r\n var requestInfo = getMetadata(_this.authWrapper_, _this.location_, _this.mappings_);\r\n var metadataRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\r\n _this.request_ = metadataRequest;\r\n metadataRequest.getPromise().then(function (metadata) {\r\n _this.request_ = null;\r\n _this.metadata_ = metadata;\r\n _this.transition_(InternalTaskState.SUCCESS);\r\n }, _this.metadataErrorHandler_);\r\n });\r\n };\r\n UploadTask.prototype.oneShotUpload_ = function () {\r\n var _this = this;\r\n this.resolveToken_(function (authToken) {\r\n var requestInfo = multipartUpload(_this.authWrapper_, _this.location_, _this.mappings_, _this.blob_, _this.metadata_);\r\n var multipartRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\r\n _this.request_ = multipartRequest;\r\n multipartRequest.getPromise().then(function (metadata) {\r\n _this.request_ = null;\r\n _this.metadata_ = metadata;\r\n _this.updateProgress_(_this.blob_.size());\r\n _this.transition_(InternalTaskState.SUCCESS);\r\n }, _this.errorHandler_);\r\n });\r\n };\r\n UploadTask.prototype.updateProgress_ = function (transferred) {\r\n var old = this.transferred_;\r\n this.transferred_ = transferred;\r\n // A progress update can make the \"transferred\" value smaller (e.g. a\r\n // partial upload not completed by server, after which the \"transferred\"\r\n // value may reset to the value at the beginning of the request).\r\n if (this.transferred_ !== old) {\r\n this.notifyObservers_();\r\n }\r\n };\r\n UploadTask.prototype.transition_ = function (state) {\r\n if (this.state_ === state) {\r\n return;\r\n }\r\n switch (state) {\r\n case InternalTaskState.CANCELING:\r\n // TODO(andysoto):\r\n // assert(this.state_ === InternalTaskState.RUNNING ||\r\n // this.state_ === InternalTaskState.PAUSING);\r\n this.state_ = state;\r\n if (this.request_ !== null) {\r\n this.request_.cancel();\r\n }\r\n break;\r\n case InternalTaskState.PAUSING:\r\n // TODO(andysoto):\r\n // assert(this.state_ === InternalTaskState.RUNNING);\r\n this.state_ = state;\r\n if (this.request_ !== null) {\r\n this.request_.cancel();\r\n }\r\n break;\r\n case InternalTaskState.RUNNING:\r\n // TODO(andysoto):\r\n // assert(this.state_ === InternalTaskState.PAUSED ||\r\n // this.state_ === InternalTaskState.PAUSING);\r\n var wasPaused = this.state_ === InternalTaskState.PAUSED;\r\n this.state_ = state;\r\n if (wasPaused) {\r\n this.notifyObservers_();\r\n this.start_();\r\n }\r\n break;\r\n case InternalTaskState.PAUSED:\r\n // TODO(andysoto):\r\n // assert(this.state_ === InternalTaskState.PAUSING);\r\n this.state_ = state;\r\n this.notifyObservers_();\r\n break;\r\n case InternalTaskState.CANCELED:\r\n // TODO(andysoto):\r\n // assert(this.state_ === InternalTaskState.PAUSED ||\r\n // this.state_ === InternalTaskState.CANCELING);\r\n this.error_ = canceled();\r\n this.state_ = state;\r\n this.notifyObservers_();\r\n break;\r\n case InternalTaskState.ERROR:\r\n // TODO(andysoto):\r\n // assert(this.state_ === InternalTaskState.RUNNING ||\r\n // this.state_ === InternalTaskState.PAUSING ||\r\n // this.state_ === InternalTaskState.CANCELING);\r\n this.state_ = state;\r\n this.notifyObservers_();\r\n break;\r\n case InternalTaskState.SUCCESS:\r\n // TODO(andysoto):\r\n // assert(this.state_ === InternalTaskState.RUNNING ||\r\n // this.state_ === InternalTaskState.PAUSING ||\r\n // this.state_ === InternalTaskState.CANCELING);\r\n this.state_ = state;\r\n this.notifyObservers_();\r\n break;\r\n }\r\n };\r\n UploadTask.prototype.completeTransitions_ = function () {\r\n switch (this.state_) {\r\n case InternalTaskState.PAUSING:\r\n this.transition_(InternalTaskState.PAUSED);\r\n break;\r\n case InternalTaskState.CANCELING:\r\n this.transition_(InternalTaskState.CANCELED);\r\n break;\r\n case InternalTaskState.RUNNING:\r\n this.start_();\r\n break;\r\n default:\r\n // TODO(andysoto): assert(false);\r\n break;\r\n }\r\n };\r\n Object.defineProperty(UploadTask.prototype, \"snapshot\", {\r\n get: function () {\r\n var externalState = taskStateFromInternalTaskState(this.state_);\r\n return new UploadTaskSnapshot(this.transferred_, this.blob_.size(), externalState, this.metadata_, this, this.ref_);\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n /**\r\n * Adds a callback for an event.\r\n * @param type The type of event to listen for.\r\n */\r\n UploadTask.prototype.on = function (type, nextOrObserver, error, completed) {\r\n if (nextOrObserver === void 0) { nextOrObserver = undefined; }\r\n if (error === void 0) { error = undefined; }\r\n if (completed === void 0) { completed = undefined; }\r\n function typeValidator(_p) {\r\n if (type !== TaskEvent.STATE_CHANGED) {\r\n throw \"Expected one of the event types: [\" + TaskEvent.STATE_CHANGED + \"].\";\r\n }\r\n }\r\n var nextOrObserverMessage = 'Expected a function or an Object with one of ' +\r\n '`next`, `error`, `complete` properties.';\r\n var nextValidator = nullFunctionSpec(true).validator;\r\n var observerValidator = looseObjectSpec(null, true).validator;\r\n function nextOrObserverValidator(p) {\r\n try {\r\n nextValidator(p);\r\n return;\r\n }\r\n catch (e) { }\r\n try {\r\n observerValidator(p);\r\n var anyDefined = isJustDef(p['next']) ||\r\n isJustDef(p['error']) ||\r\n isJustDef(p['complete']);\r\n if (!anyDefined) {\r\n throw '';\r\n }\r\n return;\r\n }\r\n catch (e) {\r\n throw nextOrObserverMessage;\r\n }\r\n }\r\n var specs = [\r\n stringSpec(typeValidator),\r\n looseObjectSpec(nextOrObserverValidator, true),\r\n nullFunctionSpec(true),\r\n nullFunctionSpec(true)\r\n ];\r\n validate('on', specs, arguments);\r\n var self = this;\r\n function makeBinder(specs) {\r\n function binder(nextOrObserver, error, opt_complete) {\r\n if (specs !== null) {\r\n validate('on', specs, arguments);\r\n }\r\n var observer = new Observer(nextOrObserver, error, completed);\r\n self.addObserver_(observer);\r\n return function () {\r\n self.removeObserver_(observer);\r\n };\r\n }\r\n return binder;\r\n }\r\n function binderNextOrObserverValidator(p) {\r\n if (p === null) {\r\n throw nextOrObserverMessage;\r\n }\r\n nextOrObserverValidator(p);\r\n }\r\n var binderSpecs = [\r\n looseObjectSpec(binderNextOrObserverValidator),\r\n nullFunctionSpec(true),\r\n nullFunctionSpec(true)\r\n ];\r\n var typeOnly = !(isJustDef(nextOrObserver) ||\r\n isJustDef(error) ||\r\n isJustDef(completed));\r\n if (typeOnly) {\r\n return makeBinder(binderSpecs);\r\n }\r\n else {\r\n return makeBinder(null)(nextOrObserver, error, completed);\r\n }\r\n };\r\n /**\r\n * This object behaves like a Promise, and resolves with its snapshot data\r\n * when the upload completes.\r\n * @param onFulfilled The fulfillment callback. Promise chaining works as normal.\r\n * @param onRejected The rejection callback.\r\n */\r\n UploadTask.prototype.then = function (onFulfilled, onRejected) {\r\n // These casts are needed so that TypeScript can infer the types of the\r\n // resulting Promise.\r\n return this.promise_.then(onFulfilled, onRejected);\r\n };\r\n /**\r\n * Equivalent to calling `then(null, onRejected)`.\r\n */\r\n UploadTask.prototype.catch = function (onRejected) {\r\n return this.then(null, onRejected);\r\n };\r\n /**\r\n * Adds the given observer.\r\n */\r\n UploadTask.prototype.addObserver_ = function (observer) {\r\n this.observers_.push(observer);\r\n this.notifyObserver_(observer);\r\n };\r\n /**\r\n * Removes the given observer.\r\n */\r\n UploadTask.prototype.removeObserver_ = function (observer) {\r\n remove(this.observers_, observer);\r\n };\r\n UploadTask.prototype.notifyObservers_ = function () {\r\n var _this = this;\r\n this.finishPromise_();\r\n var observers = clone$1(this.observers_);\r\n observers.forEach(function (observer) {\r\n _this.notifyObserver_(observer);\r\n });\r\n };\r\n UploadTask.prototype.finishPromise_ = function () {\r\n if (this.resolve_ !== null) {\r\n var triggered = true;\r\n switch (taskStateFromInternalTaskState(this.state_)) {\r\n case TaskState.SUCCESS:\r\n async(this.resolve_.bind(null, this.snapshot))();\r\n break;\r\n case TaskState.CANCELED:\r\n case TaskState.ERROR:\r\n var toCall = this.reject_;\r\n async(toCall.bind(null, this.error_))();\r\n break;\r\n default:\r\n triggered = false;\r\n break;\r\n }\r\n if (triggered) {\r\n this.resolve_ = null;\r\n this.reject_ = null;\r\n }\r\n }\r\n };\r\n UploadTask.prototype.notifyObserver_ = function (observer) {\r\n var externalState = taskStateFromInternalTaskState(this.state_);\r\n switch (externalState) {\r\n case TaskState.RUNNING:\r\n case TaskState.PAUSED:\r\n if (observer.next !== null) {\r\n async(observer.next.bind(observer, this.snapshot))();\r\n }\r\n break;\r\n case TaskState.SUCCESS:\r\n if (observer.complete !== null) {\r\n async(observer.complete.bind(observer))();\r\n }\r\n break;\r\n case TaskState.CANCELED:\r\n case TaskState.ERROR:\r\n if (observer.error !== null) {\r\n async(observer.error.bind(observer, this.error_))();\r\n }\r\n break;\r\n default:\r\n // TODO(andysoto): assert(false);\r\n if (observer.error !== null) {\r\n async(observer.error.bind(observer, this.error_))();\r\n }\r\n }\r\n };\r\n /**\r\n * Resumes a paused task. Has no effect on a currently running or failed task.\r\n * @return True if the operation took effect, false if ignored.\r\n */\r\n UploadTask.prototype.resume = function () {\r\n validate('resume', [], arguments);\r\n var valid = this.state_ === InternalTaskState.PAUSED ||\r\n this.state_ === InternalTaskState.PAUSING;\r\n if (valid) {\r\n this.transition_(InternalTaskState.RUNNING);\r\n }\r\n return valid;\r\n };\r\n /**\r\n * Pauses a currently running task. Has no effect on a paused or failed task.\r\n * @return True if the operation took effect, false if ignored.\r\n */\r\n UploadTask.prototype.pause = function () {\r\n validate('pause', [], arguments);\r\n var valid = this.state_ === InternalTaskState.RUNNING;\r\n if (valid) {\r\n this.transition_(InternalTaskState.PAUSING);\r\n }\r\n return valid;\r\n };\r\n /**\r\n * Cancels a currently running or paused task. Has no effect on a complete or\r\n * failed task.\r\n * @return True if the operation took effect, false if ignored.\r\n */\r\n UploadTask.prototype.cancel = function () {\r\n validate('cancel', [], arguments);\r\n var valid = this.state_ === InternalTaskState.RUNNING ||\r\n this.state_ === InternalTaskState.PAUSING;\r\n if (valid) {\r\n this.transition_(InternalTaskState.CANCELING);\r\n }\r\n return valid;\r\n };\r\n return UploadTask;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provides methods to interact with a bucket in the Firebase Storage service.\r\n * @param location An fbs.location, or the URL at\r\n * which to base this object, in one of the following forms:\r\n * gs:///\r\n * http[s]://firebasestorage.googleapis.com/\r\n * /b//o/\r\n * Any query or fragment strings will be ignored in the http[s]\r\n * format. If no value is passed, the storage object will use a URL based on\r\n * the project ID of the base firebase.App instance.\r\n */\r\nvar Reference = /** @class */ (function () {\r\n function Reference(authWrapper, location) {\r\n this.authWrapper = authWrapper;\r\n if (location instanceof Location) {\r\n this.location = location;\r\n }\r\n else {\r\n this.location = Location.makeFromUrl(location);\r\n }\r\n }\r\n /**\r\n * @return The URL for the bucket and path this object references,\r\n * in the form gs:///\r\n * @override\r\n */\r\n Reference.prototype.toString = function () {\r\n validate('toString', [], arguments);\r\n return 'gs://' + this.location.bucket + '/' + this.location.path;\r\n };\r\n Reference.prototype.newRef = function (authWrapper, location) {\r\n return new Reference(authWrapper, location);\r\n };\r\n Reference.prototype.mappings = function () {\r\n return getMappings();\r\n };\r\n /**\r\n * @return A reference to the object obtained by\r\n * appending childPath, removing any duplicate, beginning, or trailing\r\n * slashes.\r\n */\r\n Reference.prototype.child = function (childPath) {\r\n validate('child', [stringSpec()], arguments);\r\n var newPath = child(this.location.path, childPath);\r\n var location = new Location(this.location.bucket, newPath);\r\n return this.newRef(this.authWrapper, location);\r\n };\r\n Object.defineProperty(Reference.prototype, \"parent\", {\r\n /**\r\n * @return A reference to the parent of the\r\n * current object, or null if the current object is the root.\r\n */\r\n get: function () {\r\n var newPath = parent(this.location.path);\r\n if (newPath === null) {\r\n return null;\r\n }\r\n var location = new Location(this.location.bucket, newPath);\r\n return this.newRef(this.authWrapper, location);\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(Reference.prototype, \"root\", {\r\n /**\r\n * @return An reference to the root of this\r\n * object's bucket.\r\n */\r\n get: function () {\r\n var location = new Location(this.location.bucket, '');\r\n return this.newRef(this.authWrapper, location);\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(Reference.prototype, \"bucket\", {\r\n get: function () {\r\n return this.location.bucket;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(Reference.prototype, \"fullPath\", {\r\n get: function () {\r\n return this.location.path;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(Reference.prototype, \"name\", {\r\n get: function () {\r\n return lastComponent(this.location.path);\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(Reference.prototype, \"storage\", {\r\n get: function () {\r\n return this.authWrapper.service();\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n /**\r\n * Uploads a blob to this object's location.\r\n * @param data The blob to upload.\r\n * @return An UploadTask that lets you control and\r\n * observe the upload.\r\n */\r\n Reference.prototype.put = function (data, metadata) {\r\n if (metadata === void 0) { metadata = null; }\r\n validate('put', [uploadDataSpec(), metadataSpec(true)], arguments);\r\n this.throwIfRoot_('put');\r\n return new UploadTask(this, this.authWrapper, this.location, this.mappings(), new FbsBlob(data), metadata);\r\n };\r\n /**\r\n * Uploads a string to this object's location.\r\n * @param string The string to upload.\r\n * @param opt_format The format of the string to upload.\r\n * @return An UploadTask that lets you control and\r\n * observe the upload.\r\n */\r\n Reference.prototype.putString = function (string, format, opt_metadata) {\r\n if (format === void 0) { format = StringFormat.RAW; }\r\n validate('putString', [\r\n stringSpec(),\r\n stringSpec(formatValidator, true),\r\n metadataSpec(true)\r\n ], arguments);\r\n this.throwIfRoot_('putString');\r\n var data = dataFromString(format, string);\r\n var metadata = clone(opt_metadata);\r\n if (!isDef(metadata['contentType']) && isDef(data.contentType)) {\r\n metadata['contentType'] = data.contentType;\r\n }\r\n return new UploadTask(this, this.authWrapper, this.location, this.mappings(), new FbsBlob(data.data, true), metadata);\r\n };\r\n /**\r\n * Deletes the object at this location.\r\n * @return A promise that resolves if the deletion succeeds.\r\n */\r\n Reference.prototype.delete = function () {\r\n validate('delete', [], arguments);\r\n this.throwIfRoot_('delete');\r\n var self = this;\r\n return this.authWrapper.getAuthToken().then(function (authToken) {\r\n var requestInfo = deleteObject(self.authWrapper, self.location);\r\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\r\n });\r\n };\r\n /**\r\n * A promise that resolves with the metadata for this object. If this\r\n * object doesn't exist or metadata cannot be retreived, the promise is\r\n * rejected.\r\n */\r\n Reference.prototype.getMetadata = function () {\r\n validate('getMetadata', [], arguments);\r\n this.throwIfRoot_('getMetadata');\r\n var self = this;\r\n return this.authWrapper.getAuthToken().then(function (authToken) {\r\n var requestInfo = getMetadata(self.authWrapper, self.location, self.mappings());\r\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\r\n });\r\n };\r\n /**\r\n * Updates the metadata for this object.\r\n * @param metadata The new metadata for the object.\r\n * Only values that have been explicitly set will be changed. Explicitly\r\n * setting a value to null will remove the metadata.\r\n * @return A promise that resolves\r\n * with the new metadata for this object.\r\n * @see firebaseStorage.Reference.prototype.getMetadata\r\n */\r\n Reference.prototype.updateMetadata = function (metadata) {\r\n validate('updateMetadata', [metadataSpec()], arguments);\r\n this.throwIfRoot_('updateMetadata');\r\n var self = this;\r\n return this.authWrapper.getAuthToken().then(function (authToken) {\r\n var requestInfo = updateMetadata(self.authWrapper, self.location, metadata, self.mappings());\r\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\r\n });\r\n };\r\n /**\r\n * @return A promise that resolves with the download\r\n * URL for this object.\r\n */\r\n Reference.prototype.getDownloadURL = function () {\r\n validate('getDownloadURL', [], arguments);\r\n this.throwIfRoot_('getDownloadURL');\r\n var self = this;\r\n return this.authWrapper.getAuthToken().then(function (authToken) {\r\n var requestInfo = getDownloadUrl(self.authWrapper, self.location, self.mappings());\r\n return self.authWrapper\r\n .makeRequest(requestInfo, authToken)\r\n .getPromise()\r\n .then(function (url) {\r\n if (url === null) {\r\n throw noDownloadURL();\r\n }\r\n return url;\r\n });\r\n });\r\n };\r\n Reference.prototype.throwIfRoot_ = function (name) {\r\n if (this.location.path === '') {\r\n throw invalidRootOperation(name);\r\n }\r\n };\r\n return Reference;\r\n}());\n\n/**\r\n * A request whose promise always fails.\r\n * @struct\r\n * @template T\r\n */\r\nvar FailRequest = /** @class */ (function () {\r\n function FailRequest(error) {\r\n this.promise_ = reject(error);\r\n }\r\n /** @inheritDoc */\r\n FailRequest.prototype.getPromise = function () {\r\n return this.promise_;\r\n };\r\n /** @inheritDoc */\r\n FailRequest.prototype.cancel = function (appDelete) {\r\n if (appDelete === void 0) { appDelete = false; }\r\n };\r\n return FailRequest;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @struct\r\n */\r\nvar RequestMap = /** @class */ (function () {\r\n function RequestMap() {\r\n this.map_ = {};\r\n this.id_ = MIN_SAFE_INTEGER;\r\n }\r\n /**\r\n * Registers the given request with this map.\r\n * The request is unregistered when it completes.\r\n * @param r The request to register.\r\n */\r\n RequestMap.prototype.addRequest = function (r) {\r\n var id = this.id_;\r\n this.id_++;\r\n this.map_[id] = r;\r\n var self = this;\r\n function unmap() {\r\n delete self.map_[id];\r\n }\r\n r.getPromise().then(unmap, unmap);\r\n };\r\n /**\r\n * Cancels all registered requests.\r\n */\r\n RequestMap.prototype.clear = function () {\r\n forEach(this.map_, function (key, val) {\r\n if (val) {\r\n val.cancel(true);\r\n }\r\n });\r\n this.map_ = {};\r\n };\r\n return RequestMap;\r\n}());\n\n/**\r\n * @param app If null, getAuthToken always resolves with null.\r\n * @param service The storage service associated with this auth wrapper.\r\n * Untyped to avoid circular type dependencies.\r\n * @struct\r\n */\r\nvar AuthWrapper = /** @class */ (function () {\r\n function AuthWrapper(app, maker, requestMaker, service, pool) {\r\n this.bucket_ = null;\r\n this.deleted_ = false;\r\n this.app_ = app;\r\n if (this.app_ !== null) {\r\n var options = this.app_.options;\r\n if (isDef(options)) {\r\n this.bucket_ = AuthWrapper.extractBucket_(options);\r\n }\r\n }\r\n this.storageRefMaker_ = maker;\r\n this.requestMaker_ = requestMaker;\r\n this.pool_ = pool;\r\n this.service_ = service;\r\n this.maxOperationRetryTime_ = DEFAULT_MAX_OPERATION_RETRY_TIME;\r\n this.maxUploadRetryTime_ = DEFAULT_MAX_UPLOAD_RETRY_TIME;\r\n this.requestMap_ = new RequestMap();\r\n }\r\n AuthWrapper.extractBucket_ = function (config) {\r\n var bucketString = config[CONFIG_STORAGE_BUCKET_KEY] || null;\r\n if (bucketString == null) {\r\n return null;\r\n }\r\n var loc = Location.makeFromBucketSpec(bucketString);\r\n return loc.bucket;\r\n };\r\n AuthWrapper.prototype.getAuthToken = function () {\r\n // TODO(andysoto): remove ifDef checks after firebase-app implements stubs\r\n // (b/28673818).\r\n if (this.app_ !== null &&\r\n isDef(this.app_.INTERNAL) &&\r\n isDef(this.app_.INTERNAL.getToken)) {\r\n return this.app_.INTERNAL.getToken().then(function (response) {\r\n if (response !== null) {\r\n return response.accessToken;\r\n }\r\n else {\r\n return null;\r\n }\r\n }, function (_error) {\r\n return null;\r\n });\r\n }\r\n else {\r\n return resolve(null);\r\n }\r\n };\r\n AuthWrapper.prototype.bucket = function () {\r\n if (this.deleted_) {\r\n throw appDeleted();\r\n }\r\n else {\r\n return this.bucket_;\r\n }\r\n };\r\n /**\r\n * The service associated with this auth wrapper. Untyped to avoid circular\r\n * type dependencies.\r\n */\r\n AuthWrapper.prototype.service = function () {\r\n return this.service_;\r\n };\r\n /**\r\n * Returns a new firebaseStorage.Reference object referencing this AuthWrapper\r\n * at the given Location.\r\n * @param loc The Location.\r\n * @return Actually a firebaseStorage.Reference, typing not allowed\r\n * because of circular dependency problems.\r\n */\r\n AuthWrapper.prototype.makeStorageReference = function (loc) {\r\n return this.storageRefMaker_(this, loc);\r\n };\r\n AuthWrapper.prototype.makeRequest = function (requestInfo, authToken) {\r\n if (!this.deleted_) {\r\n var request = this.requestMaker_(requestInfo, authToken, this.pool_);\r\n this.requestMap_.addRequest(request);\r\n return request;\r\n }\r\n else {\r\n return new FailRequest(appDeleted());\r\n }\r\n };\r\n /**\r\n * Stop running requests and prevent more from being created.\r\n */\r\n AuthWrapper.prototype.deleteApp = function () {\r\n this.deleted_ = true;\r\n this.app_ = null;\r\n this.requestMap_.clear();\r\n };\r\n AuthWrapper.prototype.maxUploadRetryTime = function () {\r\n return this.maxUploadRetryTime_;\r\n };\r\n AuthWrapper.prototype.setMaxUploadRetryTime = function (time) {\r\n this.maxUploadRetryTime_ = time;\r\n };\r\n AuthWrapper.prototype.maxOperationRetryTime = function () {\r\n return this.maxOperationRetryTime_;\r\n };\r\n AuthWrapper.prototype.setMaxOperationRetryTime = function (time) {\r\n this.maxOperationRetryTime_ = time;\r\n };\r\n return AuthWrapper;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @param f May be invoked\r\n * before the function returns.\r\n * @param callback Get all the arguments passed to the function\r\n * passed to f, including the initial boolean.\r\n */\r\nfunction start(f, callback, timeout) {\r\n // TODO(andysoto): make this code cleaner (probably refactor into an actual\r\n // type instead of a bunch of functions with state shared in the closure)\r\n var waitSeconds = 1;\r\n // Would type this as \"number\" but that doesn't work for Node so ¯\\_(ツ)_/¯\r\n var timeoutId = null;\r\n var hitTimeout = false;\r\n var cancelState = 0;\r\n function canceled() {\r\n return cancelState === 2;\r\n }\r\n var triggeredCallback = false;\r\n function triggerCallback() {\r\n if (!triggeredCallback) {\r\n triggeredCallback = true;\r\n callback.apply(null, arguments);\r\n }\r\n }\r\n function callWithDelay(millis) {\r\n timeoutId = setTimeout(function () {\r\n timeoutId = null;\r\n f(handler, canceled());\r\n }, millis);\r\n }\r\n function handler(success) {\r\n var var_args = [];\r\n for (var _i = 1; _i < arguments.length; _i++) {\r\n var_args[_i - 1] = arguments[_i];\r\n }\r\n if (triggeredCallback) {\r\n return;\r\n }\r\n if (success) {\r\n triggerCallback.apply(null, arguments);\r\n return;\r\n }\r\n var mustStop = canceled() || hitTimeout;\r\n if (mustStop) {\r\n triggerCallback.apply(null, arguments);\r\n return;\r\n }\r\n if (waitSeconds < 64) {\r\n /* TODO(andysoto): don't back off so quickly if we know we're offline. */\r\n waitSeconds *= 2;\r\n }\r\n var waitMillis;\r\n if (cancelState === 1) {\r\n cancelState = 2;\r\n waitMillis = 0;\r\n }\r\n else {\r\n waitMillis = (waitSeconds + Math.random()) * 1000;\r\n }\r\n callWithDelay(waitMillis);\r\n }\r\n var stopped = false;\r\n function stop(wasTimeout) {\r\n if (stopped) {\r\n return;\r\n }\r\n stopped = true;\r\n if (triggeredCallback) {\r\n return;\r\n }\r\n if (timeoutId !== null) {\r\n if (!wasTimeout) {\r\n cancelState = 2;\r\n }\r\n clearTimeout(timeoutId);\r\n callWithDelay(0);\r\n }\r\n else {\r\n if (!wasTimeout) {\r\n cancelState = 1;\r\n }\r\n }\r\n }\r\n callWithDelay(0);\r\n setTimeout(function () {\r\n hitTimeout = true;\r\n stop(true);\r\n }, timeout);\r\n return stop;\r\n}\r\n/**\r\n * Stops the retry loop from repeating.\r\n * If the function is currently \"in between\" retries, it is invoked immediately\r\n * with the second parameter as \"true\". Otherwise, it will be invoked once more\r\n * after the current invocation finishes iff the current invocation would have\r\n * triggered another retry.\r\n */\r\nfunction stop(id) {\r\n id(false);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @struct\r\n * @template T\r\n */\r\nvar NetworkRequest = /** @class */ (function () {\r\n function NetworkRequest(url, method, headers, body, successCodes, additionalRetryCodes, callback, errorCallback, timeout, progressCallback, pool) {\r\n this.pendingXhr_ = null;\r\n this.backoffId_ = null;\r\n this.resolve_ = null;\r\n this.reject_ = null;\r\n this.canceled_ = false;\r\n this.appDelete_ = false;\r\n this.url_ = url;\r\n this.method_ = method;\r\n this.headers_ = headers;\r\n this.body_ = body;\r\n this.successCodes_ = successCodes.slice();\r\n this.additionalRetryCodes_ = additionalRetryCodes.slice();\r\n this.callback_ = callback;\r\n this.errorCallback_ = errorCallback;\r\n this.progressCallback_ = progressCallback;\r\n this.timeout_ = timeout;\r\n this.pool_ = pool;\r\n var self = this;\r\n this.promise_ = make(function (resolve, reject) {\r\n self.resolve_ = resolve;\r\n self.reject_ = reject;\r\n self.start_();\r\n });\r\n }\r\n /**\r\n * Actually starts the retry loop.\r\n */\r\n NetworkRequest.prototype.start_ = function () {\r\n var self = this;\r\n function doTheRequest(backoffCallback, canceled) {\r\n if (canceled) {\r\n backoffCallback(false, new RequestEndStatus(false, null, true));\r\n return;\r\n }\r\n var xhr = self.pool_.createXhrIo();\r\n self.pendingXhr_ = xhr;\r\n function progressListener(progressEvent) {\r\n var loaded = progressEvent.loaded;\r\n var total = progressEvent.lengthComputable ? progressEvent.total : -1;\r\n if (self.progressCallback_ !== null) {\r\n self.progressCallback_(loaded, total);\r\n }\r\n }\r\n if (self.progressCallback_ !== null) {\r\n xhr.addUploadProgressListener(progressListener);\r\n }\r\n xhr\r\n .send(self.url_, self.method_, self.body_, self.headers_)\r\n .then(function (xhr) {\r\n if (self.progressCallback_ !== null) {\r\n xhr.removeUploadProgressListener(progressListener);\r\n }\r\n self.pendingXhr_ = null;\r\n xhr = xhr;\r\n var hitServer = xhr.getErrorCode() === ErrorCode.NO_ERROR;\r\n var status = xhr.getStatus();\r\n if (!hitServer || self.isRetryStatusCode_(status)) {\r\n var wasCanceled = xhr.getErrorCode() === ErrorCode.ABORT;\r\n backoffCallback(false, new RequestEndStatus(false, null, wasCanceled));\r\n return;\r\n }\r\n var successCode = contains$1(self.successCodes_, status);\r\n backoffCallback(true, new RequestEndStatus(successCode, xhr));\r\n });\r\n }\r\n /**\r\n * @param requestWentThrough True if the request eventually went\r\n * through, false if it hit the retry limit or was canceled.\r\n */\r\n function backoffDone(requestWentThrough, status) {\r\n var resolve = self.resolve_;\r\n var reject = self.reject_;\r\n var xhr = status.xhr;\r\n if (status.wasSuccessCode) {\r\n try {\r\n var result = self.callback_(xhr, xhr.getResponseText());\r\n if (isJustDef(result)) {\r\n resolve(result);\r\n }\r\n else {\r\n resolve();\r\n }\r\n }\r\n catch (e) {\r\n reject(e);\r\n }\r\n }\r\n else {\r\n if (xhr !== null) {\r\n var err = unknown();\r\n err.setServerResponseProp(xhr.getResponseText());\r\n if (self.errorCallback_) {\r\n reject(self.errorCallback_(xhr, err));\r\n }\r\n else {\r\n reject(err);\r\n }\r\n }\r\n else {\r\n if (status.canceled) {\r\n var err = self.appDelete_\r\n ? appDeleted()\r\n : canceled();\r\n reject(err);\r\n }\r\n else {\r\n var err = retryLimitExceeded();\r\n reject(err);\r\n }\r\n }\r\n }\r\n }\r\n if (this.canceled_) {\r\n backoffDone(false, new RequestEndStatus(false, null, true));\r\n }\r\n else {\r\n this.backoffId_ = start(doTheRequest, backoffDone, this.timeout_);\r\n }\r\n };\r\n /** @inheritDoc */\r\n NetworkRequest.prototype.getPromise = function () {\r\n return this.promise_;\r\n };\r\n /** @inheritDoc */\r\n NetworkRequest.prototype.cancel = function (appDelete) {\r\n this.canceled_ = true;\r\n this.appDelete_ = appDelete || false;\r\n if (this.backoffId_ !== null) {\r\n stop(this.backoffId_);\r\n }\r\n if (this.pendingXhr_ !== null) {\r\n this.pendingXhr_.abort();\r\n }\r\n };\r\n NetworkRequest.prototype.isRetryStatusCode_ = function (status) {\r\n // The codes for which to retry came from this page:\r\n // https://cloud.google.com/storage/docs/exponential-backoff\r\n var isFiveHundredCode = status >= 500 && status < 600;\r\n var extraRetryCodes = [\r\n // Request Timeout: web server didn't receive full request in time.\r\n 408,\r\n // Too Many Requests: you're getting rate-limited, basically.\r\n 429\r\n ];\r\n var isExtraRetryCode = contains$1(extraRetryCodes, status);\r\n var isRequestSpecificRetryCode = contains$1(this.additionalRetryCodes_, status);\r\n return isFiveHundredCode || isExtraRetryCode || isRequestSpecificRetryCode;\r\n };\r\n return NetworkRequest;\r\n}());\r\n/**\r\n * A collection of information about the result of a network request.\r\n * @param opt_canceled Defaults to false.\r\n * @struct\r\n */\r\nvar RequestEndStatus = /** @class */ (function () {\r\n function RequestEndStatus(wasSuccessCode, xhr, opt_canceled) {\r\n this.wasSuccessCode = wasSuccessCode;\r\n this.xhr = xhr;\r\n this.canceled = !!opt_canceled;\r\n }\r\n return RequestEndStatus;\r\n}());\r\nfunction addAuthHeader_(headers, authToken) {\r\n if (authToken !== null && authToken.length > 0) {\r\n headers['Authorization'] = 'Firebase ' + authToken;\r\n }\r\n}\r\nfunction addVersionHeader_(headers) {\r\n var number = typeof firebase !== 'undefined' ? firebase.SDK_VERSION : 'AppManager';\r\n headers['X-Firebase-Storage-Version'] = 'webjs/' + number;\r\n}\r\n/**\r\n * @template T\r\n */\r\nfunction makeRequest(requestInfo, authToken, pool) {\r\n var queryPart = makeQueryString(requestInfo.urlParams);\r\n var url = requestInfo.url + queryPart;\r\n var headers = clone(requestInfo.headers);\r\n addAuthHeader_(headers, authToken);\r\n addVersionHeader_(headers);\r\n return new NetworkRequest(url, requestInfo.method, headers, requestInfo.body, requestInfo.successCodes, requestInfo.additionalRetryCodes, requestInfo.handler, requestInfo.errorHandler, requestInfo.timeout, requestInfo.progressCallback, pool);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A service that provides firebaseStorage.Reference instances.\r\n * @param opt_url gs:// url to a custom Storage Bucket\r\n *\r\n * @struct\r\n */\r\nvar Service = /** @class */ (function () {\r\n function Service(app, pool, url) {\r\n this.bucket_ = null;\r\n function maker(authWrapper, loc) {\r\n return new Reference(authWrapper, loc);\r\n }\r\n this.authWrapper_ = new AuthWrapper(app, maker, makeRequest, this, pool);\r\n this.app_ = app;\r\n if (url != null) {\r\n this.bucket_ = Location.makeFromBucketSpec(url);\r\n }\r\n else {\r\n var authWrapperBucket = this.authWrapper_.bucket();\r\n if (authWrapperBucket != null) {\r\n this.bucket_ = new Location(authWrapperBucket, '');\r\n }\r\n }\r\n this.internals_ = new ServiceInternals(this);\r\n }\r\n /**\r\n * Returns a firebaseStorage.Reference for the given path in the default\r\n * bucket.\r\n */\r\n Service.prototype.ref = function (path) {\r\n function validator(path) {\r\n if (/^[A-Za-z]+:\\/\\//.test(path)) {\r\n throw 'Expected child path but got a URL, use refFromURL instead.';\r\n }\r\n }\r\n validate('ref', [stringSpec(validator, true)], arguments);\r\n if (this.bucket_ == null) {\r\n throw new Error('No Storage Bucket defined in Firebase Options.');\r\n }\r\n var ref = new Reference(this.authWrapper_, this.bucket_);\r\n if (path != null) {\r\n return ref.child(path);\r\n }\r\n else {\r\n return ref;\r\n }\r\n };\r\n /**\r\n * Returns a firebaseStorage.Reference object for the given absolute URL,\r\n * which must be a gs:// or http[s]:// URL.\r\n */\r\n Service.prototype.refFromURL = function (url) {\r\n function validator(p) {\r\n if (!/^[A-Za-z]+:\\/\\//.test(p)) {\r\n throw 'Expected full URL but got a child path, use ref instead.';\r\n }\r\n try {\r\n Location.makeFromUrl(p);\r\n }\r\n catch (e) {\r\n throw 'Expected valid full URL but got an invalid one.';\r\n }\r\n }\r\n validate('refFromURL', [stringSpec(validator, false)], arguments);\r\n return new Reference(this.authWrapper_, url);\r\n };\r\n Object.defineProperty(Service.prototype, \"maxUploadRetryTime\", {\r\n get: function () {\r\n return this.authWrapper_.maxUploadRetryTime();\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Service.prototype.setMaxUploadRetryTime = function (time) {\r\n validate('setMaxUploadRetryTime', [nonNegativeNumberSpec()], arguments);\r\n this.authWrapper_.setMaxUploadRetryTime(time);\r\n };\r\n Service.prototype.setMaxOperationRetryTime = function (time) {\r\n validate('setMaxOperationRetryTime', [nonNegativeNumberSpec()], arguments);\r\n this.authWrapper_.setMaxOperationRetryTime(time);\r\n };\r\n Object.defineProperty(Service.prototype, \"app\", {\r\n get: function () {\r\n return this.app_;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(Service.prototype, \"INTERNAL\", {\r\n get: function () {\r\n return this.internals_;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n return Service;\r\n}());\r\n/**\r\n * @struct\r\n */\r\nvar ServiceInternals = /** @class */ (function () {\r\n function ServiceInternals(service) {\r\n this.service_ = service;\r\n }\r\n /**\r\n * Called when the associated app is deleted.\r\n * @see {!fbs.AuthWrapper.prototype.deleteApp}\r\n */\r\n ServiceInternals.prototype.delete = function () {\r\n this.service_.authWrapper_.deleteApp();\r\n return resolve(undefined);\r\n };\r\n return ServiceInternals;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Type constant for Firebase Storage.\r\n */\r\nvar STORAGE_TYPE = 'storage';\r\nfunction factory(app, unused, opt_url) {\r\n return new Service(app, new XhrIoPool(), opt_url);\r\n}\r\nfunction registerStorage(instance) {\r\n var namespaceExports = {\r\n // no-inline\r\n TaskState: TaskState,\r\n TaskEvent: TaskEvent,\r\n StringFormat: StringFormat,\r\n Storage: Service,\r\n Reference: Reference\r\n };\r\n instance.INTERNAL.registerService(STORAGE_TYPE, factory, namespaceExports, undefined, \r\n // Allow multiple storage instances per app.\r\n true);\r\n}\r\nregisterStorage(firebase);\n\nexport { registerStorage };\n//# sourceMappingURL=index.esm.js.map\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nfunction _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }\n\nvar firebase = _interopDefault(require('@firebase/app'));\nvar tslib_1 = require('tslib');\nvar util = require('@firebase/util');\nvar logger$1 = require('@firebase/logger');\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Wraps a DOM Storage object and:\r\n * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.\r\n * - prefixes names with \"firebase:\" to avoid collisions with app data.\r\n *\r\n * We automatically (see storage.js) create two such wrappers, one for sessionStorage,\r\n * and one for localStorage.\r\n *\r\n * @constructor\r\n */\r\nvar DOMStorageWrapper = /** @class */ (function () {\r\n /**\r\n * @param {Storage} domStorage_ The underlying storage object (e.g. localStorage or sessionStorage)\r\n */\r\n function DOMStorageWrapper(domStorage_) {\r\n this.domStorage_ = domStorage_;\r\n // Use a prefix to avoid collisions with other stuff saved by the app.\r\n this.prefix_ = 'firebase:';\r\n }\r\n /**\r\n * @param {string} key The key to save the value under\r\n * @param {?Object} value The value being stored, or null to remove the key.\r\n */\r\n DOMStorageWrapper.prototype.set = function (key, value) {\r\n if (value == null) {\r\n this.domStorage_.removeItem(this.prefixedName_(key));\r\n }\r\n else {\r\n this.domStorage_.setItem(this.prefixedName_(key), util.stringify(value));\r\n }\r\n };\r\n /**\r\n * @param {string} key\r\n * @return {*} The value that was stored under this key, or null\r\n */\r\n DOMStorageWrapper.prototype.get = function (key) {\r\n var storedVal = this.domStorage_.getItem(this.prefixedName_(key));\r\n if (storedVal == null) {\r\n return null;\r\n }\r\n else {\r\n return util.jsonEval(storedVal);\r\n }\r\n };\r\n /**\r\n * @param {string} key\r\n */\r\n DOMStorageWrapper.prototype.remove = function (key) {\r\n this.domStorage_.removeItem(this.prefixedName_(key));\r\n };\r\n /**\r\n * @param {string} name\r\n * @return {string}\r\n */\r\n DOMStorageWrapper.prototype.prefixedName_ = function (name) {\r\n return this.prefix_ + name;\r\n };\r\n DOMStorageWrapper.prototype.toString = function () {\r\n return this.domStorage_.toString();\r\n };\r\n return DOMStorageWrapper;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An in-memory storage implementation that matches the API of DOMStorageWrapper\r\n * (TODO: create interface for both to implement).\r\n *\r\n * @constructor\r\n */\r\nvar MemoryStorage = /** @class */ (function () {\r\n function MemoryStorage() {\r\n this.cache_ = {};\r\n this.isInMemoryStorage = true;\r\n }\r\n MemoryStorage.prototype.set = function (key, value) {\r\n if (value == null) {\r\n delete this.cache_[key];\r\n }\r\n else {\r\n this.cache_[key] = value;\r\n }\r\n };\r\n MemoryStorage.prototype.get = function (key) {\r\n if (util.contains(this.cache_, key)) {\r\n return this.cache_[key];\r\n }\r\n return null;\r\n };\r\n MemoryStorage.prototype.remove = function (key) {\r\n delete this.cache_[key];\r\n };\r\n return MemoryStorage;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.\r\n * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change\r\n * to reflect this type\r\n *\r\n * @param {string} domStorageName Name of the underlying storage object\r\n * (e.g. 'localStorage' or 'sessionStorage').\r\n * @return {?} Turning off type information until a common interface is defined.\r\n */\r\nvar createStoragefor = function (domStorageName) {\r\n try {\r\n // NOTE: just accessing \"localStorage\" or \"window['localStorage']\" may throw a security exception,\r\n // so it must be inside the try/catch.\r\n if (typeof window !== 'undefined' &&\r\n typeof window[domStorageName] !== 'undefined') {\r\n // Need to test cache. Just because it's here doesn't mean it works\r\n var domStorage = window[domStorageName];\r\n domStorage.setItem('firebase:sentinel', 'cache');\r\n domStorage.removeItem('firebase:sentinel');\r\n return new DOMStorageWrapper(domStorage);\r\n }\r\n }\r\n catch (e) { }\r\n // Failed to create wrapper. Just return in-memory storage.\r\n // TODO: log?\r\n return new MemoryStorage();\r\n};\r\n/** A storage object that lasts across sessions */\r\nvar PersistentStorage = createStoragefor('localStorage');\r\n/** A storage object that only lasts one session */\r\nvar SessionStorage = createStoragefor('sessionStorage');\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar logClient = new logger$1.Logger('@firebase/database');\r\n/**\r\n * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).\r\n * @type {function(): number} Generated ID.\r\n */\r\nvar LUIDGenerator = (function () {\r\n var id = 1;\r\n return function () {\r\n return id++;\r\n };\r\n})();\r\n/**\r\n * Sha1 hash of the input string\r\n * @param {!string} str The string to hash\r\n * @return {!string} The resulting hash\r\n */\r\nvar sha1 = function (str) {\r\n var utf8Bytes = util.stringToByteArray(str);\r\n var sha1 = new util.Sha1();\r\n sha1.update(utf8Bytes);\r\n var sha1Bytes = sha1.digest();\r\n return util.base64.encodeByteArray(sha1Bytes);\r\n};\r\n/**\r\n * @param {...*} var_args\r\n * @return {string}\r\n * @private\r\n */\r\nvar buildLogMessage_ = function () {\r\n var var_args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n var_args[_i] = arguments[_i];\r\n }\r\n var message = '';\r\n for (var i = 0; i < var_args.length; i++) {\r\n if (Array.isArray(var_args[i]) ||\r\n (var_args[i] &&\r\n typeof var_args[i] === 'object' &&\r\n typeof var_args[i].length === 'number')) {\r\n message += buildLogMessage_.apply(null, var_args[i]);\r\n }\r\n else if (typeof var_args[i] === 'object') {\r\n message += util.stringify(var_args[i]);\r\n }\r\n else {\r\n message += var_args[i];\r\n }\r\n message += ' ';\r\n }\r\n return message;\r\n};\r\n/**\r\n * Use this for all debug messages in Firebase.\r\n * @type {?function(string)}\r\n */\r\nvar logger = null;\r\n/**\r\n * Flag to check for log availability on first log message\r\n * @type {boolean}\r\n * @private\r\n */\r\nvar firstLog_ = true;\r\n/**\r\n * The implementation of Firebase.enableLogging (defined here to break dependencies)\r\n * @param {boolean|?function(string)} logger_ A flag to turn on logging, or a custom logger\r\n * @param {boolean=} persistent Whether or not to persist logging settings across refreshes\r\n */\r\nvar enableLogging = function (logger_, persistent) {\r\n util.assert(!persistent || (logger_ === true || logger_ === false), \"Can't turn on custom loggers persistently.\");\r\n if (logger_ === true) {\r\n logClient.logLevel = logger$1.LogLevel.VERBOSE;\r\n logger = logClient.log.bind(logClient);\r\n if (persistent)\r\n SessionStorage.set('logging_enabled', true);\r\n }\r\n else if (typeof logger_ === 'function') {\r\n logger = logger_;\r\n }\r\n else {\r\n logger = null;\r\n SessionStorage.remove('logging_enabled');\r\n }\r\n};\r\n/**\r\n *\r\n * @param {...(string|Arguments)} var_args\r\n */\r\nvar log = function () {\r\n var var_args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n var_args[_i] = arguments[_i];\r\n }\r\n if (firstLog_ === true) {\r\n firstLog_ = false;\r\n if (logger === null && SessionStorage.get('logging_enabled') === true)\r\n enableLogging(true);\r\n }\r\n if (logger) {\r\n var message = buildLogMessage_.apply(null, var_args);\r\n logger(message);\r\n }\r\n};\r\n/**\r\n * @param {!string} prefix\r\n * @return {function(...[*])}\r\n */\r\nvar logWrapper = function (prefix) {\r\n return function () {\r\n var var_args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n var_args[_i] = arguments[_i];\r\n }\r\n log.apply(void 0, [prefix].concat(var_args));\r\n };\r\n};\r\n/**\r\n * @param {...string} var_args\r\n */\r\nvar error = function () {\r\n var var_args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n var_args[_i] = arguments[_i];\r\n }\r\n var message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_.apply(void 0, var_args);\r\n logClient.error(message);\r\n};\r\n/**\r\n * @param {...string} var_args\r\n */\r\nvar fatal = function () {\r\n var var_args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n var_args[_i] = arguments[_i];\r\n }\r\n var message = \"FIREBASE FATAL ERROR: \" + buildLogMessage_.apply(void 0, var_args);\r\n logClient.error(message);\r\n throw new Error(message);\r\n};\r\n/**\r\n * @param {...*} var_args\r\n */\r\nvar warn = function () {\r\n var var_args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n var_args[_i] = arguments[_i];\r\n }\r\n var message = 'FIREBASE WARNING: ' + buildLogMessage_.apply(void 0, var_args);\r\n logClient.warn(message);\r\n};\r\n/**\r\n * Logs a warning if the containing page uses https. Called when a call to new Firebase\r\n * does not use https.\r\n */\r\nvar warnIfPageIsSecure = function () {\r\n // Be very careful accessing browser globals. Who knows what may or may not exist.\r\n if (typeof window !== 'undefined' &&\r\n window.location &&\r\n window.location.protocol &&\r\n window.location.protocol.indexOf('https:') !== -1) {\r\n warn('Insecure Firebase access from a secure page. ' +\r\n 'Please use https in calls to new Firebase().');\r\n }\r\n};\r\n/**\r\n * Returns true if data is NaN, or +/- Infinity.\r\n * @param {*} data\r\n * @return {boolean}\r\n */\r\nvar isInvalidJSONNumber = function (data) {\r\n return (typeof data === 'number' &&\r\n (data != data || // NaN\r\n data == Number.POSITIVE_INFINITY ||\r\n data == Number.NEGATIVE_INFINITY));\r\n};\r\n/**\r\n * @param {function()} fn\r\n */\r\nvar executeWhenDOMReady = function (fn) {\r\n if (util.isNodeSdk() || document.readyState === 'complete') {\r\n fn();\r\n }\r\n else {\r\n // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which\r\n // fire before onload), but fall back to onload.\r\n var called_1 = false;\r\n var wrappedFn_1 = function () {\r\n if (!document.body) {\r\n setTimeout(wrappedFn_1, Math.floor(10));\r\n return;\r\n }\r\n if (!called_1) {\r\n called_1 = true;\r\n fn();\r\n }\r\n };\r\n if (document.addEventListener) {\r\n document.addEventListener('DOMContentLoaded', wrappedFn_1, false);\r\n // fallback to onload.\r\n window.addEventListener('load', wrappedFn_1, false);\r\n }\r\n else if (document.attachEvent) {\r\n // IE.\r\n document.attachEvent('onreadystatechange', function () {\r\n if (document.readyState === 'complete')\r\n wrappedFn_1();\r\n });\r\n // fallback to onload.\r\n window.attachEvent('onload', wrappedFn_1);\r\n // jQuery has an extra hack for IE that we could employ (based on\r\n // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.\r\n // I'm hoping we don't need it.\r\n }\r\n }\r\n};\r\n/**\r\n * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names\r\n * @type {!string}\r\n */\r\nvar MIN_NAME = '[MIN_NAME]';\r\n/**\r\n * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names\r\n * @type {!string}\r\n */\r\nvar MAX_NAME = '[MAX_NAME]';\r\n/**\r\n * Compares valid Firebase key names, plus min and max name\r\n * @param {!string} a\r\n * @param {!string} b\r\n * @return {!number}\r\n */\r\nvar nameCompare = function (a, b) {\r\n if (a === b) {\r\n return 0;\r\n }\r\n else if (a === MIN_NAME || b === MAX_NAME) {\r\n return -1;\r\n }\r\n else if (b === MIN_NAME || a === MAX_NAME) {\r\n return 1;\r\n }\r\n else {\r\n var aAsInt = tryParseInt(a), bAsInt = tryParseInt(b);\r\n if (aAsInt !== null) {\r\n if (bAsInt !== null) {\r\n return aAsInt - bAsInt == 0 ? a.length - b.length : aAsInt - bAsInt;\r\n }\r\n else {\r\n return -1;\r\n }\r\n }\r\n else if (bAsInt !== null) {\r\n return 1;\r\n }\r\n else {\r\n return a < b ? -1 : 1;\r\n }\r\n }\r\n};\r\n/**\r\n * @param {!string} a\r\n * @param {!string} b\r\n * @return {!number} comparison result.\r\n */\r\nvar stringCompare = function (a, b) {\r\n if (a === b) {\r\n return 0;\r\n }\r\n else if (a < b) {\r\n return -1;\r\n }\r\n else {\r\n return 1;\r\n }\r\n};\r\n/**\r\n * @param {string} key\r\n * @param {Object} obj\r\n * @return {*}\r\n */\r\nvar requireKey = function (key, obj) {\r\n if (obj && key in obj) {\r\n return obj[key];\r\n }\r\n else {\r\n throw new Error('Missing required key (' + key + ') in object: ' + util.stringify(obj));\r\n }\r\n};\r\n/**\r\n * @param {*} obj\r\n * @return {string}\r\n */\r\nvar ObjectToUniqueKey = function (obj) {\r\n if (typeof obj !== 'object' || obj === null)\r\n return util.stringify(obj);\r\n var keys = [];\r\n for (var k in obj) {\r\n keys.push(k);\r\n }\r\n // Export as json, but with the keys sorted.\r\n keys.sort();\r\n var key = '{';\r\n for (var i = 0; i < keys.length; i++) {\r\n if (i !== 0)\r\n key += ',';\r\n key += util.stringify(keys[i]);\r\n key += ':';\r\n key += ObjectToUniqueKey(obj[keys[i]]);\r\n }\r\n key += '}';\r\n return key;\r\n};\r\n/**\r\n * Splits a string into a number of smaller segments of maximum size\r\n * @param {!string} str The string\r\n * @param {!number} segsize The maximum number of chars in the string.\r\n * @return {Array.} The string, split into appropriately-sized chunks\r\n */\r\nvar splitStringBySize = function (str, segsize) {\r\n var len = str.length;\r\n if (len <= segsize) {\r\n return [str];\r\n }\r\n var dataSegs = [];\r\n for (var c = 0; c < len; c += segsize) {\r\n if (c + segsize > len) {\r\n dataSegs.push(str.substring(c, len));\r\n }\r\n else {\r\n dataSegs.push(str.substring(c, c + segsize));\r\n }\r\n }\r\n return dataSegs;\r\n};\r\n/**\r\n * Apply a function to each (key, value) pair in an object or\r\n * apply a function to each (index, value) pair in an array\r\n * @param {!(Object|Array)} obj The object or array to iterate over\r\n * @param {function(?, ?)} fn The function to apply\r\n */\r\nvar each = function (obj, fn) {\r\n if (Array.isArray(obj)) {\r\n for (var i = 0; i < obj.length; ++i) {\r\n fn(i, obj[i]);\r\n }\r\n }\r\n else {\r\n /**\r\n * in the conversion of code we removed the goog.object.forEach\r\n * function which did a value,key callback. We standardized on\r\n * a single impl that does a key, value callback. So we invert\r\n * to not have to touch the `each` code points\r\n */\r\n util.forEach(obj, function (key, val) { return fn(val, key); });\r\n }\r\n};\r\n/**\r\n * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)\r\n * I made one modification at the end and removed the NaN / Infinity\r\n * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.\r\n * @param {!number} v A double\r\n * @return {string}\r\n */\r\nvar doubleToIEEE754String = function (v) {\r\n util.assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL\r\n var ebits = 11, fbits = 52;\r\n var bias = (1 << (ebits - 1)) - 1, s, e, f, ln, i, bits, str;\r\n // Compute sign, exponent, fraction\r\n // Skip NaN / Infinity handling --MJL.\r\n if (v === 0) {\r\n e = 0;\r\n f = 0;\r\n s = 1 / v === -Infinity ? 1 : 0;\r\n }\r\n else {\r\n s = v < 0;\r\n v = Math.abs(v);\r\n if (v >= Math.pow(2, 1 - bias)) {\r\n // Normalized\r\n ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);\r\n e = ln + bias;\r\n f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));\r\n }\r\n else {\r\n // Denormalized\r\n e = 0;\r\n f = Math.round(v / Math.pow(2, 1 - bias - fbits));\r\n }\r\n }\r\n // Pack sign, exponent, fraction\r\n bits = [];\r\n for (i = fbits; i; i -= 1) {\r\n bits.push(f % 2 ? 1 : 0);\r\n f = Math.floor(f / 2);\r\n }\r\n for (i = ebits; i; i -= 1) {\r\n bits.push(e % 2 ? 1 : 0);\r\n e = Math.floor(e / 2);\r\n }\r\n bits.push(s ? 1 : 0);\r\n bits.reverse();\r\n str = bits.join('');\r\n // Return the data as a hex string. --MJL\r\n var hexByteString = '';\r\n for (i = 0; i < 64; i += 8) {\r\n var hexByte = parseInt(str.substr(i, 8), 2).toString(16);\r\n if (hexByte.length === 1)\r\n hexByte = '0' + hexByte;\r\n hexByteString = hexByteString + hexByte;\r\n }\r\n return hexByteString.toLowerCase();\r\n};\r\n/**\r\n * Used to detect if we're in a Chrome content script (which executes in an\r\n * isolated environment where long-polling doesn't work).\r\n * @return {boolean}\r\n */\r\nvar isChromeExtensionContentScript = function () {\r\n return !!(typeof window === 'object' &&\r\n window['chrome'] &&\r\n window['chrome']['extension'] &&\r\n !/^chrome/.test(window.location.href));\r\n};\r\n/**\r\n * Used to detect if we're in a Windows 8 Store app.\r\n * @return {boolean}\r\n */\r\nvar isWindowsStoreApp = function () {\r\n // Check for the presence of a couple WinRT globals\r\n return typeof Windows === 'object' && typeof Windows.UI === 'object';\r\n};\r\n/**\r\n * Converts a server error code to a Javascript Error\r\n * @param {!string} code\r\n * @param {!Query} query\r\n * @return {Error}\r\n */\r\nvar errorForServerCode = function (code, query) {\r\n var reason = 'Unknown Error';\r\n if (code === 'too_big') {\r\n reason =\r\n 'The data requested exceeds the maximum size ' +\r\n 'that can be accessed with a single request.';\r\n }\r\n else if (code == 'permission_denied') {\r\n reason = \"Client doesn't have permission to access the desired data.\";\r\n }\r\n else if (code == 'unavailable') {\r\n reason = 'The service is unavailable';\r\n }\r\n var error = new Error(code + ' at ' + query.path.toString() + ': ' + reason);\r\n error.code = code.toUpperCase();\r\n return error;\r\n};\r\n/**\r\n * Used to test for integer-looking strings\r\n * @type {RegExp}\r\n * @private\r\n */\r\nvar INTEGER_REGEXP_ = new RegExp('^-?\\\\d{1,10}$');\r\n/**\r\n * If the string contains a 32-bit integer, return it. Else return null.\r\n * @param {!string} str\r\n * @return {?number}\r\n */\r\nvar tryParseInt = function (str) {\r\n if (INTEGER_REGEXP_.test(str)) {\r\n var intVal = Number(str);\r\n if (intVal >= -2147483648 && intVal <= 2147483647) {\r\n return intVal;\r\n }\r\n }\r\n return null;\r\n};\r\n/**\r\n * Helper to run some code but catch any exceptions and re-throw them later.\r\n * Useful for preventing user callbacks from breaking internal code.\r\n *\r\n * Re-throwing the exception from a setTimeout is a little evil, but it's very\r\n * convenient (we don't have to try to figure out when is a safe point to\r\n * re-throw it), and the behavior seems reasonable:\r\n *\r\n * * If you aren't pausing on exceptions, you get an error in the console with\r\n * the correct stack trace.\r\n * * If you're pausing on all exceptions, the debugger will pause on your\r\n * exception and then again when we rethrow it.\r\n * * If you're only pausing on uncaught exceptions, the debugger will only pause\r\n * on us re-throwing it.\r\n *\r\n * @param {!function()} fn The code to guard.\r\n */\r\nvar exceptionGuard = function (fn) {\r\n try {\r\n fn();\r\n }\r\n catch (e) {\r\n // Re-throw exception when it's safe.\r\n setTimeout(function () {\r\n // It used to be that \"throw e\" would result in a good console error with\r\n // relevant context, but as of Chrome 39, you just get the firebase.js\r\n // file/line number where we re-throw it, which is useless. So we log\r\n // e.stack explicitly.\r\n var stack = e.stack || '';\r\n warn('Exception was thrown by user callback.', stack);\r\n throw e;\r\n }, Math.floor(0));\r\n }\r\n};\r\n/**\r\n * @return {boolean} true if we think we're currently being crawled.\r\n */\r\nvar beingCrawled = function () {\r\n var userAgent = (typeof window === 'object' &&\r\n window['navigator'] &&\r\n window['navigator']['userAgent']) ||\r\n '';\r\n // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we\r\n // believe to support JavaScript/AJAX rendering.\r\n // NOTE: Google Webmaster Tools doesn't really belong, but their \"This is how a visitor to your website\r\n // would have seen the page\" is flaky if we don't treat it as a crawler.\r\n return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);\r\n};\r\n/**\r\n * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.\r\n *\r\n * It is removed with clearTimeout() as normal.\r\n *\r\n * @param {Function} fn Function to run.\r\n * @param {number} time Milliseconds to wait before running.\r\n * @return {number|Object} The setTimeout() return value.\r\n */\r\nvar setTimeoutNonBlocking = function (fn, time) {\r\n var timeout = setTimeout(fn, time);\r\n if (typeof timeout === 'object' && timeout['unref']) {\r\n timeout['unref']();\r\n }\r\n return timeout;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An immutable object representing a parsed path. It's immutable so that you\r\n * can pass them around to other functions without worrying about them changing\r\n * it.\r\n */\r\nvar Path = /** @class */ (function () {\r\n /**\r\n * @param {string|Array.} pathOrString Path string to parse,\r\n * or another path, or the raw tokens array\r\n * @param {number=} pieceNum\r\n */\r\n function Path(pathOrString, pieceNum) {\r\n if (pieceNum === void 0) {\r\n this.pieces_ = pathOrString.split('/');\r\n // Remove empty pieces.\r\n var copyTo = 0;\r\n for (var i = 0; i < this.pieces_.length; i++) {\r\n if (this.pieces_[i].length > 0) {\r\n this.pieces_[copyTo] = this.pieces_[i];\r\n copyTo++;\r\n }\r\n }\r\n this.pieces_.length = copyTo;\r\n this.pieceNum_ = 0;\r\n }\r\n else {\r\n this.pieces_ = pathOrString;\r\n this.pieceNum_ = pieceNum;\r\n }\r\n }\r\n Object.defineProperty(Path, \"Empty\", {\r\n /**\r\n * Singleton to represent an empty path\r\n *\r\n * @const\r\n */\r\n get: function () {\r\n return new Path('');\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Path.prototype.getFront = function () {\r\n if (this.pieceNum_ >= this.pieces_.length)\r\n return null;\r\n return this.pieces_[this.pieceNum_];\r\n };\r\n /**\r\n * @return {number} The number of segments in this path\r\n */\r\n Path.prototype.getLength = function () {\r\n return this.pieces_.length - this.pieceNum_;\r\n };\r\n /**\r\n * @return {!Path}\r\n */\r\n Path.prototype.popFront = function () {\r\n var pieceNum = this.pieceNum_;\r\n if (pieceNum < this.pieces_.length) {\r\n pieceNum++;\r\n }\r\n return new Path(this.pieces_, pieceNum);\r\n };\r\n /**\r\n * @return {?string}\r\n */\r\n Path.prototype.getBack = function () {\r\n if (this.pieceNum_ < this.pieces_.length)\r\n return this.pieces_[this.pieces_.length - 1];\r\n return null;\r\n };\r\n Path.prototype.toString = function () {\r\n var pathString = '';\r\n for (var i = this.pieceNum_; i < this.pieces_.length; i++) {\r\n if (this.pieces_[i] !== '')\r\n pathString += '/' + this.pieces_[i];\r\n }\r\n return pathString || '/';\r\n };\r\n Path.prototype.toUrlEncodedString = function () {\r\n var pathString = '';\r\n for (var i = this.pieceNum_; i < this.pieces_.length; i++) {\r\n if (this.pieces_[i] !== '')\r\n pathString += '/' + encodeURIComponent(String(this.pieces_[i]));\r\n }\r\n return pathString || '/';\r\n };\r\n /**\r\n * Shallow copy of the parts of the path.\r\n *\r\n * @param {number=} begin\r\n * @return {!Array}\r\n */\r\n Path.prototype.slice = function (begin) {\r\n if (begin === void 0) { begin = 0; }\r\n return this.pieces_.slice(this.pieceNum_ + begin);\r\n };\r\n /**\r\n * @return {?Path}\r\n */\r\n Path.prototype.parent = function () {\r\n if (this.pieceNum_ >= this.pieces_.length)\r\n return null;\r\n var pieces = [];\r\n for (var i = this.pieceNum_; i < this.pieces_.length - 1; i++)\r\n pieces.push(this.pieces_[i]);\r\n return new Path(pieces, 0);\r\n };\r\n /**\r\n * @param {string|!Path} childPathObj\r\n * @return {!Path}\r\n */\r\n Path.prototype.child = function (childPathObj) {\r\n var pieces = [];\r\n for (var i = this.pieceNum_; i < this.pieces_.length; i++)\r\n pieces.push(this.pieces_[i]);\r\n if (childPathObj instanceof Path) {\r\n for (var i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {\r\n pieces.push(childPathObj.pieces_[i]);\r\n }\r\n }\r\n else {\r\n var childPieces = childPathObj.split('/');\r\n for (var i = 0; i < childPieces.length; i++) {\r\n if (childPieces[i].length > 0)\r\n pieces.push(childPieces[i]);\r\n }\r\n }\r\n return new Path(pieces, 0);\r\n };\r\n /**\r\n * @return {boolean} True if there are no segments in this path\r\n */\r\n Path.prototype.isEmpty = function () {\r\n return this.pieceNum_ >= this.pieces_.length;\r\n };\r\n /**\r\n * @param {!Path} outerPath\r\n * @param {!Path} innerPath\r\n * @return {!Path} The path from outerPath to innerPath\r\n */\r\n Path.relativePath = function (outerPath, innerPath) {\r\n var outer = outerPath.getFront(), inner = innerPath.getFront();\r\n if (outer === null) {\r\n return innerPath;\r\n }\r\n else if (outer === inner) {\r\n return Path.relativePath(outerPath.popFront(), innerPath.popFront());\r\n }\r\n else {\r\n throw new Error('INTERNAL ERROR: innerPath (' +\r\n innerPath +\r\n ') is not within ' +\r\n 'outerPath (' +\r\n outerPath +\r\n ')');\r\n }\r\n };\r\n /**\r\n * @param {!Path} left\r\n * @param {!Path} right\r\n * @return {number} -1, 0, 1 if left is less, equal, or greater than the right.\r\n */\r\n Path.comparePaths = function (left, right) {\r\n var leftKeys = left.slice();\r\n var rightKeys = right.slice();\r\n for (var i = 0; i < leftKeys.length && i < rightKeys.length; i++) {\r\n var cmp = nameCompare(leftKeys[i], rightKeys[i]);\r\n if (cmp !== 0)\r\n return cmp;\r\n }\r\n if (leftKeys.length === rightKeys.length)\r\n return 0;\r\n return leftKeys.length < rightKeys.length ? -1 : 1;\r\n };\r\n /**\r\n *\r\n * @param {Path} other\r\n * @return {boolean} true if paths are the same.\r\n */\r\n Path.prototype.equals = function (other) {\r\n if (this.getLength() !== other.getLength()) {\r\n return false;\r\n }\r\n for (var i = this.pieceNum_, j = other.pieceNum_; i <= this.pieces_.length; i++, j++) {\r\n if (this.pieces_[i] !== other.pieces_[j]) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n };\r\n /**\r\n *\r\n * @param {!Path} other\r\n * @return {boolean} True if this path is a parent (or the same as) other\r\n */\r\n Path.prototype.contains = function (other) {\r\n var i = this.pieceNum_;\r\n var j = other.pieceNum_;\r\n if (this.getLength() > other.getLength()) {\r\n return false;\r\n }\r\n while (i < this.pieces_.length) {\r\n if (this.pieces_[i] !== other.pieces_[j]) {\r\n return false;\r\n }\r\n ++i;\r\n ++j;\r\n }\r\n return true;\r\n };\r\n return Path;\r\n}()); // end Path\r\n/**\r\n * Dynamic (mutable) path used to count path lengths.\r\n *\r\n * This class is used to efficiently check paths for valid\r\n * length (in UTF8 bytes) and depth (used in path validation).\r\n *\r\n * Throws Error exception if path is ever invalid.\r\n *\r\n * The definition of a path always begins with '/'.\r\n */\r\nvar ValidationPath = /** @class */ (function () {\r\n /**\r\n * @param {!Path} path Initial Path.\r\n * @param {string} errorPrefix_ Prefix for any error messages.\r\n */\r\n function ValidationPath(path, errorPrefix_) {\r\n this.errorPrefix_ = errorPrefix_;\r\n /** @type {!Array} */\r\n this.parts_ = path.slice();\r\n /** @type {number} Initialize to number of '/' chars needed in path. */\r\n this.byteLength_ = Math.max(1, this.parts_.length);\r\n for (var i = 0; i < this.parts_.length; i++) {\r\n this.byteLength_ += util.stringLength(this.parts_[i]);\r\n }\r\n this.checkValid_();\r\n }\r\n Object.defineProperty(ValidationPath, \"MAX_PATH_DEPTH\", {\r\n /** @const {number} Maximum key depth. */\r\n get: function () {\r\n return 32;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(ValidationPath, \"MAX_PATH_LENGTH_BYTES\", {\r\n /** @const {number} Maximum number of (UTF8) bytes in a Firebase path. */\r\n get: function () {\r\n return 768;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n /** @param {string} child */\r\n ValidationPath.prototype.push = function (child) {\r\n // Count the needed '/'\r\n if (this.parts_.length > 0) {\r\n this.byteLength_ += 1;\r\n }\r\n this.parts_.push(child);\r\n this.byteLength_ += util.stringLength(child);\r\n this.checkValid_();\r\n };\r\n ValidationPath.prototype.pop = function () {\r\n var last = this.parts_.pop();\r\n this.byteLength_ -= util.stringLength(last);\r\n // Un-count the previous '/'\r\n if (this.parts_.length > 0) {\r\n this.byteLength_ -= 1;\r\n }\r\n };\r\n ValidationPath.prototype.checkValid_ = function () {\r\n if (this.byteLength_ > ValidationPath.MAX_PATH_LENGTH_BYTES) {\r\n throw new Error(this.errorPrefix_ +\r\n 'has a key path longer than ' +\r\n ValidationPath.MAX_PATH_LENGTH_BYTES +\r\n ' bytes (' +\r\n this.byteLength_ +\r\n ').');\r\n }\r\n if (this.parts_.length > ValidationPath.MAX_PATH_DEPTH) {\r\n throw new Error(this.errorPrefix_ +\r\n 'path specified exceeds the maximum depth that can be written (' +\r\n ValidationPath.MAX_PATH_DEPTH +\r\n ') or object contains a cycle ' +\r\n this.toErrorString());\r\n }\r\n };\r\n /**\r\n * String for use in error messages - uses '.' notation for path.\r\n *\r\n * @return {string}\r\n */\r\n ValidationPath.prototype.toErrorString = function () {\r\n if (this.parts_.length == 0) {\r\n return '';\r\n }\r\n return \"in property '\" + this.parts_.join('.') + \"'\";\r\n };\r\n return ValidationPath;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar PROTOCOL_VERSION = '5';\r\nvar VERSION_PARAM = 'v';\r\nvar TRANSPORT_SESSION_PARAM = 's';\r\nvar REFERER_PARAM = 'r';\r\nvar FORGE_REF = 'f';\r\nvar FORGE_DOMAIN = 'firebaseio.com';\r\nvar LAST_SESSION_PARAM = 'ls';\r\nvar WEBSOCKET = 'websocket';\r\nvar LONG_POLLING = 'long_polling';\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A class that holds metadata about a Repo object\r\n *\r\n * @constructor\r\n */\r\nvar RepoInfo = /** @class */ (function () {\r\n /**\r\n * @param {string} host Hostname portion of the url for the repo\r\n * @param {boolean} secure Whether or not this repo is accessed over ssl\r\n * @param {string} namespace The namespace represented by the repo\r\n * @param {boolean} webSocketOnly Whether to prefer websockets over all other transports (used by Nest).\r\n * @param {string=} persistenceKey Override the default session persistence storage key\r\n */\r\n function RepoInfo(host, secure, namespace, webSocketOnly, persistenceKey) {\r\n if (persistenceKey === void 0) { persistenceKey = ''; }\r\n this.secure = secure;\r\n this.namespace = namespace;\r\n this.webSocketOnly = webSocketOnly;\r\n this.persistenceKey = persistenceKey;\r\n this.host = host.toLowerCase();\r\n this.domain = this.host.substr(this.host.indexOf('.') + 1);\r\n this.internalHost = PersistentStorage.get('host:' + host) || this.host;\r\n }\r\n RepoInfo.prototype.needsQueryParam = function () {\r\n return this.host !== this.internalHost || this.isCustomHost();\r\n };\r\n RepoInfo.prototype.isCacheableHost = function () {\r\n return this.internalHost.substr(0, 2) === 's-';\r\n };\r\n RepoInfo.prototype.isDemoHost = function () {\r\n return this.domain === 'firebaseio-demo.com';\r\n };\r\n RepoInfo.prototype.isCustomHost = function () {\r\n return (this.domain !== 'firebaseio.com' && this.domain !== 'firebaseio-demo.com');\r\n };\r\n RepoInfo.prototype.updateHost = function (newHost) {\r\n if (newHost !== this.internalHost) {\r\n this.internalHost = newHost;\r\n if (this.isCacheableHost()) {\r\n PersistentStorage.set('host:' + this.host, this.internalHost);\r\n }\r\n }\r\n };\r\n /**\r\n * Returns the websocket URL for this repo\r\n * @param {string} type of connection\r\n * @param {Object} params list\r\n * @return {string} The URL for this repo\r\n */\r\n RepoInfo.prototype.connectionURL = function (type, params) {\r\n util.assert(typeof type === 'string', 'typeof type must == string');\r\n util.assert(typeof params === 'object', 'typeof params must == object');\r\n var connURL;\r\n if (type === WEBSOCKET) {\r\n connURL =\r\n (this.secure ? 'wss://' : 'ws://') + this.internalHost + '/.ws?';\r\n }\r\n else if (type === LONG_POLLING) {\r\n connURL =\r\n (this.secure ? 'https://' : 'http://') + this.internalHost + '/.lp?';\r\n }\r\n else {\r\n throw new Error('Unknown connection type: ' + type);\r\n }\r\n if (this.needsQueryParam()) {\r\n params['ns'] = this.namespace;\r\n }\r\n var pairs = [];\r\n util.forEach(params, function (key, value) {\r\n pairs.push(key + '=' + value);\r\n });\r\n return connURL + pairs.join('&');\r\n };\r\n /** @return {string} */\r\n RepoInfo.prototype.toString = function () {\r\n var str = this.toURLString();\r\n if (this.persistenceKey) {\r\n str += '<' + this.persistenceKey + '>';\r\n }\r\n return str;\r\n };\r\n /** @return {string} */\r\n RepoInfo.prototype.toURLString = function () {\r\n return (this.secure ? 'https://' : 'http://') + this.host;\r\n };\r\n return RepoInfo;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @param {!string} pathString\r\n * @return {string}\r\n */\r\nfunction decodePath(pathString) {\r\n var pathStringDecoded = '';\r\n var pieces = pathString.split('/');\r\n for (var i = 0; i < pieces.length; i++) {\r\n if (pieces[i].length > 0) {\r\n var piece = pieces[i];\r\n try {\r\n piece = decodeURIComponent(piece.replace(/\\+/g, ' '));\r\n }\r\n catch (e) { }\r\n pathStringDecoded += '/' + piece;\r\n }\r\n }\r\n return pathStringDecoded;\r\n}\r\n/**\r\n * @param {!string} queryString\r\n * @return {!{[key:string]:string}} key value hash\r\n */\r\nfunction decodeQuery(queryString) {\r\n var results = {};\r\n if (queryString.charAt(0) === '?') {\r\n queryString = queryString.substring(1);\r\n }\r\n for (var _i = 0, _a = queryString.split('&'); _i < _a.length; _i++) {\r\n var segment = _a[_i];\r\n if (segment.length === 0) {\r\n continue;\r\n }\r\n var kv = segment.split('=');\r\n if (kv.length === 2) {\r\n results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);\r\n }\r\n else {\r\n warn(\"Invalid query segment '\" + segment + \"' in query '\" + queryString + \"'\");\r\n }\r\n }\r\n return results;\r\n}\r\n/**\r\n *\r\n * @param {!string} dataURL\r\n * @return {{repoInfo: !RepoInfo, path: !Path}}\r\n */\r\nvar parseRepoInfo = function (dataURL) {\r\n var parsedUrl = parseURL(dataURL), namespace = parsedUrl.subdomain;\r\n if (parsedUrl.domain === 'firebase') {\r\n fatal(parsedUrl.host +\r\n ' is no longer supported. ' +\r\n 'Please use .firebaseio.com instead');\r\n }\r\n // Catch common error of uninitialized namespace value.\r\n if ((!namespace || namespace == 'undefined') &&\r\n parsedUrl.domain !== 'localhost') {\r\n fatal('Cannot parse Firebase url. Please use https://.firebaseio.com');\r\n }\r\n if (!parsedUrl.secure) {\r\n warnIfPageIsSecure();\r\n }\r\n var webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';\r\n return {\r\n repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly),\r\n path: new Path(parsedUrl.pathString)\r\n };\r\n};\r\n/**\r\n *\r\n * @param {!string} dataURL\r\n * @return {{host: string, port: number, domain: string, subdomain: string, secure: boolean, scheme: string, pathString: string}}\r\n */\r\nvar parseURL = function (dataURL) {\r\n // Default to empty strings in the event of a malformed string.\r\n var host = '', domain = '', subdomain = '', pathString = '';\r\n // Always default to SSL, unless otherwise specified.\r\n var secure = true, scheme = 'https', port = 443;\r\n // Don't do any validation here. The caller is responsible for validating the result of parsing.\r\n if (typeof dataURL === 'string') {\r\n // Parse scheme.\r\n var colonInd = dataURL.indexOf('//');\r\n if (colonInd >= 0) {\r\n scheme = dataURL.substring(0, colonInd - 1);\r\n dataURL = dataURL.substring(colonInd + 2);\r\n }\r\n // Parse host, path, and query string.\r\n var slashInd = dataURL.indexOf('/');\r\n if (slashInd === -1) {\r\n slashInd = dataURL.length;\r\n }\r\n var questionMarkInd = dataURL.indexOf('?');\r\n if (questionMarkInd === -1) {\r\n questionMarkInd = dataURL.length;\r\n }\r\n host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));\r\n if (slashInd < questionMarkInd) {\r\n // For pathString, questionMarkInd will always come after slashInd\r\n pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));\r\n }\r\n var queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));\r\n // If we have a port, use scheme for determining if it's secure.\r\n colonInd = host.indexOf(':');\r\n if (colonInd >= 0) {\r\n secure = scheme === 'https' || scheme === 'wss';\r\n port = parseInt(host.substring(colonInd + 1), 10);\r\n }\r\n else {\r\n colonInd = dataURL.length;\r\n }\r\n var parts = host.split('.');\r\n if (parts.length === 3) {\r\n // Normalize namespaces to lowercase to share storage / connection.\r\n domain = parts[1];\r\n subdomain = parts[0].toLowerCase();\r\n }\r\n else if (parts.length === 2) {\r\n domain = parts[0];\r\n }\r\n else if (parts[0].slice(0, colonInd).toLowerCase() === 'localhost') {\r\n domain = 'localhost';\r\n }\r\n // Support `ns` query param if subdomain not already set\r\n if (subdomain === '' && 'ns' in queryParams) {\r\n subdomain = queryParams['ns'];\r\n }\r\n }\r\n return {\r\n host: host,\r\n port: port,\r\n domain: domain,\r\n subdomain: subdomain,\r\n secure: secure,\r\n scheme: scheme,\r\n pathString: pathString\r\n };\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * True for invalid Firebase keys\r\n * @type {RegExp}\r\n * @private\r\n */\r\nvar INVALID_KEY_REGEX_ = /[\\[\\].#$\\/\\u0000-\\u001F\\u007F]/;\r\n/**\r\n * True for invalid Firebase paths.\r\n * Allows '/' in paths.\r\n * @type {RegExp}\r\n * @private\r\n */\r\nvar INVALID_PATH_REGEX_ = /[\\[\\].#$\\u0000-\\u001F\\u007F]/;\r\n/**\r\n * Maximum number of characters to allow in leaf value\r\n * @type {number}\r\n * @private\r\n */\r\nvar MAX_LEAF_SIZE_ = 10 * 1024 * 1024;\r\n/**\r\n * @param {*} key\r\n * @return {boolean}\r\n */\r\nvar isValidKey = function (key) {\r\n return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key));\r\n};\r\n/**\r\n * @param {string} pathString\r\n * @return {boolean}\r\n */\r\nvar isValidPathString = function (pathString) {\r\n return (typeof pathString === 'string' &&\r\n pathString.length !== 0 &&\r\n !INVALID_PATH_REGEX_.test(pathString));\r\n};\r\n/**\r\n * @param {string} pathString\r\n * @return {boolean}\r\n */\r\nvar isValidRootPathString = function (pathString) {\r\n if (pathString) {\r\n // Allow '/.info/' at the beginning.\r\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\r\n }\r\n return isValidPathString(pathString);\r\n};\r\n/**\r\n * @param {*} priority\r\n * @return {boolean}\r\n */\r\nvar isValidPriority = function (priority) {\r\n return (priority === null ||\r\n typeof priority === 'string' ||\r\n (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||\r\n (priority && typeof priority === 'object' && util.contains(priority, '.sv')));\r\n};\r\n/**\r\n * Pre-validate a datum passed as an argument to Firebase function.\r\n *\r\n * @param {string} fnName\r\n * @param {number} argumentNumber\r\n * @param {*} data\r\n * @param {!Path} path\r\n * @param {boolean} optional\r\n */\r\nvar validateFirebaseDataArg = function (fnName, argumentNumber, data, path, optional) {\r\n if (optional && data === undefined)\r\n return;\r\n validateFirebaseData(util.errorPrefix(fnName, argumentNumber, optional), data, path);\r\n};\r\n/**\r\n * Validate a data object client-side before sending to server.\r\n *\r\n * @param {string} errorPrefix\r\n * @param {*} data\r\n * @param {!Path|!ValidationPath} path_\r\n */\r\nvar validateFirebaseData = function (errorPrefix, data, path_) {\r\n var path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;\r\n if (data === undefined) {\r\n throw new Error(errorPrefix + 'contains undefined ' + path.toErrorString());\r\n }\r\n if (typeof data === 'function') {\r\n throw new Error(errorPrefix +\r\n 'contains a function ' +\r\n path.toErrorString() +\r\n ' with contents = ' +\r\n data.toString());\r\n }\r\n if (isInvalidJSONNumber(data)) {\r\n throw new Error(errorPrefix + 'contains ' + data.toString() + ' ' + path.toErrorString());\r\n }\r\n // Check max leaf size, but try to avoid the utf8 conversion if we can.\r\n if (typeof data === 'string' &&\r\n data.length > MAX_LEAF_SIZE_ / 3 &&\r\n util.stringLength(data) > MAX_LEAF_SIZE_) {\r\n throw new Error(errorPrefix +\r\n 'contains a string greater than ' +\r\n MAX_LEAF_SIZE_ +\r\n ' utf8 bytes ' +\r\n path.toErrorString() +\r\n \" ('\" +\r\n data.substring(0, 50) +\r\n \"...')\");\r\n }\r\n // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON\r\n // to save extra walking of large objects.\r\n if (data && typeof data === 'object') {\r\n var hasDotValue_1 = false, hasActualChild_1 = false;\r\n util.forEach(data, function (key, value) {\r\n if (key === '.value') {\r\n hasDotValue_1 = true;\r\n }\r\n else if (key !== '.priority' && key !== '.sv') {\r\n hasActualChild_1 = true;\r\n if (!isValidKey(key)) {\r\n throw new Error(errorPrefix +\r\n ' contains an invalid key (' +\r\n key +\r\n ') ' +\r\n path.toErrorString() +\r\n '. Keys must be non-empty strings ' +\r\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\r\n }\r\n }\r\n path.push(key);\r\n validateFirebaseData(errorPrefix, value, path);\r\n path.pop();\r\n });\r\n if (hasDotValue_1 && hasActualChild_1) {\r\n throw new Error(errorPrefix +\r\n ' contains \".value\" child ' +\r\n path.toErrorString() +\r\n ' in addition to actual children.');\r\n }\r\n }\r\n};\r\n/**\r\n * Pre-validate paths passed in the firebase function.\r\n *\r\n * @param {string} errorPrefix\r\n * @param {Array} mergePaths\r\n */\r\nvar validateFirebaseMergePaths = function (errorPrefix, mergePaths) {\r\n var i, curPath;\r\n for (i = 0; i < mergePaths.length; i++) {\r\n curPath = mergePaths[i];\r\n var keys = curPath.slice();\r\n for (var j = 0; j < keys.length; j++) {\r\n if (keys[j] === '.priority' && j === keys.length - 1) ;\r\n else if (!isValidKey(keys[j])) {\r\n throw new Error(errorPrefix +\r\n 'contains an invalid key (' +\r\n keys[j] +\r\n ') in path ' +\r\n curPath.toString() +\r\n '. Keys must be non-empty strings ' +\r\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\r\n }\r\n }\r\n }\r\n // Check that update keys are not descendants of each other.\r\n // We rely on the property that sorting guarantees that ancestors come\r\n // right before descendants.\r\n mergePaths.sort(Path.comparePaths);\r\n var prevPath = null;\r\n for (i = 0; i < mergePaths.length; i++) {\r\n curPath = mergePaths[i];\r\n if (prevPath !== null && prevPath.contains(curPath)) {\r\n throw new Error(errorPrefix +\r\n 'contains a path ' +\r\n prevPath.toString() +\r\n ' that is ancestor of another path ' +\r\n curPath.toString());\r\n }\r\n prevPath = curPath;\r\n }\r\n};\r\n/**\r\n * pre-validate an object passed as an argument to firebase function (\r\n * must be an object - e.g. for firebase.update()).\r\n *\r\n * @param {string} fnName\r\n * @param {number} argumentNumber\r\n * @param {*} data\r\n * @param {!Path} path\r\n * @param {boolean} optional\r\n */\r\nvar validateFirebaseMergeDataArg = function (fnName, argumentNumber, data, path, optional) {\r\n if (optional && data === undefined)\r\n return;\r\n var errorPrefix = util.errorPrefix(fnName, argumentNumber, optional);\r\n if (!(data && typeof data === 'object') || Array.isArray(data)) {\r\n throw new Error(errorPrefix + ' must be an object containing the children to replace.');\r\n }\r\n var mergePaths = [];\r\n util.forEach(data, function (key, value) {\r\n var curPath = new Path(key);\r\n validateFirebaseData(errorPrefix, value, path.child(curPath));\r\n if (curPath.getBack() === '.priority') {\r\n if (!isValidPriority(value)) {\r\n throw new Error(errorPrefix +\r\n \"contains an invalid value for '\" +\r\n curPath.toString() +\r\n \"', which must be a valid \" +\r\n 'Firebase priority (a string, finite number, server value, or null).');\r\n }\r\n }\r\n mergePaths.push(curPath);\r\n });\r\n validateFirebaseMergePaths(errorPrefix, mergePaths);\r\n};\r\nvar validatePriority = function (fnName, argumentNumber, priority, optional) {\r\n if (optional && priority === undefined)\r\n return;\r\n if (isInvalidJSONNumber(priority))\r\n throw new Error(util.errorPrefix(fnName, argumentNumber, optional) +\r\n 'is ' +\r\n priority.toString() +\r\n ', but must be a valid Firebase priority (a string, finite number, ' +\r\n 'server value, or null).');\r\n // Special case to allow importing data with a .sv.\r\n if (!isValidPriority(priority))\r\n throw new Error(util.errorPrefix(fnName, argumentNumber, optional) +\r\n 'must be a valid Firebase priority ' +\r\n '(a string, finite number, server value, or null).');\r\n};\r\nvar validateEventType = function (fnName, argumentNumber, eventType, optional) {\r\n if (optional && eventType === undefined)\r\n return;\r\n switch (eventType) {\r\n case 'value':\r\n case 'child_added':\r\n case 'child_removed':\r\n case 'child_changed':\r\n case 'child_moved':\r\n break;\r\n default:\r\n throw new Error(util.errorPrefix(fnName, argumentNumber, optional) +\r\n 'must be a valid event type = \"value\", \"child_added\", \"child_removed\", ' +\r\n '\"child_changed\", or \"child_moved\".');\r\n }\r\n};\r\nvar validateKey = function (fnName, argumentNumber, key, optional) {\r\n if (optional && key === undefined)\r\n return;\r\n if (!isValidKey(key))\r\n throw new Error(util.errorPrefix(fnName, argumentNumber, optional) +\r\n 'was an invalid key = \"' +\r\n key +\r\n '\". Firebase keys must be non-empty strings and ' +\r\n 'can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\").');\r\n};\r\nvar validatePathString = function (fnName, argumentNumber, pathString, optional) {\r\n if (optional && pathString === undefined)\r\n return;\r\n if (!isValidPathString(pathString))\r\n throw new Error(util.errorPrefix(fnName, argumentNumber, optional) +\r\n 'was an invalid path = \"' +\r\n pathString +\r\n '\". Paths must be non-empty strings and ' +\r\n 'can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\"');\r\n};\r\nvar validateRootPathString = function (fnName, argumentNumber, pathString, optional) {\r\n if (pathString) {\r\n // Allow '/.info/' at the beginning.\r\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\r\n }\r\n validatePathString(fnName, argumentNumber, pathString, optional);\r\n};\r\nvar validateWritablePath = function (fnName, path) {\r\n if (path.getFront() === '.info') {\r\n throw new Error(fnName + \" failed = Can't modify data under /.info/\");\r\n }\r\n};\r\nvar validateUrl = function (fnName, argumentNumber, parsedUrl) {\r\n // TODO = Validate server better.\r\n var pathString = parsedUrl.path.toString();\r\n if (!(typeof parsedUrl.repoInfo.host === 'string') ||\r\n parsedUrl.repoInfo.host.length === 0 ||\r\n (!isValidKey(parsedUrl.repoInfo.namespace) &&\r\n parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||\r\n (pathString.length !== 0 && !isValidRootPathString(pathString))) {\r\n throw new Error(util.errorPrefix(fnName, argumentNumber, false) +\r\n 'must be a valid firebase URL and ' +\r\n 'the path can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\".');\r\n }\r\n};\r\nvar validateBoolean = function (fnName, argumentNumber, bool, optional) {\r\n if (optional && bool === undefined)\r\n return;\r\n if (typeof bool !== 'boolean')\r\n throw new Error(util.errorPrefix(fnName, argumentNumber, optional) + 'must be a boolean.');\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @constructor\r\n */\r\nvar OnDisconnect = /** @class */ (function () {\r\n /**\r\n * @param {!Repo} repo_\r\n * @param {!Path} path_\r\n */\r\n function OnDisconnect(repo_, path_) {\r\n this.repo_ = repo_;\r\n this.path_ = path_;\r\n }\r\n /**\r\n * @param {function(?Error)=} onComplete\r\n * @return {!firebase.Promise}\r\n */\r\n OnDisconnect.prototype.cancel = function (onComplete) {\r\n util.validateArgCount('OnDisconnect.cancel', 0, 1, arguments.length);\r\n util.validateCallback('OnDisconnect.cancel', 1, onComplete, true);\r\n var deferred = new util.Deferred();\r\n this.repo_.onDisconnectCancel(this.path_, deferred.wrapCallback(onComplete));\r\n return deferred.promise;\r\n };\r\n /**\r\n * @param {function(?Error)=} onComplete\r\n * @return {!firebase.Promise}\r\n */\r\n OnDisconnect.prototype.remove = function (onComplete) {\r\n util.validateArgCount('OnDisconnect.remove', 0, 1, arguments.length);\r\n validateWritablePath('OnDisconnect.remove', this.path_);\r\n util.validateCallback('OnDisconnect.remove', 1, onComplete, true);\r\n var deferred = new util.Deferred();\r\n this.repo_.onDisconnectSet(this.path_, null, deferred.wrapCallback(onComplete));\r\n return deferred.promise;\r\n };\r\n /**\r\n * @param {*} value\r\n * @param {function(?Error)=} onComplete\r\n * @return {!firebase.Promise}\r\n */\r\n OnDisconnect.prototype.set = function (value, onComplete) {\r\n util.validateArgCount('OnDisconnect.set', 1, 2, arguments.length);\r\n validateWritablePath('OnDisconnect.set', this.path_);\r\n validateFirebaseDataArg('OnDisconnect.set', 1, value, this.path_, false);\r\n util.validateCallback('OnDisconnect.set', 2, onComplete, true);\r\n var deferred = new util.Deferred();\r\n this.repo_.onDisconnectSet(this.path_, value, deferred.wrapCallback(onComplete));\r\n return deferred.promise;\r\n };\r\n /**\r\n * @param {*} value\r\n * @param {number|string|null} priority\r\n * @param {function(?Error)=} onComplete\r\n * @return {!firebase.Promise}\r\n */\r\n OnDisconnect.prototype.setWithPriority = function (value, priority, onComplete) {\r\n util.validateArgCount('OnDisconnect.setWithPriority', 2, 3, arguments.length);\r\n validateWritablePath('OnDisconnect.setWithPriority', this.path_);\r\n validateFirebaseDataArg('OnDisconnect.setWithPriority', 1, value, this.path_, false);\r\n validatePriority('OnDisconnect.setWithPriority', 2, priority, false);\r\n util.validateCallback('OnDisconnect.setWithPriority', 3, onComplete, true);\r\n var deferred = new util.Deferred();\r\n this.repo_.onDisconnectSetWithPriority(this.path_, value, priority, deferred.wrapCallback(onComplete));\r\n return deferred.promise;\r\n };\r\n /**\r\n * @param {!Object} objectToMerge\r\n * @param {function(?Error)=} onComplete\r\n * @return {!firebase.Promise}\r\n */\r\n OnDisconnect.prototype.update = function (objectToMerge, onComplete) {\r\n util.validateArgCount('OnDisconnect.update', 1, 2, arguments.length);\r\n validateWritablePath('OnDisconnect.update', this.path_);\r\n if (Array.isArray(objectToMerge)) {\r\n var newObjectToMerge = {};\r\n for (var i = 0; i < objectToMerge.length; ++i) {\r\n newObjectToMerge['' + i] = objectToMerge[i];\r\n }\r\n objectToMerge = newObjectToMerge;\r\n warn('Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the ' +\r\n 'existing data, or an Object with integer keys if you really do want to only update some of the children.');\r\n }\r\n validateFirebaseMergeDataArg('OnDisconnect.update', 1, objectToMerge, this.path_, false);\r\n util.validateCallback('OnDisconnect.update', 2, onComplete, true);\r\n var deferred = new util.Deferred();\r\n this.repo_.onDisconnectUpdate(this.path_, objectToMerge, deferred.wrapCallback(onComplete));\r\n return deferred.promise;\r\n };\r\n return OnDisconnect;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar TransactionResult = /** @class */ (function () {\r\n /**\r\n * A type for the resolve value of Firebase.transaction.\r\n * @constructor\r\n * @dict\r\n * @param {boolean} committed\r\n * @param {DataSnapshot} snapshot\r\n */\r\n function TransactionResult(committed, snapshot) {\r\n this.committed = committed;\r\n this.snapshot = snapshot;\r\n }\r\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\r\n // for end-users\r\n TransactionResult.prototype.toJSON = function () {\r\n util.validateArgCount('TransactionResult.toJSON', 0, 1, arguments.length);\r\n return { committed: this.committed, snapshot: this.snapshot.toJSON() };\r\n };\r\n return TransactionResult;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Fancy ID generator that creates 20-character string identifiers with the\r\n * following properties:\r\n *\r\n * 1. They're based on timestamp so that they sort *after* any existing ids.\r\n * 2. They contain 72-bits of random data after the timestamp so that IDs won't\r\n * collide with other clients' IDs.\r\n * 3. They sort *lexicographically* (so the timestamp is converted to characters\r\n * that will sort properly).\r\n * 4. They're monotonically increasing. Even if you generate more than one in\r\n * the same timestamp, the latter ones will sort after the former ones. We do\r\n * this by using the previous random bits but \"incrementing\" them by 1 (only\r\n * in the case of a timestamp collision).\r\n */\r\nvar nextPushId = (function () {\r\n // Modeled after base64 web-safe chars, but ordered by ASCII.\r\n var PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';\r\n // Timestamp of last push, used to prevent local collisions if you push twice\r\n // in one ms.\r\n var lastPushTime = 0;\r\n // We generate 72-bits of randomness which get turned into 12 characters and\r\n // appended to the timestamp to prevent collisions with other clients. We\r\n // store the last characters we generated because in the event of a collision,\r\n // we'll use those same characters except \"incremented\" by one.\r\n var lastRandChars = [];\r\n return function (now) {\r\n var duplicateTime = now === lastPushTime;\r\n lastPushTime = now;\r\n var i;\r\n var timeStampChars = new Array(8);\r\n for (i = 7; i >= 0; i--) {\r\n timeStampChars[i] = PUSH_CHARS.charAt(now % 64);\r\n // NOTE: Can't use << here because javascript will convert to int and lose\r\n // the upper bits.\r\n now = Math.floor(now / 64);\r\n }\r\n util.assert(now === 0, 'Cannot push at time == 0');\r\n var id = timeStampChars.join('');\r\n if (!duplicateTime) {\r\n for (i = 0; i < 12; i++) {\r\n lastRandChars[i] = Math.floor(Math.random() * 64);\r\n }\r\n }\r\n else {\r\n // If the timestamp hasn't changed since last push, use the same random\r\n // number, except incremented by 1.\r\n for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {\r\n lastRandChars[i] = 0;\r\n }\r\n lastRandChars[i]++;\r\n }\r\n for (i = 0; i < 12; i++) {\r\n id += PUSH_CHARS.charAt(lastRandChars[i]);\r\n }\r\n util.assert(id.length === 20, 'nextPushId: Length should be 20.');\r\n return id;\r\n };\r\n})();\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n *\r\n * @param {!string} name\r\n * @param {!Node} node\r\n * @constructor\r\n * @struct\r\n */\r\nvar NamedNode = /** @class */ (function () {\r\n function NamedNode(name, node) {\r\n this.name = name;\r\n this.node = node;\r\n }\r\n /**\r\n *\r\n * @param {!string} name\r\n * @param {!Node} node\r\n * @return {NamedNode}\r\n */\r\n NamedNode.Wrap = function (name, node) {\r\n return new NamedNode(name, node);\r\n };\r\n return NamedNode;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n *\r\n * @constructor\r\n */\r\nvar Index = /** @class */ (function () {\r\n function Index() {\r\n }\r\n /**\r\n * @return {function(!NamedNode, !NamedNode):number} A standalone comparison function for\r\n * this index\r\n */\r\n Index.prototype.getCompare = function () {\r\n return this.compare.bind(this);\r\n };\r\n /**\r\n * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,\r\n * it's possible that the changes are isolated to parts of the snapshot that are not indexed.\r\n *\r\n * @param {!Node} oldNode\r\n * @param {!Node} newNode\r\n * @return {boolean} True if the portion of the snapshot being indexed changed between oldNode and newNode\r\n */\r\n Index.prototype.indexedValueChanged = function (oldNode, newNode) {\r\n var oldWrapped = new NamedNode(MIN_NAME, oldNode);\r\n var newWrapped = new NamedNode(MIN_NAME, newNode);\r\n return this.compare(oldWrapped, newWrapped) !== 0;\r\n };\r\n /**\r\n * @return {!NamedNode} a node wrapper that will sort equal to or less than\r\n * any other node wrapper, using this index\r\n */\r\n Index.prototype.minPost = function () {\r\n return NamedNode.MIN;\r\n };\r\n return Index;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar __EMPTY_NODE;\r\nvar KeyIndex = /** @class */ (function (_super) {\r\n tslib_1.__extends(KeyIndex, _super);\r\n function KeyIndex() {\r\n return _super !== null && _super.apply(this, arguments) || this;\r\n }\r\n Object.defineProperty(KeyIndex, \"__EMPTY_NODE\", {\r\n get: function () {\r\n return __EMPTY_NODE;\r\n },\r\n set: function (val) {\r\n __EMPTY_NODE = val;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n /**\r\n * @inheritDoc\r\n */\r\n KeyIndex.prototype.compare = function (a, b) {\r\n return nameCompare(a.name, b.name);\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n KeyIndex.prototype.isDefinedOn = function (node) {\r\n // We could probably return true here (since every node has a key), but it's never called\r\n // so just leaving unimplemented for now.\r\n throw util.assertionError('KeyIndex.isDefinedOn not expected to be called.');\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n KeyIndex.prototype.indexedValueChanged = function (oldNode, newNode) {\r\n return false; // The key for a node never changes.\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n KeyIndex.prototype.minPost = function () {\r\n return NamedNode.MIN;\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n KeyIndex.prototype.maxPost = function () {\r\n // TODO: This should really be created once and cached in a static property, but\r\n // NamedNode isn't defined yet, so I can't use it in a static. Bleh.\r\n return new NamedNode(MAX_NAME, __EMPTY_NODE);\r\n };\r\n /**\r\n * @param {*} indexValue\r\n * @param {string} name\r\n * @return {!NamedNode}\r\n */\r\n KeyIndex.prototype.makePost = function (indexValue, name) {\r\n util.assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');\r\n // We just use empty node, but it'll never be compared, since our comparator only looks at name.\r\n return new NamedNode(indexValue, __EMPTY_NODE);\r\n };\r\n /**\r\n * @return {!string} String representation for inclusion in a query spec\r\n */\r\n KeyIndex.prototype.toString = function () {\r\n return '.key';\r\n };\r\n return KeyIndex;\r\n}(Index));\r\nvar KEY_INDEX = new KeyIndex();\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar MAX_NODE;\r\nfunction setMaxNode(val) {\r\n MAX_NODE = val;\r\n}\r\n/**\r\n * @param {(!string|!number)} priority\r\n * @return {!string}\r\n */\r\nvar priorityHashText = function (priority) {\r\n if (typeof priority === 'number')\r\n return 'number:' + doubleToIEEE754String(priority);\r\n else\r\n return 'string:' + priority;\r\n};\r\n/**\r\n * Validates that a priority snapshot Node is valid.\r\n *\r\n * @param {!Node} priorityNode\r\n */\r\nvar validatePriorityNode = function (priorityNode) {\r\n if (priorityNode.isLeafNode()) {\r\n var val = priorityNode.val();\r\n util.assert(typeof val === 'string' ||\r\n typeof val === 'number' ||\r\n (typeof val === 'object' && util.contains(val, '.sv')), 'Priority must be a string or number.');\r\n }\r\n else {\r\n util.assert(priorityNode === MAX_NODE || priorityNode.isEmpty(), 'priority of unexpected type.');\r\n }\r\n // Don't call getPriority() on MAX_NODE to avoid hitting assertion.\r\n util.assert(priorityNode === MAX_NODE || priorityNode.getPriority().isEmpty(), \"Priority nodes can't have a priority of their own.\");\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar __childrenNodeConstructor;\r\n/**\r\n * LeafNode is a class for storing leaf nodes in a DataSnapshot. It\r\n * implements Node and stores the value of the node (a string,\r\n * number, or boolean) accessible via getValue().\r\n */\r\nvar LeafNode = /** @class */ (function () {\r\n /**\r\n * @implements {Node}\r\n * @param {!(string|number|boolean|Object)} value_ The value to store in this leaf node.\r\n * The object type is possible in the event of a deferred value\r\n * @param {!Node=} priorityNode_ The priority of this node.\r\n */\r\n function LeafNode(value_, priorityNode_) {\r\n if (priorityNode_ === void 0) { priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE; }\r\n this.value_ = value_;\r\n this.priorityNode_ = priorityNode_;\r\n this.lazyHash_ = null;\r\n util.assert(this.value_ !== undefined && this.value_ !== null, \"LeafNode shouldn't be created with null/undefined value.\");\r\n validatePriorityNode(this.priorityNode_);\r\n }\r\n Object.defineProperty(LeafNode, \"__childrenNodeConstructor\", {\r\n get: function () {\r\n return __childrenNodeConstructor;\r\n },\r\n set: function (val) {\r\n __childrenNodeConstructor = val;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n /** @inheritDoc */\r\n LeafNode.prototype.isLeafNode = function () {\r\n return true;\r\n };\r\n /** @inheritDoc */\r\n LeafNode.prototype.getPriority = function () {\r\n return this.priorityNode_;\r\n };\r\n /** @inheritDoc */\r\n LeafNode.prototype.updatePriority = function (newPriorityNode) {\r\n return new LeafNode(this.value_, newPriorityNode);\r\n };\r\n /** @inheritDoc */\r\n LeafNode.prototype.getImmediateChild = function (childName) {\r\n // Hack to treat priority as a regular child\r\n if (childName === '.priority') {\r\n return this.priorityNode_;\r\n }\r\n else {\r\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\r\n }\r\n };\r\n /** @inheritDoc */\r\n LeafNode.prototype.getChild = function (path) {\r\n if (path.isEmpty()) {\r\n return this;\r\n }\r\n else if (path.getFront() === '.priority') {\r\n return this.priorityNode_;\r\n }\r\n else {\r\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\r\n }\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n LeafNode.prototype.hasChild = function () {\r\n return false;\r\n };\r\n /** @inheritDoc */\r\n LeafNode.prototype.getPredecessorChildName = function (childName, childNode) {\r\n return null;\r\n };\r\n /** @inheritDoc */\r\n LeafNode.prototype.updateImmediateChild = function (childName, newChildNode) {\r\n if (childName === '.priority') {\r\n return this.updatePriority(newChildNode);\r\n }\r\n else if (newChildNode.isEmpty() && childName !== '.priority') {\r\n return this;\r\n }\r\n else {\r\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);\r\n }\r\n };\r\n /** @inheritDoc */\r\n LeafNode.prototype.updateChild = function (path, newChildNode) {\r\n var front = path.getFront();\r\n if (front === null) {\r\n return newChildNode;\r\n }\r\n else if (newChildNode.isEmpty() && front !== '.priority') {\r\n return this;\r\n }\r\n else {\r\n util.assert(front !== '.priority' || path.getLength() === 1, '.priority must be the last token in a path');\r\n return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(path.popFront(), newChildNode));\r\n }\r\n };\r\n /** @inheritDoc */\r\n LeafNode.prototype.isEmpty = function () {\r\n return false;\r\n };\r\n /** @inheritDoc */\r\n LeafNode.prototype.numChildren = function () {\r\n return 0;\r\n };\r\n /** @inheritDoc */\r\n LeafNode.prototype.forEachChild = function (index, action) {\r\n return false;\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n LeafNode.prototype.val = function (exportFormat) {\r\n if (exportFormat && !this.getPriority().isEmpty())\r\n return {\r\n '.value': this.getValue(),\r\n '.priority': this.getPriority().val()\r\n };\r\n else\r\n return this.getValue();\r\n };\r\n /** @inheritDoc */\r\n LeafNode.prototype.hash = function () {\r\n if (this.lazyHash_ === null) {\r\n var toHash = '';\r\n if (!this.priorityNode_.isEmpty())\r\n toHash +=\r\n 'priority:' +\r\n priorityHashText(this.priorityNode_.val()) +\r\n ':';\r\n var type = typeof this.value_;\r\n toHash += type + ':';\r\n if (type === 'number') {\r\n toHash += doubleToIEEE754String(this.value_);\r\n }\r\n else {\r\n toHash += this.value_;\r\n }\r\n this.lazyHash_ = sha1(toHash);\r\n }\r\n return this.lazyHash_;\r\n };\r\n /**\r\n * Returns the value of the leaf node.\r\n * @return {Object|string|number|boolean} The value of the node.\r\n */\r\n LeafNode.prototype.getValue = function () {\r\n return this.value_;\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n LeafNode.prototype.compareTo = function (other) {\r\n if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {\r\n return 1;\r\n }\r\n else if (other instanceof LeafNode.__childrenNodeConstructor) {\r\n return -1;\r\n }\r\n else {\r\n util.assert(other.isLeafNode(), 'Unknown node type');\r\n return this.compareToLeafNode_(other);\r\n }\r\n };\r\n /**\r\n * Comparison specifically for two leaf nodes\r\n * @param {!LeafNode} otherLeaf\r\n * @return {!number}\r\n * @private\r\n */\r\n LeafNode.prototype.compareToLeafNode_ = function (otherLeaf) {\r\n var otherLeafType = typeof otherLeaf.value_;\r\n var thisLeafType = typeof this.value_;\r\n var otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);\r\n var thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);\r\n util.assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);\r\n util.assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);\r\n if (otherIndex === thisIndex) {\r\n // Same type, compare values\r\n if (thisLeafType === 'object') {\r\n // Deferred value nodes are all equal, but we should also never get to this point...\r\n return 0;\r\n }\r\n else {\r\n // Note that this works because true > false, all others are number or string comparisons\r\n if (this.value_ < otherLeaf.value_) {\r\n return -1;\r\n }\r\n else if (this.value_ === otherLeaf.value_) {\r\n return 0;\r\n }\r\n else {\r\n return 1;\r\n }\r\n }\r\n }\r\n else {\r\n return thisIndex - otherIndex;\r\n }\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n LeafNode.prototype.withIndex = function () {\r\n return this;\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n LeafNode.prototype.isIndexed = function () {\r\n return true;\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n LeafNode.prototype.equals = function (other) {\r\n /**\r\n * @inheritDoc\r\n */\r\n if (other === this) {\r\n return true;\r\n }\r\n else if (other.isLeafNode()) {\r\n var otherLeaf = other;\r\n return (this.value_ === otherLeaf.value_ &&\r\n this.priorityNode_.equals(otherLeaf.priorityNode_));\r\n }\r\n else {\r\n return false;\r\n }\r\n };\r\n /**\r\n * The sort order for comparing leaf nodes of different types. If two leaf nodes have\r\n * the same type, the comparison falls back to their value\r\n * @type {Array.}\r\n * @const\r\n */\r\n LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];\r\n return LeafNode;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar nodeFromJSON;\r\nvar MAX_NODE$1;\r\nfunction setNodeFromJSON(val) {\r\n nodeFromJSON = val;\r\n}\r\nfunction setMaxNode$1(val) {\r\n MAX_NODE$1 = val;\r\n}\r\n/**\r\n * @constructor\r\n * @extends {Index}\r\n * @private\r\n */\r\nvar PriorityIndex = /** @class */ (function (_super) {\r\n tslib_1.__extends(PriorityIndex, _super);\r\n function PriorityIndex() {\r\n return _super !== null && _super.apply(this, arguments) || this;\r\n }\r\n /**\r\n * @inheritDoc\r\n */\r\n PriorityIndex.prototype.compare = function (a, b) {\r\n var aPriority = a.node.getPriority();\r\n var bPriority = b.node.getPriority();\r\n var indexCmp = aPriority.compareTo(bPriority);\r\n if (indexCmp === 0) {\r\n return nameCompare(a.name, b.name);\r\n }\r\n else {\r\n return indexCmp;\r\n }\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n PriorityIndex.prototype.isDefinedOn = function (node) {\r\n return !node.getPriority().isEmpty();\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n PriorityIndex.prototype.indexedValueChanged = function (oldNode, newNode) {\r\n return !oldNode.getPriority().equals(newNode.getPriority());\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n PriorityIndex.prototype.minPost = function () {\r\n return NamedNode.MIN;\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n PriorityIndex.prototype.maxPost = function () {\r\n return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1));\r\n };\r\n /**\r\n * @param {*} indexValue\r\n * @param {string} name\r\n * @return {!NamedNode}\r\n */\r\n PriorityIndex.prototype.makePost = function (indexValue, name) {\r\n var priorityNode = nodeFromJSON(indexValue);\r\n return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));\r\n };\r\n /**\r\n * @return {!string} String representation for inclusion in a query spec\r\n */\r\n PriorityIndex.prototype.toString = function () {\r\n return '.priority';\r\n };\r\n return PriorityIndex;\r\n}(Index));\r\nvar PRIORITY_INDEX = new PriorityIndex();\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An iterator over an LLRBNode.\r\n */\r\nvar SortedMapIterator = /** @class */ (function () {\r\n /**\r\n * @template K, V, T\r\n * @param {LLRBNode|LLRBEmptyNode} node Node to iterate.\r\n * @param {?K} startKey\r\n * @param {function(K, K): number} comparator\r\n * @param {boolean} isReverse_ Whether or not to iterate in reverse\r\n * @param {(function(K, V):T)=} resultGenerator_\r\n */\r\n function SortedMapIterator(node, startKey, comparator, isReverse_, resultGenerator_) {\r\n if (resultGenerator_ === void 0) { resultGenerator_ = null; }\r\n this.isReverse_ = isReverse_;\r\n this.resultGenerator_ = resultGenerator_;\r\n /** @private\r\n * @type {Array.}\r\n */\r\n this.nodeStack_ = [];\r\n var cmp = 1;\r\n while (!node.isEmpty()) {\r\n node = node;\r\n cmp = startKey ? comparator(node.key, startKey) : 1;\r\n // flip the comparison if we're going in reverse\r\n if (isReverse_)\r\n cmp *= -1;\r\n if (cmp < 0) {\r\n // This node is less than our start key. ignore it\r\n if (this.isReverse_) {\r\n node = node.left;\r\n }\r\n else {\r\n node = node.right;\r\n }\r\n }\r\n else if (cmp === 0) {\r\n // This node is exactly equal to our start key. Push it on the stack, but stop iterating;\r\n this.nodeStack_.push(node);\r\n break;\r\n }\r\n else {\r\n // This node is greater than our start key, add it to the stack and move to the next one\r\n this.nodeStack_.push(node);\r\n if (this.isReverse_) {\r\n node = node.right;\r\n }\r\n else {\r\n node = node.left;\r\n }\r\n }\r\n }\r\n }\r\n SortedMapIterator.prototype.getNext = function () {\r\n if (this.nodeStack_.length === 0)\r\n return null;\r\n var node = this.nodeStack_.pop();\r\n var result;\r\n if (this.resultGenerator_)\r\n result = this.resultGenerator_(node.key, node.value);\r\n else\r\n result = { key: node.key, value: node.value };\r\n if (this.isReverse_) {\r\n node = node.left;\r\n while (!node.isEmpty()) {\r\n this.nodeStack_.push(node);\r\n node = node.right;\r\n }\r\n }\r\n else {\r\n node = node.right;\r\n while (!node.isEmpty()) {\r\n this.nodeStack_.push(node);\r\n node = node.left;\r\n }\r\n }\r\n return result;\r\n };\r\n SortedMapIterator.prototype.hasNext = function () {\r\n return this.nodeStack_.length > 0;\r\n };\r\n SortedMapIterator.prototype.peek = function () {\r\n if (this.nodeStack_.length === 0)\r\n return null;\r\n var node = this.nodeStack_[this.nodeStack_.length - 1];\r\n if (this.resultGenerator_) {\r\n return this.resultGenerator_(node.key, node.value);\r\n }\r\n else {\r\n return { key: node.key, value: node.value };\r\n }\r\n };\r\n return SortedMapIterator;\r\n}());\r\n/**\r\n * Represents a node in a Left-leaning Red-Black tree.\r\n */\r\nvar LLRBNode = /** @class */ (function () {\r\n /**\r\n * @template K, V\r\n * @param {!K} key Key associated with this node.\r\n * @param {!V} value Value associated with this node.\r\n * @param {?boolean} color Whether this node is red.\r\n * @param {?(LLRBNode|LLRBEmptyNode)=} left Left child.\r\n * @param {?(LLRBNode|LLRBEmptyNode)=} right Right child.\r\n */\r\n function LLRBNode(key, value, color, left, right) {\r\n this.key = key;\r\n this.value = value;\r\n this.color = color != null ? color : LLRBNode.RED;\r\n this.left =\r\n left != null ? left : SortedMap.EMPTY_NODE;\r\n this.right =\r\n right != null ? right : SortedMap.EMPTY_NODE;\r\n }\r\n /**\r\n * Returns a copy of the current node, optionally replacing pieces of it.\r\n *\r\n * @param {?K} key New key for the node, or null.\r\n * @param {?V} value New value for the node, or null.\r\n * @param {?boolean} color New color for the node, or null.\r\n * @param {?LLRBNode|LLRBEmptyNode} left New left child for the node, or null.\r\n * @param {?LLRBNode|LLRBEmptyNode} right New right child for the node, or null.\r\n * @return {!LLRBNode} The node copy.\r\n */\r\n LLRBNode.prototype.copy = function (key, value, color, left, right) {\r\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);\r\n };\r\n /**\r\n * @return {number} The total number of nodes in the tree.\r\n */\r\n LLRBNode.prototype.count = function () {\r\n return this.left.count() + 1 + this.right.count();\r\n };\r\n /**\r\n * @return {boolean} True if the tree is empty.\r\n */\r\n LLRBNode.prototype.isEmpty = function () {\r\n return false;\r\n };\r\n /**\r\n * Traverses the tree in key order and calls the specified action function\r\n * for each node.\r\n *\r\n * @param {function(!K, !V):*} action Callback function to be called for each\r\n * node. If it returns true, traversal is aborted.\r\n * @return {*} The first truthy value returned by action, or the last falsey\r\n * value returned by action\r\n */\r\n LLRBNode.prototype.inorderTraversal = function (action) {\r\n return (this.left.inorderTraversal(action) ||\r\n action(this.key, this.value) ||\r\n this.right.inorderTraversal(action));\r\n };\r\n /**\r\n * Traverses the tree in reverse key order and calls the specified action function\r\n * for each node.\r\n *\r\n * @param {function(!Object, !Object)} action Callback function to be called for each\r\n * node. If it returns true, traversal is aborted.\r\n * @return {*} True if traversal was aborted.\r\n */\r\n LLRBNode.prototype.reverseTraversal = function (action) {\r\n return (this.right.reverseTraversal(action) ||\r\n action(this.key, this.value) ||\r\n this.left.reverseTraversal(action));\r\n };\r\n /**\r\n * @return {!Object} The minimum node in the tree.\r\n * @private\r\n */\r\n LLRBNode.prototype.min_ = function () {\r\n if (this.left.isEmpty()) {\r\n return this;\r\n }\r\n else {\r\n return this.left.min_();\r\n }\r\n };\r\n /**\r\n * @return {!K} The maximum key in the tree.\r\n */\r\n LLRBNode.prototype.minKey = function () {\r\n return this.min_().key;\r\n };\r\n /**\r\n * @return {!K} The maximum key in the tree.\r\n */\r\n LLRBNode.prototype.maxKey = function () {\r\n if (this.right.isEmpty()) {\r\n return this.key;\r\n }\r\n else {\r\n return this.right.maxKey();\r\n }\r\n };\r\n /**\r\n *\r\n * @param {!Object} key Key to insert.\r\n * @param {!Object} value Value to insert.\r\n * @param {Comparator} comparator Comparator.\r\n * @return {!LLRBNode} New tree, with the key/value added.\r\n */\r\n LLRBNode.prototype.insert = function (key, value, comparator) {\r\n var cmp, n;\r\n n = this;\r\n cmp = comparator(key, n.key);\r\n if (cmp < 0) {\r\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\r\n }\r\n else if (cmp === 0) {\r\n n = n.copy(null, value, null, null, null);\r\n }\r\n else {\r\n n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));\r\n }\r\n return n.fixUp_();\r\n };\r\n /**\r\n * @private\r\n * @return {!LLRBNode|LLRBEmptyNode} New tree, with the minimum key removed.\r\n */\r\n LLRBNode.prototype.removeMin_ = function () {\r\n if (this.left.isEmpty()) {\r\n return SortedMap.EMPTY_NODE;\r\n }\r\n var n = this;\r\n if (!n.left.isRed_() && !n.left.left.isRed_())\r\n n = n.moveRedLeft_();\r\n n = n.copy(null, null, null, n.left.removeMin_(), null);\r\n return n.fixUp_();\r\n };\r\n /**\r\n * @param {!Object} key The key of the item to remove.\r\n * @param {Comparator} comparator Comparator.\r\n * @return {!LLRBNode|LLRBEmptyNode} New tree, with the specified item removed.\r\n */\r\n LLRBNode.prototype.remove = function (key, comparator) {\r\n var n, smallest;\r\n n = this;\r\n if (comparator(key, n.key) < 0) {\r\n if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {\r\n n = n.moveRedLeft_();\r\n }\r\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\r\n }\r\n else {\r\n if (n.left.isRed_())\r\n n = n.rotateRight_();\r\n if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {\r\n n = n.moveRedRight_();\r\n }\r\n if (comparator(key, n.key) === 0) {\r\n if (n.right.isEmpty()) {\r\n return SortedMap.EMPTY_NODE;\r\n }\r\n else {\r\n smallest = n.right.min_();\r\n n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());\r\n }\r\n }\r\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\r\n }\r\n return n.fixUp_();\r\n };\r\n /**\r\n * @private\r\n * @return {boolean} Whether this is a RED node.\r\n */\r\n LLRBNode.prototype.isRed_ = function () {\r\n return this.color;\r\n };\r\n /**\r\n * @private\r\n * @return {!LLRBNode} New tree after performing any needed rotations.\r\n */\r\n LLRBNode.prototype.fixUp_ = function () {\r\n var n = this;\r\n if (n.right.isRed_() && !n.left.isRed_())\r\n n = n.rotateLeft_();\r\n if (n.left.isRed_() && n.left.left.isRed_())\r\n n = n.rotateRight_();\r\n if (n.left.isRed_() && n.right.isRed_())\r\n n = n.colorFlip_();\r\n return n;\r\n };\r\n /**\r\n * @private\r\n * @return {!LLRBNode} New tree, after moveRedLeft.\r\n */\r\n LLRBNode.prototype.moveRedLeft_ = function () {\r\n var n = this.colorFlip_();\r\n if (n.right.left.isRed_()) {\r\n n = n.copy(null, null, null, null, n.right.rotateRight_());\r\n n = n.rotateLeft_();\r\n n = n.colorFlip_();\r\n }\r\n return n;\r\n };\r\n /**\r\n * @private\r\n * @return {!LLRBNode} New tree, after moveRedRight.\r\n */\r\n LLRBNode.prototype.moveRedRight_ = function () {\r\n var n = this.colorFlip_();\r\n if (n.left.left.isRed_()) {\r\n n = n.rotateRight_();\r\n n = n.colorFlip_();\r\n }\r\n return n;\r\n };\r\n /**\r\n * @private\r\n * @return {!LLRBNode} New tree, after rotateLeft.\r\n */\r\n LLRBNode.prototype.rotateLeft_ = function () {\r\n var nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\r\n return this.right.copy(null, null, this.color, nl, null);\r\n };\r\n /**\r\n * @private\r\n * @return {!LLRBNode} New tree, after rotateRight.\r\n */\r\n LLRBNode.prototype.rotateRight_ = function () {\r\n var nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\r\n return this.left.copy(null, null, this.color, null, nr);\r\n };\r\n /**\r\n * @private\r\n * @return {!LLRBNode} New tree, after colorFlip.\r\n */\r\n LLRBNode.prototype.colorFlip_ = function () {\r\n var left = this.left.copy(null, null, !this.left.color, null, null);\r\n var right = this.right.copy(null, null, !this.right.color, null, null);\r\n return this.copy(null, null, !this.color, left, right);\r\n };\r\n /**\r\n * For testing.\r\n *\r\n * @private\r\n * @return {boolean} True if all is well.\r\n */\r\n LLRBNode.prototype.checkMaxDepth_ = function () {\r\n var blackDepth = this.check_();\r\n return Math.pow(2.0, blackDepth) <= this.count() + 1;\r\n };\r\n /**\r\n * @private\r\n * @return {number} Not sure what this returns exactly. :-).\r\n */\r\n LLRBNode.prototype.check_ = function () {\r\n var blackDepth;\r\n if (this.isRed_() && this.left.isRed_()) {\r\n throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');\r\n }\r\n if (this.right.isRed_()) {\r\n throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');\r\n }\r\n blackDepth = this.left.check_();\r\n if (blackDepth !== this.right.check_()) {\r\n throw new Error('Black depths differ');\r\n }\r\n else {\r\n return blackDepth + (this.isRed_() ? 0 : 1);\r\n }\r\n };\r\n LLRBNode.RED = true;\r\n LLRBNode.BLACK = false;\r\n return LLRBNode;\r\n}());\r\n/**\r\n * Represents an empty node (a leaf node in the Red-Black Tree).\r\n */\r\nvar LLRBEmptyNode = /** @class */ (function () {\r\n function LLRBEmptyNode() {\r\n }\r\n /**\r\n * Returns a copy of the current node.\r\n *\r\n * @return {!LLRBEmptyNode} The node copy.\r\n */\r\n LLRBEmptyNode.prototype.copy = function (key, value, color, left, right) {\r\n return this;\r\n };\r\n /**\r\n * Returns a copy of the tree, with the specified key/value added.\r\n *\r\n * @param {!K} key Key to be added.\r\n * @param {!V} value Value to be added.\r\n * @param {Comparator} comparator Comparator.\r\n * @return {!LLRBNode} New tree, with item added.\r\n */\r\n LLRBEmptyNode.prototype.insert = function (key, value, comparator) {\r\n return new LLRBNode(key, value, null);\r\n };\r\n /**\r\n * Returns a copy of the tree, with the specified key removed.\r\n *\r\n * @param {!K} key The key to remove.\r\n * @param {Comparator} comparator Comparator.\r\n * @return {!LLRBEmptyNode} New tree, with item removed.\r\n */\r\n LLRBEmptyNode.prototype.remove = function (key, comparator) {\r\n return this;\r\n };\r\n /**\r\n * @return {number} The total number of nodes in the tree.\r\n */\r\n LLRBEmptyNode.prototype.count = function () {\r\n return 0;\r\n };\r\n /**\r\n * @return {boolean} True if the tree is empty.\r\n */\r\n LLRBEmptyNode.prototype.isEmpty = function () {\r\n return true;\r\n };\r\n /**\r\n * Traverses the tree in key order and calls the specified action function\r\n * for each node.\r\n *\r\n * @param {function(!K, !V):*} action Callback function to be called for each\r\n * node. If it returns true, traversal is aborted.\r\n * @return {boolean} True if traversal was aborted.\r\n */\r\n LLRBEmptyNode.prototype.inorderTraversal = function (action) {\r\n return false;\r\n };\r\n /**\r\n * Traverses the tree in reverse key order and calls the specified action function\r\n * for each node.\r\n *\r\n * @param {function(!K, !V)} action Callback function to be called for each\r\n * node. If it returns true, traversal is aborted.\r\n * @return {boolean} True if traversal was aborted.\r\n */\r\n LLRBEmptyNode.prototype.reverseTraversal = function (action) {\r\n return false;\r\n };\r\n /**\r\n * @return {null}\r\n */\r\n LLRBEmptyNode.prototype.minKey = function () {\r\n return null;\r\n };\r\n /**\r\n * @return {null}\r\n */\r\n LLRBEmptyNode.prototype.maxKey = function () {\r\n return null;\r\n };\r\n /**\r\n * @private\r\n * @return {number} Not sure what this returns exactly. :-).\r\n */\r\n LLRBEmptyNode.prototype.check_ = function () {\r\n return 0;\r\n };\r\n /**\r\n * @private\r\n * @return {boolean} Whether this node is red.\r\n */\r\n LLRBEmptyNode.prototype.isRed_ = function () {\r\n return false;\r\n };\r\n return LLRBEmptyNode;\r\n}());\r\n/**\r\n * An immutable sorted map implementation, based on a Left-leaning Red-Black\r\n * tree.\r\n */\r\nvar SortedMap = /** @class */ (function () {\r\n /**\r\n * @template K, V\r\n * @param {function(K, K):number} comparator_ Key comparator.\r\n * @param {LLRBNode=} root_ (Optional) Root node for the map.\r\n */\r\n function SortedMap(comparator_, root_) {\r\n if (root_ === void 0) { root_ = SortedMap.EMPTY_NODE; }\r\n this.comparator_ = comparator_;\r\n this.root_ = root_;\r\n }\r\n /**\r\n * Returns a copy of the map, with the specified key/value added or replaced.\r\n * (TODO: We should perhaps rename this method to 'put')\r\n *\r\n * @param {!K} key Key to be added.\r\n * @param {!V} value Value to be added.\r\n * @return {!SortedMap.} New map, with item added.\r\n */\r\n SortedMap.prototype.insert = function (key, value) {\r\n return new SortedMap(this.comparator_, this.root_\r\n .insert(key, value, this.comparator_)\r\n .copy(null, null, LLRBNode.BLACK, null, null));\r\n };\r\n /**\r\n * Returns a copy of the map, with the specified key removed.\r\n *\r\n * @param {!K} key The key to remove.\r\n * @return {!SortedMap.} New map, with item removed.\r\n */\r\n SortedMap.prototype.remove = function (key) {\r\n return new SortedMap(this.comparator_, this.root_\r\n .remove(key, this.comparator_)\r\n .copy(null, null, LLRBNode.BLACK, null, null));\r\n };\r\n /**\r\n * Returns the value of the node with the given key, or null.\r\n *\r\n * @param {!K} key The key to look up.\r\n * @return {?V} The value of the node with the given key, or null if the\r\n * key doesn't exist.\r\n */\r\n SortedMap.prototype.get = function (key) {\r\n var cmp;\r\n var node = this.root_;\r\n while (!node.isEmpty()) {\r\n cmp = this.comparator_(key, node.key);\r\n if (cmp === 0) {\r\n return node.value;\r\n }\r\n else if (cmp < 0) {\r\n node = node.left;\r\n }\r\n else if (cmp > 0) {\r\n node = node.right;\r\n }\r\n }\r\n return null;\r\n };\r\n /**\r\n * Returns the key of the item *before* the specified key, or null if key is the first item.\r\n * @param {K} key The key to find the predecessor of\r\n * @return {?K} The predecessor key.\r\n */\r\n SortedMap.prototype.getPredecessorKey = function (key) {\r\n var cmp, node = this.root_, rightParent = null;\r\n while (!node.isEmpty()) {\r\n cmp = this.comparator_(key, node.key);\r\n if (cmp === 0) {\r\n if (!node.left.isEmpty()) {\r\n node = node.left;\r\n while (!node.right.isEmpty())\r\n node = node.right;\r\n return node.key;\r\n }\r\n else if (rightParent) {\r\n return rightParent.key;\r\n }\r\n else {\r\n return null; // first item.\r\n }\r\n }\r\n else if (cmp < 0) {\r\n node = node.left;\r\n }\r\n else if (cmp > 0) {\r\n rightParent = node;\r\n node = node.right;\r\n }\r\n }\r\n throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');\r\n };\r\n /**\r\n * @return {boolean} True if the map is empty.\r\n */\r\n SortedMap.prototype.isEmpty = function () {\r\n return this.root_.isEmpty();\r\n };\r\n /**\r\n * @return {number} The total number of nodes in the map.\r\n */\r\n SortedMap.prototype.count = function () {\r\n return this.root_.count();\r\n };\r\n /**\r\n * @return {?K} The minimum key in the map.\r\n */\r\n SortedMap.prototype.minKey = function () {\r\n return this.root_.minKey();\r\n };\r\n /**\r\n * @return {?K} The maximum key in the map.\r\n */\r\n SortedMap.prototype.maxKey = function () {\r\n return this.root_.maxKey();\r\n };\r\n /**\r\n * Traverses the map in key order and calls the specified action function\r\n * for each key/value pair.\r\n *\r\n * @param {function(!K, !V):*} action Callback function to be called\r\n * for each key/value pair. If action returns true, traversal is aborted.\r\n * @return {*} The first truthy value returned by action, or the last falsey\r\n * value returned by action\r\n */\r\n SortedMap.prototype.inorderTraversal = function (action) {\r\n return this.root_.inorderTraversal(action);\r\n };\r\n /**\r\n * Traverses the map in reverse key order and calls the specified action function\r\n * for each key/value pair.\r\n *\r\n * @param {function(!Object, !Object)} action Callback function to be called\r\n * for each key/value pair. If action returns true, traversal is aborted.\r\n * @return {*} True if the traversal was aborted.\r\n */\r\n SortedMap.prototype.reverseTraversal = function (action) {\r\n return this.root_.reverseTraversal(action);\r\n };\r\n /**\r\n * Returns an iterator over the SortedMap.\r\n * @template T\r\n * @param {(function(K, V):T)=} resultGenerator\r\n * @return {SortedMapIterator.} The iterator.\r\n */\r\n SortedMap.prototype.getIterator = function (resultGenerator) {\r\n return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);\r\n };\r\n SortedMap.prototype.getIteratorFrom = function (key, resultGenerator) {\r\n return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);\r\n };\r\n SortedMap.prototype.getReverseIteratorFrom = function (key, resultGenerator) {\r\n return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);\r\n };\r\n SortedMap.prototype.getReverseIterator = function (resultGenerator) {\r\n return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);\r\n };\r\n /**\r\n * Always use the same empty node, to reduce memory.\r\n * @const\r\n */\r\n SortedMap.EMPTY_NODE = new LLRBEmptyNode();\r\n return SortedMap;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar LOG_2 = Math.log(2);\r\n/**\r\n * @constructor\r\n */\r\nvar Base12Num = /** @class */ (function () {\r\n /**\r\n * @param {number} length\r\n */\r\n function Base12Num(length) {\r\n var logBase2 = function (num) {\r\n return parseInt((Math.log(num) / LOG_2), 10);\r\n };\r\n var bitMask = function (bits) { return parseInt(Array(bits + 1).join('1'), 2); };\r\n this.count = logBase2(length + 1);\r\n this.current_ = this.count - 1;\r\n var mask = bitMask(this.count);\r\n this.bits_ = (length + 1) & mask;\r\n }\r\n /**\r\n * @return {boolean}\r\n */\r\n Base12Num.prototype.nextBitIsOne = function () {\r\n //noinspection JSBitwiseOperatorUsage\r\n var result = !(this.bits_ & (0x1 << this.current_));\r\n this.current_--;\r\n return result;\r\n };\r\n return Base12Num;\r\n}());\r\n/**\r\n * Takes a list of child nodes and constructs a SortedSet using the given comparison\r\n * function\r\n *\r\n * Uses the algorithm described in the paper linked here:\r\n * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458\r\n *\r\n * @template K, V\r\n * @param {Array.} childList Unsorted list of children\r\n * @param {function(!NamedNode, !NamedNode):number} cmp The comparison method to be used\r\n * @param {(function(NamedNode):K)=} keyFn An optional function to extract K from a node wrapper, if K's\r\n * type is not NamedNode\r\n * @param {(function(K, K):number)=} mapSortFn An optional override for comparator used by the generated sorted map\r\n * @return {SortedMap.}\r\n */\r\nvar buildChildSet = function (childList, cmp, keyFn, mapSortFn) {\r\n childList.sort(cmp);\r\n var buildBalancedTree = function (low, high) {\r\n var length = high - low;\r\n var namedNode;\r\n var key;\r\n if (length == 0) {\r\n return null;\r\n }\r\n else if (length == 1) {\r\n namedNode = childList[low];\r\n key = keyFn ? keyFn(namedNode) : namedNode;\r\n return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null);\r\n }\r\n else {\r\n var middle = parseInt((length / 2), 10) + low;\r\n var left = buildBalancedTree(low, middle);\r\n var right = buildBalancedTree(middle + 1, high);\r\n namedNode = childList[middle];\r\n key = keyFn ? keyFn(namedNode) : namedNode;\r\n return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right);\r\n }\r\n };\r\n var buildFrom12Array = function (base12) {\r\n var node = null;\r\n var root = null;\r\n var index = childList.length;\r\n var buildPennant = function (chunkSize, color) {\r\n var low = index - chunkSize;\r\n var high = index;\r\n index -= chunkSize;\r\n var childTree = buildBalancedTree(low + 1, high);\r\n var namedNode = childList[low];\r\n var key = keyFn ? keyFn(namedNode) : namedNode;\r\n attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree));\r\n };\r\n var attachPennant = function (pennant) {\r\n if (node) {\r\n node.left = pennant;\r\n node = pennant;\r\n }\r\n else {\r\n root = pennant;\r\n node = pennant;\r\n }\r\n };\r\n for (var i = 0; i < base12.count; ++i) {\r\n var isOne = base12.nextBitIsOne();\r\n // The number of nodes taken in each slice is 2^(arr.length - (i + 1))\r\n var chunkSize = Math.pow(2, base12.count - (i + 1));\r\n if (isOne) {\r\n buildPennant(chunkSize, LLRBNode.BLACK);\r\n }\r\n else {\r\n // current == 2\r\n buildPennant(chunkSize, LLRBNode.BLACK);\r\n buildPennant(chunkSize, LLRBNode.RED);\r\n }\r\n }\r\n return root;\r\n };\r\n var base12 = new Base12Num(childList.length);\r\n var root = buildFrom12Array(base12);\r\n return new SortedMap(mapSortFn || cmp, root);\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar _defaultIndexMap;\r\nvar fallbackObject = {};\r\n/**\r\n *\r\n * @param {Object.>} indexes\r\n * @param {Object.} indexSet\r\n * @constructor\r\n */\r\nvar IndexMap = /** @class */ (function () {\r\n function IndexMap(indexes_, indexSet_) {\r\n this.indexes_ = indexes_;\r\n this.indexSet_ = indexSet_;\r\n }\r\n Object.defineProperty(IndexMap, \"Default\", {\r\n /**\r\n * The default IndexMap for nodes without a priority\r\n * @type {!IndexMap}\r\n * @const\r\n */\r\n get: function () {\r\n util.assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');\r\n _defaultIndexMap =\r\n _defaultIndexMap ||\r\n new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX });\r\n return _defaultIndexMap;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n /**\r\n *\r\n * @param {!string} indexKey\r\n * @return {?SortedMap.}\r\n */\r\n IndexMap.prototype.get = function (indexKey) {\r\n var sortedMap = util.safeGet(this.indexes_, indexKey);\r\n if (!sortedMap)\r\n throw new Error('No index defined for ' + indexKey);\r\n if (sortedMap === fallbackObject) {\r\n // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the\r\n // regular child map\r\n return null;\r\n }\r\n else {\r\n return sortedMap;\r\n }\r\n };\r\n /**\r\n * @param {!Index} indexDefinition\r\n * @return {boolean}\r\n */\r\n IndexMap.prototype.hasIndex = function (indexDefinition) {\r\n return util.contains(this.indexSet_, indexDefinition.toString());\r\n };\r\n /**\r\n * @param {!Index} indexDefinition\r\n * @param {!SortedMap.} existingChildren\r\n * @return {!IndexMap}\r\n */\r\n IndexMap.prototype.addIndex = function (indexDefinition, existingChildren) {\r\n util.assert(indexDefinition !== KEY_INDEX, \"KeyIndex always exists and isn't meant to be added to the IndexMap.\");\r\n var childList = [];\r\n var sawIndexedValue = false;\r\n var iter = existingChildren.getIterator(NamedNode.Wrap);\r\n var next = iter.getNext();\r\n while (next) {\r\n sawIndexedValue =\r\n sawIndexedValue || indexDefinition.isDefinedOn(next.node);\r\n childList.push(next);\r\n next = iter.getNext();\r\n }\r\n var newIndex;\r\n if (sawIndexedValue) {\r\n newIndex = buildChildSet(childList, indexDefinition.getCompare());\r\n }\r\n else {\r\n newIndex = fallbackObject;\r\n }\r\n var indexName = indexDefinition.toString();\r\n var newIndexSet = util.clone(this.indexSet_);\r\n newIndexSet[indexName] = indexDefinition;\r\n var newIndexes = util.clone(this.indexes_);\r\n newIndexes[indexName] = newIndex;\r\n return new IndexMap(newIndexes, newIndexSet);\r\n };\r\n /**\r\n * Ensure that this node is properly tracked in any indexes that we're maintaining\r\n * @param {!NamedNode} namedNode\r\n * @param {!SortedMap.} existingChildren\r\n * @return {!IndexMap}\r\n */\r\n IndexMap.prototype.addToIndexes = function (namedNode, existingChildren) {\r\n var _this = this;\r\n var newIndexes = util.map(this.indexes_, function (indexedChildren, indexName) {\r\n var index = util.safeGet(_this.indexSet_, indexName);\r\n util.assert(index, 'Missing index implementation for ' + indexName);\r\n if (indexedChildren === fallbackObject) {\r\n // Check to see if we need to index everything\r\n if (index.isDefinedOn(namedNode.node)) {\r\n // We need to build this index\r\n var childList = [];\r\n var iter = existingChildren.getIterator(NamedNode.Wrap);\r\n var next = iter.getNext();\r\n while (next) {\r\n if (next.name != namedNode.name) {\r\n childList.push(next);\r\n }\r\n next = iter.getNext();\r\n }\r\n childList.push(namedNode);\r\n return buildChildSet(childList, index.getCompare());\r\n }\r\n else {\r\n // No change, this remains a fallback\r\n return fallbackObject;\r\n }\r\n }\r\n else {\r\n var existingSnap = existingChildren.get(namedNode.name);\r\n var newChildren = indexedChildren;\r\n if (existingSnap) {\r\n newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap));\r\n }\r\n return newChildren.insert(namedNode, namedNode.node);\r\n }\r\n });\r\n return new IndexMap(newIndexes, this.indexSet_);\r\n };\r\n /**\r\n * Create a new IndexMap instance with the given value removed\r\n * @param {!NamedNode} namedNode\r\n * @param {!SortedMap.} existingChildren\r\n * @return {!IndexMap}\r\n */\r\n IndexMap.prototype.removeFromIndexes = function (namedNode, existingChildren) {\r\n var newIndexes = util.map(this.indexes_, function (indexedChildren) {\r\n if (indexedChildren === fallbackObject) {\r\n // This is the fallback. Just return it, nothing to do in this case\r\n return indexedChildren;\r\n }\r\n else {\r\n var existingSnap = existingChildren.get(namedNode.name);\r\n if (existingSnap) {\r\n return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap));\r\n }\r\n else {\r\n // No record of this child\r\n return indexedChildren;\r\n }\r\n }\r\n });\r\n return new IndexMap(newIndexes, this.indexSet_);\r\n };\r\n return IndexMap;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction NAME_ONLY_COMPARATOR(left, right) {\r\n return nameCompare(left.name, right.name);\r\n}\r\nfunction NAME_COMPARATOR(left, right) {\r\n return nameCompare(left, right);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// TODO: For memory savings, don't store priorityNode_ if it's empty.\r\nvar EMPTY_NODE;\r\n/**\r\n * ChildrenNode is a class for storing internal nodes in a DataSnapshot\r\n * (i.e. nodes with children). It implements Node and stores the\r\n * list of children in the children property, sorted by child name.\r\n *\r\n * @constructor\r\n * @implements {Node}\r\n */\r\nvar ChildrenNode = /** @class */ (function () {\r\n /**\r\n *\r\n * @param {!SortedMap.} children_ List of children\r\n * of this node..\r\n * @param {?Node} priorityNode_ The priority of this node (as a snapshot node).\r\n * @param {!IndexMap} indexMap_\r\n */\r\n function ChildrenNode(children_, priorityNode_, indexMap_) {\r\n this.children_ = children_;\r\n this.priorityNode_ = priorityNode_;\r\n this.indexMap_ = indexMap_;\r\n this.lazyHash_ = null;\r\n /**\r\n * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use\r\n * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own\r\n * class instead of an empty ChildrenNode.\r\n */\r\n if (this.priorityNode_) {\r\n validatePriorityNode(this.priorityNode_);\r\n }\r\n if (this.children_.isEmpty()) {\r\n util.assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');\r\n }\r\n }\r\n Object.defineProperty(ChildrenNode, \"EMPTY_NODE\", {\r\n get: function () {\r\n return (EMPTY_NODE ||\r\n (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default)));\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n /** @inheritDoc */\r\n ChildrenNode.prototype.isLeafNode = function () {\r\n return false;\r\n };\r\n /** @inheritDoc */\r\n ChildrenNode.prototype.getPriority = function () {\r\n return this.priorityNode_ || EMPTY_NODE;\r\n };\r\n /** @inheritDoc */\r\n ChildrenNode.prototype.updatePriority = function (newPriorityNode) {\r\n if (this.children_.isEmpty()) {\r\n // Don't allow priorities on empty nodes\r\n return this;\r\n }\r\n else {\r\n return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);\r\n }\r\n };\r\n /** @inheritDoc */\r\n ChildrenNode.prototype.getImmediateChild = function (childName) {\r\n // Hack to treat priority as a regular child\r\n if (childName === '.priority') {\r\n return this.getPriority();\r\n }\r\n else {\r\n var child = this.children_.get(childName);\r\n return child === null ? EMPTY_NODE : child;\r\n }\r\n };\r\n /** @inheritDoc */\r\n ChildrenNode.prototype.getChild = function (path) {\r\n var front = path.getFront();\r\n if (front === null)\r\n return this;\r\n return this.getImmediateChild(front).getChild(path.popFront());\r\n };\r\n /** @inheritDoc */\r\n ChildrenNode.prototype.hasChild = function (childName) {\r\n return this.children_.get(childName) !== null;\r\n };\r\n /** @inheritDoc */\r\n ChildrenNode.prototype.updateImmediateChild = function (childName, newChildNode) {\r\n util.assert(newChildNode, 'We should always be passing snapshot nodes');\r\n if (childName === '.priority') {\r\n return this.updatePriority(newChildNode);\r\n }\r\n else {\r\n var namedNode = new NamedNode(childName, newChildNode);\r\n var newChildren = void 0, newIndexMap = void 0, newPriority = void 0;\r\n if (newChildNode.isEmpty()) {\r\n newChildren = this.children_.remove(childName);\r\n newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);\r\n }\r\n else {\r\n newChildren = this.children_.insert(childName, newChildNode);\r\n newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);\r\n }\r\n newPriority = newChildren.isEmpty() ? EMPTY_NODE : this.priorityNode_;\r\n return new ChildrenNode(newChildren, newPriority, newIndexMap);\r\n }\r\n };\r\n /** @inheritDoc */\r\n ChildrenNode.prototype.updateChild = function (path, newChildNode) {\r\n var front = path.getFront();\r\n if (front === null) {\r\n return newChildNode;\r\n }\r\n else {\r\n util.assert(path.getFront() !== '.priority' || path.getLength() === 1, '.priority must be the last token in a path');\r\n var newImmediateChild = this.getImmediateChild(front).updateChild(path.popFront(), newChildNode);\r\n return this.updateImmediateChild(front, newImmediateChild);\r\n }\r\n };\r\n /** @inheritDoc */\r\n ChildrenNode.prototype.isEmpty = function () {\r\n return this.children_.isEmpty();\r\n };\r\n /** @inheritDoc */\r\n ChildrenNode.prototype.numChildren = function () {\r\n return this.children_.count();\r\n };\r\n /** @inheritDoc */\r\n ChildrenNode.prototype.val = function (exportFormat) {\r\n if (this.isEmpty())\r\n return null;\r\n var obj = {};\r\n var numKeys = 0, maxKey = 0, allIntegerKeys = true;\r\n this.forEachChild(PRIORITY_INDEX, function (key, childNode) {\r\n obj[key] = childNode.val(exportFormat);\r\n numKeys++;\r\n if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {\r\n maxKey = Math.max(maxKey, Number(key));\r\n }\r\n else {\r\n allIntegerKeys = false;\r\n }\r\n });\r\n if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {\r\n // convert to array.\r\n var array = [];\r\n for (var key in obj)\r\n array[key] = obj[key];\r\n return array;\r\n }\r\n else {\r\n if (exportFormat && !this.getPriority().isEmpty()) {\r\n obj['.priority'] = this.getPriority().val();\r\n }\r\n return obj;\r\n }\r\n };\r\n /** @inheritDoc */\r\n ChildrenNode.prototype.hash = function () {\r\n if (this.lazyHash_ === null) {\r\n var toHash_1 = '';\r\n if (!this.getPriority().isEmpty())\r\n toHash_1 +=\r\n 'priority:' +\r\n priorityHashText(this.getPriority().val()) +\r\n ':';\r\n this.forEachChild(PRIORITY_INDEX, function (key, childNode) {\r\n var childHash = childNode.hash();\r\n if (childHash !== '')\r\n toHash_1 += ':' + key + ':' + childHash;\r\n });\r\n this.lazyHash_ = toHash_1 === '' ? '' : sha1(toHash_1);\r\n }\r\n return this.lazyHash_;\r\n };\r\n /** @inheritDoc */\r\n ChildrenNode.prototype.getPredecessorChildName = function (childName, childNode, index) {\r\n var idx = this.resolveIndex_(index);\r\n if (idx) {\r\n var predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode));\r\n return predecessor ? predecessor.name : null;\r\n }\r\n else {\r\n return this.children_.getPredecessorKey(childName);\r\n }\r\n };\r\n /**\r\n * @param {!Index} indexDefinition\r\n * @return {?string}\r\n */\r\n ChildrenNode.prototype.getFirstChildName = function (indexDefinition) {\r\n var idx = this.resolveIndex_(indexDefinition);\r\n if (idx) {\r\n var minKey = idx.minKey();\r\n return minKey && minKey.name;\r\n }\r\n else {\r\n return this.children_.minKey();\r\n }\r\n };\r\n /**\r\n * @param {!Index} indexDefinition\r\n * @return {?NamedNode}\r\n */\r\n ChildrenNode.prototype.getFirstChild = function (indexDefinition) {\r\n var minKey = this.getFirstChildName(indexDefinition);\r\n if (minKey) {\r\n return new NamedNode(minKey, this.children_.get(minKey));\r\n }\r\n else {\r\n return null;\r\n }\r\n };\r\n /**\r\n * Given an index, return the key name of the largest value we have, according to that index\r\n * @param {!Index} indexDefinition\r\n * @return {?string}\r\n */\r\n ChildrenNode.prototype.getLastChildName = function (indexDefinition) {\r\n var idx = this.resolveIndex_(indexDefinition);\r\n if (idx) {\r\n var maxKey = idx.maxKey();\r\n return maxKey && maxKey.name;\r\n }\r\n else {\r\n return this.children_.maxKey();\r\n }\r\n };\r\n /**\r\n * @param {!Index} indexDefinition\r\n * @return {?NamedNode}\r\n */\r\n ChildrenNode.prototype.getLastChild = function (indexDefinition) {\r\n var maxKey = this.getLastChildName(indexDefinition);\r\n if (maxKey) {\r\n return new NamedNode(maxKey, this.children_.get(maxKey));\r\n }\r\n else {\r\n return null;\r\n }\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n ChildrenNode.prototype.forEachChild = function (index, action) {\r\n var idx = this.resolveIndex_(index);\r\n if (idx) {\r\n return idx.inorderTraversal(function (wrappedNode) {\r\n return action(wrappedNode.name, wrappedNode.node);\r\n });\r\n }\r\n else {\r\n return this.children_.inorderTraversal(action);\r\n }\r\n };\r\n /**\r\n * @param {!Index} indexDefinition\r\n * @return {SortedMapIterator}\r\n */\r\n ChildrenNode.prototype.getIterator = function (indexDefinition) {\r\n return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);\r\n };\r\n /**\r\n *\r\n * @param {!NamedNode} startPost\r\n * @param {!Index} indexDefinition\r\n * @return {!SortedMapIterator}\r\n */\r\n ChildrenNode.prototype.getIteratorFrom = function (startPost, indexDefinition) {\r\n var idx = this.resolveIndex_(indexDefinition);\r\n if (idx) {\r\n return idx.getIteratorFrom(startPost, function (key) { return key; });\r\n }\r\n else {\r\n var iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap);\r\n var next = iterator.peek();\r\n while (next != null && indexDefinition.compare(next, startPost) < 0) {\r\n iterator.getNext();\r\n next = iterator.peek();\r\n }\r\n return iterator;\r\n }\r\n };\r\n /**\r\n * @param {!Index} indexDefinition\r\n * @return {!SortedMapIterator}\r\n */\r\n ChildrenNode.prototype.getReverseIterator = function (indexDefinition) {\r\n return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);\r\n };\r\n /**\r\n * @param {!NamedNode} endPost\r\n * @param {!Index} indexDefinition\r\n * @return {!SortedMapIterator}\r\n */\r\n ChildrenNode.prototype.getReverseIteratorFrom = function (endPost, indexDefinition) {\r\n var idx = this.resolveIndex_(indexDefinition);\r\n if (idx) {\r\n return idx.getReverseIteratorFrom(endPost, function (key) {\r\n return key;\r\n });\r\n }\r\n else {\r\n var iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap);\r\n var next = iterator.peek();\r\n while (next != null && indexDefinition.compare(next, endPost) > 0) {\r\n iterator.getNext();\r\n next = iterator.peek();\r\n }\r\n return iterator;\r\n }\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n ChildrenNode.prototype.compareTo = function (other) {\r\n if (this.isEmpty()) {\r\n if (other.isEmpty()) {\r\n return 0;\r\n }\r\n else {\r\n return -1;\r\n }\r\n }\r\n else if (other.isLeafNode() || other.isEmpty()) {\r\n return 1;\r\n }\r\n else if (other === MAX_NODE$2) {\r\n return -1;\r\n }\r\n else {\r\n // Must be another node with children.\r\n return 0;\r\n }\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n ChildrenNode.prototype.withIndex = function (indexDefinition) {\r\n if (indexDefinition === KEY_INDEX ||\r\n this.indexMap_.hasIndex(indexDefinition)) {\r\n return this;\r\n }\r\n else {\r\n var newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);\r\n return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);\r\n }\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n ChildrenNode.prototype.isIndexed = function (index) {\r\n return index === KEY_INDEX || this.indexMap_.hasIndex(index);\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n ChildrenNode.prototype.equals = function (other) {\r\n if (other === this) {\r\n return true;\r\n }\r\n else if (other.isLeafNode()) {\r\n return false;\r\n }\r\n else {\r\n var otherChildrenNode = other;\r\n if (!this.getPriority().equals(otherChildrenNode.getPriority())) {\r\n return false;\r\n }\r\n else if (this.children_.count() === otherChildrenNode.children_.count()) {\r\n var thisIter = this.getIterator(PRIORITY_INDEX);\r\n var otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);\r\n var thisCurrent = thisIter.getNext();\r\n var otherCurrent = otherIter.getNext();\r\n while (thisCurrent && otherCurrent) {\r\n if (thisCurrent.name !== otherCurrent.name ||\r\n !thisCurrent.node.equals(otherCurrent.node)) {\r\n return false;\r\n }\r\n thisCurrent = thisIter.getNext();\r\n otherCurrent = otherIter.getNext();\r\n }\r\n return thisCurrent === null && otherCurrent === null;\r\n }\r\n else {\r\n return false;\r\n }\r\n }\r\n };\r\n /**\r\n * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used\r\n * instead.\r\n *\r\n * @private\r\n * @param {!Index} indexDefinition\r\n * @return {?SortedMap.}\r\n */\r\n ChildrenNode.prototype.resolveIndex_ = function (indexDefinition) {\r\n if (indexDefinition === KEY_INDEX) {\r\n return null;\r\n }\r\n else {\r\n return this.indexMap_.get(indexDefinition.toString());\r\n }\r\n };\r\n /**\r\n * @private\r\n * @type {RegExp}\r\n */\r\n ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\\d*)$/;\r\n return ChildrenNode;\r\n}());\r\n/**\r\n * @constructor\r\n * @extends {ChildrenNode}\r\n * @private\r\n */\r\nvar MaxNode = /** @class */ (function (_super) {\r\n tslib_1.__extends(MaxNode, _super);\r\n function MaxNode() {\r\n return _super.call(this, new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default) || this;\r\n }\r\n MaxNode.prototype.compareTo = function (other) {\r\n if (other === this) {\r\n return 0;\r\n }\r\n else {\r\n return 1;\r\n }\r\n };\r\n MaxNode.prototype.equals = function (other) {\r\n // Not that we every compare it, but MAX_NODE is only ever equal to itself\r\n return other === this;\r\n };\r\n MaxNode.prototype.getPriority = function () {\r\n return this;\r\n };\r\n MaxNode.prototype.getImmediateChild = function (childName) {\r\n return ChildrenNode.EMPTY_NODE;\r\n };\r\n MaxNode.prototype.isEmpty = function () {\r\n return false;\r\n };\r\n return MaxNode;\r\n}(ChildrenNode));\r\n/**\r\n * Marker that will sort higher than any other snapshot.\r\n * @type {!MAX_NODE}\r\n * @const\r\n */\r\nvar MAX_NODE$2 = new MaxNode();\r\nObject.defineProperties(NamedNode, {\r\n MIN: {\r\n value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)\r\n },\r\n MAX: {\r\n value: new NamedNode(MAX_NAME, MAX_NODE$2)\r\n }\r\n});\r\n/**\r\n * Reference Extensions\r\n */\r\nKeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;\r\nLeafNode.__childrenNodeConstructor = ChildrenNode;\r\nsetMaxNode(MAX_NODE$2);\r\nsetMaxNode$1(MAX_NODE$2);\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar USE_HINZE = true;\r\n/**\r\n * Constructs a snapshot node representing the passed JSON and returns it.\r\n * @param {*} json JSON to create a node for.\r\n * @param {?string|?number=} priority Optional priority to use. This will be ignored if the\r\n * passed JSON contains a .priority property.\r\n * @return {!Node}\r\n */\r\nfunction nodeFromJSON$1(json, priority) {\r\n if (priority === void 0) { priority = null; }\r\n if (json === null) {\r\n return ChildrenNode.EMPTY_NODE;\r\n }\r\n if (typeof json === 'object' && '.priority' in json) {\r\n priority = json['.priority'];\r\n }\r\n util.assert(priority === null ||\r\n typeof priority === 'string' ||\r\n typeof priority === 'number' ||\r\n (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);\r\n if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {\r\n json = json['.value'];\r\n }\r\n // Valid leaf nodes include non-objects or server-value wrapper objects\r\n if (typeof json !== 'object' || '.sv' in json) {\r\n var jsonLeaf = json;\r\n return new LeafNode(jsonLeaf, nodeFromJSON$1(priority));\r\n }\r\n if (!(json instanceof Array) && USE_HINZE) {\r\n var children_1 = [];\r\n var childrenHavePriority_1 = false;\r\n var hinzeJsonObj_1 = json;\r\n util.forEach(hinzeJsonObj_1, function (key, child) {\r\n if (typeof key !== 'string' || key.substring(0, 1) !== '.') {\r\n // Ignore metadata nodes\r\n var childNode = nodeFromJSON$1(hinzeJsonObj_1[key]);\r\n if (!childNode.isEmpty()) {\r\n childrenHavePriority_1 =\r\n childrenHavePriority_1 || !childNode.getPriority().isEmpty();\r\n children_1.push(new NamedNode(key, childNode));\r\n }\r\n }\r\n });\r\n if (children_1.length == 0) {\r\n return ChildrenNode.EMPTY_NODE;\r\n }\r\n var childSet = buildChildSet(children_1, NAME_ONLY_COMPARATOR, function (namedNode) { return namedNode.name; }, NAME_COMPARATOR);\r\n if (childrenHavePriority_1) {\r\n var sortedChildSet = buildChildSet(children_1, PRIORITY_INDEX.getCompare());\r\n return new ChildrenNode(childSet, nodeFromJSON$1(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX }));\r\n }\r\n else {\r\n return new ChildrenNode(childSet, nodeFromJSON$1(priority), IndexMap.Default);\r\n }\r\n }\r\n else {\r\n var node_1 = ChildrenNode.EMPTY_NODE;\r\n var jsonObj_1 = json;\r\n util.forEach(jsonObj_1, function (key, childData) {\r\n if (util.contains(jsonObj_1, key)) {\r\n if (key.substring(0, 1) !== '.') {\r\n // ignore metadata nodes.\r\n var childNode = nodeFromJSON$1(childData);\r\n if (childNode.isLeafNode() || !childNode.isEmpty())\r\n node_1 = node_1.updateImmediateChild(key, childNode);\r\n }\r\n }\r\n });\r\n return node_1.updatePriority(nodeFromJSON$1(priority));\r\n }\r\n}\r\nsetNodeFromJSON(nodeFromJSON$1);\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @constructor\r\n * @extends {Index}\r\n * @private\r\n */\r\nvar ValueIndex = /** @class */ (function (_super) {\r\n tslib_1.__extends(ValueIndex, _super);\r\n function ValueIndex() {\r\n return _super !== null && _super.apply(this, arguments) || this;\r\n }\r\n /**\r\n * @inheritDoc\r\n */\r\n ValueIndex.prototype.compare = function (a, b) {\r\n var indexCmp = a.node.compareTo(b.node);\r\n if (indexCmp === 0) {\r\n return nameCompare(a.name, b.name);\r\n }\r\n else {\r\n return indexCmp;\r\n }\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n ValueIndex.prototype.isDefinedOn = function (node) {\r\n return true;\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n ValueIndex.prototype.indexedValueChanged = function (oldNode, newNode) {\r\n return !oldNode.equals(newNode);\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n ValueIndex.prototype.minPost = function () {\r\n return NamedNode.MIN;\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n ValueIndex.prototype.maxPost = function () {\r\n return NamedNode.MAX;\r\n };\r\n /**\r\n * @param {*} indexValue\r\n * @param {string} name\r\n * @return {!NamedNode}\r\n */\r\n ValueIndex.prototype.makePost = function (indexValue, name) {\r\n var valueNode = nodeFromJSON$1(indexValue);\r\n return new NamedNode(name, valueNode);\r\n };\r\n /**\r\n * @return {!string} String representation for inclusion in a query spec\r\n */\r\n ValueIndex.prototype.toString = function () {\r\n return '.value';\r\n };\r\n return ValueIndex;\r\n}(Index));\r\nvar VALUE_INDEX = new ValueIndex();\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @param {!Path} indexPath\r\n * @constructor\r\n * @extends {Index}\r\n */\r\nvar PathIndex = /** @class */ (function (_super) {\r\n tslib_1.__extends(PathIndex, _super);\r\n function PathIndex(indexPath_) {\r\n var _this = _super.call(this) || this;\r\n _this.indexPath_ = indexPath_;\r\n util.assert(!indexPath_.isEmpty() && indexPath_.getFront() !== '.priority', \"Can't create PathIndex with empty path or .priority key\");\r\n return _this;\r\n }\r\n /**\r\n * @param {!Node} snap\r\n * @return {!Node}\r\n * @protected\r\n */\r\n PathIndex.prototype.extractChild = function (snap) {\r\n return snap.getChild(this.indexPath_);\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n PathIndex.prototype.isDefinedOn = function (node) {\r\n return !node.getChild(this.indexPath_).isEmpty();\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n PathIndex.prototype.compare = function (a, b) {\r\n var aChild = this.extractChild(a.node);\r\n var bChild = this.extractChild(b.node);\r\n var indexCmp = aChild.compareTo(bChild);\r\n if (indexCmp === 0) {\r\n return nameCompare(a.name, b.name);\r\n }\r\n else {\r\n return indexCmp;\r\n }\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n PathIndex.prototype.makePost = function (indexValue, name) {\r\n var valueNode = nodeFromJSON$1(indexValue);\r\n var node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);\r\n return new NamedNode(name, node);\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n PathIndex.prototype.maxPost = function () {\r\n var node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE$2);\r\n return new NamedNode(MAX_NAME, node);\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n PathIndex.prototype.toString = function () {\r\n return this.indexPath_.slice().join('/');\r\n };\r\n return PathIndex;\r\n}(Index));\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Class representing a firebase data snapshot. It wraps a SnapshotNode and\r\n * surfaces the public methods (val, forEach, etc.) we want to expose.\r\n */\r\nvar DataSnapshot = /** @class */ (function () {\r\n /**\r\n * @param {!Node} node_ A SnapshotNode to wrap.\r\n * @param {!Reference} ref_ The ref of the location this snapshot came from.\r\n * @param {!Index} index_ The iteration order for this snapshot\r\n */\r\n function DataSnapshot(node_, ref_, index_) {\r\n this.node_ = node_;\r\n this.ref_ = ref_;\r\n this.index_ = index_;\r\n }\r\n /**\r\n * Retrieves the snapshot contents as JSON. Returns null if the snapshot is\r\n * empty.\r\n *\r\n * @return {*} JSON representation of the DataSnapshot contents, or null if empty.\r\n */\r\n DataSnapshot.prototype.val = function () {\r\n util.validateArgCount('DataSnapshot.val', 0, 0, arguments.length);\r\n return this.node_.val();\r\n };\r\n /**\r\n * Returns the snapshot contents as JSON, including priorities of node. Suitable for exporting\r\n * the entire node contents.\r\n * @return {*} JSON representation of the DataSnapshot contents, or null if empty.\r\n */\r\n DataSnapshot.prototype.exportVal = function () {\r\n util.validateArgCount('DataSnapshot.exportVal', 0, 0, arguments.length);\r\n return this.node_.val(true);\r\n };\r\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\r\n // for end-users\r\n DataSnapshot.prototype.toJSON = function () {\r\n // Optional spacer argument is unnecessary because we're depending on recursion rather than stringifying the content\r\n util.validateArgCount('DataSnapshot.toJSON', 0, 1, arguments.length);\r\n return this.exportVal();\r\n };\r\n /**\r\n * Returns whether the snapshot contains a non-null value.\r\n *\r\n * @return {boolean} Whether the snapshot contains a non-null value, or is empty.\r\n */\r\n DataSnapshot.prototype.exists = function () {\r\n util.validateArgCount('DataSnapshot.exists', 0, 0, arguments.length);\r\n return !this.node_.isEmpty();\r\n };\r\n /**\r\n * Returns a DataSnapshot of the specified child node's contents.\r\n *\r\n * @param {!string} childPathString Path to a child.\r\n * @return {!DataSnapshot} DataSnapshot for child node.\r\n */\r\n DataSnapshot.prototype.child = function (childPathString) {\r\n util.validateArgCount('DataSnapshot.child', 0, 1, arguments.length);\r\n // Ensure the childPath is a string (can be a number)\r\n childPathString = String(childPathString);\r\n validatePathString('DataSnapshot.child', 1, childPathString, false);\r\n var childPath = new Path(childPathString);\r\n var childRef = this.ref_.child(childPath);\r\n return new DataSnapshot(this.node_.getChild(childPath), childRef, PRIORITY_INDEX);\r\n };\r\n /**\r\n * Returns whether the snapshot contains a child at the specified path.\r\n *\r\n * @param {!string} childPathString Path to a child.\r\n * @return {boolean} Whether the child exists.\r\n */\r\n DataSnapshot.prototype.hasChild = function (childPathString) {\r\n util.validateArgCount('DataSnapshot.hasChild', 1, 1, arguments.length);\r\n validatePathString('DataSnapshot.hasChild', 1, childPathString, false);\r\n var childPath = new Path(childPathString);\r\n return !this.node_.getChild(childPath).isEmpty();\r\n };\r\n /**\r\n * Returns the priority of the object, or null if no priority was set.\r\n *\r\n * @return {string|number|null} The priority.\r\n */\r\n DataSnapshot.prototype.getPriority = function () {\r\n util.validateArgCount('DataSnapshot.getPriority', 0, 0, arguments.length);\r\n // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)\r\n return this.node_.getPriority().val();\r\n };\r\n /**\r\n * Iterates through child nodes and calls the specified action for each one.\r\n *\r\n * @param {function(!DataSnapshot)} action Callback function to be called\r\n * for each child.\r\n * @return {boolean} True if forEach was canceled by action returning true for\r\n * one of the child nodes.\r\n */\r\n DataSnapshot.prototype.forEach = function (action) {\r\n var _this = this;\r\n util.validateArgCount('DataSnapshot.forEach', 1, 1, arguments.length);\r\n util.validateCallback('DataSnapshot.forEach', 1, action, false);\r\n if (this.node_.isLeafNode())\r\n return false;\r\n var childrenNode = this.node_;\r\n // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...\r\n return !!childrenNode.forEachChild(this.index_, function (key, node) {\r\n return action(new DataSnapshot(node, _this.ref_.child(key), PRIORITY_INDEX));\r\n });\r\n };\r\n /**\r\n * Returns whether this DataSnapshot has children.\r\n * @return {boolean} True if the DataSnapshot contains 1 or more child nodes.\r\n */\r\n DataSnapshot.prototype.hasChildren = function () {\r\n util.validateArgCount('DataSnapshot.hasChildren', 0, 0, arguments.length);\r\n if (this.node_.isLeafNode())\r\n return false;\r\n else\r\n return !this.node_.isEmpty();\r\n };\r\n Object.defineProperty(DataSnapshot.prototype, \"key\", {\r\n get: function () {\r\n return this.ref_.getKey();\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n /**\r\n * Returns the number of children for this DataSnapshot.\r\n * @return {number} The number of children that this DataSnapshot contains.\r\n */\r\n DataSnapshot.prototype.numChildren = function () {\r\n util.validateArgCount('DataSnapshot.numChildren', 0, 0, arguments.length);\r\n return this.node_.numChildren();\r\n };\r\n /**\r\n * @return {Reference} The Firebase reference for the location this snapshot's data came from.\r\n */\r\n DataSnapshot.prototype.getRef = function () {\r\n util.validateArgCount('DataSnapshot.ref', 0, 0, arguments.length);\r\n return this.ref_;\r\n };\r\n Object.defineProperty(DataSnapshot.prototype, \"ref\", {\r\n get: function () {\r\n return this.getRef();\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n return DataSnapshot;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Encapsulates the data needed to raise an event\r\n * @implements {Event}\r\n */\r\nvar DataEvent = /** @class */ (function () {\r\n /**\r\n * @param {!string} eventType One of: value, child_added, child_changed, child_moved, child_removed\r\n * @param {!EventRegistration} eventRegistration The function to call to with the event data. User provided\r\n * @param {!DataSnapshot} snapshot The data backing the event\r\n * @param {?string=} prevName Optional, the name of the previous child for child_* events.\r\n */\r\n function DataEvent(eventType, eventRegistration, snapshot, prevName) {\r\n this.eventType = eventType;\r\n this.eventRegistration = eventRegistration;\r\n this.snapshot = snapshot;\r\n this.prevName = prevName;\r\n }\r\n /**\r\n * @inheritDoc\r\n */\r\n DataEvent.prototype.getPath = function () {\r\n var ref = this.snapshot.getRef();\r\n if (this.eventType === 'value') {\r\n return ref.path;\r\n }\r\n else {\r\n return ref.getParent().path;\r\n }\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n DataEvent.prototype.getEventType = function () {\r\n return this.eventType;\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n DataEvent.prototype.getEventRunner = function () {\r\n return this.eventRegistration.getEventRunner(this);\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n DataEvent.prototype.toString = function () {\r\n return (this.getPath().toString() +\r\n ':' +\r\n this.eventType +\r\n ':' +\r\n util.stringify(this.snapshot.exportVal()));\r\n };\r\n return DataEvent;\r\n}());\r\nvar CancelEvent = /** @class */ (function () {\r\n /**\r\n * @param {EventRegistration} eventRegistration\r\n * @param {Error} error\r\n * @param {!Path} path\r\n */\r\n function CancelEvent(eventRegistration, error, path) {\r\n this.eventRegistration = eventRegistration;\r\n this.error = error;\r\n this.path = path;\r\n }\r\n /**\r\n * @inheritDoc\r\n */\r\n CancelEvent.prototype.getPath = function () {\r\n return this.path;\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n CancelEvent.prototype.getEventType = function () {\r\n return 'cancel';\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n CancelEvent.prototype.getEventRunner = function () {\r\n return this.eventRegistration.getEventRunner(this);\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n CancelEvent.prototype.toString = function () {\r\n return this.path.toString() + ':cancel';\r\n };\r\n return CancelEvent;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Represents registration for 'value' events.\r\n */\r\nvar ValueEventRegistration = /** @class */ (function () {\r\n /**\r\n * @param {?function(!DataSnapshot)} callback_\r\n * @param {?function(Error)} cancelCallback_\r\n * @param {?Object} context_\r\n */\r\n function ValueEventRegistration(callback_, cancelCallback_, context_) {\r\n this.callback_ = callback_;\r\n this.cancelCallback_ = cancelCallback_;\r\n this.context_ = context_;\r\n }\r\n /**\r\n * @inheritDoc\r\n */\r\n ValueEventRegistration.prototype.respondsTo = function (eventType) {\r\n return eventType === 'value';\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n ValueEventRegistration.prototype.createEvent = function (change, query) {\r\n var index = query.getQueryParams().getIndex();\r\n return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, query.getRef(), index));\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n ValueEventRegistration.prototype.getEventRunner = function (eventData) {\r\n var ctx = this.context_;\r\n if (eventData.getEventType() === 'cancel') {\r\n util.assert(this.cancelCallback_, 'Raising a cancel event on a listener with no cancel callback');\r\n var cancelCB_1 = this.cancelCallback_;\r\n return function () {\r\n // We know that error exists, we checked above that this is a cancel event\r\n cancelCB_1.call(ctx, eventData.error);\r\n };\r\n }\r\n else {\r\n var cb_1 = this.callback_;\r\n return function () {\r\n cb_1.call(ctx, eventData.snapshot);\r\n };\r\n }\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n ValueEventRegistration.prototype.createCancelEvent = function (error, path) {\r\n if (this.cancelCallback_) {\r\n return new CancelEvent(this, error, path);\r\n }\r\n else {\r\n return null;\r\n }\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n ValueEventRegistration.prototype.matches = function (other) {\r\n if (!(other instanceof ValueEventRegistration)) {\r\n return false;\r\n }\r\n else if (!other.callback_ || !this.callback_) {\r\n // If no callback specified, we consider it to match any callback.\r\n return true;\r\n }\r\n else {\r\n return (other.callback_ === this.callback_ && other.context_ === this.context_);\r\n }\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n ValueEventRegistration.prototype.hasAnyCallback = function () {\r\n return this.callback_ !== null;\r\n };\r\n return ValueEventRegistration;\r\n}());\r\n/**\r\n * Represents the registration of 1 or more child_xxx events.\r\n *\r\n * Currently, it is always exactly 1 child_xxx event, but the idea is we might let you\r\n * register a group of callbacks together in the future.\r\n *\r\n * @constructor\r\n * @implements {EventRegistration}\r\n */\r\nvar ChildEventRegistration = /** @class */ (function () {\r\n /**\r\n * @param {?Object.} callbacks_\r\n * @param {?function(Error)} cancelCallback_\r\n * @param {Object=} context_\r\n */\r\n function ChildEventRegistration(callbacks_, cancelCallback_, context_) {\r\n this.callbacks_ = callbacks_;\r\n this.cancelCallback_ = cancelCallback_;\r\n this.context_ = context_;\r\n }\r\n /**\r\n * @inheritDoc\r\n */\r\n ChildEventRegistration.prototype.respondsTo = function (eventType) {\r\n var eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;\r\n eventToCheck =\r\n eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;\r\n return util.contains(this.callbacks_, eventToCheck);\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n ChildEventRegistration.prototype.createCancelEvent = function (error, path) {\r\n if (this.cancelCallback_) {\r\n return new CancelEvent(this, error, path);\r\n }\r\n else {\r\n return null;\r\n }\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n ChildEventRegistration.prototype.createEvent = function (change, query) {\r\n util.assert(change.childName != null, 'Child events should have a childName.');\r\n var ref = query.getRef().child(/** @type {!string} */ (change.childName));\r\n var index = query.getQueryParams().getIndex();\r\n return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, ref, index), change.prevName);\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n ChildEventRegistration.prototype.getEventRunner = function (eventData) {\r\n var ctx = this.context_;\r\n if (eventData.getEventType() === 'cancel') {\r\n util.assert(this.cancelCallback_, 'Raising a cancel event on a listener with no cancel callback');\r\n var cancelCB_2 = this.cancelCallback_;\r\n return function () {\r\n // We know that error exists, we checked above that this is a cancel event\r\n cancelCB_2.call(ctx, eventData.error);\r\n };\r\n }\r\n else {\r\n var cb_2 = this.callbacks_[eventData.eventType];\r\n return function () {\r\n cb_2.call(ctx, eventData.snapshot, eventData.prevName);\r\n };\r\n }\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n ChildEventRegistration.prototype.matches = function (other) {\r\n if (other instanceof ChildEventRegistration) {\r\n if (!this.callbacks_ || !other.callbacks_) {\r\n return true;\r\n }\r\n else if (this.context_ === other.context_) {\r\n var otherCount = util.getCount(other.callbacks_);\r\n var thisCount = util.getCount(this.callbacks_);\r\n if (otherCount === thisCount) {\r\n // If count is 1, do an exact match on eventType, if either is defined but null, it's a match.\r\n // If event types don't match, not a match\r\n // If count is not 1, exact match across all\r\n if (otherCount === 1) {\r\n var otherKey /** @type {!string} */ = util.getAnyKey(other.callbacks_);\r\n var thisKey /** @type {!string} */ = util.getAnyKey(this.callbacks_);\r\n return (thisKey === otherKey &&\r\n (!other.callbacks_[otherKey] ||\r\n !this.callbacks_[thisKey] ||\r\n other.callbacks_[otherKey] === this.callbacks_[thisKey]));\r\n }\r\n else {\r\n // Exact match on each key.\r\n return util.every(this.callbacks_, function (eventType, cb) { return other.callbacks_[eventType] === cb; });\r\n }\r\n }\r\n }\r\n }\r\n return false;\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n ChildEventRegistration.prototype.hasAnyCallback = function () {\r\n return this.callbacks_ !== null;\r\n };\r\n return ChildEventRegistration;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar __referenceConstructor;\r\n/**\r\n * A Query represents a filter to be applied to a firebase location. This object purely represents the\r\n * query expression (and exposes our public API to build the query). The actual query logic is in ViewBase.js.\r\n *\r\n * Since every Firebase reference is a query, Firebase inherits from this object.\r\n */\r\nvar Query = /** @class */ (function () {\r\n function Query(repo, path, queryParams_, orderByCalled_) {\r\n this.repo = repo;\r\n this.path = path;\r\n this.queryParams_ = queryParams_;\r\n this.orderByCalled_ = orderByCalled_;\r\n }\r\n Object.defineProperty(Query, \"__referenceConstructor\", {\r\n get: function () {\r\n util.assert(__referenceConstructor, 'Reference.ts has not been loaded');\r\n return __referenceConstructor;\r\n },\r\n set: function (val) {\r\n __referenceConstructor = val;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n /**\r\n * Validates start/end values for queries.\r\n * @param {!QueryParams} params\r\n * @private\r\n */\r\n Query.validateQueryEndpoints_ = function (params) {\r\n var startNode = null;\r\n var endNode = null;\r\n if (params.hasStart()) {\r\n startNode = params.getIndexStartValue();\r\n }\r\n if (params.hasEnd()) {\r\n endNode = params.getIndexEndValue();\r\n }\r\n if (params.getIndex() === KEY_INDEX) {\r\n var tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +\r\n 'startAt(), endAt(), or equalTo().';\r\n var wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), endAt(),' +\r\n 'or equalTo() must be a string.';\r\n if (params.hasStart()) {\r\n var startName = params.getIndexStartName();\r\n if (startName != MIN_NAME) {\r\n throw new Error(tooManyArgsError);\r\n }\r\n else if (typeof startNode !== 'string') {\r\n throw new Error(wrongArgTypeError);\r\n }\r\n }\r\n if (params.hasEnd()) {\r\n var endName = params.getIndexEndName();\r\n if (endName != MAX_NAME) {\r\n throw new Error(tooManyArgsError);\r\n }\r\n else if (typeof endNode !== 'string') {\r\n throw new Error(wrongArgTypeError);\r\n }\r\n }\r\n }\r\n else if (params.getIndex() === PRIORITY_INDEX) {\r\n if ((startNode != null && !isValidPriority(startNode)) ||\r\n (endNode != null && !isValidPriority(endNode))) {\r\n throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +\r\n 'endAt(), or equalTo() must be a valid priority value (null, a number, or a string).');\r\n }\r\n }\r\n else {\r\n util.assert(params.getIndex() instanceof PathIndex ||\r\n params.getIndex() === VALUE_INDEX, 'unknown index type.');\r\n if ((startNode != null && typeof startNode === 'object') ||\r\n (endNode != null && typeof endNode === 'object')) {\r\n throw new Error('Query: First argument passed to startAt(), endAt(), or equalTo() cannot be ' +\r\n 'an object.');\r\n }\r\n }\r\n };\r\n /**\r\n * Validates that limit* has been called with the correct combination of parameters\r\n * @param {!QueryParams} params\r\n * @private\r\n */\r\n Query.validateLimit_ = function (params) {\r\n if (params.hasStart() &&\r\n params.hasEnd() &&\r\n params.hasLimit() &&\r\n !params.hasAnchoredLimit()) {\r\n throw new Error(\"Query: Can't combine startAt(), endAt(), and limit(). Use limitToFirst() or limitToLast() instead.\");\r\n }\r\n };\r\n /**\r\n * Validates that no other order by call has been made\r\n * @param {!string} fnName\r\n * @private\r\n */\r\n Query.prototype.validateNoPreviousOrderByCall_ = function (fnName) {\r\n if (this.orderByCalled_ === true) {\r\n throw new Error(fnName + \": You can't combine multiple orderBy calls.\");\r\n }\r\n };\r\n /**\r\n * @return {!QueryParams}\r\n */\r\n Query.prototype.getQueryParams = function () {\r\n return this.queryParams_;\r\n };\r\n /**\r\n * @return {!Reference}\r\n */\r\n Query.prototype.getRef = function () {\r\n util.validateArgCount('Query.ref', 0, 0, arguments.length);\r\n // This is a slight hack. We cannot goog.require('fb.api.Firebase'), since Firebase requires fb.api.Query.\r\n // However, we will always export 'Firebase' to the global namespace, so it's guaranteed to exist by the time this\r\n // method gets called.\r\n return new Query.__referenceConstructor(this.repo, this.path);\r\n };\r\n /**\r\n * @param {!string} eventType\r\n * @param {!function(DataSnapshot, string=)} callback\r\n * @param {(function(Error)|Object)=} cancelCallbackOrContext\r\n * @param {Object=} context\r\n * @return {!function(DataSnapshot, string=)}\r\n */\r\n Query.prototype.on = function (eventType, callback, cancelCallbackOrContext, context) {\r\n util.validateArgCount('Query.on', 2, 4, arguments.length);\r\n validateEventType('Query.on', 1, eventType, false);\r\n util.validateCallback('Query.on', 2, callback, false);\r\n var ret = Query.getCancelAndContextArgs_('Query.on', cancelCallbackOrContext, context);\r\n if (eventType === 'value') {\r\n this.onValueEvent(callback, ret.cancel, ret.context);\r\n }\r\n else {\r\n var callbacks = {};\r\n callbacks[eventType] = callback;\r\n this.onChildEvent(callbacks, ret.cancel, ret.context);\r\n }\r\n return callback;\r\n };\r\n /**\r\n * @param {!function(!DataSnapshot)} callback\r\n * @param {?function(Error)} cancelCallback\r\n * @param {?Object} context\r\n * @protected\r\n */\r\n Query.prototype.onValueEvent = function (callback, cancelCallback, context) {\r\n var container = new ValueEventRegistration(callback, cancelCallback || null, context || null);\r\n this.repo.addEventCallbackForQuery(this, container);\r\n };\r\n /**\r\n * @param {!Object.} callbacks\r\n * @param {?function(Error)} cancelCallback\r\n * @param {?Object} context\r\n * @protected\r\n */\r\n Query.prototype.onChildEvent = function (callbacks, cancelCallback, context) {\r\n var container = new ChildEventRegistration(callbacks, cancelCallback, context);\r\n this.repo.addEventCallbackForQuery(this, container);\r\n };\r\n /**\r\n * @param {string=} eventType\r\n * @param {(function(!DataSnapshot, ?string=))=} callback\r\n * @param {Object=} context\r\n */\r\n Query.prototype.off = function (eventType, callback, context) {\r\n util.validateArgCount('Query.off', 0, 3, arguments.length);\r\n validateEventType('Query.off', 1, eventType, true);\r\n util.validateCallback('Query.off', 2, callback, true);\r\n util.validateContextObject('Query.off', 3, context, true);\r\n var container = null;\r\n var callbacks = null;\r\n if (eventType === 'value') {\r\n var valueCallback = callback || null;\r\n container = new ValueEventRegistration(valueCallback, null, context || null);\r\n }\r\n else if (eventType) {\r\n if (callback) {\r\n callbacks = {};\r\n callbacks[eventType] = callback;\r\n }\r\n container = new ChildEventRegistration(callbacks, null, context || null);\r\n }\r\n this.repo.removeEventCallbackForQuery(this, container);\r\n };\r\n /**\r\n * Attaches a listener, waits for the first event, and then removes the listener\r\n * @param {!string} eventType\r\n * @param {!function(!DataSnapshot, string=)} userCallback\r\n * @param cancelOrContext\r\n * @param context\r\n * @return {!firebase.Promise}\r\n */\r\n Query.prototype.once = function (eventType, userCallback, cancelOrContext, context) {\r\n var _this = this;\r\n util.validateArgCount('Query.once', 1, 4, arguments.length);\r\n validateEventType('Query.once', 1, eventType, false);\r\n util.validateCallback('Query.once', 2, userCallback, true);\r\n var ret = Query.getCancelAndContextArgs_('Query.once', cancelOrContext, context);\r\n // TODO: Implement this more efficiently (in particular, use 'get' wire protocol for 'value' event)\r\n // TODO: consider actually wiring the callbacks into the promise. We cannot do this without a breaking change\r\n // because the API currently expects callbacks will be called synchronously if the data is cached, but this is\r\n // against the Promise specification.\r\n var firstCall = true;\r\n var deferred = new util.Deferred();\r\n // A dummy error handler in case a user wasn't expecting promises\r\n deferred.promise.catch(function () { });\r\n var onceCallback = function (snapshot) {\r\n // NOTE: Even though we unsubscribe, we may get called multiple times if a single action (e.g. set() with JSON)\r\n // triggers multiple events (e.g. child_added or child_changed).\r\n if (firstCall) {\r\n firstCall = false;\r\n _this.off(eventType, onceCallback);\r\n if (userCallback) {\r\n userCallback.bind(ret.context)(snapshot);\r\n }\r\n deferred.resolve(snapshot);\r\n }\r\n };\r\n this.on(eventType, onceCallback, \r\n /*cancel=*/ function (err) {\r\n _this.off(eventType, onceCallback);\r\n if (ret.cancel)\r\n ret.cancel.bind(ret.context)(err);\r\n deferred.reject(err);\r\n });\r\n return deferred.promise;\r\n };\r\n /**\r\n * Set a limit and anchor it to the start of the window.\r\n * @param {!number} limit\r\n * @return {!Query}\r\n */\r\n Query.prototype.limitToFirst = function (limit) {\r\n util.validateArgCount('Query.limitToFirst', 1, 1, arguments.length);\r\n if (typeof limit !== 'number' ||\r\n Math.floor(limit) !== limit ||\r\n limit <= 0) {\r\n throw new Error('Query.limitToFirst: First argument must be a positive integer.');\r\n }\r\n if (this.queryParams_.hasLimit()) {\r\n throw new Error('Query.limitToFirst: Limit was already set (by another call to limit, ' +\r\n 'limitToFirst, or limitToLast).');\r\n }\r\n return new Query(this.repo, this.path, this.queryParams_.limitToFirst(limit), this.orderByCalled_);\r\n };\r\n /**\r\n * Set a limit and anchor it to the end of the window.\r\n * @param {!number} limit\r\n * @return {!Query}\r\n */\r\n Query.prototype.limitToLast = function (limit) {\r\n util.validateArgCount('Query.limitToLast', 1, 1, arguments.length);\r\n if (typeof limit !== 'number' ||\r\n Math.floor(limit) !== limit ||\r\n limit <= 0) {\r\n throw new Error('Query.limitToLast: First argument must be a positive integer.');\r\n }\r\n if (this.queryParams_.hasLimit()) {\r\n throw new Error('Query.limitToLast: Limit was already set (by another call to limit, ' +\r\n 'limitToFirst, or limitToLast).');\r\n }\r\n return new Query(this.repo, this.path, this.queryParams_.limitToLast(limit), this.orderByCalled_);\r\n };\r\n /**\r\n * Given a child path, return a new query ordered by the specified grandchild path.\r\n * @param {!string} path\r\n * @return {!Query}\r\n */\r\n Query.prototype.orderByChild = function (path) {\r\n util.validateArgCount('Query.orderByChild', 1, 1, arguments.length);\r\n if (path === '$key') {\r\n throw new Error('Query.orderByChild: \"$key\" is invalid. Use Query.orderByKey() instead.');\r\n }\r\n else if (path === '$priority') {\r\n throw new Error('Query.orderByChild: \"$priority\" is invalid. Use Query.orderByPriority() instead.');\r\n }\r\n else if (path === '$value') {\r\n throw new Error('Query.orderByChild: \"$value\" is invalid. Use Query.orderByValue() instead.');\r\n }\r\n validatePathString('Query.orderByChild', 1, path, false);\r\n this.validateNoPreviousOrderByCall_('Query.orderByChild');\r\n var parsedPath = new Path(path);\r\n if (parsedPath.isEmpty()) {\r\n throw new Error('Query.orderByChild: cannot pass in empty path. Use Query.orderByValue() instead.');\r\n }\r\n var index = new PathIndex(parsedPath);\r\n var newParams = this.queryParams_.orderBy(index);\r\n Query.validateQueryEndpoints_(newParams);\r\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\r\n };\r\n /**\r\n * Return a new query ordered by the KeyIndex\r\n * @return {!Query}\r\n */\r\n Query.prototype.orderByKey = function () {\r\n util.validateArgCount('Query.orderByKey', 0, 0, arguments.length);\r\n this.validateNoPreviousOrderByCall_('Query.orderByKey');\r\n var newParams = this.queryParams_.orderBy(KEY_INDEX);\r\n Query.validateQueryEndpoints_(newParams);\r\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\r\n };\r\n /**\r\n * Return a new query ordered by the PriorityIndex\r\n * @return {!Query}\r\n */\r\n Query.prototype.orderByPriority = function () {\r\n util.validateArgCount('Query.orderByPriority', 0, 0, arguments.length);\r\n this.validateNoPreviousOrderByCall_('Query.orderByPriority');\r\n var newParams = this.queryParams_.orderBy(PRIORITY_INDEX);\r\n Query.validateQueryEndpoints_(newParams);\r\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\r\n };\r\n /**\r\n * Return a new query ordered by the ValueIndex\r\n * @return {!Query}\r\n */\r\n Query.prototype.orderByValue = function () {\r\n util.validateArgCount('Query.orderByValue', 0, 0, arguments.length);\r\n this.validateNoPreviousOrderByCall_('Query.orderByValue');\r\n var newParams = this.queryParams_.orderBy(VALUE_INDEX);\r\n Query.validateQueryEndpoints_(newParams);\r\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\r\n };\r\n /**\r\n * @param {number|string|boolean|null} value\r\n * @param {?string=} name\r\n * @return {!Query}\r\n */\r\n Query.prototype.startAt = function (value, name) {\r\n if (value === void 0) { value = null; }\r\n util.validateArgCount('Query.startAt', 0, 2, arguments.length);\r\n validateFirebaseDataArg('Query.startAt', 1, value, this.path, true);\r\n validateKey('Query.startAt', 2, name, true);\r\n var newParams = this.queryParams_.startAt(value, name);\r\n Query.validateLimit_(newParams);\r\n Query.validateQueryEndpoints_(newParams);\r\n if (this.queryParams_.hasStart()) {\r\n throw new Error('Query.startAt: Starting point was already set (by another call to startAt ' +\r\n 'or equalTo).');\r\n }\r\n // Calling with no params tells us to start at the beginning.\r\n if (value === undefined) {\r\n value = null;\r\n name = null;\r\n }\r\n return new Query(this.repo, this.path, newParams, this.orderByCalled_);\r\n };\r\n /**\r\n * @param {number|string|boolean|null} value\r\n * @param {?string=} name\r\n * @return {!Query}\r\n */\r\n Query.prototype.endAt = function (value, name) {\r\n if (value === void 0) { value = null; }\r\n util.validateArgCount('Query.endAt', 0, 2, arguments.length);\r\n validateFirebaseDataArg('Query.endAt', 1, value, this.path, true);\r\n validateKey('Query.endAt', 2, name, true);\r\n var newParams = this.queryParams_.endAt(value, name);\r\n Query.validateLimit_(newParams);\r\n Query.validateQueryEndpoints_(newParams);\r\n if (this.queryParams_.hasEnd()) {\r\n throw new Error('Query.endAt: Ending point was already set (by another call to endAt or ' +\r\n 'equalTo).');\r\n }\r\n return new Query(this.repo, this.path, newParams, this.orderByCalled_);\r\n };\r\n /**\r\n * Load the selection of children with exactly the specified value, and, optionally,\r\n * the specified name.\r\n * @param {number|string|boolean|null} value\r\n * @param {string=} name\r\n * @return {!Query}\r\n */\r\n Query.prototype.equalTo = function (value, name) {\r\n util.validateArgCount('Query.equalTo', 1, 2, arguments.length);\r\n validateFirebaseDataArg('Query.equalTo', 1, value, this.path, false);\r\n validateKey('Query.equalTo', 2, name, true);\r\n if (this.queryParams_.hasStart()) {\r\n throw new Error('Query.equalTo: Starting point was already set (by another call to startAt or ' +\r\n 'equalTo).');\r\n }\r\n if (this.queryParams_.hasEnd()) {\r\n throw new Error('Query.equalTo: Ending point was already set (by another call to endAt or ' +\r\n 'equalTo).');\r\n }\r\n return this.startAt(value, name).endAt(value, name);\r\n };\r\n /**\r\n * @return {!string} URL for this location.\r\n */\r\n Query.prototype.toString = function () {\r\n util.validateArgCount('Query.toString', 0, 0, arguments.length);\r\n return this.repo.toString() + this.path.toUrlEncodedString();\r\n };\r\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\r\n // for end-users.\r\n Query.prototype.toJSON = function () {\r\n // An optional spacer argument is unnecessary for a string.\r\n util.validateArgCount('Query.toJSON', 0, 1, arguments.length);\r\n return this.toString();\r\n };\r\n /**\r\n * An object representation of the query parameters used by this Query.\r\n * @return {!Object}\r\n */\r\n Query.prototype.queryObject = function () {\r\n return this.queryParams_.getQueryObject();\r\n };\r\n /**\r\n * @return {!string}\r\n */\r\n Query.prototype.queryIdentifier = function () {\r\n var obj = this.queryObject();\r\n var id = ObjectToUniqueKey(obj);\r\n return id === '{}' ? 'default' : id;\r\n };\r\n /**\r\n * Return true if this query and the provided query are equivalent; otherwise, return false.\r\n * @param {Query} other\r\n * @return {boolean}\r\n */\r\n Query.prototype.isEqual = function (other) {\r\n util.validateArgCount('Query.isEqual', 1, 1, arguments.length);\r\n if (!(other instanceof Query)) {\r\n var error = 'Query.isEqual failed: First argument must be an instance of firebase.database.Query.';\r\n throw new Error(error);\r\n }\r\n var sameRepo = this.repo === other.repo;\r\n var samePath = this.path.equals(other.path);\r\n var sameQueryIdentifier = this.queryIdentifier() === other.queryIdentifier();\r\n return sameRepo && samePath && sameQueryIdentifier;\r\n };\r\n /**\r\n * Helper used by .on and .once to extract the context and or cancel arguments.\r\n * @param {!string} fnName The function name (on or once)\r\n * @param {(function(Error)|Object)=} cancelOrContext\r\n * @param {Object=} context\r\n * @return {{cancel: ?function(Error), context: ?Object}}\r\n * @private\r\n */\r\n Query.getCancelAndContextArgs_ = function (fnName, cancelOrContext, context) {\r\n var ret = { cancel: null, context: null };\r\n if (cancelOrContext && context) {\r\n ret.cancel = cancelOrContext;\r\n util.validateCallback(fnName, 3, ret.cancel, true);\r\n ret.context = context;\r\n util.validateContextObject(fnName, 4, ret.context, true);\r\n }\r\n else if (cancelOrContext) {\r\n // we have either a cancel callback or a context.\r\n if (typeof cancelOrContext === 'object' && cancelOrContext !== null) {\r\n // it's a context!\r\n ret.context = cancelOrContext;\r\n }\r\n else if (typeof cancelOrContext === 'function') {\r\n ret.cancel = cancelOrContext;\r\n }\r\n else {\r\n throw new Error(util.errorPrefix(fnName, 3, true) +\r\n ' must either be a cancel callback or a context object.');\r\n }\r\n }\r\n return ret;\r\n };\r\n Object.defineProperty(Query.prototype, \"ref\", {\r\n get: function () {\r\n return this.getRef();\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n return Query;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Implements a set with a count of elements.\r\n *\r\n * @template K, V\r\n */\r\nvar CountedSet = /** @class */ (function () {\r\n function CountedSet() {\r\n this.set = {};\r\n }\r\n /**\r\n * @param {!K} item\r\n * @param {V} val\r\n */\r\n CountedSet.prototype.add = function (item, val) {\r\n this.set[item] = val !== null ? val : true;\r\n };\r\n /**\r\n * @param {!K} key\r\n * @return {boolean}\r\n */\r\n CountedSet.prototype.contains = function (key) {\r\n return util.contains(this.set, key);\r\n };\r\n /**\r\n * @param {!K} item\r\n * @return {V}\r\n */\r\n CountedSet.prototype.get = function (item) {\r\n return this.contains(item) ? this.set[item] : undefined;\r\n };\r\n /**\r\n * @param {!K} item\r\n */\r\n CountedSet.prototype.remove = function (item) {\r\n delete this.set[item];\r\n };\r\n /**\r\n * Deletes everything in the set\r\n */\r\n CountedSet.prototype.clear = function () {\r\n this.set = {};\r\n };\r\n /**\r\n * True if there's nothing in the set\r\n * @return {boolean}\r\n */\r\n CountedSet.prototype.isEmpty = function () {\r\n return util.isEmpty(this.set);\r\n };\r\n /**\r\n * @return {number} The number of items in the set\r\n */\r\n CountedSet.prototype.count = function () {\r\n return util.getCount(this.set);\r\n };\r\n /**\r\n * Run a function on each k,v pair in the set\r\n * @param {function(K, V)} fn\r\n */\r\n CountedSet.prototype.each = function (fn) {\r\n util.forEach(this.set, function (k, v) { return fn(k, v); });\r\n };\r\n /**\r\n * Mostly for debugging\r\n * @return {Array.} The keys present in this CountedSet\r\n */\r\n CountedSet.prototype.keys = function () {\r\n var keys = [];\r\n util.forEach(this.set, function (k) {\r\n keys.push(k);\r\n });\r\n return keys;\r\n };\r\n return CountedSet;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Helper class to store a sparse set of snapshots.\r\n *\r\n * @constructor\r\n */\r\nvar SparseSnapshotTree = /** @class */ (function () {\r\n function SparseSnapshotTree() {\r\n /**\r\n * @private\r\n * @type {Node}\r\n */\r\n this.value_ = null;\r\n /**\r\n * @private\r\n * @type {CountedSet}\r\n */\r\n this.children_ = null;\r\n }\r\n /**\r\n * Gets the node stored at the given path if one exists.\r\n *\r\n * @param {!Path} path Path to look up snapshot for.\r\n * @return {?Node} The retrieved node, or null.\r\n */\r\n SparseSnapshotTree.prototype.find = function (path) {\r\n if (this.value_ != null) {\r\n return this.value_.getChild(path);\r\n }\r\n else if (!path.isEmpty() && this.children_ != null) {\r\n var childKey = path.getFront();\r\n path = path.popFront();\r\n if (this.children_.contains(childKey)) {\r\n var childTree = this.children_.get(childKey);\r\n return childTree.find(path);\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n else {\r\n return null;\r\n }\r\n };\r\n /**\r\n * Stores the given node at the specified path. If there is already a node\r\n * at a shallower path, it merges the new data into that snapshot node.\r\n *\r\n * @param {!Path} path Path to look up snapshot for.\r\n * @param {!Node} data The new data, or null.\r\n */\r\n SparseSnapshotTree.prototype.remember = function (path, data) {\r\n if (path.isEmpty()) {\r\n this.value_ = data;\r\n this.children_ = null;\r\n }\r\n else if (this.value_ !== null) {\r\n this.value_ = this.value_.updateChild(path, data);\r\n }\r\n else {\r\n if (this.children_ == null) {\r\n this.children_ = new CountedSet();\r\n }\r\n var childKey = path.getFront();\r\n if (!this.children_.contains(childKey)) {\r\n this.children_.add(childKey, new SparseSnapshotTree());\r\n }\r\n var child = this.children_.get(childKey);\r\n path = path.popFront();\r\n child.remember(path, data);\r\n }\r\n };\r\n /**\r\n * Purge the data at path from the cache.\r\n *\r\n * @param {!Path} path Path to look up snapshot for.\r\n * @return {boolean} True if this node should now be removed.\r\n */\r\n SparseSnapshotTree.prototype.forget = function (path) {\r\n if (path.isEmpty()) {\r\n this.value_ = null;\r\n this.children_ = null;\r\n return true;\r\n }\r\n else {\r\n if (this.value_ !== null) {\r\n if (this.value_.isLeafNode()) {\r\n // We're trying to forget a node that doesn't exist\r\n return false;\r\n }\r\n else {\r\n var value = this.value_;\r\n this.value_ = null;\r\n var self_1 = this;\r\n value.forEachChild(PRIORITY_INDEX, function (key, tree) {\r\n self_1.remember(new Path(key), tree);\r\n });\r\n return this.forget(path);\r\n }\r\n }\r\n else if (this.children_ !== null) {\r\n var childKey = path.getFront();\r\n path = path.popFront();\r\n if (this.children_.contains(childKey)) {\r\n var safeToRemove = this.children_.get(childKey).forget(path);\r\n if (safeToRemove) {\r\n this.children_.remove(childKey);\r\n }\r\n }\r\n if (this.children_.isEmpty()) {\r\n this.children_ = null;\r\n return true;\r\n }\r\n else {\r\n return false;\r\n }\r\n }\r\n else {\r\n return true;\r\n }\r\n }\r\n };\r\n /**\r\n * Recursively iterates through all of the stored tree and calls the\r\n * callback on each one.\r\n *\r\n * @param {!Path} prefixPath Path to look up node for.\r\n * @param {!Function} func The function to invoke for each tree.\r\n */\r\n SparseSnapshotTree.prototype.forEachTree = function (prefixPath, func) {\r\n if (this.value_ !== null) {\r\n func(prefixPath, this.value_);\r\n }\r\n else {\r\n this.forEachChild(function (key, tree) {\r\n var path = new Path(prefixPath.toString() + '/' + key);\r\n tree.forEachTree(path, func);\r\n });\r\n }\r\n };\r\n /**\r\n * Iterates through each immediate child and triggers the callback.\r\n *\r\n * @param {!Function} func The function to invoke for each child.\r\n */\r\n SparseSnapshotTree.prototype.forEachChild = function (func) {\r\n if (this.children_ !== null) {\r\n this.children_.each(function (key, tree) {\r\n func(key, tree);\r\n });\r\n }\r\n };\r\n return SparseSnapshotTree;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Generate placeholders for deferred values.\r\n * @param {?Object} values\r\n * @return {!Object}\r\n */\r\nvar generateWithValues = function (values) {\r\n values = values || {};\r\n values['timestamp'] = values['timestamp'] || new Date().getTime();\r\n return values;\r\n};\r\n/**\r\n * Value to use when firing local events. When writing server values, fire\r\n * local events with an approximate value, otherwise return value as-is.\r\n * @param {(Object|string|number|boolean)} value\r\n * @param {!Object} serverValues\r\n * @return {!(string|number|boolean)}\r\n */\r\nvar resolveDeferredValue = function (value, serverValues) {\r\n if (!value || typeof value !== 'object') {\r\n return value;\r\n }\r\n else {\r\n util.assert('.sv' in value, 'Unexpected leaf node or priority contents');\r\n return serverValues[value['.sv']];\r\n }\r\n};\r\n/**\r\n * Recursively replace all deferred values and priorities in the tree with the\r\n * specified generated replacement values.\r\n * @param {!SparseSnapshotTree} tree\r\n * @param {!Object} serverValues\r\n * @return {!SparseSnapshotTree}\r\n */\r\nvar resolveDeferredValueTree = function (tree, serverValues) {\r\n var resolvedTree = new SparseSnapshotTree();\r\n tree.forEachTree(new Path(''), function (path, node) {\r\n resolvedTree.remember(path, resolveDeferredValueSnapshot(node, serverValues));\r\n });\r\n return resolvedTree;\r\n};\r\n/**\r\n * Recursively replace all deferred values and priorities in the node with the\r\n * specified generated replacement values. If there are no server values in the node,\r\n * it'll be returned as-is.\r\n * @param {!Node} node\r\n * @param {!Object} serverValues\r\n * @return {!Node}\r\n */\r\nvar resolveDeferredValueSnapshot = function (node, serverValues) {\r\n var rawPri = node.getPriority().val();\r\n var priority = resolveDeferredValue(rawPri, serverValues);\r\n var newNode;\r\n if (node.isLeafNode()) {\r\n var leafNode = node;\r\n var value = resolveDeferredValue(leafNode.getValue(), serverValues);\r\n if (value !== leafNode.getValue() ||\r\n priority !== leafNode.getPriority().val()) {\r\n return new LeafNode(value, nodeFromJSON$1(priority));\r\n }\r\n else {\r\n return node;\r\n }\r\n }\r\n else {\r\n var childrenNode = node;\r\n newNode = childrenNode;\r\n if (priority !== childrenNode.getPriority().val()) {\r\n newNode = newNode.updatePriority(new LeafNode(priority));\r\n }\r\n childrenNode.forEachChild(PRIORITY_INDEX, function (childName, childNode) {\r\n var newChildNode = resolveDeferredValueSnapshot(childNode, serverValues);\r\n if (newChildNode !== childNode) {\r\n newNode = newNode.updateImmediateChild(childName, newChildNode);\r\n }\r\n });\r\n return newNode;\r\n }\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n *\r\n * @enum\r\n */\r\nvar OperationType;\r\n(function (OperationType) {\r\n OperationType[OperationType[\"OVERWRITE\"] = 0] = \"OVERWRITE\";\r\n OperationType[OperationType[\"MERGE\"] = 1] = \"MERGE\";\r\n OperationType[OperationType[\"ACK_USER_WRITE\"] = 2] = \"ACK_USER_WRITE\";\r\n OperationType[OperationType[\"LISTEN_COMPLETE\"] = 3] = \"LISTEN_COMPLETE\";\r\n})(OperationType || (OperationType = {}));\r\n/**\r\n * @param {boolean} fromUser\r\n * @param {boolean} fromServer\r\n * @param {?string} queryId\r\n * @param {boolean} tagged\r\n * @constructor\r\n */\r\nvar OperationSource = /** @class */ (function () {\r\n function OperationSource(fromUser, fromServer, queryId, tagged) {\r\n this.fromUser = fromUser;\r\n this.fromServer = fromServer;\r\n this.queryId = queryId;\r\n this.tagged = tagged;\r\n util.assert(!tagged || fromServer, 'Tagged queries must be from server.');\r\n }\r\n /**\r\n * @const\r\n * @type {!OperationSource}\r\n */\r\n OperationSource.User = new OperationSource(\r\n /*fromUser=*/ true, false, null, \r\n /*tagged=*/ false);\r\n /**\r\n * @const\r\n * @type {!OperationSource}\r\n */\r\n OperationSource.Server = new OperationSource(false, \r\n /*fromServer=*/ true, null, \r\n /*tagged=*/ false);\r\n /**\r\n * @param {string} queryId\r\n * @return {!OperationSource}\r\n */\r\n OperationSource.forServerTaggedQuery = function (queryId) {\r\n return new OperationSource(false, \r\n /*fromServer=*/ true, queryId, \r\n /*tagged=*/ true);\r\n };\r\n return OperationSource;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar AckUserWrite = /** @class */ (function () {\r\n /**\r\n *\r\n * @param {!Path} path\r\n * @param {!ImmutableTree} affectedTree A tree containing true for each affected path. Affected paths can't overlap.\r\n * @param {!boolean} revert\r\n */\r\n function AckUserWrite(\r\n /**@inheritDoc */ path, \r\n /**@inheritDoc */ affectedTree, \r\n /**@inheritDoc */ revert) {\r\n this.path = path;\r\n this.affectedTree = affectedTree;\r\n this.revert = revert;\r\n /** @inheritDoc */\r\n this.type = OperationType.ACK_USER_WRITE;\r\n /** @inheritDoc */\r\n this.source = OperationSource.User;\r\n }\r\n /**\r\n * @inheritDoc\r\n */\r\n AckUserWrite.prototype.operationForChild = function (childName) {\r\n if (!this.path.isEmpty()) {\r\n util.assert(this.path.getFront() === childName, 'operationForChild called for unrelated child.');\r\n return new AckUserWrite(this.path.popFront(), this.affectedTree, this.revert);\r\n }\r\n else if (this.affectedTree.value != null) {\r\n util.assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');\r\n // All child locations are affected as well; just return same operation.\r\n return this;\r\n }\r\n else {\r\n var childTree = this.affectedTree.subtree(new Path(childName));\r\n return new AckUserWrite(Path.Empty, childTree, this.revert);\r\n }\r\n };\r\n return AckUserWrite;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar emptyChildrenSingleton;\r\n/**\r\n * Singleton empty children collection.\r\n *\r\n * @const\r\n * @type {!SortedMap.>}\r\n */\r\nvar EmptyChildren = function () {\r\n if (!emptyChildrenSingleton) {\r\n emptyChildrenSingleton = new SortedMap(stringCompare);\r\n }\r\n return emptyChildrenSingleton;\r\n};\r\n/**\r\n * A tree with immutable elements.\r\n */\r\nvar ImmutableTree = /** @class */ (function () {\r\n /**\r\n * @template T\r\n * @param {?T} value\r\n * @param {SortedMap.>=} children\r\n */\r\n function ImmutableTree(value, children) {\r\n if (children === void 0) { children = EmptyChildren(); }\r\n this.value = value;\r\n this.children = children;\r\n }\r\n /**\r\n * @template T\r\n * @param {!Object.} obj\r\n * @return {!ImmutableTree.}\r\n */\r\n ImmutableTree.fromObject = function (obj) {\r\n var tree = ImmutableTree.Empty;\r\n util.forEach(obj, function (childPath, childSnap) {\r\n tree = tree.set(new Path(childPath), childSnap);\r\n });\r\n return tree;\r\n };\r\n /**\r\n * True if the value is empty and there are no children\r\n * @return {boolean}\r\n */\r\n ImmutableTree.prototype.isEmpty = function () {\r\n return this.value === null && this.children.isEmpty();\r\n };\r\n /**\r\n * Given a path and predicate, return the first node and the path to that node\r\n * where the predicate returns true.\r\n *\r\n * TODO Do a perf test -- If we're creating a bunch of {path: value:} objects\r\n * on the way back out, it may be better to pass down a pathSoFar obj.\r\n *\r\n * @param {!Path} relativePath The remainder of the path\r\n * @param {function(T):boolean} predicate The predicate to satisfy to return a\r\n * node\r\n * @return {?{path:!Path, value:!T}}\r\n */\r\n ImmutableTree.prototype.findRootMostMatchingPathAndValue = function (relativePath, predicate) {\r\n if (this.value != null && predicate(this.value)) {\r\n return { path: Path.Empty, value: this.value };\r\n }\r\n else {\r\n if (relativePath.isEmpty()) {\r\n return null;\r\n }\r\n else {\r\n var front = relativePath.getFront();\r\n var child = this.children.get(front);\r\n if (child !== null) {\r\n var childExistingPathAndValue = child.findRootMostMatchingPathAndValue(relativePath.popFront(), predicate);\r\n if (childExistingPathAndValue != null) {\r\n var fullPath = new Path(front).child(childExistingPathAndValue.path);\r\n return { path: fullPath, value: childExistingPathAndValue.value };\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n }\r\n };\r\n /**\r\n * Find, if it exists, the shortest subpath of the given path that points a defined\r\n * value in the tree\r\n * @param {!Path} relativePath\r\n * @return {?{path: !Path, value: !T}}\r\n */\r\n ImmutableTree.prototype.findRootMostValueAndPath = function (relativePath) {\r\n return this.findRootMostMatchingPathAndValue(relativePath, function () { return true; });\r\n };\r\n /**\r\n * @param {!Path} relativePath\r\n * @return {!ImmutableTree.} The subtree at the given path\r\n */\r\n ImmutableTree.prototype.subtree = function (relativePath) {\r\n if (relativePath.isEmpty()) {\r\n return this;\r\n }\r\n else {\r\n var front = relativePath.getFront();\r\n var childTree = this.children.get(front);\r\n if (childTree !== null) {\r\n return childTree.subtree(relativePath.popFront());\r\n }\r\n else {\r\n return ImmutableTree.Empty;\r\n }\r\n }\r\n };\r\n /**\r\n * Sets a value at the specified path.\r\n *\r\n * @param {!Path} relativePath Path to set value at.\r\n * @param {?T} toSet Value to set.\r\n * @return {!ImmutableTree.} Resulting tree.\r\n */\r\n ImmutableTree.prototype.set = function (relativePath, toSet) {\r\n if (relativePath.isEmpty()) {\r\n return new ImmutableTree(toSet, this.children);\r\n }\r\n else {\r\n var front = relativePath.getFront();\r\n var child = this.children.get(front) || ImmutableTree.Empty;\r\n var newChild = child.set(relativePath.popFront(), toSet);\r\n var newChildren = this.children.insert(front, newChild);\r\n return new ImmutableTree(this.value, newChildren);\r\n }\r\n };\r\n /**\r\n * Removes the value at the specified path.\r\n *\r\n * @param {!Path} relativePath Path to value to remove.\r\n * @return {!ImmutableTree.} Resulting tree.\r\n */\r\n ImmutableTree.prototype.remove = function (relativePath) {\r\n if (relativePath.isEmpty()) {\r\n if (this.children.isEmpty()) {\r\n return ImmutableTree.Empty;\r\n }\r\n else {\r\n return new ImmutableTree(null, this.children);\r\n }\r\n }\r\n else {\r\n var front = relativePath.getFront();\r\n var child = this.children.get(front);\r\n if (child) {\r\n var newChild = child.remove(relativePath.popFront());\r\n var newChildren = void 0;\r\n if (newChild.isEmpty()) {\r\n newChildren = this.children.remove(front);\r\n }\r\n else {\r\n newChildren = this.children.insert(front, newChild);\r\n }\r\n if (this.value === null && newChildren.isEmpty()) {\r\n return ImmutableTree.Empty;\r\n }\r\n else {\r\n return new ImmutableTree(this.value, newChildren);\r\n }\r\n }\r\n else {\r\n return this;\r\n }\r\n }\r\n };\r\n /**\r\n * Gets a value from the tree.\r\n *\r\n * @param {!Path} relativePath Path to get value for.\r\n * @return {?T} Value at path, or null.\r\n */\r\n ImmutableTree.prototype.get = function (relativePath) {\r\n if (relativePath.isEmpty()) {\r\n return this.value;\r\n }\r\n else {\r\n var front = relativePath.getFront();\r\n var child = this.children.get(front);\r\n if (child) {\r\n return child.get(relativePath.popFront());\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n };\r\n /**\r\n * Replace the subtree at the specified path with the given new tree.\r\n *\r\n * @param {!Path} relativePath Path to replace subtree for.\r\n * @param {!ImmutableTree} newTree New tree.\r\n * @return {!ImmutableTree} Resulting tree.\r\n */\r\n ImmutableTree.prototype.setTree = function (relativePath, newTree) {\r\n if (relativePath.isEmpty()) {\r\n return newTree;\r\n }\r\n else {\r\n var front = relativePath.getFront();\r\n var child = this.children.get(front) || ImmutableTree.Empty;\r\n var newChild = child.setTree(relativePath.popFront(), newTree);\r\n var newChildren = void 0;\r\n if (newChild.isEmpty()) {\r\n newChildren = this.children.remove(front);\r\n }\r\n else {\r\n newChildren = this.children.insert(front, newChild);\r\n }\r\n return new ImmutableTree(this.value, newChildren);\r\n }\r\n };\r\n /**\r\n * Performs a depth first fold on this tree. Transforms a tree into a single\r\n * value, given a function that operates on the path to a node, an optional\r\n * current value, and a map of child names to folded subtrees\r\n * @template V\r\n * @param {function(Path, ?T, Object.):V} fn\r\n * @return {V}\r\n */\r\n ImmutableTree.prototype.fold = function (fn) {\r\n return this.fold_(Path.Empty, fn);\r\n };\r\n /**\r\n * Recursive helper for public-facing fold() method\r\n * @template V\r\n * @param {!Path} pathSoFar\r\n * @param {function(Path, ?T, Object.):V} fn\r\n * @return {V}\r\n * @private\r\n */\r\n ImmutableTree.prototype.fold_ = function (pathSoFar, fn) {\r\n var accum = {};\r\n this.children.inorderTraversal(function (childKey, childTree) {\r\n accum[childKey] = childTree.fold_(pathSoFar.child(childKey), fn);\r\n });\r\n return fn(pathSoFar, this.value, accum);\r\n };\r\n /**\r\n * Find the first matching value on the given path. Return the result of applying f to it.\r\n * @template V\r\n * @param {!Path} path\r\n * @param {!function(!Path, !T):?V} f\r\n * @return {?V}\r\n */\r\n ImmutableTree.prototype.findOnPath = function (path, f) {\r\n return this.findOnPath_(path, Path.Empty, f);\r\n };\r\n ImmutableTree.prototype.findOnPath_ = function (pathToFollow, pathSoFar, f) {\r\n var result = this.value ? f(pathSoFar, this.value) : false;\r\n if (result) {\r\n return result;\r\n }\r\n else {\r\n if (pathToFollow.isEmpty()) {\r\n return null;\r\n }\r\n else {\r\n var front = pathToFollow.getFront();\r\n var nextChild = this.children.get(front);\r\n if (nextChild) {\r\n return nextChild.findOnPath_(pathToFollow.popFront(), pathSoFar.child(front), f);\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n }\r\n };\r\n /**\r\n *\r\n * @param {!Path} path\r\n * @param {!function(!Path, !T)} f\r\n * @returns {!ImmutableTree.}\r\n */\r\n ImmutableTree.prototype.foreachOnPath = function (path, f) {\r\n return this.foreachOnPath_(path, Path.Empty, f);\r\n };\r\n ImmutableTree.prototype.foreachOnPath_ = function (pathToFollow, currentRelativePath, f) {\r\n if (pathToFollow.isEmpty()) {\r\n return this;\r\n }\r\n else {\r\n if (this.value) {\r\n f(currentRelativePath, this.value);\r\n }\r\n var front = pathToFollow.getFront();\r\n var nextChild = this.children.get(front);\r\n if (nextChild) {\r\n return nextChild.foreachOnPath_(pathToFollow.popFront(), currentRelativePath.child(front), f);\r\n }\r\n else {\r\n return ImmutableTree.Empty;\r\n }\r\n }\r\n };\r\n /**\r\n * Calls the given function for each node in the tree that has a value.\r\n *\r\n * @param {function(!Path, !T)} f A function to be called with\r\n * the path from the root of the tree to a node, and the value at that node.\r\n * Called in depth-first order.\r\n */\r\n ImmutableTree.prototype.foreach = function (f) {\r\n this.foreach_(Path.Empty, f);\r\n };\r\n ImmutableTree.prototype.foreach_ = function (currentRelativePath, f) {\r\n this.children.inorderTraversal(function (childName, childTree) {\r\n childTree.foreach_(currentRelativePath.child(childName), f);\r\n });\r\n if (this.value) {\r\n f(currentRelativePath, this.value);\r\n }\r\n };\r\n /**\r\n *\r\n * @param {function(string, !T)} f\r\n */\r\n ImmutableTree.prototype.foreachChild = function (f) {\r\n this.children.inorderTraversal(function (childName, childTree) {\r\n if (childTree.value) {\r\n f(childName, childTree.value);\r\n }\r\n });\r\n };\r\n ImmutableTree.Empty = new ImmutableTree(null);\r\n return ImmutableTree;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @param {!OperationSource} source\r\n * @param {!Path} path\r\n * @constructor\r\n * @implements {Operation}\r\n */\r\nvar ListenComplete = /** @class */ (function () {\r\n function ListenComplete(source, path) {\r\n this.source = source;\r\n this.path = path;\r\n /** @inheritDoc */\r\n this.type = OperationType.LISTEN_COMPLETE;\r\n }\r\n ListenComplete.prototype.operationForChild = function (childName) {\r\n if (this.path.isEmpty()) {\r\n return new ListenComplete(this.source, Path.Empty);\r\n }\r\n else {\r\n return new ListenComplete(this.source, this.path.popFront());\r\n }\r\n };\r\n return ListenComplete;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @param {!OperationSource} source\r\n * @param {!Path} path\r\n * @param {!Node} snap\r\n * @constructor\r\n * @implements {Operation}\r\n */\r\nvar Overwrite = /** @class */ (function () {\r\n function Overwrite(source, path, snap) {\r\n this.source = source;\r\n this.path = path;\r\n this.snap = snap;\r\n /** @inheritDoc */\r\n this.type = OperationType.OVERWRITE;\r\n }\r\n Overwrite.prototype.operationForChild = function (childName) {\r\n if (this.path.isEmpty()) {\r\n return new Overwrite(this.source, Path.Empty, this.snap.getImmediateChild(childName));\r\n }\r\n else {\r\n return new Overwrite(this.source, this.path.popFront(), this.snap);\r\n }\r\n };\r\n return Overwrite;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @param {!OperationSource} source\r\n * @param {!Path} path\r\n * @param {!ImmutableTree.} children\r\n * @constructor\r\n * @implements {Operation}\r\n */\r\nvar Merge = /** @class */ (function () {\r\n function Merge(\r\n /**@inheritDoc */ source, \r\n /**@inheritDoc */ path, \r\n /**@inheritDoc */ children) {\r\n this.source = source;\r\n this.path = path;\r\n this.children = children;\r\n /** @inheritDoc */\r\n this.type = OperationType.MERGE;\r\n }\r\n /**\r\n * @inheritDoc\r\n */\r\n Merge.prototype.operationForChild = function (childName) {\r\n if (this.path.isEmpty()) {\r\n var childTree = this.children.subtree(new Path(childName));\r\n if (childTree.isEmpty()) {\r\n // This child is unaffected\r\n return null;\r\n }\r\n else if (childTree.value) {\r\n // We have a snapshot for the child in question. This becomes an overwrite of the child.\r\n return new Overwrite(this.source, Path.Empty, childTree.value);\r\n }\r\n else {\r\n // This is a merge at a deeper level\r\n return new Merge(this.source, Path.Empty, childTree);\r\n }\r\n }\r\n else {\r\n util.assert(this.path.getFront() === childName, \"Can't get a merge for a child not on the path of the operation\");\r\n return new Merge(this.source, this.path.popFront(), this.children);\r\n }\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n Merge.prototype.toString = function () {\r\n return ('Operation(' +\r\n this.path +\r\n ': ' +\r\n this.source.toString() +\r\n ' merge: ' +\r\n this.children.toString() +\r\n ')');\r\n };\r\n return Merge;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully\r\n * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.\r\n * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks\r\n * whether a node potentially had children removed due to a filter.\r\n */\r\nvar CacheNode = /** @class */ (function () {\r\n /**\r\n * @param {!Node} node_\r\n * @param {boolean} fullyInitialized_\r\n * @param {boolean} filtered_\r\n */\r\n function CacheNode(node_, fullyInitialized_, filtered_) {\r\n this.node_ = node_;\r\n this.fullyInitialized_ = fullyInitialized_;\r\n this.filtered_ = filtered_;\r\n }\r\n /**\r\n * Returns whether this node was fully initialized with either server data or a complete overwrite by the client\r\n * @return {boolean}\r\n */\r\n CacheNode.prototype.isFullyInitialized = function () {\r\n return this.fullyInitialized_;\r\n };\r\n /**\r\n * Returns whether this node is potentially missing children due to a filter applied to the node\r\n * @return {boolean}\r\n */\r\n CacheNode.prototype.isFiltered = function () {\r\n return this.filtered_;\r\n };\r\n /**\r\n * @param {!Path} path\r\n * @return {boolean}\r\n */\r\n CacheNode.prototype.isCompleteForPath = function (path) {\r\n if (path.isEmpty()) {\r\n return this.isFullyInitialized() && !this.filtered_;\r\n }\r\n var childKey = path.getFront();\r\n return this.isCompleteForChild(childKey);\r\n };\r\n /**\r\n * @param {!string} key\r\n * @return {boolean}\r\n */\r\n CacheNode.prototype.isCompleteForChild = function (key) {\r\n return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));\r\n };\r\n /**\r\n * @return {!Node}\r\n */\r\n CacheNode.prototype.getNode = function () {\r\n return this.node_;\r\n };\r\n return CacheNode;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Stores the data we have cached for a view.\r\n *\r\n * serverSnap is the cached server data, eventSnap is the cached event data (server data plus any local writes).\r\n *\r\n * @constructor\r\n */\r\nvar ViewCache = /** @class */ (function () {\r\n /**\r\n *\r\n * @param {!CacheNode} eventCache_\r\n * @param {!CacheNode} serverCache_\r\n */\r\n function ViewCache(eventCache_, serverCache_) {\r\n this.eventCache_ = eventCache_;\r\n this.serverCache_ = serverCache_;\r\n }\r\n /**\r\n * @param {!Node} eventSnap\r\n * @param {boolean} complete\r\n * @param {boolean} filtered\r\n * @return {!ViewCache}\r\n */\r\n ViewCache.prototype.updateEventSnap = function (eventSnap, complete, filtered) {\r\n return new ViewCache(new CacheNode(eventSnap, complete, filtered), this.serverCache_);\r\n };\r\n /**\r\n * @param {!Node} serverSnap\r\n * @param {boolean} complete\r\n * @param {boolean} filtered\r\n * @return {!ViewCache}\r\n */\r\n ViewCache.prototype.updateServerSnap = function (serverSnap, complete, filtered) {\r\n return new ViewCache(this.eventCache_, new CacheNode(serverSnap, complete, filtered));\r\n };\r\n /**\r\n * @return {!CacheNode}\r\n */\r\n ViewCache.prototype.getEventCache = function () {\r\n return this.eventCache_;\r\n };\r\n /**\r\n * @return {?Node}\r\n */\r\n ViewCache.prototype.getCompleteEventSnap = function () {\r\n return this.eventCache_.isFullyInitialized()\r\n ? this.eventCache_.getNode()\r\n : null;\r\n };\r\n /**\r\n * @return {!CacheNode}\r\n */\r\n ViewCache.prototype.getServerCache = function () {\r\n return this.serverCache_;\r\n };\r\n /**\r\n * @return {?Node}\r\n */\r\n ViewCache.prototype.getCompleteServerSnap = function () {\r\n return this.serverCache_.isFullyInitialized()\r\n ? this.serverCache_.getNode()\r\n : null;\r\n };\r\n /**\r\n * @const\r\n * @type {ViewCache}\r\n */\r\n ViewCache.Empty = new ViewCache(new CacheNode(ChildrenNode.EMPTY_NODE, \r\n /*fullyInitialized=*/ false, \r\n /*filtered=*/ false), new CacheNode(ChildrenNode.EMPTY_NODE, \r\n /*fullyInitialized=*/ false, \r\n /*filtered=*/ false));\r\n return ViewCache;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @constructor\r\n * @struct\r\n * @param {!string} type The event type\r\n * @param {!Node} snapshotNode The data\r\n * @param {string=} childName The name for this child, if it's a child event\r\n * @param {Node=} oldSnap Used for intermediate processing of child changed events\r\n * @param {string=} prevName The name for the previous child, if applicable\r\n */\r\nvar Change = /** @class */ (function () {\r\n function Change(type, snapshotNode, childName, oldSnap, prevName) {\r\n this.type = type;\r\n this.snapshotNode = snapshotNode;\r\n this.childName = childName;\r\n this.oldSnap = oldSnap;\r\n this.prevName = prevName;\r\n }\r\n /**\r\n * @param {!Node} snapshot\r\n * @return {!Change}\r\n */\r\n Change.valueChange = function (snapshot) {\r\n return new Change(Change.VALUE, snapshot);\r\n };\r\n /**\r\n * @param {string} childKey\r\n * @param {!Node} snapshot\r\n * @return {!Change}\r\n */\r\n Change.childAddedChange = function (childKey, snapshot) {\r\n return new Change(Change.CHILD_ADDED, snapshot, childKey);\r\n };\r\n /**\r\n * @param {string} childKey\r\n * @param {!Node} snapshot\r\n * @return {!Change}\r\n */\r\n Change.childRemovedChange = function (childKey, snapshot) {\r\n return new Change(Change.CHILD_REMOVED, snapshot, childKey);\r\n };\r\n /**\r\n * @param {string} childKey\r\n * @param {!Node} newSnapshot\r\n * @param {!Node} oldSnapshot\r\n * @return {!Change}\r\n */\r\n Change.childChangedChange = function (childKey, newSnapshot, oldSnapshot) {\r\n return new Change(Change.CHILD_CHANGED, newSnapshot, childKey, oldSnapshot);\r\n };\r\n /**\r\n * @param {string} childKey\r\n * @param {!Node} snapshot\r\n * @return {!Change}\r\n */\r\n Change.childMovedChange = function (childKey, snapshot) {\r\n return new Change(Change.CHILD_MOVED, snapshot, childKey);\r\n };\r\n //event types\r\n /** Event type for a child added */\r\n Change.CHILD_ADDED = 'child_added';\r\n /** Event type for a child removed */\r\n Change.CHILD_REMOVED = 'child_removed';\r\n /** Event type for a child changed */\r\n Change.CHILD_CHANGED = 'child_changed';\r\n /** Event type for a child moved */\r\n Change.CHILD_MOVED = 'child_moved';\r\n /** Event type for a value change */\r\n Change.VALUE = 'value';\r\n return Change;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Doesn't really filter nodes but applies an index to the node and keeps track of any changes\r\n *\r\n * @constructor\r\n * @implements {NodeFilter}\r\n * @param {!Index} index\r\n */\r\nvar IndexedFilter = /** @class */ (function () {\r\n function IndexedFilter(index_) {\r\n this.index_ = index_;\r\n }\r\n IndexedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\r\n util.assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');\r\n var oldChild = snap.getImmediateChild(key);\r\n // Check if anything actually changed.\r\n if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {\r\n // There's an edge case where a child can enter or leave the view because affectedPath was set to null.\r\n // In this case, affectedPath will appear null in both the old and new snapshots. So we need\r\n // to avoid treating these cases as \"nothing changed.\"\r\n if (oldChild.isEmpty() == newChild.isEmpty()) {\r\n // Nothing changed.\r\n // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.\r\n //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');\r\n return snap;\r\n }\r\n }\r\n if (optChangeAccumulator != null) {\r\n if (newChild.isEmpty()) {\r\n if (snap.hasChild(key)) {\r\n optChangeAccumulator.trackChildChange(Change.childRemovedChange(key, oldChild));\r\n }\r\n else {\r\n util.assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');\r\n }\r\n }\r\n else if (oldChild.isEmpty()) {\r\n optChangeAccumulator.trackChildChange(Change.childAddedChange(key, newChild));\r\n }\r\n else {\r\n optChangeAccumulator.trackChildChange(Change.childChangedChange(key, newChild, oldChild));\r\n }\r\n }\r\n if (snap.isLeafNode() && newChild.isEmpty()) {\r\n return snap;\r\n }\r\n else {\r\n // Make sure the node is indexed\r\n return snap.updateImmediateChild(key, newChild).withIndex(this.index_);\r\n }\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n IndexedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\r\n if (optChangeAccumulator != null) {\r\n if (!oldSnap.isLeafNode()) {\r\n oldSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) {\r\n if (!newSnap.hasChild(key)) {\r\n optChangeAccumulator.trackChildChange(Change.childRemovedChange(key, childNode));\r\n }\r\n });\r\n }\r\n if (!newSnap.isLeafNode()) {\r\n newSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) {\r\n if (oldSnap.hasChild(key)) {\r\n var oldChild = oldSnap.getImmediateChild(key);\r\n if (!oldChild.equals(childNode)) {\r\n optChangeAccumulator.trackChildChange(Change.childChangedChange(key, childNode, oldChild));\r\n }\r\n }\r\n else {\r\n optChangeAccumulator.trackChildChange(Change.childAddedChange(key, childNode));\r\n }\r\n });\r\n }\r\n }\r\n return newSnap.withIndex(this.index_);\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n IndexedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\r\n if (oldSnap.isEmpty()) {\r\n return ChildrenNode.EMPTY_NODE;\r\n }\r\n else {\r\n return oldSnap.updatePriority(newPriority);\r\n }\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n IndexedFilter.prototype.filtersNodes = function () {\r\n return false;\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n IndexedFilter.prototype.getIndexedFilter = function () {\r\n return this;\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n IndexedFilter.prototype.getIndex = function () {\r\n return this.index_;\r\n };\r\n return IndexedFilter;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @constructor\r\n */\r\nvar ChildChangeAccumulator = /** @class */ (function () {\r\n function ChildChangeAccumulator() {\r\n this.changeMap_ = {};\r\n }\r\n /**\r\n * @param {!Change} change\r\n */\r\n ChildChangeAccumulator.prototype.trackChildChange = function (change) {\r\n var type = change.type;\r\n var childKey /** @type {!string} */ = change.childName;\r\n util.assert(type == Change.CHILD_ADDED ||\r\n type == Change.CHILD_CHANGED ||\r\n type == Change.CHILD_REMOVED, 'Only child changes supported for tracking');\r\n util.assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');\r\n var oldChange = util.safeGet(this.changeMap_, childKey);\r\n if (oldChange) {\r\n var oldType = oldChange.type;\r\n if (type == Change.CHILD_ADDED && oldType == Change.CHILD_REMOVED) {\r\n this.changeMap_[childKey] = Change.childChangedChange(childKey, change.snapshotNode, oldChange.snapshotNode);\r\n }\r\n else if (type == Change.CHILD_REMOVED &&\r\n oldType == Change.CHILD_ADDED) {\r\n delete this.changeMap_[childKey];\r\n }\r\n else if (type == Change.CHILD_REMOVED &&\r\n oldType == Change.CHILD_CHANGED) {\r\n this.changeMap_[childKey] = Change.childRemovedChange(childKey, oldChange.oldSnap);\r\n }\r\n else if (type == Change.CHILD_CHANGED &&\r\n oldType == Change.CHILD_ADDED) {\r\n this.changeMap_[childKey] = Change.childAddedChange(childKey, change.snapshotNode);\r\n }\r\n else if (type == Change.CHILD_CHANGED &&\r\n oldType == Change.CHILD_CHANGED) {\r\n this.changeMap_[childKey] = Change.childChangedChange(childKey, change.snapshotNode, oldChange.oldSnap);\r\n }\r\n else {\r\n throw util.assertionError('Illegal combination of changes: ' +\r\n change +\r\n ' occurred after ' +\r\n oldChange);\r\n }\r\n }\r\n else {\r\n this.changeMap_[childKey] = change;\r\n }\r\n };\r\n /**\r\n * @return {!Array.}\r\n */\r\n ChildChangeAccumulator.prototype.getChanges = function () {\r\n return util.getValues(this.changeMap_);\r\n };\r\n return ChildChangeAccumulator;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An implementation of CompleteChildSource that never returns any additional children\r\n *\r\n * @private\r\n * @constructor\r\n * @implements CompleteChildSource\r\n */\r\nvar NoCompleteChildSource_ = /** @class */ (function () {\r\n function NoCompleteChildSource_() {\r\n }\r\n /**\r\n * @inheritDoc\r\n */\r\n NoCompleteChildSource_.prototype.getCompleteChild = function (childKey) {\r\n return null;\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n NoCompleteChildSource_.prototype.getChildAfterChild = function (index, child, reverse) {\r\n return null;\r\n };\r\n return NoCompleteChildSource_;\r\n}());\r\n/**\r\n * Singleton instance.\r\n * @const\r\n * @type {!CompleteChildSource}\r\n */\r\nvar NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();\r\n/**\r\n * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or\r\n * old event caches available to calculate complete children.\r\n *\r\n *\r\n * @implements CompleteChildSource\r\n */\r\nvar WriteTreeCompleteChildSource = /** @class */ (function () {\r\n /**\r\n * @param {!WriteTreeRef} writes_\r\n * @param {!ViewCache} viewCache_\r\n * @param {?Node} optCompleteServerCache_\r\n */\r\n function WriteTreeCompleteChildSource(writes_, viewCache_, optCompleteServerCache_) {\r\n if (optCompleteServerCache_ === void 0) { optCompleteServerCache_ = null; }\r\n this.writes_ = writes_;\r\n this.viewCache_ = viewCache_;\r\n this.optCompleteServerCache_ = optCompleteServerCache_;\r\n }\r\n /**\r\n * @inheritDoc\r\n */\r\n WriteTreeCompleteChildSource.prototype.getCompleteChild = function (childKey) {\r\n var node = this.viewCache_.getEventCache();\r\n if (node.isCompleteForChild(childKey)) {\r\n return node.getNode().getImmediateChild(childKey);\r\n }\r\n else {\r\n var serverNode = this.optCompleteServerCache_ != null\r\n ? new CacheNode(this.optCompleteServerCache_, true, false)\r\n : this.viewCache_.getServerCache();\r\n return this.writes_.calcCompleteChild(childKey, serverNode);\r\n }\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n WriteTreeCompleteChildSource.prototype.getChildAfterChild = function (index, child, reverse) {\r\n var completeServerData = this.optCompleteServerCache_ != null\r\n ? this.optCompleteServerCache_\r\n : this.viewCache_.getCompleteServerSnap();\r\n var nodes = this.writes_.calcIndexedSlice(completeServerData, child, 1, reverse, index);\r\n if (nodes.length === 0) {\r\n return null;\r\n }\r\n else {\r\n return nodes[0];\r\n }\r\n };\r\n return WriteTreeCompleteChildSource;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @constructor\r\n * @struct\r\n */\r\nvar ProcessorResult = /** @class */ (function () {\r\n /**\r\n * @param {!ViewCache} viewCache\r\n * @param {!Array.} changes\r\n */\r\n function ProcessorResult(viewCache, changes) {\r\n this.viewCache = viewCache;\r\n this.changes = changes;\r\n }\r\n return ProcessorResult;\r\n}());\r\n/**\r\n * @constructor\r\n */\r\nvar ViewProcessor = /** @class */ (function () {\r\n /**\r\n * @param {!NodeFilter} filter_\r\n */\r\n function ViewProcessor(filter_) {\r\n this.filter_ = filter_;\r\n }\r\n /**\r\n * @param {!ViewCache} viewCache\r\n */\r\n ViewProcessor.prototype.assertIndexed = function (viewCache) {\r\n util.assert(viewCache\r\n .getEventCache()\r\n .getNode()\r\n .isIndexed(this.filter_.getIndex()), 'Event snap not indexed');\r\n util.assert(viewCache\r\n .getServerCache()\r\n .getNode()\r\n .isIndexed(this.filter_.getIndex()), 'Server snap not indexed');\r\n };\r\n /**\r\n * @param {!ViewCache} oldViewCache\r\n * @param {!Operation} operation\r\n * @param {!WriteTreeRef} writesCache\r\n * @param {?Node} completeCache\r\n * @return {!ProcessorResult}\r\n */\r\n ViewProcessor.prototype.applyOperation = function (oldViewCache, operation, writesCache, completeCache) {\r\n var accumulator = new ChildChangeAccumulator();\r\n var newViewCache, filterServerNode;\r\n if (operation.type === OperationType.OVERWRITE) {\r\n var overwrite = operation;\r\n if (overwrite.source.fromUser) {\r\n newViewCache = this.applyUserOverwrite_(oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);\r\n }\r\n else {\r\n util.assert(overwrite.source.fromServer, 'Unknown source.');\r\n // We filter the node if it's a tagged update or the node has been previously filtered and the\r\n // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered\r\n // again\r\n filterServerNode =\r\n overwrite.source.tagged ||\r\n (oldViewCache.getServerCache().isFiltered() &&\r\n !overwrite.path.isEmpty());\r\n newViewCache = this.applyServerOverwrite_(oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);\r\n }\r\n }\r\n else if (operation.type === OperationType.MERGE) {\r\n var merge = operation;\r\n if (merge.source.fromUser) {\r\n newViewCache = this.applyUserMerge_(oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);\r\n }\r\n else {\r\n util.assert(merge.source.fromServer, 'Unknown source.');\r\n // We filter the node if it's a tagged update or the node has been previously filtered\r\n filterServerNode =\r\n merge.source.tagged || oldViewCache.getServerCache().isFiltered();\r\n newViewCache = this.applyServerMerge_(oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);\r\n }\r\n }\r\n else if (operation.type === OperationType.ACK_USER_WRITE) {\r\n var ackUserWrite = operation;\r\n if (!ackUserWrite.revert) {\r\n newViewCache = this.ackUserWrite_(oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);\r\n }\r\n else {\r\n newViewCache = this.revertUserWrite_(oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);\r\n }\r\n }\r\n else if (operation.type === OperationType.LISTEN_COMPLETE) {\r\n newViewCache = this.listenComplete_(oldViewCache, operation.path, writesCache, accumulator);\r\n }\r\n else {\r\n throw util.assertionError('Unknown operation type: ' + operation.type);\r\n }\r\n var changes = accumulator.getChanges();\r\n ViewProcessor.maybeAddValueEvent_(oldViewCache, newViewCache, changes);\r\n return new ProcessorResult(newViewCache, changes);\r\n };\r\n /**\r\n * @param {!ViewCache} oldViewCache\r\n * @param {!ViewCache} newViewCache\r\n * @param {!Array.} accumulator\r\n * @private\r\n */\r\n ViewProcessor.maybeAddValueEvent_ = function (oldViewCache, newViewCache, accumulator) {\r\n var eventSnap = newViewCache.getEventCache();\r\n if (eventSnap.isFullyInitialized()) {\r\n var isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();\r\n var oldCompleteSnap = oldViewCache.getCompleteEventSnap();\r\n if (accumulator.length > 0 ||\r\n !oldViewCache.getEventCache().isFullyInitialized() ||\r\n (isLeafOrEmpty &&\r\n !eventSnap\r\n .getNode()\r\n .equals(/** @type {!Node} */ (oldCompleteSnap))) ||\r\n !eventSnap\r\n .getNode()\r\n .getPriority()\r\n .equals(oldCompleteSnap.getPriority())) {\r\n accumulator.push(Change.valueChange(\r\n /** @type {!Node} */ newViewCache.getCompleteEventSnap()));\r\n }\r\n }\r\n };\r\n /**\r\n * @param {!ViewCache} viewCache\r\n * @param {!Path} changePath\r\n * @param {!WriteTreeRef} writesCache\r\n * @param {!CompleteChildSource} source\r\n * @param {!ChildChangeAccumulator} accumulator\r\n * @return {!ViewCache}\r\n * @private\r\n */\r\n ViewProcessor.prototype.generateEventCacheAfterServerEvent_ = function (viewCache, changePath, writesCache, source, accumulator) {\r\n var oldEventSnap = viewCache.getEventCache();\r\n if (writesCache.shadowingWrite(changePath) != null) {\r\n // we have a shadowing write, ignore changes\r\n return viewCache;\r\n }\r\n else {\r\n var newEventCache = void 0, serverNode = void 0;\r\n if (changePath.isEmpty()) {\r\n // TODO: figure out how this plays with \"sliding ack windows\"\r\n util.assert(viewCache.getServerCache().isFullyInitialized(), 'If change path is empty, we must have complete server data');\r\n if (viewCache.getServerCache().isFiltered()) {\r\n // We need to special case this, because we need to only apply writes to complete children, or\r\n // we might end up raising events for incomplete children. If the server data is filtered deep\r\n // writes cannot be guaranteed to be complete\r\n var serverCache = viewCache.getCompleteServerSnap();\r\n var completeChildren = serverCache instanceof ChildrenNode\r\n ? serverCache\r\n : ChildrenNode.EMPTY_NODE;\r\n var completeEventChildren = writesCache.calcCompleteEventChildren(completeChildren);\r\n newEventCache = this.filter_.updateFullNode(viewCache.getEventCache().getNode(), completeEventChildren, accumulator);\r\n }\r\n else {\r\n var completeNode = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\r\n newEventCache = this.filter_.updateFullNode(viewCache.getEventCache().getNode(), completeNode, accumulator);\r\n }\r\n }\r\n else {\r\n var childKey = changePath.getFront();\r\n if (childKey == '.priority') {\r\n util.assert(changePath.getLength() == 1, \"Can't have a priority with additional path components\");\r\n var oldEventNode = oldEventSnap.getNode();\r\n serverNode = viewCache.getServerCache().getNode();\r\n // we might have overwrites for this priority\r\n var updatedPriority = writesCache.calcEventCacheAfterServerOverwrite(changePath, oldEventNode, serverNode);\r\n if (updatedPriority != null) {\r\n newEventCache = this.filter_.updatePriority(oldEventNode, updatedPriority);\r\n }\r\n else {\r\n // priority didn't change, keep old node\r\n newEventCache = oldEventSnap.getNode();\r\n }\r\n }\r\n else {\r\n var childChangePath = changePath.popFront();\r\n // update child\r\n var newEventChild = void 0;\r\n if (oldEventSnap.isCompleteForChild(childKey)) {\r\n serverNode = viewCache.getServerCache().getNode();\r\n var eventChildUpdate = writesCache.calcEventCacheAfterServerOverwrite(changePath, oldEventSnap.getNode(), serverNode);\r\n if (eventChildUpdate != null) {\r\n newEventChild = oldEventSnap\r\n .getNode()\r\n .getImmediateChild(childKey)\r\n .updateChild(childChangePath, eventChildUpdate);\r\n }\r\n else {\r\n // Nothing changed, just keep the old child\r\n newEventChild = oldEventSnap\r\n .getNode()\r\n .getImmediateChild(childKey);\r\n }\r\n }\r\n else {\r\n newEventChild = writesCache.calcCompleteChild(childKey, viewCache.getServerCache());\r\n }\r\n if (newEventChild != null) {\r\n newEventCache = this.filter_.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);\r\n }\r\n else {\r\n // no complete child available or no change\r\n newEventCache = oldEventSnap.getNode();\r\n }\r\n }\r\n }\r\n return viewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitialized() || changePath.isEmpty(), this.filter_.filtersNodes());\r\n }\r\n };\r\n /**\r\n * @param {!ViewCache} oldViewCache\r\n * @param {!Path} changePath\r\n * @param {!Node} changedSnap\r\n * @param {!WriteTreeRef} writesCache\r\n * @param {?Node} completeCache\r\n * @param {boolean} filterServerNode\r\n * @param {!ChildChangeAccumulator} accumulator\r\n * @return {!ViewCache}\r\n * @private\r\n */\r\n ViewProcessor.prototype.applyServerOverwrite_ = function (oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {\r\n var oldServerSnap = oldViewCache.getServerCache();\r\n var newServerCache;\r\n var serverFilter = filterServerNode\r\n ? this.filter_\r\n : this.filter_.getIndexedFilter();\r\n if (changePath.isEmpty()) {\r\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);\r\n }\r\n else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {\r\n // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update\r\n var newServerNode = oldServerSnap\r\n .getNode()\r\n .updateChild(changePath, changedSnap);\r\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);\r\n }\r\n else {\r\n var childKey = changePath.getFront();\r\n if (!oldServerSnap.isCompleteForPath(changePath) &&\r\n changePath.getLength() > 1) {\r\n // We don't update incomplete nodes with updates intended for other listeners\r\n return oldViewCache;\r\n }\r\n var childChangePath = changePath.popFront();\r\n var childNode = oldServerSnap.getNode().getImmediateChild(childKey);\r\n var newChildNode = childNode.updateChild(childChangePath, changedSnap);\r\n if (childKey == '.priority') {\r\n newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);\r\n }\r\n else {\r\n newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null);\r\n }\r\n }\r\n var newViewCache = oldViewCache.updateServerSnap(newServerCache, oldServerSnap.isFullyInitialized() || changePath.isEmpty(), serverFilter.filtersNodes());\r\n var source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);\r\n return this.generateEventCacheAfterServerEvent_(newViewCache, changePath, writesCache, source, accumulator);\r\n };\r\n /**\r\n * @param {!ViewCache} oldViewCache\r\n * @param {!Path} changePath\r\n * @param {!Node} changedSnap\r\n * @param {!WriteTreeRef} writesCache\r\n * @param {?Node} completeCache\r\n * @param {!ChildChangeAccumulator} accumulator\r\n * @return {!ViewCache}\r\n * @private\r\n */\r\n ViewProcessor.prototype.applyUserOverwrite_ = function (oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {\r\n var oldEventSnap = oldViewCache.getEventCache();\r\n var newViewCache, newEventCache;\r\n var source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);\r\n if (changePath.isEmpty()) {\r\n newEventCache = this.filter_.updateFullNode(oldViewCache.getEventCache().getNode(), changedSnap, accumulator);\r\n newViewCache = oldViewCache.updateEventSnap(newEventCache, true, this.filter_.filtersNodes());\r\n }\r\n else {\r\n var childKey = changePath.getFront();\r\n if (childKey === '.priority') {\r\n newEventCache = this.filter_.updatePriority(oldViewCache.getEventCache().getNode(), changedSnap);\r\n newViewCache = oldViewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());\r\n }\r\n else {\r\n var childChangePath = changePath.popFront();\r\n var oldChild = oldEventSnap.getNode().getImmediateChild(childKey);\r\n var newChild = void 0;\r\n if (childChangePath.isEmpty()) {\r\n // Child overwrite, we can replace the child\r\n newChild = changedSnap;\r\n }\r\n else {\r\n var childNode = source.getCompleteChild(childKey);\r\n if (childNode != null) {\r\n if (childChangePath.getBack() === '.priority' &&\r\n childNode.getChild(childChangePath.parent()).isEmpty()) {\r\n // This is a priority update on an empty node. If this node exists on the server, the\r\n // server will send down the priority in the update, so ignore for now\r\n newChild = childNode;\r\n }\r\n else {\r\n newChild = childNode.updateChild(childChangePath, changedSnap);\r\n }\r\n }\r\n else {\r\n // There is no complete child node available\r\n newChild = ChildrenNode.EMPTY_NODE;\r\n }\r\n }\r\n if (!oldChild.equals(newChild)) {\r\n var newEventSnap = this.filter_.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);\r\n newViewCache = oldViewCache.updateEventSnap(newEventSnap, oldEventSnap.isFullyInitialized(), this.filter_.filtersNodes());\r\n }\r\n else {\r\n newViewCache = oldViewCache;\r\n }\r\n }\r\n }\r\n return newViewCache;\r\n };\r\n /**\r\n * @param {!ViewCache} viewCache\r\n * @param {string} childKey\r\n * @return {boolean}\r\n * @private\r\n */\r\n ViewProcessor.cacheHasChild_ = function (viewCache, childKey) {\r\n return viewCache.getEventCache().isCompleteForChild(childKey);\r\n };\r\n /**\r\n * @param {!ViewCache} viewCache\r\n * @param {!Path} path\r\n * @param {ImmutableTree.} changedChildren\r\n * @param {!WriteTreeRef} writesCache\r\n * @param {?Node} serverCache\r\n * @param {!ChildChangeAccumulator} accumulator\r\n * @return {!ViewCache}\r\n * @private\r\n */\r\n ViewProcessor.prototype.applyUserMerge_ = function (viewCache, path, changedChildren, writesCache, serverCache, accumulator) {\r\n var _this = this;\r\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\r\n // window leaving room for new items. It's important we process these changes first, so we\r\n // iterate the changes twice, first processing any that affect items currently in view.\r\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\r\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\r\n // not the other.\r\n var curViewCache = viewCache;\r\n changedChildren.foreach(function (relativePath, childNode) {\r\n var writePath = path.child(relativePath);\r\n if (ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) {\r\n curViewCache = _this.applyUserOverwrite_(curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\r\n }\r\n });\r\n changedChildren.foreach(function (relativePath, childNode) {\r\n var writePath = path.child(relativePath);\r\n if (!ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) {\r\n curViewCache = _this.applyUserOverwrite_(curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\r\n }\r\n });\r\n return curViewCache;\r\n };\r\n /**\r\n * @param {!Node} node\r\n * @param {ImmutableTree.} merge\r\n * @return {!Node}\r\n * @private\r\n */\r\n ViewProcessor.prototype.applyMerge_ = function (node, merge) {\r\n merge.foreach(function (relativePath, childNode) {\r\n node = node.updateChild(relativePath, childNode);\r\n });\r\n return node;\r\n };\r\n /**\r\n * @param {!ViewCache} viewCache\r\n * @param {!Path} path\r\n * @param {!ImmutableTree.} changedChildren\r\n * @param {!WriteTreeRef} writesCache\r\n * @param {?Node} serverCache\r\n * @param {boolean} filterServerNode\r\n * @param {!ChildChangeAccumulator} accumulator\r\n * @return {!ViewCache}\r\n * @private\r\n */\r\n ViewProcessor.prototype.applyServerMerge_ = function (viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {\r\n var _this = this;\r\n // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and\r\n // wait for the complete data update coming soon.\r\n if (viewCache\r\n .getServerCache()\r\n .getNode()\r\n .isEmpty() &&\r\n !viewCache.getServerCache().isFullyInitialized()) {\r\n return viewCache;\r\n }\r\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\r\n // window leaving room for new items. It's important we process these changes first, so we\r\n // iterate the changes twice, first processing any that affect items currently in view.\r\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\r\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\r\n // not the other.\r\n var curViewCache = viewCache;\r\n var viewMergeTree;\r\n if (path.isEmpty()) {\r\n viewMergeTree = changedChildren;\r\n }\r\n else {\r\n viewMergeTree = ImmutableTree.Empty.setTree(path, changedChildren);\r\n }\r\n var serverNode = viewCache.getServerCache().getNode();\r\n viewMergeTree.children.inorderTraversal(function (childKey, childTree) {\r\n if (serverNode.hasChild(childKey)) {\r\n var serverChild = viewCache\r\n .getServerCache()\r\n .getNode()\r\n .getImmediateChild(childKey);\r\n var newChild = _this.applyMerge_(serverChild, childTree);\r\n curViewCache = _this.applyServerOverwrite_(curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\r\n }\r\n });\r\n viewMergeTree.children.inorderTraversal(function (childKey, childMergeTree) {\r\n var isUnknownDeepMerge = !viewCache.getServerCache().isCompleteForChild(childKey) &&\r\n childMergeTree.value == null;\r\n if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {\r\n var serverChild = viewCache\r\n .getServerCache()\r\n .getNode()\r\n .getImmediateChild(childKey);\r\n var newChild = _this.applyMerge_(serverChild, childMergeTree);\r\n curViewCache = _this.applyServerOverwrite_(curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\r\n }\r\n });\r\n return curViewCache;\r\n };\r\n /**\r\n * @param {!ViewCache} viewCache\r\n * @param {!Path} ackPath\r\n * @param {!ImmutableTree} affectedTree\r\n * @param {!WriteTreeRef} writesCache\r\n * @param {?Node} completeCache\r\n * @param {!ChildChangeAccumulator} accumulator\r\n * @return {!ViewCache}\r\n * @private\r\n */\r\n ViewProcessor.prototype.ackUserWrite_ = function (viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {\r\n if (writesCache.shadowingWrite(ackPath) != null) {\r\n return viewCache;\r\n }\r\n // Only filter server node if it is currently filtered\r\n var filterServerNode = viewCache.getServerCache().isFiltered();\r\n // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update\r\n // now that it won't be shadowed.\r\n var serverCache = viewCache.getServerCache();\r\n if (affectedTree.value != null) {\r\n // This is an overwrite.\r\n if ((ackPath.isEmpty() && serverCache.isFullyInitialized()) ||\r\n serverCache.isCompleteForPath(ackPath)) {\r\n return this.applyServerOverwrite_(viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);\r\n }\r\n else if (ackPath.isEmpty()) {\r\n // This is a goofy edge case where we are acking data at this location but don't have full data. We\r\n // should just re-apply whatever we have in our cache as a merge.\r\n var changedChildren_1 = ImmutableTree.Empty;\r\n serverCache.getNode().forEachChild(KEY_INDEX, function (name, node) {\r\n changedChildren_1 = changedChildren_1.set(new Path(name), node);\r\n });\r\n return this.applyServerMerge_(viewCache, ackPath, changedChildren_1, writesCache, completeCache, filterServerNode, accumulator);\r\n }\r\n else {\r\n return viewCache;\r\n }\r\n }\r\n else {\r\n // This is a merge.\r\n var changedChildren_2 = ImmutableTree.Empty;\r\n affectedTree.foreach(function (mergePath, value) {\r\n var serverCachePath = ackPath.child(mergePath);\r\n if (serverCache.isCompleteForPath(serverCachePath)) {\r\n changedChildren_2 = changedChildren_2.set(mergePath, serverCache.getNode().getChild(serverCachePath));\r\n }\r\n });\r\n return this.applyServerMerge_(viewCache, ackPath, changedChildren_2, writesCache, completeCache, filterServerNode, accumulator);\r\n }\r\n };\r\n /**\r\n * @param {!ViewCache} viewCache\r\n * @param {!Path} path\r\n * @param {!WriteTreeRef} writesCache\r\n * @param {!ChildChangeAccumulator} accumulator\r\n * @return {!ViewCache}\r\n * @private\r\n */\r\n ViewProcessor.prototype.listenComplete_ = function (viewCache, path, writesCache, accumulator) {\r\n var oldServerNode = viewCache.getServerCache();\r\n var newViewCache = viewCache.updateServerSnap(oldServerNode.getNode(), oldServerNode.isFullyInitialized() || path.isEmpty(), oldServerNode.isFiltered());\r\n return this.generateEventCacheAfterServerEvent_(newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator);\r\n };\r\n /**\r\n * @param {!ViewCache} viewCache\r\n * @param {!Path} path\r\n * @param {!WriteTreeRef} writesCache\r\n * @param {?Node} completeServerCache\r\n * @param {!ChildChangeAccumulator} accumulator\r\n * @return {!ViewCache}\r\n * @private\r\n */\r\n ViewProcessor.prototype.revertUserWrite_ = function (viewCache, path, writesCache, completeServerCache, accumulator) {\r\n var complete;\r\n if (writesCache.shadowingWrite(path) != null) {\r\n return viewCache;\r\n }\r\n else {\r\n var source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);\r\n var oldEventCache = viewCache.getEventCache().getNode();\r\n var newEventCache = void 0;\r\n if (path.isEmpty() || path.getFront() === '.priority') {\r\n var newNode = void 0;\r\n if (viewCache.getServerCache().isFullyInitialized()) {\r\n newNode = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\r\n }\r\n else {\r\n var serverChildren = viewCache.getServerCache().getNode();\r\n util.assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node');\r\n newNode = writesCache.calcCompleteEventChildren(serverChildren);\r\n }\r\n newNode = newNode;\r\n newEventCache = this.filter_.updateFullNode(oldEventCache, newNode, accumulator);\r\n }\r\n else {\r\n var childKey = path.getFront();\r\n var newChild = writesCache.calcCompleteChild(childKey, viewCache.getServerCache());\r\n if (newChild == null &&\r\n viewCache.getServerCache().isCompleteForChild(childKey)) {\r\n newChild = oldEventCache.getImmediateChild(childKey);\r\n }\r\n if (newChild != null) {\r\n newEventCache = this.filter_.updateChild(oldEventCache, childKey, newChild, path.popFront(), source, accumulator);\r\n }\r\n else if (viewCache\r\n .getEventCache()\r\n .getNode()\r\n .hasChild(childKey)) {\r\n // No complete child available, delete the existing one, if any\r\n newEventCache = this.filter_.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, path.popFront(), source, accumulator);\r\n }\r\n else {\r\n newEventCache = oldEventCache;\r\n }\r\n if (newEventCache.isEmpty() &&\r\n viewCache.getServerCache().isFullyInitialized()) {\r\n // We might have reverted all child writes. Maybe the old event was a leaf node\r\n complete = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\r\n if (complete.isLeafNode()) {\r\n newEventCache = this.filter_.updateFullNode(newEventCache, complete, accumulator);\r\n }\r\n }\r\n }\r\n complete =\r\n viewCache.getServerCache().isFullyInitialized() ||\r\n writesCache.shadowingWrite(Path.Empty) != null;\r\n return viewCache.updateEventSnap(newEventCache, complete, this.filter_.filtersNodes());\r\n }\r\n };\r\n return ViewProcessor;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An EventGenerator is used to convert \"raw\" changes (Change) as computed by the\r\n * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()\r\n * for details.\r\n *\r\n * @constructor\r\n */\r\nvar EventGenerator = /** @class */ (function () {\r\n /**\r\n *\r\n * @param {!Query} query_\r\n */\r\n function EventGenerator(query_) {\r\n this.query_ = query_;\r\n /**\r\n * @private\r\n * @type {!Index}\r\n */\r\n this.index_ = this.query_.getQueryParams().getIndex();\r\n }\r\n /**\r\n * Given a set of raw changes (no moved events and prevName not specified yet), and a set of\r\n * EventRegistrations that should be notified of these changes, generate the actual events to be raised.\r\n *\r\n * Notes:\r\n * - child_moved events will be synthesized at this time for any child_changed events that affect\r\n * our index.\r\n * - prevName will be calculated based on the index ordering.\r\n *\r\n * @param {!Array.} changes\r\n * @param {!Node} eventCache\r\n * @param {!Array.} eventRegistrations\r\n * @return {!Array.}\r\n */\r\n EventGenerator.prototype.generateEventsForChanges = function (changes, eventCache, eventRegistrations) {\r\n var _this = this;\r\n var events = [];\r\n var moves = [];\r\n changes.forEach(function (change) {\r\n if (change.type === Change.CHILD_CHANGED &&\r\n _this.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {\r\n moves.push(Change.childMovedChange(change.childName, change.snapshotNode));\r\n }\r\n });\r\n this.generateEventsForType_(events, Change.CHILD_REMOVED, changes, eventRegistrations, eventCache);\r\n this.generateEventsForType_(events, Change.CHILD_ADDED, changes, eventRegistrations, eventCache);\r\n this.generateEventsForType_(events, Change.CHILD_MOVED, moves, eventRegistrations, eventCache);\r\n this.generateEventsForType_(events, Change.CHILD_CHANGED, changes, eventRegistrations, eventCache);\r\n this.generateEventsForType_(events, Change.VALUE, changes, eventRegistrations, eventCache);\r\n return events;\r\n };\r\n /**\r\n * Given changes of a single change type, generate the corresponding events.\r\n *\r\n * @param {!Array.} events\r\n * @param {!string} eventType\r\n * @param {!Array.} changes\r\n * @param {!Array.} registrations\r\n * @param {!Node} eventCache\r\n * @private\r\n */\r\n EventGenerator.prototype.generateEventsForType_ = function (events, eventType, changes, registrations, eventCache) {\r\n var _this = this;\r\n var filteredChanges = changes.filter(function (change) { return change.type === eventType; });\r\n filteredChanges.sort(this.compareChanges_.bind(this));\r\n filteredChanges.forEach(function (change) {\r\n var materializedChange = _this.materializeSingleChange_(change, eventCache);\r\n registrations.forEach(function (registration) {\r\n if (registration.respondsTo(change.type)) {\r\n events.push(registration.createEvent(materializedChange, _this.query_));\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * @param {!Change} change\r\n * @param {!Node} eventCache\r\n * @return {!Change}\r\n * @private\r\n */\r\n EventGenerator.prototype.materializeSingleChange_ = function (change, eventCache) {\r\n if (change.type === 'value' || change.type === 'child_removed') {\r\n return change;\r\n }\r\n else {\r\n change.prevName = eventCache.getPredecessorChildName(\r\n /** @type {!string} */\r\n change.childName, change.snapshotNode, this.index_);\r\n return change;\r\n }\r\n };\r\n /**\r\n * @param {!Change} a\r\n * @param {!Change} b\r\n * @return {number}\r\n * @private\r\n */\r\n EventGenerator.prototype.compareChanges_ = function (a, b) {\r\n if (a.childName == null || b.childName == null) {\r\n throw util.assertionError('Should only compare child_ events.');\r\n }\r\n var aWrapped = new NamedNode(a.childName, a.snapshotNode);\r\n var bWrapped = new NamedNode(b.childName, b.snapshotNode);\r\n return this.index_.compare(aWrapped, bWrapped);\r\n };\r\n return EventGenerator;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A view represents a specific location and query that has 1 or more event registrations.\r\n *\r\n * It does several things:\r\n * - Maintains the list of event registrations for this location/query.\r\n * - Maintains a cache of the data visible for this location/query.\r\n * - Applies new operations (via applyOperation), updates the cache, and based on the event\r\n * registrations returns the set of events to be raised.\r\n * @constructor\r\n */\r\nvar View = /** @class */ (function () {\r\n /**\r\n *\r\n * @param {!Query} query_\r\n * @param {!ViewCache} initialViewCache\r\n */\r\n function View(query_, initialViewCache) {\r\n this.query_ = query_;\r\n this.eventRegistrations_ = [];\r\n var params = this.query_.getQueryParams();\r\n var indexFilter = new IndexedFilter(params.getIndex());\r\n var filter = params.getNodeFilter();\r\n /**\r\n * @type {ViewProcessor}\r\n * @private\r\n */\r\n this.processor_ = new ViewProcessor(filter);\r\n var initialServerCache = initialViewCache.getServerCache();\r\n var initialEventCache = initialViewCache.getEventCache();\r\n // Don't filter server node with other filter than index, wait for tagged listen\r\n var serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);\r\n var eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);\r\n var newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());\r\n var newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());\r\n /**\r\n * @type {!ViewCache}\r\n * @private\r\n */\r\n this.viewCache_ = new ViewCache(newEventCache, newServerCache);\r\n /**\r\n * @type {!EventGenerator}\r\n * @private\r\n */\r\n this.eventGenerator_ = new EventGenerator(this.query_);\r\n }\r\n /**\r\n * @return {!Query}\r\n */\r\n View.prototype.getQuery = function () {\r\n return this.query_;\r\n };\r\n /**\r\n * @return {?Node}\r\n */\r\n View.prototype.getServerCache = function () {\r\n return this.viewCache_.getServerCache().getNode();\r\n };\r\n /**\r\n * @param {!Path} path\r\n * @return {?Node}\r\n */\r\n View.prototype.getCompleteServerCache = function (path) {\r\n var cache = this.viewCache_.getCompleteServerSnap();\r\n if (cache) {\r\n // If this isn't a \"loadsAllData\" view, then cache isn't actually a complete cache and\r\n // we need to see if it contains the child we're interested in.\r\n if (this.query_.getQueryParams().loadsAllData() ||\r\n (!path.isEmpty() && !cache.getImmediateChild(path.getFront()).isEmpty())) {\r\n return cache.getChild(path);\r\n }\r\n }\r\n return null;\r\n };\r\n /**\r\n * @return {boolean}\r\n */\r\n View.prototype.isEmpty = function () {\r\n return this.eventRegistrations_.length === 0;\r\n };\r\n /**\r\n * @param {!EventRegistration} eventRegistration\r\n */\r\n View.prototype.addEventRegistration = function (eventRegistration) {\r\n this.eventRegistrations_.push(eventRegistration);\r\n };\r\n /**\r\n * @param {?EventRegistration} eventRegistration If null, remove all callbacks.\r\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\r\n * @return {!Array.} Cancel events, if cancelError was provided.\r\n */\r\n View.prototype.removeEventRegistration = function (eventRegistration, cancelError) {\r\n var cancelEvents = [];\r\n if (cancelError) {\r\n util.assert(eventRegistration == null, 'A cancel should cancel all event registrations.');\r\n var path_1 = this.query_.path;\r\n this.eventRegistrations_.forEach(function (registration) {\r\n cancelError /** @type {!Error} */ = cancelError;\r\n var maybeEvent = registration.createCancelEvent(cancelError, path_1);\r\n if (maybeEvent) {\r\n cancelEvents.push(maybeEvent);\r\n }\r\n });\r\n }\r\n if (eventRegistration) {\r\n var remaining = [];\r\n for (var i = 0; i < this.eventRegistrations_.length; ++i) {\r\n var existing = this.eventRegistrations_[i];\r\n if (!existing.matches(eventRegistration)) {\r\n remaining.push(existing);\r\n }\r\n else if (eventRegistration.hasAnyCallback()) {\r\n // We're removing just this one\r\n remaining = remaining.concat(this.eventRegistrations_.slice(i + 1));\r\n break;\r\n }\r\n }\r\n this.eventRegistrations_ = remaining;\r\n }\r\n else {\r\n this.eventRegistrations_ = [];\r\n }\r\n return cancelEvents;\r\n };\r\n /**\r\n * Applies the given Operation, updates our cache, and returns the appropriate events.\r\n *\r\n * @param {!Operation} operation\r\n * @param {!WriteTreeRef} writesCache\r\n * @param {?Node} completeServerCache\r\n * @return {!Array.}\r\n */\r\n View.prototype.applyOperation = function (operation, writesCache, completeServerCache) {\r\n if (operation.type === OperationType.MERGE &&\r\n operation.source.queryId !== null) {\r\n util.assert(this.viewCache_.getCompleteServerSnap(), 'We should always have a full cache before handling merges');\r\n util.assert(this.viewCache_.getCompleteEventSnap(), 'Missing event cache, even though we have a server cache');\r\n }\r\n var oldViewCache = this.viewCache_;\r\n var result = this.processor_.applyOperation(oldViewCache, operation, writesCache, completeServerCache);\r\n this.processor_.assertIndexed(result.viewCache);\r\n util.assert(result.viewCache.getServerCache().isFullyInitialized() ||\r\n !oldViewCache.getServerCache().isFullyInitialized(), 'Once a server snap is complete, it should never go back');\r\n this.viewCache_ = result.viewCache;\r\n return this.generateEventsForChanges_(result.changes, result.viewCache.getEventCache().getNode(), null);\r\n };\r\n /**\r\n * @param {!EventRegistration} registration\r\n * @return {!Array.}\r\n */\r\n View.prototype.getInitialEvents = function (registration) {\r\n var eventSnap = this.viewCache_.getEventCache();\r\n var initialChanges = [];\r\n if (!eventSnap.getNode().isLeafNode()) {\r\n var eventNode = eventSnap.getNode();\r\n eventNode.forEachChild(PRIORITY_INDEX, function (key, childNode) {\r\n initialChanges.push(Change.childAddedChange(key, childNode));\r\n });\r\n }\r\n if (eventSnap.isFullyInitialized()) {\r\n initialChanges.push(Change.valueChange(eventSnap.getNode()));\r\n }\r\n return this.generateEventsForChanges_(initialChanges, eventSnap.getNode(), registration);\r\n };\r\n /**\r\n * @private\r\n * @param {!Array.} changes\r\n * @param {!Node} eventCache\r\n * @param {EventRegistration=} eventRegistration\r\n * @return {!Array.}\r\n */\r\n View.prototype.generateEventsForChanges_ = function (changes, eventCache, eventRegistration) {\r\n var registrations = eventRegistration\r\n ? [eventRegistration]\r\n : this.eventRegistrations_;\r\n return this.eventGenerator_.generateEventsForChanges(changes, eventCache, registrations);\r\n };\r\n return View;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar __referenceConstructor$1;\r\n/**\r\n * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to\r\n * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes\r\n * and user writes (set, transaction, update).\r\n *\r\n * It's responsible for:\r\n * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).\r\n * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,\r\n * applyUserOverwrite, etc.)\r\n */\r\nvar SyncPoint = /** @class */ (function () {\r\n function SyncPoint() {\r\n /**\r\n * The Views being tracked at this location in the tree, stored as a map where the key is a\r\n * queryId and the value is the View for that query.\r\n *\r\n * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).\r\n *\r\n * @type {!Object.}\r\n * @private\r\n */\r\n this.views_ = {};\r\n }\r\n Object.defineProperty(SyncPoint, \"__referenceConstructor\", {\r\n get: function () {\r\n util.assert(__referenceConstructor$1, 'Reference.ts has not been loaded');\r\n return __referenceConstructor$1;\r\n },\r\n set: function (val) {\r\n util.assert(!__referenceConstructor$1, '__referenceConstructor has already been defined');\r\n __referenceConstructor$1 = val;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n /**\r\n * @return {boolean}\r\n */\r\n SyncPoint.prototype.isEmpty = function () {\r\n return util.isEmpty(this.views_);\r\n };\r\n /**\r\n *\r\n * @param {!Operation} operation\r\n * @param {!WriteTreeRef} writesCache\r\n * @param {?Node} optCompleteServerCache\r\n * @return {!Array.}\r\n */\r\n SyncPoint.prototype.applyOperation = function (operation, writesCache, optCompleteServerCache) {\r\n var queryId = operation.source.queryId;\r\n if (queryId !== null) {\r\n var view = util.safeGet(this.views_, queryId);\r\n util.assert(view != null, 'SyncTree gave us an op for an invalid query.');\r\n return view.applyOperation(operation, writesCache, optCompleteServerCache);\r\n }\r\n else {\r\n var events_1 = [];\r\n util.forEach(this.views_, function (key, view) {\r\n events_1 = events_1.concat(view.applyOperation(operation, writesCache, optCompleteServerCache));\r\n });\r\n return events_1;\r\n }\r\n };\r\n /**\r\n * Add an event callback for the specified query.\r\n *\r\n * @param {!Query} query\r\n * @param {!EventRegistration} eventRegistration\r\n * @param {!WriteTreeRef} writesCache\r\n * @param {?Node} serverCache Complete server cache, if we have it.\r\n * @param {boolean} serverCacheComplete\r\n * @return {!Array.} Events to raise.\r\n */\r\n SyncPoint.prototype.addEventRegistration = function (query, eventRegistration, writesCache, serverCache, serverCacheComplete) {\r\n var queryId = query.queryIdentifier();\r\n var view = util.safeGet(this.views_, queryId);\r\n if (!view) {\r\n // TODO: make writesCache take flag for complete server node\r\n var eventCache = writesCache.calcCompleteEventCache(serverCacheComplete ? serverCache : null);\r\n var eventCacheComplete = false;\r\n if (eventCache) {\r\n eventCacheComplete = true;\r\n }\r\n else if (serverCache instanceof ChildrenNode) {\r\n eventCache = writesCache.calcCompleteEventChildren(serverCache);\r\n eventCacheComplete = false;\r\n }\r\n else {\r\n eventCache = ChildrenNode.EMPTY_NODE;\r\n eventCacheComplete = false;\r\n }\r\n var viewCache = new ViewCache(new CacheNode(\r\n /** @type {!Node} */ (eventCache), eventCacheComplete, false), new CacheNode(\r\n /** @type {!Node} */ (serverCache), serverCacheComplete, false));\r\n view = new View(query, viewCache);\r\n this.views_[queryId] = view;\r\n }\r\n // This is guaranteed to exist now, we just created anything that was missing\r\n view.addEventRegistration(eventRegistration);\r\n return view.getInitialEvents(eventRegistration);\r\n };\r\n /**\r\n * Remove event callback(s). Return cancelEvents if a cancelError is specified.\r\n *\r\n * If query is the default query, we'll check all views for the specified eventRegistration.\r\n * If eventRegistration is null, we'll remove all callbacks for the specified view(s).\r\n *\r\n * @param {!Query} query\r\n * @param {?EventRegistration} eventRegistration If null, remove all callbacks.\r\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\r\n * @return {{removed:!Array., events:!Array.}} removed queries and any cancel events\r\n */\r\n SyncPoint.prototype.removeEventRegistration = function (query, eventRegistration, cancelError) {\r\n var queryId = query.queryIdentifier();\r\n var removed = [];\r\n var cancelEvents = [];\r\n var hadCompleteView = this.hasCompleteView();\r\n if (queryId === 'default') {\r\n // When you do ref.off(...), we search all views for the registration to remove.\r\n var self_1 = this;\r\n util.forEach(this.views_, function (viewQueryId, view) {\r\n cancelEvents = cancelEvents.concat(view.removeEventRegistration(eventRegistration, cancelError));\r\n if (view.isEmpty()) {\r\n delete self_1.views_[viewQueryId];\r\n // We'll deal with complete views later.\r\n if (!view\r\n .getQuery()\r\n .getQueryParams()\r\n .loadsAllData()) {\r\n removed.push(view.getQuery());\r\n }\r\n }\r\n });\r\n }\r\n else {\r\n // remove the callback from the specific view.\r\n var view = util.safeGet(this.views_, queryId);\r\n if (view) {\r\n cancelEvents = cancelEvents.concat(view.removeEventRegistration(eventRegistration, cancelError));\r\n if (view.isEmpty()) {\r\n delete this.views_[queryId];\r\n // We'll deal with complete views later.\r\n if (!view\r\n .getQuery()\r\n .getQueryParams()\r\n .loadsAllData()) {\r\n removed.push(view.getQuery());\r\n }\r\n }\r\n }\r\n }\r\n if (hadCompleteView && !this.hasCompleteView()) {\r\n // We removed our last complete view.\r\n removed.push(new SyncPoint.__referenceConstructor(query.repo, query.path));\r\n }\r\n return { removed: removed, events: cancelEvents };\r\n };\r\n /**\r\n * @return {!Array.}\r\n */\r\n SyncPoint.prototype.getQueryViews = function () {\r\n var _this = this;\r\n var values = Object.keys(this.views_).map(function (key) { return _this.views_[key]; });\r\n return values.filter(function (view) {\r\n return !view\r\n .getQuery()\r\n .getQueryParams()\r\n .loadsAllData();\r\n });\r\n };\r\n /**\r\n *\r\n * @param {!Path} path The path to the desired complete snapshot\r\n * @return {?Node} A complete cache, if it exists\r\n */\r\n SyncPoint.prototype.getCompleteServerCache = function (path) {\r\n var serverCache = null;\r\n util.forEach(this.views_, function (key, view) {\r\n serverCache = serverCache || view.getCompleteServerCache(path);\r\n });\r\n return serverCache;\r\n };\r\n /**\r\n * @param {!Query} query\r\n * @return {?View}\r\n */\r\n SyncPoint.prototype.viewForQuery = function (query) {\r\n var params = query.getQueryParams();\r\n if (params.loadsAllData()) {\r\n return this.getCompleteView();\r\n }\r\n else {\r\n var queryId = query.queryIdentifier();\r\n return util.safeGet(this.views_, queryId);\r\n }\r\n };\r\n /**\r\n * @param {!Query} query\r\n * @return {boolean}\r\n */\r\n SyncPoint.prototype.viewExistsForQuery = function (query) {\r\n return this.viewForQuery(query) != null;\r\n };\r\n /**\r\n * @return {boolean}\r\n */\r\n SyncPoint.prototype.hasCompleteView = function () {\r\n return this.getCompleteView() != null;\r\n };\r\n /**\r\n * @return {?View}\r\n */\r\n SyncPoint.prototype.getCompleteView = function () {\r\n var completeView = util.findValue(this.views_, function (view) {\r\n return view\r\n .getQuery()\r\n .getQueryParams()\r\n .loadsAllData();\r\n });\r\n return completeView || null;\r\n };\r\n return SyncPoint;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with\r\n * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write\r\n * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write\r\n * to reflect the write added.\r\n *\r\n * @constructor\r\n * @param {!ImmutableTree.} writeTree\r\n */\r\nvar CompoundWrite = /** @class */ (function () {\r\n function CompoundWrite(writeTree_) {\r\n this.writeTree_ = writeTree_;\r\n }\r\n /**\r\n * @param {!Path} path\r\n * @param {!Node} node\r\n * @return {!CompoundWrite}\r\n */\r\n CompoundWrite.prototype.addWrite = function (path, node) {\r\n if (path.isEmpty()) {\r\n return new CompoundWrite(new ImmutableTree(node));\r\n }\r\n else {\r\n var rootmost = this.writeTree_.findRootMostValueAndPath(path);\r\n if (rootmost != null) {\r\n var rootMostPath = rootmost.path;\r\n var value = rootmost.value;\r\n var relativePath = Path.relativePath(rootMostPath, path);\r\n value = value.updateChild(relativePath, node);\r\n return new CompoundWrite(this.writeTree_.set(rootMostPath, value));\r\n }\r\n else {\r\n var subtree = new ImmutableTree(node);\r\n var newWriteTree = this.writeTree_.setTree(path, subtree);\r\n return new CompoundWrite(newWriteTree);\r\n }\r\n }\r\n };\r\n /**\r\n * @param {!Path} path\r\n * @param {!Object.} updates\r\n * @return {!CompoundWrite}\r\n */\r\n CompoundWrite.prototype.addWrites = function (path, updates) {\r\n var newWrite = this;\r\n util.forEach(updates, function (childKey, node) {\r\n newWrite = newWrite.addWrite(path.child(childKey), node);\r\n });\r\n return newWrite;\r\n };\r\n /**\r\n * Will remove a write at the given path and deeper paths. This will not modify a write at a higher\r\n * location, which must be removed by calling this method with that path.\r\n *\r\n * @param {!Path} path The path at which a write and all deeper writes should be removed\r\n * @return {!CompoundWrite} The new CompoundWrite with the removed path\r\n */\r\n CompoundWrite.prototype.removeWrite = function (path) {\r\n if (path.isEmpty()) {\r\n return CompoundWrite.Empty;\r\n }\r\n else {\r\n var newWriteTree = this.writeTree_.setTree(path, ImmutableTree.Empty);\r\n return new CompoundWrite(newWriteTree);\r\n }\r\n };\r\n /**\r\n * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be\r\n * considered \"complete\".\r\n *\r\n * @param {!Path} path The path to check for\r\n * @return {boolean} Whether there is a complete write at that path\r\n */\r\n CompoundWrite.prototype.hasCompleteWrite = function (path) {\r\n return this.getCompleteNode(path) != null;\r\n };\r\n /**\r\n * Returns a node for a path if and only if the node is a \"complete\" overwrite at that path. This will not aggregate\r\n * writes from deeper paths, but will return child nodes from a more shallow path.\r\n *\r\n * @param {!Path} path The path to get a complete write\r\n * @return {?Node} The node if complete at that path, or null otherwise.\r\n */\r\n CompoundWrite.prototype.getCompleteNode = function (path) {\r\n var rootmost = this.writeTree_.findRootMostValueAndPath(path);\r\n if (rootmost != null) {\r\n return this.writeTree_\r\n .get(rootmost.path)\r\n .getChild(Path.relativePath(rootmost.path, path));\r\n }\r\n else {\r\n return null;\r\n }\r\n };\r\n /**\r\n * Returns all children that are guaranteed to be a complete overwrite.\r\n *\r\n * @return {!Array.} A list of all complete children.\r\n */\r\n CompoundWrite.prototype.getCompleteChildren = function () {\r\n var children = [];\r\n var node = this.writeTree_.value;\r\n if (node != null) {\r\n // If it's a leaf node, it has no children; so nothing to do.\r\n if (!node.isLeafNode()) {\r\n node.forEachChild(PRIORITY_INDEX, function (childName, childNode) {\r\n children.push(new NamedNode(childName, childNode));\r\n });\r\n }\r\n }\r\n else {\r\n this.writeTree_.children.inorderTraversal(function (childName, childTree) {\r\n if (childTree.value != null) {\r\n children.push(new NamedNode(childName, childTree.value));\r\n }\r\n });\r\n }\r\n return children;\r\n };\r\n /**\r\n * @param {!Path} path\r\n * @return {!CompoundWrite}\r\n */\r\n CompoundWrite.prototype.childCompoundWrite = function (path) {\r\n if (path.isEmpty()) {\r\n return this;\r\n }\r\n else {\r\n var shadowingNode = this.getCompleteNode(path);\r\n if (shadowingNode != null) {\r\n return new CompoundWrite(new ImmutableTree(shadowingNode));\r\n }\r\n else {\r\n return new CompoundWrite(this.writeTree_.subtree(path));\r\n }\r\n }\r\n };\r\n /**\r\n * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.\r\n * @return {boolean} Whether this CompoundWrite is empty\r\n */\r\n CompoundWrite.prototype.isEmpty = function () {\r\n return this.writeTree_.isEmpty();\r\n };\r\n /**\r\n * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the\r\n * node\r\n * @param {!Node} node The node to apply this CompoundWrite to\r\n * @return {!Node} The node with all writes applied\r\n */\r\n CompoundWrite.prototype.apply = function (node) {\r\n return CompoundWrite.applySubtreeWrite_(Path.Empty, this.writeTree_, node);\r\n };\r\n /**\r\n * @type {!CompoundWrite}\r\n */\r\n CompoundWrite.Empty = new CompoundWrite(new ImmutableTree(null));\r\n /**\r\n * @param {!Path} relativePath\r\n * @param {!ImmutableTree.} writeTree\r\n * @param {!Node} node\r\n * @return {!Node}\r\n * @private\r\n */\r\n CompoundWrite.applySubtreeWrite_ = function (relativePath, writeTree, node) {\r\n if (writeTree.value != null) {\r\n // Since there a write is always a leaf, we're done here\r\n return node.updateChild(relativePath, writeTree.value);\r\n }\r\n else {\r\n var priorityWrite_1 = null;\r\n writeTree.children.inorderTraversal(function (childKey, childTree) {\r\n if (childKey === '.priority') {\r\n // Apply priorities at the end so we don't update priorities for either empty nodes or forget\r\n // to apply priorities to empty nodes that are later filled\r\n util.assert(childTree.value !== null, 'Priority writes must always be leaf nodes');\r\n priorityWrite_1 = childTree.value;\r\n }\r\n else {\r\n node = CompoundWrite.applySubtreeWrite_(relativePath.child(childKey), childTree, node);\r\n }\r\n });\r\n // If there was a priority write, we only apply it if the node is not empty\r\n if (!node.getChild(relativePath).isEmpty() && priorityWrite_1 !== null) {\r\n node = node.updateChild(relativePath.child('.priority'), priorityWrite_1);\r\n }\r\n return node;\r\n }\r\n };\r\n return CompoundWrite;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * WriteTree tracks all pending user-initiated writes and has methods to calculate the result of merging them\r\n * with underlying server data (to create \"event cache\" data). Pending writes are added with addOverwrite()\r\n * and addMerge(), and removed with removeWrite().\r\n *\r\n * @constructor\r\n */\r\nvar WriteTree = /** @class */ (function () {\r\n function WriteTree() {\r\n /**\r\n * A tree tracking the result of applying all visible writes. This does not include transactions with\r\n * applyLocally=false or writes that are completely shadowed by other writes.\r\n *\r\n * @type {!CompoundWrite}\r\n * @private\r\n */\r\n this.visibleWrites_ = CompoundWrite.Empty;\r\n /**\r\n * A list of all pending writes, regardless of visibility and shadowed-ness. Used to calculate arbitrary\r\n * sets of the changed data, such as hidden writes (from transactions) or changes with certain writes excluded (also\r\n * used by transactions).\r\n *\r\n * @type {!Array.}\r\n * @private\r\n */\r\n this.allWrites_ = [];\r\n this.lastWriteId_ = -1;\r\n }\r\n /**\r\n * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.\r\n *\r\n * @param {!Path} path\r\n * @return {!WriteTreeRef}\r\n */\r\n WriteTree.prototype.childWrites = function (path) {\r\n return new WriteTreeRef(path, this);\r\n };\r\n /**\r\n * Record a new overwrite from user code.\r\n *\r\n * @param {!Path} path\r\n * @param {!Node} snap\r\n * @param {!number} writeId\r\n * @param {boolean=} visible This is set to false by some transactions. It should be excluded from event caches\r\n */\r\n WriteTree.prototype.addOverwrite = function (path, snap, writeId, visible) {\r\n util.assert(writeId > this.lastWriteId_, 'Stacking an older write on top of newer ones');\r\n if (visible === undefined) {\r\n visible = true;\r\n }\r\n this.allWrites_.push({\r\n path: path,\r\n snap: snap,\r\n writeId: writeId,\r\n visible: visible\r\n });\r\n if (visible) {\r\n this.visibleWrites_ = this.visibleWrites_.addWrite(path, snap);\r\n }\r\n this.lastWriteId_ = writeId;\r\n };\r\n /**\r\n * Record a new merge from user code.\r\n *\r\n * @param {!Path} path\r\n * @param {!Object.} changedChildren\r\n * @param {!number} writeId\r\n */\r\n WriteTree.prototype.addMerge = function (path, changedChildren, writeId) {\r\n util.assert(writeId > this.lastWriteId_, 'Stacking an older merge on top of newer ones');\r\n this.allWrites_.push({\r\n path: path,\r\n children: changedChildren,\r\n writeId: writeId,\r\n visible: true\r\n });\r\n this.visibleWrites_ = this.visibleWrites_.addWrites(path, changedChildren);\r\n this.lastWriteId_ = writeId;\r\n };\r\n /**\r\n * @param {!number} writeId\r\n * @return {?WriteRecord}\r\n */\r\n WriteTree.prototype.getWrite = function (writeId) {\r\n for (var i = 0; i < this.allWrites_.length; i++) {\r\n var record = this.allWrites_[i];\r\n if (record.writeId === writeId) {\r\n return record;\r\n }\r\n }\r\n return null;\r\n };\r\n /**\r\n * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates\r\n * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.\r\n *\r\n * @param {!number} writeId\r\n * @return {boolean} true if the write may have been visible (meaning we'll need to reevaluate / raise\r\n * events as a result).\r\n */\r\n WriteTree.prototype.removeWrite = function (writeId) {\r\n // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied\r\n // out of order.\r\n //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;\r\n //assert(validClear, \"Either we don't have this write, or it's the first one in the queue\");\r\n var _this = this;\r\n var idx = this.allWrites_.findIndex(function (s) {\r\n return s.writeId === writeId;\r\n });\r\n util.assert(idx >= 0, 'removeWrite called with nonexistent writeId.');\r\n var writeToRemove = this.allWrites_[idx];\r\n this.allWrites_.splice(idx, 1);\r\n var removedWriteWasVisible = writeToRemove.visible;\r\n var removedWriteOverlapsWithOtherWrites = false;\r\n var i = this.allWrites_.length - 1;\r\n while (removedWriteWasVisible && i >= 0) {\r\n var currentWrite = this.allWrites_[i];\r\n if (currentWrite.visible) {\r\n if (i >= idx &&\r\n this.recordContainsPath_(currentWrite, writeToRemove.path)) {\r\n // The removed write was completely shadowed by a subsequent write.\r\n removedWriteWasVisible = false;\r\n }\r\n else if (writeToRemove.path.contains(currentWrite.path)) {\r\n // Either we're covering some writes or they're covering part of us (depending on which came first).\r\n removedWriteOverlapsWithOtherWrites = true;\r\n }\r\n }\r\n i--;\r\n }\r\n if (!removedWriteWasVisible) {\r\n return false;\r\n }\r\n else if (removedWriteOverlapsWithOtherWrites) {\r\n // There's some shadowing going on. Just rebuild the visible writes from scratch.\r\n this.resetTree_();\r\n return true;\r\n }\r\n else {\r\n // There's no shadowing. We can safely just remove the write(s) from visibleWrites.\r\n if (writeToRemove.snap) {\r\n this.visibleWrites_ = this.visibleWrites_.removeWrite(writeToRemove.path);\r\n }\r\n else {\r\n var children = writeToRemove.children;\r\n util.forEach(children, function (childName) {\r\n _this.visibleWrites_ = _this.visibleWrites_.removeWrite(writeToRemove.path.child(childName));\r\n });\r\n }\r\n return true;\r\n }\r\n };\r\n /**\r\n * Return a complete snapshot for the given path if there's visible write data at that path, else null.\r\n * No server data is considered.\r\n *\r\n * @param {!Path} path\r\n * @return {?Node}\r\n */\r\n WriteTree.prototype.getCompleteWriteData = function (path) {\r\n return this.visibleWrites_.getCompleteNode(path);\r\n };\r\n /**\r\n * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden\r\n * writes), attempt to calculate a complete snapshot for the given path\r\n *\r\n * @param {!Path} treePath\r\n * @param {?Node} completeServerCache\r\n * @param {Array.=} writeIdsToExclude An optional set to be excluded\r\n * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false\r\n * @return {?Node}\r\n */\r\n WriteTree.prototype.calcCompleteEventCache = function (treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {\r\n if (!writeIdsToExclude && !includeHiddenWrites) {\r\n var shadowingNode = this.visibleWrites_.getCompleteNode(treePath);\r\n if (shadowingNode != null) {\r\n return shadowingNode;\r\n }\r\n else {\r\n var subMerge = this.visibleWrites_.childCompoundWrite(treePath);\r\n if (subMerge.isEmpty()) {\r\n return completeServerCache;\r\n }\r\n else if (completeServerCache == null &&\r\n !subMerge.hasCompleteWrite(Path.Empty)) {\r\n // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow\r\n return null;\r\n }\r\n else {\r\n var layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;\r\n return subMerge.apply(layeredCache);\r\n }\r\n }\r\n }\r\n else {\r\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\r\n if (!includeHiddenWrites && merge.isEmpty()) {\r\n return completeServerCache;\r\n }\r\n else {\r\n // If the server cache is null, and we don't have a complete cache, we need to return null\r\n if (!includeHiddenWrites &&\r\n completeServerCache == null &&\r\n !merge.hasCompleteWrite(Path.Empty)) {\r\n return null;\r\n }\r\n else {\r\n var filter = function (write) {\r\n return ((write.visible || includeHiddenWrites) &&\r\n (!writeIdsToExclude ||\r\n !~writeIdsToExclude.indexOf(write.writeId)) &&\r\n (write.path.contains(treePath) || treePath.contains(write.path)));\r\n };\r\n var mergeAtPath = WriteTree.layerTree_(this.allWrites_, filter, treePath);\r\n var layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;\r\n return mergeAtPath.apply(layeredCache);\r\n }\r\n }\r\n }\r\n };\r\n /**\r\n * With optional, underlying server data, attempt to return a children node of children that we have complete data for.\r\n * Used when creating new views, to pre-fill their complete event children snapshot.\r\n *\r\n * @param {!Path} treePath\r\n * @param {?ChildrenNode} completeServerChildren\r\n * @return {!ChildrenNode}\r\n */\r\n WriteTree.prototype.calcCompleteEventChildren = function (treePath, completeServerChildren) {\r\n var completeChildren = ChildrenNode.EMPTY_NODE;\r\n var topLevelSet = this.visibleWrites_.getCompleteNode(treePath);\r\n if (topLevelSet) {\r\n if (!topLevelSet.isLeafNode()) {\r\n // we're shadowing everything. Return the children.\r\n topLevelSet.forEachChild(PRIORITY_INDEX, function (childName, childSnap) {\r\n completeChildren = completeChildren.updateImmediateChild(childName, childSnap);\r\n });\r\n }\r\n return completeChildren;\r\n }\r\n else if (completeServerChildren) {\r\n // Layer any children we have on top of this\r\n // We know we don't have a top-level set, so just enumerate existing children\r\n var merge_1 = this.visibleWrites_.childCompoundWrite(treePath);\r\n completeServerChildren.forEachChild(PRIORITY_INDEX, function (childName, childNode) {\r\n var node = merge_1\r\n .childCompoundWrite(new Path(childName))\r\n .apply(childNode);\r\n completeChildren = completeChildren.updateImmediateChild(childName, node);\r\n });\r\n // Add any complete children we have from the set\r\n merge_1.getCompleteChildren().forEach(function (namedNode) {\r\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\r\n });\r\n return completeChildren;\r\n }\r\n else {\r\n // We don't have anything to layer on top of. Layer on any children we have\r\n // Note that we can return an empty snap if we have a defined delete\r\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\r\n merge.getCompleteChildren().forEach(function (namedNode) {\r\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\r\n });\r\n return completeChildren;\r\n }\r\n };\r\n /**\r\n * Given that the underlying server data has updated, determine what, if anything, needs to be\r\n * applied to the event cache.\r\n *\r\n * Possibilities:\r\n *\r\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\r\n *\r\n * 2. Some write is completely shadowing. No events to be raised\r\n *\r\n * 3. Is partially shadowed. Events\r\n *\r\n * Either existingEventSnap or existingServerSnap must exist\r\n *\r\n * @param {!Path} treePath\r\n * @param {!Path} childPath\r\n * @param {?Node} existingEventSnap\r\n * @param {?Node} existingServerSnap\r\n * @return {?Node}\r\n */\r\n WriteTree.prototype.calcEventCacheAfterServerOverwrite = function (treePath, childPath, existingEventSnap, existingServerSnap) {\r\n util.assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');\r\n var path = treePath.child(childPath);\r\n if (this.visibleWrites_.hasCompleteWrite(path)) {\r\n // At this point we can probably guarantee that we're in case 2, meaning no events\r\n // May need to check visibility while doing the findRootMostValueAndPath call\r\n return null;\r\n }\r\n else {\r\n // No complete shadowing. We're either partially shadowing or not shadowing at all.\r\n var childMerge = this.visibleWrites_.childCompoundWrite(path);\r\n if (childMerge.isEmpty()) {\r\n // We're not shadowing at all. Case 1\r\n return existingServerSnap.getChild(childPath);\r\n }\r\n else {\r\n // This could be more efficient if the serverNode + updates doesn't change the eventSnap\r\n // However this is tricky to find out, since user updates don't necessary change the server\r\n // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server\r\n // adds nodes, but doesn't change any existing writes. It is therefore not enough to\r\n // only check if the updates change the serverNode.\r\n // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?\r\n return childMerge.apply(existingServerSnap.getChild(childPath));\r\n }\r\n }\r\n };\r\n /**\r\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\r\n * complete child for this ChildKey.\r\n *\r\n * @param {!Path} treePath\r\n * @param {!string} childKey\r\n * @param {!CacheNode} existingServerSnap\r\n * @return {?Node}\r\n */\r\n WriteTree.prototype.calcCompleteChild = function (treePath, childKey, existingServerSnap) {\r\n var path = treePath.child(childKey);\r\n var shadowingNode = this.visibleWrites_.getCompleteNode(path);\r\n if (shadowingNode != null) {\r\n return shadowingNode;\r\n }\r\n else {\r\n if (existingServerSnap.isCompleteForChild(childKey)) {\r\n var childMerge = this.visibleWrites_.childCompoundWrite(path);\r\n return childMerge.apply(existingServerSnap.getNode().getImmediateChild(childKey));\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n };\r\n /**\r\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\r\n * a higher path, this will return the child of that write relative to the write and this path.\r\n * Returns null if there is no write at this path.\r\n *\r\n * @param {!Path} path\r\n * @return {?Node}\r\n */\r\n WriteTree.prototype.shadowingWrite = function (path) {\r\n return this.visibleWrites_.getCompleteNode(path);\r\n };\r\n /**\r\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\r\n * the window, but may now be in the window.\r\n *\r\n * @param {!Path} treePath\r\n * @param {?Node} completeServerData\r\n * @param {!NamedNode} startPost\r\n * @param {!number} count\r\n * @param {boolean} reverse\r\n * @param {!Index} index\r\n * @return {!Array.}\r\n */\r\n WriteTree.prototype.calcIndexedSlice = function (treePath, completeServerData, startPost, count, reverse, index) {\r\n var toIterate;\r\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\r\n var shadowingNode = merge.getCompleteNode(Path.Empty);\r\n if (shadowingNode != null) {\r\n toIterate = shadowingNode;\r\n }\r\n else if (completeServerData != null) {\r\n toIterate = merge.apply(completeServerData);\r\n }\r\n else {\r\n // no children to iterate on\r\n return [];\r\n }\r\n toIterate = toIterate.withIndex(index);\r\n if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {\r\n var nodes = [];\r\n var cmp = index.getCompare();\r\n var iter = reverse\r\n ? toIterate.getReverseIteratorFrom(startPost, index)\r\n : toIterate.getIteratorFrom(startPost, index);\r\n var next = iter.getNext();\r\n while (next && nodes.length < count) {\r\n if (cmp(next, startPost) !== 0) {\r\n nodes.push(next);\r\n }\r\n next = iter.getNext();\r\n }\r\n return nodes;\r\n }\r\n else {\r\n return [];\r\n }\r\n };\r\n /**\r\n * @param {!WriteRecord} writeRecord\r\n * @param {!Path} path\r\n * @return {boolean}\r\n * @private\r\n */\r\n WriteTree.prototype.recordContainsPath_ = function (writeRecord, path) {\r\n if (writeRecord.snap) {\r\n return writeRecord.path.contains(path);\r\n }\r\n else {\r\n // findKey can return undefined, so use !! to coerce to boolean\r\n return !!util.findKey(writeRecord.children, function (childSnap, childName) {\r\n return writeRecord.path.child(childName).contains(path);\r\n });\r\n }\r\n };\r\n /**\r\n * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots\r\n * @private\r\n */\r\n WriteTree.prototype.resetTree_ = function () {\r\n this.visibleWrites_ = WriteTree.layerTree_(this.allWrites_, WriteTree.DefaultFilter_, Path.Empty);\r\n if (this.allWrites_.length > 0) {\r\n this.lastWriteId_ = this.allWrites_[this.allWrites_.length - 1].writeId;\r\n }\r\n else {\r\n this.lastWriteId_ = -1;\r\n }\r\n };\r\n /**\r\n * The default filter used when constructing the tree. Keep everything that's visible.\r\n *\r\n * @param {!WriteRecord} write\r\n * @return {boolean}\r\n * @private\r\n */\r\n WriteTree.DefaultFilter_ = function (write) {\r\n return write.visible;\r\n };\r\n /**\r\n * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of\r\n * event data at that path.\r\n *\r\n * @param {!Array.} writes\r\n * @param {!function(!WriteRecord):boolean} filter\r\n * @param {!Path} treeRoot\r\n * @return {!CompoundWrite}\r\n * @private\r\n */\r\n WriteTree.layerTree_ = function (writes, filter, treeRoot) {\r\n var compoundWrite = CompoundWrite.Empty;\r\n for (var i = 0; i < writes.length; ++i) {\r\n var write = writes[i];\r\n // Theory, a later set will either:\r\n // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction\r\n // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction\r\n if (filter(write)) {\r\n var writePath = write.path;\r\n var relativePath = void 0;\r\n if (write.snap) {\r\n if (treeRoot.contains(writePath)) {\r\n relativePath = Path.relativePath(treeRoot, writePath);\r\n compoundWrite = compoundWrite.addWrite(relativePath, write.snap);\r\n }\r\n else if (writePath.contains(treeRoot)) {\r\n relativePath = Path.relativePath(writePath, treeRoot);\r\n compoundWrite = compoundWrite.addWrite(Path.Empty, write.snap.getChild(relativePath));\r\n }\r\n }\r\n else if (write.children) {\r\n if (treeRoot.contains(writePath)) {\r\n relativePath = Path.relativePath(treeRoot, writePath);\r\n compoundWrite = compoundWrite.addWrites(relativePath, write.children);\r\n }\r\n else if (writePath.contains(treeRoot)) {\r\n relativePath = Path.relativePath(writePath, treeRoot);\r\n if (relativePath.isEmpty()) {\r\n compoundWrite = compoundWrite.addWrites(Path.Empty, write.children);\r\n }\r\n else {\r\n var child = util.safeGet(write.children, relativePath.getFront());\r\n if (child) {\r\n // There exists a child in this node that matches the root path\r\n var deepNode = child.getChild(relativePath.popFront());\r\n compoundWrite = compoundWrite.addWrite(Path.Empty, deepNode);\r\n }\r\n }\r\n }\r\n }\r\n else {\r\n throw util.assertionError('WriteRecord should have .snap or .children');\r\n }\r\n }\r\n }\r\n return compoundWrite;\r\n };\r\n return WriteTree;\r\n}());\r\n/**\r\n * A WriteTreeRef wraps a WriteTree and a path, for convenient access to a particular subtree. All of the methods\r\n * just proxy to the underlying WriteTree.\r\n *\r\n * @constructor\r\n */\r\nvar WriteTreeRef = /** @class */ (function () {\r\n /**\r\n * @param {!Path} path\r\n * @param {!WriteTree} writeTree\r\n */\r\n function WriteTreeRef(path, writeTree) {\r\n this.treePath_ = path;\r\n this.writeTree_ = writeTree;\r\n }\r\n /**\r\n * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used\r\n * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node\r\n * can lead to a more expensive calculation.\r\n *\r\n * @param {?Node} completeServerCache\r\n * @param {Array.=} writeIdsToExclude Optional writes to exclude.\r\n * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false\r\n * @return {?Node}\r\n */\r\n WriteTreeRef.prototype.calcCompleteEventCache = function (completeServerCache, writeIdsToExclude, includeHiddenWrites) {\r\n return this.writeTree_.calcCompleteEventCache(this.treePath_, completeServerCache, writeIdsToExclude, includeHiddenWrites);\r\n };\r\n /**\r\n * If possible, returns a children node containing all of the complete children we have data for. The returned data is a\r\n * mix of the given server data and write data.\r\n *\r\n * @param {?ChildrenNode} completeServerChildren\r\n * @return {!ChildrenNode}\r\n */\r\n WriteTreeRef.prototype.calcCompleteEventChildren = function (completeServerChildren) {\r\n return this.writeTree_.calcCompleteEventChildren(this.treePath_, completeServerChildren);\r\n };\r\n /**\r\n * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,\r\n * if anything, needs to be applied to the event cache.\r\n *\r\n * Possibilities:\r\n *\r\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\r\n *\r\n * 2. Some write is completely shadowing. No events to be raised\r\n *\r\n * 3. Is partially shadowed. Events should be raised\r\n *\r\n * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert\r\n *\r\n * @param {!Path} path\r\n * @param {?Node} existingEventSnap\r\n * @param {?Node} existingServerSnap\r\n * @return {?Node}\r\n */\r\n WriteTreeRef.prototype.calcEventCacheAfterServerOverwrite = function (path, existingEventSnap, existingServerSnap) {\r\n return this.writeTree_.calcEventCacheAfterServerOverwrite(this.treePath_, path, existingEventSnap, existingServerSnap);\r\n };\r\n /**\r\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\r\n * a higher path, this will return the child of that write relative to the write and this path.\r\n * Returns null if there is no write at this path.\r\n *\r\n * @param {!Path} path\r\n * @return {?Node}\r\n */\r\n WriteTreeRef.prototype.shadowingWrite = function (path) {\r\n return this.writeTree_.shadowingWrite(this.treePath_.child(path));\r\n };\r\n /**\r\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\r\n * the window, but may now be in the window\r\n *\r\n * @param {?Node} completeServerData\r\n * @param {!NamedNode} startPost\r\n * @param {!number} count\r\n * @param {boolean} reverse\r\n * @param {!Index} index\r\n * @return {!Array.}\r\n */\r\n WriteTreeRef.prototype.calcIndexedSlice = function (completeServerData, startPost, count, reverse, index) {\r\n return this.writeTree_.calcIndexedSlice(this.treePath_, completeServerData, startPost, count, reverse, index);\r\n };\r\n /**\r\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\r\n * complete child for this ChildKey.\r\n *\r\n * @param {!string} childKey\r\n * @param {!CacheNode} existingServerCache\r\n * @return {?Node}\r\n */\r\n WriteTreeRef.prototype.calcCompleteChild = function (childKey, existingServerCache) {\r\n return this.writeTree_.calcCompleteChild(this.treePath_, childKey, existingServerCache);\r\n };\r\n /**\r\n * Return a WriteTreeRef for a child.\r\n *\r\n * @param {string} childName\r\n * @return {!WriteTreeRef}\r\n */\r\n WriteTreeRef.prototype.child = function (childName) {\r\n return new WriteTreeRef(this.treePath_.child(childName), this.writeTree_);\r\n };\r\n return WriteTreeRef;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * SyncTree is the central class for managing event callback registration, data caching, views\r\n * (query processing), and event generation. There are typically two SyncTree instances for\r\n * each Repo, one for the normal Firebase data, and one for the .info data.\r\n *\r\n * It has a number of responsibilities, including:\r\n * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).\r\n * - Applying and caching data changes for user set(), transaction(), and update() calls\r\n * (applyUserOverwrite(), applyUserMerge()).\r\n * - Applying and caching data changes for server data changes (applyServerOverwrite(),\r\n * applyServerMerge()).\r\n * - Generating user-facing events for server and user changes (all of the apply* methods\r\n * return the set of events that need to be raised as a result).\r\n * - Maintaining the appropriate set of server listens to ensure we are always subscribed\r\n * to the correct set of paths and queries to satisfy the current set of user event\r\n * callbacks (listens are started/stopped using the provided listenProvider).\r\n *\r\n * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual\r\n * events are returned to the caller rather than raised synchronously.\r\n *\r\n * @constructor\r\n */\r\nvar SyncTree = /** @class */ (function () {\r\n /**\r\n * @param {!ListenProvider} listenProvider_ Used by SyncTree to start / stop listening\r\n * to server data.\r\n */\r\n function SyncTree(listenProvider_) {\r\n this.listenProvider_ = listenProvider_;\r\n /**\r\n * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.\r\n * @type {!ImmutableTree.}\r\n * @private\r\n */\r\n this.syncPointTree_ = ImmutableTree.Empty;\r\n /**\r\n * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).\r\n * @type {!WriteTree}\r\n * @private\r\n */\r\n this.pendingWriteTree_ = new WriteTree();\r\n this.tagToQueryMap_ = {};\r\n this.queryToTagMap_ = {};\r\n }\r\n /**\r\n * Apply the data changes for a user-generated set() or transaction() call.\r\n *\r\n * @param {!Path} path\r\n * @param {!Node} newData\r\n * @param {number} writeId\r\n * @param {boolean=} visible\r\n * @return {!Array.} Events to raise.\r\n */\r\n SyncTree.prototype.applyUserOverwrite = function (path, newData, writeId, visible) {\r\n // Record pending write.\r\n this.pendingWriteTree_.addOverwrite(path, newData, writeId, visible);\r\n if (!visible) {\r\n return [];\r\n }\r\n else {\r\n return this.applyOperationToSyncPoints_(new Overwrite(OperationSource.User, path, newData));\r\n }\r\n };\r\n /**\r\n * Apply the data from a user-generated update() call\r\n *\r\n * @param {!Path} path\r\n * @param {!Object.} changedChildren\r\n * @param {!number} writeId\r\n * @return {!Array.} Events to raise.\r\n */\r\n SyncTree.prototype.applyUserMerge = function (path, changedChildren, writeId) {\r\n // Record pending merge.\r\n this.pendingWriteTree_.addMerge(path, changedChildren, writeId);\r\n var changeTree = ImmutableTree.fromObject(changedChildren);\r\n return this.applyOperationToSyncPoints_(new Merge(OperationSource.User, path, changeTree));\r\n };\r\n /**\r\n * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().\r\n *\r\n * @param {!number} writeId\r\n * @param {boolean=} revert True if the given write failed and needs to be reverted\r\n * @return {!Array.} Events to raise.\r\n */\r\n SyncTree.prototype.ackUserWrite = function (writeId, revert) {\r\n if (revert === void 0) { revert = false; }\r\n var write = this.pendingWriteTree_.getWrite(writeId);\r\n var needToReevaluate = this.pendingWriteTree_.removeWrite(writeId);\r\n if (!needToReevaluate) {\r\n return [];\r\n }\r\n else {\r\n var affectedTree_1 = ImmutableTree.Empty;\r\n if (write.snap != null) {\r\n // overwrite\r\n affectedTree_1 = affectedTree_1.set(Path.Empty, true);\r\n }\r\n else {\r\n util.forEach(write.children, function (pathString, node) {\r\n affectedTree_1 = affectedTree_1.set(new Path(pathString), node);\r\n });\r\n }\r\n return this.applyOperationToSyncPoints_(new AckUserWrite(write.path, affectedTree_1, revert));\r\n }\r\n };\r\n /**\r\n * Apply new server data for the specified path..\r\n *\r\n * @param {!Path} path\r\n * @param {!Node} newData\r\n * @return {!Array.} Events to raise.\r\n */\r\n SyncTree.prototype.applyServerOverwrite = function (path, newData) {\r\n return this.applyOperationToSyncPoints_(new Overwrite(OperationSource.Server, path, newData));\r\n };\r\n /**\r\n * Apply new server data to be merged in at the specified path.\r\n *\r\n * @param {!Path} path\r\n * @param {!Object.} changedChildren\r\n * @return {!Array.} Events to raise.\r\n */\r\n SyncTree.prototype.applyServerMerge = function (path, changedChildren) {\r\n var changeTree = ImmutableTree.fromObject(changedChildren);\r\n return this.applyOperationToSyncPoints_(new Merge(OperationSource.Server, path, changeTree));\r\n };\r\n /**\r\n * Apply a listen complete for a query\r\n *\r\n * @param {!Path} path\r\n * @return {!Array.} Events to raise.\r\n */\r\n SyncTree.prototype.applyListenComplete = function (path) {\r\n return this.applyOperationToSyncPoints_(new ListenComplete(OperationSource.Server, path));\r\n };\r\n /**\r\n * Apply new server data for the specified tagged query.\r\n *\r\n * @param {!Path} path\r\n * @param {!Node} snap\r\n * @param {!number} tag\r\n * @return {!Array.} Events to raise.\r\n */\r\n SyncTree.prototype.applyTaggedQueryOverwrite = function (path, snap, tag) {\r\n var queryKey = this.queryKeyForTag_(tag);\r\n if (queryKey != null) {\r\n var r = SyncTree.parseQueryKey_(queryKey);\r\n var queryPath = r.path, queryId = r.queryId;\r\n var relativePath = Path.relativePath(queryPath, path);\r\n var op = new Overwrite(OperationSource.forServerTaggedQuery(queryId), relativePath, snap);\r\n return this.applyTaggedOperation_(queryPath, op);\r\n }\r\n else {\r\n // Query must have been removed already\r\n return [];\r\n }\r\n };\r\n /**\r\n * Apply server data to be merged in for the specified tagged query.\r\n *\r\n * @param {!Path} path\r\n * @param {!Object.} changedChildren\r\n * @param {!number} tag\r\n * @return {!Array.} Events to raise.\r\n */\r\n SyncTree.prototype.applyTaggedQueryMerge = function (path, changedChildren, tag) {\r\n var queryKey = this.queryKeyForTag_(tag);\r\n if (queryKey) {\r\n var r = SyncTree.parseQueryKey_(queryKey);\r\n var queryPath = r.path, queryId = r.queryId;\r\n var relativePath = Path.relativePath(queryPath, path);\r\n var changeTree = ImmutableTree.fromObject(changedChildren);\r\n var op = new Merge(OperationSource.forServerTaggedQuery(queryId), relativePath, changeTree);\r\n return this.applyTaggedOperation_(queryPath, op);\r\n }\r\n else {\r\n // We've already removed the query. No big deal, ignore the update\r\n return [];\r\n }\r\n };\r\n /**\r\n * Apply a listen complete for a tagged query\r\n *\r\n * @param {!Path} path\r\n * @param {!number} tag\r\n * @return {!Array.} Events to raise.\r\n */\r\n SyncTree.prototype.applyTaggedListenComplete = function (path, tag) {\r\n var queryKey = this.queryKeyForTag_(tag);\r\n if (queryKey) {\r\n var r = SyncTree.parseQueryKey_(queryKey);\r\n var queryPath = r.path, queryId = r.queryId;\r\n var relativePath = Path.relativePath(queryPath, path);\r\n var op = new ListenComplete(OperationSource.forServerTaggedQuery(queryId), relativePath);\r\n return this.applyTaggedOperation_(queryPath, op);\r\n }\r\n else {\r\n // We've already removed the query. No big deal, ignore the update\r\n return [];\r\n }\r\n };\r\n /**\r\n * Add an event callback for the specified query.\r\n *\r\n * @param {!Query} query\r\n * @param {!EventRegistration} eventRegistration\r\n * @return {!Array.} Events to raise.\r\n */\r\n SyncTree.prototype.addEventRegistration = function (query, eventRegistration) {\r\n var path = query.path;\r\n var serverCache = null;\r\n var foundAncestorDefaultView = false;\r\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\r\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\r\n this.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) {\r\n var relativePath = Path.relativePath(pathToSyncPoint, path);\r\n serverCache = serverCache || sp.getCompleteServerCache(relativePath);\r\n foundAncestorDefaultView =\r\n foundAncestorDefaultView || sp.hasCompleteView();\r\n });\r\n var syncPoint = this.syncPointTree_.get(path);\r\n if (!syncPoint) {\r\n syncPoint = new SyncPoint();\r\n this.syncPointTree_ = this.syncPointTree_.set(path, syncPoint);\r\n }\r\n else {\r\n foundAncestorDefaultView =\r\n foundAncestorDefaultView || syncPoint.hasCompleteView();\r\n serverCache = serverCache || syncPoint.getCompleteServerCache(Path.Empty);\r\n }\r\n var serverCacheComplete;\r\n if (serverCache != null) {\r\n serverCacheComplete = true;\r\n }\r\n else {\r\n serverCacheComplete = false;\r\n serverCache = ChildrenNode.EMPTY_NODE;\r\n var subtree = this.syncPointTree_.subtree(path);\r\n subtree.foreachChild(function (childName, childSyncPoint) {\r\n var completeCache = childSyncPoint.getCompleteServerCache(Path.Empty);\r\n if (completeCache) {\r\n serverCache = serverCache.updateImmediateChild(childName, completeCache);\r\n }\r\n });\r\n }\r\n var viewAlreadyExists = syncPoint.viewExistsForQuery(query);\r\n if (!viewAlreadyExists && !query.getQueryParams().loadsAllData()) {\r\n // We need to track a tag for this query\r\n var queryKey = SyncTree.makeQueryKey_(query);\r\n util.assert(!(queryKey in this.queryToTagMap_), 'View does not exist, but we have a tag');\r\n var tag = SyncTree.getNextQueryTag_();\r\n this.queryToTagMap_[queryKey] = tag;\r\n // Coerce to string to avoid sparse arrays.\r\n this.tagToQueryMap_['_' + tag] = queryKey;\r\n }\r\n var writesCache = this.pendingWriteTree_.childWrites(path);\r\n var events = syncPoint.addEventRegistration(query, eventRegistration, writesCache, serverCache, serverCacheComplete);\r\n if (!viewAlreadyExists && !foundAncestorDefaultView) {\r\n var view /** @type !View */ = syncPoint.viewForQuery(query);\r\n events = events.concat(this.setupListener_(query, view));\r\n }\r\n return events;\r\n };\r\n /**\r\n * Remove event callback(s).\r\n *\r\n * If query is the default query, we'll check all queries for the specified eventRegistration.\r\n * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.\r\n *\r\n * @param {!Query} query\r\n * @param {?EventRegistration} eventRegistration If null, all callbacks are removed.\r\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\r\n * @return {!Array.} Cancel events, if cancelError was provided.\r\n */\r\n SyncTree.prototype.removeEventRegistration = function (query, eventRegistration, cancelError) {\r\n var _this = this;\r\n // Find the syncPoint first. Then deal with whether or not it has matching listeners\r\n var path = query.path;\r\n var maybeSyncPoint = this.syncPointTree_.get(path);\r\n var cancelEvents = [];\r\n // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without\r\n // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and\r\n // not loadsAllData().\r\n if (maybeSyncPoint &&\r\n (query.queryIdentifier() === 'default' ||\r\n maybeSyncPoint.viewExistsForQuery(query))) {\r\n /**\r\n * @type {{removed: !Array., events: !Array.}}\r\n */\r\n var removedAndEvents = maybeSyncPoint.removeEventRegistration(query, eventRegistration, cancelError);\r\n if (maybeSyncPoint.isEmpty()) {\r\n this.syncPointTree_ = this.syncPointTree_.remove(path);\r\n }\r\n var removed = removedAndEvents.removed;\r\n cancelEvents = removedAndEvents.events;\r\n // We may have just removed one of many listeners and can short-circuit this whole process\r\n // We may also not have removed a default listener, in which case all of the descendant listeners should already be\r\n // properly set up.\r\n //\r\n // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of\r\n // queryId === 'default'\r\n var removingDefault = -1 !==\r\n removed.findIndex(function (query) {\r\n return query.getQueryParams().loadsAllData();\r\n });\r\n var covered = this.syncPointTree_.findOnPath(path, function (relativePath, parentSyncPoint) {\r\n return parentSyncPoint.hasCompleteView();\r\n });\r\n if (removingDefault && !covered) {\r\n var subtree = this.syncPointTree_.subtree(path);\r\n // There are potentially child listeners. Determine what if any listens we need to send before executing the\r\n // removal\r\n if (!subtree.isEmpty()) {\r\n // We need to fold over our subtree and collect the listeners to send\r\n var newViews = this.collectDistinctViewsForSubTree_(subtree);\r\n // Ok, we've collected all the listens we need. Set them up.\r\n for (var i = 0; i < newViews.length; ++i) {\r\n var view = newViews[i], newQuery = view.getQuery();\r\n var listener = this.createListenerForView_(view);\r\n this.listenProvider_.startListening(SyncTree.queryForListening_(newQuery), this.tagForQuery_(newQuery), listener.hashFn, listener.onComplete);\r\n }\r\n }\r\n }\r\n // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query\r\n // The above block has us covered in terms of making sure we're set up on listens lower in the tree.\r\n // Also, note that if we have a cancelError, it's already been removed at the provider level.\r\n if (!covered && removed.length > 0 && !cancelError) {\r\n // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one\r\n // default. Otherwise, we need to iterate through and cancel each individual query\r\n if (removingDefault) {\r\n // We don't tag default listeners\r\n var defaultTag = null;\r\n this.listenProvider_.stopListening(SyncTree.queryForListening_(query), defaultTag);\r\n }\r\n else {\r\n removed.forEach(function (queryToRemove) {\r\n var tagToRemove = _this.queryToTagMap_[SyncTree.makeQueryKey_(queryToRemove)];\r\n _this.listenProvider_.stopListening(SyncTree.queryForListening_(queryToRemove), tagToRemove);\r\n });\r\n }\r\n }\r\n // Now, clear all of the tags we're tracking for the removed listens\r\n this.removeTags_(removed);\r\n }\r\n return cancelEvents;\r\n };\r\n /**\r\n * Returns a complete cache, if we have one, of the data at a particular path. The location must have a listener above\r\n * it, but as this is only used by transaction code, that should always be the case anyways.\r\n *\r\n * Note: this method will *include* hidden writes from transaction with applyLocally set to false.\r\n * @param {!Path} path The path to the data we want\r\n * @param {Array.=} writeIdsToExclude A specific set to be excluded\r\n * @return {?Node}\r\n */\r\n SyncTree.prototype.calcCompleteEventCache = function (path, writeIdsToExclude) {\r\n var includeHiddenSets = true;\r\n var writeTree = this.pendingWriteTree_;\r\n var serverCache = this.syncPointTree_.findOnPath(path, function (pathSoFar, syncPoint) {\r\n var relativePath = Path.relativePath(pathSoFar, path);\r\n var serverCache = syncPoint.getCompleteServerCache(relativePath);\r\n if (serverCache) {\r\n return serverCache;\r\n }\r\n });\r\n return writeTree.calcCompleteEventCache(path, serverCache, writeIdsToExclude, includeHiddenSets);\r\n };\r\n /**\r\n * This collapses multiple unfiltered views into a single view, since we only need a single\r\n * listener for them.\r\n *\r\n * @param {!ImmutableTree.} subtree\r\n * @return {!Array.}\r\n * @private\r\n */\r\n SyncTree.prototype.collectDistinctViewsForSubTree_ = function (subtree) {\r\n return subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {\r\n if (maybeChildSyncPoint && maybeChildSyncPoint.hasCompleteView()) {\r\n var completeView = maybeChildSyncPoint.getCompleteView();\r\n return [completeView];\r\n }\r\n else {\r\n // No complete view here, flatten any deeper listens into an array\r\n var views_1 = [];\r\n if (maybeChildSyncPoint) {\r\n views_1 = maybeChildSyncPoint.getQueryViews();\r\n }\r\n util.forEach(childMap, function (key, childViews) {\r\n views_1 = views_1.concat(childViews);\r\n });\r\n return views_1;\r\n }\r\n });\r\n };\r\n /**\r\n * @param {!Array.} queries\r\n * @private\r\n */\r\n SyncTree.prototype.removeTags_ = function (queries) {\r\n for (var j = 0; j < queries.length; ++j) {\r\n var removedQuery = queries[j];\r\n if (!removedQuery.getQueryParams().loadsAllData()) {\r\n // We should have a tag for this\r\n var removedQueryKey = SyncTree.makeQueryKey_(removedQuery);\r\n var removedQueryTag = this.queryToTagMap_[removedQueryKey];\r\n delete this.queryToTagMap_[removedQueryKey];\r\n delete this.tagToQueryMap_['_' + removedQueryTag];\r\n }\r\n }\r\n };\r\n /**\r\n * Normalizes a query to a query we send the server for listening\r\n * @param {!Query} query\r\n * @return {!Query} The normalized query\r\n * @private\r\n */\r\n SyncTree.queryForListening_ = function (query) {\r\n if (query.getQueryParams().loadsAllData() &&\r\n !query.getQueryParams().isDefault()) {\r\n // We treat queries that load all data as default queries\r\n // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits\r\n // from Query\r\n return /** @type {!Query} */ query.getRef();\r\n }\r\n else {\r\n return query;\r\n }\r\n };\r\n /**\r\n * For a given new listen, manage the de-duplication of outstanding subscriptions.\r\n *\r\n * @param {!Query} query\r\n * @param {!View} view\r\n * @return {!Array.} This method can return events to support synchronous data sources\r\n * @private\r\n */\r\n SyncTree.prototype.setupListener_ = function (query, view) {\r\n var path = query.path;\r\n var tag = this.tagForQuery_(query);\r\n var listener = this.createListenerForView_(view);\r\n var events = this.listenProvider_.startListening(SyncTree.queryForListening_(query), tag, listener.hashFn, listener.onComplete);\r\n var subtree = this.syncPointTree_.subtree(path);\r\n // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we\r\n // may need to shadow other listens as well.\r\n if (tag) {\r\n util.assert(!subtree.value.hasCompleteView(), \"If we're adding a query, it shouldn't be shadowed\");\r\n }\r\n else {\r\n // Shadow everything at or below this location, this is a default listener.\r\n var queriesToStop = subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {\r\n if (!relativePath.isEmpty() &&\r\n maybeChildSyncPoint &&\r\n maybeChildSyncPoint.hasCompleteView()) {\r\n return [maybeChildSyncPoint.getCompleteView().getQuery()];\r\n }\r\n else {\r\n // No default listener here, flatten any deeper queries into an array\r\n var queries_1 = [];\r\n if (maybeChildSyncPoint) {\r\n queries_1 = queries_1.concat(maybeChildSyncPoint.getQueryViews().map(function (view) { return view.getQuery(); }));\r\n }\r\n util.forEach(childMap, function (key, childQueries) {\r\n queries_1 = queries_1.concat(childQueries);\r\n });\r\n return queries_1;\r\n }\r\n });\r\n for (var i = 0; i < queriesToStop.length; ++i) {\r\n var queryToStop = queriesToStop[i];\r\n this.listenProvider_.stopListening(SyncTree.queryForListening_(queryToStop), this.tagForQuery_(queryToStop));\r\n }\r\n }\r\n return events;\r\n };\r\n /**\r\n *\r\n * @param {!View} view\r\n * @return {{hashFn: function(), onComplete: function(!string, *)}}\r\n * @private\r\n */\r\n SyncTree.prototype.createListenerForView_ = function (view) {\r\n var _this = this;\r\n var query = view.getQuery();\r\n var tag = this.tagForQuery_(query);\r\n return {\r\n hashFn: function () {\r\n var cache = view.getServerCache() || ChildrenNode.EMPTY_NODE;\r\n return cache.hash();\r\n },\r\n onComplete: function (status) {\r\n if (status === 'ok') {\r\n if (tag) {\r\n return _this.applyTaggedListenComplete(query.path, tag);\r\n }\r\n else {\r\n return _this.applyListenComplete(query.path);\r\n }\r\n }\r\n else {\r\n // If a listen failed, kill all of the listeners here, not just the one that triggered the error.\r\n // Note that this may need to be scoped to just this listener if we change permissions on filtered children\r\n var error = errorForServerCode(status, query);\r\n return _this.removeEventRegistration(query, \r\n /*eventRegistration*/ null, error);\r\n }\r\n }\r\n };\r\n };\r\n /**\r\n * Given a query, computes a \"queryKey\" suitable for use in our queryToTagMap_.\r\n * @private\r\n * @param {!Query} query\r\n * @return {string}\r\n */\r\n SyncTree.makeQueryKey_ = function (query) {\r\n return query.path.toString() + '$' + query.queryIdentifier();\r\n };\r\n /**\r\n * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.\r\n * @private\r\n * @param {!string} queryKey\r\n * @return {{queryId: !string, path: !Path}}\r\n */\r\n SyncTree.parseQueryKey_ = function (queryKey) {\r\n var splitIndex = queryKey.indexOf('$');\r\n util.assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');\r\n return {\r\n queryId: queryKey.substr(splitIndex + 1),\r\n path: new Path(queryKey.substr(0, splitIndex))\r\n };\r\n };\r\n /**\r\n * Return the query associated with the given tag, if we have one\r\n * @param {!number} tag\r\n * @return {?string}\r\n * @private\r\n */\r\n SyncTree.prototype.queryKeyForTag_ = function (tag) {\r\n return this.tagToQueryMap_['_' + tag];\r\n };\r\n /**\r\n * Return the tag associated with the given query.\r\n * @param {!Query} query\r\n * @return {?number}\r\n * @private\r\n */\r\n SyncTree.prototype.tagForQuery_ = function (query) {\r\n var queryKey = SyncTree.makeQueryKey_(query);\r\n return util.safeGet(this.queryToTagMap_, queryKey);\r\n };\r\n /**\r\n * Static accessor for query tags.\r\n * @return {number}\r\n * @private\r\n */\r\n SyncTree.getNextQueryTag_ = function () {\r\n return SyncTree.nextQueryTag_++;\r\n };\r\n /**\r\n * A helper method to apply tagged operations\r\n *\r\n * @param {!Path} queryPath\r\n * @param {!Operation} operation\r\n * @return {!Array.}\r\n * @private\r\n */\r\n SyncTree.prototype.applyTaggedOperation_ = function (queryPath, operation) {\r\n var syncPoint = this.syncPointTree_.get(queryPath);\r\n util.assert(syncPoint, \"Missing sync point for query tag that we're tracking\");\r\n var writesCache = this.pendingWriteTree_.childWrites(queryPath);\r\n return syncPoint.applyOperation(operation, writesCache, \r\n /*serverCache=*/ null);\r\n };\r\n /**\r\n * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.\r\n *\r\n * NOTES:\r\n * - Descendant SyncPoints will be visited first (since we raise events depth-first).\r\n \n * - We call applyOperation() on each SyncPoint passing three things:\r\n * 1. A version of the Operation that has been made relative to the SyncPoint location.\r\n * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.\r\n * 3. A snapshot Node with cached server data, if we have it.\r\n \n * - We concatenate all of the events returned by each SyncPoint and return the result.\r\n *\r\n * @param {!Operation} operation\r\n * @return {!Array.}\r\n * @private\r\n */\r\n SyncTree.prototype.applyOperationToSyncPoints_ = function (operation) {\r\n return this.applyOperationHelper_(operation, this.syncPointTree_, \r\n /*serverCache=*/ null, this.pendingWriteTree_.childWrites(Path.Empty));\r\n };\r\n /**\r\n * Recursive helper for applyOperationToSyncPoints_\r\n *\r\n * @private\r\n * @param {!Operation} operation\r\n * @param {ImmutableTree.} syncPointTree\r\n * @param {?Node} serverCache\r\n * @param {!WriteTreeRef} writesCache\r\n * @return {!Array.}\r\n */\r\n SyncTree.prototype.applyOperationHelper_ = function (operation, syncPointTree, serverCache, writesCache) {\r\n if (operation.path.isEmpty()) {\r\n return this.applyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);\r\n }\r\n else {\r\n var syncPoint = syncPointTree.get(Path.Empty);\r\n // If we don't have cached server data, see if we can get it from this SyncPoint.\r\n if (serverCache == null && syncPoint != null) {\r\n serverCache = syncPoint.getCompleteServerCache(Path.Empty);\r\n }\r\n var events = [];\r\n var childName = operation.path.getFront();\r\n var childOperation = operation.operationForChild(childName);\r\n var childTree = syncPointTree.children.get(childName);\r\n if (childTree && childOperation) {\r\n var childServerCache = serverCache\r\n ? serverCache.getImmediateChild(childName)\r\n : null;\r\n var childWritesCache = writesCache.child(childName);\r\n events = events.concat(this.applyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));\r\n }\r\n if (syncPoint) {\r\n events = events.concat(syncPoint.applyOperation(operation, writesCache, serverCache));\r\n }\r\n return events;\r\n }\r\n };\r\n /**\r\n * Recursive helper for applyOperationToSyncPoints_\r\n *\r\n * @private\r\n * @param {!Operation} operation\r\n * @param {ImmutableTree.} syncPointTree\r\n * @param {?Node} serverCache\r\n * @param {!WriteTreeRef} writesCache\r\n * @return {!Array.}\r\n */\r\n SyncTree.prototype.applyOperationDescendantsHelper_ = function (operation, syncPointTree, serverCache, writesCache) {\r\n var _this = this;\r\n var syncPoint = syncPointTree.get(Path.Empty);\r\n // If we don't have cached server data, see if we can get it from this SyncPoint.\r\n if (serverCache == null && syncPoint != null) {\r\n serverCache = syncPoint.getCompleteServerCache(Path.Empty);\r\n }\r\n var events = [];\r\n syncPointTree.children.inorderTraversal(function (childName, childTree) {\r\n var childServerCache = serverCache\r\n ? serverCache.getImmediateChild(childName)\r\n : null;\r\n var childWritesCache = writesCache.child(childName);\r\n var childOperation = operation.operationForChild(childName);\r\n if (childOperation) {\r\n events = events.concat(_this.applyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));\r\n }\r\n });\r\n if (syncPoint) {\r\n events = events.concat(syncPoint.applyOperation(operation, writesCache, serverCache));\r\n }\r\n return events;\r\n };\r\n /**\r\n * Static tracker for next query tag.\r\n * @type {number}\r\n * @private\r\n */\r\n SyncTree.nextQueryTag_ = 1;\r\n return SyncTree;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Mutable object which basically just stores a reference to the \"latest\" immutable snapshot.\r\n *\r\n * @constructor\r\n */\r\nvar SnapshotHolder = /** @class */ (function () {\r\n function SnapshotHolder() {\r\n this.rootNode_ = ChildrenNode.EMPTY_NODE;\r\n }\r\n SnapshotHolder.prototype.getNode = function (path) {\r\n return this.rootNode_.getChild(path);\r\n };\r\n SnapshotHolder.prototype.updateSnapshot = function (path, newSnapshotNode) {\r\n this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);\r\n };\r\n return SnapshotHolder;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Abstraction around FirebaseApp's token fetching capabilities.\r\n */\r\nvar AuthTokenProvider = /** @class */ (function () {\r\n /**\r\n * @param {!FirebaseApp} app_\r\n */\r\n function AuthTokenProvider(app_) {\r\n this.app_ = app_;\r\n }\r\n /**\r\n * @param {boolean} forceRefresh\r\n * @return {!Promise}\r\n */\r\n AuthTokenProvider.prototype.getToken = function (forceRefresh) {\r\n return this.app_['INTERNAL']['getToken'](forceRefresh).then(null, \r\n // .catch\r\n function (error) {\r\n // TODO: Need to figure out all the cases this is raised and whether\r\n // this makes sense.\r\n if (error && error.code === 'auth/token-not-initialized') {\r\n log('Got auth/token-not-initialized error. Treating as null token.');\r\n return null;\r\n }\r\n else {\r\n return Promise.reject(error);\r\n }\r\n });\r\n };\r\n AuthTokenProvider.prototype.addTokenChangeListener = function (listener) {\r\n // TODO: We might want to wrap the listener and call it with no args to\r\n // avoid a leaky abstraction, but that makes removing the listener harder.\r\n this.app_['INTERNAL']['addAuthTokenListener'](listener);\r\n };\r\n AuthTokenProvider.prototype.removeTokenChangeListener = function (listener) {\r\n this.app_['INTERNAL']['removeAuthTokenListener'](listener);\r\n };\r\n AuthTokenProvider.prototype.notifyForInvalidToken = function () {\r\n var errorMessage = 'Provided authentication credentials for the app named \"' +\r\n this.app_.name +\r\n '\" are invalid. This usually indicates your app was not ' +\r\n 'initialized correctly. ';\r\n if ('credential' in this.app_.options) {\r\n errorMessage +=\r\n 'Make sure the \"credential\" property provided to initializeApp() ' +\r\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\r\n 'project.';\r\n }\r\n else if ('serviceAccount' in this.app_.options) {\r\n errorMessage +=\r\n 'Make sure the \"serviceAccount\" property provided to initializeApp() ' +\r\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\r\n 'project.';\r\n }\r\n else {\r\n errorMessage +=\r\n 'Make sure the \"apiKey\" and \"databaseURL\" properties provided to ' +\r\n 'initializeApp() match the values provided for your app at ' +\r\n 'https://console.firebase.google.com/.';\r\n }\r\n warn(errorMessage);\r\n };\r\n return AuthTokenProvider;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Tracks a collection of stats.\r\n *\r\n * @constructor\r\n */\r\nvar StatsCollection = /** @class */ (function () {\r\n function StatsCollection() {\r\n this.counters_ = {};\r\n }\r\n StatsCollection.prototype.incrementCounter = function (name, amount) {\r\n if (amount === void 0) { amount = 1; }\r\n if (!util.contains(this.counters_, name))\r\n this.counters_[name] = 0;\r\n this.counters_[name] += amount;\r\n };\r\n StatsCollection.prototype.get = function () {\r\n return util.deepCopy(this.counters_);\r\n };\r\n return StatsCollection;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar StatsManager = /** @class */ (function () {\r\n function StatsManager() {\r\n }\r\n StatsManager.getCollection = function (repoInfo) {\r\n var hashString = repoInfo.toString();\r\n if (!this.collections_[hashString]) {\r\n this.collections_[hashString] = new StatsCollection();\r\n }\r\n return this.collections_[hashString];\r\n };\r\n StatsManager.getOrCreateReporter = function (repoInfo, creatorFunction) {\r\n var hashString = repoInfo.toString();\r\n if (!this.reporters_[hashString]) {\r\n this.reporters_[hashString] = creatorFunction();\r\n }\r\n return this.reporters_[hashString];\r\n };\r\n StatsManager.collections_ = {};\r\n StatsManager.reporters_ = {};\r\n return StatsManager;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns the delta from the previous call to get stats.\r\n *\r\n * @param collection_ The collection to \"listen\" to.\r\n * @constructor\r\n */\r\nvar StatsListener = /** @class */ (function () {\r\n function StatsListener(collection_) {\r\n this.collection_ = collection_;\r\n this.last_ = null;\r\n }\r\n StatsListener.prototype.get = function () {\r\n var newStats = this.collection_.get();\r\n var delta = util.clone(newStats);\r\n if (this.last_) {\r\n util.forEach(this.last_, function (stat, value) {\r\n delta[stat] = delta[stat] - value;\r\n });\r\n }\r\n this.last_ = newStats;\r\n return delta;\r\n };\r\n return StatsListener;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably\r\n// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10\r\n// seconds to try to ensure the Firebase connection is established / settled.\r\nvar FIRST_STATS_MIN_TIME = 10 * 1000;\r\nvar FIRST_STATS_MAX_TIME = 30 * 1000;\r\n// We'll continue to report stats on average every 5 minutes.\r\nvar REPORT_STATS_INTERVAL = 5 * 60 * 1000;\r\n/**\r\n * @constructor\r\n */\r\nvar StatsReporter = /** @class */ (function () {\r\n /**\r\n * @param collection\r\n * @param server_\r\n */\r\n function StatsReporter(collection, server_) {\r\n this.server_ = server_;\r\n this.statsToReport_ = {};\r\n this.statsListener_ = new StatsListener(collection);\r\n var timeout = FIRST_STATS_MIN_TIME +\r\n (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();\r\n setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));\r\n }\r\n StatsReporter.prototype.includeStat = function (stat) {\r\n this.statsToReport_[stat] = true;\r\n };\r\n StatsReporter.prototype.reportStats_ = function () {\r\n var _this = this;\r\n var stats = this.statsListener_.get();\r\n var reportedStats = {};\r\n var haveStatsToReport = false;\r\n util.forEach(stats, function (stat, value) {\r\n if (value > 0 && util.contains(_this.statsToReport_, stat)) {\r\n reportedStats[stat] = value;\r\n haveStatsToReport = true;\r\n }\r\n });\r\n if (haveStatsToReport) {\r\n this.server_.reportStats(reportedStats);\r\n }\r\n // queue our next run.\r\n setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));\r\n };\r\n return StatsReporter;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The event queue serves a few purposes:\r\n * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more\r\n * events being queued.\r\n * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,\r\n * raiseQueuedEvents() is called again, the \"inner\" call will pick up raising events where the \"outer\" call\r\n * left off, ensuring that the events are still raised synchronously and in order.\r\n * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued\r\n * events are raised synchronously.\r\n *\r\n * NOTE: This can all go away if/when we move to async events.\r\n *\r\n * @constructor\r\n */\r\nvar EventQueue = /** @class */ (function () {\r\n function EventQueue() {\r\n /**\r\n * @private\r\n * @type {!Array.}\r\n */\r\n this.eventLists_ = [];\r\n /**\r\n * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.\r\n * @private\r\n * @type {!number}\r\n */\r\n this.recursionDepth_ = 0;\r\n }\r\n /**\r\n * @param {!Array.} eventDataList The new events to queue.\r\n */\r\n EventQueue.prototype.queueEvents = function (eventDataList) {\r\n // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.\r\n var currList = null;\r\n for (var i = 0; i < eventDataList.length; i++) {\r\n var eventData = eventDataList[i];\r\n var eventPath = eventData.getPath();\r\n if (currList !== null && !eventPath.equals(currList.getPath())) {\r\n this.eventLists_.push(currList);\r\n currList = null;\r\n }\r\n if (currList === null) {\r\n currList = new EventList(eventPath);\r\n }\r\n currList.add(eventData);\r\n }\r\n if (currList) {\r\n this.eventLists_.push(currList);\r\n }\r\n };\r\n /**\r\n * Queues the specified events and synchronously raises all events (including previously queued ones)\r\n * for the specified path.\r\n *\r\n * It is assumed that the new events are all for the specified path.\r\n *\r\n * @param {!Path} path The path to raise events for.\r\n * @param {!Array.} eventDataList The new events to raise.\r\n */\r\n EventQueue.prototype.raiseEventsAtPath = function (path, eventDataList) {\r\n this.queueEvents(eventDataList);\r\n this.raiseQueuedEventsMatchingPredicate_(function (eventPath) {\r\n return eventPath.equals(path);\r\n });\r\n };\r\n /**\r\n * Queues the specified events and synchronously raises all events (including previously queued ones) for\r\n * locations related to the specified change path (i.e. all ancestors and descendants).\r\n *\r\n * It is assumed that the new events are all related (ancestor or descendant) to the specified path.\r\n *\r\n * @param {!Path} changedPath The path to raise events for.\r\n * @param {!Array.} eventDataList The events to raise\r\n */\r\n EventQueue.prototype.raiseEventsForChangedPath = function (changedPath, eventDataList) {\r\n this.queueEvents(eventDataList);\r\n this.raiseQueuedEventsMatchingPredicate_(function (eventPath) {\r\n return eventPath.contains(changedPath) || changedPath.contains(eventPath);\r\n });\r\n };\r\n /**\r\n * @param {!function(!Path):boolean} predicate\r\n * @private\r\n */\r\n EventQueue.prototype.raiseQueuedEventsMatchingPredicate_ = function (predicate) {\r\n this.recursionDepth_++;\r\n var sentAll = true;\r\n for (var i = 0; i < this.eventLists_.length; i++) {\r\n var eventList = this.eventLists_[i];\r\n if (eventList) {\r\n var eventPath = eventList.getPath();\r\n if (predicate(eventPath)) {\r\n this.eventLists_[i].raise();\r\n this.eventLists_[i] = null;\r\n }\r\n else {\r\n sentAll = false;\r\n }\r\n }\r\n }\r\n if (sentAll) {\r\n this.eventLists_ = [];\r\n }\r\n this.recursionDepth_--;\r\n };\r\n return EventQueue;\r\n}());\r\n/**\r\n * @param {!Path} path\r\n * @constructor\r\n */\r\nvar EventList = /** @class */ (function () {\r\n function EventList(path_) {\r\n this.path_ = path_;\r\n /**\r\n * @type {!Array.}\r\n * @private\r\n */\r\n this.events_ = [];\r\n }\r\n /**\r\n * @param {!Event} eventData\r\n */\r\n EventList.prototype.add = function (eventData) {\r\n this.events_.push(eventData);\r\n };\r\n /**\r\n * Iterates through the list and raises each event\r\n */\r\n EventList.prototype.raise = function () {\r\n for (var i = 0; i < this.events_.length; i++) {\r\n var eventData = this.events_[i];\r\n if (eventData !== null) {\r\n this.events_[i] = null;\r\n var eventFn = eventData.getEventRunner();\r\n if (logger) {\r\n log('event: ' + eventData.toString());\r\n }\r\n exceptionGuard(eventFn);\r\n }\r\n }\r\n };\r\n /**\r\n * @return {!Path}\r\n */\r\n EventList.prototype.getPath = function () {\r\n return this.path_;\r\n };\r\n return EventList;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Base class to be used if you want to emit events. Call the constructor with\r\n * the set of allowed event names.\r\n */\r\nvar EventEmitter = /** @class */ (function () {\r\n /**\r\n * @param {!Array.} allowedEvents_\r\n */\r\n function EventEmitter(allowedEvents_) {\r\n this.allowedEvents_ = allowedEvents_;\r\n this.listeners_ = {};\r\n util.assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');\r\n }\r\n /**\r\n * To be called by derived classes to trigger events.\r\n * @param {!string} eventType\r\n * @param {...*} var_args\r\n */\r\n EventEmitter.prototype.trigger = function (eventType) {\r\n var var_args = [];\r\n for (var _i = 1; _i < arguments.length; _i++) {\r\n var_args[_i - 1] = arguments[_i];\r\n }\r\n if (Array.isArray(this.listeners_[eventType])) {\r\n // Clone the list, since callbacks could add/remove listeners.\r\n var listeners = this.listeners_[eventType].slice();\r\n for (var i = 0; i < listeners.length; i++) {\r\n listeners[i].callback.apply(listeners[i].context, var_args);\r\n }\r\n }\r\n };\r\n EventEmitter.prototype.on = function (eventType, callback, context) {\r\n this.validateEventType_(eventType);\r\n this.listeners_[eventType] = this.listeners_[eventType] || [];\r\n this.listeners_[eventType].push({ callback: callback, context: context });\r\n var eventData = this.getInitialEvent(eventType);\r\n if (eventData) {\r\n callback.apply(context, eventData);\r\n }\r\n };\r\n EventEmitter.prototype.off = function (eventType, callback, context) {\r\n this.validateEventType_(eventType);\r\n var listeners = this.listeners_[eventType] || [];\r\n for (var i = 0; i < listeners.length; i++) {\r\n if (listeners[i].callback === callback &&\r\n (!context || context === listeners[i].context)) {\r\n listeners.splice(i, 1);\r\n return;\r\n }\r\n }\r\n };\r\n EventEmitter.prototype.validateEventType_ = function (eventType) {\r\n util.assert(this.allowedEvents_.find(function (et) {\r\n return et === eventType;\r\n }), 'Unknown event: ' + eventType);\r\n };\r\n return EventEmitter;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @extends {EventEmitter}\r\n */\r\nvar VisibilityMonitor = /** @class */ (function (_super) {\r\n tslib_1.__extends(VisibilityMonitor, _super);\r\n function VisibilityMonitor() {\r\n var _this = _super.call(this, ['visible']) || this;\r\n var hidden;\r\n var visibilityChange;\r\n if (typeof document !== 'undefined' &&\r\n typeof document.addEventListener !== 'undefined') {\r\n if (typeof document['hidden'] !== 'undefined') {\r\n // Opera 12.10 and Firefox 18 and later support\r\n visibilityChange = 'visibilitychange';\r\n hidden = 'hidden';\r\n }\r\n else if (typeof document['mozHidden'] !== 'undefined') {\r\n visibilityChange = 'mozvisibilitychange';\r\n hidden = 'mozHidden';\r\n }\r\n else if (typeof document['msHidden'] !== 'undefined') {\r\n visibilityChange = 'msvisibilitychange';\r\n hidden = 'msHidden';\r\n }\r\n else if (typeof document['webkitHidden'] !== 'undefined') {\r\n visibilityChange = 'webkitvisibilitychange';\r\n hidden = 'webkitHidden';\r\n }\r\n }\r\n // Initially, we always assume we are visible. This ensures that in browsers\r\n // without page visibility support or in cases where we are never visible\r\n // (e.g. chrome extension), we act as if we are visible, i.e. don't delay\r\n // reconnects\r\n _this.visible_ = true;\r\n if (visibilityChange) {\r\n document.addEventListener(visibilityChange, function () {\r\n var visible = !document[hidden];\r\n if (visible !== _this.visible_) {\r\n _this.visible_ = visible;\r\n _this.trigger('visible', visible);\r\n }\r\n }, false);\r\n }\r\n return _this;\r\n }\r\n VisibilityMonitor.getInstance = function () {\r\n return new VisibilityMonitor();\r\n };\r\n /**\r\n * @param {!string} eventType\r\n * @return {Array.}\r\n */\r\n VisibilityMonitor.prototype.getInitialEvent = function (eventType) {\r\n util.assert(eventType === 'visible', 'Unknown event type: ' + eventType);\r\n return [this.visible_];\r\n };\r\n return VisibilityMonitor;\r\n}(EventEmitter));\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Monitors online state (as reported by window.online/offline events).\r\n *\r\n * The expectation is that this could have many false positives (thinks we are online\r\n * when we're not), but no false negatives. So we can safely use it to determine when\r\n * we definitely cannot reach the internet.\r\n *\r\n * @extends {EventEmitter}\r\n */\r\nvar OnlineMonitor = /** @class */ (function (_super) {\r\n tslib_1.__extends(OnlineMonitor, _super);\r\n function OnlineMonitor() {\r\n var _this = _super.call(this, ['online']) || this;\r\n _this.online_ = true;\r\n // We've had repeated complaints that Cordova apps can get stuck \"offline\", e.g.\r\n // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810\r\n // It would seem that the 'online' event does not always fire consistently. So we disable it\r\n // for Cordova.\r\n if (typeof window !== 'undefined' &&\r\n typeof window.addEventListener !== 'undefined' &&\r\n !util.isMobileCordova()) {\r\n window.addEventListener('online', function () {\r\n if (!_this.online_) {\r\n _this.online_ = true;\r\n _this.trigger('online', true);\r\n }\r\n }, false);\r\n window.addEventListener('offline', function () {\r\n if (_this.online_) {\r\n _this.online_ = false;\r\n _this.trigger('online', false);\r\n }\r\n }, false);\r\n }\r\n return _this;\r\n }\r\n OnlineMonitor.getInstance = function () {\r\n return new OnlineMonitor();\r\n };\r\n /**\r\n * @param {!string} eventType\r\n * @return {Array.}\r\n */\r\n OnlineMonitor.prototype.getInitialEvent = function (eventType) {\r\n util.assert(eventType === 'online', 'Unknown event type: ' + eventType);\r\n return [this.online_];\r\n };\r\n /**\r\n * @return {boolean}\r\n */\r\n OnlineMonitor.prototype.currentlyOnline = function () {\r\n return this.online_;\r\n };\r\n return OnlineMonitor;\r\n}(EventEmitter));\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * This class ensures the packets from the server arrive in order\r\n * This class takes data from the server and ensures it gets passed into the callbacks in order.\r\n * @constructor\r\n */\r\nvar PacketReceiver = /** @class */ (function () {\r\n /**\r\n * @param onMessage_\r\n */\r\n function PacketReceiver(onMessage_) {\r\n this.onMessage_ = onMessage_;\r\n this.pendingResponses = [];\r\n this.currentResponseNum = 0;\r\n this.closeAfterResponse = -1;\r\n this.onClose = null;\r\n }\r\n PacketReceiver.prototype.closeAfter = function (responseNum, callback) {\r\n this.closeAfterResponse = responseNum;\r\n this.onClose = callback;\r\n if (this.closeAfterResponse < this.currentResponseNum) {\r\n this.onClose();\r\n this.onClose = null;\r\n }\r\n };\r\n /**\r\n * Each message from the server comes with a response number, and an array of data. The responseNumber\r\n * allows us to ensure that we process them in the right order, since we can't be guaranteed that all\r\n * browsers will respond in the same order as the requests we sent\r\n * @param {number} requestNum\r\n * @param {Array} data\r\n */\r\n PacketReceiver.prototype.handleResponse = function (requestNum, data) {\r\n var _this = this;\r\n this.pendingResponses[requestNum] = data;\r\n var _loop_1 = function () {\r\n var toProcess = this_1.pendingResponses[this_1.currentResponseNum];\r\n delete this_1.pendingResponses[this_1.currentResponseNum];\r\n var _loop_2 = function (i) {\r\n if (toProcess[i]) {\r\n exceptionGuard(function () {\r\n _this.onMessage_(toProcess[i]);\r\n });\r\n }\r\n };\r\n for (var i = 0; i < toProcess.length; ++i) {\r\n _loop_2(i);\r\n }\r\n if (this_1.currentResponseNum === this_1.closeAfterResponse) {\r\n if (this_1.onClose) {\r\n this_1.onClose();\r\n this_1.onClose = null;\r\n }\r\n return \"break\";\r\n }\r\n this_1.currentResponseNum++;\r\n };\r\n var this_1 = this;\r\n while (this.pendingResponses[this.currentResponseNum]) {\r\n var state_1 = _loop_1();\r\n if (state_1 === \"break\")\r\n break;\r\n }\r\n };\r\n return PacketReceiver;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// URL query parameters associated with longpolling\r\nvar FIREBASE_LONGPOLL_START_PARAM = 'start';\r\nvar FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';\r\nvar FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';\r\nvar FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';\r\nvar FIREBASE_LONGPOLL_ID_PARAM = 'id';\r\nvar FIREBASE_LONGPOLL_PW_PARAM = 'pw';\r\nvar FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';\r\nvar FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';\r\nvar FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';\r\nvar FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';\r\nvar FIREBASE_LONGPOLL_DATA_PARAM = 'd';\r\nvar FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM = 'disconn';\r\nvar FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';\r\n//Data size constants.\r\n//TODO: Perf: the maximum length actually differs from browser to browser.\r\n// We should check what browser we're on and set accordingly.\r\nvar MAX_URL_DATA_SIZE = 1870;\r\nvar SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=\r\nvar MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;\r\n/**\r\n * Keepalive period\r\n * send a fresh request at minimum every 25 seconds. Opera has a maximum request\r\n * length of 30 seconds that we can't exceed.\r\n * @const\r\n * @type {number}\r\n */\r\nvar KEEPALIVE_REQUEST_INTERVAL = 25000;\r\n/**\r\n * How long to wait before aborting a long-polling connection attempt.\r\n * @const\r\n * @type {number}\r\n */\r\nvar LP_CONNECT_TIMEOUT = 30000;\r\n/**\r\n * This class manages a single long-polling connection.\r\n *\r\n * @constructor\r\n * @implements {Transport}\r\n */\r\nvar BrowserPollConnection = /** @class */ (function () {\r\n /**\r\n * @param {string} connId An identifier for this connection, used for logging\r\n * @param {RepoInfo} repoInfo The info for the endpoint to send data to.\r\n * @param {string=} transportSessionId Optional transportSessionid if we are reconnecting for an existing\r\n * transport session\r\n * @param {string=} lastSessionId Optional lastSessionId if the PersistentConnection has already created a\r\n * connection previously\r\n */\r\n function BrowserPollConnection(connId, repoInfo, transportSessionId, lastSessionId) {\r\n this.connId = connId;\r\n this.repoInfo = repoInfo;\r\n this.transportSessionId = transportSessionId;\r\n this.lastSessionId = lastSessionId;\r\n this.bytesSent = 0;\r\n this.bytesReceived = 0;\r\n this.everConnected_ = false;\r\n this.log_ = logWrapper(connId);\r\n this.stats_ = StatsManager.getCollection(repoInfo);\r\n this.urlFn = function (params) {\r\n return repoInfo.connectionURL(LONG_POLLING, params);\r\n };\r\n }\r\n /**\r\n *\r\n * @param {function(Object)} onMessage Callback when messages arrive\r\n * @param {function()} onDisconnect Callback with connection lost.\r\n */\r\n BrowserPollConnection.prototype.open = function (onMessage, onDisconnect) {\r\n var _this = this;\r\n this.curSegmentNum = 0;\r\n this.onDisconnect_ = onDisconnect;\r\n this.myPacketOrderer = new PacketReceiver(onMessage);\r\n this.isClosed_ = false;\r\n this.connectTimeoutTimer_ = setTimeout(function () {\r\n _this.log_('Timed out trying to connect.');\r\n // Make sure we clear the host cache\r\n _this.onClosed_();\r\n _this.connectTimeoutTimer_ = null;\r\n }, Math.floor(LP_CONNECT_TIMEOUT));\r\n // Ensure we delay the creation of the iframe until the DOM is loaded.\r\n executeWhenDOMReady(function () {\r\n if (_this.isClosed_)\r\n return;\r\n //Set up a callback that gets triggered once a connection is set up.\r\n _this.scriptTagHolder = new FirebaseIFrameScriptHolder(function () {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n var command = args[0], arg1 = args[1], arg2 = args[2];\r\n _this.incrementIncomingBytes_(args);\r\n if (!_this.scriptTagHolder)\r\n return; // we closed the connection.\r\n if (_this.connectTimeoutTimer_) {\r\n clearTimeout(_this.connectTimeoutTimer_);\r\n _this.connectTimeoutTimer_ = null;\r\n }\r\n _this.everConnected_ = true;\r\n if (command == FIREBASE_LONGPOLL_START_PARAM) {\r\n _this.id = arg1;\r\n _this.password = arg2;\r\n }\r\n else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {\r\n // Don't clear the host cache. We got a response from the server, so we know it's reachable\r\n if (arg1) {\r\n // We aren't expecting any more data (other than what the server's already in the process of sending us\r\n // through our already open polls), so don't send any more.\r\n _this.scriptTagHolder.sendNewPolls = false;\r\n // arg1 in this case is the last response number sent by the server. We should try to receive\r\n // all of the responses up to this one before closing\r\n _this.myPacketOrderer.closeAfter(arg1, function () {\r\n _this.onClosed_();\r\n });\r\n }\r\n else {\r\n _this.onClosed_();\r\n }\r\n }\r\n else {\r\n throw new Error('Unrecognized command received: ' + command);\r\n }\r\n }, function () {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n var pN = args[0], data = args[1];\r\n _this.incrementIncomingBytes_(args);\r\n _this.myPacketOrderer.handleResponse(pN, data);\r\n }, function () {\r\n _this.onClosed_();\r\n }, _this.urlFn);\r\n //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results\r\n //from cache.\r\n var urlParams = {};\r\n urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';\r\n urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);\r\n if (_this.scriptTagHolder.uniqueCallbackIdentifier)\r\n urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] = _this.scriptTagHolder.uniqueCallbackIdentifier;\r\n urlParams[VERSION_PARAM] = PROTOCOL_VERSION;\r\n if (_this.transportSessionId) {\r\n urlParams[TRANSPORT_SESSION_PARAM] = _this.transportSessionId;\r\n }\r\n if (_this.lastSessionId) {\r\n urlParams[LAST_SESSION_PARAM] = _this.lastSessionId;\r\n }\r\n if (!util.isNodeSdk() &&\r\n typeof location !== 'undefined' &&\r\n location.href &&\r\n location.href.indexOf(FORGE_DOMAIN) !== -1) {\r\n urlParams[REFERER_PARAM] = FORGE_REF;\r\n }\r\n var connectURL = _this.urlFn(urlParams);\r\n _this.log_('Connecting via long-poll to ' + connectURL);\r\n _this.scriptTagHolder.addTag(connectURL, function () {\r\n /* do nothing */\r\n });\r\n });\r\n };\r\n /**\r\n * Call this when a handshake has completed successfully and we want to consider the connection established\r\n */\r\n BrowserPollConnection.prototype.start = function () {\r\n this.scriptTagHolder.startLongPoll(this.id, this.password);\r\n this.addDisconnectPingFrame(this.id, this.password);\r\n };\r\n /**\r\n * Forces long polling to be considered as a potential transport\r\n */\r\n BrowserPollConnection.forceAllow = function () {\r\n BrowserPollConnection.forceAllow_ = true;\r\n };\r\n /**\r\n * Forces longpolling to not be considered as a potential transport\r\n */\r\n BrowserPollConnection.forceDisallow = function () {\r\n BrowserPollConnection.forceDisallow_ = true;\r\n };\r\n // Static method, use string literal so it can be accessed in a generic way\r\n BrowserPollConnection.isAvailable = function () {\r\n // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in\r\n // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).\r\n return (BrowserPollConnection.forceAllow_ ||\r\n (!BrowserPollConnection.forceDisallow_ &&\r\n typeof document !== 'undefined' &&\r\n document.createElement != null &&\r\n !isChromeExtensionContentScript() &&\r\n !isWindowsStoreApp() &&\r\n !util.isNodeSdk()));\r\n };\r\n /**\r\n * No-op for polling\r\n */\r\n BrowserPollConnection.prototype.markConnectionHealthy = function () { };\r\n /**\r\n * Stops polling and cleans up the iframe\r\n * @private\r\n */\r\n BrowserPollConnection.prototype.shutdown_ = function () {\r\n this.isClosed_ = true;\r\n if (this.scriptTagHolder) {\r\n this.scriptTagHolder.close();\r\n this.scriptTagHolder = null;\r\n }\r\n //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.\r\n if (this.myDisconnFrame) {\r\n document.body.removeChild(this.myDisconnFrame);\r\n this.myDisconnFrame = null;\r\n }\r\n if (this.connectTimeoutTimer_) {\r\n clearTimeout(this.connectTimeoutTimer_);\r\n this.connectTimeoutTimer_ = null;\r\n }\r\n };\r\n /**\r\n * Triggered when this transport is closed\r\n * @private\r\n */\r\n BrowserPollConnection.prototype.onClosed_ = function () {\r\n if (!this.isClosed_) {\r\n this.log_('Longpoll is closing itself');\r\n this.shutdown_();\r\n if (this.onDisconnect_) {\r\n this.onDisconnect_(this.everConnected_);\r\n this.onDisconnect_ = null;\r\n }\r\n }\r\n };\r\n /**\r\n * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server\r\n * that we've left.\r\n */\r\n BrowserPollConnection.prototype.close = function () {\r\n if (!this.isClosed_) {\r\n this.log_('Longpoll is being closed.');\r\n this.shutdown_();\r\n }\r\n };\r\n /**\r\n * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then\r\n * broken into chunks (since URLs have a small maximum length).\r\n * @param {!Object} data The JSON data to transmit.\r\n */\r\n BrowserPollConnection.prototype.send = function (data) {\r\n var dataStr = util.stringify(data);\r\n this.bytesSent += dataStr.length;\r\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\r\n //first, lets get the base64-encoded data\r\n var base64data = util.base64Encode(dataStr);\r\n //We can only fit a certain amount in each URL, so we need to split this request\r\n //up into multiple pieces if it doesn't fit in one request.\r\n var dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);\r\n //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number\r\n //of segments so that we can reassemble the packet on the server.\r\n for (var i = 0; i < dataSegs.length; i++) {\r\n this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);\r\n this.curSegmentNum++;\r\n }\r\n };\r\n /**\r\n * This is how we notify the server that we're leaving.\r\n * We aren't able to send requests with DHTML on a window close event, but we can\r\n * trigger XHR requests in some browsers (everything but Opera basically).\r\n * @param {!string} id\r\n * @param {!string} pw\r\n */\r\n BrowserPollConnection.prototype.addDisconnectPingFrame = function (id, pw) {\r\n if (util.isNodeSdk())\r\n return;\r\n this.myDisconnFrame = document.createElement('iframe');\r\n var urlParams = {};\r\n urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';\r\n urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;\r\n urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;\r\n this.myDisconnFrame.src = this.urlFn(urlParams);\r\n this.myDisconnFrame.style.display = 'none';\r\n document.body.appendChild(this.myDisconnFrame);\r\n };\r\n /**\r\n * Used to track the bytes received by this client\r\n * @param {*} args\r\n * @private\r\n */\r\n BrowserPollConnection.prototype.incrementIncomingBytes_ = function (args) {\r\n // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.\r\n var bytesReceived = util.stringify(args).length;\r\n this.bytesReceived += bytesReceived;\r\n this.stats_.incrementCounter('bytes_received', bytesReceived);\r\n };\r\n return BrowserPollConnection;\r\n}());\r\n/*********************************************************************************************\r\n * A wrapper around an iframe that is used as a long-polling script holder.\r\n * @constructor\r\n *********************************************************************************************/\r\nvar FirebaseIFrameScriptHolder = /** @class */ (function () {\r\n /**\r\n * @param commandCB - The callback to be called when control commands are recevied from the server.\r\n * @param onMessageCB - The callback to be triggered when responses arrive from the server.\r\n * @param onDisconnect - The callback to be triggered when this tag holder is closed\r\n * @param urlFn - A function that provides the URL of the endpoint to send data to.\r\n */\r\n function FirebaseIFrameScriptHolder(commandCB, onMessageCB, onDisconnect, urlFn) {\r\n this.onDisconnect = onDisconnect;\r\n this.urlFn = urlFn;\r\n //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause\r\n //problems in some browsers.\r\n /**\r\n * @type {CountedSet.}\r\n */\r\n this.outstandingRequests = new CountedSet();\r\n //A queue of the pending segments waiting for transmission to the server.\r\n this.pendingSegs = [];\r\n //A serial number. We use this for two things:\r\n // 1) A way to ensure the browser doesn't cache responses to polls\r\n // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The\r\n // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute\r\n // JSONP code in the order it was added to the iframe.\r\n this.currentSerial = Math.floor(Math.random() * 100000000);\r\n // This gets set to false when we're \"closing down\" the connection (e.g. we're switching transports but there's still\r\n // incoming data from the server that we're waiting for).\r\n this.sendNewPolls = true;\r\n if (!util.isNodeSdk()) {\r\n //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the\r\n //iframes where we put the long-polling script tags. We have two callbacks:\r\n // 1) Command Callback - Triggered for control issues, like starting a connection.\r\n // 2) Message Callback - Triggered when new data arrives.\r\n this.uniqueCallbackIdentifier = LUIDGenerator();\r\n window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;\r\n window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] = onMessageCB;\r\n //Create an iframe for us to add script tags to.\r\n this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();\r\n // Set the iframe's contents.\r\n var script = '';\r\n // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient\r\n // for ie9, but ie8 needs to do it again in the document itself.\r\n if (this.myIFrame.src &&\r\n this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {\r\n var currentDomain = document.domain;\r\n script = '';\r\n }\r\n var iframeContents = '' + script + '';\r\n try {\r\n this.myIFrame.doc.open();\r\n this.myIFrame.doc.write(iframeContents);\r\n this.myIFrame.doc.close();\r\n }\r\n catch (e) {\r\n log('frame writing exception');\r\n if (e.stack) {\r\n log(e.stack);\r\n }\r\n log(e);\r\n }\r\n }\r\n else {\r\n this.commandCB = commandCB;\r\n this.onMessageCB = onMessageCB;\r\n }\r\n }\r\n /**\r\n * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can\r\n * actually use.\r\n * @private\r\n * @return {Element}\r\n */\r\n FirebaseIFrameScriptHolder.createIFrame_ = function () {\r\n var iframe = document.createElement('iframe');\r\n iframe.style.display = 'none';\r\n // This is necessary in order to initialize the document inside the iframe\r\n if (document.body) {\r\n document.body.appendChild(iframe);\r\n try {\r\n // If document.domain has been modified in IE, this will throw an error, and we need to set the\r\n // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute\r\n // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.\r\n var a = iframe.contentWindow.document;\r\n if (!a) {\r\n // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.\r\n log('No IE domain setting required');\r\n }\r\n }\r\n catch (e) {\r\n var domain = document.domain;\r\n iframe.src =\r\n \"javascript:void((function(){document.open();document.domain='\" +\r\n domain +\r\n \"';document.close();})())\";\r\n }\r\n }\r\n else {\r\n // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this\r\n // never gets hit.\r\n throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';\r\n }\r\n // Get the document of the iframe in a browser-specific way.\r\n if (iframe.contentDocument) {\r\n iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari\r\n }\r\n else if (iframe.contentWindow) {\r\n iframe.doc = iframe.contentWindow.document; // Internet Explorer\r\n }\r\n else if (iframe.document) {\r\n iframe.doc = iframe.document; //others?\r\n }\r\n return iframe;\r\n };\r\n /**\r\n * Cancel all outstanding queries and remove the frame.\r\n */\r\n FirebaseIFrameScriptHolder.prototype.close = function () {\r\n var _this = this;\r\n //Mark this iframe as dead, so no new requests are sent.\r\n this.alive = false;\r\n if (this.myIFrame) {\r\n //We have to actually remove all of the html inside this iframe before removing it from the\r\n //window, or IE will continue loading and executing the script tags we've already added, which\r\n //can lead to some errors being thrown. Setting innerHTML seems to be the easiest way to do this.\r\n this.myIFrame.doc.body.innerHTML = '';\r\n setTimeout(function () {\r\n if (_this.myIFrame !== null) {\r\n document.body.removeChild(_this.myIFrame);\r\n _this.myIFrame = null;\r\n }\r\n }, Math.floor(0));\r\n }\r\n if (util.isNodeSdk() && this.myID) {\r\n var urlParams = {};\r\n urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM] = 't';\r\n urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\r\n urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\r\n var theURL = this.urlFn(urlParams);\r\n FirebaseIFrameScriptHolder.nodeRestRequest(theURL);\r\n }\r\n // Protect from being called recursively.\r\n var onDisconnect = this.onDisconnect;\r\n if (onDisconnect) {\r\n this.onDisconnect = null;\r\n onDisconnect();\r\n }\r\n };\r\n /**\r\n * Actually start the long-polling session by adding the first script tag(s) to the iframe.\r\n * @param {!string} id - The ID of this connection\r\n * @param {!string} pw - The password for this connection\r\n */\r\n FirebaseIFrameScriptHolder.prototype.startLongPoll = function (id, pw) {\r\n this.myID = id;\r\n this.myPW = pw;\r\n this.alive = true;\r\n //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.\r\n while (this.newRequest_()) { }\r\n };\r\n /**\r\n * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't\r\n * too many outstanding requests and we are still alive.\r\n *\r\n * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if\r\n * needed.\r\n */\r\n FirebaseIFrameScriptHolder.prototype.newRequest_ = function () {\r\n // We keep one outstanding request open all the time to receive data, but if we need to send data\r\n // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically\r\n // close the old request.\r\n if (this.alive &&\r\n this.sendNewPolls &&\r\n this.outstandingRequests.count() < (this.pendingSegs.length > 0 ? 2 : 1)) {\r\n //construct our url\r\n this.currentSerial++;\r\n var urlParams = {};\r\n urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\r\n urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\r\n urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;\r\n var theURL = this.urlFn(urlParams);\r\n //Now add as much data as we can.\r\n var curDataString = '';\r\n var i = 0;\r\n while (this.pendingSegs.length > 0) {\r\n //first, lets see if the next segment will fit.\r\n var nextSeg = this.pendingSegs[0];\r\n if (nextSeg.d.length + SEG_HEADER_SIZE + curDataString.length <=\r\n MAX_URL_DATA_SIZE) {\r\n //great, the segment will fit. Lets append it.\r\n var theSeg = this.pendingSegs.shift();\r\n curDataString =\r\n curDataString +\r\n '&' +\r\n FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +\r\n i +\r\n '=' +\r\n theSeg.seg +\r\n '&' +\r\n FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +\r\n i +\r\n '=' +\r\n theSeg.ts +\r\n '&' +\r\n FIREBASE_LONGPOLL_DATA_PARAM +\r\n i +\r\n '=' +\r\n theSeg.d;\r\n i++;\r\n }\r\n else {\r\n break;\r\n }\r\n }\r\n theURL = theURL + curDataString;\r\n this.addLongPollTag_(theURL, this.currentSerial);\r\n return true;\r\n }\r\n else {\r\n return false;\r\n }\r\n };\r\n /**\r\n * Queue a packet for transmission to the server.\r\n * @param segnum - A sequential id for this packet segment used for reassembly\r\n * @param totalsegs - The total number of segments in this packet\r\n * @param data - The data for this segment.\r\n */\r\n FirebaseIFrameScriptHolder.prototype.enqueueSegment = function (segnum, totalsegs, data) {\r\n //add this to the queue of segments to send.\r\n this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });\r\n //send the data immediately if there isn't already data being transmitted, unless\r\n //startLongPoll hasn't been called yet.\r\n if (this.alive) {\r\n this.newRequest_();\r\n }\r\n };\r\n /**\r\n * Add a script tag for a regular long-poll request.\r\n * @param {!string} url - The URL of the script tag.\r\n * @param {!number} serial - The serial number of the request.\r\n * @private\r\n */\r\n FirebaseIFrameScriptHolder.prototype.addLongPollTag_ = function (url, serial) {\r\n var _this = this;\r\n //remember that we sent this request.\r\n this.outstandingRequests.add(serial, 1);\r\n var doNewRequest = function () {\r\n _this.outstandingRequests.remove(serial);\r\n _this.newRequest_();\r\n };\r\n // If this request doesn't return on its own accord (by the server sending us some data), we'll\r\n // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.\r\n var keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));\r\n var readyStateCB = function () {\r\n // Request completed. Cancel the keepalive.\r\n clearTimeout(keepaliveTimeout);\r\n // Trigger a new request so we can continue receiving data.\r\n doNewRequest();\r\n };\r\n this.addTag(url, readyStateCB);\r\n };\r\n /**\r\n * Add an arbitrary script tag to the iframe.\r\n * @param {!string} url - The URL for the script tag source.\r\n * @param {!function()} loadCB - A callback to be triggered once the script has loaded.\r\n */\r\n FirebaseIFrameScriptHolder.prototype.addTag = function (url, loadCB) {\r\n var _this = this;\r\n if (util.isNodeSdk()) {\r\n this.doNodeLongPoll(url, loadCB);\r\n }\r\n else {\r\n setTimeout(function () {\r\n try {\r\n // if we're already closed, don't add this poll\r\n if (!_this.sendNewPolls)\r\n return;\r\n var newScript_1 = _this.myIFrame.doc.createElement('script');\r\n newScript_1.type = 'text/javascript';\r\n newScript_1.async = true;\r\n newScript_1.src = url;\r\n newScript_1.onload = newScript_1.onreadystatechange = function () {\r\n var rstate = newScript_1.readyState;\r\n if (!rstate || rstate === 'loaded' || rstate === 'complete') {\r\n newScript_1.onload = newScript_1.onreadystatechange = null;\r\n if (newScript_1.parentNode) {\r\n newScript_1.parentNode.removeChild(newScript_1);\r\n }\r\n loadCB();\r\n }\r\n };\r\n newScript_1.onerror = function () {\r\n log('Long-poll script failed to load: ' + url);\r\n _this.sendNewPolls = false;\r\n _this.close();\r\n };\r\n _this.myIFrame.doc.body.appendChild(newScript_1);\r\n }\r\n catch (e) {\r\n // TODO: we should make this error visible somehow\r\n }\r\n }, Math.floor(1));\r\n }\r\n };\r\n return FirebaseIFrameScriptHolder;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar WEBSOCKET_MAX_FRAME_SIZE = 16384;\r\nvar WEBSOCKET_KEEPALIVE_INTERVAL = 45000;\r\nvar WebSocketImpl = null;\r\nif (typeof MozWebSocket !== 'undefined') {\r\n WebSocketImpl = MozWebSocket;\r\n}\r\nelse if (typeof WebSocket !== 'undefined') {\r\n WebSocketImpl = WebSocket;\r\n}\r\n/**\r\n * Create a new websocket connection with the given callbacks.\r\n * @constructor\r\n * @implements {Transport}\r\n */\r\nvar WebSocketConnection = /** @class */ (function () {\r\n /**\r\n * @param {string} connId identifier for this transport\r\n * @param {RepoInfo} repoInfo The info for the websocket endpoint.\r\n * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport\r\n * session\r\n * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection\r\n */\r\n function WebSocketConnection(connId, repoInfo, transportSessionId, lastSessionId) {\r\n this.connId = connId;\r\n this.keepaliveTimer = null;\r\n this.frames = null;\r\n this.totalFrames = 0;\r\n this.bytesSent = 0;\r\n this.bytesReceived = 0;\r\n this.log_ = logWrapper(this.connId);\r\n this.stats_ = StatsManager.getCollection(repoInfo);\r\n this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId);\r\n }\r\n /**\r\n * @param {RepoInfo} repoInfo The info for the websocket endpoint.\r\n * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport\r\n * session\r\n * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection\r\n * @return {string} connection url\r\n * @private\r\n */\r\n WebSocketConnection.connectionURL_ = function (repoInfo, transportSessionId, lastSessionId) {\r\n var urlParams = {};\r\n urlParams[VERSION_PARAM] = PROTOCOL_VERSION;\r\n if (!util.isNodeSdk() &&\r\n typeof location !== 'undefined' &&\r\n location.href &&\r\n location.href.indexOf(FORGE_DOMAIN) !== -1) {\r\n urlParams[REFERER_PARAM] = FORGE_REF;\r\n }\r\n if (transportSessionId) {\r\n urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;\r\n }\r\n if (lastSessionId) {\r\n urlParams[LAST_SESSION_PARAM] = lastSessionId;\r\n }\r\n return repoInfo.connectionURL(WEBSOCKET, urlParams);\r\n };\r\n /**\r\n *\r\n * @param onMessage Callback when messages arrive\r\n * @param onDisconnect Callback with connection lost.\r\n */\r\n WebSocketConnection.prototype.open = function (onMessage, onDisconnect) {\r\n var _this = this;\r\n this.onDisconnect = onDisconnect;\r\n this.onMessage = onMessage;\r\n this.log_('Websocket connecting to ' + this.connURL);\r\n this.everConnected_ = false;\r\n // Assume failure until proven otherwise.\r\n PersistentStorage.set('previous_websocket_failure', true);\r\n try {\r\n if (util.isNodeSdk()) {\r\n var device = util.CONSTANTS.NODE_ADMIN ? 'AdminNode' : 'Node';\r\n // UA Format: Firebase////\r\n var options = {\r\n headers: {\r\n 'User-Agent': \"Firebase/\" + PROTOCOL_VERSION + \"/\" + firebase.SDK_VERSION + \"/\" + process.platform + \"/\" + device\r\n }\r\n };\r\n // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.\r\n var env = process['env'];\r\n var proxy = this.connURL.indexOf('wss://') == 0\r\n ? env['HTTPS_PROXY'] || env['https_proxy']\r\n : env['HTTP_PROXY'] || env['http_proxy'];\r\n if (proxy) {\r\n options['proxy'] = { origin: proxy };\r\n }\r\n this.mySock = new WebSocketImpl(this.connURL, [], options);\r\n }\r\n else {\r\n this.mySock = new WebSocketImpl(this.connURL);\r\n }\r\n }\r\n catch (e) {\r\n this.log_('Error instantiating WebSocket.');\r\n var error = e.message || e.data;\r\n if (error) {\r\n this.log_(error);\r\n }\r\n this.onClosed_();\r\n return;\r\n }\r\n this.mySock.onopen = function () {\r\n _this.log_('Websocket connected.');\r\n _this.everConnected_ = true;\r\n };\r\n this.mySock.onclose = function () {\r\n _this.log_('Websocket connection was disconnected.');\r\n _this.mySock = null;\r\n _this.onClosed_();\r\n };\r\n this.mySock.onmessage = function (m) {\r\n _this.handleIncomingFrame(m);\r\n };\r\n this.mySock.onerror = function (e) {\r\n _this.log_('WebSocket error. Closing connection.');\r\n var error = e.message || e.data;\r\n if (error) {\r\n _this.log_(error);\r\n }\r\n _this.onClosed_();\r\n };\r\n };\r\n /**\r\n * No-op for websockets, we don't need to do anything once the connection is confirmed as open\r\n */\r\n WebSocketConnection.prototype.start = function () { };\r\n WebSocketConnection.forceDisallow = function () {\r\n WebSocketConnection.forceDisallow_ = true;\r\n };\r\n WebSocketConnection.isAvailable = function () {\r\n var isOldAndroid = false;\r\n if (typeof navigator !== 'undefined' && navigator.userAgent) {\r\n var oldAndroidRegex = /Android ([0-9]{0,}\\.[0-9]{0,})/;\r\n var oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);\r\n if (oldAndroidMatch && oldAndroidMatch.length > 1) {\r\n if (parseFloat(oldAndroidMatch[1]) < 4.4) {\r\n isOldAndroid = true;\r\n }\r\n }\r\n }\r\n return (!isOldAndroid &&\r\n WebSocketImpl !== null &&\r\n !WebSocketConnection.forceDisallow_);\r\n };\r\n /**\r\n * Returns true if we previously failed to connect with this transport.\r\n * @return {boolean}\r\n */\r\n WebSocketConnection.previouslyFailed = function () {\r\n // If our persistent storage is actually only in-memory storage,\r\n // we default to assuming that it previously failed to be safe.\r\n return (PersistentStorage.isInMemoryStorage ||\r\n PersistentStorage.get('previous_websocket_failure') === true);\r\n };\r\n WebSocketConnection.prototype.markConnectionHealthy = function () {\r\n PersistentStorage.remove('previous_websocket_failure');\r\n };\r\n WebSocketConnection.prototype.appendFrame_ = function (data) {\r\n this.frames.push(data);\r\n if (this.frames.length == this.totalFrames) {\r\n var fullMess = this.frames.join('');\r\n this.frames = null;\r\n var jsonMess = util.jsonEval(fullMess);\r\n //handle the message\r\n this.onMessage(jsonMess);\r\n }\r\n };\r\n /**\r\n * @param {number} frameCount The number of frames we are expecting from the server\r\n * @private\r\n */\r\n WebSocketConnection.prototype.handleNewFrameCount_ = function (frameCount) {\r\n this.totalFrames = frameCount;\r\n this.frames = [];\r\n };\r\n /**\r\n * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1\r\n * @param {!String} data\r\n * @return {?String} Any remaining data to be process, or null if there is none\r\n * @private\r\n */\r\n WebSocketConnection.prototype.extractFrameCount_ = function (data) {\r\n util.assert(this.frames === null, 'We already have a frame buffer');\r\n // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced\r\n // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508\r\n if (data.length <= 6) {\r\n var frameCount = Number(data);\r\n if (!isNaN(frameCount)) {\r\n this.handleNewFrameCount_(frameCount);\r\n return null;\r\n }\r\n }\r\n this.handleNewFrameCount_(1);\r\n return data;\r\n };\r\n /**\r\n * Process a websocket frame that has arrived from the server.\r\n * @param mess The frame data\r\n */\r\n WebSocketConnection.prototype.handleIncomingFrame = function (mess) {\r\n if (this.mySock === null)\r\n return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.\r\n var data = mess['data'];\r\n this.bytesReceived += data.length;\r\n this.stats_.incrementCounter('bytes_received', data.length);\r\n this.resetKeepAlive();\r\n if (this.frames !== null) {\r\n // we're buffering\r\n this.appendFrame_(data);\r\n }\r\n else {\r\n // try to parse out a frame count, otherwise, assume 1 and process it\r\n var remainingData = this.extractFrameCount_(data);\r\n if (remainingData !== null) {\r\n this.appendFrame_(remainingData);\r\n }\r\n }\r\n };\r\n /**\r\n * Send a message to the server\r\n * @param {Object} data The JSON object to transmit\r\n */\r\n WebSocketConnection.prototype.send = function (data) {\r\n this.resetKeepAlive();\r\n var dataStr = util.stringify(data);\r\n this.bytesSent += dataStr.length;\r\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\r\n //We can only fit a certain amount in each websocket frame, so we need to split this request\r\n //up into multiple pieces if it doesn't fit in one request.\r\n var dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);\r\n //Send the length header\r\n if (dataSegs.length > 1) {\r\n this.sendString_(String(dataSegs.length));\r\n }\r\n //Send the actual data in segments.\r\n for (var i = 0; i < dataSegs.length; i++) {\r\n this.sendString_(dataSegs[i]);\r\n }\r\n };\r\n WebSocketConnection.prototype.shutdown_ = function () {\r\n this.isClosed_ = true;\r\n if (this.keepaliveTimer) {\r\n clearInterval(this.keepaliveTimer);\r\n this.keepaliveTimer = null;\r\n }\r\n if (this.mySock) {\r\n this.mySock.close();\r\n this.mySock = null;\r\n }\r\n };\r\n WebSocketConnection.prototype.onClosed_ = function () {\r\n if (!this.isClosed_) {\r\n this.log_('WebSocket is closing itself');\r\n this.shutdown_();\r\n // since this is an internal close, trigger the close listener\r\n if (this.onDisconnect) {\r\n this.onDisconnect(this.everConnected_);\r\n this.onDisconnect = null;\r\n }\r\n }\r\n };\r\n /**\r\n * External-facing close handler.\r\n * Close the websocket and kill the connection.\r\n */\r\n WebSocketConnection.prototype.close = function () {\r\n if (!this.isClosed_) {\r\n this.log_('WebSocket is being closed');\r\n this.shutdown_();\r\n }\r\n };\r\n /**\r\n * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after\r\n * the last activity.\r\n */\r\n WebSocketConnection.prototype.resetKeepAlive = function () {\r\n var _this = this;\r\n clearInterval(this.keepaliveTimer);\r\n this.keepaliveTimer = setInterval(function () {\r\n //If there has been no websocket activity for a while, send a no-op\r\n if (_this.mySock) {\r\n _this.sendString_('0');\r\n }\r\n _this.resetKeepAlive();\r\n }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));\r\n };\r\n /**\r\n * Send a string over the websocket.\r\n *\r\n * @param {string} str String to send.\r\n * @private\r\n */\r\n WebSocketConnection.prototype.sendString_ = function (str) {\r\n // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()\r\n // calls for some unknown reason. We treat these as an error and disconnect.\r\n // See https://app.asana.com/0/58926111402292/68021340250410\r\n try {\r\n this.mySock.send(str);\r\n }\r\n catch (e) {\r\n this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');\r\n setTimeout(this.onClosed_.bind(this), 0);\r\n }\r\n };\r\n /**\r\n * Number of response before we consider the connection \"healthy.\"\r\n * @type {number}\r\n */\r\n WebSocketConnection.responsesRequiredToBeHealthy = 2;\r\n /**\r\n * Time to wait for the connection te become healthy before giving up.\r\n * @type {number}\r\n */\r\n WebSocketConnection.healthyTimeout = 30000;\r\n return WebSocketConnection;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Currently simplistic, this class manages what transport a Connection should use at various stages of its\r\n * lifecycle.\r\n *\r\n * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if\r\n * they are available.\r\n * @constructor\r\n */\r\nvar TransportManager = /** @class */ (function () {\r\n /**\r\n * @param {!RepoInfo} repoInfo Metadata around the namespace we're connecting to\r\n */\r\n function TransportManager(repoInfo) {\r\n this.initTransports_(repoInfo);\r\n }\r\n Object.defineProperty(TransportManager, \"ALL_TRANSPORTS\", {\r\n /**\r\n * @const\r\n * @type {!Array.}\r\n */\r\n get: function () {\r\n return [BrowserPollConnection, WebSocketConnection];\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n /**\r\n * @param {!RepoInfo} repoInfo\r\n * @private\r\n */\r\n TransportManager.prototype.initTransports_ = function (repoInfo) {\r\n var isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable']();\r\n var isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();\r\n if (repoInfo.webSocketOnly) {\r\n if (!isWebSocketsAvailable)\r\n warn(\"wss:// URL used, but browser isn't known to support websockets. Trying anyway.\");\r\n isSkipPollConnection = true;\r\n }\r\n if (isSkipPollConnection) {\r\n this.transports_ = [WebSocketConnection];\r\n }\r\n else {\r\n var transports_1 = (this.transports_ = []);\r\n each(TransportManager.ALL_TRANSPORTS, function (i, transport) {\r\n if (transport && transport['isAvailable']()) {\r\n transports_1.push(transport);\r\n }\r\n });\r\n }\r\n };\r\n /**\r\n * @return {function(new:Transport, !string, !RepoInfo, string=, string=)} The constructor for the\r\n * initial transport to use\r\n */\r\n TransportManager.prototype.initialTransport = function () {\r\n if (this.transports_.length > 0) {\r\n return this.transports_[0];\r\n }\r\n else {\r\n throw new Error('No transports available');\r\n }\r\n };\r\n /**\r\n * @return {?function(new:Transport, function(),function(), string=)} The constructor for the next\r\n * transport, or null\r\n */\r\n TransportManager.prototype.upgradeTransport = function () {\r\n if (this.transports_.length > 1) {\r\n return this.transports_[1];\r\n }\r\n else {\r\n return null;\r\n }\r\n };\r\n return TransportManager;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Abort upgrade attempt if it takes longer than 60s.\r\nvar UPGRADE_TIMEOUT = 60000;\r\n// For some transports (WebSockets), we need to \"validate\" the transport by exchanging a few requests and responses.\r\n// If we haven't sent enough requests within 5s, we'll start sending noop ping requests.\r\nvar DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;\r\n// If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data)\r\n// then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout\r\n// but we've sent/received enough bytes, we don't cancel the connection.\r\nvar BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;\r\nvar BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;\r\nvar MESSAGE_TYPE = 't';\r\nvar MESSAGE_DATA = 'd';\r\nvar CONTROL_SHUTDOWN = 's';\r\nvar CONTROL_RESET = 'r';\r\nvar CONTROL_ERROR = 'e';\r\nvar CONTROL_PONG = 'o';\r\nvar SWITCH_ACK = 'a';\r\nvar END_TRANSMISSION = 'n';\r\nvar PING = 'p';\r\nvar SERVER_HELLO = 'h';\r\n/**\r\n * Creates a new real-time connection to the server using whichever method works\r\n * best in the current browser.\r\n *\r\n * @constructor\r\n */\r\nvar Connection = /** @class */ (function () {\r\n /**\r\n * @param {!string} id - an id for this connection\r\n * @param {!RepoInfo} repoInfo_ - the info for the endpoint to connect to\r\n * @param {function(Object)} onMessage_ - the callback to be triggered when a server-push message arrives\r\n * @param {function(number, string)} onReady_ - the callback to be triggered when this connection is ready to send messages.\r\n * @param {function()} onDisconnect_ - the callback to be triggered when a connection was lost\r\n * @param {function(string)} onKill_ - the callback to be triggered when this connection has permanently shut down.\r\n * @param {string=} lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server\r\n */\r\n function Connection(id, repoInfo_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {\r\n this.id = id;\r\n this.repoInfo_ = repoInfo_;\r\n this.onMessage_ = onMessage_;\r\n this.onReady_ = onReady_;\r\n this.onDisconnect_ = onDisconnect_;\r\n this.onKill_ = onKill_;\r\n this.lastSessionId = lastSessionId;\r\n this.connectionCount = 0;\r\n this.pendingDataMessages = [];\r\n this.state_ = 0 /* CONNECTING */;\r\n this.log_ = logWrapper('c:' + this.id + ':');\r\n this.transportManager_ = new TransportManager(repoInfo_);\r\n this.log_('Connection created');\r\n this.start_();\r\n }\r\n /**\r\n * Starts a connection attempt\r\n * @private\r\n */\r\n Connection.prototype.start_ = function () {\r\n var _this = this;\r\n var conn = this.transportManager_.initialTransport();\r\n this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, undefined, this.lastSessionId);\r\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\r\n // can consider the transport healthy.\r\n this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;\r\n var onMessageReceived = this.connReceiver_(this.conn_);\r\n var onConnectionLost = this.disconnReceiver_(this.conn_);\r\n this.tx_ = this.conn_;\r\n this.rx_ = this.conn_;\r\n this.secondaryConn_ = null;\r\n this.isHealthy_ = false;\r\n /*\r\n * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.\r\n * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.\r\n * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should\r\n * still have the context of your originating frame.\r\n */\r\n setTimeout(function () {\r\n // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it\r\n _this.conn_ && _this.conn_.open(onMessageReceived, onConnectionLost);\r\n }, Math.floor(0));\r\n var healthyTimeout_ms = conn['healthyTimeout'] || 0;\r\n if (healthyTimeout_ms > 0) {\r\n this.healthyTimeout_ = setTimeoutNonBlocking(function () {\r\n _this.healthyTimeout_ = null;\r\n if (!_this.isHealthy_) {\r\n if (_this.conn_ &&\r\n _this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {\r\n _this.log_('Connection exceeded healthy timeout but has received ' +\r\n _this.conn_.bytesReceived +\r\n ' bytes. Marking connection healthy.');\r\n _this.isHealthy_ = true;\r\n _this.conn_.markConnectionHealthy();\r\n }\r\n else if (_this.conn_ &&\r\n _this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {\r\n _this.log_('Connection exceeded healthy timeout but has sent ' +\r\n _this.conn_.bytesSent +\r\n ' bytes. Leaving connection alive.');\r\n // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to\r\n // the server.\r\n }\r\n else {\r\n _this.log_('Closing unhealthy connection after timeout.');\r\n _this.close();\r\n }\r\n }\r\n }, Math.floor(healthyTimeout_ms));\r\n }\r\n };\r\n /**\r\n * @return {!string}\r\n * @private\r\n */\r\n Connection.prototype.nextTransportId_ = function () {\r\n return 'c:' + this.id + ':' + this.connectionCount++;\r\n };\r\n Connection.prototype.disconnReceiver_ = function (conn) {\r\n var _this = this;\r\n return function (everConnected) {\r\n if (conn === _this.conn_) {\r\n _this.onConnectionLost_(everConnected);\r\n }\r\n else if (conn === _this.secondaryConn_) {\r\n _this.log_('Secondary connection lost.');\r\n _this.onSecondaryConnectionLost_();\r\n }\r\n else {\r\n _this.log_('closing an old connection');\r\n }\r\n };\r\n };\r\n Connection.prototype.connReceiver_ = function (conn) {\r\n var _this = this;\r\n return function (message) {\r\n if (_this.state_ != 2 /* DISCONNECTED */) {\r\n if (conn === _this.rx_) {\r\n _this.onPrimaryMessageReceived_(message);\r\n }\r\n else if (conn === _this.secondaryConn_) {\r\n _this.onSecondaryMessageReceived_(message);\r\n }\r\n else {\r\n _this.log_('message on old connection');\r\n }\r\n }\r\n };\r\n };\r\n /**\r\n *\r\n * @param {Object} dataMsg An arbitrary data message to be sent to the server\r\n */\r\n Connection.prototype.sendRequest = function (dataMsg) {\r\n // wrap in a data message envelope and send it on\r\n var msg = { t: 'd', d: dataMsg };\r\n this.sendData_(msg);\r\n };\r\n Connection.prototype.tryCleanupConnection = function () {\r\n if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {\r\n this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);\r\n this.conn_ = this.secondaryConn_;\r\n this.secondaryConn_ = null;\r\n // the server will shutdown the old connection\r\n }\r\n };\r\n Connection.prototype.onSecondaryControl_ = function (controlData) {\r\n if (MESSAGE_TYPE in controlData) {\r\n var cmd = controlData[MESSAGE_TYPE];\r\n if (cmd === SWITCH_ACK) {\r\n this.upgradeIfSecondaryHealthy_();\r\n }\r\n else if (cmd === CONTROL_RESET) {\r\n // Most likely the session wasn't valid. Abandon the switch attempt\r\n this.log_('Got a reset on secondary, closing it');\r\n this.secondaryConn_.close();\r\n // If we were already using this connection for something, than we need to fully close\r\n if (this.tx_ === this.secondaryConn_ ||\r\n this.rx_ === this.secondaryConn_) {\r\n this.close();\r\n }\r\n }\r\n else if (cmd === CONTROL_PONG) {\r\n this.log_('got pong on secondary.');\r\n this.secondaryResponsesRequired_--;\r\n this.upgradeIfSecondaryHealthy_();\r\n }\r\n }\r\n };\r\n Connection.prototype.onSecondaryMessageReceived_ = function (parsedData) {\r\n var layer = requireKey('t', parsedData);\r\n var data = requireKey('d', parsedData);\r\n if (layer == 'c') {\r\n this.onSecondaryControl_(data);\r\n }\r\n else if (layer == 'd') {\r\n // got a data message, but we're still second connection. Need to buffer it up\r\n this.pendingDataMessages.push(data);\r\n }\r\n else {\r\n throw new Error('Unknown protocol layer: ' + layer);\r\n }\r\n };\r\n Connection.prototype.upgradeIfSecondaryHealthy_ = function () {\r\n if (this.secondaryResponsesRequired_ <= 0) {\r\n this.log_('Secondary connection is healthy.');\r\n this.isHealthy_ = true;\r\n this.secondaryConn_.markConnectionHealthy();\r\n this.proceedWithUpgrade_();\r\n }\r\n else {\r\n // Send a ping to make sure the connection is healthy.\r\n this.log_('sending ping on secondary.');\r\n this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });\r\n }\r\n };\r\n Connection.prototype.proceedWithUpgrade_ = function () {\r\n // tell this connection to consider itself open\r\n this.secondaryConn_.start();\r\n // send ack\r\n this.log_('sending client ack on secondary');\r\n this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });\r\n // send end packet on primary transport, switch to sending on this one\r\n // can receive on this one, buffer responses until end received on primary transport\r\n this.log_('Ending transmission on primary');\r\n this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });\r\n this.tx_ = this.secondaryConn_;\r\n this.tryCleanupConnection();\r\n };\r\n Connection.prototype.onPrimaryMessageReceived_ = function (parsedData) {\r\n // Must refer to parsedData properties in quotes, so closure doesn't touch them.\r\n var layer = requireKey('t', parsedData);\r\n var data = requireKey('d', parsedData);\r\n if (layer == 'c') {\r\n this.onControl_(data);\r\n }\r\n else if (layer == 'd') {\r\n this.onDataMessage_(data);\r\n }\r\n };\r\n Connection.prototype.onDataMessage_ = function (message) {\r\n this.onPrimaryResponse_();\r\n // We don't do anything with data messages, just kick them up a level\r\n this.onMessage_(message);\r\n };\r\n Connection.prototype.onPrimaryResponse_ = function () {\r\n if (!this.isHealthy_) {\r\n this.primaryResponsesRequired_--;\r\n if (this.primaryResponsesRequired_ <= 0) {\r\n this.log_('Primary connection is healthy.');\r\n this.isHealthy_ = true;\r\n this.conn_.markConnectionHealthy();\r\n }\r\n }\r\n };\r\n Connection.prototype.onControl_ = function (controlData) {\r\n var cmd = requireKey(MESSAGE_TYPE, controlData);\r\n if (MESSAGE_DATA in controlData) {\r\n var payload = controlData[MESSAGE_DATA];\r\n if (cmd === SERVER_HELLO) {\r\n this.onHandshake_(payload);\r\n }\r\n else if (cmd === END_TRANSMISSION) {\r\n this.log_('recvd end transmission on primary');\r\n this.rx_ = this.secondaryConn_;\r\n for (var i = 0; i < this.pendingDataMessages.length; ++i) {\r\n this.onDataMessage_(this.pendingDataMessages[i]);\r\n }\r\n this.pendingDataMessages = [];\r\n this.tryCleanupConnection();\r\n }\r\n else if (cmd === CONTROL_SHUTDOWN) {\r\n // This was previously the 'onKill' callback passed to the lower-level connection\r\n // payload in this case is the reason for the shutdown. Generally a human-readable error\r\n this.onConnectionShutdown_(payload);\r\n }\r\n else if (cmd === CONTROL_RESET) {\r\n // payload in this case is the host we should contact\r\n this.onReset_(payload);\r\n }\r\n else if (cmd === CONTROL_ERROR) {\r\n error('Server Error: ' + payload);\r\n }\r\n else if (cmd === CONTROL_PONG) {\r\n this.log_('got pong on primary.');\r\n this.onPrimaryResponse_();\r\n this.sendPingOnPrimaryIfNecessary_();\r\n }\r\n else {\r\n error('Unknown control packet command: ' + cmd);\r\n }\r\n }\r\n };\r\n /**\r\n *\r\n * @param {Object} handshake The handshake data returned from the server\r\n * @private\r\n */\r\n Connection.prototype.onHandshake_ = function (handshake) {\r\n var timestamp = handshake.ts;\r\n var version = handshake.v;\r\n var host = handshake.h;\r\n this.sessionId = handshake.s;\r\n this.repoInfo_.updateHost(host);\r\n // if we've already closed the connection, then don't bother trying to progress further\r\n if (this.state_ == 0 /* CONNECTING */) {\r\n this.conn_.start();\r\n this.onConnectionEstablished_(this.conn_, timestamp);\r\n if (PROTOCOL_VERSION !== version) {\r\n warn('Protocol version mismatch detected');\r\n }\r\n // TODO: do we want to upgrade? when? maybe a delay?\r\n this.tryStartUpgrade_();\r\n }\r\n };\r\n Connection.prototype.tryStartUpgrade_ = function () {\r\n var conn = this.transportManager_.upgradeTransport();\r\n if (conn) {\r\n this.startUpgrade_(conn);\r\n }\r\n };\r\n Connection.prototype.startUpgrade_ = function (conn) {\r\n var _this = this;\r\n this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.sessionId);\r\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\r\n // can consider the transport healthy.\r\n this.secondaryResponsesRequired_ =\r\n conn['responsesRequiredToBeHealthy'] || 0;\r\n var onMessage = this.connReceiver_(this.secondaryConn_);\r\n var onDisconnect = this.disconnReceiver_(this.secondaryConn_);\r\n this.secondaryConn_.open(onMessage, onDisconnect);\r\n // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.\r\n setTimeoutNonBlocking(function () {\r\n if (_this.secondaryConn_) {\r\n _this.log_('Timed out trying to upgrade.');\r\n _this.secondaryConn_.close();\r\n }\r\n }, Math.floor(UPGRADE_TIMEOUT));\r\n };\r\n Connection.prototype.onReset_ = function (host) {\r\n this.log_('Reset packet received. New host: ' + host);\r\n this.repoInfo_.updateHost(host);\r\n // TODO: if we're already \"connected\", we need to trigger a disconnect at the next layer up.\r\n // We don't currently support resets after the connection has already been established\r\n if (this.state_ === 1 /* CONNECTED */) {\r\n this.close();\r\n }\r\n else {\r\n // Close whatever connections we have open and start again.\r\n this.closeConnections_();\r\n this.start_();\r\n }\r\n };\r\n Connection.prototype.onConnectionEstablished_ = function (conn, timestamp) {\r\n var _this = this;\r\n this.log_('Realtime connection established.');\r\n this.conn_ = conn;\r\n this.state_ = 1 /* CONNECTED */;\r\n if (this.onReady_) {\r\n this.onReady_(timestamp, this.sessionId);\r\n this.onReady_ = null;\r\n }\r\n // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,\r\n // send some pings.\r\n if (this.primaryResponsesRequired_ === 0) {\r\n this.log_('Primary connection is healthy.');\r\n this.isHealthy_ = true;\r\n }\r\n else {\r\n setTimeoutNonBlocking(function () {\r\n _this.sendPingOnPrimaryIfNecessary_();\r\n }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));\r\n }\r\n };\r\n Connection.prototype.sendPingOnPrimaryIfNecessary_ = function () {\r\n // If the connection isn't considered healthy yet, we'll send a noop ping packet request.\r\n if (!this.isHealthy_ && this.state_ === 1 /* CONNECTED */) {\r\n this.log_('sending ping on primary.');\r\n this.sendData_({ t: 'c', d: { t: PING, d: {} } });\r\n }\r\n };\r\n Connection.prototype.onSecondaryConnectionLost_ = function () {\r\n var conn = this.secondaryConn_;\r\n this.secondaryConn_ = null;\r\n if (this.tx_ === conn || this.rx_ === conn) {\r\n // we are relying on this connection already in some capacity. Therefore, a failure is real\r\n this.close();\r\n }\r\n };\r\n /**\r\n *\r\n * @param {boolean} everConnected Whether or not the connection ever reached a server. Used to determine if\r\n * we should flush the host cache\r\n * @private\r\n */\r\n Connection.prototype.onConnectionLost_ = function (everConnected) {\r\n this.conn_ = null;\r\n // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting\r\n // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.\r\n if (!everConnected && this.state_ === 0 /* CONNECTING */) {\r\n this.log_('Realtime connection failed.');\r\n // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away\r\n if (this.repoInfo_.isCacheableHost()) {\r\n PersistentStorage.remove('host:' + this.repoInfo_.host);\r\n // reset the internal host to what we would show the user, i.e. .firebaseio.com\r\n this.repoInfo_.internalHost = this.repoInfo_.host;\r\n }\r\n }\r\n else if (this.state_ === 1 /* CONNECTED */) {\r\n this.log_('Realtime connection lost.');\r\n }\r\n this.close();\r\n };\r\n /**\r\n *\r\n * @param {string} reason\r\n * @private\r\n */\r\n Connection.prototype.onConnectionShutdown_ = function (reason) {\r\n this.log_('Connection shutdown command received. Shutting down...');\r\n if (this.onKill_) {\r\n this.onKill_(reason);\r\n this.onKill_ = null;\r\n }\r\n // We intentionally don't want to fire onDisconnect (kill is a different case),\r\n // so clear the callback.\r\n this.onDisconnect_ = null;\r\n this.close();\r\n };\r\n Connection.prototype.sendData_ = function (data) {\r\n if (this.state_ !== 1 /* CONNECTED */) {\r\n throw 'Connection is not connected';\r\n }\r\n else {\r\n this.tx_.send(data);\r\n }\r\n };\r\n /**\r\n * Cleans up this connection, calling the appropriate callbacks\r\n */\r\n Connection.prototype.close = function () {\r\n if (this.state_ !== 2 /* DISCONNECTED */) {\r\n this.log_('Closing realtime connection.');\r\n this.state_ = 2 /* DISCONNECTED */;\r\n this.closeConnections_();\r\n if (this.onDisconnect_) {\r\n this.onDisconnect_();\r\n this.onDisconnect_ = null;\r\n }\r\n }\r\n };\r\n /**\r\n *\r\n * @private\r\n */\r\n Connection.prototype.closeConnections_ = function () {\r\n this.log_('Shutting down all connections');\r\n if (this.conn_) {\r\n this.conn_.close();\r\n this.conn_ = null;\r\n }\r\n if (this.secondaryConn_) {\r\n this.secondaryConn_.close();\r\n this.secondaryConn_ = null;\r\n }\r\n if (this.healthyTimeout_) {\r\n clearTimeout(this.healthyTimeout_);\r\n this.healthyTimeout_ = null;\r\n }\r\n };\r\n return Connection;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface defining the set of actions that can be performed against the Firebase server\r\n * (basically corresponds to our wire protocol).\r\n *\r\n * @interface\r\n */\r\nvar ServerActions = /** @class */ (function () {\r\n function ServerActions() {\r\n }\r\n /**\r\n * @param {string} pathString\r\n * @param {*} data\r\n * @param {function(string, string)=} onComplete\r\n * @param {string=} hash\r\n */\r\n ServerActions.prototype.put = function (pathString, data, onComplete, hash) { };\r\n /**\r\n * @param {string} pathString\r\n * @param {*} data\r\n * @param {function(string, ?string)} onComplete\r\n * @param {string=} hash\r\n */\r\n ServerActions.prototype.merge = function (pathString, data, onComplete, hash) { };\r\n /**\r\n * Refreshes the auth token for the current connection.\r\n * @param {string} token The authentication token\r\n */\r\n ServerActions.prototype.refreshAuthToken = function (token) { };\r\n /**\r\n * @param {string} pathString\r\n * @param {*} data\r\n * @param {function(string, string)=} onComplete\r\n */\r\n ServerActions.prototype.onDisconnectPut = function (pathString, data, onComplete) { };\r\n /**\r\n * @param {string} pathString\r\n * @param {*} data\r\n * @param {function(string, string)=} onComplete\r\n */\r\n ServerActions.prototype.onDisconnectMerge = function (pathString, data, onComplete) { };\r\n /**\r\n * @param {string} pathString\r\n * @param {function(string, string)=} onComplete\r\n */\r\n ServerActions.prototype.onDisconnectCancel = function (pathString, onComplete) { };\r\n /**\r\n * @param {Object.} stats\r\n */\r\n ServerActions.prototype.reportStats = function (stats) { };\r\n return ServerActions;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar RECONNECT_MIN_DELAY = 1000;\r\nvar RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)\r\nvar RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)\r\nvar RECONNECT_DELAY_MULTIPLIER = 1.3;\r\nvar RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.\r\nvar SERVER_KILL_INTERRUPT_REASON = 'server_kill';\r\n// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.\r\nvar INVALID_AUTH_TOKEN_THRESHOLD = 3;\r\n/**\r\n * Firebase connection. Abstracts wire protocol and handles reconnecting.\r\n *\r\n * NOTE: All JSON objects sent to the realtime connection must have property names enclosed\r\n * in quotes to make sure the closure compiler does not minify them.\r\n */\r\nvar PersistentConnection = /** @class */ (function (_super) {\r\n tslib_1.__extends(PersistentConnection, _super);\r\n /**\r\n * @implements {ServerActions}\r\n * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to\r\n * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server\r\n * @param onConnectStatus_\r\n * @param onServerInfoUpdate_\r\n * @param authTokenProvider_\r\n * @param authOverride_\r\n */\r\n function PersistentConnection(repoInfo_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, authOverride_) {\r\n var _this = _super.call(this) || this;\r\n _this.repoInfo_ = repoInfo_;\r\n _this.onDataUpdate_ = onDataUpdate_;\r\n _this.onConnectStatus_ = onConnectStatus_;\r\n _this.onServerInfoUpdate_ = onServerInfoUpdate_;\r\n _this.authTokenProvider_ = authTokenProvider_;\r\n _this.authOverride_ = authOverride_;\r\n // Used for diagnostic logging.\r\n _this.id = PersistentConnection.nextPersistentConnectionId_++;\r\n _this.log_ = logWrapper('p:' + _this.id + ':');\r\n /** @private {Object} */\r\n _this.interruptReasons_ = {};\r\n _this.listens_ = {};\r\n _this.outstandingPuts_ = [];\r\n _this.outstandingPutCount_ = 0;\r\n _this.onDisconnectRequestQueue_ = [];\r\n _this.connected_ = false;\r\n _this.reconnectDelay_ = RECONNECT_MIN_DELAY;\r\n _this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;\r\n _this.securityDebugCallback_ = null;\r\n _this.lastSessionId = null;\r\n /** @private {number|null} */\r\n _this.establishConnectionTimer_ = null;\r\n /** @private {boolean} */\r\n _this.visible_ = false;\r\n // Before we get connected, we keep a queue of pending messages to send.\r\n _this.requestCBHash_ = {};\r\n _this.requestNumber_ = 0;\r\n /** @private {?{\r\n * sendRequest(Object),\r\n * close()\r\n * }} */\r\n _this.realtime_ = null;\r\n /** @private {string|null} */\r\n _this.authToken_ = null;\r\n _this.forceTokenRefresh_ = false;\r\n _this.invalidAuthTokenCount_ = 0;\r\n _this.firstConnection_ = true;\r\n _this.lastConnectionAttemptTime_ = null;\r\n _this.lastConnectionEstablishedTime_ = null;\r\n if (authOverride_ && !util.isNodeSdk()) {\r\n throw new Error('Auth override specified in options, but not supported on non Node.js platforms');\r\n }\r\n _this.scheduleConnect_(0);\r\n VisibilityMonitor.getInstance().on('visible', _this.onVisible_, _this);\r\n if (repoInfo_.host.indexOf('fblocal') === -1) {\r\n OnlineMonitor.getInstance().on('online', _this.onOnline_, _this);\r\n }\r\n return _this;\r\n }\r\n /**\r\n * @param {!string} action\r\n * @param {*} body\r\n * @param {function(*)=} onResponse\r\n * @protected\r\n */\r\n PersistentConnection.prototype.sendRequest = function (action, body, onResponse) {\r\n var curReqNum = ++this.requestNumber_;\r\n var msg = { r: curReqNum, a: action, b: body };\r\n this.log_(util.stringify(msg));\r\n util.assert(this.connected_, \"sendRequest call when we're not connected not allowed.\");\r\n this.realtime_.sendRequest(msg);\r\n if (onResponse) {\r\n this.requestCBHash_[curReqNum] = onResponse;\r\n }\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n PersistentConnection.prototype.listen = function (query, currentHashFn, tag, onComplete) {\r\n var queryId = query.queryIdentifier();\r\n var pathString = query.path.toString();\r\n this.log_('Listen called for ' + pathString + ' ' + queryId);\r\n this.listens_[pathString] = this.listens_[pathString] || {};\r\n util.assert(query.getQueryParams().isDefault() ||\r\n !query.getQueryParams().loadsAllData(), 'listen() called for non-default but complete query');\r\n util.assert(!this.listens_[pathString][queryId], 'listen() called twice for same path/queryId.');\r\n var listenSpec = {\r\n onComplete: onComplete,\r\n hashFn: currentHashFn,\r\n query: query,\r\n tag: tag\r\n };\r\n this.listens_[pathString][queryId] = listenSpec;\r\n if (this.connected_) {\r\n this.sendListen_(listenSpec);\r\n }\r\n };\r\n /**\r\n * @param {!{onComplete(),\r\n * hashFn():!string,\r\n * query: !Query,\r\n * tag: ?number}} listenSpec\r\n * @private\r\n */\r\n PersistentConnection.prototype.sendListen_ = function (listenSpec) {\r\n var _this = this;\r\n var query = listenSpec.query;\r\n var pathString = query.path.toString();\r\n var queryId = query.queryIdentifier();\r\n this.log_('Listen on ' + pathString + ' for ' + queryId);\r\n var req = { /*path*/ p: pathString };\r\n var action = 'q';\r\n // Only bother to send query if it's non-default.\r\n if (listenSpec.tag) {\r\n req['q'] = query.queryObject();\r\n req['t'] = listenSpec.tag;\r\n }\r\n req[ /*hash*/'h'] = listenSpec.hashFn();\r\n this.sendRequest(action, req, function (message) {\r\n var payload = message[ /*data*/'d'];\r\n var status = message[ /*status*/'s'];\r\n // print warnings in any case...\r\n PersistentConnection.warnOnListenWarnings_(payload, query);\r\n var currentListenSpec = _this.listens_[pathString] && _this.listens_[pathString][queryId];\r\n // only trigger actions if the listen hasn't been removed and readded\r\n if (currentListenSpec === listenSpec) {\r\n _this.log_('listen response', message);\r\n if (status !== 'ok') {\r\n _this.removeListen_(pathString, queryId);\r\n }\r\n if (listenSpec.onComplete) {\r\n listenSpec.onComplete(status, payload);\r\n }\r\n }\r\n });\r\n };\r\n /**\r\n * @param {*} payload\r\n * @param {!Query} query\r\n * @private\r\n */\r\n PersistentConnection.warnOnListenWarnings_ = function (payload, query) {\r\n if (payload && typeof payload === 'object' && util.contains(payload, 'w')) {\r\n var warnings = util.safeGet(payload, 'w');\r\n if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {\r\n var indexSpec = '\".indexOn\": \"' +\r\n query\r\n .getQueryParams()\r\n .getIndex()\r\n .toString() +\r\n '\"';\r\n var indexPath = query.path.toString();\r\n warn(\"Using an unspecified index. Your data will be downloaded and \" +\r\n (\"filtered on the client. Consider adding \" + indexSpec + \" at \") +\r\n (indexPath + \" to your security rules for better performance.\"));\r\n }\r\n }\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n PersistentConnection.prototype.refreshAuthToken = function (token) {\r\n this.authToken_ = token;\r\n this.log_('Auth token refreshed');\r\n if (this.authToken_) {\r\n this.tryAuth();\r\n }\r\n else {\r\n //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete\r\n //the credential so we dont become authenticated next time we connect.\r\n if (this.connected_) {\r\n this.sendRequest('unauth', {}, function () { });\r\n }\r\n }\r\n this.reduceReconnectDelayIfAdminCredential_(token);\r\n };\r\n /**\r\n * @param {!string} credential\r\n * @private\r\n */\r\n PersistentConnection.prototype.reduceReconnectDelayIfAdminCredential_ = function (credential) {\r\n // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).\r\n // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.\r\n var isFirebaseSecret = credential && credential.length === 40;\r\n if (isFirebaseSecret || util.isAdmin(credential)) {\r\n this.log_('Admin auth credential detected. Reducing max reconnect time.');\r\n this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\r\n }\r\n };\r\n /**\r\n * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like\r\n * a auth revoked (the connection is closed).\r\n */\r\n PersistentConnection.prototype.tryAuth = function () {\r\n var _this = this;\r\n if (this.connected_ && this.authToken_) {\r\n var token_1 = this.authToken_;\r\n var authMethod = util.isValidFormat(token_1) ? 'auth' : 'gauth';\r\n var requestData = { cred: token_1 };\r\n if (this.authOverride_ === null) {\r\n requestData['noauth'] = true;\r\n }\r\n else if (typeof this.authOverride_ === 'object') {\r\n requestData['authvar'] = this.authOverride_;\r\n }\r\n this.sendRequest(authMethod, requestData, function (res) {\r\n var status = res[ /*status*/'s'];\r\n var data = res[ /*data*/'d'] || 'error';\r\n if (_this.authToken_ === token_1) {\r\n if (status === 'ok') {\r\n _this.invalidAuthTokenCount_ = 0;\r\n }\r\n else {\r\n // Triggers reconnect and force refresh for auth token\r\n _this.onAuthRevoked_(status, data);\r\n }\r\n }\r\n });\r\n }\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n PersistentConnection.prototype.unlisten = function (query, tag) {\r\n var pathString = query.path.toString();\r\n var queryId = query.queryIdentifier();\r\n this.log_('Unlisten called for ' + pathString + ' ' + queryId);\r\n util.assert(query.getQueryParams().isDefault() ||\r\n !query.getQueryParams().loadsAllData(), 'unlisten() called for non-default but complete query');\r\n var listen = this.removeListen_(pathString, queryId);\r\n if (listen && this.connected_) {\r\n this.sendUnlisten_(pathString, queryId, query.queryObject(), tag);\r\n }\r\n };\r\n PersistentConnection.prototype.sendUnlisten_ = function (pathString, queryId, queryObj, tag) {\r\n this.log_('Unlisten on ' + pathString + ' for ' + queryId);\r\n var req = { /*path*/ p: pathString };\r\n var action = 'n';\r\n // Only bother sending queryId if it's non-default.\r\n if (tag) {\r\n req['q'] = queryObj;\r\n req['t'] = tag;\r\n }\r\n this.sendRequest(action, req);\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n PersistentConnection.prototype.onDisconnectPut = function (pathString, data, onComplete) {\r\n if (this.connected_) {\r\n this.sendOnDisconnect_('o', pathString, data, onComplete);\r\n }\r\n else {\r\n this.onDisconnectRequestQueue_.push({\r\n pathString: pathString,\r\n action: 'o',\r\n data: data,\r\n onComplete: onComplete\r\n });\r\n }\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n PersistentConnection.prototype.onDisconnectMerge = function (pathString, data, onComplete) {\r\n if (this.connected_) {\r\n this.sendOnDisconnect_('om', pathString, data, onComplete);\r\n }\r\n else {\r\n this.onDisconnectRequestQueue_.push({\r\n pathString: pathString,\r\n action: 'om',\r\n data: data,\r\n onComplete: onComplete\r\n });\r\n }\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n PersistentConnection.prototype.onDisconnectCancel = function (pathString, onComplete) {\r\n if (this.connected_) {\r\n this.sendOnDisconnect_('oc', pathString, null, onComplete);\r\n }\r\n else {\r\n this.onDisconnectRequestQueue_.push({\r\n pathString: pathString,\r\n action: 'oc',\r\n data: null,\r\n onComplete: onComplete\r\n });\r\n }\r\n };\r\n PersistentConnection.prototype.sendOnDisconnect_ = function (action, pathString, data, onComplete) {\r\n var request = { /*path*/ p: pathString, /*data*/ d: data };\r\n this.log_('onDisconnect ' + action, request);\r\n this.sendRequest(action, request, function (response) {\r\n if (onComplete) {\r\n setTimeout(function () {\r\n onComplete(response[ /*status*/'s'], response[ /* data */'d']);\r\n }, Math.floor(0));\r\n }\r\n });\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {\r\n this.putInternal('p', pathString, data, onComplete, hash);\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n PersistentConnection.prototype.merge = function (pathString, data, onComplete, hash) {\r\n this.putInternal('m', pathString, data, onComplete, hash);\r\n };\r\n PersistentConnection.prototype.putInternal = function (action, pathString, data, onComplete, hash) {\r\n var request = {\r\n /*path*/ p: pathString,\r\n /*data*/ d: data\r\n };\r\n if (hash !== undefined)\r\n request[ /*hash*/'h'] = hash;\r\n // TODO: Only keep track of the most recent put for a given path?\r\n this.outstandingPuts_.push({\r\n action: action,\r\n request: request,\r\n onComplete: onComplete\r\n });\r\n this.outstandingPutCount_++;\r\n var index = this.outstandingPuts_.length - 1;\r\n if (this.connected_) {\r\n this.sendPut_(index);\r\n }\r\n else {\r\n this.log_('Buffering put: ' + pathString);\r\n }\r\n };\r\n PersistentConnection.prototype.sendPut_ = function (index) {\r\n var _this = this;\r\n var action = this.outstandingPuts_[index].action;\r\n var request = this.outstandingPuts_[index].request;\r\n var onComplete = this.outstandingPuts_[index].onComplete;\r\n this.outstandingPuts_[index].queued = this.connected_;\r\n this.sendRequest(action, request, function (message) {\r\n _this.log_(action + ' response', message);\r\n delete _this.outstandingPuts_[index];\r\n _this.outstandingPutCount_--;\r\n // Clean up array occasionally.\r\n if (_this.outstandingPutCount_ === 0) {\r\n _this.outstandingPuts_ = [];\r\n }\r\n if (onComplete)\r\n onComplete(message[ /*status*/'s'], message[ /* data */'d']);\r\n });\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n PersistentConnection.prototype.reportStats = function (stats) {\r\n var _this = this;\r\n // If we're not connected, we just drop the stats.\r\n if (this.connected_) {\r\n var request = { /*counters*/ c: stats };\r\n this.log_('reportStats', request);\r\n this.sendRequest(/*stats*/ 's', request, function (result) {\r\n var status = result[ /*status*/'s'];\r\n if (status !== 'ok') {\r\n var errorReason = result[ /* data */'d'];\r\n _this.log_('reportStats', 'Error sending stats: ' + errorReason);\r\n }\r\n });\r\n }\r\n };\r\n /**\r\n * @param {*} message\r\n * @private\r\n */\r\n PersistentConnection.prototype.onDataMessage_ = function (message) {\r\n if ('r' in message) {\r\n // this is a response\r\n this.log_('from server: ' + util.stringify(message));\r\n var reqNum = message['r'];\r\n var onResponse = this.requestCBHash_[reqNum];\r\n if (onResponse) {\r\n delete this.requestCBHash_[reqNum];\r\n onResponse(message[ /*body*/'b']);\r\n }\r\n }\r\n else if ('error' in message) {\r\n throw 'A server-side error has occurred: ' + message['error'];\r\n }\r\n else if ('a' in message) {\r\n // a and b are action and body, respectively\r\n this.onDataPush_(message['a'], message['b']);\r\n }\r\n };\r\n PersistentConnection.prototype.onDataPush_ = function (action, body) {\r\n this.log_('handleServerMessage', action, body);\r\n if (action === 'd')\r\n this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], \r\n /*isMerge*/ false, body['t']);\r\n else if (action === 'm')\r\n this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], \r\n /*isMerge=*/ true, body['t']);\r\n else if (action === 'c')\r\n this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']);\r\n else if (action === 'ac')\r\n this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);\r\n else if (action === 'sd')\r\n this.onSecurityDebugPacket_(body);\r\n else\r\n error('Unrecognized action received from server: ' +\r\n util.stringify(action) +\r\n '\\nAre you using the latest client?');\r\n };\r\n PersistentConnection.prototype.onReady_ = function (timestamp, sessionId) {\r\n this.log_('connection ready');\r\n this.connected_ = true;\r\n this.lastConnectionEstablishedTime_ = new Date().getTime();\r\n this.handleTimestamp_(timestamp);\r\n this.lastSessionId = sessionId;\r\n if (this.firstConnection_) {\r\n this.sendConnectStats_();\r\n }\r\n this.restoreState_();\r\n this.firstConnection_ = false;\r\n this.onConnectStatus_(true);\r\n };\r\n PersistentConnection.prototype.scheduleConnect_ = function (timeout) {\r\n var _this = this;\r\n util.assert(!this.realtime_, \"Scheduling a connect when we're already connected/ing?\");\r\n if (this.establishConnectionTimer_) {\r\n clearTimeout(this.establishConnectionTimer_);\r\n }\r\n // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating \"Security Error\" in\r\n // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).\r\n this.establishConnectionTimer_ = setTimeout(function () {\r\n _this.establishConnectionTimer_ = null;\r\n _this.establishConnection_();\r\n }, Math.floor(timeout));\r\n };\r\n /**\r\n * @param {boolean} visible\r\n * @private\r\n */\r\n PersistentConnection.prototype.onVisible_ = function (visible) {\r\n // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.\r\n if (visible &&\r\n !this.visible_ &&\r\n this.reconnectDelay_ === this.maxReconnectDelay_) {\r\n this.log_('Window became visible. Reducing delay.');\r\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\r\n if (!this.realtime_) {\r\n this.scheduleConnect_(0);\r\n }\r\n }\r\n this.visible_ = visible;\r\n };\r\n PersistentConnection.prototype.onOnline_ = function (online) {\r\n if (online) {\r\n this.log_('Browser went online.');\r\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\r\n if (!this.realtime_) {\r\n this.scheduleConnect_(0);\r\n }\r\n }\r\n else {\r\n this.log_('Browser went offline. Killing connection.');\r\n if (this.realtime_) {\r\n this.realtime_.close();\r\n }\r\n }\r\n };\r\n PersistentConnection.prototype.onRealtimeDisconnect_ = function () {\r\n this.log_('data client disconnected');\r\n this.connected_ = false;\r\n this.realtime_ = null;\r\n // Since we don't know if our sent transactions succeeded or not, we need to cancel them.\r\n this.cancelSentTransactions_();\r\n // Clear out the pending requests.\r\n this.requestCBHash_ = {};\r\n if (this.shouldReconnect_()) {\r\n if (!this.visible_) {\r\n this.log_(\"Window isn't visible. Delaying reconnect.\");\r\n this.reconnectDelay_ = this.maxReconnectDelay_;\r\n this.lastConnectionAttemptTime_ = new Date().getTime();\r\n }\r\n else if (this.lastConnectionEstablishedTime_) {\r\n // If we've been connected long enough, reset reconnect delay to minimum.\r\n var timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;\r\n if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT)\r\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\r\n this.lastConnectionEstablishedTime_ = null;\r\n }\r\n var timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;\r\n var reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);\r\n reconnectDelay = Math.random() * reconnectDelay;\r\n this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');\r\n this.scheduleConnect_(reconnectDelay);\r\n // Adjust reconnect delay for next time.\r\n this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);\r\n }\r\n this.onConnectStatus_(false);\r\n };\r\n PersistentConnection.prototype.establishConnection_ = function () {\r\n if (this.shouldReconnect_()) {\r\n this.log_('Making a connection attempt');\r\n this.lastConnectionAttemptTime_ = new Date().getTime();\r\n this.lastConnectionEstablishedTime_ = null;\r\n var onDataMessage_1 = this.onDataMessage_.bind(this);\r\n var onReady_1 = this.onReady_.bind(this);\r\n var onDisconnect_1 = this.onRealtimeDisconnect_.bind(this);\r\n var connId_1 = this.id + ':' + PersistentConnection.nextConnectionId_++;\r\n var self_1 = this;\r\n var lastSessionId_1 = this.lastSessionId;\r\n var canceled_1 = false;\r\n var connection_1 = null;\r\n var closeFn_1 = function () {\r\n if (connection_1) {\r\n connection_1.close();\r\n }\r\n else {\r\n canceled_1 = true;\r\n onDisconnect_1();\r\n }\r\n };\r\n var sendRequestFn = function (msg) {\r\n util.assert(connection_1, \"sendRequest call when we're not connected not allowed.\");\r\n connection_1.sendRequest(msg);\r\n };\r\n this.realtime_ = {\r\n close: closeFn_1,\r\n sendRequest: sendRequestFn\r\n };\r\n var forceRefresh = this.forceTokenRefresh_;\r\n this.forceTokenRefresh_ = false;\r\n // First fetch auth token, and establish connection after fetching the token was successful\r\n this.authTokenProvider_\r\n .getToken(forceRefresh)\r\n .then(function (result) {\r\n if (!canceled_1) {\r\n log('getToken() completed. Creating connection.');\r\n self_1.authToken_ = result && result.accessToken;\r\n connection_1 = new Connection(connId_1, self_1.repoInfo_, onDataMessage_1, onReady_1, onDisconnect_1, \r\n /* onKill= */ function (reason) {\r\n warn(reason + ' (' + self_1.repoInfo_.toString() + ')');\r\n self_1.interrupt(SERVER_KILL_INTERRUPT_REASON);\r\n }, lastSessionId_1);\r\n }\r\n else {\r\n log('getToken() completed but was canceled');\r\n }\r\n })\r\n .then(null, function (error) {\r\n self_1.log_('Failed to get token: ' + error);\r\n if (!canceled_1) {\r\n if (util.CONSTANTS.NODE_ADMIN) {\r\n // This may be a critical error for the Admin Node.js SDK, so log a warning.\r\n // But getToken() may also just have temporarily failed, so we still want to\r\n // continue retrying.\r\n warn(error);\r\n }\r\n closeFn_1();\r\n }\r\n });\r\n }\r\n };\r\n /**\r\n * @param {string} reason\r\n */\r\n PersistentConnection.prototype.interrupt = function (reason) {\r\n log('Interrupting connection for reason: ' + reason);\r\n this.interruptReasons_[reason] = true;\r\n if (this.realtime_) {\r\n this.realtime_.close();\r\n }\r\n else {\r\n if (this.establishConnectionTimer_) {\r\n clearTimeout(this.establishConnectionTimer_);\r\n this.establishConnectionTimer_ = null;\r\n }\r\n if (this.connected_) {\r\n this.onRealtimeDisconnect_();\r\n }\r\n }\r\n };\r\n /**\r\n * @param {string} reason\r\n */\r\n PersistentConnection.prototype.resume = function (reason) {\r\n log('Resuming connection for reason: ' + reason);\r\n delete this.interruptReasons_[reason];\r\n if (util.isEmpty(this.interruptReasons_)) {\r\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\r\n if (!this.realtime_) {\r\n this.scheduleConnect_(0);\r\n }\r\n }\r\n };\r\n PersistentConnection.prototype.handleTimestamp_ = function (timestamp) {\r\n var delta = timestamp - new Date().getTime();\r\n this.onServerInfoUpdate_({ serverTimeOffset: delta });\r\n };\r\n PersistentConnection.prototype.cancelSentTransactions_ = function () {\r\n for (var i = 0; i < this.outstandingPuts_.length; i++) {\r\n var put = this.outstandingPuts_[i];\r\n if (put && /*hash*/ 'h' in put.request && put.queued) {\r\n if (put.onComplete)\r\n put.onComplete('disconnect');\r\n delete this.outstandingPuts_[i];\r\n this.outstandingPutCount_--;\r\n }\r\n }\r\n // Clean up array occasionally.\r\n if (this.outstandingPutCount_ === 0)\r\n this.outstandingPuts_ = [];\r\n };\r\n /**\r\n * @param {!string} pathString\r\n * @param {Array.<*>=} query\r\n * @private\r\n */\r\n PersistentConnection.prototype.onListenRevoked_ = function (pathString, query) {\r\n // Remove the listen and manufacture a \"permission_denied\" error for the failed listen.\r\n var queryId;\r\n if (!query) {\r\n queryId = 'default';\r\n }\r\n else {\r\n queryId = query.map(function (q) { return ObjectToUniqueKey(q); }).join('$');\r\n }\r\n var listen = this.removeListen_(pathString, queryId);\r\n if (listen && listen.onComplete)\r\n listen.onComplete('permission_denied');\r\n };\r\n /**\r\n * @param {!string} pathString\r\n * @param {!string} queryId\r\n * @return {{queries:Array., onComplete:function(string)}}\r\n * @private\r\n */\r\n PersistentConnection.prototype.removeListen_ = function (pathString, queryId) {\r\n var normalizedPathString = new Path(pathString).toString(); // normalize path.\r\n var listen;\r\n if (this.listens_[normalizedPathString] !== undefined) {\r\n listen = this.listens_[normalizedPathString][queryId];\r\n delete this.listens_[normalizedPathString][queryId];\r\n if (util.getCount(this.listens_[normalizedPathString]) === 0) {\r\n delete this.listens_[normalizedPathString];\r\n }\r\n }\r\n else {\r\n // all listens for this path has already been removed\r\n listen = undefined;\r\n }\r\n return listen;\r\n };\r\n PersistentConnection.prototype.onAuthRevoked_ = function (statusCode, explanation) {\r\n log('Auth token revoked: ' + statusCode + '/' + explanation);\r\n this.authToken_ = null;\r\n this.forceTokenRefresh_ = true;\r\n this.realtime_.close();\r\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\r\n // We'll wait a couple times before logging the warning / increasing the\r\n // retry period since oauth tokens will report as \"invalid\" if they're\r\n // just expired. Plus there may be transient issues that resolve themselves.\r\n this.invalidAuthTokenCount_++;\r\n if (this.invalidAuthTokenCount_ >= INVALID_AUTH_TOKEN_THRESHOLD) {\r\n // Set a long reconnect delay because recovery is unlikely\r\n this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\r\n // Notify the auth token provider that the token is invalid, which will log\r\n // a warning\r\n this.authTokenProvider_.notifyForInvalidToken();\r\n }\r\n }\r\n };\r\n PersistentConnection.prototype.onSecurityDebugPacket_ = function (body) {\r\n if (this.securityDebugCallback_) {\r\n this.securityDebugCallback_(body);\r\n }\r\n else {\r\n if ('msg' in body) {\r\n console.log('FIREBASE: ' + body['msg'].replace('\\n', '\\nFIREBASE: '));\r\n }\r\n }\r\n };\r\n PersistentConnection.prototype.restoreState_ = function () {\r\n var _this = this;\r\n //Re-authenticate ourselves if we have a credential stored.\r\n this.tryAuth();\r\n // Puts depend on having received the corresponding data update from the server before they complete, so we must\r\n // make sure to send listens before puts.\r\n util.forEach(this.listens_, function (pathString, queries) {\r\n util.forEach(queries, function (key, listenSpec) {\r\n _this.sendListen_(listenSpec);\r\n });\r\n });\r\n for (var i = 0; i < this.outstandingPuts_.length; i++) {\r\n if (this.outstandingPuts_[i])\r\n this.sendPut_(i);\r\n }\r\n while (this.onDisconnectRequestQueue_.length) {\r\n var request = this.onDisconnectRequestQueue_.shift();\r\n this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);\r\n }\r\n };\r\n /**\r\n * Sends client stats for first connection\r\n * @private\r\n */\r\n PersistentConnection.prototype.sendConnectStats_ = function () {\r\n var stats = {};\r\n var clientName = 'js';\r\n if (util.CONSTANTS.NODE_ADMIN) {\r\n clientName = 'admin_node';\r\n }\r\n else if (util.CONSTANTS.NODE_CLIENT) {\r\n clientName = 'node';\r\n }\r\n stats['sdk.' + clientName + '.' + firebase.SDK_VERSION.replace(/\\./g, '-')] = 1;\r\n if (util.isMobileCordova()) {\r\n stats['framework.cordova'] = 1;\r\n }\r\n else if (util.isReactNative()) {\r\n stats['framework.reactnative'] = 1;\r\n }\r\n this.reportStats(stats);\r\n };\r\n /**\r\n * @return {boolean}\r\n * @private\r\n */\r\n PersistentConnection.prototype.shouldReconnect_ = function () {\r\n var online = OnlineMonitor.getInstance().currentlyOnline();\r\n return util.isEmpty(this.interruptReasons_) && online;\r\n };\r\n /**\r\n * @private\r\n */\r\n PersistentConnection.nextPersistentConnectionId_ = 0;\r\n /**\r\n * Counter for number of connections created. Mainly used for tagging in the logs\r\n * @type {number}\r\n * @private\r\n */\r\n PersistentConnection.nextConnectionId_ = 0;\r\n return PersistentConnection;\r\n}(ServerActions));\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An implementation of ServerActions that communicates with the server via REST requests.\r\n * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full\r\n * persistent connection (using WebSockets or long-polling)\r\n */\r\nvar ReadonlyRestClient = /** @class */ (function (_super) {\r\n tslib_1.__extends(ReadonlyRestClient, _super);\r\n /**\r\n * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to\r\n * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server\r\n * @param {AuthTokenProvider} authTokenProvider_\r\n * @implements {ServerActions}\r\n */\r\n function ReadonlyRestClient(repoInfo_, onDataUpdate_, authTokenProvider_) {\r\n var _this = _super.call(this) || this;\r\n _this.repoInfo_ = repoInfo_;\r\n _this.onDataUpdate_ = onDataUpdate_;\r\n _this.authTokenProvider_ = authTokenProvider_;\r\n /** @private {function(...[*])} */\r\n _this.log_ = logWrapper('p:rest:');\r\n /**\r\n * We don't actually need to track listens, except to prevent us calling an onComplete for a listen\r\n * that's been removed. :-/\r\n *\r\n * @private {!Object.}\r\n */\r\n _this.listens_ = {};\r\n return _this;\r\n }\r\n ReadonlyRestClient.prototype.reportStats = function (stats) {\r\n throw new Error('Method not implemented.');\r\n };\r\n /**\r\n * @param {!Query} query\r\n * @param {?number=} tag\r\n * @return {string}\r\n * @private\r\n */\r\n ReadonlyRestClient.getListenId_ = function (query, tag) {\r\n if (tag !== undefined) {\r\n return 'tag$' + tag;\r\n }\r\n else {\r\n util.assert(query.getQueryParams().isDefault(), \"should have a tag if it's not a default query.\");\r\n return query.path.toString();\r\n }\r\n };\r\n /** @inheritDoc */\r\n ReadonlyRestClient.prototype.listen = function (query, currentHashFn, tag, onComplete) {\r\n var _this = this;\r\n var pathString = query.path.toString();\r\n this.log_('Listen called for ' + pathString + ' ' + query.queryIdentifier());\r\n // Mark this listener so we can tell if it's removed.\r\n var listenId = ReadonlyRestClient.getListenId_(query, tag);\r\n var thisListen = {};\r\n this.listens_[listenId] = thisListen;\r\n var queryStringParameters = query\r\n .getQueryParams()\r\n .toRestQueryStringParameters();\r\n this.restRequest_(pathString + '.json', queryStringParameters, function (error, result) {\r\n var data = result;\r\n if (error === 404) {\r\n data = null;\r\n error = null;\r\n }\r\n if (error === null) {\r\n _this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);\r\n }\r\n if (util.safeGet(_this.listens_, listenId) === thisListen) {\r\n var status_1;\r\n if (!error) {\r\n status_1 = 'ok';\r\n }\r\n else if (error == 401) {\r\n status_1 = 'permission_denied';\r\n }\r\n else {\r\n status_1 = 'rest_error:' + error;\r\n }\r\n onComplete(status_1, null);\r\n }\r\n });\r\n };\r\n /** @inheritDoc */\r\n ReadonlyRestClient.prototype.unlisten = function (query, tag) {\r\n var listenId = ReadonlyRestClient.getListenId_(query, tag);\r\n delete this.listens_[listenId];\r\n };\r\n /** @inheritDoc */\r\n ReadonlyRestClient.prototype.refreshAuthToken = function (token) {\r\n // no-op since we just always call getToken.\r\n };\r\n /**\r\n * Performs a REST request to the given path, with the provided query string parameters,\r\n * and any auth credentials we have.\r\n *\r\n * @param {!string} pathString\r\n * @param {!Object.} queryStringParameters\r\n * @param {?function(?number, *=)} callback\r\n * @private\r\n */\r\n ReadonlyRestClient.prototype.restRequest_ = function (pathString, queryStringParameters, callback) {\r\n var _this = this;\r\n if (queryStringParameters === void 0) { queryStringParameters = {}; }\r\n queryStringParameters['format'] = 'export';\r\n this.authTokenProvider_\r\n .getToken(/*forceRefresh=*/ false)\r\n .then(function (authTokenData) {\r\n var authToken = authTokenData && authTokenData.accessToken;\r\n if (authToken) {\r\n queryStringParameters['auth'] = authToken;\r\n }\r\n var url = (_this.repoInfo_.secure ? 'https://' : 'http://') +\r\n _this.repoInfo_.host +\r\n pathString +\r\n '?' +\r\n 'ns=' +\r\n _this.repoInfo_.namespace +\r\n util.querystring(queryStringParameters);\r\n _this.log_('Sending REST request for ' + url);\r\n var xhr = new XMLHttpRequest();\r\n xhr.onreadystatechange = function () {\r\n if (callback && xhr.readyState === 4) {\r\n _this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);\r\n var res = null;\r\n if (xhr.status >= 200 && xhr.status < 300) {\r\n try {\r\n res = util.jsonEval(xhr.responseText);\r\n }\r\n catch (e) {\r\n warn('Failed to parse JSON response for ' +\r\n url +\r\n ': ' +\r\n xhr.responseText);\r\n }\r\n callback(null, res);\r\n }\r\n else {\r\n // 401 and 404 are expected.\r\n if (xhr.status !== 401 && xhr.status !== 404) {\r\n warn('Got unsuccessful REST response for ' +\r\n url +\r\n ' Status: ' +\r\n xhr.status);\r\n }\r\n callback(xhr.status);\r\n }\r\n callback = null;\r\n }\r\n };\r\n xhr.open('GET', url, /*asynchronous=*/ true);\r\n xhr.send();\r\n });\r\n };\r\n return ReadonlyRestClient;\r\n}(ServerActions));\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar INTERRUPT_REASON = 'repo_interrupt';\r\n/**\r\n * A connection to a single data repository.\r\n */\r\nvar Repo = /** @class */ (function () {\r\n /**\r\n * @param {!RepoInfo} repoInfo_\r\n * @param {boolean} forceRestClient\r\n * @param {!FirebaseApp} app\r\n */\r\n function Repo(repoInfo_, forceRestClient, app) {\r\n var _this = this;\r\n this.repoInfo_ = repoInfo_;\r\n this.app = app;\r\n this.dataUpdateCount = 0;\r\n this.statsListener_ = null;\r\n this.eventQueue_ = new EventQueue();\r\n this.nextWriteId_ = 1;\r\n this.interceptServerDataCallback_ = null;\r\n // A list of data pieces and paths to be set when this client disconnects.\r\n this.onDisconnect_ = new SparseSnapshotTree();\r\n /**\r\n * TODO: This should be @private but it's used by test_access.js and internal.js\r\n * @type {?PersistentConnection}\r\n */\r\n this.persistentConnection_ = null;\r\n /** @type {!AuthTokenProvider} */\r\n var authTokenProvider = new AuthTokenProvider(app);\r\n this.stats_ = StatsManager.getCollection(repoInfo_);\r\n if (forceRestClient || beingCrawled()) {\r\n this.server_ = new ReadonlyRestClient(this.repoInfo_, this.onDataUpdate_.bind(this), authTokenProvider);\r\n // Minor hack: Fire onConnect immediately, since there's no actual connection.\r\n setTimeout(this.onConnectStatus_.bind(this, true), 0);\r\n }\r\n else {\r\n var authOverride = app.options['databaseAuthVariableOverride'];\r\n // Validate authOverride\r\n if (typeof authOverride !== 'undefined' && authOverride !== null) {\r\n if (typeof authOverride !== 'object') {\r\n throw new Error('Only objects are supported for option databaseAuthVariableOverride');\r\n }\r\n try {\r\n util.stringify(authOverride);\r\n }\r\n catch (e) {\r\n throw new Error('Invalid authOverride provided: ' + e);\r\n }\r\n }\r\n this.persistentConnection_ = new PersistentConnection(this.repoInfo_, this.onDataUpdate_.bind(this), this.onConnectStatus_.bind(this), this.onServerInfoUpdate_.bind(this), authTokenProvider, authOverride);\r\n this.server_ = this.persistentConnection_;\r\n }\r\n authTokenProvider.addTokenChangeListener(function (token) {\r\n _this.server_.refreshAuthToken(token);\r\n });\r\n // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),\r\n // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.\r\n this.statsReporter_ = StatsManager.getOrCreateReporter(repoInfo_, function () { return new StatsReporter(_this.stats_, _this.server_); });\r\n this.transactions_init_();\r\n // Used for .info.\r\n this.infoData_ = new SnapshotHolder();\r\n this.infoSyncTree_ = new SyncTree({\r\n startListening: function (query, tag, currentHashFn, onComplete) {\r\n var infoEvents = [];\r\n var node = _this.infoData_.getNode(query.path);\r\n // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events\r\n // on initial data...\r\n if (!node.isEmpty()) {\r\n infoEvents = _this.infoSyncTree_.applyServerOverwrite(query.path, node);\r\n setTimeout(function () {\r\n onComplete('ok');\r\n }, 0);\r\n }\r\n return infoEvents;\r\n },\r\n stopListening: function () { }\r\n });\r\n this.updateInfo_('connected', false);\r\n this.serverSyncTree_ = new SyncTree({\r\n startListening: function (query, tag, currentHashFn, onComplete) {\r\n _this.server_.listen(query, currentHashFn, tag, function (status, data) {\r\n var events = onComplete(status, data);\r\n _this.eventQueue_.raiseEventsForChangedPath(query.path, events);\r\n });\r\n // No synchronous events for network-backed sync trees\r\n return [];\r\n },\r\n stopListening: function (query, tag) {\r\n _this.server_.unlisten(query, tag);\r\n }\r\n });\r\n }\r\n /**\r\n * @return {string} The URL corresponding to the root of this Firebase.\r\n */\r\n Repo.prototype.toString = function () {\r\n return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);\r\n };\r\n /**\r\n * @return {!string} The namespace represented by the repo.\r\n */\r\n Repo.prototype.name = function () {\r\n return this.repoInfo_.namespace;\r\n };\r\n /**\r\n * @return {!number} The time in milliseconds, taking the server offset into account if we have one.\r\n */\r\n Repo.prototype.serverTime = function () {\r\n var offsetNode = this.infoData_.getNode(new Path('.info/serverTimeOffset'));\r\n var offset = offsetNode.val() || 0;\r\n return new Date().getTime() + offset;\r\n };\r\n /**\r\n * Generate ServerValues using some variables from the repo object.\r\n * @return {!Object}\r\n */\r\n Repo.prototype.generateServerValues = function () {\r\n return generateWithValues({\r\n timestamp: this.serverTime()\r\n });\r\n };\r\n /**\r\n * Called by realtime when we get new messages from the server.\r\n *\r\n * @private\r\n * @param {string} pathString\r\n * @param {*} data\r\n * @param {boolean} isMerge\r\n * @param {?number} tag\r\n */\r\n Repo.prototype.onDataUpdate_ = function (pathString, data, isMerge, tag) {\r\n // For testing.\r\n this.dataUpdateCount++;\r\n var path = new Path(pathString);\r\n data = this.interceptServerDataCallback_\r\n ? this.interceptServerDataCallback_(pathString, data)\r\n : data;\r\n var events = [];\r\n if (tag) {\r\n if (isMerge) {\r\n var taggedChildren = util.map(data, function (raw) {\r\n return nodeFromJSON$1(raw);\r\n });\r\n events = this.serverSyncTree_.applyTaggedQueryMerge(path, taggedChildren, tag);\r\n }\r\n else {\r\n var taggedSnap = nodeFromJSON$1(data);\r\n events = this.serverSyncTree_.applyTaggedQueryOverwrite(path, taggedSnap, tag);\r\n }\r\n }\r\n else if (isMerge) {\r\n var changedChildren = util.map(data, function (raw) {\r\n return nodeFromJSON$1(raw);\r\n });\r\n events = this.serverSyncTree_.applyServerMerge(path, changedChildren);\r\n }\r\n else {\r\n var snap = nodeFromJSON$1(data);\r\n events = this.serverSyncTree_.applyServerOverwrite(path, snap);\r\n }\r\n var affectedPath = path;\r\n if (events.length > 0) {\r\n // Since we have a listener outstanding for each transaction, receiving any events\r\n // is a proxy for some change having occurred.\r\n affectedPath = this.rerunTransactions_(path);\r\n }\r\n this.eventQueue_.raiseEventsForChangedPath(affectedPath, events);\r\n };\r\n /**\r\n * TODO: This should be @private but it's used by test_access.js and internal.js\r\n * @param {?function(!string, *):*} callback\r\n * @private\r\n */\r\n Repo.prototype.interceptServerData_ = function (callback) {\r\n this.interceptServerDataCallback_ = callback;\r\n };\r\n /**\r\n * @param {!boolean} connectStatus\r\n * @private\r\n */\r\n Repo.prototype.onConnectStatus_ = function (connectStatus) {\r\n this.updateInfo_('connected', connectStatus);\r\n if (connectStatus === false) {\r\n this.runOnDisconnectEvents_();\r\n }\r\n };\r\n /**\r\n * @param {!Object} updates\r\n * @private\r\n */\r\n Repo.prototype.onServerInfoUpdate_ = function (updates) {\r\n var _this = this;\r\n each(updates, function (value, key) {\r\n _this.updateInfo_(key, value);\r\n });\r\n };\r\n /**\r\n *\r\n * @param {!string} pathString\r\n * @param {*} value\r\n * @private\r\n */\r\n Repo.prototype.updateInfo_ = function (pathString, value) {\r\n var path = new Path('/.info/' + pathString);\r\n var newNode = nodeFromJSON$1(value);\r\n this.infoData_.updateSnapshot(path, newNode);\r\n var events = this.infoSyncTree_.applyServerOverwrite(path, newNode);\r\n this.eventQueue_.raiseEventsForChangedPath(path, events);\r\n };\r\n /**\r\n * @return {!number}\r\n * @private\r\n */\r\n Repo.prototype.getNextWriteId_ = function () {\r\n return this.nextWriteId_++;\r\n };\r\n /**\r\n * @param {!Path} path\r\n * @param {*} newVal\r\n * @param {number|string|null} newPriority\r\n * @param {?function(?Error, *=)} onComplete\r\n */\r\n Repo.prototype.setWithPriority = function (path, newVal, newPriority, onComplete) {\r\n var _this = this;\r\n this.log_('set', {\r\n path: path.toString(),\r\n value: newVal,\r\n priority: newPriority\r\n });\r\n // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or\r\n // (b) store unresolved paths on JSON parse\r\n var serverValues = this.generateServerValues();\r\n var newNodeUnresolved = nodeFromJSON$1(newVal, newPriority);\r\n var newNode = resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\r\n var writeId = this.getNextWriteId_();\r\n var events = this.serverSyncTree_.applyUserOverwrite(path, newNode, writeId, true);\r\n this.eventQueue_.queueEvents(events);\r\n this.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), function (status, errorReason) {\r\n var success = status === 'ok';\r\n if (!success) {\r\n warn('set at ' + path + ' failed: ' + status);\r\n }\r\n var clearEvents = _this.serverSyncTree_.ackUserWrite(writeId, !success);\r\n _this.eventQueue_.raiseEventsForChangedPath(path, clearEvents);\r\n _this.callOnCompleteCallback(onComplete, status, errorReason);\r\n });\r\n var affectedPath = this.abortTransactions_(path);\r\n this.rerunTransactions_(affectedPath);\r\n // We queued the events above, so just flush the queue here\r\n this.eventQueue_.raiseEventsForChangedPath(affectedPath, []);\r\n };\r\n /**\r\n * @param {!Path} path\r\n * @param {!Object} childrenToMerge\r\n * @param {?function(?Error, *=)} onComplete\r\n */\r\n Repo.prototype.update = function (path, childrenToMerge, onComplete) {\r\n var _this = this;\r\n this.log_('update', { path: path.toString(), value: childrenToMerge });\r\n // Start with our existing data and merge each child into it.\r\n var empty = true;\r\n var serverValues = this.generateServerValues();\r\n var changedChildren = {};\r\n util.forEach(childrenToMerge, function (changedKey, changedValue) {\r\n empty = false;\r\n var newNodeUnresolved = nodeFromJSON$1(changedValue);\r\n changedChildren[changedKey] = resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\r\n });\r\n if (!empty) {\r\n var writeId_1 = this.getNextWriteId_();\r\n var events = this.serverSyncTree_.applyUserMerge(path, changedChildren, writeId_1);\r\n this.eventQueue_.queueEvents(events);\r\n this.server_.merge(path.toString(), childrenToMerge, function (status, errorReason) {\r\n var success = status === 'ok';\r\n if (!success) {\r\n warn('update at ' + path + ' failed: ' + status);\r\n }\r\n var clearEvents = _this.serverSyncTree_.ackUserWrite(writeId_1, !success);\r\n var affectedPath = clearEvents.length > 0 ? _this.rerunTransactions_(path) : path;\r\n _this.eventQueue_.raiseEventsForChangedPath(affectedPath, clearEvents);\r\n _this.callOnCompleteCallback(onComplete, status, errorReason);\r\n });\r\n util.forEach(childrenToMerge, function (changedPath) {\r\n var affectedPath = _this.abortTransactions_(path.child(changedPath));\r\n _this.rerunTransactions_(affectedPath);\r\n });\r\n // We queued the events above, so just flush the queue here\r\n this.eventQueue_.raiseEventsForChangedPath(path, []);\r\n }\r\n else {\r\n log(\"update() called with empty data. Don't do anything.\");\r\n this.callOnCompleteCallback(onComplete, 'ok');\r\n }\r\n };\r\n /**\r\n * Applies all of the changes stored up in the onDisconnect_ tree.\r\n * @private\r\n */\r\n Repo.prototype.runOnDisconnectEvents_ = function () {\r\n var _this = this;\r\n this.log_('onDisconnectEvents');\r\n var serverValues = this.generateServerValues();\r\n var resolvedOnDisconnectTree = resolveDeferredValueTree(this.onDisconnect_, serverValues);\r\n var events = [];\r\n resolvedOnDisconnectTree.forEachTree(Path.Empty, function (path, snap) {\r\n events = events.concat(_this.serverSyncTree_.applyServerOverwrite(path, snap));\r\n var affectedPath = _this.abortTransactions_(path);\r\n _this.rerunTransactions_(affectedPath);\r\n });\r\n this.onDisconnect_ = new SparseSnapshotTree();\r\n this.eventQueue_.raiseEventsForChangedPath(Path.Empty, events);\r\n };\r\n /**\r\n * @param {!Path} path\r\n * @param {?function(?Error, *=)} onComplete\r\n */\r\n Repo.prototype.onDisconnectCancel = function (path, onComplete) {\r\n var _this = this;\r\n this.server_.onDisconnectCancel(path.toString(), function (status, errorReason) {\r\n if (status === 'ok') {\r\n _this.onDisconnect_.forget(path);\r\n }\r\n _this.callOnCompleteCallback(onComplete, status, errorReason);\r\n });\r\n };\r\n /**\r\n * @param {!Path} path\r\n * @param {*} value\r\n * @param {?function(?Error, *=)} onComplete\r\n */\r\n Repo.prototype.onDisconnectSet = function (path, value, onComplete) {\r\n var _this = this;\r\n var newNode = nodeFromJSON$1(value);\r\n this.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {\r\n if (status === 'ok') {\r\n _this.onDisconnect_.remember(path, newNode);\r\n }\r\n _this.callOnCompleteCallback(onComplete, status, errorReason);\r\n });\r\n };\r\n /**\r\n * @param {!Path} path\r\n * @param {*} value\r\n * @param {*} priority\r\n * @param {?function(?Error, *=)} onComplete\r\n */\r\n Repo.prototype.onDisconnectSetWithPriority = function (path, value, priority, onComplete) {\r\n var _this = this;\r\n var newNode = nodeFromJSON$1(value, priority);\r\n this.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {\r\n if (status === 'ok') {\r\n _this.onDisconnect_.remember(path, newNode);\r\n }\r\n _this.callOnCompleteCallback(onComplete, status, errorReason);\r\n });\r\n };\r\n /**\r\n * @param {!Path} path\r\n * @param {*} childrenToMerge\r\n * @param {?function(?Error, *=)} onComplete\r\n */\r\n Repo.prototype.onDisconnectUpdate = function (path, childrenToMerge, onComplete) {\r\n var _this = this;\r\n if (util.isEmpty(childrenToMerge)) {\r\n log(\"onDisconnect().update() called with empty data. Don't do anything.\");\r\n this.callOnCompleteCallback(onComplete, 'ok');\r\n return;\r\n }\r\n this.server_.onDisconnectMerge(path.toString(), childrenToMerge, function (status, errorReason) {\r\n if (status === 'ok') {\r\n util.forEach(childrenToMerge, function (childName, childNode) {\r\n var newChildNode = nodeFromJSON$1(childNode);\r\n _this.onDisconnect_.remember(path.child(childName), newChildNode);\r\n });\r\n }\r\n _this.callOnCompleteCallback(onComplete, status, errorReason);\r\n });\r\n };\r\n /**\r\n * @param {!Query} query\r\n * @param {!EventRegistration} eventRegistration\r\n */\r\n Repo.prototype.addEventCallbackForQuery = function (query, eventRegistration) {\r\n var events;\r\n if (query.path.getFront() === '.info') {\r\n events = this.infoSyncTree_.addEventRegistration(query, eventRegistration);\r\n }\r\n else {\r\n events = this.serverSyncTree_.addEventRegistration(query, eventRegistration);\r\n }\r\n this.eventQueue_.raiseEventsAtPath(query.path, events);\r\n };\r\n /**\r\n * @param {!Query} query\r\n * @param {?EventRegistration} eventRegistration\r\n */\r\n Repo.prototype.removeEventCallbackForQuery = function (query, eventRegistration) {\r\n // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof\r\n // a little bit by handling the return values anyways.\r\n var events;\r\n if (query.path.getFront() === '.info') {\r\n events = this.infoSyncTree_.removeEventRegistration(query, eventRegistration);\r\n }\r\n else {\r\n events = this.serverSyncTree_.removeEventRegistration(query, eventRegistration);\r\n }\r\n this.eventQueue_.raiseEventsAtPath(query.path, events);\r\n };\r\n Repo.prototype.interrupt = function () {\r\n if (this.persistentConnection_) {\r\n this.persistentConnection_.interrupt(INTERRUPT_REASON);\r\n }\r\n };\r\n Repo.prototype.resume = function () {\r\n if (this.persistentConnection_) {\r\n this.persistentConnection_.resume(INTERRUPT_REASON);\r\n }\r\n };\r\n Repo.prototype.stats = function (showDelta) {\r\n if (showDelta === void 0) { showDelta = false; }\r\n if (typeof console === 'undefined')\r\n return;\r\n var stats;\r\n if (showDelta) {\r\n if (!this.statsListener_)\r\n this.statsListener_ = new StatsListener(this.stats_);\r\n stats = this.statsListener_.get();\r\n }\r\n else {\r\n stats = this.stats_.get();\r\n }\r\n var longestName = Object.keys(stats).reduce(function (previousValue, currentValue) {\r\n return Math.max(currentValue.length, previousValue);\r\n }, 0);\r\n util.forEach(stats, function (stat, value) {\r\n // pad stat names to be the same length (plus 2 extra spaces).\r\n for (var i = stat.length; i < longestName + 2; i++)\r\n stat += ' ';\r\n console.log(stat + value);\r\n });\r\n };\r\n Repo.prototype.statsIncrementCounter = function (metric) {\r\n this.stats_.incrementCounter(metric);\r\n this.statsReporter_.includeStat(metric);\r\n };\r\n /**\r\n * @param {...*} var_args\r\n * @private\r\n */\r\n Repo.prototype.log_ = function () {\r\n var var_args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n var_args[_i] = arguments[_i];\r\n }\r\n var prefix = '';\r\n if (this.persistentConnection_) {\r\n prefix = this.persistentConnection_.id + ':';\r\n }\r\n log.apply(void 0, [prefix].concat(var_args));\r\n };\r\n /**\r\n * @param {?function(?Error, *=)} callback\r\n * @param {!string} status\r\n * @param {?string=} errorReason\r\n */\r\n Repo.prototype.callOnCompleteCallback = function (callback, status, errorReason) {\r\n if (callback) {\r\n exceptionGuard(function () {\r\n if (status == 'ok') {\r\n callback(null);\r\n }\r\n else {\r\n var code = (status || 'error').toUpperCase();\r\n var message = code;\r\n if (errorReason)\r\n message += ': ' + errorReason;\r\n var error = new Error(message);\r\n error.code = code;\r\n callback(error);\r\n }\r\n });\r\n }\r\n };\r\n Object.defineProperty(Repo.prototype, \"database\", {\r\n get: function () {\r\n return this.__database || (this.__database = new Database(this));\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n return Repo;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node\r\n *\r\n * @constructor\r\n * @implements {NodeFilter}\r\n */\r\nvar RangedFilter = /** @class */ (function () {\r\n /**\r\n * @param {!QueryParams} params\r\n */\r\n function RangedFilter(params) {\r\n this.indexedFilter_ = new IndexedFilter(params.getIndex());\r\n this.index_ = params.getIndex();\r\n this.startPost_ = RangedFilter.getStartPost_(params);\r\n this.endPost_ = RangedFilter.getEndPost_(params);\r\n }\r\n /**\r\n * @return {!NamedNode}\r\n */\r\n RangedFilter.prototype.getStartPost = function () {\r\n return this.startPost_;\r\n };\r\n /**\r\n * @return {!NamedNode}\r\n */\r\n RangedFilter.prototype.getEndPost = function () {\r\n return this.endPost_;\r\n };\r\n /**\r\n * @param {!NamedNode} node\r\n * @return {boolean}\r\n */\r\n RangedFilter.prototype.matches = function (node) {\r\n return (this.index_.compare(this.getStartPost(), node) <= 0 &&\r\n this.index_.compare(node, this.getEndPost()) <= 0);\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n RangedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\r\n if (!this.matches(new NamedNode(key, newChild))) {\r\n newChild = ChildrenNode.EMPTY_NODE;\r\n }\r\n return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n RangedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\r\n if (newSnap.isLeafNode()) {\r\n // Make sure we have a children node with the correct index, not a leaf node;\r\n newSnap = ChildrenNode.EMPTY_NODE;\r\n }\r\n var filtered = newSnap.withIndex(this.index_);\r\n // Don't support priorities on queries\r\n filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);\r\n var self = this;\r\n newSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) {\r\n if (!self.matches(new NamedNode(key, childNode))) {\r\n filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);\r\n }\r\n });\r\n return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n RangedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\r\n // Don't support priorities on queries\r\n return oldSnap;\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n RangedFilter.prototype.filtersNodes = function () {\r\n return true;\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n RangedFilter.prototype.getIndexedFilter = function () {\r\n return this.indexedFilter_;\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n RangedFilter.prototype.getIndex = function () {\r\n return this.index_;\r\n };\r\n /**\r\n * @param {!QueryParams} params\r\n * @return {!NamedNode}\r\n * @private\r\n */\r\n RangedFilter.getStartPost_ = function (params) {\r\n if (params.hasStart()) {\r\n var startName = params.getIndexStartName();\r\n return params.getIndex().makePost(params.getIndexStartValue(), startName);\r\n }\r\n else {\r\n return params.getIndex().minPost();\r\n }\r\n };\r\n /**\r\n * @param {!QueryParams} params\r\n * @return {!NamedNode}\r\n * @private\r\n */\r\n RangedFilter.getEndPost_ = function (params) {\r\n if (params.hasEnd()) {\r\n var endName = params.getIndexEndName();\r\n return params.getIndex().makePost(params.getIndexEndValue(), endName);\r\n }\r\n else {\r\n return params.getIndex().maxPost();\r\n }\r\n };\r\n return RangedFilter;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible\r\n *\r\n * @constructor\r\n * @implements {NodeFilter}\r\n */\r\nvar LimitedFilter = /** @class */ (function () {\r\n /**\r\n * @param {!QueryParams} params\r\n */\r\n function LimitedFilter(params) {\r\n this.rangedFilter_ = new RangedFilter(params);\r\n this.index_ = params.getIndex();\r\n this.limit_ = params.getLimit();\r\n this.reverse_ = !params.isViewFromLeft();\r\n }\r\n /**\r\n * @inheritDoc\r\n */\r\n LimitedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\r\n if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {\r\n newChild = ChildrenNode.EMPTY_NODE;\r\n }\r\n if (snap.getImmediateChild(key).equals(newChild)) {\r\n // No change\r\n return snap;\r\n }\r\n else if (snap.numChildren() < this.limit_) {\r\n return this.rangedFilter_\r\n .getIndexedFilter()\r\n .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\r\n }\r\n else {\r\n return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);\r\n }\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n LimitedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\r\n var filtered;\r\n if (newSnap.isLeafNode() || newSnap.isEmpty()) {\r\n // Make sure we have a children node with the correct index, not a leaf node;\r\n filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);\r\n }\r\n else {\r\n if (this.limit_ * 2 < newSnap.numChildren() &&\r\n newSnap.isIndexed(this.index_)) {\r\n // Easier to build up a snapshot, since what we're given has more than twice the elements we want\r\n filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);\r\n // anchor to the startPost, endPost, or last element as appropriate\r\n var iterator = void 0;\r\n if (this.reverse_) {\r\n iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);\r\n }\r\n else {\r\n iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);\r\n }\r\n var count = 0;\r\n while (iterator.hasNext() && count < this.limit_) {\r\n var next = iterator.getNext();\r\n var inRange = void 0;\r\n if (this.reverse_) {\r\n inRange =\r\n this.index_.compare(this.rangedFilter_.getStartPost(), next) <= 0;\r\n }\r\n else {\r\n inRange =\r\n this.index_.compare(next, this.rangedFilter_.getEndPost()) <= 0;\r\n }\r\n if (inRange) {\r\n filtered = filtered.updateImmediateChild(next.name, next.node);\r\n count++;\r\n }\r\n else {\r\n // if we have reached the end post, we cannot keep adding elemments\r\n break;\r\n }\r\n }\r\n }\r\n else {\r\n // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one\r\n filtered = newSnap.withIndex(this.index_);\r\n // Don't support priorities on queries\r\n filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);\r\n var startPost = void 0;\r\n var endPost = void 0;\r\n var cmp = void 0;\r\n var iterator = void 0;\r\n if (this.reverse_) {\r\n iterator = filtered.getReverseIterator(this.index_);\r\n startPost = this.rangedFilter_.getEndPost();\r\n endPost = this.rangedFilter_.getStartPost();\r\n var indexCompare_1 = this.index_.getCompare();\r\n cmp = function (a, b) { return indexCompare_1(b, a); };\r\n }\r\n else {\r\n iterator = filtered.getIterator(this.index_);\r\n startPost = this.rangedFilter_.getStartPost();\r\n endPost = this.rangedFilter_.getEndPost();\r\n cmp = this.index_.getCompare();\r\n }\r\n var count = 0;\r\n var foundStartPost = false;\r\n while (iterator.hasNext()) {\r\n var next = iterator.getNext();\r\n if (!foundStartPost && cmp(startPost, next) <= 0) {\r\n // start adding\r\n foundStartPost = true;\r\n }\r\n var inRange = foundStartPost && count < this.limit_ && cmp(next, endPost) <= 0;\r\n if (inRange) {\r\n count++;\r\n }\r\n else {\r\n filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE);\r\n }\r\n }\r\n }\r\n }\r\n return this.rangedFilter_\r\n .getIndexedFilter()\r\n .updateFullNode(oldSnap, filtered, optChangeAccumulator);\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n LimitedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\r\n // Don't support priorities on queries\r\n return oldSnap;\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n LimitedFilter.prototype.filtersNodes = function () {\r\n return true;\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n LimitedFilter.prototype.getIndexedFilter = function () {\r\n return this.rangedFilter_.getIndexedFilter();\r\n };\r\n /**\r\n * @inheritDoc\r\n */\r\n LimitedFilter.prototype.getIndex = function () {\r\n return this.index_;\r\n };\r\n /**\r\n * @param {!Node} snap\r\n * @param {string} childKey\r\n * @param {!Node} childSnap\r\n * @param {!CompleteChildSource} source\r\n * @param {?ChildChangeAccumulator} changeAccumulator\r\n * @return {!Node}\r\n * @private\r\n */\r\n LimitedFilter.prototype.fullLimitUpdateChild_ = function (snap, childKey, childSnap, source, changeAccumulator) {\r\n // TODO: rename all cache stuff etc to general snap terminology\r\n var cmp;\r\n if (this.reverse_) {\r\n var indexCmp_1 = this.index_.getCompare();\r\n cmp = function (a, b) { return indexCmp_1(b, a); };\r\n }\r\n else {\r\n cmp = this.index_.getCompare();\r\n }\r\n var oldEventCache = snap;\r\n util.assert(oldEventCache.numChildren() == this.limit_, '');\r\n var newChildNamedNode = new NamedNode(childKey, childSnap);\r\n var windowBoundary = this.reverse_\r\n ? oldEventCache.getFirstChild(this.index_)\r\n : oldEventCache.getLastChild(this.index_);\r\n var inRange = this.rangedFilter_.matches(newChildNamedNode);\r\n if (oldEventCache.hasChild(childKey)) {\r\n var oldChildSnap = oldEventCache.getImmediateChild(childKey);\r\n var nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);\r\n while (nextChild != null &&\r\n (nextChild.name == childKey || oldEventCache.hasChild(nextChild.name))) {\r\n // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't\r\n // been applied to the limited filter yet. Ignore this next child which will be updated later in\r\n // the limited filter...\r\n nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);\r\n }\r\n var compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);\r\n var remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;\r\n if (remainsInWindow) {\r\n if (changeAccumulator != null) {\r\n changeAccumulator.trackChildChange(Change.childChangedChange(childKey, childSnap, oldChildSnap));\r\n }\r\n return oldEventCache.updateImmediateChild(childKey, childSnap);\r\n }\r\n else {\r\n if (changeAccumulator != null) {\r\n changeAccumulator.trackChildChange(Change.childRemovedChange(childKey, oldChildSnap));\r\n }\r\n var newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE);\r\n var nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);\r\n if (nextChildInRange) {\r\n if (changeAccumulator != null) {\r\n changeAccumulator.trackChildChange(Change.childAddedChange(nextChild.name, nextChild.node));\r\n }\r\n return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);\r\n }\r\n else {\r\n return newEventCache;\r\n }\r\n }\r\n }\r\n else if (childSnap.isEmpty()) {\r\n // we're deleting a node, but it was not in the window, so ignore it\r\n return snap;\r\n }\r\n else if (inRange) {\r\n if (cmp(windowBoundary, newChildNamedNode) >= 0) {\r\n if (changeAccumulator != null) {\r\n changeAccumulator.trackChildChange(Change.childRemovedChange(windowBoundary.name, windowBoundary.node));\r\n changeAccumulator.trackChildChange(Change.childAddedChange(childKey, childSnap));\r\n }\r\n return oldEventCache\r\n .updateImmediateChild(childKey, childSnap)\r\n .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);\r\n }\r\n else {\r\n return snap;\r\n }\r\n }\r\n else {\r\n return snap;\r\n }\r\n };\r\n return LimitedFilter;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a\r\n * range to be returned for a particular location. It is assumed that validation of parameters is done at the\r\n * user-facing API level, so it is not done here.\r\n * @constructor\r\n */\r\nvar QueryParams = /** @class */ (function () {\r\n function QueryParams() {\r\n this.limitSet_ = false;\r\n this.startSet_ = false;\r\n this.startNameSet_ = false;\r\n this.endSet_ = false;\r\n this.endNameSet_ = false;\r\n this.limit_ = 0;\r\n this.viewFrom_ = '';\r\n this.indexStartValue_ = null;\r\n this.indexStartName_ = '';\r\n this.indexEndValue_ = null;\r\n this.indexEndName_ = '';\r\n this.index_ = PRIORITY_INDEX;\r\n }\r\n /**\r\n * @return {boolean}\r\n */\r\n QueryParams.prototype.hasStart = function () {\r\n return this.startSet_;\r\n };\r\n /**\r\n * @return {boolean} True if it would return from left.\r\n */\r\n QueryParams.prototype.isViewFromLeft = function () {\r\n if (this.viewFrom_ === '') {\r\n // limit(), rather than limitToFirst or limitToLast was called.\r\n // This means that only one of startSet_ and endSet_ is true. Use them\r\n // to calculate which side of the view to anchor to. If neither is set,\r\n // anchor to the end.\r\n return this.startSet_;\r\n }\r\n else {\r\n return (this.viewFrom_ === QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT);\r\n }\r\n };\r\n /**\r\n * Only valid to call if hasStart() returns true\r\n * @return {*}\r\n */\r\n QueryParams.prototype.getIndexStartValue = function () {\r\n util.assert(this.startSet_, 'Only valid if start has been set');\r\n return this.indexStartValue_;\r\n };\r\n /**\r\n * Only valid to call if hasStart() returns true.\r\n * Returns the starting key name for the range defined by these query parameters\r\n * @return {!string}\r\n */\r\n QueryParams.prototype.getIndexStartName = function () {\r\n util.assert(this.startSet_, 'Only valid if start has been set');\r\n if (this.startNameSet_) {\r\n return this.indexStartName_;\r\n }\r\n else {\r\n return MIN_NAME;\r\n }\r\n };\r\n /**\r\n * @return {boolean}\r\n */\r\n QueryParams.prototype.hasEnd = function () {\r\n return this.endSet_;\r\n };\r\n /**\r\n * Only valid to call if hasEnd() returns true.\r\n * @return {*}\r\n */\r\n QueryParams.prototype.getIndexEndValue = function () {\r\n util.assert(this.endSet_, 'Only valid if end has been set');\r\n return this.indexEndValue_;\r\n };\r\n /**\r\n * Only valid to call if hasEnd() returns true.\r\n * Returns the end key name for the range defined by these query parameters\r\n * @return {!string}\r\n */\r\n QueryParams.prototype.getIndexEndName = function () {\r\n util.assert(this.endSet_, 'Only valid if end has been set');\r\n if (this.endNameSet_) {\r\n return this.indexEndName_;\r\n }\r\n else {\r\n return MAX_NAME;\r\n }\r\n };\r\n /**\r\n * @return {boolean}\r\n */\r\n QueryParams.prototype.hasLimit = function () {\r\n return this.limitSet_;\r\n };\r\n /**\r\n * @return {boolean} True if a limit has been set and it has been explicitly anchored\r\n */\r\n QueryParams.prototype.hasAnchoredLimit = function () {\r\n return this.limitSet_ && this.viewFrom_ !== '';\r\n };\r\n /**\r\n * Only valid to call if hasLimit() returns true\r\n * @return {!number}\r\n */\r\n QueryParams.prototype.getLimit = function () {\r\n util.assert(this.limitSet_, 'Only valid if limit has been set');\r\n return this.limit_;\r\n };\r\n /**\r\n * @return {!Index}\r\n */\r\n QueryParams.prototype.getIndex = function () {\r\n return this.index_;\r\n };\r\n /**\r\n * @return {!QueryParams}\r\n * @private\r\n */\r\n QueryParams.prototype.copy_ = function () {\r\n var copy = new QueryParams();\r\n copy.limitSet_ = this.limitSet_;\r\n copy.limit_ = this.limit_;\r\n copy.startSet_ = this.startSet_;\r\n copy.indexStartValue_ = this.indexStartValue_;\r\n copy.startNameSet_ = this.startNameSet_;\r\n copy.indexStartName_ = this.indexStartName_;\r\n copy.endSet_ = this.endSet_;\r\n copy.indexEndValue_ = this.indexEndValue_;\r\n copy.endNameSet_ = this.endNameSet_;\r\n copy.indexEndName_ = this.indexEndName_;\r\n copy.index_ = this.index_;\r\n copy.viewFrom_ = this.viewFrom_;\r\n return copy;\r\n };\r\n /**\r\n * @param {!number} newLimit\r\n * @return {!QueryParams}\r\n */\r\n QueryParams.prototype.limit = function (newLimit) {\r\n var newParams = this.copy_();\r\n newParams.limitSet_ = true;\r\n newParams.limit_ = newLimit;\r\n newParams.viewFrom_ = '';\r\n return newParams;\r\n };\r\n /**\r\n * @param {!number} newLimit\r\n * @return {!QueryParams}\r\n */\r\n QueryParams.prototype.limitToFirst = function (newLimit) {\r\n var newParams = this.copy_();\r\n newParams.limitSet_ = true;\r\n newParams.limit_ = newLimit;\r\n newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT;\r\n return newParams;\r\n };\r\n /**\r\n * @param {!number} newLimit\r\n * @return {!QueryParams}\r\n */\r\n QueryParams.prototype.limitToLast = function (newLimit) {\r\n var newParams = this.copy_();\r\n newParams.limitSet_ = true;\r\n newParams.limit_ = newLimit;\r\n newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_RIGHT;\r\n return newParams;\r\n };\r\n /**\r\n * @param {*} indexValue\r\n * @param {?string=} key\r\n * @return {!QueryParams}\r\n */\r\n QueryParams.prototype.startAt = function (indexValue, key) {\r\n var newParams = this.copy_();\r\n newParams.startSet_ = true;\r\n if (indexValue === undefined) {\r\n indexValue = null;\r\n }\r\n newParams.indexStartValue_ = indexValue;\r\n if (key != null) {\r\n newParams.startNameSet_ = true;\r\n newParams.indexStartName_ = key;\r\n }\r\n else {\r\n newParams.startNameSet_ = false;\r\n newParams.indexStartName_ = '';\r\n }\r\n return newParams;\r\n };\r\n /**\r\n * @param {*} indexValue\r\n * @param {?string=} key\r\n * @return {!QueryParams}\r\n */\r\n QueryParams.prototype.endAt = function (indexValue, key) {\r\n var newParams = this.copy_();\r\n newParams.endSet_ = true;\r\n if (indexValue === undefined) {\r\n indexValue = null;\r\n }\r\n newParams.indexEndValue_ = indexValue;\r\n if (key !== undefined) {\r\n newParams.endNameSet_ = true;\r\n newParams.indexEndName_ = key;\r\n }\r\n else {\r\n newParams.endNameSet_ = false;\r\n newParams.indexEndName_ = '';\r\n }\r\n return newParams;\r\n };\r\n /**\r\n * @param {!Index} index\r\n * @return {!QueryParams}\r\n */\r\n QueryParams.prototype.orderBy = function (index) {\r\n var newParams = this.copy_();\r\n newParams.index_ = index;\r\n return newParams;\r\n };\r\n /**\r\n * @return {!Object}\r\n */\r\n QueryParams.prototype.getQueryObject = function () {\r\n var WIRE_PROTOCOL_CONSTANTS = QueryParams.WIRE_PROTOCOL_CONSTANTS_;\r\n var obj = {};\r\n if (this.startSet_) {\r\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE] = this.indexStartValue_;\r\n if (this.startNameSet_) {\r\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME] = this.indexStartName_;\r\n }\r\n }\r\n if (this.endSet_) {\r\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE] = this.indexEndValue_;\r\n if (this.endNameSet_) {\r\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME] = this.indexEndName_;\r\n }\r\n }\r\n if (this.limitSet_) {\r\n obj[WIRE_PROTOCOL_CONSTANTS.LIMIT] = this.limit_;\r\n var viewFrom = this.viewFrom_;\r\n if (viewFrom === '') {\r\n if (this.isViewFromLeft()) {\r\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\r\n }\r\n else {\r\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT;\r\n }\r\n }\r\n obj[WIRE_PROTOCOL_CONSTANTS.VIEW_FROM] = viewFrom;\r\n }\r\n // For now, priority index is the default, so we only specify if it's some other index\r\n if (this.index_ !== PRIORITY_INDEX) {\r\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX] = this.index_.toString();\r\n }\r\n return obj;\r\n };\r\n /**\r\n * @return {boolean}\r\n */\r\n QueryParams.prototype.loadsAllData = function () {\r\n return !(this.startSet_ || this.endSet_ || this.limitSet_);\r\n };\r\n /**\r\n * @return {boolean}\r\n */\r\n QueryParams.prototype.isDefault = function () {\r\n return this.loadsAllData() && this.index_ == PRIORITY_INDEX;\r\n };\r\n /**\r\n * @return {!NodeFilter}\r\n */\r\n QueryParams.prototype.getNodeFilter = function () {\r\n if (this.loadsAllData()) {\r\n return new IndexedFilter(this.getIndex());\r\n }\r\n else if (this.hasLimit()) {\r\n return new LimitedFilter(this);\r\n }\r\n else {\r\n return new RangedFilter(this);\r\n }\r\n };\r\n /**\r\n * Returns a set of REST query string parameters representing this query.\r\n *\r\n * @return {!Object.} query string parameters\r\n */\r\n QueryParams.prototype.toRestQueryStringParameters = function () {\r\n var REST_CONSTANTS = QueryParams.REST_QUERY_CONSTANTS_;\r\n var qs = {};\r\n if (this.isDefault()) {\r\n return qs;\r\n }\r\n var orderBy;\r\n if (this.index_ === PRIORITY_INDEX) {\r\n orderBy = REST_CONSTANTS.PRIORITY_INDEX;\r\n }\r\n else if (this.index_ === VALUE_INDEX) {\r\n orderBy = REST_CONSTANTS.VALUE_INDEX;\r\n }\r\n else if (this.index_ === KEY_INDEX) {\r\n orderBy = REST_CONSTANTS.KEY_INDEX;\r\n }\r\n else {\r\n util.assert(this.index_ instanceof PathIndex, 'Unrecognized index type!');\r\n orderBy = this.index_.toString();\r\n }\r\n qs[REST_CONSTANTS.ORDER_BY] = util.stringify(orderBy);\r\n if (this.startSet_) {\r\n qs[REST_CONSTANTS.START_AT] = util.stringify(this.indexStartValue_);\r\n if (this.startNameSet_) {\r\n qs[REST_CONSTANTS.START_AT] += ',' + util.stringify(this.indexStartName_);\r\n }\r\n }\r\n if (this.endSet_) {\r\n qs[REST_CONSTANTS.END_AT] = util.stringify(this.indexEndValue_);\r\n if (this.endNameSet_) {\r\n qs[REST_CONSTANTS.END_AT] += ',' + util.stringify(this.indexEndName_);\r\n }\r\n }\r\n if (this.limitSet_) {\r\n if (this.isViewFromLeft()) {\r\n qs[REST_CONSTANTS.LIMIT_TO_FIRST] = this.limit_;\r\n }\r\n else {\r\n qs[REST_CONSTANTS.LIMIT_TO_LAST] = this.limit_;\r\n }\r\n }\r\n return qs;\r\n };\r\n /**\r\n * Wire Protocol Constants\r\n * @const\r\n * @enum {string}\r\n * @private\r\n */\r\n QueryParams.WIRE_PROTOCOL_CONSTANTS_ = {\r\n INDEX_START_VALUE: 'sp',\r\n INDEX_START_NAME: 'sn',\r\n INDEX_END_VALUE: 'ep',\r\n INDEX_END_NAME: 'en',\r\n LIMIT: 'l',\r\n VIEW_FROM: 'vf',\r\n VIEW_FROM_LEFT: 'l',\r\n VIEW_FROM_RIGHT: 'r',\r\n INDEX: 'i'\r\n };\r\n /**\r\n * REST Query Constants\r\n * @const\r\n * @enum {string}\r\n * @private\r\n */\r\n QueryParams.REST_QUERY_CONSTANTS_ = {\r\n ORDER_BY: 'orderBy',\r\n PRIORITY_INDEX: '$priority',\r\n VALUE_INDEX: '$value',\r\n KEY_INDEX: '$key',\r\n START_AT: 'startAt',\r\n END_AT: 'endAt',\r\n LIMIT_TO_FIRST: 'limitToFirst',\r\n LIMIT_TO_LAST: 'limitToLast'\r\n };\r\n /**\r\n * Default, empty query parameters\r\n * @type {!QueryParams}\r\n * @const\r\n */\r\n QueryParams.DEFAULT = new QueryParams();\r\n return QueryParams;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar Reference = /** @class */ (function (_super) {\r\n tslib_1.__extends(Reference, _super);\r\n /**\r\n * Call options:\r\n * new Reference(Repo, Path) or\r\n * new Reference(url: string, string|RepoManager)\r\n *\r\n * Externally - this is the firebase.database.Reference type.\r\n *\r\n * @param {!Repo} repo\r\n * @param {(!Path)} path\r\n * @extends {Query}\r\n */\r\n function Reference(repo, path) {\r\n var _this = this;\r\n if (!(repo instanceof Repo)) {\r\n throw new Error('new Reference() no longer supported - use app.database().');\r\n }\r\n // call Query's constructor, passing in the repo and path.\r\n _this = _super.call(this, repo, path, QueryParams.DEFAULT, false) || this;\r\n return _this;\r\n }\r\n /** @return {?string} */\r\n Reference.prototype.getKey = function () {\r\n util.validateArgCount('Reference.key', 0, 0, arguments.length);\r\n if (this.path.isEmpty())\r\n return null;\r\n else\r\n return this.path.getBack();\r\n };\r\n /**\r\n * @param {!(string|Path)} pathString\r\n * @return {!Reference}\r\n */\r\n Reference.prototype.child = function (pathString) {\r\n util.validateArgCount('Reference.child', 1, 1, arguments.length);\r\n if (typeof pathString === 'number') {\r\n pathString = String(pathString);\r\n }\r\n else if (!(pathString instanceof Path)) {\r\n if (this.path.getFront() === null)\r\n validateRootPathString('Reference.child', 1, pathString, false);\r\n else\r\n validatePathString('Reference.child', 1, pathString, false);\r\n }\r\n return new Reference(this.repo, this.path.child(pathString));\r\n };\r\n /** @return {?Reference} */\r\n Reference.prototype.getParent = function () {\r\n util.validateArgCount('Reference.parent', 0, 0, arguments.length);\r\n var parentPath = this.path.parent();\r\n return parentPath === null ? null : new Reference(this.repo, parentPath);\r\n };\r\n /** @return {!Reference} */\r\n Reference.prototype.getRoot = function () {\r\n util.validateArgCount('Reference.root', 0, 0, arguments.length);\r\n var ref = this;\r\n while (ref.getParent() !== null) {\r\n ref = ref.getParent();\r\n }\r\n return ref;\r\n };\r\n /** @return {!Database} */\r\n Reference.prototype.databaseProp = function () {\r\n return this.repo.database;\r\n };\r\n /**\r\n * @param {*} newVal\r\n * @param {function(?Error)=} onComplete\r\n * @return {!Promise}\r\n */\r\n Reference.prototype.set = function (newVal, onComplete) {\r\n util.validateArgCount('Reference.set', 1, 2, arguments.length);\r\n validateWritablePath('Reference.set', this.path);\r\n validateFirebaseDataArg('Reference.set', 1, newVal, this.path, false);\r\n util.validateCallback('Reference.set', 2, onComplete, true);\r\n var deferred = new util.Deferred();\r\n this.repo.setWithPriority(this.path, newVal, \r\n /*priority=*/ null, deferred.wrapCallback(onComplete));\r\n return deferred.promise;\r\n };\r\n /**\r\n * @param {!Object} objectToMerge\r\n * @param {function(?Error)=} onComplete\r\n * @return {!Promise}\r\n */\r\n Reference.prototype.update = function (objectToMerge, onComplete) {\r\n util.validateArgCount('Reference.update', 1, 2, arguments.length);\r\n validateWritablePath('Reference.update', this.path);\r\n if (Array.isArray(objectToMerge)) {\r\n var newObjectToMerge = {};\r\n for (var i = 0; i < objectToMerge.length; ++i) {\r\n newObjectToMerge['' + i] = objectToMerge[i];\r\n }\r\n objectToMerge = newObjectToMerge;\r\n warn('Passing an Array to Firebase.update() is deprecated. ' +\r\n 'Use set() if you want to overwrite the existing data, or ' +\r\n 'an Object with integer keys if you really do want to ' +\r\n 'only update some of the children.');\r\n }\r\n validateFirebaseMergeDataArg('Reference.update', 1, objectToMerge, this.path, false);\r\n util.validateCallback('Reference.update', 2, onComplete, true);\r\n var deferred = new util.Deferred();\r\n this.repo.update(this.path, objectToMerge, deferred.wrapCallback(onComplete));\r\n return deferred.promise;\r\n };\r\n /**\r\n * @param {*} newVal\r\n * @param {string|number|null} newPriority\r\n * @param {function(?Error)=} onComplete\r\n * @return {!Promise}\r\n */\r\n Reference.prototype.setWithPriority = function (newVal, newPriority, onComplete) {\r\n util.validateArgCount('Reference.setWithPriority', 2, 3, arguments.length);\r\n validateWritablePath('Reference.setWithPriority', this.path);\r\n validateFirebaseDataArg('Reference.setWithPriority', 1, newVal, this.path, false);\r\n validatePriority('Reference.setWithPriority', 2, newPriority, false);\r\n util.validateCallback('Reference.setWithPriority', 3, onComplete, true);\r\n if (this.getKey() === '.length' || this.getKey() === '.keys')\r\n throw 'Reference.setWithPriority failed: ' +\r\n this.getKey() +\r\n ' is a read-only object.';\r\n var deferred = new util.Deferred();\r\n this.repo.setWithPriority(this.path, newVal, newPriority, deferred.wrapCallback(onComplete));\r\n return deferred.promise;\r\n };\r\n /**\r\n * @param {function(?Error)=} onComplete\r\n * @return {!Promise}\r\n */\r\n Reference.prototype.remove = function (onComplete) {\r\n util.validateArgCount('Reference.remove', 0, 1, arguments.length);\r\n validateWritablePath('Reference.remove', this.path);\r\n util.validateCallback('Reference.remove', 1, onComplete, true);\r\n return this.set(null, onComplete);\r\n };\r\n /**\r\n * @param {function(*):*} transactionUpdate\r\n * @param {(function(?Error, boolean, ?DataSnapshot))=} onComplete\r\n * @param {boolean=} applyLocally\r\n * @return {!Promise}\r\n */\r\n Reference.prototype.transaction = function (transactionUpdate, onComplete, applyLocally) {\r\n util.validateArgCount('Reference.transaction', 1, 3, arguments.length);\r\n validateWritablePath('Reference.transaction', this.path);\r\n util.validateCallback('Reference.transaction', 1, transactionUpdate, false);\r\n util.validateCallback('Reference.transaction', 2, onComplete, true);\r\n // NOTE: applyLocally is an internal-only option for now. We need to decide if we want to keep it and how\r\n // to expose it.\r\n validateBoolean('Reference.transaction', 3, applyLocally, true);\r\n if (this.getKey() === '.length' || this.getKey() === '.keys')\r\n throw 'Reference.transaction failed: ' +\r\n this.getKey() +\r\n ' is a read-only object.';\r\n if (applyLocally === undefined)\r\n applyLocally = true;\r\n var deferred = new util.Deferred();\r\n if (typeof onComplete === 'function') {\r\n deferred.promise.catch(function () { });\r\n }\r\n var promiseComplete = function (error, committed, snapshot) {\r\n if (error) {\r\n deferred.reject(error);\r\n }\r\n else {\r\n deferred.resolve(new TransactionResult(committed, snapshot));\r\n }\r\n if (typeof onComplete === 'function') {\r\n onComplete(error, committed, snapshot);\r\n }\r\n };\r\n this.repo.startTransaction(this.path, transactionUpdate, promiseComplete, applyLocally);\r\n return deferred.promise;\r\n };\r\n /**\r\n * @param {string|number|null} priority\r\n * @param {function(?Error)=} onComplete\r\n * @return {!Promise}\r\n */\r\n Reference.prototype.setPriority = function (priority, onComplete) {\r\n util.validateArgCount('Reference.setPriority', 1, 2, arguments.length);\r\n validateWritablePath('Reference.setPriority', this.path);\r\n validatePriority('Reference.setPriority', 1, priority, false);\r\n util.validateCallback('Reference.setPriority', 2, onComplete, true);\r\n var deferred = new util.Deferred();\r\n this.repo.setWithPriority(this.path.child('.priority'), priority, null, deferred.wrapCallback(onComplete));\r\n return deferred.promise;\r\n };\r\n /**\r\n * @param {*=} value\r\n * @param {function(?Error)=} onComplete\r\n * @return {!Reference}\r\n */\r\n Reference.prototype.push = function (value, onComplete) {\r\n util.validateArgCount('Reference.push', 0, 2, arguments.length);\r\n validateWritablePath('Reference.push', this.path);\r\n validateFirebaseDataArg('Reference.push', 1, value, this.path, true);\r\n util.validateCallback('Reference.push', 2, onComplete, true);\r\n var now = this.repo.serverTime();\r\n var name = nextPushId(now);\r\n // push() returns a ThennableReference whose promise is fulfilled with a regular Reference.\r\n // We use child() to create handles to two different references. The first is turned into a\r\n // ThennableReference below by adding then() and catch() methods and is used as the\r\n // return value of push(). The second remains a regular Reference and is used as the fulfilled\r\n // value of the first ThennableReference.\r\n var thennablePushRef = this.child(name);\r\n var pushRef = this.child(name);\r\n var promise;\r\n if (value != null) {\r\n promise = thennablePushRef.set(value, onComplete).then(function () { return pushRef; });\r\n }\r\n else {\r\n promise = Promise.resolve(pushRef);\r\n }\r\n thennablePushRef.then = promise.then.bind(promise);\r\n thennablePushRef.catch = promise.then.bind(promise, undefined);\r\n if (typeof onComplete === 'function') {\r\n promise.catch(function () { });\r\n }\r\n return thennablePushRef;\r\n };\r\n /**\r\n * @return {!OnDisconnect}\r\n */\r\n Reference.prototype.onDisconnect = function () {\r\n validateWritablePath('Reference.onDisconnect', this.path);\r\n return new OnDisconnect(this.repo, this.path);\r\n };\r\n Object.defineProperty(Reference.prototype, \"database\", {\r\n get: function () {\r\n return this.databaseProp();\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(Reference.prototype, \"key\", {\r\n get: function () {\r\n return this.getKey();\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(Reference.prototype, \"parent\", {\r\n get: function () {\r\n return this.getParent();\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(Reference.prototype, \"root\", {\r\n get: function () {\r\n return this.getRoot();\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n return Reference;\r\n}(Query));\r\n/**\r\n * Define reference constructor in various modules\r\n *\r\n * We are doing this here to avoid several circular\r\n * dependency issues\r\n */\r\nQuery.__referenceConstructor = Reference;\r\nSyncPoint.__referenceConstructor = Reference;\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Node in a Tree.\r\n */\r\nvar TreeNode = /** @class */ (function () {\r\n function TreeNode() {\r\n // TODO: Consider making accessors that create children and value lazily or\r\n // separate Internal / Leaf 'types'.\r\n this.children = {};\r\n this.childCount = 0;\r\n this.value = null;\r\n }\r\n return TreeNode;\r\n}());\r\n/**\r\n * A light-weight tree, traversable by path. Nodes can have both values and children.\r\n * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty\r\n * children.\r\n */\r\nvar Tree = /** @class */ (function () {\r\n /**\r\n * @template T\r\n * @param {string=} name_ Optional name of the node.\r\n * @param {Tree=} parent_ Optional parent node.\r\n * @param {TreeNode=} node_ Optional node to wrap.\r\n */\r\n function Tree(name_, parent_, node_) {\r\n if (name_ === void 0) { name_ = ''; }\r\n if (parent_ === void 0) { parent_ = null; }\r\n if (node_ === void 0) { node_ = new TreeNode(); }\r\n this.name_ = name_;\r\n this.parent_ = parent_;\r\n this.node_ = node_;\r\n }\r\n /**\r\n * Returns a sub-Tree for the given path.\r\n *\r\n * @param {!(string|Path)} pathObj Path to look up.\r\n * @return {!Tree.} Tree for path.\r\n */\r\n Tree.prototype.subTree = function (pathObj) {\r\n // TODO: Require pathObj to be Path?\r\n var path = pathObj instanceof Path ? pathObj : new Path(pathObj);\r\n var child = this, next;\r\n while ((next = path.getFront()) !== null) {\r\n var childNode = util.safeGet(child.node_.children, next) || new TreeNode();\r\n child = new Tree(next, child, childNode);\r\n path = path.popFront();\r\n }\r\n return child;\r\n };\r\n /**\r\n * Returns the data associated with this tree node.\r\n *\r\n * @return {?T} The data or null if no data exists.\r\n */\r\n Tree.prototype.getValue = function () {\r\n return this.node_.value;\r\n };\r\n /**\r\n * Sets data to this tree node.\r\n *\r\n * @param {!T} value Value to set.\r\n */\r\n Tree.prototype.setValue = function (value) {\r\n util.assert(typeof value !== 'undefined', 'Cannot set value to undefined');\r\n this.node_.value = value;\r\n this.updateParents_();\r\n };\r\n /**\r\n * Clears the contents of the tree node (its value and all children).\r\n */\r\n Tree.prototype.clear = function () {\r\n this.node_.value = null;\r\n this.node_.children = {};\r\n this.node_.childCount = 0;\r\n this.updateParents_();\r\n };\r\n /**\r\n * @return {boolean} Whether the tree has any children.\r\n */\r\n Tree.prototype.hasChildren = function () {\r\n return this.node_.childCount > 0;\r\n };\r\n /**\r\n * @return {boolean} Whether the tree is empty (no value or children).\r\n */\r\n Tree.prototype.isEmpty = function () {\r\n return this.getValue() === null && !this.hasChildren();\r\n };\r\n /**\r\n * Calls action for each child of this tree node.\r\n *\r\n * @param {function(!Tree.)} action Action to be called for each child.\r\n */\r\n Tree.prototype.forEachChild = function (action) {\r\n var _this = this;\r\n util.forEach(this.node_.children, function (child, childTree) {\r\n action(new Tree(child, _this, childTree));\r\n });\r\n };\r\n /**\r\n * Does a depth-first traversal of this node's descendants, calling action for each one.\r\n *\r\n * @param {function(!Tree.)} action Action to be called for each child.\r\n * @param {boolean=} includeSelf Whether to call action on this node as well. Defaults to\r\n * false.\r\n * @param {boolean=} childrenFirst Whether to call action on children before calling it on\r\n * parent.\r\n */\r\n Tree.prototype.forEachDescendant = function (action, includeSelf, childrenFirst) {\r\n if (includeSelf && !childrenFirst)\r\n action(this);\r\n this.forEachChild(function (child) {\r\n child.forEachDescendant(action, /*includeSelf=*/ true, childrenFirst);\r\n });\r\n if (includeSelf && childrenFirst)\r\n action(this);\r\n };\r\n /**\r\n * Calls action on each ancestor node.\r\n *\r\n * @param {function(!Tree.)} action Action to be called on each parent; return\r\n * true to abort.\r\n * @param {boolean=} includeSelf Whether to call action on this node as well.\r\n * @return {boolean} true if the action callback returned true.\r\n */\r\n Tree.prototype.forEachAncestor = function (action, includeSelf) {\r\n var node = includeSelf ? this : this.parent();\r\n while (node !== null) {\r\n if (action(node)) {\r\n return true;\r\n }\r\n node = node.parent();\r\n }\r\n return false;\r\n };\r\n /**\r\n * Does a depth-first traversal of this node's descendants. When a descendant with a value\r\n * is found, action is called on it and traversal does not continue inside the node.\r\n * Action is *not* called on this node.\r\n *\r\n * @param {function(!Tree.)} action Action to be called for each child.\r\n */\r\n Tree.prototype.forEachImmediateDescendantWithValue = function (action) {\r\n this.forEachChild(function (child) {\r\n if (child.getValue() !== null)\r\n action(child);\r\n else\r\n child.forEachImmediateDescendantWithValue(action);\r\n });\r\n };\r\n /**\r\n * @return {!Path} The path of this tree node, as a Path.\r\n */\r\n Tree.prototype.path = function () {\r\n return new Path(this.parent_ === null\r\n ? this.name_\r\n : this.parent_.path() + '/' + this.name_);\r\n };\r\n /**\r\n * @return {string} The name of the tree node.\r\n */\r\n Tree.prototype.name = function () {\r\n return this.name_;\r\n };\r\n /**\r\n * @return {?Tree} The parent tree node, or null if this is the root of the tree.\r\n */\r\n Tree.prototype.parent = function () {\r\n return this.parent_;\r\n };\r\n /**\r\n * Adds or removes this child from its parent based on whether it's empty or not.\r\n *\r\n * @private\r\n */\r\n Tree.prototype.updateParents_ = function () {\r\n if (this.parent_ !== null)\r\n this.parent_.updateChild_(this.name_, this);\r\n };\r\n /**\r\n * Adds or removes the passed child to this tree node, depending on whether it's empty.\r\n *\r\n * @param {string} childName The name of the child to update.\r\n * @param {!Tree.} child The child to update.\r\n * @private\r\n */\r\n Tree.prototype.updateChild_ = function (childName, child) {\r\n var childEmpty = child.isEmpty();\r\n var childExists = util.contains(this.node_.children, childName);\r\n if (childEmpty && childExists) {\r\n delete this.node_.children[childName];\r\n this.node_.childCount--;\r\n this.updateParents_();\r\n }\r\n else if (!childEmpty && !childExists) {\r\n this.node_.children[childName] = child.node_;\r\n this.node_.childCount++;\r\n this.updateParents_();\r\n }\r\n };\r\n return Tree;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// TODO: This is pretty messy. Ideally, a lot of this would move into FirebaseData, or a transaction-specific\r\n// component used by FirebaseData, but it has ties to user callbacks (transaction update and onComplete) as well\r\n// as the realtime connection (to send transactions to the server). So that all needs to be decoupled first.\r\n// For now it's part of Repo, but in its own file.\r\n/**\r\n * @enum {number}\r\n */\r\nvar TransactionStatus;\r\n(function (TransactionStatus) {\r\n // We've run the transaction and updated transactionResultData_ with the result, but it isn't currently sent to the\r\n // server. A transaction will go from RUN -> SENT -> RUN if it comes back from the server as rejected due to\r\n // mismatched hash.\r\n TransactionStatus[TransactionStatus[\"RUN\"] = 0] = \"RUN\";\r\n // We've run the transaction and sent it to the server and it's currently outstanding (hasn't come back as accepted\r\n // or rejected yet).\r\n TransactionStatus[TransactionStatus[\"SENT\"] = 1] = \"SENT\";\r\n // Temporary state used to mark completed transactions (whether successful or aborted). The transaction will be\r\n // removed when we get a chance to prune completed ones.\r\n TransactionStatus[TransactionStatus[\"COMPLETED\"] = 2] = \"COMPLETED\";\r\n // Used when an already-sent transaction needs to be aborted (e.g. due to a conflicting set() call that was made).\r\n // If it comes back as unsuccessful, we'll abort it.\r\n TransactionStatus[TransactionStatus[\"SENT_NEEDS_ABORT\"] = 3] = \"SENT_NEEDS_ABORT\";\r\n // Temporary state used to mark transactions that need to be aborted.\r\n TransactionStatus[TransactionStatus[\"NEEDS_ABORT\"] = 4] = \"NEEDS_ABORT\";\r\n})(TransactionStatus || (TransactionStatus = {}));\r\n/**\r\n * If a transaction does not succeed after 25 retries, we abort it. Among other things this ensure that if there's\r\n * ever a bug causing a mismatch between client / server hashes for some data, we won't retry indefinitely.\r\n * @type {number}\r\n * @const\r\n * @private\r\n */\r\nRepo.MAX_TRANSACTION_RETRIES_ = 25;\r\n/**\r\n * Setup the transaction data structures\r\n * @private\r\n */\r\nRepo.prototype.transactions_init_ = function () {\r\n /**\r\n * Stores queues of outstanding transactions for Firebase locations.\r\n *\r\n * @type {!Tree.>}\r\n * @private\r\n */\r\n this.transactionQueueTree_ = new Tree();\r\n};\r\n/**\r\n * Creates a new transaction, adds it to the transactions we're tracking, and sends it to the server if possible.\r\n *\r\n * @param {!Path} path Path at which to do transaction.\r\n * @param {function(*):*} transactionUpdate Update callback.\r\n * @param {?function(?Error, boolean, ?DataSnapshot)} onComplete Completion callback.\r\n * @param {boolean} applyLocally Whether or not to make intermediate results visible\r\n */\r\nRepo.prototype.startTransaction = function (path, transactionUpdate, onComplete, applyLocally) {\r\n this.log_('transaction on ' + path);\r\n // Add a watch to make sure we get server updates.\r\n var valueCallback = function () { };\r\n var watchRef = new Reference(this, path);\r\n watchRef.on('value', valueCallback);\r\n var unwatcher = function () {\r\n watchRef.off('value', valueCallback);\r\n };\r\n // Initialize transaction.\r\n var transaction = {\r\n path: path,\r\n update: transactionUpdate,\r\n onComplete: onComplete,\r\n // One of TransactionStatus enums.\r\n status: null,\r\n // Used when combining transactions at different locations to figure out which one goes first.\r\n order: LUIDGenerator(),\r\n // Whether to raise local events for this transaction.\r\n applyLocally: applyLocally,\r\n // Count of how many times we've retried the transaction.\r\n retryCount: 0,\r\n // Function to call to clean up our .on() listener.\r\n unwatcher: unwatcher,\r\n // Stores why a transaction was aborted.\r\n abortReason: null,\r\n currentWriteId: null,\r\n currentInputSnapshot: null,\r\n currentOutputSnapshotRaw: null,\r\n currentOutputSnapshotResolved: null\r\n };\r\n // Run transaction initially.\r\n var currentState = this.getLatestState_(path);\r\n transaction.currentInputSnapshot = currentState;\r\n var newVal = transaction.update(currentState.val());\r\n if (newVal === undefined) {\r\n // Abort transaction.\r\n transaction.unwatcher();\r\n transaction.currentOutputSnapshotRaw = null;\r\n transaction.currentOutputSnapshotResolved = null;\r\n if (transaction.onComplete) {\r\n // We just set the input snapshot, so this cast should be safe\r\n var snapshot = new DataSnapshot(transaction.currentInputSnapshot, new Reference(this, transaction.path), PRIORITY_INDEX);\r\n transaction.onComplete(null, false, snapshot);\r\n }\r\n }\r\n else {\r\n validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);\r\n // Mark as run and add to our queue.\r\n transaction.status = TransactionStatus.RUN;\r\n var queueNode = this.transactionQueueTree_.subTree(path);\r\n var nodeQueue = queueNode.getValue() || [];\r\n nodeQueue.push(transaction);\r\n queueNode.setValue(nodeQueue);\r\n // Update visibleData and raise events\r\n // Note: We intentionally raise events after updating all of our transaction state, since the user could\r\n // start new transactions from the event callbacks.\r\n var priorityForNode = void 0;\r\n if (typeof newVal === 'object' &&\r\n newVal !== null &&\r\n util.contains(newVal, '.priority')) {\r\n priorityForNode = util.safeGet(newVal, '.priority');\r\n util.assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +\r\n 'Priority must be a valid string, finite number, server value, or null.');\r\n }\r\n else {\r\n var currentNode = this.serverSyncTree_.calcCompleteEventCache(path) ||\r\n ChildrenNode.EMPTY_NODE;\r\n priorityForNode = currentNode.getPriority().val();\r\n }\r\n priorityForNode /** @type {null|number|string} */ = priorityForNode;\r\n var serverValues = this.generateServerValues();\r\n var newNodeUnresolved = nodeFromJSON$1(newVal, priorityForNode);\r\n var newNode = resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\r\n transaction.currentOutputSnapshotRaw = newNodeUnresolved;\r\n transaction.currentOutputSnapshotResolved = newNode;\r\n transaction.currentWriteId = this.getNextWriteId_();\r\n var events = this.serverSyncTree_.applyUserOverwrite(path, newNode, transaction.currentWriteId, transaction.applyLocally);\r\n this.eventQueue_.raiseEventsForChangedPath(path, events);\r\n this.sendReadyTransactions_();\r\n }\r\n};\r\n/**\r\n * @param {!Path} path\r\n * @param {Array.=} excludeSets A specific set to exclude\r\n * @return {Node}\r\n * @private\r\n */\r\nRepo.prototype.getLatestState_ = function (path, excludeSets) {\r\n return (this.serverSyncTree_.calcCompleteEventCache(path, excludeSets) ||\r\n ChildrenNode.EMPTY_NODE);\r\n};\r\n/**\r\n * Sends any already-run transactions that aren't waiting for outstanding transactions to\r\n * complete.\r\n *\r\n * Externally it's called with no arguments, but it calls itself recursively with a particular\r\n * transactionQueueTree node to recurse through the tree.\r\n *\r\n * @param {Tree.>=} node transactionQueueTree node to start at.\r\n * @private\r\n */\r\nRepo.prototype.sendReadyTransactions_ = function (node) {\r\n var _this = this;\r\n if (node === void 0) { node = this.transactionQueueTree_; }\r\n // Before recursing, make sure any completed transactions are removed.\r\n if (!node) {\r\n this.pruneCompletedTransactionsBelowNode_(node);\r\n }\r\n if (node.getValue() !== null) {\r\n var queue = this.buildTransactionQueue_(node);\r\n util.assert(queue.length > 0, 'Sending zero length transaction queue');\r\n var allRun = queue.every(function (transaction) { return transaction.status === TransactionStatus.RUN; });\r\n // If they're all run (and not sent), we can send them. Else, we must wait.\r\n if (allRun) {\r\n this.sendTransactionQueue_(node.path(), queue);\r\n }\r\n }\r\n else if (node.hasChildren()) {\r\n node.forEachChild(function (childNode) {\r\n _this.sendReadyTransactions_(childNode);\r\n });\r\n }\r\n};\r\n/**\r\n * Given a list of run transactions, send them to the server and then handle the result (success or failure).\r\n *\r\n * @param {!Path} path The location of the queue.\r\n * @param {!Array.} queue Queue of transactions under the specified location.\r\n * @private\r\n */\r\nRepo.prototype.sendTransactionQueue_ = function (path, queue) {\r\n var _this = this;\r\n // Mark transactions as sent and increment retry count!\r\n var setsToIgnore = queue.map(function (txn) {\r\n return txn.currentWriteId;\r\n });\r\n var latestState = this.getLatestState_(path, setsToIgnore);\r\n var snapToSend = latestState;\r\n var latestHash = latestState.hash();\r\n for (var i = 0; i < queue.length; i++) {\r\n var txn = queue[i];\r\n util.assert(txn.status === TransactionStatus.RUN, 'tryToSendTransactionQueue_: items in queue should all be run.');\r\n txn.status = TransactionStatus.SENT;\r\n txn.retryCount++;\r\n var relativePath = Path.relativePath(path, txn.path);\r\n // If we've gotten to this point, the output snapshot must be defined.\r\n snapToSend = snapToSend.updateChild(relativePath /**@type {!Node} */, txn.currentOutputSnapshotRaw);\r\n }\r\n var dataToSend = snapToSend.val(true);\r\n var pathToSend = path;\r\n // Send the put.\r\n this.server_.put(pathToSend.toString(), dataToSend, function (status) {\r\n _this.log_('transaction put response', {\r\n path: pathToSend.toString(),\r\n status: status\r\n });\r\n var events = [];\r\n if (status === 'ok') {\r\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\r\n // the callback could trigger more transactions or sets.\r\n var callbacks = [];\r\n for (var i = 0; i < queue.length; i++) {\r\n queue[i].status = TransactionStatus.COMPLETED;\r\n events = events.concat(_this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId));\r\n if (queue[i].onComplete) {\r\n // We never unset the output snapshot, and given that this transaction is complete, it should be set\r\n var node = queue[i].currentOutputSnapshotResolved;\r\n var ref = new Reference(_this, queue[i].path);\r\n var snapshot = new DataSnapshot(node, ref, PRIORITY_INDEX);\r\n callbacks.push(queue[i].onComplete.bind(null, null, true, snapshot));\r\n }\r\n queue[i].unwatcher();\r\n }\r\n // Now remove the completed transactions.\r\n _this.pruneCompletedTransactionsBelowNode_(_this.transactionQueueTree_.subTree(path));\r\n // There may be pending transactions that we can now send.\r\n _this.sendReadyTransactions_();\r\n _this.eventQueue_.raiseEventsForChangedPath(path, events);\r\n // Finally, trigger onComplete callbacks.\r\n for (var i = 0; i < callbacks.length; i++) {\r\n exceptionGuard(callbacks[i]);\r\n }\r\n }\r\n else {\r\n // transactions are no longer sent. Update their status appropriately.\r\n if (status === 'datastale') {\r\n for (var i = 0; i < queue.length; i++) {\r\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT)\r\n queue[i].status = TransactionStatus.NEEDS_ABORT;\r\n else\r\n queue[i].status = TransactionStatus.RUN;\r\n }\r\n }\r\n else {\r\n warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);\r\n for (var i = 0; i < queue.length; i++) {\r\n queue[i].status = TransactionStatus.NEEDS_ABORT;\r\n queue[i].abortReason = status;\r\n }\r\n }\r\n _this.rerunTransactions_(path);\r\n }\r\n }, latestHash);\r\n};\r\n/**\r\n * Finds all transactions dependent on the data at changedPath and reruns them.\r\n *\r\n * Should be called any time cached data changes.\r\n *\r\n * Return the highest path that was affected by rerunning transactions. This is the path at which events need to\r\n * be raised for.\r\n *\r\n * @param {!Path} changedPath The path in mergedData that changed.\r\n * @return {!Path} The rootmost path that was affected by rerunning transactions.\r\n * @private\r\n */\r\nRepo.prototype.rerunTransactions_ = function (changedPath) {\r\n var rootMostTransactionNode = this.getAncestorTransactionNode_(changedPath);\r\n var path = rootMostTransactionNode.path();\r\n var queue = this.buildTransactionQueue_(rootMostTransactionNode);\r\n this.rerunTransactionQueue_(queue, path);\r\n return path;\r\n};\r\n/**\r\n * Does all the work of rerunning transactions (as well as cleans up aborted transactions and whatnot).\r\n *\r\n * @param {Array.} queue The queue of transactions to run.\r\n * @param {!Path} path The path the queue is for.\r\n * @private\r\n */\r\nRepo.prototype.rerunTransactionQueue_ = function (queue, path) {\r\n if (queue.length === 0) {\r\n return; // Nothing to do!\r\n }\r\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\r\n // the callback could trigger more transactions or sets.\r\n var callbacks = [];\r\n var events = [];\r\n // Ignore all of the sets we're going to re-run.\r\n var txnsToRerun = queue.filter(function (q) {\r\n return q.status === TransactionStatus.RUN;\r\n });\r\n var setsToIgnore = txnsToRerun.map(function (q) {\r\n return q.currentWriteId;\r\n });\r\n for (var i = 0; i < queue.length; i++) {\r\n var transaction = queue[i];\r\n var relativePath = Path.relativePath(path, transaction.path);\r\n var abortTransaction = false, abortReason = void 0;\r\n util.assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');\r\n if (transaction.status === TransactionStatus.NEEDS_ABORT) {\r\n abortTransaction = true;\r\n abortReason = transaction.abortReason;\r\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\r\n }\r\n else if (transaction.status === TransactionStatus.RUN) {\r\n if (transaction.retryCount >= Repo.MAX_TRANSACTION_RETRIES_) {\r\n abortTransaction = true;\r\n abortReason = 'maxretry';\r\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\r\n }\r\n else {\r\n // This code reruns a transaction\r\n var currentNode = this.getLatestState_(transaction.path, setsToIgnore);\r\n transaction.currentInputSnapshot = currentNode;\r\n var newData = queue[i].update(currentNode.val());\r\n if (newData !== undefined) {\r\n validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);\r\n var newDataNode = nodeFromJSON$1(newData);\r\n var hasExplicitPriority = typeof newData === 'object' &&\r\n newData != null &&\r\n util.contains(newData, '.priority');\r\n if (!hasExplicitPriority) {\r\n // Keep the old priority if there wasn't a priority explicitly specified.\r\n newDataNode = newDataNode.updatePriority(currentNode.getPriority());\r\n }\r\n var oldWriteId = transaction.currentWriteId;\r\n var serverValues = this.generateServerValues();\r\n var newNodeResolved = resolveDeferredValueSnapshot(newDataNode, serverValues);\r\n transaction.currentOutputSnapshotRaw = newDataNode;\r\n transaction.currentOutputSnapshotResolved = newNodeResolved;\r\n transaction.currentWriteId = this.getNextWriteId_();\r\n // Mutates setsToIgnore in place\r\n setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);\r\n events = events.concat(this.serverSyncTree_.applyUserOverwrite(transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));\r\n events = events.concat(this.serverSyncTree_.ackUserWrite(oldWriteId, true));\r\n }\r\n else {\r\n abortTransaction = true;\r\n abortReason = 'nodata';\r\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\r\n }\r\n }\r\n }\r\n this.eventQueue_.raiseEventsForChangedPath(path, events);\r\n events = [];\r\n if (abortTransaction) {\r\n // Abort.\r\n queue[i].status = TransactionStatus.COMPLETED;\r\n // Removing a listener can trigger pruning which can muck with mergedData/visibleData (as it prunes data).\r\n // So defer the unwatcher until we're done.\r\n (function (unwatcher) {\r\n setTimeout(unwatcher, Math.floor(0));\r\n })(queue[i].unwatcher);\r\n if (queue[i].onComplete) {\r\n if (abortReason === 'nodata') {\r\n var ref = new Reference(this, queue[i].path);\r\n // We set this field immediately, so it's safe to cast to an actual snapshot\r\n var lastInput /** @type {!Node} */ = queue[i].currentInputSnapshot;\r\n var snapshot = new DataSnapshot(lastInput, ref, PRIORITY_INDEX);\r\n callbacks.push(queue[i].onComplete.bind(null, null, false, snapshot));\r\n }\r\n else {\r\n callbacks.push(queue[i].onComplete.bind(null, new Error(abortReason), false, null));\r\n }\r\n }\r\n }\r\n }\r\n // Clean up completed transactions.\r\n this.pruneCompletedTransactionsBelowNode_(this.transactionQueueTree_);\r\n // Now fire callbacks, now that we're in a good, known state.\r\n for (var i = 0; i < callbacks.length; i++) {\r\n exceptionGuard(callbacks[i]);\r\n }\r\n // Try to send the transaction result to the server.\r\n this.sendReadyTransactions_();\r\n};\r\n/**\r\n * Returns the rootmost ancestor node of the specified path that has a pending transaction on it, or just returns\r\n * the node for the given path if there are no pending transactions on any ancestor.\r\n *\r\n * @param {!Path} path The location to start at.\r\n * @return {!Tree.>} The rootmost node with a transaction.\r\n * @private\r\n */\r\nRepo.prototype.getAncestorTransactionNode_ = function (path) {\r\n var front;\r\n // Start at the root and walk deeper into the tree towards path until we find a node with pending transactions.\r\n var transactionNode = this.transactionQueueTree_;\r\n while ((front = path.getFront()) !== null &&\r\n transactionNode.getValue() === null) {\r\n transactionNode = transactionNode.subTree(front);\r\n path = path.popFront();\r\n }\r\n return transactionNode;\r\n};\r\n/**\r\n * Builds the queue of all transactions at or below the specified transactionNode.\r\n *\r\n * @param {!Tree.>} transactionNode\r\n * @return {Array.} The generated queue.\r\n * @private\r\n */\r\nRepo.prototype.buildTransactionQueue_ = function (transactionNode) {\r\n // Walk any child transaction queues and aggregate them into a single queue.\r\n var transactionQueue = [];\r\n this.aggregateTransactionQueuesForNode_(transactionNode, transactionQueue);\r\n // Sort them by the order the transactions were created.\r\n transactionQueue.sort(function (a, b) {\r\n return a.order - b.order;\r\n });\r\n return transactionQueue;\r\n};\r\n/**\r\n * @param {!Tree.>} node\r\n * @param {Array.} queue\r\n * @private\r\n */\r\nRepo.prototype.aggregateTransactionQueuesForNode_ = function (node, queue) {\r\n var _this = this;\r\n var nodeQueue = node.getValue();\r\n if (nodeQueue !== null) {\r\n for (var i = 0; i < nodeQueue.length; i++) {\r\n queue.push(nodeQueue[i]);\r\n }\r\n }\r\n node.forEachChild(function (child) {\r\n _this.aggregateTransactionQueuesForNode_(child, queue);\r\n });\r\n};\r\n/**\r\n * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.\r\n *\r\n * @param {!Tree.>} node\r\n * @private\r\n */\r\nRepo.prototype.pruneCompletedTransactionsBelowNode_ = function (node) {\r\n var _this = this;\r\n var queue = node.getValue();\r\n if (queue) {\r\n var to = 0;\r\n for (var from = 0; from < queue.length; from++) {\r\n if (queue[from].status !== TransactionStatus.COMPLETED) {\r\n queue[to] = queue[from];\r\n to++;\r\n }\r\n }\r\n queue.length = to;\r\n node.setValue(queue.length > 0 ? queue : null);\r\n }\r\n node.forEachChild(function (childNode) {\r\n _this.pruneCompletedTransactionsBelowNode_(childNode);\r\n });\r\n};\r\n/**\r\n * Aborts all transactions on ancestors or descendants of the specified path. Called when doing a set() or update()\r\n * since we consider them incompatible with transactions.\r\n *\r\n * @param {!Path} path Path for which we want to abort related transactions.\r\n * @return {!Path}\r\n * @private\r\n */\r\nRepo.prototype.abortTransactions_ = function (path) {\r\n var _this = this;\r\n var affectedPath = this.getAncestorTransactionNode_(path).path();\r\n var transactionNode = this.transactionQueueTree_.subTree(path);\r\n transactionNode.forEachAncestor(function (node) {\r\n _this.abortTransactionsOnNode_(node);\r\n });\r\n this.abortTransactionsOnNode_(transactionNode);\r\n transactionNode.forEachDescendant(function (node) {\r\n _this.abortTransactionsOnNode_(node);\r\n });\r\n return affectedPath;\r\n};\r\n/**\r\n * Abort transactions stored in this transaction queue node.\r\n *\r\n * @param {!Tree.>} node Node to abort transactions for.\r\n * @private\r\n */\r\nRepo.prototype.abortTransactionsOnNode_ = function (node) {\r\n var queue = node.getValue();\r\n if (queue !== null) {\r\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\r\n // the callback could trigger more transactions or sets.\r\n var callbacks = [];\r\n // Go through queue. Any already-sent transactions must be marked for abort, while the unsent ones\r\n // can be immediately aborted and removed.\r\n var events = [];\r\n var lastSent = -1;\r\n for (var i = 0; i < queue.length; i++) {\r\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) ;\r\n else if (queue[i].status === TransactionStatus.SENT) {\r\n util.assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');\r\n lastSent = i;\r\n // Mark transaction for abort when it comes back.\r\n queue[i].status = TransactionStatus.SENT_NEEDS_ABORT;\r\n queue[i].abortReason = 'set';\r\n }\r\n else {\r\n util.assert(queue[i].status === TransactionStatus.RUN, 'Unexpected transaction status in abort');\r\n // We can abort it immediately.\r\n queue[i].unwatcher();\r\n events = events.concat(this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId, true));\r\n if (queue[i].onComplete) {\r\n var snapshot = null;\r\n callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, snapshot));\r\n }\r\n }\r\n }\r\n if (lastSent === -1) {\r\n // We're not waiting for any sent transactions. We can clear the queue.\r\n node.setValue(null);\r\n }\r\n else {\r\n // Remove the transactions we aborted.\r\n queue.length = lastSent + 1;\r\n }\r\n // Now fire the callbacks.\r\n this.eventQueue_.raiseEventsForChangedPath(node.path(), events);\r\n for (var i = 0; i < callbacks.length; i++) {\r\n exceptionGuard(callbacks[i]);\r\n }\r\n }\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** @const {string} */\r\nvar DATABASE_URL_OPTION = 'databaseURL';\r\nvar _staticInstance;\r\n/**\r\n * Creates and caches Repo instances.\r\n */\r\nvar RepoManager = /** @class */ (function () {\r\n function RepoManager() {\r\n /**\r\n * @private {!Object.>}\r\n */\r\n this.repos_ = {};\r\n /**\r\n * If true, new Repos will be created to use ReadonlyRestClient (for testing purposes).\r\n * @private {boolean}\r\n */\r\n this.useRestClient_ = false;\r\n }\r\n RepoManager.getInstance = function () {\r\n if (!_staticInstance) {\r\n _staticInstance = new RepoManager();\r\n }\r\n return _staticInstance;\r\n };\r\n // TODO(koss): Remove these functions unless used in tests?\r\n RepoManager.prototype.interrupt = function () {\r\n for (var appName in this.repos_) {\r\n for (var dbUrl in this.repos_[appName]) {\r\n this.repos_[appName][dbUrl].interrupt();\r\n }\r\n }\r\n };\r\n RepoManager.prototype.resume = function () {\r\n for (var appName in this.repos_) {\r\n for (var dbUrl in this.repos_[appName]) {\r\n this.repos_[appName][dbUrl].resume();\r\n }\r\n }\r\n };\r\n /**\r\n * This function should only ever be called to CREATE a new database instance.\r\n *\r\n * @param {!FirebaseApp} app\r\n * @return {!Database}\r\n */\r\n RepoManager.prototype.databaseFromApp = function (app, url) {\r\n var dbUrl = url || app.options[DATABASE_URL_OPTION];\r\n if (dbUrl === undefined) {\r\n fatal(\"Can't determine Firebase Database URL. Be sure to include \" +\r\n DATABASE_URL_OPTION +\r\n ' option when calling firebase.initializeApp().');\r\n }\r\n var parsedUrl = parseRepoInfo(dbUrl);\r\n var repoInfo = parsedUrl.repoInfo;\r\n validateUrl('Invalid Firebase Database URL', 1, parsedUrl);\r\n if (!parsedUrl.path.isEmpty()) {\r\n fatal('Database URL must point to the root of a Firebase Database ' +\r\n '(not including a child path).');\r\n }\r\n var repo = this.createRepo(repoInfo, app);\r\n return repo.database;\r\n };\r\n /**\r\n * Remove the repo and make sure it is disconnected.\r\n *\r\n * @param {!Repo} repo\r\n */\r\n RepoManager.prototype.deleteRepo = function (repo) {\r\n var appRepos = util.safeGet(this.repos_, repo.app.name);\r\n // This should never happen...\r\n if (!appRepos || util.safeGet(appRepos, repo.repoInfo_.toURLString()) !== repo) {\r\n fatal(\"Database \" + repo.app.name + \"(\" + repo.repoInfo_ + \") has already been deleted.\");\r\n }\r\n repo.interrupt();\r\n delete appRepos[repo.repoInfo_.toURLString()];\r\n };\r\n /**\r\n * Ensures a repo doesn't already exist and then creates one using the\r\n * provided app.\r\n *\r\n * @param {!RepoInfo} repoInfo The metadata about the Repo\r\n * @param {!FirebaseApp} app\r\n * @return {!Repo} The Repo object for the specified server / repoName.\r\n */\r\n RepoManager.prototype.createRepo = function (repoInfo, app) {\r\n var appRepos = util.safeGet(this.repos_, app.name);\r\n if (!appRepos) {\r\n appRepos = {};\r\n this.repos_[app.name] = appRepos;\r\n }\r\n var repo = util.safeGet(appRepos, repoInfo.toURLString());\r\n if (repo) {\r\n fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');\r\n }\r\n repo = new Repo(repoInfo, this.useRestClient_, app);\r\n appRepos[repoInfo.toURLString()] = repo;\r\n return repo;\r\n };\r\n /**\r\n * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.\r\n * @param {boolean} forceRestClient\r\n */\r\n RepoManager.prototype.forceRestClient = function (forceRestClient) {\r\n this.useRestClient_ = forceRestClient;\r\n };\r\n return RepoManager;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Class representing a firebase database.\r\n * @implements {FirebaseService}\r\n */\r\nvar Database = /** @class */ (function () {\r\n /**\r\n * The constructor should not be called by users of our public API.\r\n * @param {!Repo} repo_\r\n */\r\n function Database(repo_) {\r\n this.repo_ = repo_;\r\n if (!(repo_ instanceof Repo)) {\r\n fatal(\"Don't call new Database() directly - please use firebase.database().\");\r\n }\r\n /** @type {Reference} */\r\n this.root_ = new Reference(repo_, Path.Empty);\r\n this.INTERNAL = new DatabaseInternals(this);\r\n }\r\n Object.defineProperty(Database.prototype, \"app\", {\r\n get: function () {\r\n return this.repo_.app;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Database.prototype.ref = function (path) {\r\n this.checkDeleted_('ref');\r\n util.validateArgCount('database.ref', 0, 1, arguments.length);\r\n if (path instanceof Reference) {\r\n return this.refFromURL(path.toString());\r\n }\r\n return path !== undefined ? this.root_.child(path) : this.root_;\r\n };\r\n /**\r\n * Returns a reference to the root or the path specified in url.\r\n * We throw a exception if the url is not in the same domain as the\r\n * current repo.\r\n * @param {string} url\r\n * @return {!Reference} Firebase reference.\r\n */\r\n Database.prototype.refFromURL = function (url) {\r\n /** @const {string} */\r\n var apiName = 'database.refFromURL';\r\n this.checkDeleted_(apiName);\r\n util.validateArgCount(apiName, 1, 1, arguments.length);\r\n var parsedURL = parseRepoInfo(url);\r\n validateUrl(apiName, 1, parsedURL);\r\n var repoInfo = parsedURL.repoInfo;\r\n if (repoInfo.host !== this.repo_.repoInfo_.host) {\r\n fatal(apiName +\r\n ': Host name does not match the current database: ' +\r\n '(found ' +\r\n repoInfo.host +\r\n ' but expected ' +\r\n this.repo_.repoInfo_.host +\r\n ')');\r\n }\r\n return this.ref(parsedURL.path.toString());\r\n };\r\n /**\r\n * @param {string} apiName\r\n */\r\n Database.prototype.checkDeleted_ = function (apiName) {\r\n if (this.repo_ === null) {\r\n fatal('Cannot call ' + apiName + ' on a deleted database.');\r\n }\r\n };\r\n // Make individual repo go offline.\r\n Database.prototype.goOffline = function () {\r\n util.validateArgCount('database.goOffline', 0, 0, arguments.length);\r\n this.checkDeleted_('goOffline');\r\n this.repo_.interrupt();\r\n };\r\n Database.prototype.goOnline = function () {\r\n util.validateArgCount('database.goOnline', 0, 0, arguments.length);\r\n this.checkDeleted_('goOnline');\r\n this.repo_.resume();\r\n };\r\n Database.ServerValue = {\r\n TIMESTAMP: {\r\n '.sv': 'timestamp'\r\n }\r\n };\r\n return Database;\r\n}());\r\nvar DatabaseInternals = /** @class */ (function () {\r\n /** @param {!Database} database */\r\n function DatabaseInternals(database) {\r\n this.database = database;\r\n }\r\n /** @return {Promise} */\r\n DatabaseInternals.prototype.delete = function () {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n return tslib_1.__generator(this, function (_a) {\r\n this.database.checkDeleted_('delete');\r\n RepoManager.getInstance().deleteRepo(this.database.repo_);\r\n this.database.repo_ = null;\r\n this.database.root_ = null;\r\n this.database.INTERNAL = null;\r\n this.database = null;\r\n return [2 /*return*/];\r\n });\r\n });\r\n };\r\n return DatabaseInternals;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * INTERNAL methods for internal-use only (tests, etc.).\r\n *\r\n * Customers shouldn't use these or else should be aware that they could break at any time.\r\n *\r\n * @const\r\n */\r\nvar forceLongPolling = function () {\r\n WebSocketConnection.forceDisallow();\r\n BrowserPollConnection.forceAllow();\r\n};\r\nvar forceWebSockets = function () {\r\n BrowserPollConnection.forceDisallow();\r\n};\r\n/* Used by App Manager */\r\nvar isWebSocketsAvailable = function () {\r\n return WebSocketConnection['isAvailable']();\r\n};\r\nvar setSecurityDebugCallback = function (ref, callback) {\r\n ref.repo.persistentConnection_.securityDebugCallback_ = callback;\r\n};\r\nvar stats = function (ref, showDelta) {\r\n ref.repo.stats(showDelta);\r\n};\r\nvar statsIncrementCounter = function (ref, metric) {\r\n ref.repo.statsIncrementCounter(metric);\r\n};\r\nvar dataUpdateCount = function (ref) {\r\n return ref.repo.dataUpdateCount;\r\n};\r\nvar interceptServerData = function (ref, callback) {\r\n return ref.repo.interceptServerData_(callback);\r\n};\n\nvar INTERNAL = /*#__PURE__*/Object.freeze({\n forceLongPolling: forceLongPolling,\n forceWebSockets: forceWebSockets,\n isWebSocketsAvailable: isWebSocketsAvailable,\n setSecurityDebugCallback: setSecurityDebugCallback,\n stats: stats,\n statsIncrementCounter: statsIncrementCounter,\n dataUpdateCount: dataUpdateCount,\n interceptServerData: interceptServerData\n});\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar DataConnection = PersistentConnection;\r\n/**\r\n * @param {!string} pathString\r\n * @param {function(*)} onComplete\r\n */\r\nPersistentConnection.prototype.simpleListen = function (pathString, onComplete) {\r\n this.sendRequest('q', { p: pathString }, onComplete);\r\n};\r\n/**\r\n * @param {*} data\r\n * @param {function(*)} onEcho\r\n */\r\nPersistentConnection.prototype.echo = function (data, onEcho) {\r\n this.sendRequest('echo', { d: data }, onEcho);\r\n};\r\n// RealTimeConnection properties that we use in tests.\r\nvar RealTimeConnection = Connection;\r\n/**\r\n * @param {function(): string} newHash\r\n * @return {function()}\r\n */\r\nvar hijackHash = function (newHash) {\r\n var oldPut = PersistentConnection.prototype.put;\r\n PersistentConnection.prototype.put = function (pathString, data, opt_onComplete, opt_hash) {\r\n if (opt_hash !== undefined) {\r\n opt_hash = newHash();\r\n }\r\n oldPut.call(this, pathString, data, opt_onComplete, opt_hash);\r\n };\r\n return function () {\r\n PersistentConnection.prototype.put = oldPut;\r\n };\r\n};\r\n/**\r\n * @type {function(new:RepoInfo, !string, boolean, !string, boolean): undefined}\r\n */\r\nvar ConnectionTarget = RepoInfo;\r\n/**\r\n * @param {!Query} query\r\n * @return {!string}\r\n */\r\nvar queryIdentifier = function (query) {\r\n return query.queryIdentifier();\r\n};\r\n/**\r\n * @param {!Query} firebaseRef\r\n * @return {!Object}\r\n */\r\nvar listens = function (firebaseRef) {\r\n return firebaseRef.repo.persistentConnection_.listens_;\r\n};\r\n/**\r\n * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.\r\n *\r\n * @param {boolean} forceRestClient\r\n */\r\nvar forceRestClient = function (forceRestClient) {\r\n RepoManager.getInstance().forceRestClient(forceRestClient);\r\n};\n\nvar TEST_ACCESS = /*#__PURE__*/Object.freeze({\n DataConnection: DataConnection,\n RealTimeConnection: RealTimeConnection,\n hijackHash: hijackHash,\n ConnectionTarget: ConnectionTarget,\n queryIdentifier: queryIdentifier,\n listens: listens,\n forceRestClient: forceRestClient\n});\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar ServerValue = Database.ServerValue;\r\nfunction registerDatabase(instance) {\r\n // Register the Database Service with the 'firebase' namespace.\r\n var namespace = instance.INTERNAL.registerService('database', function (app, unused, url) { return RepoManager.getInstance().databaseFromApp(app, url); }, \r\n // firebase.database namespace properties\r\n {\r\n Reference: Reference,\r\n Query: Query,\r\n Database: Database,\r\n DataSnapshot: DataSnapshot,\r\n enableLogging: enableLogging,\r\n INTERNAL: INTERNAL,\r\n ServerValue: ServerValue,\r\n TEST_ACCESS: TEST_ACCESS\r\n }, null, true);\r\n if (util.isNodeSdk()) {\r\n module.exports = namespace;\r\n }\r\n}\r\nregisterDatabase(firebase);\n\nexports.DataSnapshot = DataSnapshot;\nexports.Database = Database;\nexports.OnDisconnect = OnDisconnect;\nexports.Query = Query;\nexports.Reference = Reference;\nexports.ServerValue = ServerValue;\nexports.enableLogging = enableLogging;\nexports.registerDatabase = registerDatabase;\n//# sourceMappingURL=index.cjs.js.map\n","var render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',[_c('vx-card',{staticClass:\"mt-3\"},[_c('vs-table',{attrs:{\"sst\":true,\"data\":_vm.vesselGroups,\"pagination\":\"\",\"max-items\":\"10\",\"search\":\"\"},on:{\"search\":_vm.handleSearch,\"sort\":_vm.handleSort,\"change-page\":_vm.handleChangePage},scopedSlots:_vm._u([{key:\"default\",fn:function(ref){\nvar data = ref.data;\nreturn _vm._l((data),function(tr,indextr){return _c('vs-tr',{key:indextr,attrs:{\"data\":tr}},[_c('vs-td',{attrs:{\"data\":data[indextr].id}},[_vm._v(_vm._s(indextr +1))]),_c('vs-td',{attrs:{\"data\":data[indextr].name}},[_vm._v(_vm._s(data[indextr].name))]),_c('vs-td',{attrs:{\"data\":data[indextr].icon_type}},[_vm._v(_vm._s(data[indextr].icon_type))])],1)})}}]),model:{value:(_vm.selected),callback:function ($$v) {_vm.selected=$$v},expression:\"selected\"}},[_c('template',{slot:\"header\"},[_c('vs-button',{staticStyle:{\"margin-left\":\"5px\",\"margin-top\":\"5px\"},attrs:{\"icon-pack\":\"feather\",\"icon\":\"icon-plus\"},on:{\"click\":function($event){_vm.popupActive=true}}},[_vm._v(\"Add vessel group\")])],1),_c('template',{slot:\"thead\"},[_c('vs-th',{attrs:{\"sort-key\":\"id\"}},[_vm._v(\"No.\")]),_c('vs-th',{attrs:{\"sort-key\":\"name\"}},[_vm._v(\"Name\")]),_c('vs-th',{attrs:{\"sort-key\":\"icon_type\"}},[_vm._v(\"Icon type\")])],1)],2),(_vm.selected!='')?_c('vs-button',{staticClass:\"m-3\",attrs:{\"color\":\"danger\"},on:{\"click\":function($event){return _vm.openConfirm()}}},[_vm._v(\"Delete\")]):_vm._e(),(_vm.selected!='')?_c('vs-button',{staticClass:\"m-3\",attrs:{\"color\":\"warning\"},on:{\"click\":function($event){return _vm.edit()}}},[_vm._v(\"Edit\")]):_vm._e()],1),_c('div',[_c('div',{staticClass:\"demo-alignment\"},[_c('vs-popup',{attrs:{\"classContent\":\"popup-example\",\"title\":\"Add Vessel Groups\",\"active\":_vm.popupActive},on:{\"update:active\":function($event){_vm.popupActive=$event}}},[_c('vs-input',{staticClass:\"w-full mb-3\",attrs:{\"label-placeholder\":\"Name\",\"placeholder\":\"Name\"},model:{value:(_vm.theVesselGroups.name),callback:function ($$v) {_vm.$set(_vm.theVesselGroups, \"name\", $$v)},expression:\"theVesselGroups.name\"}}),_c('vs-textarea',{staticClass:\"w-full mb-3\",staticStyle:{\"background-color\":\"white\",\"border\":\"1px solid rgba(0, 0, 0, 0.2)\"},attrs:{\"label-placeholder\":\"MMSI_LIST\",\"placeholder\":\"MMSI_LIST\"},model:{value:(_vm.theVesselGroups.mmsi_list),callback:function ($$v) {_vm.$set(_vm.theVesselGroups, \"mmsi_list\", $$v)},expression:\"theVesselGroups.mmsi_list\"}}),_c('vs-input',{staticClass:\"w-full mb-3\",attrs:{\"label-placeholder\":\"Icon Type\",\"placeholder\":\"Icon Type\"},model:{value:(_vm.theVesselGroups.icon_type),callback:function ($$v) {_vm.$set(_vm.theVesselGroups, \"icon_type\", $$v)},expression:\"theVesselGroups.icon_type\"}}),_c('vs-button',{staticClass:\"w-full\",attrs:{\"color\":\"primary\",\"type\":\"filled\"},on:{\"click\":function($event){return _vm.insert()}}},[_vm._v(\"Save\")])],1)],1)]),_c('div',[_c('div',{staticClass:\"demo-alignment\"},[_c('vs-popup',{attrs:{\"active\":_vm.popupActive2,\"classContent\":\"popup-example\",\"title\":\"Edit Vessel Groups\"},on:{\"update:active\":function($event){_vm.popupActive2=$event}}},[_c('vs-input',{staticClass:\"w-full mb-3\",attrs:{\"label-placeholder\":\"Name\",\"placeholder\":\"Name\"},model:{value:(_vm.editVesselGroup.name),callback:function ($$v) {_vm.$set(_vm.editVesselGroup, \"name\", $$v)},expression:\"editVesselGroup.name\"}}),_c('vs-textarea',{staticClass:\"w-full mb-3\",staticStyle:{\"background-color\":\"white\",\"border\":\"1px solid rgba(0, 0, 0, 0.2)\"},attrs:{\"label-placeholder\":\"MMSI_LIST\",\"placeholder\":\"MMSI_LIST\"},model:{value:(_vm.editVesselGroup.mmsi_list),callback:function ($$v) {_vm.$set(_vm.editVesselGroup, \"mmsi_list\", $$v)},expression:\"editVesselGroup.mmsi_list\"}}),_c('vs-input',{staticClass:\"w-full mb-3\",attrs:{\"label-placeholder\":\"Icon Type\",\"placeholder\":\"Icon Type\"},model:{value:(_vm.editVesselGroup.icon_type),callback:function ($$v) {_vm.$set(_vm.editVesselGroup, \"icon_type\", $$v)},expression:\"editVesselGroup.icon_type\"}}),_c('vs-button',{staticClass:\"w-full\",attrs:{\"color\":\"primary\",\"type\":\"filled\"},on:{\"click\":function($event){return _vm.update()}}},[_vm._v(\"update\")])],1)],1)])],1)}\nvar staticRenderFns = []\n\nexport { render, staticRenderFns }","\n\n","import mod from \"-!../../../node_modules/cache-loader/dist/cjs.js??ref--12-0!../../../node_modules/thread-loader/dist/cjs.js!../../../node_modules/@vue/cli-plugin-babel/node_modules/babel-loader/lib/index.js!../../../node_modules/cache-loader/dist/cjs.js??ref--0-0!../../../node_modules/vue-loader/lib/index.js??vue-loader-options!./VesselGroup.vue?vue&type=script&lang=js\"; export default mod; export * from \"-!../../../node_modules/cache-loader/dist/cjs.js??ref--12-0!../../../node_modules/thread-loader/dist/cjs.js!../../../node_modules/@vue/cli-plugin-babel/node_modules/babel-loader/lib/index.js!../../../node_modules/cache-loader/dist/cjs.js??ref--0-0!../../../node_modules/vue-loader/lib/index.js??vue-loader-options!./VesselGroup.vue?vue&type=script&lang=js\"","import { render, staticRenderFns } from \"./VesselGroup.vue?vue&type=template&id=01e6304c\"\nimport script from \"./VesselGroup.vue?vue&type=script&lang=js\"\nexport * from \"./VesselGroup.vue?vue&type=script&lang=js\"\n\n\n/* normalize component */\nimport normalizer from \"!../../../node_modules/vue-loader/lib/runtime/componentNormalizer.js\"\nvar component = normalizer(\n script,\n render,\n staticRenderFns,\n false,\n null,\n null,\n null\n \n)\n\nexport default component.exports","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nfunction _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }\n\nvar firebase = _interopDefault(require('@firebase/app'));\nvar tslib_1 = require('tslib');\nvar util = require('@firebase/util');\nrequire('@firebase/installations');\nvar logger$1 = require('@firebase/logger');\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar SDK_VERSION = '0.2.1';\r\n/** The prefix for start User Timing marks used for creating Traces. */\r\nvar TRACE_START_MARK_PREFIX = 'FB-PERF-TRACE-START';\r\n/** The prefix for stop User Timing marks used for creating Traces. */\r\nvar TRACE_STOP_MARK_PREFIX = 'FB-PERF-TRACE-STOP';\r\n/** The prefix for User Timing measure used for creating Traces. */\r\nvar TRACE_MEASURE_PREFIX = 'FB-PERF-TRACE-MEASURE';\r\n/** The prefix for out of the box page load Trace name. */\r\nvar OOB_TRACE_PAGE_LOAD_PREFIX = '_wt_';\r\nvar FIRST_PAINT_COUNTER_NAME = '_fp';\r\nvar FIRST_CONTENTFUL_PAINT_COUNTER_NAME = '_fcp';\r\nvar FIRST_INPUT_DELAY_COUNTER_NAME = '_fid';\r\nvar CONFIG_LOCAL_STORAGE_KEY = '@firebase/performance/config';\r\nvar CONFIG_EXPIRY_LOCAL_STORAGE_KEY = '@firebase/performance/configexpire';\r\nvar SERVICE = 'performance';\r\nvar SERVICE_NAME = 'Performance';\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar _a;\r\nvar ERROR_DESCRIPTION_MAP = (_a = {},\r\n _a[\"trace started\" /* TRACE_STARTED_BEFORE */] = 'Trace {$traceName} was started before.',\r\n _a[\"trace stopped\" /* TRACE_STOPPED_BEFORE */] = 'Trace {$traceName} is not running.',\r\n _a[\"no window\" /* NO_WINDOW */] = 'Window is not available.',\r\n _a[\"no app id\" /* NO_APP_ID */] = 'App id is not available.',\r\n _a[\"no project id\" /* NO_PROJECT_ID */] = 'Project id is not available.',\r\n _a[\"no api key\" /* NO_API_KEY */] = 'Api key is not available.',\r\n _a[\"invalid cc log\" /* INVALID_CC_LOG */] = 'Attempted to queue invalid cc event',\r\n _a[\"FB not default\" /* FB_NOT_DEFAULT */] = 'Performance can only start when Firebase app instance is the default one.',\r\n _a[\"RC response not ok\" /* RC_NOT_OK */] = 'RC response is not ok',\r\n _a);\r\nvar ERROR_FACTORY = new util.ErrorFactory(SERVICE, SERVICE_NAME, ERROR_DESCRIPTION_MAP);\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar apiInstance;\r\nvar windowInstance;\r\n/**\r\n * This class holds a reference to various browser related objects injected by set methods.\r\n */\r\nvar Api = /** @class */ (function () {\r\n function Api(window) {\r\n if (!window) {\r\n throw ERROR_FACTORY.create(\"no window\" /* NO_WINDOW */);\r\n }\r\n this.performance = window.performance;\r\n this.PerformanceObserver = window.PerformanceObserver;\r\n this.windowLocation = window.location;\r\n this.navigator = window.navigator;\r\n this.document = window.document;\r\n this.localStorage = window.localStorage;\r\n if (window.perfMetrics && window.perfMetrics.onFirstInputDelay) {\r\n this.onFirstInputDelay = window.perfMetrics.onFirstInputDelay;\r\n }\r\n }\r\n Api.prototype.getUrl = function () {\r\n // Do not capture the string query part of url.\r\n return this.windowLocation.href.split('?')[0];\r\n };\r\n Api.prototype.mark = function (name) {\r\n if (!this.performance || !this.performance.mark)\r\n return;\r\n this.performance.mark(name);\r\n };\r\n Api.prototype.measure = function (measureName, mark1, mark2) {\r\n if (!this.performance || !this.performance.measure)\r\n return;\r\n this.performance.measure(measureName, mark1, mark2);\r\n };\r\n Api.prototype.getEntriesByType = function (type) {\r\n if (!this.performance || !this.performance.getEntriesByType)\r\n return [];\r\n return this.performance.getEntriesByType(type);\r\n };\r\n Api.prototype.getEntriesByName = function (name) {\r\n if (!this.performance || !this.performance.getEntriesByName)\r\n return [];\r\n return this.performance.getEntriesByName(name);\r\n };\r\n Api.prototype.getTimeOrigin = function () {\r\n // Polyfill the time origin with performance.timing.navigationStart.\r\n return (this.performance &&\r\n (this.performance.timeOrigin || this.performance.timing.navigationStart));\r\n };\r\n Api.prototype.setupObserver = function (entryType, callback) {\r\n if (!this.PerformanceObserver)\r\n return;\r\n var observer = new this.PerformanceObserver(function (list) {\r\n for (var _i = 0, _a = list.getEntries(); _i < _a.length; _i++) {\r\n var entry = _a[_i];\r\n // `entry` is a PerformanceEntry instance.\r\n callback(entry);\r\n }\r\n });\r\n // Start observing the entry types you care about.\r\n observer.observe({ entryTypes: [entryType] });\r\n };\r\n Api.getInstance = function () {\r\n if (apiInstance === undefined) {\r\n apiInstance = new Api(windowInstance);\r\n }\r\n return apiInstance;\r\n };\r\n return Api;\r\n}());\r\nfunction setupApi(window) {\r\n windowInstance = window;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar settingsServiceInstance;\r\nvar SettingsService = /** @class */ (function () {\r\n function SettingsService() {\r\n // The variable which controls logging of automatic traces and HTTP/S network monitoring.\r\n this.instrumentationEnabled = true;\r\n // The variable which controls logging of custom traces.\r\n this.dataCollectionEnabled = true;\r\n // Configuration flags set through remote config.\r\n this.loggingEnabled = false;\r\n // Sampling rate between 0 and 1.\r\n this.tracesSamplingRate = 1;\r\n this.networkRequestsSamplingRate = 1;\r\n // Address of logging service.\r\n this.logEndPointUrl = 'https://firebaselogging.googleapis.com/v0cc/log?format=json_proto';\r\n this.logSource = 462;\r\n // Flags which control per session logging of traces and network requests.\r\n this.logTraceAfterSampling = false;\r\n this.logNetworkAfterSampling = false;\r\n // TTL of config retrieved from remote config in hours.\r\n this.configTimeToLive = 12;\r\n }\r\n SettingsService.prototype.getAppId = function () {\r\n var appId = this.firebaseAppInstance &&\r\n this.firebaseAppInstance.options &&\r\n this.firebaseAppInstance.options.appId;\r\n if (!appId) {\r\n throw ERROR_FACTORY.create(\"no app id\" /* NO_APP_ID */);\r\n }\r\n return appId;\r\n };\r\n SettingsService.prototype.getProjectId = function () {\r\n var projectId = this.firebaseAppInstance &&\r\n this.firebaseAppInstance.options &&\r\n this.firebaseAppInstance.options.projectId;\r\n if (!projectId) {\r\n throw ERROR_FACTORY.create(\"no project id\" /* NO_PROJECT_ID */);\r\n }\r\n return projectId;\r\n };\r\n SettingsService.prototype.getApiKey = function () {\r\n var apiKey = this.firebaseAppInstance &&\r\n this.firebaseAppInstance.options &&\r\n this.firebaseAppInstance.options.apiKey;\r\n if (!apiKey) {\r\n throw ERROR_FACTORY.create(\"no api key\" /* NO_API_KEY */);\r\n }\r\n return apiKey;\r\n };\r\n SettingsService.getInstance = function () {\r\n if (settingsServiceInstance === undefined) {\r\n settingsServiceInstance = new SettingsService();\r\n }\r\n return settingsServiceInstance;\r\n };\r\n return SettingsService;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar iid;\r\nfunction getIidPromise() {\r\n var iidPromise = SettingsService.getInstance()\r\n .firebaseAppInstance.installations()\r\n .getId();\r\n iidPromise.then(function (iidVal) {\r\n iid = iidVal;\r\n });\r\n return iidPromise;\r\n}\r\n// This method should be used after the iid is retrieved by getIidPromise method.\r\nfunction getIid() {\r\n return iid;\r\n}\r\nfunction getAuthTokenPromise() {\r\n var authTokenPromise = SettingsService.getInstance()\r\n .firebaseAppInstance.installations()\r\n .getToken();\r\n authTokenPromise.then(function (authTokenVal) {\r\n });\r\n return authTokenPromise;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar VisibilityState;\r\n(function (VisibilityState) {\r\n VisibilityState[VisibilityState[\"UNKNOWN\"] = 0] = \"UNKNOWN\";\r\n VisibilityState[VisibilityState[\"VISIBLE\"] = 1] = \"VISIBLE\";\r\n VisibilityState[VisibilityState[\"HIDDEN\"] = 2] = \"HIDDEN\";\r\n VisibilityState[VisibilityState[\"PRERENDER\"] = 3] = \"PRERENDER\";\r\n VisibilityState[VisibilityState[\"UNLOADED\"] = 4] = \"UNLOADED\";\r\n})(VisibilityState || (VisibilityState = {}));\r\nfunction getServiceWorkerStatus() {\r\n var navigator = Api.getInstance().navigator;\r\n if ('serviceWorker' in navigator) {\r\n if (navigator.serviceWorker.controller) {\r\n return 2 /* CONTROLLED */;\r\n }\r\n else {\r\n return 3 /* UNCONTROLLED */;\r\n }\r\n }\r\n else {\r\n return 1 /* UNSUPPORTED */;\r\n }\r\n}\r\nfunction getVisibilityState() {\r\n var document = Api.getInstance().document;\r\n var visibilityState = document.visibilityState;\r\n switch (visibilityState) {\r\n case 'visible':\r\n return VisibilityState.VISIBLE;\r\n case 'hidden':\r\n return VisibilityState.HIDDEN;\r\n case 'prerender':\r\n return VisibilityState.PRERENDER;\r\n default:\r\n return VisibilityState.UNKNOWN;\r\n }\r\n}\r\nfunction getEffectiveConnectionType() {\r\n var navigator = Api.getInstance().navigator;\r\n var navigatorConnection = navigator.connection;\r\n var effectiveType = navigatorConnection && navigatorConnection.effectiveType;\r\n switch (effectiveType) {\r\n case 'slow-2g':\r\n return 1 /* CONNECTION_SLOW_2G */;\r\n case '2g':\r\n return 2 /* CONNECTION_2G */;\r\n case '3g':\r\n return 3 /* CONNECTION_3G */;\r\n case '4g':\r\n return 4 /* CONNECTION_4G */;\r\n default:\r\n return 0 /* UNKNOWN */;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar consoleLogger = new logger$1.Logger(SERVICE_NAME);\r\nconsoleLogger.logLevel = logger$1.LogLevel.INFO;\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar REMOTE_CONFIG_SDK_VERSION = '0.0.1';\r\n// These values will be used if the remote config object is successfully\r\n// retrieved, but the template does not have these fields.\r\nvar SECONDARY_CONFIGS = {\r\n loggingEnabled: true\r\n};\r\nvar FIS_AUTH_PREFIX = 'FIREBASE_INSTALLATIONS_AUTH';\r\nfunction getConfig(iid) {\r\n var config = getStoredConfig();\r\n if (config) {\r\n processConfig(config);\r\n return Promise.resolve();\r\n }\r\n return getRemoteConfig(iid)\r\n .then(function (config) { return processConfig(config); })\r\n .then(function (config) { return storeConfig(config); }, \r\n /** Do nothing for error, use defaults set in settings service. */ function () { });\r\n}\r\nfunction getStoredConfig() {\r\n var localStorage = Api.getInstance().localStorage;\r\n var expiryString = localStorage.getItem(CONFIG_EXPIRY_LOCAL_STORAGE_KEY);\r\n if (!expiryString || !configValid(expiryString))\r\n return;\r\n var configStringified = localStorage.getItem(CONFIG_LOCAL_STORAGE_KEY);\r\n if (!configStringified)\r\n return;\r\n try {\r\n var configResponse = JSON.parse(configStringified);\r\n return configResponse;\r\n }\r\n catch (_a) {\r\n return;\r\n }\r\n}\r\nfunction storeConfig(config) {\r\n if (!config)\r\n return;\r\n var localStorage = Api.getInstance().localStorage;\r\n localStorage.setItem(CONFIG_LOCAL_STORAGE_KEY, JSON.stringify(config));\r\n localStorage.setItem(CONFIG_EXPIRY_LOCAL_STORAGE_KEY, String(Date.now() +\r\n SettingsService.getInstance().configTimeToLive * 60 * 60 * 1000));\r\n}\r\nvar COULD_NOT_GET_CONFIG_MSG = 'Could not fetch config, will use default configs';\r\nfunction getRemoteConfig(iid) {\r\n // Perf needs auth token only to retrieve remote config.\r\n return getAuthTokenPromise()\r\n .then(function (authToken) {\r\n var projectId = SettingsService.getInstance().getProjectId();\r\n var configEndPoint = \"https://firebaseremoteconfig.googleapis.com/v1/projects/\" + projectId + \"/namespaces/fireperf:fetch?key=\" + SettingsService.getInstance().getApiKey();\r\n var request = new Request(configEndPoint, {\r\n method: 'POST',\r\n headers: {\r\n Authorization: FIS_AUTH_PREFIX + \" \" + authToken\r\n },\r\n body: JSON.stringify({\r\n app_instance_id: iid,\r\n app_instance_id_token: authToken,\r\n app_id: SettingsService.getInstance().getAppId(),\r\n app_version: SDK_VERSION,\r\n sdk_version: REMOTE_CONFIG_SDK_VERSION\r\n })\r\n });\r\n return fetch(request).then(function (response) {\r\n if (response.ok) {\r\n return response.json();\r\n }\r\n // In case response is not ok. This will be caught by catch.\r\n throw ERROR_FACTORY.create(\"RC response not ok\" /* RC_NOT_OK */);\r\n });\r\n })\r\n .catch(function () {\r\n consoleLogger.info(COULD_NOT_GET_CONFIG_MSG);\r\n return undefined;\r\n });\r\n}\r\n/**\r\n * Processes config coming either from calling RC or from local storage.\r\n * This method only runs if call is successful or config in storage\r\n * is valie.\r\n */\r\nfunction processConfig(config) {\r\n if (!config)\r\n return config;\r\n var settingsServiceInstance = SettingsService.getInstance();\r\n var entries = config.entries || {};\r\n if (entries.fpr_enabled !== undefined) {\r\n // TODO: Change the assignment of loggingEnabled once the received type is known.\r\n settingsServiceInstance.loggingEnabled =\r\n String(entries.fpr_enabled) === 'true';\r\n }\r\n else {\r\n // Config retrieved successfully, but there is no fpr_enabled in template.\r\n // Use secondary configs value.\r\n settingsServiceInstance.loggingEnabled = SECONDARY_CONFIGS.loggingEnabled;\r\n }\r\n if (entries.fpr_log_source) {\r\n settingsServiceInstance.logSource = Number(entries.fpr_log_source);\r\n }\r\n if (entries.fpr_log_endpoint_url) {\r\n settingsServiceInstance.logEndPointUrl = entries.fpr_log_endpoint_url;\r\n }\r\n if (entries.fpr_vc_network_request_sampling_rate !== undefined) {\r\n settingsServiceInstance.networkRequestsSamplingRate = Number(entries.fpr_vc_network_request_sampling_rate);\r\n }\r\n if (entries.fpr_vc_trace_sampling_rate !== undefined) {\r\n settingsServiceInstance.tracesSamplingRate = Number(entries.fpr_vc_trace_sampling_rate);\r\n }\r\n // Set the per session trace and network logging flags.\r\n settingsServiceInstance.logTraceAfterSampling = shouldLogAfterSampling(settingsServiceInstance.tracesSamplingRate);\r\n settingsServiceInstance.logNetworkAfterSampling = shouldLogAfterSampling(settingsServiceInstance.networkRequestsSamplingRate);\r\n return config;\r\n}\r\nfunction configValid(expiry) {\r\n return Number(expiry) > Date.now();\r\n}\r\nfunction shouldLogAfterSampling(samplingRate) {\r\n return Math.random() <= samplingRate;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar initializationStatus = 1 /* notInitialized */;\r\nvar initializationPromise;\r\nfunction getInitializationPromise() {\r\n initializationStatus = 2 /* initializationPending */;\r\n initializationPromise = initializationPromise || initializePerf();\r\n return initializationPromise;\r\n}\r\nfunction isPerfInitialized() {\r\n return initializationStatus === 3 /* initialized */;\r\n}\r\nfunction initializePerf() {\r\n return getDocumentReadyComplete()\r\n .then(function () { return getIidPromise(); })\r\n .then(function (iid) { return getConfig(iid); })\r\n .then(function () { return changeInitializationStatus(); }, function () { return changeInitializationStatus(); });\r\n}\r\n/**\r\n * Returns a promise which resolves whenever the document readystate is complete or\r\n * immediately if it is called after page load complete.\r\n */\r\nfunction getDocumentReadyComplete() {\r\n var document = Api.getInstance().document;\r\n return new Promise(function (resolve) {\r\n if (document && document.readyState !== 'complete') {\r\n var handler_1 = function () {\r\n if (document.readyState === 'complete') {\r\n document.removeEventListener('readystatechange', handler_1);\r\n resolve();\r\n }\r\n };\r\n document.addEventListener('readystatechange', handler_1);\r\n }\r\n else {\r\n resolve();\r\n }\r\n });\r\n}\r\nfunction changeInitializationStatus() {\r\n initializationStatus = 3 /* initialized */;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar DEFAULT_SEND_INTERVAL_MS = 10 * 1000;\r\nvar INITIAL_SEND_TIME_DELAY_MS = 5.5 * 1000;\r\n// If end point does not work, the call will be tried for these many times.\r\nvar DEFAULT_REMAINING_TRIES = 3;\r\nvar remainingTries = DEFAULT_REMAINING_TRIES;\r\nvar queue = [];\r\nfunction processQueue(timeOffset) {\r\n setTimeout(function () {\r\n // If there is no remainingTries left, stop retrying.\r\n if (remainingTries === 0) {\r\n return;\r\n }\r\n // If there are no events to process, wait for DEFAULT_SEND_INTERVAL_MS and try again.\r\n if (!queue.length) {\r\n return processQueue(DEFAULT_SEND_INTERVAL_MS);\r\n }\r\n // Capture a snapshot of the queue and empty the \"official queue\".\r\n var staged = queue.slice();\r\n queue = [];\r\n // We will pass the JSON serialized event to the backend.\r\n var log_event = staged.map(function (evt) { return ({\r\n source_extension_json: evt.message,\r\n event_time_ms: String(evt.eventTime)\r\n }); });\r\n var data = {\r\n request_time_ms: String(Date.now()),\r\n client_info: {\r\n client_type: 1,\r\n js_client_info: {}\r\n },\r\n log_source: SettingsService.getInstance().logSource,\r\n log_event: log_event\r\n };\r\n fetch(SettingsService.getInstance().logEndPointUrl, {\r\n method: 'POST',\r\n body: JSON.stringify(data)\r\n })\r\n .then(function (res) {\r\n if (!res.ok) {\r\n consoleLogger.info('Call to Firebase backend failed.');\r\n }\r\n return res.json();\r\n })\r\n .then(function (res) {\r\n // Find the next call wait time from the response.\r\n var requestOffset = Math.max(DEFAULT_SEND_INTERVAL_MS, parseInt(res.next_request_wait_millis, 10));\r\n remainingTries = DEFAULT_REMAINING_TRIES;\r\n // Schedule the next process.\r\n processQueue(requestOffset);\r\n })\r\n .catch(function () {\r\n /**\r\n * If the request fails for some reason, add the events that were attempted\r\n * back to the primary queue to retry later.\r\n */\r\n queue = staged.concat(queue);\r\n remainingTries--;\r\n consoleLogger.info(\"Tries left: \" + remainingTries + \".\");\r\n processQueue(DEFAULT_SEND_INTERVAL_MS);\r\n });\r\n }, timeOffset);\r\n}\r\nprocessQueue(INITIAL_SEND_TIME_DELAY_MS);\r\nfunction addToQueue(evt) {\r\n if (!evt.eventTime || !evt.message) {\r\n throw ERROR_FACTORY.create(\"invalid cc log\" /* INVALID_CC_LOG */);\r\n }\r\n // Add the new event to the queue.\r\n queue = queue.concat([evt]);\r\n}\r\n/** Log handler for cc service to send the performance logs to the server. */\r\nfunction ccHandler(serializer) {\r\n // The underscores for loggerInstance and level parameters are added to avoid the\r\n // noUnusedParameters related error.\r\n return function (_loggerInstance, _level) {\r\n var args = [];\r\n for (var _i = 2; _i < arguments.length; _i++) {\r\n args[_i - 2] = arguments[_i];\r\n }\r\n var message = serializer.apply(void 0, args);\r\n addToQueue({\r\n message: message,\r\n eventTime: Date.now()\r\n });\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar logger;\r\n// This method is not called before initialization.\r\nfunction getLogger() {\r\n if (logger)\r\n return logger;\r\n var ccLogger = ccHandler(serializer);\r\n logger = new logger$1.Logger('@firebase/performance/cc');\r\n logger.logHandler = ccLogger;\r\n return logger;\r\n}\r\nfunction logTrace(trace) {\r\n var settingsService = SettingsService.getInstance();\r\n // Do not log if trace is auto generated and instrumentation is disabled.\r\n if (!settingsService.instrumentationEnabled && trace.isAuto)\r\n return;\r\n // Do not log if trace is custom and data collection is disabled.\r\n if (!settingsService.dataCollectionEnabled && !trace.isAuto)\r\n return;\r\n // Only log the page load auto traces if page is visible.\r\n if (trace.isAuto && getVisibilityState() !== VisibilityState.VISIBLE)\r\n return;\r\n if (!settingsService.loggingEnabled || !settingsService.logTraceAfterSampling)\r\n return;\r\n if (isPerfInitialized()) {\r\n sendTraceLog(trace);\r\n }\r\n else {\r\n // Custom traces can be used before the initialization but logging\r\n // should wait until after.\r\n getInitializationPromise().then(function () { return sendTraceLog(trace); }, function () { return sendTraceLog(trace); });\r\n }\r\n}\r\nfunction sendTraceLog(trace) {\r\n if (getIid()) {\r\n setTimeout(function () { return getLogger().log(trace, 1 /* Trace */); }, 0);\r\n }\r\n}\r\nfunction logNetworkRequest(networkRequest) {\r\n var settingsService = SettingsService.getInstance();\r\n // Do not log network requests if instrumentation is disabled.\r\n if (!settingsService.instrumentationEnabled)\r\n return;\r\n // Do not log the js sdk's call to cc service to avoid unnecessary cycle.\r\n if (networkRequest.url === settingsService.logEndPointUrl.split('?')[0])\r\n return;\r\n if (!settingsService.loggingEnabled ||\r\n !settingsService.logNetworkAfterSampling)\r\n return;\r\n setTimeout(function () { return getLogger().log(networkRequest, 0 /* NetworkRequest */); }, 0);\r\n}\r\nfunction serializer(resource, resourceType) {\r\n if (resourceType === 0 /* NetworkRequest */) {\r\n return serializeNetworkRequest(resource);\r\n }\r\n return serializeTrace(resource);\r\n}\r\nfunction serializeNetworkRequest(networkRequest) {\r\n var networkRequestMetric = {\r\n url: networkRequest.url,\r\n http_method: 1,\r\n http_response_code: 200,\r\n response_payload_bytes: networkRequest.responsePayloadBytes,\r\n client_start_time_us: networkRequest.startTimeUs,\r\n time_to_response_initiated_us: networkRequest.timeToResponseInitiatedUs,\r\n time_to_response_completed_us: networkRequest.timeToResponseCompletedUs\r\n };\r\n var perfMetric = {\r\n application_info: getApplicationInfo(),\r\n network_request_metric: networkRequestMetric\r\n };\r\n return JSON.stringify(perfMetric);\r\n}\r\nfunction serializeTrace(trace) {\r\n var traceMetric = {\r\n name: trace.name,\r\n is_auto: trace.isAuto,\r\n client_start_time_us: trace.startTimeUs,\r\n duration_us: trace.durationUs\r\n };\r\n if (Object.keys(trace.counters).length !== 0) {\r\n traceMetric.counters = convertToKeyValueArray(trace.counters);\r\n }\r\n var customAttributes = trace.getAttributes();\r\n if (Object.keys(customAttributes).length !== 0) {\r\n traceMetric.custom_attributes = convertToKeyValueArray(customAttributes);\r\n }\r\n var perfMetric = {\r\n application_info: getApplicationInfo(),\r\n trace_metric: traceMetric\r\n };\r\n return JSON.stringify(perfMetric);\r\n}\r\nfunction getApplicationInfo() {\r\n return {\r\n google_app_id: SettingsService.getInstance().getAppId(),\r\n app_instance_id: getIid(),\r\n web_app_info: {\r\n sdk_version: SDK_VERSION,\r\n page_url: Api.getInstance().getUrl(),\r\n service_worker_status: getServiceWorkerStatus(),\r\n visibility_state: getVisibilityState(),\r\n effective_connection_type: getEffectiveConnectionType()\r\n },\r\n application_process_state: 0\r\n };\r\n}\r\nfunction convertToKeyValueArray(obj) {\r\n var keys = Object.keys(obj);\r\n return keys.map(function (key) { return ({ key: key, value: obj[key] }); });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar Trace = /** @class */ (function () {\r\n /**\r\n * @param name The name of the trace.\r\n * @param isAuto If the trace is auto-instrumented.\r\n * @param traceMeasureName The name of the measure marker in user timing specification. This field\r\n * is only set when the trace is built for logging when the user directly uses the user timing\r\n * api (performance.mark and performance.measure).\r\n */\r\n function Trace(name, isAuto, traceMeasureName) {\r\n if (isAuto === void 0) { isAuto = false; }\r\n this.name = name;\r\n this.isAuto = isAuto;\r\n this.state = 1 /* UNINITIALIZED */;\r\n this.customAttributes = {};\r\n this.counters = {};\r\n this.api = Api.getInstance();\r\n this.randomId = Math.floor(Math.random() * 1000000);\r\n if (!this.isAuto) {\r\n this.traceStartMark = TRACE_START_MARK_PREFIX + \"-\" + this.randomId + \"-\" + this.name;\r\n this.traceStopMark = TRACE_STOP_MARK_PREFIX + \"-\" + this.randomId + \"-\" + this.name;\r\n this.traceMeasure =\r\n traceMeasureName ||\r\n TRACE_MEASURE_PREFIX + \"-\" + this.randomId + \"-\" + this.name;\r\n if (traceMeasureName) {\r\n // For the case of direct user timing traces, no start stop will happen. The measure object\r\n // is already available.\r\n this.calculateTraceMetrics();\r\n }\r\n }\r\n }\r\n /**\r\n * Starts a trace. The measurement of the duration starts at this point.\r\n */\r\n Trace.prototype.start = function () {\r\n if (this.state !== 1 /* UNINITIALIZED */) {\r\n throw ERROR_FACTORY.create(\"trace started\" /* TRACE_STARTED_BEFORE */, {\r\n traceName: this.name\r\n });\r\n }\r\n this.api.mark(this.traceStartMark);\r\n this.state = 2 /* RUNNING */;\r\n };\r\n /**\r\n * Stops the trace. The measurement of the duration of the trace stops at this point and trace\r\n * is logged.\r\n */\r\n Trace.prototype.stop = function () {\r\n if (this.state !== 2 /* RUNNING */) {\r\n throw ERROR_FACTORY.create(\"trace stopped\" /* TRACE_STOPPED_BEFORE */, {\r\n traceName: this.name\r\n });\r\n }\r\n this.state = 3 /* TERMINATED */;\r\n this.api.mark(this.traceStopMark);\r\n this.api.measure(this.traceMeasure, this.traceStartMark, this.traceStopMark);\r\n this.calculateTraceMetrics();\r\n logTrace(this);\r\n };\r\n /**\r\n * Records a trace with predetermined values. If this method is used a trace is created and logged\r\n * directly. No need to use start and stop methods.\r\n * @param startTime Trace start time since epoch in millisec\r\n * @param duration The duraction of the trace in millisec\r\n * @param options An object which can optionally hold maps of custom metrics and custom attributes\r\n */\r\n Trace.prototype.record = function (startTime, duration, options) {\r\n this.durationUs = Math.floor(duration * 1000);\r\n this.startTimeUs = Math.floor(startTime * 1000);\r\n if (options && options.attributes) {\r\n this.customAttributes = tslib_1.__assign({}, options.attributes);\r\n }\r\n if (options && options.metrics) {\r\n for (var _i = 0, _a = Object.keys(options.metrics); _i < _a.length; _i++) {\r\n var metric = _a[_i];\r\n if (!isNaN(Number(options.metrics[metric]))) {\r\n this.counters[metric] = Number(Math.floor(options.metrics[metric]));\r\n }\r\n }\r\n }\r\n logTrace(this);\r\n };\r\n /**\r\n * Increments a custom metric by a certain number or 1 if number not specified. Will create a new\r\n * custom metric if one with the given name does not exist.\r\n * @param counter Name of the custom metric\r\n * @param num Increment by value\r\n */\r\n Trace.prototype.incrementMetric = function (counter, num) {\r\n if (num === void 0) { num = 1; }\r\n if (this.counters[counter] === undefined) {\r\n this.counters[counter] = 0;\r\n }\r\n this.counters[counter] += num;\r\n };\r\n /**\r\n * Sets a custom metric to a specified value. Will create a new custom metric if one with the\r\n * given name does not exist.\r\n * @param counter Name of the custom metric\r\n * @param num Set custom metric to this value\r\n */\r\n Trace.prototype.putMetric = function (counter, num) {\r\n this.counters[counter] = num;\r\n };\r\n /**\r\n * Returns the value of the custom metric by that name. If a custom metric with that name does\r\n * not exist will return zero.\r\n * @param counter\r\n */\r\n Trace.prototype.getMetric = function (counter) {\r\n return this.counters[counter] || 0;\r\n };\r\n /**\r\n * Sets a custom attribute of a trace to a certain value.\r\n * @param attr\r\n * @param value\r\n */\r\n Trace.prototype.putAttribute = function (attr, value) {\r\n this.customAttributes[attr] = value;\r\n };\r\n /**\r\n * Retrieves the value a custom attribute of a trace is set to.\r\n * @param attr\r\n */\r\n Trace.prototype.getAttribute = function (attr) {\r\n return this.customAttributes[attr];\r\n };\r\n Trace.prototype.removeAttribute = function (attr) {\r\n if (this.customAttributes[attr] === undefined)\r\n return;\r\n delete this.customAttributes[attr];\r\n };\r\n Trace.prototype.getAttributes = function () {\r\n return tslib_1.__assign({}, this.customAttributes);\r\n };\r\n Trace.prototype.setStartTime = function (startTime) {\r\n this.startTimeUs = startTime;\r\n };\r\n Trace.prototype.setDuration = function (duration) {\r\n this.durationUs = duration;\r\n };\r\n /**\r\n * Calculates and assigns the duration and start time of the trace using the measure performance\r\n * entry.\r\n */\r\n Trace.prototype.calculateTraceMetrics = function () {\r\n var perfMeasureEntries = this.api.getEntriesByName(this.traceMeasure);\r\n var perfMeasureEntry = perfMeasureEntries && perfMeasureEntries[0];\r\n if (perfMeasureEntry) {\r\n this.durationUs = Math.floor(perfMeasureEntry.duration * 1000);\r\n this.startTimeUs = Math.floor((perfMeasureEntry.startTime + this.api.getTimeOrigin()) * 1000);\r\n }\r\n };\r\n /**\r\n * @param navigationTimings A single element array which contains the navigationTIming object of\r\n * the page load\r\n * @param paintTimings A array which contains paintTiming object of the page load\r\n * @param firstInputDelay First input delay in millisec\r\n */\r\n Trace.createOobTrace = function (navigationTimings, paintTimings, firstInputDelay) {\r\n var route = Api.getInstance().getUrl();\r\n if (!route)\r\n return;\r\n var trace = new Trace(OOB_TRACE_PAGE_LOAD_PREFIX + route, true);\r\n var timeOriginUs = Math.floor(Api.getInstance().getTimeOrigin() * 1000);\r\n trace.setStartTime(timeOriginUs);\r\n // navigationTimings includes only one element.\r\n if (navigationTimings && navigationTimings[0]) {\r\n trace.setDuration(Math.floor(navigationTimings[0].duration * 1000));\r\n trace.incrementMetric('domInteractive', Math.floor(navigationTimings[0].domInteractive * 1000));\r\n trace.incrementMetric('domContentLoadedEventEnd', Math.floor(navigationTimings[0].domContentLoadedEventEnd * 1000));\r\n trace.incrementMetric('loadEventEnd', Math.floor(navigationTimings[0].loadEventEnd * 1000));\r\n }\r\n var FIRST_PAINT = 'first-paint';\r\n var FIRST_CONTENTFUL_PAINT = 'first-contentful-paint';\r\n if (paintTimings) {\r\n var firstPaint = paintTimings.find(function (paintObject) { return paintObject.name === FIRST_PAINT; });\r\n if (firstPaint && firstPaint.startTime) {\r\n trace.incrementMetric(FIRST_PAINT_COUNTER_NAME, Math.floor(firstPaint.startTime * 1000));\r\n }\r\n var firstContentfulPaint = paintTimings.find(function (paintObject) { return paintObject.name === FIRST_CONTENTFUL_PAINT; });\r\n if (firstContentfulPaint && firstContentfulPaint.startTime) {\r\n trace.incrementMetric(FIRST_CONTENTFUL_PAINT_COUNTER_NAME, Math.floor(firstContentfulPaint.startTime * 1000));\r\n }\r\n if (firstInputDelay) {\r\n trace.incrementMetric(FIRST_INPUT_DELAY_COUNTER_NAME, Math.floor(firstInputDelay * 1000));\r\n }\r\n }\r\n logTrace(trace);\r\n };\r\n Trace.createUserTimingTrace = function (measureName) {\r\n var trace = new Trace(measureName, false, measureName);\r\n logTrace(trace);\r\n };\r\n return Trace;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction createNetworkRequestEntry(entry) {\r\n var performanceEntry = entry;\r\n if (!performanceEntry || performanceEntry.responseStart === undefined)\r\n return;\r\n var timeOrigin = Api.getInstance().getTimeOrigin();\r\n var startTimeUs = Math.floor((performanceEntry.startTime + timeOrigin) * 1000);\r\n var timeToResponseInitiatedUs = performanceEntry.responseStart\r\n ? Math.floor((performanceEntry.responseStart - performanceEntry.startTime) * 1000)\r\n : undefined;\r\n var timeToResponseCompletedUs = Math.floor((performanceEntry.responseEnd - performanceEntry.startTime) * 1000);\r\n // Remove the query params from logged network request url.\r\n var url = performanceEntry.name && performanceEntry.name.split('?')[0];\r\n var networkRequest = {\r\n url: url,\r\n responsePayloadBytes: performanceEntry.transferSize,\r\n startTimeUs: startTimeUs,\r\n timeToResponseInitiatedUs: timeToResponseInitiatedUs,\r\n timeToResponseCompletedUs: timeToResponseCompletedUs\r\n };\r\n logNetworkRequest(networkRequest);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar FID_WAIT_TIME_MS = 5000;\r\nfunction setupOobResources() {\r\n // Do not initialize unless iid is available.\r\n if (!getIid())\r\n return;\r\n // The load event might not have fired yet, and that means performance navigation timing\r\n // object has a duration of 0. The setup should run after all current tasks in js queue.\r\n setTimeout(function () { return setupOobTraces(); }, 0);\r\n setTimeout(function () { return setupNetworkRequests(); }, 0);\r\n setTimeout(function () { return setupUserTimingTraces(); }, 0);\r\n}\r\nfunction setupNetworkRequests() {\r\n var api = Api.getInstance();\r\n var resources = api.getEntriesByType('resource');\r\n for (var _i = 0, resources_1 = resources; _i < resources_1.length; _i++) {\r\n var resource = resources_1[_i];\r\n createNetworkRequestEntry(resource);\r\n }\r\n api.setupObserver('resource', createNetworkRequestEntry);\r\n}\r\nfunction setupOobTraces() {\r\n var api = Api.getInstance();\r\n var navigationTimings = api.getEntriesByType('navigation');\r\n var paintTimings = api.getEntriesByType('paint');\r\n // If First Input Desly polyfill is added to the page, report the fid value.\r\n // https://github.com/GoogleChromeLabs/first-input-delay\r\n if (api.onFirstInputDelay) {\r\n // If the fid call back is not called for certain time, continue without it.\r\n var timeoutId_1 = setTimeout(function () {\r\n Trace.createOobTrace(navigationTimings, paintTimings);\r\n timeoutId_1 = undefined;\r\n }, FID_WAIT_TIME_MS);\r\n api.onFirstInputDelay(function (fid) {\r\n if (timeoutId_1) {\r\n clearTimeout(timeoutId_1);\r\n Trace.createOobTrace(navigationTimings, paintTimings, fid);\r\n }\r\n });\r\n }\r\n else {\r\n Trace.createOobTrace(navigationTimings, paintTimings);\r\n }\r\n}\r\nfunction setupUserTimingTraces() {\r\n var api = Api.getInstance();\r\n // Run through the measure performance entries collected up to this point.\r\n var measures = api.getEntriesByType('measure');\r\n for (var _i = 0, measures_1 = measures; _i < measures_1.length; _i++) {\r\n var measure = measures_1[_i];\r\n createUserTimingTrace(measure);\r\n }\r\n // Setup an observer to capture the measures from this point on.\r\n api.setupObserver('measure', createUserTimingTrace);\r\n}\r\nfunction createUserTimingTrace(measure) {\r\n var measureName = measure.name;\r\n // Do not create a trace, if the user timing marks and measures are created by the sdk itself.\r\n if (measureName.substring(0, TRACE_MEASURE_PREFIX.length) ===\r\n TRACE_MEASURE_PREFIX)\r\n return;\r\n Trace.createUserTimingTrace(measureName);\r\n}\n\n/**\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar PerformanceController = /** @class */ (function () {\r\n function PerformanceController(app) {\r\n this.app = app;\r\n getInitializationPromise().then(setupOobResources, setupOobResources);\r\n }\r\n PerformanceController.prototype.trace = function (name) {\r\n return new Trace(name);\r\n };\r\n Object.defineProperty(PerformanceController.prototype, \"instrumentationEnabled\", {\r\n get: function () {\r\n return SettingsService.getInstance().instrumentationEnabled;\r\n },\r\n set: function (val) {\r\n SettingsService.getInstance().instrumentationEnabled = val;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(PerformanceController.prototype, \"dataCollectionEnabled\", {\r\n get: function () {\r\n return SettingsService.getInstance().dataCollectionEnabled;\r\n },\r\n set: function (val) {\r\n SettingsService.getInstance().dataCollectionEnabled = val;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n return PerformanceController;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar DEFAULT_ENTRY_NAME = '[DEFAULT]';\r\nfunction registerPerformance(instance) {\r\n var factoryMethod = function (app) {\r\n if (app.name !== DEFAULT_ENTRY_NAME) {\r\n throw ERROR_FACTORY.create(\"FB not default\" /* FB_NOT_DEFAULT */);\r\n }\r\n SettingsService.getInstance().firebaseAppInstance = app;\r\n return new PerformanceController(app);\r\n };\r\n // Register performance with firebase-app.\r\n var namespaceExports = {};\r\n instance.INTERNAL.registerService('performance', factoryMethod, namespaceExports);\r\n}\r\nif (window && fetch && Promise) {\r\n setupApi(window);\r\n registerPerformance(firebase);\r\n}\r\nelse {\r\n consoleLogger.info('Firebase Performance cannot start if browser does not support fetch and Promise.');\r\n}\n\nexports.registerPerformance = registerPerformance;\n//# sourceMappingURL=index.cjs.js.map\n","import firebase from '@firebase/app';\nimport { ErrorFactory, FirebaseError } from '@firebase/util';\nimport { openDb } from 'idb';\n\n/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation. All rights reserved.\r\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\r\nthis file except in compliance with the License. You may obtain a copy of the\r\nLicense at http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\r\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\r\nMERCHANTABLITY OR NON-INFRINGEMENT.\r\n\r\nSee the Apache Version 2.0 License for specific language governing permissions\r\nand limitations under the License.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nfunction __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nvar __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n };\r\n return __assign.apply(this, arguments);\r\n};\r\n\r\nfunction __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\r\n t[p[i]] = s[p[i]];\r\n return t;\r\n}\r\n\r\nfunction __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nfunction __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nfunction __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nfunction __awaiter(thisArg, _arguments, P, generator) {\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nfunction __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nfunction __exportStar(m, exports) {\r\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nfunction __values(o) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\r\n if (m) return m.call(o);\r\n return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n}\r\n\r\nfunction __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nfunction __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nfunction __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nfunction __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nfunction __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nfunction __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nfunction __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n}\r\nfunction __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nfunction __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\n\nvar tslib_1 = /*#__PURE__*/Object.freeze({\n __extends: __extends,\n get __assign () { return __assign; },\n __rest: __rest,\n __decorate: __decorate,\n __param: __param,\n __metadata: __metadata,\n __awaiter: __awaiter,\n __generator: __generator,\n __exportStar: __exportStar,\n __values: __values,\n __read: __read,\n __spread: __spread,\n __await: __await,\n __asyncGenerator: __asyncGenerator,\n __asyncDelegator: __asyncDelegator,\n __asyncValues: __asyncValues,\n __makeTemplateObject: __makeTemplateObject,\n __importStar: __importStar,\n __importDefault: __importDefault\n});\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar PENDING_TIMEOUT_MS = 10000;\r\nvar PACKAGE_VERSION = 'w:0.1.0'; // Will be replaced by Rollup\r\nvar INTERNAL_AUTH_VERSION = 'FIS_v2';\r\nvar INSTALLATIONS_API_URL = 'https://firebaseinstallations.googleapis.com/v1';\r\nvar TOKEN_EXPIRATION_BUFFER = 60 * 60 * 1000; // One hour\r\nvar SERVICE = 'installations';\r\nvar SERVICE_NAME = 'Installations';\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar _a;\r\nvar ERROR_DESCRIPTION_MAP = (_a = {},\r\n _a[\"missing-app-config-values\" /* MISSING_APP_CONFIG_VALUES */] = 'Missing App configuration values.',\r\n _a[\"create-installation-failed\" /* CREATE_INSTALLATION_FAILED */] = 'Could not register Firebase Installation.',\r\n _a[\"generate-token-failed\" /* GENERATE_TOKEN_FAILED */] = 'Could not generate Auth Token.',\r\n _a[\"not-registered\" /* NOT_REGISTERED */] = 'Firebase Installation is not registered.',\r\n _a[\"installation-not-found\" /* INSTALLATION_NOT_FOUND */] = 'Firebase Installation not found.',\r\n _a[\"request-failed\" /* REQUEST_FAILED */] = '{$requestName} request failed with error \"{$serverCode} {$serverStatus}: {$serverMessage}\"',\r\n _a[\"app-offline\" /* APP_OFFLINE */] = 'Could not process request. Application offline.',\r\n _a[\"delete-pending-registration\" /* DELETE_PENDING_REGISTRATION */] = \"Can't delete installation while there is a pending registration request.\",\r\n _a);\r\nvar ERROR_FACTORY = new ErrorFactory(SERVICE, SERVICE_NAME, ERROR_DESCRIPTION_MAP);\r\n/** Returns true if error is a FirebaseError that is based on an error from the server. */\r\nfunction isServerError(error) {\r\n return (error instanceof FirebaseError &&\r\n error.code.includes(\"request-failed\" /* REQUEST_FAILED */));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction extractAppConfig(app) {\r\n if (!app || !app.options) {\r\n throw ERROR_FACTORY.create(\"missing-app-config-values\" /* MISSING_APP_CONFIG_VALUES */);\r\n }\r\n var appName = app.name;\r\n var _a = app.options, projectId = _a.projectId, apiKey = _a.apiKey, appId = _a.appId;\r\n if (!appName || !projectId || !apiKey || !appId) {\r\n throw ERROR_FACTORY.create(\"missing-app-config-values\" /* MISSING_APP_CONFIG_VALUES */);\r\n }\r\n return { appName: appName, projectId: projectId, apiKey: apiKey, appId: appId };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getInstallationsEndpoint(_a) {\r\n var projectId = _a.projectId;\r\n return INSTALLATIONS_API_URL + \"/projects/\" + projectId + \"/installations\";\r\n}\r\nfunction extractAuthTokenInfoFromResponse(response) {\r\n return {\r\n token: response.token,\r\n requestStatus: 2 /* COMPLETED */,\r\n expiresIn: getExpiresInFromResponseExpiresIn(response.expiresIn),\r\n creationTime: Date.now()\r\n };\r\n}\r\nfunction getErrorFromResponse(requestName, response) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var responseJson, errorData;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, response.json()];\r\n case 1:\r\n responseJson = _a.sent();\r\n errorData = responseJson.error;\r\n return [2 /*return*/, ERROR_FACTORY.create(\"request-failed\" /* REQUEST_FAILED */, {\r\n requestName: requestName,\r\n serverCode: errorData.code,\r\n serverMessage: errorData.message,\r\n serverStatus: errorData.status\r\n })];\r\n }\r\n });\r\n });\r\n}\r\nfunction getHeaders(_a) {\r\n var apiKey = _a.apiKey;\r\n return new Headers({\r\n 'Content-Type': 'application/json',\r\n Accept: 'application/json',\r\n 'x-goog-api-key': apiKey\r\n });\r\n}\r\nfunction getHeadersWithAuth(appConfig, _a) {\r\n var refreshToken = _a.refreshToken;\r\n var headers = getHeaders(appConfig);\r\n headers.append('Authorization', getAuthorizationHeader(refreshToken));\r\n return headers;\r\n}\r\nfunction getExpiresInFromResponseExpiresIn(responseExpiresIn) {\r\n // This works because the server will never respond with fractions of a second.\r\n return Number(responseExpiresIn.replace('s', '000'));\r\n}\r\nfunction getAuthorizationHeader(refreshToken) {\r\n return INTERNAL_AUTH_VERSION + \" \" + refreshToken;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction createInstallation(appConfig, _a) {\r\n var fid = _a.fid;\r\n return __awaiter(this, void 0, void 0, function () {\r\n var endpoint, headers, body, request, response, responseValue, registeredInstallationEntry;\r\n return __generator(this, function (_b) {\r\n switch (_b.label) {\r\n case 0:\r\n endpoint = getInstallationsEndpoint(appConfig);\r\n headers = getHeaders(appConfig);\r\n body = {\r\n fid: fid,\r\n authVersion: INTERNAL_AUTH_VERSION,\r\n appId: appConfig.appId,\r\n sdkVersion: PACKAGE_VERSION\r\n };\r\n request = {\r\n method: 'POST',\r\n headers: headers,\r\n body: JSON.stringify(body)\r\n };\r\n return [4 /*yield*/, fetch(endpoint, request)];\r\n case 1:\r\n response = _b.sent();\r\n if (!response.ok) return [3 /*break*/, 3];\r\n return [4 /*yield*/, response.json()];\r\n case 2:\r\n responseValue = _b.sent();\r\n registeredInstallationEntry = {\r\n fid: fid,\r\n registrationStatus: 2 /* COMPLETED */,\r\n refreshToken: responseValue.refreshToken,\r\n authToken: extractAuthTokenInfoFromResponse(responseValue.authToken)\r\n };\r\n return [2 /*return*/, registeredInstallationEntry];\r\n case 3: throw getErrorFromResponse('Create Installation', response);\r\n }\r\n });\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** Returns a promise that resolves after given time passes. */\r\nfunction sleep(ms) {\r\n return new Promise(function (resolve) {\r\n setTimeout(resolve, ms);\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction bufferToBase64UrlSafe(buffer) {\r\n var array = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);\r\n var b64 = btoa(String.fromCharCode.apply(String, __spread(array)));\r\n return b64.replace(/\\+/g, '-').replace(/\\//g, '_');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** Generates a new FID using random values from Web Crypto API. */\r\nfunction generateFid() {\r\n // A valid FID has exactly 22 base64 characters, which is 132 bits, or 16.5\r\n // bytes. our implementation generates a 17 byte array instead.\r\n var fidByteArray = new Uint8Array(17);\r\n crypto.getRandomValues(fidByteArray);\r\n // Replace the first 4 random bits with the constant FID header of 0b0111.\r\n fidByteArray[0] = 112 + (fidByteArray[0] % 16);\r\n return encode(fidByteArray);\r\n}\r\n/** Converts a FID Uint8Array to a base64 string representation. */\r\nfunction encode(fidByteArray) {\r\n var b64String = bufferToBase64UrlSafe(fidByteArray);\r\n // Remove the 23rd character that was added because of the extra 4 bits at the\r\n // end of our 17 byte array, and the '=' padding.\r\n return b64String.substr(0, 22);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar DATABASE_NAME = 'firebase-installations-database';\r\nvar DATABASE_VERSION = 1;\r\nvar OBJECT_STORE_NAME = 'firebase-installations-store';\r\nvar dbPromise = openDb(DATABASE_NAME, DATABASE_VERSION, function (upgradeDB) {\r\n // We don't use 'break' in this switch statement, the fall-through\r\n // behavior is what we want, because if there are multiple versions between\r\n // the old version and the current version, we want ALL the migrations\r\n // that correspond to those versions to run, not only the last one.\r\n switch (upgradeDB.oldVersion) {\r\n case 0:\r\n upgradeDB.createObjectStore(OBJECT_STORE_NAME);\r\n }\r\n});\r\n/** Assigns or overwrites the record for the given key with the given value. */\r\nfunction set(appConfig, value) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var key, db, tx;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n key = getKey(appConfig);\r\n return [4 /*yield*/, dbPromise];\r\n case 1:\r\n db = _a.sent();\r\n tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n tx.objectStore(OBJECT_STORE_NAME).put(value, key);\r\n return [4 /*yield*/, tx.complete];\r\n case 2:\r\n _a.sent();\r\n return [2 /*return*/, value];\r\n }\r\n });\r\n });\r\n}\r\n/** Removes record(s) from the objectStore that match the given key. */\r\nfunction remove(appConfig) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var key, db, tx;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n key = getKey(appConfig);\r\n return [4 /*yield*/, dbPromise];\r\n case 1:\r\n db = _a.sent();\r\n tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n tx.objectStore(OBJECT_STORE_NAME).delete(key);\r\n return [2 /*return*/, tx.complete];\r\n }\r\n });\r\n });\r\n}\r\n/**\r\n * Atomically updates a record with the result of updateFn, which gets\r\n * called with the current value. If newValue is undefined, the record is\r\n * deleted instead.\r\n * @return Updated value\r\n */\r\nfunction update(appConfig, updateFn) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var key, db, tx, store, oldValue, newValue;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n key = getKey(appConfig);\r\n return [4 /*yield*/, dbPromise];\r\n case 1:\r\n db = _a.sent();\r\n tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n store = tx.objectStore(OBJECT_STORE_NAME);\r\n return [4 /*yield*/, store.get(key)];\r\n case 2:\r\n oldValue = _a.sent();\r\n newValue = updateFn(oldValue);\r\n if (newValue === oldValue) {\r\n return [2 /*return*/, newValue];\r\n }\r\n if (newValue === undefined) {\r\n store.delete(key);\r\n }\r\n else {\r\n store.put(newValue, key);\r\n }\r\n return [4 /*yield*/, tx.complete];\r\n case 3:\r\n _a.sent();\r\n return [2 /*return*/, newValue];\r\n }\r\n });\r\n });\r\n}\r\nfunction getKey(appConfig) {\r\n return appConfig.appName + \"!\" + appConfig.appId;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Updates and returns the InstallationEntry from the database.\r\n * Also triggers a registration request if it is necessary and possible.\r\n */\r\nfunction getInstallationEntry(appConfig) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var registrationPromise, _a;\r\n return __generator(this, function (_b) {\r\n switch (_b.label) {\r\n case 0:\r\n _a = {};\r\n return [4 /*yield*/, update(appConfig, function (oldEntry) {\r\n var installationEntry = updateOrCreateFid(oldEntry);\r\n var entryWithPromise = triggerRegistrationIfNecessary(appConfig, installationEntry);\r\n registrationPromise = entryWithPromise.registrationPromise;\r\n return entryWithPromise.installationEntry;\r\n })];\r\n case 1: return [2 /*return*/, (_a.installationEntry = _b.sent(),\r\n _a.registrationPromise = registrationPromise,\r\n _a)];\r\n }\r\n });\r\n });\r\n}\r\nfunction updateOrCreateFid(oldEntry) {\r\n var entry = oldEntry || {\r\n fid: generateFid(),\r\n registrationStatus: 0 /* NOT_STARTED */\r\n };\r\n if (hasInstallationRequestTimedOut(entry)) {\r\n return {\r\n fid: entry.fid,\r\n registrationStatus: 0 /* NOT_STARTED */\r\n };\r\n }\r\n return entry;\r\n}\r\n/**\r\n * If the Firebase Installation is not registered yet, this will trigger the registration\r\n * and return an InProgressInstallationEntry.\r\n */\r\nfunction triggerRegistrationIfNecessary(appConfig, installationEntry) {\r\n if (installationEntry.registrationStatus === 0 /* NOT_STARTED */) {\r\n if (!navigator.onLine) {\r\n // Registration required but app is offline.\r\n var registrationPromiseWithError = Promise.reject(ERROR_FACTORY.create(\"app-offline\" /* APP_OFFLINE */));\r\n return {\r\n installationEntry: installationEntry,\r\n registrationPromise: registrationPromiseWithError\r\n };\r\n }\r\n // Try registering. Change status to IN_PROGRESS.\r\n var inProgressEntry = {\r\n fid: installationEntry.fid,\r\n registrationStatus: 1 /* IN_PROGRESS */,\r\n registrationTime: Date.now()\r\n };\r\n var registrationPromise = registerInstallation(appConfig, inProgressEntry);\r\n return { installationEntry: inProgressEntry, registrationPromise: registrationPromise };\r\n }\r\n else if (installationEntry.registrationStatus === 1 /* IN_PROGRESS */) {\r\n return {\r\n installationEntry: installationEntry,\r\n registrationPromise: waitUntilFidRegistration(appConfig)\r\n };\r\n }\r\n else {\r\n return { installationEntry: installationEntry };\r\n }\r\n}\r\n/** This will be executed only once for each new Firebase Installation. */\r\nfunction registerInstallation(appConfig, installationEntry) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var registeredInstallationEntry, e_1;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n _a.trys.push([0, 3, , 8]);\r\n return [4 /*yield*/, createInstallation(appConfig, installationEntry)];\r\n case 1:\r\n registeredInstallationEntry = _a.sent();\r\n return [4 /*yield*/, set(appConfig, registeredInstallationEntry)];\r\n case 2:\r\n _a.sent();\r\n return [3 /*break*/, 8];\r\n case 3:\r\n e_1 = _a.sent();\r\n if (!(isServerError(e_1) && e_1.serverCode === 409)) return [3 /*break*/, 5];\r\n // Server returned a \"FID can not be used\" error.\r\n // Generate a new ID next time.\r\n return [4 /*yield*/, remove(appConfig)];\r\n case 4:\r\n // Server returned a \"FID can not be used\" error.\r\n // Generate a new ID next time.\r\n _a.sent();\r\n return [3 /*break*/, 7];\r\n case 5: \r\n // Registration failed. Set FID as not registered.\r\n return [4 /*yield*/, set(appConfig, {\r\n fid: installationEntry.fid,\r\n registrationStatus: 0 /* NOT_STARTED */\r\n })];\r\n case 6:\r\n // Registration failed. Set FID as not registered.\r\n _a.sent();\r\n _a.label = 7;\r\n case 7: throw e_1;\r\n case 8: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n}\r\n/** Call if FID registration is pending. */\r\nfunction waitUntilFidRegistration(appConfig) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var entry;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, updateInstallationRequest(appConfig)];\r\n case 1:\r\n entry = _a.sent();\r\n _a.label = 2;\r\n case 2:\r\n if (!(entry.registrationStatus === 1 /* IN_PROGRESS */)) return [3 /*break*/, 5];\r\n // createInstallation request still in progress.\r\n return [4 /*yield*/, sleep(100)];\r\n case 3:\r\n // createInstallation request still in progress.\r\n _a.sent();\r\n return [4 /*yield*/, updateInstallationRequest(appConfig)];\r\n case 4:\r\n entry = _a.sent();\r\n return [3 /*break*/, 2];\r\n case 5:\r\n if (entry.registrationStatus === 0 /* NOT_STARTED */) {\r\n throw ERROR_FACTORY.create(\"create-installation-failed\" /* CREATE_INSTALLATION_FAILED */);\r\n }\r\n return [2 /*return*/];\r\n }\r\n });\r\n });\r\n}\r\n/**\r\n * Called only if there is a CreateInstallation request in progress.\r\n *\r\n * Updates the InstallationEntry in the DB based on the status of the\r\n * CreateInstallation request.\r\n *\r\n * Returns the updated InstallationEntry.\r\n */\r\nfunction updateInstallationRequest(appConfig) {\r\n return update(appConfig, function (oldEntry) {\r\n if (!oldEntry) {\r\n throw ERROR_FACTORY.create(\"installation-not-found\" /* INSTALLATION_NOT_FOUND */);\r\n }\r\n if (hasInstallationRequestTimedOut(oldEntry)) {\r\n return {\r\n fid: oldEntry.fid,\r\n registrationStatus: 0 /* NOT_STARTED */\r\n };\r\n }\r\n return oldEntry;\r\n });\r\n}\r\nfunction hasInstallationRequestTimedOut(installationEntry) {\r\n return (installationEntry.registrationStatus === 1 /* IN_PROGRESS */ &&\r\n installationEntry.registrationTime + PENDING_TIMEOUT_MS < Date.now());\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getId(app) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var appConfig, _a, installationEntry, registrationPromise;\r\n return __generator(this, function (_b) {\r\n switch (_b.label) {\r\n case 0:\r\n appConfig = extractAppConfig(app);\r\n return [4 /*yield*/, getInstallationEntry(appConfig)];\r\n case 1:\r\n _a = _b.sent(), installationEntry = _a.installationEntry, registrationPromise = _a.registrationPromise;\r\n if (registrationPromise) {\r\n // Suppress registration errors as they are not a problem for getId.\r\n registrationPromise.catch(function () { });\r\n }\r\n return [2 /*return*/, installationEntry.fid];\r\n }\r\n });\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction generateAuthToken(appConfig, installationEntry) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var endpoint, headers, body, request, response, responseValue, completedAuthToken;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n endpoint = getGenerateAuthTokenEndpoint(appConfig, installationEntry);\r\n headers = getHeadersWithAuth(appConfig, installationEntry);\r\n body = {\r\n installation: {\r\n sdkVersion: PACKAGE_VERSION\r\n }\r\n };\r\n request = {\r\n method: 'POST',\r\n headers: headers,\r\n body: JSON.stringify(body)\r\n };\r\n return [4 /*yield*/, fetch(endpoint, request)];\r\n case 1:\r\n response = _a.sent();\r\n if (!response.ok) return [3 /*break*/, 3];\r\n return [4 /*yield*/, response.json()];\r\n case 2:\r\n responseValue = _a.sent();\r\n completedAuthToken = extractAuthTokenInfoFromResponse(responseValue);\r\n return [2 /*return*/, completedAuthToken];\r\n case 3: throw getErrorFromResponse('Generate Auth Token', response);\r\n }\r\n });\r\n });\r\n}\r\nfunction getGenerateAuthTokenEndpoint(appConfig, _a) {\r\n var fid = _a.fid;\r\n return getInstallationsEndpoint(appConfig) + \"/\" + fid + \"/authTokens:generate\";\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getToken(app) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var appConfig;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n appConfig = extractAppConfig(app);\r\n return [4 /*yield*/, completeInstallationRegistration(appConfig)];\r\n case 1:\r\n _a.sent();\r\n // At this point we either have a Registered Installation in the DB, or we've\r\n // already thrown an error.\r\n return [2 /*return*/, fetchAuthToken(appConfig)];\r\n }\r\n });\r\n });\r\n}\r\nfunction completeInstallationRegistration(appConfig) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var _a, installationEntry, registrationPromise;\r\n return __generator(this, function (_b) {\r\n switch (_b.label) {\r\n case 0: return [4 /*yield*/, getInstallationEntry(appConfig)];\r\n case 1:\r\n _a = _b.sent(), installationEntry = _a.installationEntry, registrationPromise = _a.registrationPromise;\r\n if (!registrationPromise) return [3 /*break*/, 3];\r\n // A createInstallation request is in progress. Wait until it finishes.\r\n return [4 /*yield*/, registrationPromise];\r\n case 2:\r\n // A createInstallation request is in progress. Wait until it finishes.\r\n _b.sent();\r\n return [3 /*break*/, 4];\r\n case 3:\r\n if (installationEntry.registrationStatus !== 2 /* COMPLETED */) {\r\n // Installation ID can't be registered.\r\n throw ERROR_FACTORY.create(\"create-installation-failed\" /* CREATE_INSTALLATION_FAILED */);\r\n }\r\n _b.label = 4;\r\n case 4: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n}\r\nfunction fetchAuthToken(appConfig) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var tokenPromise, entry, authToken, _a;\r\n return __generator(this, function (_b) {\r\n switch (_b.label) {\r\n case 0: return [4 /*yield*/, update(appConfig, function (oldEntry) {\r\n if (!isEntryRegistered(oldEntry)) {\r\n throw ERROR_FACTORY.create(\"not-registered\" /* NOT_REGISTERED */);\r\n }\r\n var oldAuthToken = oldEntry.authToken;\r\n if (isAuthTokenValid(oldAuthToken)) {\r\n // There is a valid token in the DB.\r\n return oldEntry;\r\n }\r\n else if (oldAuthToken.requestStatus === 1 /* IN_PROGRESS */) {\r\n // There already is a token request in progress.\r\n tokenPromise = waitUntilAuthTokenRequest(appConfig);\r\n return oldEntry;\r\n }\r\n else {\r\n // No token or token expired.\r\n if (!navigator.onLine) {\r\n throw ERROR_FACTORY.create(\"app-offline\" /* APP_OFFLINE */);\r\n }\r\n var inProgressEntry = makeAuthTokenRequestInProgressEntry(oldEntry);\r\n tokenPromise = fetchAuthTokenFromServer(appConfig, inProgressEntry);\r\n return inProgressEntry;\r\n }\r\n })];\r\n case 1:\r\n entry = _b.sent();\r\n if (!tokenPromise) return [3 /*break*/, 3];\r\n return [4 /*yield*/, tokenPromise];\r\n case 2:\r\n _a = _b.sent();\r\n return [3 /*break*/, 4];\r\n case 3:\r\n _a = entry.authToken;\r\n _b.label = 4;\r\n case 4:\r\n authToken = _a;\r\n return [2 /*return*/, authToken.token];\r\n }\r\n });\r\n });\r\n}\r\n/**\r\n * Call only if FID is registered and Auth Token request is in progress.\r\n */\r\nfunction waitUntilAuthTokenRequest(appConfig) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var entry, authToken;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, updateAuthTokenRequest(appConfig)];\r\n case 1:\r\n entry = _a.sent();\r\n _a.label = 2;\r\n case 2:\r\n if (!(entry.authToken.requestStatus === 1 /* IN_PROGRESS */)) return [3 /*break*/, 5];\r\n // generateAuthToken still in progress.\r\n return [4 /*yield*/, sleep(100)];\r\n case 3:\r\n // generateAuthToken still in progress.\r\n _a.sent();\r\n return [4 /*yield*/, updateAuthTokenRequest(appConfig)];\r\n case 4:\r\n entry = _a.sent();\r\n return [3 /*break*/, 2];\r\n case 5:\r\n authToken = entry.authToken;\r\n if (authToken.requestStatus === 0 /* NOT_STARTED */) {\r\n throw ERROR_FACTORY.create(\"generate-token-failed\" /* GENERATE_TOKEN_FAILED */);\r\n }\r\n else {\r\n return [2 /*return*/, authToken];\r\n }\r\n return [2 /*return*/];\r\n }\r\n });\r\n });\r\n}\r\n/**\r\n * Called only if there is a GenerateAuthToken request in progress.\r\n *\r\n * Updates the InstallationEntry in the DB based on the status of the\r\n * GenerateAuthToken request.\r\n *\r\n * Returns the updated InstallationEntry.\r\n */\r\nfunction updateAuthTokenRequest(appConfig) {\r\n return update(appConfig, function (oldEntry) {\r\n if (!isEntryRegistered(oldEntry)) {\r\n throw ERROR_FACTORY.create(\"not-registered\" /* NOT_REGISTERED */);\r\n }\r\n var oldAuthToken = oldEntry.authToken;\r\n if (hasAuthTokenRequestTimedOut(oldAuthToken)) {\r\n return __assign({}, oldEntry, { authToken: { requestStatus: 0 /* NOT_STARTED */ } });\r\n }\r\n return oldEntry;\r\n });\r\n}\r\nfunction fetchAuthTokenFromServer(appConfig, installationEntry) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var authToken, updatedInstallationEntry, e_1, updatedInstallationEntry;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n _a.trys.push([0, 3, , 8]);\r\n return [4 /*yield*/, generateAuthToken(appConfig, installationEntry)];\r\n case 1:\r\n authToken = _a.sent();\r\n updatedInstallationEntry = __assign({}, installationEntry, { authToken: authToken });\r\n return [4 /*yield*/, set(appConfig, updatedInstallationEntry)];\r\n case 2:\r\n _a.sent();\r\n return [2 /*return*/, authToken];\r\n case 3:\r\n e_1 = _a.sent();\r\n if (!(isServerError(e_1) && (e_1.serverCode === 401 || e_1.serverCode === 404))) return [3 /*break*/, 5];\r\n // Server returned a \"FID not found\" or a \"Invalid authentication\" error.\r\n // Generate a new ID next time.\r\n return [4 /*yield*/, remove(appConfig)];\r\n case 4:\r\n // Server returned a \"FID not found\" or a \"Invalid authentication\" error.\r\n // Generate a new ID next time.\r\n _a.sent();\r\n return [3 /*break*/, 7];\r\n case 5:\r\n updatedInstallationEntry = __assign({}, installationEntry, { authToken: { requestStatus: 0 /* NOT_STARTED */ } });\r\n return [4 /*yield*/, set(appConfig, updatedInstallationEntry)];\r\n case 6:\r\n _a.sent();\r\n _a.label = 7;\r\n case 7: throw e_1;\r\n case 8: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n}\r\nfunction isEntryRegistered(installationEntry) {\r\n return (installationEntry !== undefined &&\r\n installationEntry.registrationStatus === 2 /* COMPLETED */);\r\n}\r\nfunction isAuthTokenValid(authToken) {\r\n return (authToken.requestStatus === 2 /* COMPLETED */ &&\r\n !isAuthTokenExpired(authToken));\r\n}\r\nfunction isAuthTokenExpired(authToken) {\r\n var now = Date.now();\r\n return (now < authToken.creationTime ||\r\n authToken.creationTime + authToken.expiresIn < now + TOKEN_EXPIRATION_BUFFER);\r\n}\r\n/** Returns an updated InstallationEntry with an InProgressAuthToken. */\r\nfunction makeAuthTokenRequestInProgressEntry(oldEntry) {\r\n var inProgressAuthToken = {\r\n requestStatus: 1 /* IN_PROGRESS */,\r\n requestTime: Date.now()\r\n };\r\n return __assign({}, oldEntry, { authToken: inProgressAuthToken });\r\n}\r\nfunction hasAuthTokenRequestTimedOut(authToken) {\r\n return (authToken.requestStatus === 1 /* IN_PROGRESS */ &&\r\n authToken.requestTime + PENDING_TIMEOUT_MS < Date.now());\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction deleteInstallation(appConfig, installationEntry) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var endpoint, headers, request, response;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n endpoint = getDeleteEndpoint(appConfig, installationEntry);\r\n headers = getHeadersWithAuth(appConfig, installationEntry);\r\n request = {\r\n method: 'DELETE',\r\n headers: headers\r\n };\r\n return [4 /*yield*/, fetch(endpoint, request)];\r\n case 1:\r\n response = _a.sent();\r\n if (!response.ok) {\r\n throw getErrorFromResponse('Delete Installation', response);\r\n }\r\n return [2 /*return*/];\r\n }\r\n });\r\n });\r\n}\r\nfunction getDeleteEndpoint(appConfig, _a) {\r\n var fid = _a.fid;\r\n return getInstallationsEndpoint(appConfig) + \"/\" + fid;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction deleteInstallation$1(app) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var appConfig, entry;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n appConfig = extractAppConfig(app);\r\n return [4 /*yield*/, update(appConfig, function (oldEntry) {\r\n if (oldEntry &&\r\n oldEntry.registrationStatus === 0 /* NOT_STARTED */) {\r\n // Delete the unregistered entry without sending a deleteInstallation request.\r\n return undefined;\r\n }\r\n return oldEntry;\r\n })];\r\n case 1:\r\n entry = _a.sent();\r\n if (!entry) return [3 /*break*/, 6];\r\n if (!(entry.registrationStatus === 1 /* IN_PROGRESS */)) return [3 /*break*/, 2];\r\n // Can't delete while trying to register.\r\n throw ERROR_FACTORY.create(\"delete-pending-registration\" /* DELETE_PENDING_REGISTRATION */);\r\n case 2:\r\n if (!(entry.registrationStatus === 2 /* COMPLETED */)) return [3 /*break*/, 6];\r\n if (!!navigator.onLine) return [3 /*break*/, 3];\r\n throw ERROR_FACTORY.create(\"app-offline\" /* APP_OFFLINE */);\r\n case 3: return [4 /*yield*/, deleteInstallation(appConfig, entry)];\r\n case 4:\r\n _a.sent();\r\n return [4 /*yield*/, remove(appConfig)];\r\n case 5:\r\n _a.sent();\r\n _a.label = 6;\r\n case 6: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction registerInstallations(instance) {\r\n var installationsName = 'installations';\r\n var factoryMethod = function (app) {\r\n // Throws if app isn't configured properly.\r\n extractAppConfig(app);\r\n return {\r\n app: app,\r\n getId: function () { return getId(app); },\r\n getToken: function () { return getToken(app); },\r\n delete: function () { return deleteInstallation$1(app); }\r\n };\r\n };\r\n instance.INTERNAL.registerService(installationsName, factoryMethod);\r\n}\r\nregisterInstallations(firebase);\n\nexport { registerInstallations };\n//# sourceMappingURL=index.esm.js.map\n","import firebase from '@firebase/app';\nimport * as tslib_1 from 'tslib';\nimport { __spread, __awaiter, __generator, __extends, __assign } from 'tslib';\nimport { ErrorFactory, createSubscribe } from '@firebase/util';\n\n/**\r\n * @license\r\n * Copyright 2018 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar _a;\r\nvar ERROR_MAP = (_a = {},\r\n _a[\"only-available-in-window\" /* AVAILABLE_IN_WINDOW */] = 'This method is available in a Window context.',\r\n _a[\"only-available-in-sw\" /* AVAILABLE_IN_SW */] = 'This method is available in a service worker ' + 'context.',\r\n _a[\"should-be-overriden\" /* SHOULD_BE_INHERITED */] = 'This method should be overriden by ' + 'extended classes.',\r\n _a[\"bad-sender-id\" /* BAD_SENDER_ID */] = \"Please ensure that 'messagingSenderId' is set \" +\r\n 'correctly in the options passed into firebase.initializeApp().',\r\n _a[\"permission-default\" /* PERMISSION_DEFAULT */] = 'The required permissions were not granted and ' + 'dismissed instead.',\r\n _a[\"permission-blocked\" /* PERMISSION_BLOCKED */] = 'The required permissions were not granted and ' + 'blocked instead.',\r\n _a[\"unsupported-browser\" /* UNSUPPORTED_BROWSER */] = \"This browser doesn't support the API's \" +\r\n 'required to use the firebase SDK.',\r\n _a[\"notifications-blocked\" /* NOTIFICATIONS_BLOCKED */] = 'Notifications have been blocked.',\r\n _a[\"failed-serviceworker-registration\" /* FAILED_DEFAULT_REGISTRATION */] = 'We are unable to register the ' +\r\n 'default service worker. {$browserErrorMessage}',\r\n _a[\"sw-registration-expected\" /* SW_REGISTRATION_EXPECTED */] = 'A service worker registration was the ' + 'expected input.',\r\n _a[\"get-subscription-failed\" /* GET_SUBSCRIPTION_FAILED */] = 'There was an error when trying to get ' +\r\n 'any existing Push Subscriptions.',\r\n _a[\"invalid-saved-token\" /* INVALID_SAVED_TOKEN */] = 'Unable to access details of the saved token.',\r\n _a[\"sw-reg-redundant\" /* SW_REG_REDUNDANT */] = 'The service worker being used for push was made ' + 'redundant.',\r\n _a[\"token-subscribe-failed\" /* TOKEN_SUBSCRIBE_FAILED */] = 'A problem occured while subscribing the ' + 'user to FCM: {$message}',\r\n _a[\"token-subscribe-no-token\" /* TOKEN_SUBSCRIBE_NO_TOKEN */] = 'FCM returned no token when subscribing ' + 'the user to push.',\r\n _a[\"token-subscribe-no-push-set\" /* TOKEN_SUBSCRIBE_NO_PUSH_SET */] = 'FCM returned an invalid response ' + 'when getting an FCM token.',\r\n _a[\"token-unsubscribe-failed\" /* TOKEN_UNSUBSCRIBE_FAILED */] = 'A problem occured while unsubscribing the ' + 'user from FCM: {$message}',\r\n _a[\"token-update-failed\" /* TOKEN_UPDATE_FAILED */] = 'A problem occured while updating the ' + 'user from FCM: {$message}',\r\n _a[\"token-update-no-token\" /* TOKEN_UPDATE_NO_TOKEN */] = 'FCM returned no token when updating ' + 'the user to push.',\r\n _a[\"use-sw-before-get-token\" /* USE_SW_BEFORE_GET_TOKEN */] = 'The useServiceWorker() method may only be called once and must be ' +\r\n 'called before calling getToken() to ensure your service worker is used.',\r\n _a[\"invalid-delete-token\" /* INVALID_DELETE_TOKEN */] = 'You must pass a valid token into ' +\r\n 'deleteToken(), i.e. the token from getToken().',\r\n _a[\"delete-token-not-found\" /* DELETE_TOKEN_NOT_FOUND */] = 'The deletion attempt for token could not ' +\r\n 'be performed as the token was not found.',\r\n _a[\"delete-scope-not-found\" /* DELETE_SCOPE_NOT_FOUND */] = 'The deletion attempt for service worker ' +\r\n 'scope could not be performed as the scope was not found.',\r\n _a[\"bg-handler-function-expected\" /* BG_HANDLER_FUNCTION_EXPECTED */] = 'The input to ' + 'setBackgroundMessageHandler() must be a function.',\r\n _a[\"no-window-client-to-msg\" /* NO_WINDOW_CLIENT_TO_MSG */] = 'An attempt was made to message a ' + 'non-existant window client.',\r\n _a[\"unable-to-resubscribe\" /* UNABLE_TO_RESUBSCRIBE */] = 'There was an error while re-subscribing ' +\r\n 'the FCM token for push messaging. Will have to resubscribe the ' +\r\n 'user on next visit. {$message}',\r\n _a[\"no-fcm-token-for-resubscribe\" /* NO_FCM_TOKEN_FOR_RESUBSCRIBE */] = 'Could not find an FCM token ' +\r\n 'and as a result, unable to resubscribe. Will have to resubscribe the ' +\r\n 'user on next visit.',\r\n _a[\"failed-to-delete-token\" /* FAILED_TO_DELETE_TOKEN */] = 'Unable to delete the currently saved token.',\r\n _a[\"no-sw-in-reg\" /* NO_SW_IN_REG */] = 'Even though the service worker registration was ' +\r\n 'successful, there was a problem accessing the service worker itself.',\r\n _a[\"incorrect-gcm-sender-id\" /* INCORRECT_GCM_SENDER_ID */] = \"Please change your web app manifest's \" +\r\n \"'gcm_sender_id' value to '103953800507' to use Firebase messaging.\",\r\n _a[\"bad-scope\" /* BAD_SCOPE */] = 'The service worker scope must be a string with at ' +\r\n 'least one character.',\r\n _a[\"bad-vapid-key\" /* BAD_VAPID_KEY */] = 'The public VAPID key is not a Uint8Array with 65 bytes.',\r\n _a[\"bad-subscription\" /* BAD_SUBSCRIPTION */] = 'The subscription must be a valid ' + 'PushSubscription.',\r\n _a[\"bad-token\" /* BAD_TOKEN */] = 'The FCM Token used for storage / lookup was not ' +\r\n 'a valid token string.',\r\n _a[\"bad-push-set\" /* BAD_PUSH_SET */] = 'The FCM push set used for storage / lookup was not ' +\r\n 'not a valid push set string.',\r\n _a[\"failed-delete-vapid-key\" /* FAILED_DELETE_VAPID_KEY */] = 'The VAPID key could not be deleted.',\r\n _a[\"invalid-public-vapid-key\" /* INVALID_PUBLIC_VAPID_KEY */] = 'The public VAPID key must be a string.',\r\n _a[\"use-public-key-before-get-token\" /* USE_PUBLIC_KEY_BEFORE_GET_TOKEN */] = 'The usePublicVapidKey() method may only be called once and must be ' +\r\n 'called before calling getToken() to ensure your VAPID key is used.',\r\n _a[\"public-vapid-key-decryption-failed\" /* PUBLIC_KEY_DECRYPTION_FAILED */] = 'The public VAPID key did not equal ' + '65 bytes when decrypted.',\r\n _a);\r\nvar errorFactory = new ErrorFactory('messaging', 'Messaging', ERROR_MAP);\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar DEFAULT_PUBLIC_VAPID_KEY = new Uint8Array([\r\n 0x04,\r\n 0x33,\r\n 0x94,\r\n 0xf7,\r\n 0xdf,\r\n 0xa1,\r\n 0xeb,\r\n 0xb1,\r\n 0xdc,\r\n 0x03,\r\n 0xa2,\r\n 0x5e,\r\n 0x15,\r\n 0x71,\r\n 0xdb,\r\n 0x48,\r\n 0xd3,\r\n 0x2e,\r\n 0xed,\r\n 0xed,\r\n 0xb2,\r\n 0x34,\r\n 0xdb,\r\n 0xb7,\r\n 0x47,\r\n 0x3a,\r\n 0x0c,\r\n 0x8f,\r\n 0xc4,\r\n 0xcc,\r\n 0xe1,\r\n 0x6f,\r\n 0x3c,\r\n 0x8c,\r\n 0x84,\r\n 0xdf,\r\n 0xab,\r\n 0xb6,\r\n 0x66,\r\n 0x3e,\r\n 0xf2,\r\n 0x0c,\r\n 0xd4,\r\n 0x8b,\r\n 0xfe,\r\n 0xe3,\r\n 0xf9,\r\n 0x76,\r\n 0x2f,\r\n 0x14,\r\n 0x1c,\r\n 0x63,\r\n 0x08,\r\n 0x6a,\r\n 0x6f,\r\n 0x2d,\r\n 0xb1,\r\n 0x1a,\r\n 0x95,\r\n 0xb0,\r\n 0xce,\r\n 0x37,\r\n 0xc0,\r\n 0x9c,\r\n 0x6e\r\n]);\r\nvar ENDPOINT = 'https://fcm.googleapis.com';\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar MessageParameter;\r\n(function (MessageParameter) {\r\n MessageParameter[\"TYPE_OF_MSG\"] = \"firebase-messaging-msg-type\";\r\n MessageParameter[\"DATA\"] = \"firebase-messaging-msg-data\";\r\n})(MessageParameter || (MessageParameter = {}));\r\nvar MessageType;\r\n(function (MessageType) {\r\n MessageType[\"PUSH_MSG_RECEIVED\"] = \"push-msg-received\";\r\n MessageType[\"NOTIFICATION_CLICKED\"] = \"notification-clicked\";\r\n})(MessageType || (MessageType = {}));\n\n/**\r\n * @license\r\n * Copyright 2018 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction isArrayBufferEqual(a, b) {\r\n if (a == null || b == null) {\r\n return false;\r\n }\r\n if (a === b) {\r\n return true;\r\n }\r\n if (a.byteLength !== b.byteLength) {\r\n return false;\r\n }\r\n var viewA = new DataView(a);\r\n var viewB = new DataView(b);\r\n for (var i = 0; i < a.byteLength; i++) {\r\n if (viewA.getUint8(i) !== viewB.getUint8(i)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction toBase64(arrayBuffer) {\r\n var uint8Version = new Uint8Array(arrayBuffer);\r\n return btoa(String.fromCharCode.apply(String, __spread(uint8Version)));\r\n}\r\nfunction arrayBufferToBase64(arrayBuffer) {\r\n var base64String = toBase64(arrayBuffer);\r\n return base64String\r\n .replace(/=/g, '')\r\n .replace(/\\+/g, '-')\r\n .replace(/\\//g, '_');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar IidModel = /** @class */ (function () {\r\n function IidModel() {\r\n }\r\n IidModel.prototype.getToken = function (senderId, subscription, publicVapidKey) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var p256dh, auth, fcmSubscribeBody, applicationPubKey, headers, subscribeOptions, responseData, response, err_1, message;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n p256dh = arrayBufferToBase64(subscription.getKey('p256dh'));\r\n auth = arrayBufferToBase64(subscription.getKey('auth'));\r\n fcmSubscribeBody = \"authorized_entity=\" + senderId + \"&\" +\r\n (\"endpoint=\" + subscription.endpoint + \"&\") +\r\n (\"encryption_key=\" + p256dh + \"&\") +\r\n (\"encryption_auth=\" + auth);\r\n if (!isArrayBufferEqual(publicVapidKey.buffer, DEFAULT_PUBLIC_VAPID_KEY.buffer)) {\r\n applicationPubKey = arrayBufferToBase64(publicVapidKey);\r\n fcmSubscribeBody += \"&application_pub_key=\" + applicationPubKey;\r\n }\r\n headers = new Headers();\r\n headers.append('Content-Type', 'application/x-www-form-urlencoded');\r\n subscribeOptions = {\r\n method: 'POST',\r\n headers: headers,\r\n body: fcmSubscribeBody\r\n };\r\n _a.label = 1;\r\n case 1:\r\n _a.trys.push([1, 4, , 5]);\r\n return [4 /*yield*/, fetch(ENDPOINT + '/fcm/connect/subscribe', subscribeOptions)];\r\n case 2:\r\n response = _a.sent();\r\n return [4 /*yield*/, response.json()];\r\n case 3:\r\n responseData = _a.sent();\r\n return [3 /*break*/, 5];\r\n case 4:\r\n err_1 = _a.sent();\r\n throw errorFactory.create(\"token-subscribe-failed\" /* TOKEN_SUBSCRIBE_FAILED */);\r\n case 5:\r\n if (responseData.error) {\r\n message = responseData.error.message;\r\n throw errorFactory.create(\"token-subscribe-failed\" /* TOKEN_SUBSCRIBE_FAILED */, {\r\n message: message\r\n });\r\n }\r\n if (!responseData.token) {\r\n throw errorFactory.create(\"token-subscribe-no-token\" /* TOKEN_SUBSCRIBE_NO_TOKEN */);\r\n }\r\n if (!responseData.pushSet) {\r\n throw errorFactory.create(\"token-subscribe-no-push-set\" /* TOKEN_SUBSCRIBE_NO_PUSH_SET */);\r\n }\r\n return [2 /*return*/, {\r\n token: responseData.token,\r\n pushSet: responseData.pushSet\r\n }];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * Update the underlying token details for fcmToken.\r\n */\r\n IidModel.prototype.updateToken = function (senderId, fcmToken, fcmPushSet, subscription, publicVapidKey) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var p256dh, auth, fcmUpdateBody, applicationPubKey, headers, updateOptions, responseData, response, err_2, message;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n p256dh = arrayBufferToBase64(subscription.getKey('p256dh'));\r\n auth = arrayBufferToBase64(subscription.getKey('auth'));\r\n fcmUpdateBody = \"push_set=\" + fcmPushSet + \"&\" +\r\n (\"token=\" + fcmToken + \"&\") +\r\n (\"authorized_entity=\" + senderId + \"&\") +\r\n (\"endpoint=\" + subscription.endpoint + \"&\") +\r\n (\"encryption_key=\" + p256dh + \"&\") +\r\n (\"encryption_auth=\" + auth);\r\n if (!isArrayBufferEqual(publicVapidKey.buffer, DEFAULT_PUBLIC_VAPID_KEY.buffer)) {\r\n applicationPubKey = arrayBufferToBase64(publicVapidKey);\r\n fcmUpdateBody += \"&application_pub_key=\" + applicationPubKey;\r\n }\r\n headers = new Headers();\r\n headers.append('Content-Type', 'application/x-www-form-urlencoded');\r\n updateOptions = {\r\n method: 'POST',\r\n headers: headers,\r\n body: fcmUpdateBody\r\n };\r\n _a.label = 1;\r\n case 1:\r\n _a.trys.push([1, 4, , 5]);\r\n return [4 /*yield*/, fetch(ENDPOINT + '/fcm/connect/subscribe', updateOptions)];\r\n case 2:\r\n response = _a.sent();\r\n return [4 /*yield*/, response.json()];\r\n case 3:\r\n responseData = _a.sent();\r\n return [3 /*break*/, 5];\r\n case 4:\r\n err_2 = _a.sent();\r\n throw errorFactory.create(\"token-update-failed\" /* TOKEN_UPDATE_FAILED */);\r\n case 5:\r\n if (responseData.error) {\r\n message = responseData.error.message;\r\n throw errorFactory.create(\"token-update-failed\" /* TOKEN_UPDATE_FAILED */, {\r\n message: message\r\n });\r\n }\r\n if (!responseData.token) {\r\n throw errorFactory.create(\"token-update-no-token\" /* TOKEN_UPDATE_NO_TOKEN */);\r\n }\r\n return [2 /*return*/, responseData.token];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * Given a fcmToken, pushSet and messagingSenderId, delete an FCM token.\r\n */\r\n IidModel.prototype.deleteToken = function (senderId, fcmToken, fcmPushSet) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var fcmUnsubscribeBody, headers, unsubscribeOptions, response, responseData, message, err_3;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n fcmUnsubscribeBody = \"authorized_entity=\" + senderId + \"&\" +\r\n (\"token=\" + fcmToken + \"&\") +\r\n (\"pushSet=\" + fcmPushSet);\r\n headers = new Headers();\r\n headers.append('Content-Type', 'application/x-www-form-urlencoded');\r\n unsubscribeOptions = {\r\n method: 'POST',\r\n headers: headers,\r\n body: fcmUnsubscribeBody\r\n };\r\n _a.label = 1;\r\n case 1:\r\n _a.trys.push([1, 4, , 5]);\r\n return [4 /*yield*/, fetch(ENDPOINT + '/fcm/connect/unsubscribe', unsubscribeOptions)];\r\n case 2:\r\n response = _a.sent();\r\n return [4 /*yield*/, response.json()];\r\n case 3:\r\n responseData = _a.sent();\r\n if (responseData.error) {\r\n message = responseData.error.message;\r\n throw errorFactory.create(\"token-unsubscribe-failed\" /* TOKEN_UNSUBSCRIBE_FAILED */, {\r\n message: message\r\n });\r\n }\r\n return [3 /*break*/, 5];\r\n case 4:\r\n err_3 = _a.sent();\r\n throw errorFactory.create(\"token-unsubscribe-failed\" /* TOKEN_UNSUBSCRIBE_FAILED */);\r\n case 5: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n return IidModel;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction base64ToArrayBuffer(base64String) {\r\n var padding = '='.repeat((4 - (base64String.length % 4)) % 4);\r\n var base64 = (base64String + padding)\r\n .replace(/\\-/g, '+')\r\n .replace(/_/g, '/');\r\n var rawData = atob(base64);\r\n var outputArray = new Uint8Array(rawData.length);\r\n for (var i = 0; i < rawData.length; ++i) {\r\n outputArray[i] = rawData.charCodeAt(i);\r\n }\r\n return outputArray;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar OLD_DB_NAME = 'undefined';\r\nvar OLD_OBJECT_STORE_NAME = 'fcm_token_object_Store';\r\nfunction handleDb(db) {\r\n if (!db.objectStoreNames.contains(OLD_OBJECT_STORE_NAME)) {\r\n // We found a database with the name 'undefined', but our expected object\r\n // store isn't defined.\r\n return;\r\n }\r\n var transaction = db.transaction(OLD_OBJECT_STORE_NAME);\r\n var objectStore = transaction.objectStore(OLD_OBJECT_STORE_NAME);\r\n var iidModel = new IidModel();\r\n var openCursorRequest = objectStore.openCursor();\r\n openCursorRequest.onerror = function (event) {\r\n // NOOP - Nothing we can do.\r\n console.warn('Unable to cleanup old IDB.', event);\r\n };\r\n openCursorRequest.onsuccess = function () {\r\n var cursor = openCursorRequest.result;\r\n if (cursor) {\r\n // cursor.value contains the current record being iterated through\r\n // this is where you'd do something with the result\r\n var tokenDetails = cursor.value;\r\n iidModel.deleteToken(tokenDetails.fcmSenderId, tokenDetails.fcmToken, tokenDetails.fcmPushSet);\r\n cursor.continue();\r\n }\r\n else {\r\n db.close();\r\n indexedDB.deleteDatabase(OLD_DB_NAME);\r\n }\r\n };\r\n}\r\nfunction cleanV1() {\r\n var request = indexedDB.open(OLD_DB_NAME);\r\n request.onerror = function (event) {\r\n // NOOP - Nothing we can do.\r\n };\r\n request.onsuccess = function (event) {\r\n var db = request.result;\r\n handleDb(db);\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar DbInterface = /** @class */ (function () {\r\n function DbInterface() {\r\n this.dbPromise = null;\r\n }\r\n /** Gets record(s) from the objectStore that match the given key. */\r\n DbInterface.prototype.get = function (key) {\r\n return this.createTransaction(function (objectStore) { return objectStore.get(key); });\r\n };\r\n /** Gets record(s) from the objectStore that match the given index. */\r\n DbInterface.prototype.getIndex = function (index, key) {\r\n function runRequest(objectStore) {\r\n var idbIndex = objectStore.index(index);\r\n return idbIndex.get(key);\r\n }\r\n return this.createTransaction(runRequest);\r\n };\r\n /** Assigns or overwrites the record for the given value. */\r\n // tslint:disable-next-line:no-any IndexedDB values are of type \"any\"\r\n DbInterface.prototype.put = function (value) {\r\n return this.createTransaction(function (objectStore) { return objectStore.put(value); }, 'readwrite');\r\n };\r\n /** Deletes record(s) from the objectStore that match the given key. */\r\n DbInterface.prototype.delete = function (key) {\r\n return this.createTransaction(function (objectStore) { return objectStore.delete(key); }, 'readwrite');\r\n };\r\n /**\r\n * Close the currently open database.\r\n */\r\n DbInterface.prototype.closeDatabase = function () {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var db;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (!this.dbPromise) return [3 /*break*/, 2];\r\n return [4 /*yield*/, this.dbPromise];\r\n case 1:\r\n db = _a.sent();\r\n db.close();\r\n this.dbPromise = null;\r\n _a.label = 2;\r\n case 2: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * Creates an IndexedDB Transaction and passes its objectStore to the\r\n * runRequest function, which runs the database request.\r\n *\r\n * @return Promise that resolves with the result of the runRequest function\r\n */\r\n DbInterface.prototype.createTransaction = function (runRequest, mode) {\r\n if (mode === void 0) { mode = 'readonly'; }\r\n return __awaiter(this, void 0, void 0, function () {\r\n var db, transaction, request, result;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, this.getDb()];\r\n case 1:\r\n db = _a.sent();\r\n transaction = db.transaction(this.objectStoreName, mode);\r\n request = transaction.objectStore(this.objectStoreName);\r\n return [4 /*yield*/, promisify(runRequest(request))];\r\n case 2:\r\n result = _a.sent();\r\n return [2 /*return*/, new Promise(function (resolve, reject) {\r\n transaction.oncomplete = function () {\r\n resolve(result);\r\n };\r\n transaction.onerror = function () {\r\n reject(transaction.error);\r\n };\r\n })];\r\n }\r\n });\r\n });\r\n };\r\n /** Gets the cached db connection or opens a new one. */\r\n DbInterface.prototype.getDb = function () {\r\n var _this = this;\r\n if (!this.dbPromise) {\r\n this.dbPromise = new Promise(function (resolve, reject) {\r\n var request = indexedDB.open(_this.dbName, _this.dbVersion);\r\n request.onsuccess = function () {\r\n resolve(request.result);\r\n };\r\n request.onerror = function () {\r\n _this.dbPromise = null;\r\n reject(request.error);\r\n };\r\n request.onupgradeneeded = function (event) { return _this.onDbUpgrade(request, event); };\r\n });\r\n }\r\n return this.dbPromise;\r\n };\r\n return DbInterface;\r\n}());\r\n/** Promisifies an IDBRequest. Resolves with the IDBRequest's result. */\r\nfunction promisify(request) {\r\n return new Promise(function (resolve, reject) {\r\n request.onsuccess = function () {\r\n resolve(request.result);\r\n };\r\n request.onerror = function () {\r\n reject(request.error);\r\n };\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar TokenDetailsModel = /** @class */ (function (_super) {\r\n __extends(TokenDetailsModel, _super);\r\n function TokenDetailsModel() {\r\n var _this = _super !== null && _super.apply(this, arguments) || this;\r\n _this.dbName = 'fcm_token_details_db';\r\n _this.dbVersion = 3;\r\n _this.objectStoreName = 'fcm_token_object_Store';\r\n return _this;\r\n }\r\n TokenDetailsModel.prototype.onDbUpgrade = function (request, event) {\r\n var db = request.result;\r\n // Lack of 'break' statements is intentional.\r\n switch (event.oldVersion) {\r\n case 0: {\r\n // New IDB instance\r\n var objectStore = db.createObjectStore(this.objectStoreName, {\r\n keyPath: 'swScope'\r\n });\r\n // Make sure the sender ID can be searched\r\n objectStore.createIndex('fcmSenderId', 'fcmSenderId', {\r\n unique: false\r\n });\r\n objectStore.createIndex('fcmToken', 'fcmToken', { unique: true });\r\n }\r\n case 1: {\r\n // Prior to version 2, we were using either 'fcm_token_details_db'\r\n // or 'undefined' as the database name due to bug in the SDK\r\n // So remove the old tokens and databases.\r\n cleanV1();\r\n }\r\n case 2: {\r\n var objectStore = request.transaction.objectStore(this.objectStoreName);\r\n var cursorRequest_1 = objectStore.openCursor();\r\n cursorRequest_1.onsuccess = function () {\r\n var cursor = cursorRequest_1.result;\r\n if (cursor) {\r\n var value = cursor.value;\r\n var newValue = __assign({}, value);\r\n if (!value.createTime) {\r\n newValue.createTime = Date.now();\r\n }\r\n if (typeof value.vapidKey === 'string') {\r\n newValue.vapidKey = base64ToArrayBuffer(value.vapidKey);\r\n }\r\n if (typeof value.auth === 'string') {\r\n newValue.auth = base64ToArrayBuffer(value.auth).buffer;\r\n }\r\n if (typeof value.auth === 'string') {\r\n newValue.p256dh = base64ToArrayBuffer(value.p256dh).buffer;\r\n }\r\n cursor.update(newValue);\r\n cursor.continue();\r\n }\r\n };\r\n }\r\n }\r\n };\r\n /**\r\n * Given a token, this method will look up the details in indexedDB.\r\n */\r\n TokenDetailsModel.prototype.getTokenDetailsFromToken = function (fcmToken) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n return __generator(this, function (_a) {\r\n if (!fcmToken) {\r\n throw errorFactory.create(\"bad-token\" /* BAD_TOKEN */);\r\n }\r\n validateInputs({ fcmToken: fcmToken });\r\n return [2 /*return*/, this.getIndex('fcmToken', fcmToken)];\r\n });\r\n });\r\n };\r\n /**\r\n * Given a service worker scope, this method will look up the details in\r\n * indexedDB.\r\n * @return The details associated with that token.\r\n */\r\n TokenDetailsModel.prototype.getTokenDetailsFromSWScope = function (swScope) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n return __generator(this, function (_a) {\r\n if (!swScope) {\r\n throw errorFactory.create(\"bad-scope\" /* BAD_SCOPE */);\r\n }\r\n validateInputs({ swScope: swScope });\r\n return [2 /*return*/, this.get(swScope)];\r\n });\r\n });\r\n };\r\n /**\r\n * Save the details for the fcm token for re-use at a later date.\r\n * @param input A plain js object containing args to save.\r\n */\r\n TokenDetailsModel.prototype.saveTokenDetails = function (tokenDetails) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n return __generator(this, function (_a) {\r\n if (!tokenDetails.swScope) {\r\n throw errorFactory.create(\"bad-scope\" /* BAD_SCOPE */);\r\n }\r\n if (!tokenDetails.vapidKey) {\r\n throw errorFactory.create(\"bad-vapid-key\" /* BAD_VAPID_KEY */);\r\n }\r\n if (!tokenDetails.endpoint || !tokenDetails.auth || !tokenDetails.p256dh) {\r\n throw errorFactory.create(\"bad-subscription\" /* BAD_SUBSCRIPTION */);\r\n }\r\n if (!tokenDetails.fcmSenderId) {\r\n throw errorFactory.create(\"bad-sender-id\" /* BAD_SENDER_ID */);\r\n }\r\n if (!tokenDetails.fcmToken) {\r\n throw errorFactory.create(\"bad-token\" /* BAD_TOKEN */);\r\n }\r\n if (!tokenDetails.fcmPushSet) {\r\n throw errorFactory.create(\"bad-push-set\" /* BAD_PUSH_SET */);\r\n }\r\n validateInputs(tokenDetails);\r\n return [2 /*return*/, this.put(tokenDetails)];\r\n });\r\n });\r\n };\r\n /**\r\n * This method deletes details of the current FCM token.\r\n * It's returning a promise in case we need to move to an async\r\n * method for deleting at a later date.\r\n *\r\n * @return Resolves once the FCM token details have been deleted and returns\r\n * the deleted details.\r\n */\r\n TokenDetailsModel.prototype.deleteToken = function (token) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var details;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (typeof token !== 'string' || token.length === 0) {\r\n return [2 /*return*/, Promise.reject(errorFactory.create(\"invalid-delete-token\" /* INVALID_DELETE_TOKEN */))];\r\n }\r\n return [4 /*yield*/, this.getTokenDetailsFromToken(token)];\r\n case 1:\r\n details = _a.sent();\r\n if (!details) {\r\n throw errorFactory.create(\"delete-token-not-found\" /* DELETE_TOKEN_NOT_FOUND */);\r\n }\r\n return [4 /*yield*/, this.delete(details.swScope)];\r\n case 2:\r\n _a.sent();\r\n return [2 /*return*/, details];\r\n }\r\n });\r\n });\r\n };\r\n return TokenDetailsModel;\r\n}(DbInterface));\r\n/**\r\n * This method takes an object and will check for known arguments and\r\n * validate the input.\r\n * @return Promise that resolves if input is valid, rejects otherwise.\r\n */\r\nfunction validateInputs(input) {\r\n if (input.fcmToken) {\r\n if (typeof input.fcmToken !== 'string' || input.fcmToken.length === 0) {\r\n throw errorFactory.create(\"bad-token\" /* BAD_TOKEN */);\r\n }\r\n }\r\n if (input.swScope) {\r\n if (typeof input.swScope !== 'string' || input.swScope.length === 0) {\r\n throw errorFactory.create(\"bad-scope\" /* BAD_SCOPE */);\r\n }\r\n }\r\n if (input.vapidKey) {\r\n if (!(input.vapidKey instanceof Uint8Array) ||\r\n input.vapidKey.length !== 65) {\r\n throw errorFactory.create(\"bad-vapid-key\" /* BAD_VAPID_KEY */);\r\n }\r\n }\r\n if (input.endpoint) {\r\n if (typeof input.endpoint !== 'string' || input.endpoint.length === 0) {\r\n throw errorFactory.create(\"bad-subscription\" /* BAD_SUBSCRIPTION */);\r\n }\r\n }\r\n if (input.auth) {\r\n if (!(input.auth instanceof ArrayBuffer)) {\r\n throw errorFactory.create(\"bad-subscription\" /* BAD_SUBSCRIPTION */);\r\n }\r\n }\r\n if (input.p256dh) {\r\n if (!(input.p256dh instanceof ArrayBuffer)) {\r\n throw errorFactory.create(\"bad-subscription\" /* BAD_SUBSCRIPTION */);\r\n }\r\n }\r\n if (input.fcmSenderId) {\r\n if (typeof input.fcmSenderId !== 'string' ||\r\n input.fcmSenderId.length === 0) {\r\n throw errorFactory.create(\"bad-sender-id\" /* BAD_SENDER_ID */);\r\n }\r\n }\r\n if (input.fcmPushSet) {\r\n if (typeof input.fcmPushSet !== 'string' || input.fcmPushSet.length === 0) {\r\n throw errorFactory.create(\"bad-push-set\" /* BAD_PUSH_SET */);\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar UNCOMPRESSED_PUBLIC_KEY_SIZE = 65;\r\nvar VapidDetailsModel = /** @class */ (function (_super) {\r\n __extends(VapidDetailsModel, _super);\r\n function VapidDetailsModel() {\r\n var _this = _super !== null && _super.apply(this, arguments) || this;\r\n _this.dbName = 'fcm_vapid_details_db';\r\n _this.dbVersion = 1;\r\n _this.objectStoreName = 'fcm_vapid_object_Store';\r\n return _this;\r\n }\r\n VapidDetailsModel.prototype.onDbUpgrade = function (request) {\r\n var db = request.result;\r\n db.createObjectStore(this.objectStoreName, { keyPath: 'swScope' });\r\n };\r\n /**\r\n * Given a service worker scope, this method will look up the vapid key\r\n * in indexedDB.\r\n */\r\n VapidDetailsModel.prototype.getVapidFromSWScope = function (swScope) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var result;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (typeof swScope !== 'string' || swScope.length === 0) {\r\n throw errorFactory.create(\"bad-scope\" /* BAD_SCOPE */);\r\n }\r\n return [4 /*yield*/, this.get(swScope)];\r\n case 1:\r\n result = _a.sent();\r\n return [2 /*return*/, result ? result.vapidKey : undefined];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * Save a vapid key against a swScope for later date.\r\n */\r\n VapidDetailsModel.prototype.saveVapidDetails = function (swScope, vapidKey) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var details;\r\n return __generator(this, function (_a) {\r\n if (typeof swScope !== 'string' || swScope.length === 0) {\r\n throw errorFactory.create(\"bad-scope\" /* BAD_SCOPE */);\r\n }\r\n if (vapidKey === null || vapidKey.length !== UNCOMPRESSED_PUBLIC_KEY_SIZE) {\r\n throw errorFactory.create(\"bad-vapid-key\" /* BAD_VAPID_KEY */);\r\n }\r\n details = {\r\n swScope: swScope,\r\n vapidKey: vapidKey\r\n };\r\n return [2 /*return*/, this.put(details)];\r\n });\r\n });\r\n };\r\n /**\r\n * This method deletes details of the current FCM VAPID key for a SW scope.\r\n * Resolves once the scope/vapid details have been deleted and returns the\r\n * deleted vapid key.\r\n */\r\n VapidDetailsModel.prototype.deleteVapidDetails = function (swScope) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var vapidKey;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, this.getVapidFromSWScope(swScope)];\r\n case 1:\r\n vapidKey = _a.sent();\r\n if (!vapidKey) {\r\n throw errorFactory.create(\"delete-scope-not-found\" /* DELETE_SCOPE_NOT_FOUND */);\r\n }\r\n return [4 /*yield*/, this.delete(swScope)];\r\n case 2:\r\n _a.sent();\r\n return [2 /*return*/, vapidKey];\r\n }\r\n });\r\n });\r\n };\r\n return VapidDetailsModel;\r\n}(DbInterface));\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar SENDER_ID_OPTION_NAME = 'messagingSenderId';\r\n// Database cache should be invalidated once a week.\r\nvar TOKEN_EXPIRATION_MILLIS = 7 * 24 * 60 * 60 * 1000; // 7 days\r\nvar BaseController = /** @class */ (function () {\r\n /**\r\n * An interface of the Messaging Service API\r\n */\r\n function BaseController(app) {\r\n var _this = this;\r\n if (!app.options[SENDER_ID_OPTION_NAME] ||\r\n typeof app.options[SENDER_ID_OPTION_NAME] !== 'string') {\r\n throw errorFactory.create(\"bad-sender-id\" /* BAD_SENDER_ID */);\r\n }\r\n this.messagingSenderId = app.options[SENDER_ID_OPTION_NAME];\r\n this.tokenDetailsModel = new TokenDetailsModel();\r\n this.vapidDetailsModel = new VapidDetailsModel();\r\n this.iidModel = new IidModel();\r\n this.app = app;\r\n this.INTERNAL = {\r\n delete: function () { return _this.delete(); }\r\n };\r\n }\r\n /**\r\n * @export\r\n */\r\n BaseController.prototype.getToken = function () {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var currentPermission, swReg, publicVapidKey, pushSubscription, tokenDetails;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n currentPermission = this.getNotificationPermission_();\r\n if (currentPermission === 'denied') {\r\n throw errorFactory.create(\"notifications-blocked\" /* NOTIFICATIONS_BLOCKED */);\r\n }\r\n else if (currentPermission !== 'granted') {\r\n // We must wait for permission to be granted\r\n return [2 /*return*/, null];\r\n }\r\n return [4 /*yield*/, this.getSWRegistration_()];\r\n case 1:\r\n swReg = _a.sent();\r\n return [4 /*yield*/, this.getPublicVapidKey_()];\r\n case 2:\r\n publicVapidKey = _a.sent();\r\n return [4 /*yield*/, this.getPushSubscription(swReg, publicVapidKey)];\r\n case 3:\r\n pushSubscription = _a.sent();\r\n return [4 /*yield*/, this.tokenDetailsModel.getTokenDetailsFromSWScope(swReg.scope)];\r\n case 4:\r\n tokenDetails = _a.sent();\r\n if (tokenDetails) {\r\n return [2 /*return*/, this.manageExistingToken(swReg, pushSubscription, publicVapidKey, tokenDetails)];\r\n }\r\n return [2 /*return*/, this.getNewToken(swReg, pushSubscription, publicVapidKey)];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * manageExistingToken is triggered if there's an existing FCM token in the\r\n * database and it can take 3 different actions:\r\n * 1) Retrieve the existing FCM token from the database.\r\n * 2) If VAPID details have changed: Delete the existing token and create a\r\n * new one with the new VAPID key.\r\n * 3) If the database cache is invalidated: Send a request to FCM to update\r\n * the token, and to check if the token is still valid on FCM-side.\r\n */\r\n BaseController.prototype.manageExistingToken = function (swReg, pushSubscription, publicVapidKey, tokenDetails) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var isTokenValid, now;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n isTokenValid = isTokenStillValid(pushSubscription, publicVapidKey, tokenDetails);\r\n if (isTokenValid) {\r\n now = Date.now();\r\n if (now < tokenDetails.createTime + TOKEN_EXPIRATION_MILLIS) {\r\n return [2 /*return*/, tokenDetails.fcmToken];\r\n }\r\n else {\r\n return [2 /*return*/, this.updateToken(swReg, pushSubscription, publicVapidKey, tokenDetails)];\r\n }\r\n }\r\n // If the token is no longer valid (for example if the VAPID details\r\n // have changed), delete the existing token from the FCM client and server\r\n // database. No need to unsubscribe from the Service Worker as we have a\r\n // good push subscription that we'd like to use in getNewToken.\r\n return [4 /*yield*/, this.deleteTokenFromDB(tokenDetails.fcmToken)];\r\n case 1:\r\n // If the token is no longer valid (for example if the VAPID details\r\n // have changed), delete the existing token from the FCM client and server\r\n // database. No need to unsubscribe from the Service Worker as we have a\r\n // good push subscription that we'd like to use in getNewToken.\r\n _a.sent();\r\n return [2 /*return*/, this.getNewToken(swReg, pushSubscription, publicVapidKey)];\r\n }\r\n });\r\n });\r\n };\r\n BaseController.prototype.updateToken = function (swReg, pushSubscription, publicVapidKey, tokenDetails) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var updatedToken, allDetails, e_1;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n _a.trys.push([0, 4, , 6]);\r\n return [4 /*yield*/, this.iidModel.updateToken(this.messagingSenderId, tokenDetails.fcmToken, tokenDetails.fcmPushSet, pushSubscription, publicVapidKey)];\r\n case 1:\r\n updatedToken = _a.sent();\r\n allDetails = {\r\n swScope: swReg.scope,\r\n vapidKey: publicVapidKey,\r\n fcmSenderId: this.messagingSenderId,\r\n fcmToken: updatedToken,\r\n fcmPushSet: tokenDetails.fcmPushSet,\r\n createTime: Date.now(),\r\n endpoint: pushSubscription.endpoint,\r\n auth: pushSubscription.getKey('auth'),\r\n p256dh: pushSubscription.getKey('p256dh')\r\n };\r\n return [4 /*yield*/, this.tokenDetailsModel.saveTokenDetails(allDetails)];\r\n case 2:\r\n _a.sent();\r\n return [4 /*yield*/, this.vapidDetailsModel.saveVapidDetails(swReg.scope, publicVapidKey)];\r\n case 3:\r\n _a.sent();\r\n return [2 /*return*/, updatedToken];\r\n case 4:\r\n e_1 = _a.sent();\r\n return [4 /*yield*/, this.deleteToken(tokenDetails.fcmToken)];\r\n case 5:\r\n _a.sent();\r\n throw e_1;\r\n case 6: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n BaseController.prototype.getNewToken = function (swReg, pushSubscription, publicVapidKey) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var tokenDetails, allDetails;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, this.iidModel.getToken(this.messagingSenderId, pushSubscription, publicVapidKey)];\r\n case 1:\r\n tokenDetails = _a.sent();\r\n allDetails = {\r\n swScope: swReg.scope,\r\n vapidKey: publicVapidKey,\r\n fcmSenderId: this.messagingSenderId,\r\n fcmToken: tokenDetails.token,\r\n fcmPushSet: tokenDetails.pushSet,\r\n createTime: Date.now(),\r\n endpoint: pushSubscription.endpoint,\r\n auth: pushSubscription.getKey('auth'),\r\n p256dh: pushSubscription.getKey('p256dh')\r\n };\r\n return [4 /*yield*/, this.tokenDetailsModel.saveTokenDetails(allDetails)];\r\n case 2:\r\n _a.sent();\r\n return [4 /*yield*/, this.vapidDetailsModel.saveVapidDetails(swReg.scope, publicVapidKey)];\r\n case 3:\r\n _a.sent();\r\n return [2 /*return*/, tokenDetails.token];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * This method deletes tokens that the token manager looks after,\r\n * unsubscribes the token from FCM and then unregisters the push\r\n * subscription if it exists. It returns a promise that indicates\r\n * whether or not the unsubscribe request was processed successfully.\r\n */\r\n BaseController.prototype.deleteToken = function (token) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var registration, pushSubscription;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: \r\n // Delete the token details from the database.\r\n return [4 /*yield*/, this.deleteTokenFromDB(token)];\r\n case 1:\r\n // Delete the token details from the database.\r\n _a.sent();\r\n return [4 /*yield*/, this.getSWRegistration_()];\r\n case 2:\r\n registration = _a.sent();\r\n if (!registration) return [3 /*break*/, 4];\r\n return [4 /*yield*/, registration.pushManager.getSubscription()];\r\n case 3:\r\n pushSubscription = _a.sent();\r\n if (pushSubscription) {\r\n return [2 /*return*/, pushSubscription.unsubscribe()];\r\n }\r\n _a.label = 4;\r\n case 4: \r\n // If there's no SW, consider it a success.\r\n return [2 /*return*/, true];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * This method will delete the token from the client database, and make a\r\n * call to FCM to remove it from the server DB. Does not temper with the\r\n * push subscription.\r\n */\r\n BaseController.prototype.deleteTokenFromDB = function (token) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var details;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, this.tokenDetailsModel.deleteToken(token)];\r\n case 1:\r\n details = _a.sent();\r\n return [4 /*yield*/, this.iidModel.deleteToken(details.fcmSenderId, details.fcmToken, details.fcmPushSet)];\r\n case 2:\r\n _a.sent();\r\n return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * Gets a PushSubscription for the current user.\r\n */\r\n BaseController.prototype.getPushSubscription = function (swRegistration, publicVapidKey) {\r\n return swRegistration.pushManager.getSubscription().then(function (subscription) {\r\n if (subscription) {\r\n return subscription;\r\n }\r\n return swRegistration.pushManager.subscribe({\r\n userVisibleOnly: true,\r\n applicationServerKey: publicVapidKey\r\n });\r\n });\r\n };\r\n //\r\n // The following methods should only be available in the window.\r\n //\r\n BaseController.prototype.requestPermission = function () {\r\n throw errorFactory.create(\"only-available-in-window\" /* AVAILABLE_IN_WINDOW */);\r\n };\r\n BaseController.prototype.useServiceWorker = function (registration) {\r\n throw errorFactory.create(\"only-available-in-window\" /* AVAILABLE_IN_WINDOW */);\r\n };\r\n BaseController.prototype.usePublicVapidKey = function (b64PublicKey) {\r\n throw errorFactory.create(\"only-available-in-window\" /* AVAILABLE_IN_WINDOW */);\r\n };\r\n BaseController.prototype.onMessage = function (nextOrObserver, error, completed) {\r\n throw errorFactory.create(\"only-available-in-window\" /* AVAILABLE_IN_WINDOW */);\r\n };\r\n BaseController.prototype.onTokenRefresh = function (nextOrObserver, error, completed) {\r\n throw errorFactory.create(\"only-available-in-window\" /* AVAILABLE_IN_WINDOW */);\r\n };\r\n //\r\n // The following methods are used by the service worker only.\r\n //\r\n BaseController.prototype.setBackgroundMessageHandler = function (callback) {\r\n throw errorFactory.create(\"only-available-in-sw\" /* AVAILABLE_IN_SW */);\r\n };\r\n //\r\n // The following methods are used by the service themselves and not exposed\r\n // publicly or not expected to be used by developers.\r\n //\r\n /**\r\n * This method is required to adhere to the Firebase interface.\r\n * It closes any currently open indexdb database connections.\r\n */\r\n BaseController.prototype.delete = function () {\r\n return __awaiter(this, void 0, void 0, function () {\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, Promise.all([\r\n this.tokenDetailsModel.closeDatabase(),\r\n this.vapidDetailsModel.closeDatabase()\r\n ])];\r\n case 1:\r\n _a.sent();\r\n return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * Returns the current Notification Permission state.\r\n */\r\n BaseController.prototype.getNotificationPermission_ = function () {\r\n // TODO: Remove the cast when this issue is fixed:\r\n // https://github.com/Microsoft/TypeScript/issues/14701\r\n // tslint:disable-next-line no-any\r\n return Notification.permission;\r\n };\r\n BaseController.prototype.getTokenDetailsModel = function () {\r\n return this.tokenDetailsModel;\r\n };\r\n BaseController.prototype.getVapidDetailsModel = function () {\r\n return this.vapidDetailsModel;\r\n };\r\n // Visible for testing\r\n // TODO: make protected\r\n BaseController.prototype.getIidModel = function () {\r\n return this.iidModel;\r\n };\r\n return BaseController;\r\n}());\r\n/**\r\n * Checks if the tokenDetails match the details provided in the clients.\r\n */\r\nfunction isTokenStillValid(pushSubscription, publicVapidKey, tokenDetails) {\r\n if (!tokenDetails.vapidKey ||\r\n !isArrayBufferEqual(publicVapidKey.buffer, tokenDetails.vapidKey.buffer)) {\r\n return false;\r\n }\r\n var isEndpointEqual = pushSubscription.endpoint === tokenDetails.endpoint;\r\n var isAuthEqual = isArrayBufferEqual(pushSubscription.getKey('auth'), tokenDetails.auth);\r\n var isP256dhEqual = isArrayBufferEqual(pushSubscription.getKey('p256dh'), tokenDetails.p256dh);\r\n return isEndpointEqual && isAuthEqual && isP256dhEqual;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar FCM_MSG = 'FCM_MSG';\r\nvar SwController = /** @class */ (function (_super) {\r\n __extends(SwController, _super);\r\n function SwController(app) {\r\n var _this = _super.call(this, app) || this;\r\n _this.bgMessageHandler = null;\r\n self.addEventListener('push', function (e) {\r\n _this.onPush(e);\r\n });\r\n self.addEventListener('pushsubscriptionchange', function (e) {\r\n _this.onSubChange(e);\r\n });\r\n self.addEventListener('notificationclick', function (e) {\r\n _this.onNotificationClick(e);\r\n });\r\n return _this;\r\n }\r\n // Visible for testing\r\n // TODO: Make private\r\n SwController.prototype.onPush = function (event) {\r\n event.waitUntil(this.onPush_(event));\r\n };\r\n // Visible for testing\r\n // TODO: Make private\r\n SwController.prototype.onSubChange = function (event) {\r\n event.waitUntil(this.onSubChange_(event));\r\n };\r\n // Visible for testing\r\n // TODO: Make private\r\n SwController.prototype.onNotificationClick = function (event) {\r\n event.waitUntil(this.onNotificationClick_(event));\r\n };\r\n /**\r\n * A handler for push events that shows notifications based on the content of\r\n * the payload.\r\n *\r\n * The payload must be a JSON-encoded Object with a `notification` key. The\r\n * value of the `notification` property will be used as the NotificationOptions\r\n * object passed to showNotification. Additionally, the `title` property of the\r\n * notification object will be used as the title.\r\n *\r\n * If there is no notification data in the payload then no notification will be\r\n * shown.\r\n */\r\n SwController.prototype.onPush_ = function (event) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var msgPayload, hasVisibleClients, notificationDetails, notificationTitle, reg, actions, maxActions;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (!event.data) {\r\n return [2 /*return*/];\r\n }\r\n try {\r\n msgPayload = event.data.json();\r\n }\r\n catch (err) {\r\n // Not JSON so not an FCM message\r\n return [2 /*return*/];\r\n }\r\n return [4 /*yield*/, this.hasVisibleClients_()];\r\n case 1:\r\n hasVisibleClients = _a.sent();\r\n if (hasVisibleClients) {\r\n // App in foreground. Send to page.\r\n return [2 /*return*/, this.sendMessageToWindowClients_(msgPayload)];\r\n }\r\n notificationDetails = this.getNotificationData_(msgPayload);\r\n if (!notificationDetails) return [3 /*break*/, 3];\r\n notificationTitle = notificationDetails.title || '';\r\n return [4 /*yield*/, this.getSWRegistration_()];\r\n case 2:\r\n reg = _a.sent();\r\n actions = notificationDetails.actions;\r\n maxActions = Notification.maxActions;\r\n // tslint:enable no-any\r\n if (actions && maxActions && actions.length > maxActions) {\r\n console.warn(\"This browser only supports \" + maxActions + \" actions.\" +\r\n \"The remaining actions will not be displayed.\");\r\n }\r\n return [2 /*return*/, reg.showNotification(notificationTitle, notificationDetails)];\r\n case 3:\r\n if (!this.bgMessageHandler) return [3 /*break*/, 5];\r\n return [4 /*yield*/, this.bgMessageHandler(msgPayload)];\r\n case 4:\r\n _a.sent();\r\n return [2 /*return*/];\r\n case 5: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n SwController.prototype.onSubChange_ = function (event) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var registration, err_1, err_2, tokenDetailsModel, tokenDetails;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n _a.trys.push([0, 2, , 3]);\r\n return [4 /*yield*/, this.getSWRegistration_()];\r\n case 1:\r\n registration = _a.sent();\r\n return [3 /*break*/, 3];\r\n case 2:\r\n err_1 = _a.sent();\r\n throw errorFactory.create(\"unable-to-resubscribe\" /* UNABLE_TO_RESUBSCRIBE */, {\r\n message: err_1\r\n });\r\n case 3:\r\n _a.trys.push([3, 5, , 8]);\r\n return [4 /*yield*/, registration.pushManager.getSubscription()];\r\n case 4:\r\n _a.sent();\r\n return [3 /*break*/, 8];\r\n case 5:\r\n err_2 = _a.sent();\r\n tokenDetailsModel = this.getTokenDetailsModel();\r\n return [4 /*yield*/, tokenDetailsModel.getTokenDetailsFromSWScope(registration.scope)];\r\n case 6:\r\n tokenDetails = _a.sent();\r\n if (!tokenDetails) {\r\n // This should rarely occure, but could if indexedDB\r\n // is corrupted or wiped\r\n throw err_2;\r\n }\r\n // Attempt to delete the token if we know it's bad\r\n return [4 /*yield*/, this.deleteToken(tokenDetails.fcmToken)];\r\n case 7:\r\n // Attempt to delete the token if we know it's bad\r\n _a.sent();\r\n throw err_2;\r\n case 8: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n SwController.prototype.onNotificationClick_ = function (event) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var msgPayload, link, windowClient, internalMsg;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (!event.notification ||\r\n !event.notification.data ||\r\n !event.notification.data[FCM_MSG]) {\r\n // Not an FCM notification, do nothing.\r\n return [2 /*return*/];\r\n }\r\n else if (event.action) {\r\n // User clicked on an action button.\r\n // This will allow devs to act on action button clicks by using a custom\r\n // onNotificationClick listener that they define.\r\n return [2 /*return*/];\r\n }\r\n // Prevent other listeners from receiving the event\r\n event.stopImmediatePropagation();\r\n event.notification.close();\r\n msgPayload = event.notification.data[FCM_MSG];\r\n if (!msgPayload.notification) {\r\n // Nothing to do.\r\n return [2 /*return*/];\r\n }\r\n link = (msgPayload.fcmOptions && msgPayload.fcmOptions.link) ||\r\n msgPayload.notification.click_action;\r\n if (!link) {\r\n // Nothing to do.\r\n return [2 /*return*/];\r\n }\r\n return [4 /*yield*/, this.getWindowClient_(link)];\r\n case 1:\r\n windowClient = _a.sent();\r\n if (!!windowClient) return [3 /*break*/, 3];\r\n return [4 /*yield*/, self.clients.openWindow(link)];\r\n case 2:\r\n // Unable to find window client so need to open one.\r\n windowClient = _a.sent();\r\n return [3 /*break*/, 5];\r\n case 3: return [4 /*yield*/, windowClient.focus()];\r\n case 4:\r\n windowClient = _a.sent();\r\n _a.label = 5;\r\n case 5:\r\n if (!windowClient) {\r\n // Window Client will not be returned if it's for a third party origin.\r\n return [2 /*return*/];\r\n }\r\n // Delete notification and fcmOptions data from payload before sending to\r\n // the page.\r\n delete msgPayload.notification;\r\n delete msgPayload.fcmOptions;\r\n internalMsg = createNewMsg(MessageType.NOTIFICATION_CLICKED, msgPayload);\r\n // Attempt to send a message to the client to handle the data\r\n // Is affected by: https://github.com/slightlyoff/ServiceWorker/issues/728\r\n return [2 /*return*/, this.attemptToMessageClient_(windowClient, internalMsg)];\r\n }\r\n });\r\n });\r\n };\r\n // Visible for testing\r\n // TODO: Make private\r\n SwController.prototype.getNotificationData_ = function (msgPayload) {\r\n var _a;\r\n if (!msgPayload) {\r\n return;\r\n }\r\n if (typeof msgPayload.notification !== 'object') {\r\n return;\r\n }\r\n var notificationInformation = __assign({}, msgPayload.notification);\r\n // Put the message payload under FCM_MSG name so we can identify the\r\n // notification as being an FCM notification vs a notification from\r\n // somewhere else (i.e. normal web push or developer generated\r\n // notification).\r\n notificationInformation.data = __assign({}, msgPayload.notification.data, (_a = {}, _a[FCM_MSG] = msgPayload, _a));\r\n return notificationInformation;\r\n };\r\n /**\r\n * Calling setBackgroundMessageHandler will opt in to some specific\r\n * behaviours.\r\n * 1.) If a notification doesn't need to be shown due to a window already\r\n * being visible, then push messages will be sent to the page.\r\n * 2.) If a notification needs to be shown, and the message contains no\r\n * notification data this method will be called\r\n * and the promise it returns will be passed to event.waitUntil.\r\n * If you do not set this callback then all push messages will let and the\r\n * developer can handle them in a their own 'push' event callback\r\n *\r\n * @param callback The callback to be called when a push message is received\r\n * and a notification must be shown. The callback will be given the data from\r\n * the push message.\r\n */\r\n SwController.prototype.setBackgroundMessageHandler = function (callback) {\r\n if (!callback || typeof callback !== 'function') {\r\n throw errorFactory.create(\"bg-handler-function-expected\" /* BG_HANDLER_FUNCTION_EXPECTED */);\r\n }\r\n this.bgMessageHandler = callback;\r\n };\r\n /**\r\n * @param url The URL to look for when focusing a client.\r\n * @return Returns an existing window client or a newly opened WindowClient.\r\n */\r\n // Visible for testing\r\n // TODO: Make private\r\n SwController.prototype.getWindowClient_ = function (url) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var parsedURL, clientList, suitableClient, i, parsedClientUrl;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n parsedURL = new URL(url, self.location.href).href;\r\n return [4 /*yield*/, getClientList()];\r\n case 1:\r\n clientList = _a.sent();\r\n suitableClient = null;\r\n for (i = 0; i < clientList.length; i++) {\r\n parsedClientUrl = new URL(clientList[i].url, self.location.href)\r\n .href;\r\n if (parsedClientUrl === parsedURL) {\r\n suitableClient = clientList[i];\r\n break;\r\n }\r\n }\r\n return [2 /*return*/, suitableClient];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * This message will attempt to send the message to a window client.\r\n * @param client The WindowClient to send the message to.\r\n * @param message The message to send to the client.\r\n * @returns Returns a promise that resolves after sending the message. This\r\n * does not guarantee that the message was successfully received.\r\n */\r\n // Visible for testing\r\n // TODO: Make private\r\n SwController.prototype.attemptToMessageClient_ = function (client, message) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n return __generator(this, function (_a) {\r\n // NOTE: This returns a promise in case this API is abstracted later on to\r\n // do additional work\r\n if (!client) {\r\n throw errorFactory.create(\"no-window-client-to-msg\" /* NO_WINDOW_CLIENT_TO_MSG */);\r\n }\r\n client.postMessage(message);\r\n return [2 /*return*/];\r\n });\r\n });\r\n };\r\n /**\r\n * @returns If there is currently a visible WindowClient, this method will\r\n * resolve to true, otherwise false.\r\n */\r\n // Visible for testing\r\n // TODO: Make private\r\n SwController.prototype.hasVisibleClients_ = function () {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var clientList;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, getClientList()];\r\n case 1:\r\n clientList = _a.sent();\r\n return [2 /*return*/, clientList.some(function (client) {\r\n return client.visibilityState === 'visible' &&\r\n // Ignore chrome-extension clients as that matches the background pages\r\n // of extensions, which are always considered visible.\r\n !client.url.startsWith('chrome-extension://');\r\n })];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * @param msgPayload The data from the push event that should be sent to all\r\n * available pages.\r\n * @returns Returns a promise that resolves once the message has been sent to\r\n * all WindowClients.\r\n */\r\n // Visible for testing\r\n // TODO: Make private\r\n SwController.prototype.sendMessageToWindowClients_ = function (msgPayload) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var clientList, internalMsg;\r\n var _this = this;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, getClientList()];\r\n case 1:\r\n clientList = _a.sent();\r\n internalMsg = createNewMsg(MessageType.PUSH_MSG_RECEIVED, msgPayload);\r\n return [4 /*yield*/, Promise.all(clientList.map(function (client) {\r\n return _this.attemptToMessageClient_(client, internalMsg);\r\n }))];\r\n case 2:\r\n _a.sent();\r\n return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * This will register the default service worker and return the registration.\r\n * @return he service worker registration to be used for the push service.\r\n */\r\n SwController.prototype.getSWRegistration_ = function () {\r\n return __awaiter(this, void 0, void 0, function () {\r\n return __generator(this, function (_a) {\r\n return [2 /*return*/, self.registration];\r\n });\r\n });\r\n };\r\n /**\r\n * This will return the default VAPID key or the uint8array version of the\r\n * public VAPID key provided by the developer.\r\n */\r\n SwController.prototype.getPublicVapidKey_ = function () {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var swReg, vapidKeyFromDatabase;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, this.getSWRegistration_()];\r\n case 1:\r\n swReg = _a.sent();\r\n if (!swReg) {\r\n throw errorFactory.create(\"sw-registration-expected\" /* SW_REGISTRATION_EXPECTED */);\r\n }\r\n return [4 /*yield*/, this.getVapidDetailsModel().getVapidFromSWScope(swReg.scope)];\r\n case 2:\r\n vapidKeyFromDatabase = _a.sent();\r\n if (vapidKeyFromDatabase == null) {\r\n return [2 /*return*/, DEFAULT_PUBLIC_VAPID_KEY];\r\n }\r\n return [2 /*return*/, vapidKeyFromDatabase];\r\n }\r\n });\r\n });\r\n };\r\n return SwController;\r\n}(BaseController));\r\nfunction getClientList() {\r\n return self.clients.matchAll({\r\n type: 'window',\r\n includeUncontrolled: true\r\n // TS doesn't know that \"type: 'window'\" means it'll return WindowClient[]\r\n });\r\n}\r\nfunction createNewMsg(msgType, msgData) {\r\n var _a;\r\n return _a = {},\r\n _a[MessageParameter.TYPE_OF_MSG] = msgType,\r\n _a[MessageParameter.DATA] = msgData,\r\n _a;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar DEFAULT_SW_PATH = '/firebase-messaging-sw.js';\r\nvar DEFAULT_SW_SCOPE = '/firebase-cloud-messaging-push-scope';\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar WindowController = /** @class */ (function (_super) {\r\n __extends(WindowController, _super);\r\n /**\r\n * A service that provides a MessagingService instance.\r\n */\r\n function WindowController(app) {\r\n var _this = _super.call(this, app) || this;\r\n _this.registrationToUse = null;\r\n _this.publicVapidKeyToUse = null;\r\n _this.manifestCheckPromise = null;\r\n _this.messageObserver = null;\r\n // @ts-ignore: Unused variable error, this is not implemented yet.\r\n _this.tokenRefreshObserver = null;\r\n _this.onMessageInternal = createSubscribe(function (observer) {\r\n _this.messageObserver = observer;\r\n });\r\n _this.onTokenRefreshInternal = createSubscribe(function (observer) {\r\n _this.tokenRefreshObserver = observer;\r\n });\r\n _this.setupSWMessageListener_();\r\n return _this;\r\n }\r\n /**\r\n * This method returns an FCM token if it can be generated.\r\n * The return promise will reject if the browser doesn't support\r\n * FCM, if permission is denied for notifications or it's not\r\n * possible to generate a token.\r\n *\r\n * @return Returns a promise that resolves to an FCM token or null if\r\n * permission isn't granted.\r\n */\r\n WindowController.prototype.getToken = function () {\r\n return __awaiter(this, void 0, void 0, function () {\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (!this.manifestCheckPromise) {\r\n this.manifestCheckPromise = manifestCheck();\r\n }\r\n return [4 /*yield*/, this.manifestCheckPromise];\r\n case 1:\r\n _a.sent();\r\n return [2 /*return*/, _super.prototype.getToken.call(this)];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * Request permission if it is not currently granted\r\n *\r\n * @return Resolves if the permission was granted, otherwise rejects\r\n */\r\n WindowController.prototype.requestPermission = function () {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var permissionResult;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (this.getNotificationPermission_() === 'granted') {\r\n return [2 /*return*/];\r\n }\r\n return [4 /*yield*/, Notification.requestPermission()];\r\n case 1:\r\n permissionResult = _a.sent();\r\n if (permissionResult === 'granted') {\r\n return [2 /*return*/];\r\n }\r\n else if (permissionResult === 'denied') {\r\n throw errorFactory.create(\"permission-blocked\" /* PERMISSION_BLOCKED */);\r\n }\r\n else {\r\n throw errorFactory.create(\"permission-default\" /* PERMISSION_DEFAULT */);\r\n }\r\n return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * This method allows a developer to override the default service worker and\r\n * instead use a custom service worker.\r\n *\r\n * @param registration The service worker registration that should be used to\r\n * receive the push messages.\r\n */\r\n WindowController.prototype.useServiceWorker = function (registration) {\r\n if (!(registration instanceof ServiceWorkerRegistration)) {\r\n throw errorFactory.create(\"sw-registration-expected\" /* SW_REGISTRATION_EXPECTED */);\r\n }\r\n if (this.registrationToUse != null) {\r\n throw errorFactory.create(\"use-sw-before-get-token\" /* USE_SW_BEFORE_GET_TOKEN */);\r\n }\r\n this.registrationToUse = registration;\r\n };\r\n /**\r\n * This method allows a developer to override the default vapid key\r\n * and instead use a custom VAPID public key.\r\n *\r\n * @param publicKey A URL safe base64 encoded string.\r\n */\r\n WindowController.prototype.usePublicVapidKey = function (publicKey) {\r\n if (typeof publicKey !== 'string') {\r\n throw errorFactory.create(\"invalid-public-vapid-key\" /* INVALID_PUBLIC_VAPID_KEY */);\r\n }\r\n if (this.publicVapidKeyToUse != null) {\r\n throw errorFactory.create(\"use-public-key-before-get-token\" /* USE_PUBLIC_KEY_BEFORE_GET_TOKEN */);\r\n }\r\n var parsedKey = base64ToArrayBuffer(publicKey);\r\n if (parsedKey.length !== 65) {\r\n throw errorFactory.create(\"public-vapid-key-decryption-failed\" /* PUBLIC_KEY_DECRYPTION_FAILED */);\r\n }\r\n this.publicVapidKeyToUse = parsedKey;\r\n };\r\n /**\r\n * @export\r\n * @param nextOrObserver An observer object or a function triggered on\r\n * message.\r\n * @param error A function triggered on message error.\r\n * @param completed function triggered when the observer is removed.\r\n * @return The unsubscribe function for the observer.\r\n */\r\n WindowController.prototype.onMessage = function (nextOrObserver, error, completed) {\r\n if (typeof nextOrObserver === 'function') {\r\n return this.onMessageInternal(nextOrObserver, error, completed);\r\n }\r\n else {\r\n return this.onMessageInternal(nextOrObserver);\r\n }\r\n };\r\n /**\r\n * @param nextOrObserver An observer object or a function triggered on token\r\n * refresh.\r\n * @param error A function triggered on token refresh error.\r\n * @param completed function triggered when the observer is removed.\r\n * @return The unsubscribe function for the observer.\r\n */\r\n WindowController.prototype.onTokenRefresh = function (nextOrObserver, error, completed) {\r\n if (typeof nextOrObserver === 'function') {\r\n return this.onTokenRefreshInternal(nextOrObserver, error, completed);\r\n }\r\n else {\r\n return this.onTokenRefreshInternal(nextOrObserver);\r\n }\r\n };\r\n /**\r\n * Given a registration, wait for the service worker it relates to\r\n * become activer\r\n * @param registration Registration to wait for service worker to become active\r\n * @return Wait for service worker registration to become active\r\n */\r\n // Visible for testing\r\n // TODO: Make private\r\n WindowController.prototype.waitForRegistrationToActivate_ = function (registration) {\r\n var serviceWorker = registration.installing || registration.waiting || registration.active;\r\n return new Promise(function (resolve, reject) {\r\n if (!serviceWorker) {\r\n // This is a rare scenario but has occured in firefox\r\n reject(errorFactory.create(\"no-sw-in-reg\" /* NO_SW_IN_REG */));\r\n return;\r\n }\r\n // Because the Promise function is called on next tick there is a\r\n // small chance that the worker became active or redundant already.\r\n if (serviceWorker.state === 'activated') {\r\n resolve(registration);\r\n return;\r\n }\r\n if (serviceWorker.state === 'redundant') {\r\n reject(errorFactory.create(\"sw-reg-redundant\" /* SW_REG_REDUNDANT */));\r\n return;\r\n }\r\n var stateChangeListener = function () {\r\n if (serviceWorker.state === 'activated') {\r\n resolve(registration);\r\n }\r\n else if (serviceWorker.state === 'redundant') {\r\n reject(errorFactory.create(\"sw-reg-redundant\" /* SW_REG_REDUNDANT */));\r\n }\r\n else {\r\n // Return early and wait to next state change\r\n return;\r\n }\r\n serviceWorker.removeEventListener('statechange', stateChangeListener);\r\n };\r\n serviceWorker.addEventListener('statechange', stateChangeListener);\r\n });\r\n };\r\n /**\r\n * This will register the default service worker and return the registration\r\n * @return The service worker registration to be used for the push service.\r\n */\r\n WindowController.prototype.getSWRegistration_ = function () {\r\n var _this = this;\r\n if (this.registrationToUse) {\r\n return this.waitForRegistrationToActivate_(this.registrationToUse);\r\n }\r\n // Make the registration null so we know useServiceWorker will not\r\n // use a new service worker as registrationToUse is no longer undefined\r\n this.registrationToUse = null;\r\n return navigator.serviceWorker\r\n .register(DEFAULT_SW_PATH, {\r\n scope: DEFAULT_SW_SCOPE\r\n })\r\n .catch(function (err) {\r\n throw errorFactory.create(\"failed-serviceworker-registration\" /* FAILED_DEFAULT_REGISTRATION */, {\r\n browserErrorMessage: err.message\r\n });\r\n })\r\n .then(function (registration) {\r\n return _this.waitForRegistrationToActivate_(registration).then(function () {\r\n _this.registrationToUse = registration;\r\n // We update after activation due to an issue with Firefox v49 where\r\n // a race condition occassionally causes the service work to not\r\n // install\r\n registration.update();\r\n return registration;\r\n });\r\n });\r\n };\r\n /**\r\n * This will return the default VAPID key or the uint8array version of the public VAPID key\r\n * provided by the developer.\r\n */\r\n WindowController.prototype.getPublicVapidKey_ = function () {\r\n return __awaiter(this, void 0, void 0, function () {\r\n return __generator(this, function (_a) {\r\n if (this.publicVapidKeyToUse) {\r\n return [2 /*return*/, this.publicVapidKeyToUse];\r\n }\r\n return [2 /*return*/, DEFAULT_PUBLIC_VAPID_KEY];\r\n });\r\n });\r\n };\r\n /**\r\n * This method will set up a message listener to handle\r\n * events from the service worker that should trigger\r\n * events in the page.\r\n */\r\n // Visible for testing\r\n // TODO: Make private\r\n WindowController.prototype.setupSWMessageListener_ = function () {\r\n var _this = this;\r\n navigator.serviceWorker.addEventListener('message', function (event) {\r\n if (!event.data || !event.data[MessageParameter.TYPE_OF_MSG]) {\r\n // Not a message from FCM\r\n return;\r\n }\r\n var workerPageMessage = event.data;\r\n switch (workerPageMessage[MessageParameter.TYPE_OF_MSG]) {\r\n case MessageType.PUSH_MSG_RECEIVED:\r\n case MessageType.NOTIFICATION_CLICKED:\r\n var pushMessage = workerPageMessage[MessageParameter.DATA];\r\n if (_this.messageObserver) {\r\n _this.messageObserver.next(pushMessage);\r\n }\r\n break;\r\n default:\r\n // Noop.\r\n break;\r\n }\r\n }, false);\r\n };\r\n return WindowController;\r\n}(BaseController));\r\n/**\r\n * The method checks that a manifest is defined and has the correct GCM\r\n * sender ID.\r\n * @return Returns a promise that resolves if the manifest matches\r\n * our required sender ID\r\n */\r\n// Exported for testing\r\nfunction manifestCheck() {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var manifestTag, manifestContent, response, e_1;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n manifestTag = document.querySelector('link[rel=\"manifest\"]');\r\n if (!manifestTag) {\r\n return [2 /*return*/];\r\n }\r\n _a.label = 1;\r\n case 1:\r\n _a.trys.push([1, 4, , 5]);\r\n return [4 /*yield*/, fetch(manifestTag.href)];\r\n case 2:\r\n response = _a.sent();\r\n return [4 /*yield*/, response.json()];\r\n case 3:\r\n manifestContent = _a.sent();\r\n return [3 /*break*/, 5];\r\n case 4:\r\n e_1 = _a.sent();\r\n // If the download or parsing fails allow check.\r\n // We only want to error if we KNOW that the gcm_sender_id is incorrect.\r\n return [2 /*return*/];\r\n case 5:\r\n if (!manifestContent || !manifestContent.gcm_sender_id) {\r\n return [2 /*return*/];\r\n }\r\n if (manifestContent.gcm_sender_id !== '103953800507') {\r\n throw errorFactory.create(\"incorrect-gcm-sender-id\" /* INCORRECT_GCM_SENDER_ID */);\r\n }\r\n return [2 /*return*/];\r\n }\r\n });\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction registerMessaging(instance) {\r\n var messagingName = 'messaging';\r\n var factoryMethod = function (app) {\r\n if (!isSupported()) {\r\n throw errorFactory.create(\"unsupported-browser\" /* UNSUPPORTED_BROWSER */);\r\n }\r\n if (self && 'ServiceWorkerGlobalScope' in self) {\r\n // Running in ServiceWorker context\r\n return new SwController(app);\r\n }\r\n else {\r\n // Assume we are in the window context.\r\n return new WindowController(app);\r\n }\r\n };\r\n var namespaceExports = {\r\n isSupported: isSupported\r\n };\r\n instance.INTERNAL.registerService(messagingName, factoryMethod, namespaceExports);\r\n}\r\nregisterMessaging(firebase);\r\nfunction isSupported() {\r\n if (self && 'ServiceWorkerGlobalScope' in self) {\r\n // Running in ServiceWorker context\r\n return isSWControllerSupported();\r\n }\r\n else {\r\n // Assume we are in the window context.\r\n return isWindowControllerSupported();\r\n }\r\n}\r\n/**\r\n * Checks to see if the required APIs exist.\r\n */\r\nfunction isWindowControllerSupported() {\r\n return (navigator.cookieEnabled &&\r\n 'serviceWorker' in navigator &&\r\n 'PushManager' in window &&\r\n 'Notification' in window &&\r\n 'fetch' in window &&\r\n ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&\r\n PushSubscription.prototype.hasOwnProperty('getKey'));\r\n}\r\n/**\r\n * Checks to see if the required APIs exist within SW Context.\r\n */\r\nfunction isSWControllerSupported() {\r\n return ('PushManager' in self &&\r\n 'Notification' in self &&\r\n ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&\r\n PushSubscription.prototype.hasOwnProperty('getKey'));\r\n}\n\nexport { isSupported, registerMessaging };\n//# sourceMappingURL=index.esm.js.map\n","'use strict';\n\nfunction _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }\n\nrequire('@firebase/polyfill');\nvar firebase = _interopDefault(require('@firebase/app'));\nrequire('@firebase/auth');\nrequire('@firebase/database');\nrequire('@firebase/firestore');\nrequire('@firebase/functions');\nrequire('@firebase/messaging');\nrequire('@firebase/storage');\nrequire('@firebase/performance');\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconsole.warn(\"\\nIt looks like you're using the development build of the Firebase JS SDK.\\nWhen deploying Firebase apps to production, it is advisable to only import\\nthe individual SDK components you intend to use.\\n\\nFor the module builds, these are available in the following manner\\n(replace with the name of a component - i.e. auth, database, etc):\\n\\nCommonJS Modules:\\nconst firebase = require('firebase/app');\\nrequire('firebase/');\\n\\nES Modules:\\nimport firebase from 'firebase/app';\\nimport 'firebase/';\\n\\nTypescript:\\nimport * as firebase from 'firebase/app';\\nimport 'firebase/';\\n\");\n\nmodule.exports = firebase;\n//# sourceMappingURL=index.cjs.js.map\n","(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :\n typeof define === 'function' && define.amd ? define(['exports'], factory) :\n (global = global || self, factory(global.idb = {}));\n}(this, function (exports) { 'use strict';\n\n function toArray(arr) {\n return Array.prototype.slice.call(arr);\n }\n\n function promisifyRequest(request) {\n return new Promise(function(resolve, reject) {\n request.onsuccess = function() {\n resolve(request.result);\n };\n\n request.onerror = function() {\n reject(request.error);\n };\n });\n }\n\n function promisifyRequestCall(obj, method, args) {\n var request;\n var p = new Promise(function(resolve, reject) {\n request = obj[method].apply(obj, args);\n promisifyRequest(request).then(resolve, reject);\n });\n\n p.request = request;\n return p;\n }\n\n function promisifyCursorRequestCall(obj, method, args) {\n var p = promisifyRequestCall(obj, method, args);\n return p.then(function(value) {\n if (!value) return;\n return new Cursor(value, p.request);\n });\n }\n\n function proxyProperties(ProxyClass, targetProp, properties) {\n properties.forEach(function(prop) {\n Object.defineProperty(ProxyClass.prototype, prop, {\n get: function() {\n return this[targetProp][prop];\n },\n set: function(val) {\n this[targetProp][prop] = val;\n }\n });\n });\n }\n\n function proxyRequestMethods(ProxyClass, targetProp, Constructor, properties) {\n properties.forEach(function(prop) {\n if (!(prop in Constructor.prototype)) return;\n ProxyClass.prototype[prop] = function() {\n return promisifyRequestCall(this[targetProp], prop, arguments);\n };\n });\n }\n\n function proxyMethods(ProxyClass, targetProp, Constructor, properties) {\n properties.forEach(function(prop) {\n if (!(prop in Constructor.prototype)) return;\n ProxyClass.prototype[prop] = function() {\n return this[targetProp][prop].apply(this[targetProp], arguments);\n };\n });\n }\n\n function proxyCursorRequestMethods(ProxyClass, targetProp, Constructor, properties) {\n properties.forEach(function(prop) {\n if (!(prop in Constructor.prototype)) return;\n ProxyClass.prototype[prop] = function() {\n return promisifyCursorRequestCall(this[targetProp], prop, arguments);\n };\n });\n }\n\n function Index(index) {\n this._index = index;\n }\n\n proxyProperties(Index, '_index', [\n 'name',\n 'keyPath',\n 'multiEntry',\n 'unique'\n ]);\n\n proxyRequestMethods(Index, '_index', IDBIndex, [\n 'get',\n 'getKey',\n 'getAll',\n 'getAllKeys',\n 'count'\n ]);\n\n proxyCursorRequestMethods(Index, '_index', IDBIndex, [\n 'openCursor',\n 'openKeyCursor'\n ]);\n\n function Cursor(cursor, request) {\n this._cursor = cursor;\n this._request = request;\n }\n\n proxyProperties(Cursor, '_cursor', [\n 'direction',\n 'key',\n 'primaryKey',\n 'value'\n ]);\n\n proxyRequestMethods(Cursor, '_cursor', IDBCursor, [\n 'update',\n 'delete'\n ]);\n\n // proxy 'next' methods\n ['advance', 'continue', 'continuePrimaryKey'].forEach(function(methodName) {\n if (!(methodName in IDBCursor.prototype)) return;\n Cursor.prototype[methodName] = function() {\n var cursor = this;\n var args = arguments;\n return Promise.resolve().then(function() {\n cursor._cursor[methodName].apply(cursor._cursor, args);\n return promisifyRequest(cursor._request).then(function(value) {\n if (!value) return;\n return new Cursor(value, cursor._request);\n });\n });\n };\n });\n\n function ObjectStore(store) {\n this._store = store;\n }\n\n ObjectStore.prototype.createIndex = function() {\n return new Index(this._store.createIndex.apply(this._store, arguments));\n };\n\n ObjectStore.prototype.index = function() {\n return new Index(this._store.index.apply(this._store, arguments));\n };\n\n proxyProperties(ObjectStore, '_store', [\n 'name',\n 'keyPath',\n 'indexNames',\n 'autoIncrement'\n ]);\n\n proxyRequestMethods(ObjectStore, '_store', IDBObjectStore, [\n 'put',\n 'add',\n 'delete',\n 'clear',\n 'get',\n 'getAll',\n 'getKey',\n 'getAllKeys',\n 'count'\n ]);\n\n proxyCursorRequestMethods(ObjectStore, '_store', IDBObjectStore, [\n 'openCursor',\n 'openKeyCursor'\n ]);\n\n proxyMethods(ObjectStore, '_store', IDBObjectStore, [\n 'deleteIndex'\n ]);\n\n function Transaction(idbTransaction) {\n this._tx = idbTransaction;\n this.complete = new Promise(function(resolve, reject) {\n idbTransaction.oncomplete = function() {\n resolve();\n };\n idbTransaction.onerror = function() {\n reject(idbTransaction.error);\n };\n idbTransaction.onabort = function() {\n reject(idbTransaction.error);\n };\n });\n }\n\n Transaction.prototype.objectStore = function() {\n return new ObjectStore(this._tx.objectStore.apply(this._tx, arguments));\n };\n\n proxyProperties(Transaction, '_tx', [\n 'objectStoreNames',\n 'mode'\n ]);\n\n proxyMethods(Transaction, '_tx', IDBTransaction, [\n 'abort'\n ]);\n\n function UpgradeDB(db, oldVersion, transaction) {\n this._db = db;\n this.oldVersion = oldVersion;\n this.transaction = new Transaction(transaction);\n }\n\n UpgradeDB.prototype.createObjectStore = function() {\n return new ObjectStore(this._db.createObjectStore.apply(this._db, arguments));\n };\n\n proxyProperties(UpgradeDB, '_db', [\n 'name',\n 'version',\n 'objectStoreNames'\n ]);\n\n proxyMethods(UpgradeDB, '_db', IDBDatabase, [\n 'deleteObjectStore',\n 'close'\n ]);\n\n function DB(db) {\n this._db = db;\n }\n\n DB.prototype.transaction = function() {\n return new Transaction(this._db.transaction.apply(this._db, arguments));\n };\n\n proxyProperties(DB, '_db', [\n 'name',\n 'version',\n 'objectStoreNames'\n ]);\n\n proxyMethods(DB, '_db', IDBDatabase, [\n 'close'\n ]);\n\n // Add cursor iterators\n // TODO: remove this once browsers do the right thing with promises\n ['openCursor', 'openKeyCursor'].forEach(function(funcName) {\n [ObjectStore, Index].forEach(function(Constructor) {\n // Don't create iterateKeyCursor if openKeyCursor doesn't exist.\n if (!(funcName in Constructor.prototype)) return;\n\n Constructor.prototype[funcName.replace('open', 'iterate')] = function() {\n var args = toArray(arguments);\n var callback = args[args.length - 1];\n var nativeObject = this._store || this._index;\n var request = nativeObject[funcName].apply(nativeObject, args.slice(0, -1));\n request.onsuccess = function() {\n callback(request.result);\n };\n };\n });\n });\n\n // polyfill getAll\n [Index, ObjectStore].forEach(function(Constructor) {\n if (Constructor.prototype.getAll) return;\n Constructor.prototype.getAll = function(query, count) {\n var instance = this;\n var items = [];\n\n return new Promise(function(resolve) {\n instance.iterateCursor(query, function(cursor) {\n if (!cursor) {\n resolve(items);\n return;\n }\n items.push(cursor.value);\n\n if (count !== undefined && items.length == count) {\n resolve(items);\n return;\n }\n cursor.continue();\n });\n });\n };\n });\n\n function openDb(name, version, upgradeCallback) {\n var p = promisifyRequestCall(indexedDB, 'open', [name, version]);\n var request = p.request;\n\n if (request) {\n request.onupgradeneeded = function(event) {\n if (upgradeCallback) {\n upgradeCallback(new UpgradeDB(request.result, event.oldVersion, request.transaction));\n }\n };\n }\n\n return p.then(function(db) {\n return new DB(db);\n });\n }\n\n function deleteDb(name) {\n return promisifyRequestCall(indexedDB, 'deleteDatabase', [name]);\n }\n\n exports.openDb = openDb;\n exports.deleteDb = deleteDb;\n\n Object.defineProperty(exports, '__esModule', { value: true });\n\n}));\n","/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A container for all of the Logger instances\r\n */\r\nvar instances = [];\r\n/**\r\n * The JS SDK supports 5 log levels and also allows a user the ability to\r\n * silence the logs altogether.\r\n *\r\n * The order is a follows:\r\n * DEBUG < VERBOSE < INFO < WARN < ERROR\r\n *\r\n * All of the log types above the current log level will be captured (i.e. if\r\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\r\n * `VERBOSE` logs will not)\r\n */\r\nvar LogLevel;\r\n(function (LogLevel) {\r\n LogLevel[LogLevel[\"DEBUG\"] = 0] = \"DEBUG\";\r\n LogLevel[LogLevel[\"VERBOSE\"] = 1] = \"VERBOSE\";\r\n LogLevel[LogLevel[\"INFO\"] = 2] = \"INFO\";\r\n LogLevel[LogLevel[\"WARN\"] = 3] = \"WARN\";\r\n LogLevel[LogLevel[\"ERROR\"] = 4] = \"ERROR\";\r\n LogLevel[LogLevel[\"SILENT\"] = 5] = \"SILENT\";\r\n})(LogLevel || (LogLevel = {}));\r\n/**\r\n * The default log level\r\n */\r\nvar defaultLogLevel = LogLevel.INFO;\r\n/**\r\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\r\n * messages on to their corresponding console counterparts (if the log method\r\n * is supported by the current log level)\r\n */\r\nvar defaultLogHandler = function (instance, logType) {\r\n var args = [];\r\n for (var _i = 2; _i < arguments.length; _i++) {\r\n args[_i - 2] = arguments[_i];\r\n }\r\n if (logType < instance.logLevel)\r\n return;\r\n var now = new Date().toISOString();\r\n switch (logType) {\r\n /**\r\n * By default, `console.debug` is not displayed in the developer console (in\r\n * chrome). To avoid forcing users to have to opt-in to these logs twice\r\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\r\n * logs to the `console.log` function.\r\n */\r\n case LogLevel.DEBUG:\r\n console.log.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\r\n break;\r\n case LogLevel.VERBOSE:\r\n console.log.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\r\n break;\r\n case LogLevel.INFO:\r\n console.info.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\r\n break;\r\n case LogLevel.WARN:\r\n console.warn.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\r\n break;\r\n case LogLevel.ERROR:\r\n console.error.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\r\n break;\r\n default:\r\n throw new Error(\"Attempted to log a message with an invalid logType (value: \" + logType + \")\");\r\n }\r\n};\r\nvar Logger = /** @class */ (function () {\r\n /**\r\n * Gives you an instance of a Logger to capture messages according to\r\n * Firebase's logging scheme.\r\n *\r\n * @param name The name that the logs will be associated with\r\n */\r\n function Logger(name) {\r\n this.name = name;\r\n /**\r\n * The log level of the given Logger instance.\r\n */\r\n this._logLevel = defaultLogLevel;\r\n /**\r\n * The log handler for the Logger instance.\r\n */\r\n this._logHandler = defaultLogHandler;\r\n /**\r\n * Capture the current instance for later use\r\n */\r\n instances.push(this);\r\n }\r\n Object.defineProperty(Logger.prototype, \"logLevel\", {\r\n get: function () {\r\n return this._logLevel;\r\n },\r\n set: function (val) {\r\n if (!(val in LogLevel)) {\r\n throw new TypeError('Invalid value assigned to `logLevel`');\r\n }\r\n this._logLevel = val;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(Logger.prototype, \"logHandler\", {\r\n get: function () {\r\n return this._logHandler;\r\n },\r\n set: function (val) {\r\n if (typeof val !== 'function') {\r\n throw new TypeError('Value assigned to `logHandler` must be a function');\r\n }\r\n this._logHandler = val;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n /**\r\n * The functions below are all based on the `console` interface\r\n */\r\n Logger.prototype.debug = function () {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n this._logHandler.apply(this, [this, LogLevel.DEBUG].concat(args));\r\n };\r\n Logger.prototype.log = function () {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n this._logHandler.apply(this, [this, LogLevel.VERBOSE].concat(args));\r\n };\r\n Logger.prototype.info = function () {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n this._logHandler.apply(this, [this, LogLevel.INFO].concat(args));\r\n };\r\n Logger.prototype.warn = function () {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n this._logHandler.apply(this, [this, LogLevel.WARN].concat(args));\r\n };\r\n Logger.prototype.error = function () {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n this._logHandler.apply(this, [this, LogLevel.ERROR].concat(args));\r\n };\r\n return Logger;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction setLogLevel(level) {\r\n instances.forEach(function (inst) {\r\n inst.logLevel = level;\r\n });\r\n}\n\nexport { LogLevel, Logger, setLogLevel };\n//# sourceMappingURL=index.esm.js.map\n","var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};\n\nvar g,goog=goog||{},k=commonjsGlobal;function m(a){return \"string\"==typeof a}function aa(a){return \"number\"==typeof a}function n(a,b){a=a.split(\".\");b=b||k;for(var c=0;c>>0),da=0;function ea(a,b,c){return a.call.apply(a.bind,arguments)}\nfunction fa(a,b,c){if(!a)throw Error();if(2b?null:m(a)?a.charAt(b):a[b]}function oa(a){return Array.prototype.concat.apply([],arguments)}function pa(a){var b=a.length;if(0b?1:0}var A;a:{var ta=k.navigator;if(ta){var ua=ta.userAgent;if(ua){A=ua;break a}}A=\"\";}function va(a,b,c){for(var d in a)b.call(c,a[d],d,a);}function wa(a){var b={},c;for(c in a)b[c]=a[c];return b}var xa=\"constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf\".split(\" \");function ya(a,b){for(var c,d,e=1;eparseFloat(Ja)){Ia=String(La);break a}}Ia=Ja;}var Ba={};\nfunction Ma(a){return Aa(a,function(){for(var b=0,c=ra(String(Ia)).split(\".\"),d=ra(String(a)).split(\".\"),e=Math.max(c.length,d.length),f=0;0==b&&f=a.keyCode)a.keyCode=-1;}catch(b){}};var E=\"closure_listenable_\"+(1E6*Math.random()|0),Ta=0;function Ua(a,b,c,d,e){this.listener=a;this.proxy=null;this.src=b;this.type=c;this.capture=!!d;this.da=e;this.key=++Ta;this.X=this.Z=!1;}function Va(a){a.X=!0;a.listener=null;a.proxy=null;a.src=null;a.da=null;}function Wa(a){this.src=a;this.a={};this.b=0;}Wa.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=Xa(a,b,d,e);-1>>0);function db(a){if(\"function\"==p(a))return a;a[mb]||(a[mb]=function(b){return a.handleEvent(b)});return a[mb]}function G(){y.call(this);this.c=new Wa(this);this.J=this;this.B=null;}x(G,y);G.prototype[E]=!0;g=G.prototype;g.addEventListener=function(a,b,c,d){bb(this,a,b,c,d);};g.removeEventListener=function(a,b,c,d){jb(this,a,b,c,d);};\ng.dispatchEvent=function(a){var b,c=this.B;if(c)for(b=[];c;c=c.B)b.push(c);c=this.J;var d=a.type||a;if(m(a))a=new C(a,c);else if(a instanceof C)a.target=a.target||c;else{var e=a;a=new C(d,c);ya(a,e);}e=!0;if(b)for(var f=b.length-1;0<=f;f--){var h=a.a=b[f];e=nb(h,d,!0,a)&&e;}h=a.a=c;e=nb(h,d,!0,a)&&e;e=nb(h,d,!1,a)&&e;if(b)for(f=0;fb.b&&(b.b++,a.next=b.a,b.a=a);}zb=!1;}function Cb(a,b){G.call(this);this.b=a||1;this.a=b||k;this.f=u(this.gb,this);this.g=w();}x(Cb,G);g=Cb.prototype;g.ba=!1;g.L=null;g.gb=function(){if(this.ba){var a=w()-this.g;0b||3==b&&!Ea&&!this.a.aa())){this.m||4!=b||7==c||(8==c||0>=d?J(3):J(2));gc(this);var e=this.a.T();this.o=e;var f=this.a.aa();if(this.b=200==e){if(this.S&&!this.s){b:{if(this.a){var h=hc(this.a,\"X-HTTP-Initial-Response\");if(h&&!qa(h)){var l=h;break b}}l=null;}if(l)this.s=!0,ic(this,l);else{this.b=!1;this.c=3;K(12);P(this);jc(this);break a}}this.H?(kc(this,b,f),Ea&&this.b&&3==b&&(Ib(this.I,this.P,\"tick\",this.cb),this.P.start())):\nic(this,f);4==b&&P(this);this.b&&!this.m&&(4==b?this.g.na(this):(this.b=!1,ec(this)));}else 400==e&&0b.length)return $b;b=b.substr(d,c);a.A=d+c;return b}g.cancel=function(){this.m=!0;P(this);};function ec(a){a.R=w()+a.O;mc(a,a.O);}function mc(a,b){if(null!=a.i)throw Error(\"WatchDog timer not null\");a.i=Ob(u(a.bb,a),b);}\nfunction gc(a){a.i&&(k.clearTimeout(a.i),a.i=null);}g.bb=function(){this.i=null;var a=w();0<=a-this.R?(2!=this.F&&(J(3),K(17)),P(this),this.c=2,jc(this)):mc(this,this.R-a);};function jc(a){a.g.Da()||a.m||a.g.na(a);}function P(a){gc(a);var b=a.B;b&&\"function\"==typeof b.la&&b.la();a.B=null;Db(a.P);Jb(a.I);a.a&&(b=a.a,a.a=null,b.abort(),b.la());}function ic(a,b){try{a.g.Ga(a,b),J(4);}catch(c){}}function nc(a){if(a.C&&\"function\"==typeof a.C)return a.C();if(m(a))return a.split(\"\");if(ca(a)){for(var b=[],c=a.length,d=0;d2*a.c&&pc(a));}function pc(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 xc(a,b,c){b instanceof Ac?(a.c=b,Gc(a.c,a.h)):(c||(b=Bc(b,Hc)),a.c=new Ac(b,a.h));}\nfunction T(a,b,c){a.c.set(b,c);}function fc(a,b,c){q(c)||(c=[String(c)]);Ic(a.c,b,c);}function bc(a){T(a,\"zx\",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^w()).toString(36));return a}function Jc(a){return a instanceof S?N(a):new S(a,void 0)}function Kc(a,b,c,d){var e=new S(null,void 0);a&&uc(e,a);b&&vc(e,b);c&&wc(e,c);d&&(e.a=d);return e}function zc(a,b){return a?b?decodeURI(a.replace(/%25/g,\"%2525\")):decodeURIComponent(a):\"\"}\nfunction Bc(a,b,c){return m(a)?(a=encodeURI(a).replace(b,Lc),c&&(a=a.replace(/%25([0-9a-fA-F]{2})/g,\"%$1\")),a):null}function Lc(a){a=a.charCodeAt(0);return \"%\"+(a>>4&15).toString(16)+(a&15).toString(16)}var Cc=/[#\\/\\?@]/g,Ec=/[#\\?:]/g,Dc=/[#\\?]/g,Hc=/[#\\?@]/g,Fc=/#/g;function Ac(a,b){this.b=this.a=null;this.c=a||null;this.f=!!b;}function U(a){a.a||(a.a=new Q,a.b=0,a.c&&tc(a.c,function(b,c){a.add(decodeURIComponent(b.replace(/\\+/g,\" \")),c);}));}g=Ac.prototype;\ng.add=function(a,b){U(this);this.c=null;a=V(this,a);var c=this.a.get(a);c||this.a.set(a,c=[]);c.push(b);this.b+=1;return this};function Mc(a,b){U(a);b=V(a,b);R(a.a.b,b)&&(a.c=null,a.b-=a.a.get(b).length,rc(a.a,b));}function Nc(a,b){U(a);b=V(a,b);return R(a.a.b,b)}g.forEach=function(a,b){U(this);this.a.forEach(function(c,d){la(c,function(e){a.call(b,e,d,this);},this);},this);};\ng.K=function(){U(this);for(var a=this.a.C(),b=this.a.K(),c=[],d=0;d=a.f:!1}\nfunction fd(a){return a.b?1:a.a?a.a.a.c:0}function gd(a,b){a.b?a=a.b==b:a.a?(b=Zc(b),a=R(a.a.a.b,b)):a=!1;return a}function dd(a,b){a.a?a.a.add(b):a.b=b;}function hd(a,b){if(a.b&&a.b==b)a.b=null;else{var c;if(c=a.a)c=Zc(b),c=R(a.a.a.b,c);c&&rc(a.a.a,Zc(b));}}ad.prototype.cancel=function(){this.c=id(this);this.b?(this.b.cancel(),this.b=null):this.a&&0!=this.a.a.c&&(la(this.a.C(),function(a){a.cancel();}),qc(this.a.a));};\nfunction id(a){if(null!=a.b)return a.c.concat(a.b.j);if(null!=a.a&&0!=a.a.a.c){var b=a.c;la(a.a.C(),function(c){b=b.concat(c.j);});return b}return pa(a.c)}function jd(){}jd.prototype.stringify=function(a){return k.JSON.stringify(a,void 0)};jd.prototype.parse=function(a){return k.JSON.parse(a,void 0)};function kd(){this.a=new jd;}function ld(a,b,c){var d=c||\"\";try{oc(a,function(e,f){var h=e;r(e)&&(h=ob(e));b.push(d+f+\"=\"+encodeURIComponent(h));});}catch(e){throw b.push(d+\"type=\"+encodeURIComponent(\"_badmap\")),e;}}function md(a,b){var c=new Kb;if(k.Image){var d=new Image;d.onload=v(nd,c,d,\"TestLoadImage: loaded\",!0,b);d.onerror=v(nd,c,d,\"TestLoadImage: error\",!1,b);d.onabort=v(nd,c,d,\"TestLoadImage: abort\",!1,b);d.ontimeout=v(nd,c,d,\"TestLoadImage: timeout\",!1,b);k.setTimeout(function(){if(d.ontimeout)d.ontimeout();},1E4);d.src=a;}else b(!1);}function nd(a,b,c,d,e){try{b.onload=null,b.onerror=null,b.onabort=null,b.ontimeout=null,e(d);}catch(f){}}var od=k.JSON.parse;function X(a){G.call(this);this.headers=new Q;this.H=a||null;this.b=!1;this.s=this.a=null;this.A=\"\";this.h=0;this.f=\"\";this.g=this.w=this.l=this.v=!1;this.o=0;this.m=null;this.I=pd;this.D=this.F=!1;}x(X,G);var pd=\"\",qd=/^https?$/i,rd=[\"POST\",\"PUT\"];g=X.prototype;\ng.ca=function(a,b,c,d){if(this.a)throw Error(\"[goog.net.XhrIo] Object is active with another request=\"+this.A+\"; newUri=\"+a);b=b?b.toUpperCase():\"GET\";this.A=a;this.f=\"\";this.h=0;this.v=!1;this.b=!0;this.a=new XMLHttpRequest;this.s=this.H?Sb(this.H):Sb(Wb);this.a.onreadystatechange=u(this.Fa,this);try{this.w=!0,this.a.open(b,String(a),!0),this.w=!1;}catch(f){sd(this,f);return}a=c||\"\";var e=new Q(this.headers);d&&oc(d,function(f,h){e.set(h,f);});d=ma(e.K());c=k.FormData&&a instanceof k.FormData;!(0<=\nja(rd,b))||d||c||e.set(\"Content-Type\",\"application/x-www-form-urlencoded;charset=utf-8\");e.forEach(function(f,h){this.a.setRequestHeader(h,f);},this);this.I&&(this.a.responseType=this.I);\"withCredentials\"in this.a&&this.a.withCredentials!==this.F&&(this.a.withCredentials=this.F);try{td(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}T(a,b,c);return a}function Ad(a){this.f=[];this.F=new Xc;this.ga=this.pa=this.B=this.ha=this.a=this.I=this.j=this.V=this.g=this.J=this.i=null;this.Ra=this.P=0;this.Pa=!!n(\"internalChannelParams.failFast\",a);this.ia=this.w=this.s=this.l=this.h=this.c=null;this.oa=!0;this.m=this.ra=this.O=-1;this.S=this.v=this.A=0;this.Oa=n(\"internalChannelParams.baseRetryDelayMs\",a)||5E3;this.Sa=n(\"internalChannelParams.retryDelaySeedMs\",a)||1E4;this.Qa=n(\"internalChannelParams.forwardChannelMaxRetries\",a)||2;this.qa=n(\"internalChannelParams.forwardChannelRequestTimeoutMs\",\na)||2E4;this.La=a&&a.Ab||void 0;this.D=void 0;this.R=a&&a.supportsCrossDomainXhr||!1;this.H=\"\";this.b=new ad(a&&a.concurrentRequestLimit);this.ja=new kd;this.o=a&&void 0!==a.backgroundChannelTest?a.backgroundChannelTest:!0;(this.W=a&&a.fastHandshake||!1)&&!this.o&&(this.o=!0);a&&a.forceLongPolling&&(this.oa=!1);this.fa=void 0;}g=Ad.prototype;g.wa=8;g.u=1;\nfunction Bd(a){Cd(a);if(3==a.u){var b=a.P++,c=N(a.B);T(c,\"SID\",a.H);T(c,\"RID\",b);T(c,\"TYPE\",\"terminate\");Dd(a,c);b=new M(a,b,void 0);b.F=2;b.f=bc(N(c));c=!1;k.navigator&&k.navigator.sendBeacon&&(c=k.navigator.sendBeacon(b.f.toString(),\"\"));!c&&k.Image&&((new Image).src=b.f,c=!0);c||(b.a=b.g.$(null),b.a.ca(b.f));b.v=w();ec(b);}Ed(a);}\nfunction Cd(a){a.w&&(a.w.abort(),a.w=null);a.a&&(a.a.cancel(),a.a=null);a.l&&(k.clearTimeout(a.l),a.l=null);Fd(a);a.b.cancel();a.h&&(aa(a.h)&&k.clearTimeout(a.h),a.h=null);}function Gd(a,b){a.f.push(new $c(a.Ra++,b));3==a.u&&Hd(a);}g.Da=function(){return 0==this.u};function Hd(a){ed(a.b)||a.h||(a.h=!0,wb(a.Ia,a),a.A=0);}\nfunction Id(a,b){if(fd(a.b)>=a.b.f-(a.h?1:0))return !1;if(a.h)return a.f=b.j.concat(a.f),!0;if(1==a.u||2==a.u||a.A>=(a.Pa?0:a.Qa))return !1;a.h=Ob(u(a.Ia,a,b),Jd(a,a.A));a.A++;return !0}\ng.Ia=function(a){if(this.h)if(this.h=null,1==this.u){if(!a){this.P=Math.floor(1E5*Math.random());a=this.P++;var b=new M(this,a,void 0),c=this.i;this.J&&(c?(c=wa(c),ya(c,this.J)):c=this.J);null===this.g&&(b.h=c);var d;if(this.W)a:{for(var e=d=0;eBb)f=Math.max(0,e[F].b-100),l=!1;else try{ld(Tc,h,\"req\"+Bb+\"_\");}catch(Ud){d&&d(Tc);}}if(l){d=h.join(\"&\");break a}}a=a.f.splice(0,c);b.j=a;return d}function Md(a){a.a||a.l||(a.S=1,wb(a.Ha,a),a.v=0);}\nfunction Nd(a){if(a.a||a.l||3<=a.v)return !1;a.S++;a.l=Ob(u(a.Ha,a),Jd(a,a.v));a.v++;return !0}g.Ha=function(){this.l=null;this.a=new M(this,\"rpc\",this.S);null===this.g&&(this.a.h=this.i);this.a.J=0;var a=N(this.pa);T(a,\"RID\",\"rpc\");T(a,\"SID\",this.H);T(a,\"CI\",this.ia?\"0\":\"1\");T(a,\"AID\",this.O);Dd(this,a);T(a,\"TYPE\",\"xmlhttp\");this.g&&this.i&&zd(a,this.g,this.i);this.D&&this.a.setTimeout(this.D);dc(this.a,a,!0,this.ga);};\nfunction Vc(a,b,c){var d=b.l;d&&cd(a.b,d);a.ia=a.oa&&c;a.m=b.c;a.B=Wc(a,null,a.ha);Hd(a);}\ng.Ga=function(a,b){if(0!=this.u&&(this.a==a||gd(this.b,a)))if(this.m=a.o,!a.s&&gd(this.b,a)&&3==this.u){try{var c=this.ja.a.parse(b);}catch(f){c=null;}if(q(c)&&3==c.length){b=c;if(0==b[0])a:{if(!this.l){if(this.a)if(this.a.v+3E3b[2]&&this.ia&&0==this.v&&!this.s&&(this.s=Ob(u(this.Za,this),6E3));if(1>=fd(this.b)&&this.fa){try{this.fa();}catch(f){}this.fa=void 0;}}else W(this,11);}else if((a.s||\nthis.a==a)&&Fd(this),!qa(b))for(b=c=this.ja.a.parse(b),c=0;c maxNumberOfArgs) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires between \" + minNumberOfArgs + \" and \" +\r\n (maxNumberOfArgs + \" arguments, but was called with \") +\r\n formatPlural(args.length, 'argument') +\r\n '.');\r\n }\r\n}\r\n/**\r\n * Validates the provided argument is an array and has as least the expected\r\n * number of elements.\r\n */\r\nfunction validateNamedArrayAtLeastNumberOfElements(functionName, value, name, minNumberOfElements) {\r\n if (!(value instanceof Array) || value.length < minNumberOfElements) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires its \" + name + \" argument to be an \" +\r\n 'array with at least ' +\r\n (formatPlural(minNumberOfElements, 'element') + \".\"));\r\n }\r\n}\r\n/**\r\n * Validates the provided positional argument has the native JavaScript type\r\n * using typeof checks.\r\n */\r\nfunction validateArgType(functionName, type, position, argument) {\r\n validateType(functionName, type, ordinal(position) + \" argument\", argument);\r\n}\r\n/**\r\n * Validates the provided argument has the native JavaScript type using\r\n * typeof checks or is undefined.\r\n */\r\nfunction validateOptionalArgType(functionName, type, position, argument) {\r\n if (argument !== undefined) {\r\n validateArgType(functionName, type, position, argument);\r\n }\r\n}\r\n/**\r\n * Validates the provided named option has the native JavaScript type using\r\n * typeof checks.\r\n */\r\nfunction validateNamedType(functionName, type, optionName, argument) {\r\n validateType(functionName, type, optionName + \" option\", argument);\r\n}\r\n/**\r\n * Validates the provided named option has the native JavaScript type using\r\n * typeof checks or is undefined.\r\n */\r\nfunction validateNamedOptionalType(functionName, type, optionName, argument) {\r\n if (argument !== undefined) {\r\n validateNamedType(functionName, type, optionName, argument);\r\n }\r\n}\r\nfunction validateArrayElements(functionName, optionName, typeDescription, argument, validator) {\r\n if (!(argument instanceof Array)) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires its \" + optionName + \" \" +\r\n (\"option to be an array, but it was: \" + valueDescription(argument)));\r\n }\r\n for (var i = 0; i < argument.length; ++i) {\r\n if (!validator(argument[i])) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires all \" + optionName + \" \" +\r\n (\"elements to be \" + typeDescription + \", but the value at index \" + i + \" \") +\r\n (\"was: \" + valueDescription(argument[i])));\r\n }\r\n }\r\n}\r\nfunction validateOptionalArrayElements(functionName, optionName, typeDescription, argument, validator) {\r\n if (argument !== undefined) {\r\n validateArrayElements(functionName, optionName, typeDescription, argument, validator);\r\n }\r\n}\r\n/**\r\n * Validates that the provided named option equals one of the expected values.\r\n */\r\nfunction validateNamedPropertyEquals(functionName, inputName, optionName, input, expected) {\r\n var expectedDescription = [];\r\n for (var _i = 0, expected_1 = expected; _i < expected_1.length; _i++) {\r\n var val = expected_1[_i];\r\n if (val === input) {\r\n return;\r\n }\r\n expectedDescription.push(valueDescription(val));\r\n }\r\n var actualDescription = valueDescription(input);\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid value \" + actualDescription + \" provided to function \" + functionName + \"() for option \" +\r\n (\"\\\"\" + optionName + \"\\\". Acceptable values: \" + expectedDescription.join(', ')));\r\n}\r\n/**\r\n * Validates that the provided named option equals one of the expected values or\r\n * is undefined.\r\n */\r\nfunction validateNamedOptionalPropertyEquals(functionName, inputName, optionName, input, expected) {\r\n if (input !== undefined) {\r\n validateNamedPropertyEquals(functionName, inputName, optionName, input, expected);\r\n }\r\n}\r\n/**\r\n * Validates that the provided argument is a valid enum.\r\n *\r\n * @param functionName Function making the validation call.\r\n * @param enums Array containing all possible values for the enum.\r\n * @param position Position of the argument in `functionName`.\r\n * @param argument Arugment to validate.\r\n */\r\nfunction validateStringEnum(functionName, enums, position, argument) {\r\n if (!enums.some(function (element) { return element === argument; })) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid value \" + valueDescription(argument) + \" provided to function \" +\r\n (functionName + \"() for its \" + ordinal(position) + \" argument. Acceptable \") +\r\n (\"values: \" + enums.join(', ')));\r\n }\r\n}\r\n/** Helper to validate the type of a provided input. */\r\nfunction validateType(functionName, type, inputName, input) {\r\n var valid = false;\r\n if (type === 'object') {\r\n valid = isPlainObject(input);\r\n }\r\n else if (type === 'non-empty string') {\r\n valid = typeof input === 'string' && input !== '';\r\n }\r\n else {\r\n valid = typeof input === type;\r\n }\r\n if (!valid) {\r\n var description = valueDescription(input);\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires its \" + inputName + \" \" +\r\n (\"to be of type \" + type + \", but it was: \" + description));\r\n }\r\n}\r\n/**\r\n * Returns true if it's a non-null object without a custom prototype\r\n * (i.e. excludes Array, Date, etc.).\r\n */\r\nfunction isPlainObject(input) {\r\n return (typeof input === 'object' &&\r\n input !== null &&\r\n (Object.getPrototypeOf(input) === Object.prototype ||\r\n Object.getPrototypeOf(input) === null));\r\n}\r\n/** Returns a string describing the type / value of the provided input. */\r\nfunction valueDescription(input) {\r\n if (input === undefined) {\r\n return 'undefined';\r\n }\r\n else if (input === null) {\r\n return 'null';\r\n }\r\n else if (typeof input === 'string') {\r\n if (input.length > 20) {\r\n input = input.substring(0, 20) + \"...\";\r\n }\r\n return JSON.stringify(input);\r\n }\r\n else if (typeof input === 'number' || typeof input === 'boolean') {\r\n return '' + input;\r\n }\r\n else if (typeof input === 'object') {\r\n if (input instanceof Array) {\r\n return 'an array';\r\n }\r\n else {\r\n var customObjectName = tryGetCustomObjectType(input);\r\n if (customObjectName) {\r\n return \"a custom \" + customObjectName + \" object\";\r\n }\r\n else {\r\n return 'an object';\r\n }\r\n }\r\n }\r\n else if (typeof input === 'function') {\r\n return 'a function';\r\n }\r\n else {\r\n return fail('Unknown wrong type: ' + typeof input);\r\n }\r\n}\r\n/** Hacky method to try to get the constructor name for an object. */\r\nfunction tryGetCustomObjectType(input) {\r\n if (input.constructor) {\r\n var funcNameRegex = /function\\s+([^\\s(]+)\\s*\\(/;\r\n var results = funcNameRegex.exec(input.constructor.toString());\r\n if (results && results.length > 1) {\r\n return results[1];\r\n }\r\n }\r\n return null;\r\n}\r\n/** Validates the provided argument is defined. */\r\nfunction validateDefined(functionName, position, argument) {\r\n if (argument === undefined) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires a valid \" + ordinal(position) + \" \" +\r\n \"argument, but it was undefined.\");\r\n }\r\n}\r\n/**\r\n * Validates the provided positional argument is an object, and its keys and\r\n * values match the expected keys and types provided in optionTypes.\r\n */\r\nfunction validateOptionNames(functionName, options, optionNames) {\r\n forEach(options, function (key, _) {\r\n if (optionNames.indexOf(key) < 0) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Unknown option '\" + key + \"' passed to function \" + functionName + \"(). \" +\r\n 'Available options: ' +\r\n optionNames.join(', '));\r\n }\r\n });\r\n}\r\n/**\r\n * Helper method to throw an error that the provided argument did not pass\r\n * an instanceof check.\r\n */\r\nfunction invalidClassError(functionName, type, position, argument) {\r\n var description = valueDescription(argument);\r\n return new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires its \" + ordinal(position) + \" \" +\r\n (\"argument to be a \" + type + \", but it was: \" + description));\r\n}\r\n/** Converts a number to its english word representation */\r\nfunction ordinal(num) {\r\n switch (num) {\r\n case 1:\r\n return 'first';\r\n case 2:\r\n return 'second';\r\n case 3:\r\n return 'third';\r\n default:\r\n return num + 'th';\r\n }\r\n}\r\n/**\r\n * Formats the given word as plural conditionally given the preceding number.\r\n */\r\nfunction formatPlural(num, str) {\r\n return num + \" \" + str + (num === 1 ? '' : 's');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// tslint:disable-next-line:class-as-namespace\r\nvar AutoId = /** @class */ (function () {\r\n function AutoId() {\r\n }\r\n AutoId.newId = function () {\r\n // Alphanumeric characters\r\n var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\r\n var autoId = '';\r\n for (var i = 0; i < 20; i++) {\r\n autoId += chars.charAt(Math.floor(Math.random() * chars.length));\r\n }\r\n assert(autoId.length === 20, 'Invalid auto ID: ' + autoId);\r\n return autoId;\r\n };\r\n return AutoId;\r\n}());\r\nfunction primitiveComparator(left, right) {\r\n if (left < right)\r\n return -1;\r\n if (left > right)\r\n return 1;\r\n return 0;\r\n}\r\n/** Helper to compare nullable (or undefined-able) objects using isEqual(). */\r\nfunction equals(left, right) {\r\n if (left !== null && left !== undefined) {\r\n return !!(right && left.isEqual(right));\r\n }\r\n else {\r\n // HACK: Explicitly cast since TypeScript's type narrowing apparently isn't\r\n // smart enough.\r\n return left === right;\r\n }\r\n}\r\n/** Helper to compare arrays using isEqual(). */\r\nfunction arrayEquals(left, right) {\r\n if (left.length !== right.length) {\r\n return false;\r\n }\r\n for (var i = 0; i < left.length; i++) {\r\n if (!left[i].isEqual(right[i])) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\n/**\r\n * Returns the immediate lexicographically-following string. This is useful to\r\n * construct an inclusive range for indexeddb iterators.\r\n */\r\nfunction immediateSuccessor(s) {\r\n // Return the input string, with an additional NUL byte appended.\r\n return s + '\\0';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** Helper function to assert Uint8Array is available at runtime. */\r\nfunction assertUint8ArrayAvailable() {\r\n if (typeof Uint8Array === 'undefined') {\r\n throw new FirestoreError(Code.UNIMPLEMENTED, 'Uint8Arrays are not available in this environment.');\r\n }\r\n}\r\n/** Helper function to assert Base64 functions are available at runtime. */\r\nfunction assertBase64Available() {\r\n if (!PlatformSupport.getPlatform().base64Available) {\r\n throw new FirestoreError(Code.UNIMPLEMENTED, 'Blobs are unavailable in Firestore in this environment.');\r\n }\r\n}\r\n/**\r\n * Immutable class holding a blob (binary data).\r\n * This class is directly exposed in the public API.\r\n *\r\n * Note that while you can't hide the constructor in JavaScript code, we are\r\n * using the hack above to make sure no-one outside this module can call it.\r\n */\r\nvar Blob = /** @class */ (function () {\r\n function Blob(binaryString) {\r\n assertBase64Available();\r\n this._binaryString = binaryString;\r\n }\r\n Blob.fromBase64String = function (base64) {\r\n validateExactNumberOfArgs('Blob.fromBase64String', arguments, 1);\r\n validateArgType('Blob.fromBase64String', 'string', 1, base64);\r\n assertBase64Available();\r\n try {\r\n var binaryString = PlatformSupport.getPlatform().atob(base64);\r\n return new Blob(binaryString);\r\n }\r\n catch (e) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Failed to construct Blob from Base64 string: ' + e);\r\n }\r\n };\r\n Blob.fromUint8Array = function (array) {\r\n validateExactNumberOfArgs('Blob.fromUint8Array', arguments, 1);\r\n assertUint8ArrayAvailable();\r\n if (!(array instanceof Uint8Array)) {\r\n throw invalidClassError('Blob.fromUint8Array', 'Uint8Array', 1, array);\r\n }\r\n // We can't call array.map directly because it expects the return type to\r\n // be a Uint8Array, whereas we can convert it to a regular array by invoking\r\n // map on the Array prototype.\r\n var binaryString = Array.prototype.map\r\n .call(array, function (char) {\r\n return String.fromCharCode(char);\r\n })\r\n .join('');\r\n return new Blob(binaryString);\r\n };\r\n Blob.prototype.toBase64 = function () {\r\n validateExactNumberOfArgs('Blob.toBase64', arguments, 0);\r\n assertBase64Available();\r\n return PlatformSupport.getPlatform().btoa(this._binaryString);\r\n };\r\n Blob.prototype.toUint8Array = function () {\r\n validateExactNumberOfArgs('Blob.toUint8Array', arguments, 0);\r\n assertUint8ArrayAvailable();\r\n var buffer = new Uint8Array(this._binaryString.length);\r\n for (var i = 0; i < this._binaryString.length; i++) {\r\n buffer[i] = this._binaryString.charCodeAt(i);\r\n }\r\n return buffer;\r\n };\r\n Blob.prototype.toString = function () {\r\n return 'Blob(base64: ' + this.toBase64() + ')';\r\n };\r\n Blob.prototype.isEqual = function (other) {\r\n return this._binaryString === other._binaryString;\r\n };\r\n /**\r\n * Actually private to JS consumers of our API, so this function is prefixed\r\n * with an underscore.\r\n */\r\n Blob.prototype._compareTo = function (other) {\r\n return primitiveComparator(this._binaryString, other._binaryString);\r\n };\r\n return Blob;\r\n}());\r\n// Public instance that disallows construction at runtime. This constructor is\r\n// used when exporting Blob on firebase.firestore.Blob and will be called Blob\r\n// publicly. Internally we still use Blob which has a type checked private\r\n// constructor. Note that Blob and PublicBlob can be used interchangeably in\r\n// instanceof checks.\r\n// For our internal TypeScript code PublicBlob doesn't exist as a type, and so\r\n// we need to use Blob as type and export it too.\r\n// tslint:disable-next-line:variable-name We're treating this as a class name.\r\nvar PublicBlob = makeConstructorPrivate(Blob, 'Use Blob.fromUint8Array() or Blob.fromBase64String() instead.');\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Immutable class representing a geo point as latitude-longitude pair.\r\n * This class is directly exposed in the public API, including its constructor.\r\n */\r\nvar GeoPoint = /** @class */ (function () {\r\n function GeoPoint(latitude, longitude) {\r\n validateExactNumberOfArgs('GeoPoint', arguments, 2);\r\n validateArgType('GeoPoint', 'number', 1, latitude);\r\n validateArgType('GeoPoint', 'number', 2, longitude);\r\n if (!isFinite(latitude) || latitude < -90 || latitude > 90) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Latitude must be a number between -90 and 90, but was: ' + latitude);\r\n }\r\n if (!isFinite(longitude) || longitude < -180 || longitude > 180) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Longitude must be a number between -180 and 180, but was: ' + longitude);\r\n }\r\n this._lat = latitude;\r\n this._long = longitude;\r\n }\r\n Object.defineProperty(GeoPoint.prototype, \"latitude\", {\r\n /**\r\n * Returns the latitude of this geo point, a number between -90 and 90.\r\n */\r\n get: function () {\r\n return this._lat;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(GeoPoint.prototype, \"longitude\", {\r\n /**\r\n * Returns the longitude of this geo point, a number between -180 and 180.\r\n */\r\n get: function () {\r\n return this._long;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n GeoPoint.prototype.isEqual = function (other) {\r\n return this._lat === other._lat && this._long === other._long;\r\n };\r\n /**\r\n * Actually private to JS consumers of our API, so this function is prefixed\r\n * with an underscore.\r\n */\r\n GeoPoint.prototype._compareTo = function (other) {\r\n return (primitiveComparator(this._lat, other._lat) ||\r\n primitiveComparator(this._long, other._long));\r\n };\r\n return GeoPoint;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar Timestamp = /** @class */ (function () {\r\n function Timestamp(seconds, nanoseconds) {\r\n this.seconds = seconds;\r\n this.nanoseconds = nanoseconds;\r\n if (nanoseconds < 0) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp nanoseconds out of range: ' + nanoseconds);\r\n }\r\n if (nanoseconds >= 1e9) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp nanoseconds out of range: ' + nanoseconds);\r\n }\r\n // Midnight at the beginning of 1/1/1 is the earliest Firestore supports.\r\n if (seconds < -62135596800) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp seconds out of range: ' + seconds);\r\n }\r\n // This will break in the year 10,000.\r\n if (seconds >= 253402300800) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp seconds out of range: ' + seconds);\r\n }\r\n }\r\n Timestamp.now = function () {\r\n return Timestamp.fromMillis(Date.now());\r\n };\r\n Timestamp.fromDate = function (date) {\r\n return Timestamp.fromMillis(date.getTime());\r\n };\r\n Timestamp.fromMillis = function (milliseconds) {\r\n var seconds = Math.floor(milliseconds / 1000);\r\n var nanos = (milliseconds - seconds * 1000) * 1e6;\r\n return new Timestamp(seconds, nanos);\r\n };\r\n Timestamp.prototype.toDate = function () {\r\n return new Date(this.toMillis());\r\n };\r\n Timestamp.prototype.toMillis = function () {\r\n return this.seconds * 1000 + this.nanoseconds / 1e6;\r\n };\r\n Timestamp.prototype._compareTo = function (other) {\r\n if (this.seconds === other.seconds) {\r\n return primitiveComparator(this.nanoseconds, other.nanoseconds);\r\n }\r\n return primitiveComparator(this.seconds, other.seconds);\r\n };\r\n Timestamp.prototype.isEqual = function (other) {\r\n return (other.seconds === this.seconds && other.nanoseconds === this.nanoseconds);\r\n };\r\n Timestamp.prototype.toString = function () {\r\n return ('Timestamp(seconds=' +\r\n this.seconds +\r\n ', nanoseconds=' +\r\n this.nanoseconds +\r\n ')');\r\n };\r\n return Timestamp;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar DatabaseInfo = /** @class */ (function () {\r\n /**\r\n * Constructs a DatabaseInfo using the provided host, databaseId and\r\n * persistenceKey.\r\n *\r\n * @param databaseId The database to use.\r\n * @param persistenceKey A unique identifier for this Firestore's local\r\n * storage (used in conjunction with the databaseId).\r\n * @param host The Firestore backend host to connect to.\r\n * @param ssl Whether to use SSL when connecting.\r\n * @param forceLongPolling Whether to use the forceLongPolling option\r\n * when using WebChannel as the network transport.\r\n */\r\n function DatabaseInfo(databaseId, persistenceKey, host, ssl, forceLongPolling) {\r\n this.databaseId = databaseId;\r\n this.persistenceKey = persistenceKey;\r\n this.host = host;\r\n this.ssl = ssl;\r\n this.forceLongPolling = forceLongPolling;\r\n }\r\n return DatabaseInfo;\r\n}());\r\n/** The default database name for a project. */\r\nvar DEFAULT_DATABASE_NAME = '(default)';\r\n/** Represents the database ID a Firestore client is associated with. */\r\nvar DatabaseId = /** @class */ (function () {\r\n function DatabaseId(projectId, database) {\r\n this.projectId = projectId;\r\n this.database = database ? database : DEFAULT_DATABASE_NAME;\r\n }\r\n Object.defineProperty(DatabaseId.prototype, \"isDefaultDatabase\", {\r\n get: function () {\r\n return this.database === DEFAULT_DATABASE_NAME;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n DatabaseId.prototype.isEqual = function (other) {\r\n return (other instanceof DatabaseId &&\r\n other.projectId === this.projectId &&\r\n other.database === this.database);\r\n };\r\n DatabaseId.prototype.compareTo = function (other) {\r\n return (primitiveComparator(this.projectId, other.projectId) ||\r\n primitiveComparator(this.database, other.database));\r\n };\r\n return DatabaseId;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar DOCUMENT_KEY_NAME = '__name__';\r\n/**\r\n * Path represents an ordered sequence of string segments.\r\n */\r\nvar Path = /** @class */ (function () {\r\n function Path(segments, offset, length) {\r\n this.init(segments, offset, length);\r\n }\r\n /**\r\n * An initialization method that can be called from outside the constructor.\r\n * We need this so that we can have a non-static construct method that returns\r\n * the polymorphic `this` type.\r\n */\r\n Path.prototype.init = function (segments, offset, length) {\r\n if (offset === undefined) {\r\n offset = 0;\r\n }\r\n else if (offset > segments.length) {\r\n fail('offset ' + offset + ' out of range ' + segments.length);\r\n }\r\n if (length === undefined) {\r\n length = segments.length - offset;\r\n }\r\n else if (length > segments.length - offset) {\r\n fail('length ' + length + ' out of range ' + (segments.length - offset));\r\n }\r\n this.segments = segments;\r\n this.offset = offset;\r\n this.len = length;\r\n };\r\n /**\r\n * Constructs a new instance of Path using the same concrete type as `this`.\r\n * We need this instead of using the normal constructor, because polymorphic\r\n * `this` doesn't work on static methods.\r\n */\r\n Path.prototype.construct = function (segments, offset, length) {\r\n var path = Object.create(Object.getPrototypeOf(this));\r\n path.init(segments, offset, length);\r\n return path;\r\n };\r\n Object.defineProperty(Path.prototype, \"length\", {\r\n get: function () {\r\n return this.len;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Path.prototype.isEqual = function (other) {\r\n return Path.comparator(this, other) === 0;\r\n };\r\n Path.prototype.child = function (nameOrPath) {\r\n var segments = this.segments.slice(this.offset, this.limit());\r\n if (nameOrPath instanceof Path) {\r\n nameOrPath.forEach(function (segment) {\r\n segments.push(segment);\r\n });\r\n }\r\n else if (typeof nameOrPath === 'string') {\r\n segments.push(nameOrPath);\r\n }\r\n else {\r\n fail('Unknown parameter type for Path.child(): ' + nameOrPath);\r\n }\r\n return this.construct(segments);\r\n };\r\n /** The index of one past the last segment of the path. */\r\n Path.prototype.limit = function () {\r\n return this.offset + this.length;\r\n };\r\n Path.prototype.popFirst = function (size) {\r\n size = size === undefined ? 1 : size;\r\n assert(this.length >= size, \"Can't call popFirst() with less segments\");\r\n return this.construct(this.segments, this.offset + size, this.length - size);\r\n };\r\n Path.prototype.popLast = function () {\r\n assert(!this.isEmpty(), \"Can't call popLast() on empty path\");\r\n return this.construct(this.segments, this.offset, this.length - 1);\r\n };\r\n Path.prototype.firstSegment = function () {\r\n assert(!this.isEmpty(), \"Can't call firstSegment() on empty path\");\r\n return this.segments[this.offset];\r\n };\r\n Path.prototype.lastSegment = function () {\r\n return this.get(this.length - 1);\r\n };\r\n Path.prototype.get = function (index) {\r\n assert(index < this.length, 'Index out of range');\r\n return this.segments[this.offset + index];\r\n };\r\n Path.prototype.isEmpty = function () {\r\n return this.length === 0;\r\n };\r\n Path.prototype.isPrefixOf = function (other) {\r\n if (other.length < this.length) {\r\n return false;\r\n }\r\n for (var i = 0; i < this.length; i++) {\r\n if (this.get(i) !== other.get(i)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n };\r\n Path.prototype.isImmediateParentOf = function (potentialChild) {\r\n if (this.length + 1 !== potentialChild.length) {\r\n return false;\r\n }\r\n for (var i = 0; i < this.length; i++) {\r\n if (this.get(i) !== potentialChild.get(i)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n };\r\n Path.prototype.forEach = function (fn) {\r\n for (var i = this.offset, end = this.limit(); i < end; i++) {\r\n fn(this.segments[i]);\r\n }\r\n };\r\n Path.prototype.toArray = function () {\r\n return this.segments.slice(this.offset, this.limit());\r\n };\r\n Path.comparator = function (p1, p2) {\r\n var len = Math.min(p1.length, p2.length);\r\n for (var i = 0; i < len; i++) {\r\n var left = p1.get(i);\r\n var right = p2.get(i);\r\n if (left < right)\r\n return -1;\r\n if (left > right)\r\n return 1;\r\n }\r\n if (p1.length < p2.length)\r\n return -1;\r\n if (p1.length > p2.length)\r\n return 1;\r\n return 0;\r\n };\r\n return Path;\r\n}());\r\n/**\r\n * A slash-separated path for navigating resources (documents and collections)\r\n * within Firestore.\r\n */\r\nvar ResourcePath = /** @class */ (function (_super) {\r\n tslib_1.__extends(ResourcePath, _super);\r\n function ResourcePath() {\r\n return _super !== null && _super.apply(this, arguments) || this;\r\n }\r\n ResourcePath.prototype.canonicalString = function () {\r\n // NOTE: The client is ignorant of any path segments containing escape\r\n // sequences (e.g. __id123__) and just passes them through raw (they exist\r\n // for legacy reasons and should not be used frequently).\r\n return this.toArray().join('/');\r\n };\r\n ResourcePath.prototype.toString = function () {\r\n return this.canonicalString();\r\n };\r\n /**\r\n * Creates a resource path from the given slash-delimited string.\r\n */\r\n ResourcePath.fromString = function (path) {\r\n // NOTE: The client is ignorant of any path segments containing escape\r\n // sequences (e.g. __id123__) and just passes them through raw (they exist\r\n // for legacy reasons and should not be used frequently).\r\n if (path.indexOf('//') >= 0) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid path (\" + path + \"). Paths must not contain // in them.\");\r\n }\r\n // We may still have an empty segment at the beginning or end if they had a\r\n // leading or trailing slash (which we allow).\r\n var segments = path.split('/').filter(function (segment) { return segment.length > 0; });\r\n return new ResourcePath(segments);\r\n };\r\n ResourcePath.EMPTY_PATH = new ResourcePath([]);\r\n return ResourcePath;\r\n}(Path));\r\nvar identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/;\r\n/** A dot-separated path for navigating sub-objects within a document. */\r\nvar FieldPath = /** @class */ (function (_super) {\r\n tslib_1.__extends(FieldPath, _super);\r\n function FieldPath() {\r\n return _super !== null && _super.apply(this, arguments) || this;\r\n }\r\n /**\r\n * Returns true if the string could be used as a segment in a field path\r\n * without escaping.\r\n */\r\n FieldPath.isValidIdentifier = function (segment) {\r\n return identifierRegExp.test(segment);\r\n };\r\n FieldPath.prototype.canonicalString = function () {\r\n return this.toArray()\r\n .map(function (str) {\r\n str = str.replace('\\\\', '\\\\\\\\').replace('`', '\\\\`');\r\n if (!FieldPath.isValidIdentifier(str)) {\r\n str = '`' + str + '`';\r\n }\r\n return str;\r\n })\r\n .join('.');\r\n };\r\n FieldPath.prototype.toString = function () {\r\n return this.canonicalString();\r\n };\r\n /**\r\n * Returns true if this field references the key of a document.\r\n */\r\n FieldPath.prototype.isKeyField = function () {\r\n return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME;\r\n };\r\n /**\r\n * The field designating the key of a document.\r\n */\r\n FieldPath.keyField = function () {\r\n return new FieldPath([DOCUMENT_KEY_NAME]);\r\n };\r\n /**\r\n * Parses a field string from the given server-formatted string.\r\n *\r\n * - Splitting the empty string is not allowed (for now at least).\r\n * - Empty segments within the string (e.g. if there are two consecutive\r\n * separators) are not allowed.\r\n *\r\n * TODO(b/37244157): we should make this more strict. Right now, it allows\r\n * non-identifier path components, even if they aren't escaped.\r\n */\r\n FieldPath.fromServerFormat = function (path) {\r\n var segments = [];\r\n var current = '';\r\n var i = 0;\r\n var addCurrentSegment = function () {\r\n if (current.length === 0) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field path (\" + path + \"). Paths must not be empty, begin \" +\r\n \"with '.', end with '.', or contain '..'\");\r\n }\r\n segments.push(current);\r\n current = '';\r\n };\r\n var inBackticks = false;\r\n while (i < path.length) {\r\n var c = path[i];\r\n if (c === '\\\\') {\r\n if (i + 1 === path.length) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has trailing escape character: ' + path);\r\n }\r\n var next = path[i + 1];\r\n if (!(next === '\\\\' || next === '.' || next === '`')) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has invalid escape sequence: ' + path);\r\n }\r\n current += next;\r\n i += 2;\r\n }\r\n else if (c === '`') {\r\n inBackticks = !inBackticks;\r\n i++;\r\n }\r\n else if (c === '.' && !inBackticks) {\r\n addCurrentSegment();\r\n i++;\r\n }\r\n else {\r\n current += c;\r\n i++;\r\n }\r\n }\r\n addCurrentSegment();\r\n if (inBackticks) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Unterminated ` in path: ' + path);\r\n }\r\n return new FieldPath(segments);\r\n };\r\n FieldPath.EMPTY_PATH = new FieldPath([]);\r\n return FieldPath;\r\n}(Path));\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar DocumentKey = /** @class */ (function () {\r\n function DocumentKey(path) {\r\n this.path = path;\r\n assert(DocumentKey.isDocumentKey(path), 'Invalid DocumentKey with an odd number of segments: ' +\r\n path.toArray().join('/'));\r\n }\r\n /** Returns true if the document is in the specified collectionId. */\r\n DocumentKey.prototype.hasCollectionId = function (collectionId) {\r\n return (this.path.length >= 2 &&\r\n this.path.get(this.path.length - 2) === collectionId);\r\n };\r\n DocumentKey.prototype.isEqual = function (other) {\r\n return (other !== null && ResourcePath.comparator(this.path, other.path) === 0);\r\n };\r\n DocumentKey.prototype.toString = function () {\r\n return this.path.toString();\r\n };\r\n DocumentKey.comparator = function (k1, k2) {\r\n return ResourcePath.comparator(k1.path, k2.path);\r\n };\r\n DocumentKey.isDocumentKey = function (path) {\r\n return path.length % 2 === 0;\r\n };\r\n /**\r\n * Creates and returns a new document key with the given segments.\r\n *\r\n * @param path The segments of the path to the document\r\n * @return A new instance of DocumentKey\r\n */\r\n DocumentKey.fromSegments = function (segments) {\r\n return new DocumentKey(new ResourcePath(segments.slice()));\r\n };\r\n /**\r\n * Creates and returns a new document key using '/' to split the string into\r\n * segments.\r\n *\r\n * @param path The slash-separated path string to the document\r\n * @return A new instance of DocumentKey\r\n */\r\n DocumentKey.fromPathString = function (path) {\r\n return new DocumentKey(ResourcePath.fromString(path));\r\n };\r\n DocumentKey.EMPTY = new DocumentKey(new ResourcePath([]));\r\n return DocumentKey;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The result of a lookup for a given path may be an existing document or a\r\n * marker that this document does not exist at a given version.\r\n */\r\nvar MaybeDocument = /** @class */ (function () {\r\n function MaybeDocument(key, version) {\r\n this.key = key;\r\n this.version = version;\r\n }\r\n MaybeDocument.compareByKey = function (d1, d2) {\r\n return DocumentKey.comparator(d1.key, d2.key);\r\n };\r\n return MaybeDocument;\r\n}());\r\n/**\r\n * Represents a document in Firestore with a key, version, data and whether the\r\n * data has local mutations applied to it.\r\n */\r\nvar Document = /** @class */ (function (_super) {\r\n tslib_1.__extends(Document, _super);\r\n function Document(key, version, data, options, \r\n /**\r\n * Memoized serialized form of the document for optimization purposes (avoids repeated\r\n * serialization). Might be undefined.\r\n */\r\n proto) {\r\n var _this = _super.call(this, key, version) || this;\r\n _this.data = data;\r\n _this.proto = proto;\r\n _this.hasLocalMutations = !!options.hasLocalMutations;\r\n _this.hasCommittedMutations = !!options.hasCommittedMutations;\r\n return _this;\r\n }\r\n Document.prototype.field = function (path) {\r\n return this.data.field(path);\r\n };\r\n Document.prototype.fieldValue = function (path) {\r\n var field = this.field(path);\r\n return field ? field.value() : undefined;\r\n };\r\n Document.prototype.value = function () {\r\n return this.data.value();\r\n };\r\n Document.prototype.isEqual = function (other) {\r\n return (other instanceof Document &&\r\n this.key.isEqual(other.key) &&\r\n this.version.isEqual(other.version) &&\r\n this.data.isEqual(other.data) &&\r\n this.hasLocalMutations === other.hasLocalMutations &&\r\n this.hasCommittedMutations === other.hasCommittedMutations);\r\n };\r\n Document.prototype.toString = function () {\r\n return (\"Document(\" + this.key + \", \" + this.version + \", \" + this.data.toString() + \", \" +\r\n (\"{hasLocalMutations: \" + this.hasLocalMutations + \"}), \") +\r\n (\"{hasCommittedMutations: \" + this.hasCommittedMutations + \"})\"));\r\n };\r\n Object.defineProperty(Document.prototype, \"hasPendingWrites\", {\r\n get: function () {\r\n return this.hasLocalMutations || this.hasCommittedMutations;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Document.compareByField = function (field, d1, d2) {\r\n var v1 = d1.field(field);\r\n var v2 = d2.field(field);\r\n if (v1 !== undefined && v2 !== undefined) {\r\n return v1.compareTo(v2);\r\n }\r\n else {\r\n return fail(\"Trying to compare documents on fields that don't exist\");\r\n }\r\n };\r\n return Document;\r\n}(MaybeDocument));\r\n/**\r\n * A class representing a deleted document.\r\n * Version is set to 0 if we don't point to any specific time, otherwise it\r\n * denotes time we know it didn't exist at.\r\n */\r\nvar NoDocument = /** @class */ (function (_super) {\r\n tslib_1.__extends(NoDocument, _super);\r\n function NoDocument(key, version, options) {\r\n var _this = _super.call(this, key, version) || this;\r\n _this.hasCommittedMutations = !!(options && options.hasCommittedMutations);\r\n return _this;\r\n }\r\n NoDocument.prototype.toString = function () {\r\n return \"NoDocument(\" + this.key + \", \" + this.version + \")\";\r\n };\r\n Object.defineProperty(NoDocument.prototype, \"hasPendingWrites\", {\r\n get: function () {\r\n return this.hasCommittedMutations;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n NoDocument.prototype.isEqual = function (other) {\r\n return (other instanceof NoDocument &&\r\n other.hasCommittedMutations === this.hasCommittedMutations &&\r\n other.version.isEqual(this.version) &&\r\n other.key.isEqual(this.key));\r\n };\r\n return NoDocument;\r\n}(MaybeDocument));\r\n/**\r\n * A class representing an existing document whose data is unknown (e.g. a\r\n * document that was updated without a known base document).\r\n */\r\nvar UnknownDocument = /** @class */ (function (_super) {\r\n tslib_1.__extends(UnknownDocument, _super);\r\n function UnknownDocument(key, version) {\r\n return _super.call(this, key, version) || this;\r\n }\r\n UnknownDocument.prototype.toString = function () {\r\n return \"UnknownDocument(\" + this.key + \", \" + this.version + \")\";\r\n };\r\n Object.defineProperty(UnknownDocument.prototype, \"hasPendingWrites\", {\r\n get: function () {\r\n return true;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n UnknownDocument.prototype.isEqual = function (other) {\r\n return (other instanceof UnknownDocument &&\r\n other.version.isEqual(this.version) &&\r\n other.key.isEqual(this.key));\r\n };\r\n return UnknownDocument;\r\n}(MaybeDocument));\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// An immutable sorted map implementation, based on a Left-leaning Red-Black\r\n// tree.\r\nvar SortedMap = /** @class */ (function () {\r\n function SortedMap(comparator, root) {\r\n this.comparator = comparator;\r\n this.root = root ? root : LLRBNode.EMPTY;\r\n }\r\n // Returns a copy of the map, with the specified key/value added or replaced.\r\n SortedMap.prototype.insert = function (key, value) {\r\n return new SortedMap(this.comparator, this.root\r\n .insert(key, value, this.comparator)\r\n .copy(null, null, LLRBNode.BLACK, null, null));\r\n };\r\n // Returns a copy of the map, with the specified key removed.\r\n SortedMap.prototype.remove = function (key) {\r\n return new SortedMap(this.comparator, this.root\r\n .remove(key, this.comparator)\r\n .copy(null, null, LLRBNode.BLACK, null, null));\r\n };\r\n // Returns the value of the node with the given key, or null.\r\n SortedMap.prototype.get = function (key) {\r\n var node = this.root;\r\n while (!node.isEmpty()) {\r\n var cmp = this.comparator(key, node.key);\r\n if (cmp === 0) {\r\n return node.value;\r\n }\r\n else if (cmp < 0) {\r\n node = node.left;\r\n }\r\n else if (cmp > 0) {\r\n node = node.right;\r\n }\r\n }\r\n return null;\r\n };\r\n // Returns the index of the element in this sorted map, or -1 if it doesn't\r\n // exist.\r\n SortedMap.prototype.indexOf = function (key) {\r\n // Number of nodes that were pruned when descending right\r\n var prunedNodes = 0;\r\n var node = this.root;\r\n while (!node.isEmpty()) {\r\n var cmp = this.comparator(key, node.key);\r\n if (cmp === 0) {\r\n return prunedNodes + node.left.size;\r\n }\r\n else if (cmp < 0) {\r\n node = node.left;\r\n }\r\n else {\r\n // Count all nodes left of the node plus the node itself\r\n prunedNodes += node.left.size + 1;\r\n node = node.right;\r\n }\r\n }\r\n // Node not found\r\n return -1;\r\n };\r\n SortedMap.prototype.isEmpty = function () {\r\n return this.root.isEmpty();\r\n };\r\n Object.defineProperty(SortedMap.prototype, \"size\", {\r\n // Returns the total number of nodes in the map.\r\n get: function () {\r\n return this.root.size;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n // Returns the minimum key in the map.\r\n SortedMap.prototype.minKey = function () {\r\n return this.root.minKey();\r\n };\r\n // Returns the maximum key in the map.\r\n SortedMap.prototype.maxKey = function () {\r\n return this.root.maxKey();\r\n };\r\n // Traverses the map in key order and calls the specified action function\r\n // for each key/value pair. If action returns true, traversal is aborted.\r\n // Returns the first truthy value returned by action, or the last falsey\r\n // value returned by action.\r\n SortedMap.prototype.inorderTraversal = function (action) {\r\n return this.root.inorderTraversal(action);\r\n };\r\n SortedMap.prototype.forEach = function (fn) {\r\n this.inorderTraversal(function (k, v) {\r\n fn(k, v);\r\n return false;\r\n });\r\n };\r\n SortedMap.prototype.toString = function () {\r\n var descriptions = [];\r\n this.inorderTraversal(function (k, v) {\r\n descriptions.push(k + \":\" + v);\r\n return false;\r\n });\r\n return \"{\" + descriptions.join(', ') + \"}\";\r\n };\r\n // Traverses the map in reverse key order and calls the specified action\r\n // function for each key/value pair. If action returns true, traversal is\r\n // aborted.\r\n // Returns the first truthy value returned by action, or the last falsey\r\n // value returned by action.\r\n SortedMap.prototype.reverseTraversal = function (action) {\r\n return this.root.reverseTraversal(action);\r\n };\r\n // Returns an iterator over the SortedMap.\r\n SortedMap.prototype.getIterator = function () {\r\n return new SortedMapIterator(this.root, null, this.comparator, false);\r\n };\r\n SortedMap.prototype.getIteratorFrom = function (key) {\r\n return new SortedMapIterator(this.root, key, this.comparator, false);\r\n };\r\n SortedMap.prototype.getReverseIterator = function () {\r\n return new SortedMapIterator(this.root, null, this.comparator, true);\r\n };\r\n SortedMap.prototype.getReverseIteratorFrom = function (key) {\r\n return new SortedMapIterator(this.root, key, this.comparator, true);\r\n };\r\n return SortedMap;\r\n}()); // end SortedMap\r\n// An iterator over an LLRBNode.\r\nvar SortedMapIterator = /** @class */ (function () {\r\n function SortedMapIterator(node, startKey, comparator, isReverse) {\r\n this.isReverse = isReverse;\r\n this.nodeStack = [];\r\n var cmp = 1;\r\n while (!node.isEmpty()) {\r\n cmp = startKey ? comparator(node.key, startKey) : 1;\r\n // flip the comparison if we're going in reverse\r\n if (isReverse)\r\n cmp *= -1;\r\n if (cmp < 0) {\r\n // This node is less than our start key. ignore it\r\n if (this.isReverse) {\r\n node = node.left;\r\n }\r\n else {\r\n node = node.right;\r\n }\r\n }\r\n else if (cmp === 0) {\r\n // This node is exactly equal to our start key. Push it on the stack,\r\n // but stop iterating;\r\n this.nodeStack.push(node);\r\n break;\r\n }\r\n else {\r\n // This node is greater than our start key, add it to the stack and move\r\n // to the next one\r\n this.nodeStack.push(node);\r\n if (this.isReverse) {\r\n node = node.right;\r\n }\r\n else {\r\n node = node.left;\r\n }\r\n }\r\n }\r\n }\r\n SortedMapIterator.prototype.getNext = function () {\r\n assert(this.nodeStack.length > 0, 'getNext() called on iterator when hasNext() is false.');\r\n var node = this.nodeStack.pop();\r\n var result = { key: node.key, value: node.value };\r\n if (this.isReverse) {\r\n node = node.left;\r\n while (!node.isEmpty()) {\r\n this.nodeStack.push(node);\r\n node = node.right;\r\n }\r\n }\r\n else {\r\n node = node.right;\r\n while (!node.isEmpty()) {\r\n this.nodeStack.push(node);\r\n node = node.left;\r\n }\r\n }\r\n return result;\r\n };\r\n SortedMapIterator.prototype.hasNext = function () {\r\n return this.nodeStack.length > 0;\r\n };\r\n SortedMapIterator.prototype.peek = function () {\r\n if (this.nodeStack.length === 0)\r\n return null;\r\n var node = this.nodeStack[this.nodeStack.length - 1];\r\n return { key: node.key, value: node.value };\r\n };\r\n return SortedMapIterator;\r\n}()); // end SortedMapIterator\r\n// Represents a node in a Left-leaning Red-Black tree.\r\nvar LLRBNode = /** @class */ (function () {\r\n function LLRBNode(key, value, color, left, right) {\r\n this.key = key;\r\n this.value = value;\r\n this.color = color != null ? color : LLRBNode.RED;\r\n this.left = left != null ? left : LLRBNode.EMPTY;\r\n this.right = right != null ? right : LLRBNode.EMPTY;\r\n this.size = this.left.size + 1 + this.right.size;\r\n }\r\n // Returns a copy of the current node, optionally replacing pieces of it.\r\n LLRBNode.prototype.copy = function (key, value, color, left, right) {\r\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);\r\n };\r\n LLRBNode.prototype.isEmpty = function () {\r\n return false;\r\n };\r\n // Traverses the tree in key order and calls the specified action function\r\n // for each node. If action returns true, traversal is aborted.\r\n // Returns the first truthy value returned by action, or the last falsey\r\n // value returned by action.\r\n LLRBNode.prototype.inorderTraversal = function (action) {\r\n return (this.left.inorderTraversal(action) ||\r\n action(this.key, this.value) ||\r\n this.right.inorderTraversal(action));\r\n };\r\n // Traverses the tree in reverse key order and calls the specified action\r\n // function for each node. If action returns true, traversal is aborted.\r\n // Returns the first truthy value returned by action, or the last falsey\r\n // value returned by action.\r\n LLRBNode.prototype.reverseTraversal = function (action) {\r\n return (this.right.reverseTraversal(action) ||\r\n action(this.key, this.value) ||\r\n this.left.reverseTraversal(action));\r\n };\r\n // Returns the minimum node in the tree.\r\n LLRBNode.prototype.min = function () {\r\n if (this.left.isEmpty()) {\r\n return this;\r\n }\r\n else {\r\n return this.left.min();\r\n }\r\n };\r\n // Returns the maximum key in the tree.\r\n LLRBNode.prototype.minKey = function () {\r\n return this.min().key;\r\n };\r\n // Returns the maximum key in the tree.\r\n LLRBNode.prototype.maxKey = function () {\r\n if (this.right.isEmpty()) {\r\n return this.key;\r\n }\r\n else {\r\n return this.right.maxKey();\r\n }\r\n };\r\n // Returns new tree, with the key/value added.\r\n LLRBNode.prototype.insert = function (key, value, comparator) {\r\n var n = this;\r\n var cmp = comparator(key, n.key);\r\n if (cmp < 0) {\r\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\r\n }\r\n else if (cmp === 0) {\r\n n = n.copy(null, value, null, null, null);\r\n }\r\n else {\r\n n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));\r\n }\r\n return n.fixUp();\r\n };\r\n LLRBNode.prototype.removeMin = function () {\r\n if (this.left.isEmpty()) {\r\n return LLRBNode.EMPTY;\r\n }\r\n var n = this;\r\n if (!n.left.isRed() && !n.left.left.isRed())\r\n n = n.moveRedLeft();\r\n n = n.copy(null, null, null, n.left.removeMin(), null);\r\n return n.fixUp();\r\n };\r\n // Returns new tree, with the specified item removed.\r\n LLRBNode.prototype.remove = function (key, comparator) {\r\n var smallest;\r\n var n = this;\r\n if (comparator(key, n.key) < 0) {\r\n if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {\r\n n = n.moveRedLeft();\r\n }\r\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\r\n }\r\n else {\r\n if (n.left.isRed())\r\n n = n.rotateRight();\r\n if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {\r\n n = n.moveRedRight();\r\n }\r\n if (comparator(key, n.key) === 0) {\r\n if (n.right.isEmpty()) {\r\n return LLRBNode.EMPTY;\r\n }\r\n else {\r\n smallest = n.right.min();\r\n n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin());\r\n }\r\n }\r\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\r\n }\r\n return n.fixUp();\r\n };\r\n LLRBNode.prototype.isRed = function () {\r\n return this.color;\r\n };\r\n // Returns new tree after performing any needed rotations.\r\n LLRBNode.prototype.fixUp = function () {\r\n var n = this;\r\n if (n.right.isRed() && !n.left.isRed())\r\n n = n.rotateLeft();\r\n if (n.left.isRed() && n.left.left.isRed())\r\n n = n.rotateRight();\r\n if (n.left.isRed() && n.right.isRed())\r\n n = n.colorFlip();\r\n return n;\r\n };\r\n LLRBNode.prototype.moveRedLeft = function () {\r\n var n = this.colorFlip();\r\n if (n.right.left.isRed()) {\r\n n = n.copy(null, null, null, null, n.right.rotateRight());\r\n n = n.rotateLeft();\r\n n = n.colorFlip();\r\n }\r\n return n;\r\n };\r\n LLRBNode.prototype.moveRedRight = function () {\r\n var n = this.colorFlip();\r\n if (n.left.left.isRed()) {\r\n n = n.rotateRight();\r\n n = n.colorFlip();\r\n }\r\n return n;\r\n };\r\n LLRBNode.prototype.rotateLeft = function () {\r\n var nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\r\n return this.right.copy(null, null, this.color, nl, null);\r\n };\r\n LLRBNode.prototype.rotateRight = function () {\r\n var nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\r\n return this.left.copy(null, null, this.color, null, nr);\r\n };\r\n LLRBNode.prototype.colorFlip = function () {\r\n var left = this.left.copy(null, null, !this.left.color, null, null);\r\n var right = this.right.copy(null, null, !this.right.color, null, null);\r\n return this.copy(null, null, !this.color, left, right);\r\n };\r\n // For testing.\r\n LLRBNode.prototype.checkMaxDepth = function () {\r\n var blackDepth = this.check();\r\n if (Math.pow(2.0, blackDepth) <= this.size + 1) {\r\n return true;\r\n }\r\n else {\r\n return false;\r\n }\r\n };\r\n // In a balanced RB tree, the black-depth (number of black nodes) from root to\r\n // leaves is equal on both sides. This function verifies that or asserts.\r\n LLRBNode.prototype.check = function () {\r\n if (this.isRed() && this.left.isRed()) {\r\n throw fail('Red node has red child(' + this.key + ',' + this.value + ')');\r\n }\r\n if (this.right.isRed()) {\r\n throw fail('Right child of (' + this.key + ',' + this.value + ') is red');\r\n }\r\n var blackDepth = this.left.check();\r\n if (blackDepth !== this.right.check()) {\r\n throw fail('Black depths differ');\r\n }\r\n else {\r\n return blackDepth + (this.isRed() ? 0 : 1);\r\n }\r\n };\r\n // tslint:disable-next-line:no-any Empty node is shared between all LLRB trees.\r\n LLRBNode.EMPTY = null;\r\n LLRBNode.RED = true;\r\n LLRBNode.BLACK = false;\r\n return LLRBNode;\r\n}()); // end LLRBNode\r\n// Represents an empty node (a leaf node in the Red-Black Tree).\r\nvar LLRBEmptyNode = /** @class */ (function () {\r\n function LLRBEmptyNode() {\r\n this.size = 0;\r\n }\r\n // Returns a copy of the current node.\r\n LLRBEmptyNode.prototype.copy = function (key, value, color, left, right) {\r\n return this;\r\n };\r\n // Returns a copy of the tree, with the specified key/value added.\r\n LLRBEmptyNode.prototype.insert = function (key, value, comparator) {\r\n return new LLRBNode(key, value);\r\n };\r\n // Returns a copy of the tree, with the specified key removed.\r\n LLRBEmptyNode.prototype.remove = function (key, comparator) {\r\n return this;\r\n };\r\n LLRBEmptyNode.prototype.isEmpty = function () {\r\n return true;\r\n };\r\n LLRBEmptyNode.prototype.inorderTraversal = function (action) {\r\n return false;\r\n };\r\n LLRBEmptyNode.prototype.reverseTraversal = function (action) {\r\n return false;\r\n };\r\n LLRBEmptyNode.prototype.minKey = function () {\r\n return null;\r\n };\r\n LLRBEmptyNode.prototype.maxKey = function () {\r\n return null;\r\n };\r\n LLRBEmptyNode.prototype.isRed = function () {\r\n return false;\r\n };\r\n // For testing.\r\n LLRBEmptyNode.prototype.checkMaxDepth = function () {\r\n return true;\r\n };\r\n LLRBEmptyNode.prototype.check = function () {\r\n return 0;\r\n };\r\n return LLRBEmptyNode;\r\n}()); // end LLRBEmptyNode\r\nLLRBNode.EMPTY = new LLRBEmptyNode();\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar TypeOrder;\r\n(function (TypeOrder) {\r\n // This order is defined by the backend.\r\n TypeOrder[TypeOrder[\"NullValue\"] = 0] = \"NullValue\";\r\n TypeOrder[TypeOrder[\"BooleanValue\"] = 1] = \"BooleanValue\";\r\n TypeOrder[TypeOrder[\"NumberValue\"] = 2] = \"NumberValue\";\r\n TypeOrder[TypeOrder[\"TimestampValue\"] = 3] = \"TimestampValue\";\r\n TypeOrder[TypeOrder[\"StringValue\"] = 4] = \"StringValue\";\r\n TypeOrder[TypeOrder[\"BlobValue\"] = 5] = \"BlobValue\";\r\n TypeOrder[TypeOrder[\"RefValue\"] = 6] = \"RefValue\";\r\n TypeOrder[TypeOrder[\"GeoPointValue\"] = 7] = \"GeoPointValue\";\r\n TypeOrder[TypeOrder[\"ArrayValue\"] = 8] = \"ArrayValue\";\r\n TypeOrder[TypeOrder[\"ObjectValue\"] = 9] = \"ObjectValue\";\r\n})(TypeOrder || (TypeOrder = {}));\r\n/** Defines the return value for pending server timestamps. */\r\nvar ServerTimestampBehavior;\r\n(function (ServerTimestampBehavior) {\r\n ServerTimestampBehavior[ServerTimestampBehavior[\"Default\"] = 0] = \"Default\";\r\n ServerTimestampBehavior[ServerTimestampBehavior[\"Estimate\"] = 1] = \"Estimate\";\r\n ServerTimestampBehavior[ServerTimestampBehavior[\"Previous\"] = 2] = \"Previous\";\r\n})(ServerTimestampBehavior || (ServerTimestampBehavior = {}));\r\n/** Holds properties that define field value deserialization options. */\r\nvar FieldValueOptions = /** @class */ (function () {\r\n function FieldValueOptions(serverTimestampBehavior, timestampsInSnapshots) {\r\n this.serverTimestampBehavior = serverTimestampBehavior;\r\n this.timestampsInSnapshots = timestampsInSnapshots;\r\n }\r\n FieldValueOptions.fromSnapshotOptions = function (options, timestampsInSnapshots) {\r\n switch (options.serverTimestamps) {\r\n case 'estimate':\r\n return new FieldValueOptions(ServerTimestampBehavior.Estimate, timestampsInSnapshots);\r\n case 'previous':\r\n return new FieldValueOptions(ServerTimestampBehavior.Previous, timestampsInSnapshots);\r\n case 'none': // Fall-through intended.\r\n case undefined:\r\n return new FieldValueOptions(ServerTimestampBehavior.Default, timestampsInSnapshots);\r\n default:\r\n return fail('fromSnapshotOptions() called with invalid options.');\r\n }\r\n };\r\n return FieldValueOptions;\r\n}());\r\n/**\r\n * A field value represents a datatype as stored by Firestore.\r\n */\r\nvar FieldValue = /** @class */ (function () {\r\n function FieldValue() {\r\n }\r\n FieldValue.prototype.toString = function () {\r\n var val = this.value();\r\n return val === null ? 'null' : val.toString();\r\n };\r\n FieldValue.prototype.defaultCompareTo = function (other) {\r\n assert(this.typeOrder !== other.typeOrder, 'Default compareTo should not be used for values of same type.');\r\n var cmp = primitiveComparator(this.typeOrder, other.typeOrder);\r\n return cmp;\r\n };\r\n return FieldValue;\r\n}());\r\nvar NullValue = /** @class */ (function (_super) {\r\n tslib_1.__extends(NullValue, _super);\r\n function NullValue() {\r\n var _this = _super.call(this) || this;\r\n _this.typeOrder = TypeOrder.NullValue;\r\n // internalValue is unused but we add it to work around\r\n // https://github.com/Microsoft/TypeScript/issues/15585\r\n _this.internalValue = null;\r\n return _this;\r\n }\r\n NullValue.prototype.value = function (options) {\r\n return null;\r\n };\r\n NullValue.prototype.isEqual = function (other) {\r\n return other instanceof NullValue;\r\n };\r\n NullValue.prototype.compareTo = function (other) {\r\n if (other instanceof NullValue) {\r\n return 0;\r\n }\r\n return this.defaultCompareTo(other);\r\n };\r\n NullValue.INSTANCE = new NullValue();\r\n return NullValue;\r\n}(FieldValue));\r\nvar BooleanValue = /** @class */ (function (_super) {\r\n tslib_1.__extends(BooleanValue, _super);\r\n function BooleanValue(internalValue) {\r\n var _this = _super.call(this) || this;\r\n _this.internalValue = internalValue;\r\n _this.typeOrder = TypeOrder.BooleanValue;\r\n return _this;\r\n }\r\n BooleanValue.prototype.value = function (options) {\r\n return this.internalValue;\r\n };\r\n BooleanValue.prototype.isEqual = function (other) {\r\n return (other instanceof BooleanValue &&\r\n this.internalValue === other.internalValue);\r\n };\r\n BooleanValue.prototype.compareTo = function (other) {\r\n if (other instanceof BooleanValue) {\r\n return primitiveComparator(this, other);\r\n }\r\n return this.defaultCompareTo(other);\r\n };\r\n BooleanValue.of = function (value) {\r\n return value ? BooleanValue.TRUE : BooleanValue.FALSE;\r\n };\r\n BooleanValue.TRUE = new BooleanValue(true);\r\n BooleanValue.FALSE = new BooleanValue(false);\r\n return BooleanValue;\r\n}(FieldValue));\r\n/** Base class for IntegerValue and DoubleValue. */\r\nvar NumberValue = /** @class */ (function (_super) {\r\n tslib_1.__extends(NumberValue, _super);\r\n function NumberValue(internalValue) {\r\n var _this = _super.call(this) || this;\r\n _this.internalValue = internalValue;\r\n _this.typeOrder = TypeOrder.NumberValue;\r\n return _this;\r\n }\r\n NumberValue.prototype.value = function (options) {\r\n return this.internalValue;\r\n };\r\n NumberValue.prototype.compareTo = function (other) {\r\n if (other instanceof NumberValue) {\r\n return numericComparator(this.internalValue, other.internalValue);\r\n }\r\n return this.defaultCompareTo(other);\r\n };\r\n return NumberValue;\r\n}(FieldValue));\r\n/** Utility function to compare doubles (using Firestore semantics for NaN). */\r\nfunction numericComparator(left, right) {\r\n if (left < right) {\r\n return -1;\r\n }\r\n else if (left > right) {\r\n return 1;\r\n }\r\n else if (left === right) {\r\n return 0;\r\n }\r\n else {\r\n // one or both are NaN.\r\n if (isNaN(left)) {\r\n return isNaN(right) ? 0 : -1;\r\n }\r\n else {\r\n return 1;\r\n }\r\n }\r\n}\r\n/**\r\n * Utility function to check numbers for equality using Firestore semantics\r\n * (NaN === NaN, -0.0 !== 0.0).\r\n */\r\nfunction numericEquals(left, right) {\r\n // Implemented based on Object.is() polyfill from\r\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\r\n if (left === right) {\r\n // +0 != -0\r\n return left !== 0 || 1 / left === 1 / right;\r\n }\r\n else {\r\n // NaN == NaN\r\n return left !== left && right !== right;\r\n }\r\n}\r\nvar IntegerValue = /** @class */ (function (_super) {\r\n tslib_1.__extends(IntegerValue, _super);\r\n function IntegerValue(internalValue) {\r\n return _super.call(this, internalValue) || this;\r\n }\r\n IntegerValue.prototype.isEqual = function (other) {\r\n // NOTE: DoubleValue and IntegerValue instances may compareTo() the same,\r\n // but that doesn't make them equal via isEqual().\r\n if (other instanceof IntegerValue) {\r\n return numericEquals(this.internalValue, other.internalValue);\r\n }\r\n else {\r\n return false;\r\n }\r\n };\r\n return IntegerValue;\r\n}(NumberValue));\r\nvar DoubleValue = /** @class */ (function (_super) {\r\n tslib_1.__extends(DoubleValue, _super);\r\n function DoubleValue(internalValue) {\r\n var _this = _super.call(this, internalValue) || this;\r\n _this.internalValue = internalValue;\r\n return _this;\r\n }\r\n DoubleValue.prototype.isEqual = function (other) {\r\n // NOTE: DoubleValue and IntegerValue instances may compareTo() the same,\r\n // but that doesn't make them equal via isEqual().\r\n if (other instanceof DoubleValue) {\r\n return numericEquals(this.internalValue, other.internalValue);\r\n }\r\n else {\r\n return false;\r\n }\r\n };\r\n DoubleValue.NAN = new DoubleValue(NaN);\r\n DoubleValue.POSITIVE_INFINITY = new DoubleValue(Infinity);\r\n DoubleValue.NEGATIVE_INFINITY = new DoubleValue(-Infinity);\r\n return DoubleValue;\r\n}(NumberValue));\r\n// TODO(b/37267885): Add truncation support\r\nvar StringValue = /** @class */ (function (_super) {\r\n tslib_1.__extends(StringValue, _super);\r\n function StringValue(internalValue) {\r\n var _this = _super.call(this) || this;\r\n _this.internalValue = internalValue;\r\n _this.typeOrder = TypeOrder.StringValue;\r\n return _this;\r\n }\r\n StringValue.prototype.value = function (options) {\r\n return this.internalValue;\r\n };\r\n StringValue.prototype.isEqual = function (other) {\r\n return (other instanceof StringValue && this.internalValue === other.internalValue);\r\n };\r\n StringValue.prototype.compareTo = function (other) {\r\n if (other instanceof StringValue) {\r\n return primitiveComparator(this.internalValue, other.internalValue);\r\n }\r\n return this.defaultCompareTo(other);\r\n };\r\n return StringValue;\r\n}(FieldValue));\r\nvar TimestampValue = /** @class */ (function (_super) {\r\n tslib_1.__extends(TimestampValue, _super);\r\n function TimestampValue(internalValue) {\r\n var _this = _super.call(this) || this;\r\n _this.internalValue = internalValue;\r\n _this.typeOrder = TypeOrder.TimestampValue;\r\n return _this;\r\n }\r\n TimestampValue.prototype.value = function (options) {\r\n if (!options || options.timestampsInSnapshots) {\r\n return this.internalValue;\r\n }\r\n else {\r\n return this.internalValue.toDate();\r\n }\r\n };\r\n TimestampValue.prototype.isEqual = function (other) {\r\n return (other instanceof TimestampValue &&\r\n this.internalValue.isEqual(other.internalValue));\r\n };\r\n TimestampValue.prototype.compareTo = function (other) {\r\n if (other instanceof TimestampValue) {\r\n return this.internalValue._compareTo(other.internalValue);\r\n }\r\n else if (other instanceof ServerTimestampValue) {\r\n // Concrete timestamps come before server timestamps.\r\n return -1;\r\n }\r\n else {\r\n return this.defaultCompareTo(other);\r\n }\r\n };\r\n return TimestampValue;\r\n}(FieldValue));\r\n/**\r\n * Represents a locally-applied ServerTimestamp.\r\n *\r\n * Notes:\r\n * - ServerTimestampValue instances are created as the result of applying a\r\n * TransformMutation (see TransformMutation.applyTo()). They can only exist in\r\n * the local view of a document. Therefore they do not need to be parsed or\r\n * serialized.\r\n * - When evaluated locally (e.g. for snapshot.data()), they by default\r\n * evaluate to `null`. This behavior can be configured by passing custom\r\n * FieldValueOptions to value().\r\n * - With respect to other ServerTimestampValues, they sort by their\r\n * localWriteTime.\r\n */\r\nvar ServerTimestampValue = /** @class */ (function (_super) {\r\n tslib_1.__extends(ServerTimestampValue, _super);\r\n function ServerTimestampValue(localWriteTime, previousValue) {\r\n var _this = _super.call(this) || this;\r\n _this.localWriteTime = localWriteTime;\r\n _this.previousValue = previousValue;\r\n _this.typeOrder = TypeOrder.TimestampValue;\r\n return _this;\r\n }\r\n ServerTimestampValue.prototype.value = function (options) {\r\n if (options &&\r\n options.serverTimestampBehavior === ServerTimestampBehavior.Estimate) {\r\n return new TimestampValue(this.localWriteTime).value(options);\r\n }\r\n else if (options &&\r\n options.serverTimestampBehavior === ServerTimestampBehavior.Previous) {\r\n return this.previousValue ? this.previousValue.value(options) : null;\r\n }\r\n else {\r\n return null;\r\n }\r\n };\r\n ServerTimestampValue.prototype.isEqual = function (other) {\r\n return (other instanceof ServerTimestampValue &&\r\n this.localWriteTime.isEqual(other.localWriteTime));\r\n };\r\n ServerTimestampValue.prototype.compareTo = function (other) {\r\n if (other instanceof ServerTimestampValue) {\r\n return this.localWriteTime._compareTo(other.localWriteTime);\r\n }\r\n else if (other instanceof TimestampValue) {\r\n // Server timestamps come after all concrete timestamps.\r\n return 1;\r\n }\r\n else {\r\n return this.defaultCompareTo(other);\r\n }\r\n };\r\n ServerTimestampValue.prototype.toString = function () {\r\n return '';\r\n };\r\n return ServerTimestampValue;\r\n}(FieldValue));\r\nvar BlobValue = /** @class */ (function (_super) {\r\n tslib_1.__extends(BlobValue, _super);\r\n function BlobValue(internalValue) {\r\n var _this = _super.call(this) || this;\r\n _this.internalValue = internalValue;\r\n _this.typeOrder = TypeOrder.BlobValue;\r\n return _this;\r\n }\r\n BlobValue.prototype.value = function (options) {\r\n return this.internalValue;\r\n };\r\n BlobValue.prototype.isEqual = function (other) {\r\n return (other instanceof BlobValue &&\r\n this.internalValue.isEqual(other.internalValue));\r\n };\r\n BlobValue.prototype.compareTo = function (other) {\r\n if (other instanceof BlobValue) {\r\n return this.internalValue._compareTo(other.internalValue);\r\n }\r\n return this.defaultCompareTo(other);\r\n };\r\n return BlobValue;\r\n}(FieldValue));\r\nvar RefValue = /** @class */ (function (_super) {\r\n tslib_1.__extends(RefValue, _super);\r\n function RefValue(databaseId, key) {\r\n var _this = _super.call(this) || this;\r\n _this.databaseId = databaseId;\r\n _this.key = key;\r\n _this.typeOrder = TypeOrder.RefValue;\r\n return _this;\r\n }\r\n RefValue.prototype.value = function (options) {\r\n return this.key;\r\n };\r\n RefValue.prototype.isEqual = function (other) {\r\n if (other instanceof RefValue) {\r\n return (this.key.isEqual(other.key) && this.databaseId.isEqual(other.databaseId));\r\n }\r\n else {\r\n return false;\r\n }\r\n };\r\n RefValue.prototype.compareTo = function (other) {\r\n if (other instanceof RefValue) {\r\n var cmp = this.databaseId.compareTo(other.databaseId);\r\n return cmp !== 0 ? cmp : DocumentKey.comparator(this.key, other.key);\r\n }\r\n return this.defaultCompareTo(other);\r\n };\r\n return RefValue;\r\n}(FieldValue));\r\nvar GeoPointValue = /** @class */ (function (_super) {\r\n tslib_1.__extends(GeoPointValue, _super);\r\n function GeoPointValue(internalValue) {\r\n var _this = _super.call(this) || this;\r\n _this.internalValue = internalValue;\r\n _this.typeOrder = TypeOrder.GeoPointValue;\r\n return _this;\r\n }\r\n GeoPointValue.prototype.value = function (options) {\r\n return this.internalValue;\r\n };\r\n GeoPointValue.prototype.isEqual = function (other) {\r\n return (other instanceof GeoPointValue &&\r\n this.internalValue.isEqual(other.internalValue));\r\n };\r\n GeoPointValue.prototype.compareTo = function (other) {\r\n if (other instanceof GeoPointValue) {\r\n return this.internalValue._compareTo(other.internalValue);\r\n }\r\n return this.defaultCompareTo(other);\r\n };\r\n return GeoPointValue;\r\n}(FieldValue));\r\nvar ObjectValue = /** @class */ (function (_super) {\r\n tslib_1.__extends(ObjectValue, _super);\r\n function ObjectValue(internalValue) {\r\n var _this = _super.call(this) || this;\r\n _this.internalValue = internalValue;\r\n _this.typeOrder = TypeOrder.ObjectValue;\r\n return _this;\r\n }\r\n ObjectValue.prototype.value = function (options) {\r\n var result = {};\r\n this.internalValue.inorderTraversal(function (key, val) {\r\n result[key] = val.value(options);\r\n });\r\n return result;\r\n };\r\n ObjectValue.prototype.forEach = function (action) {\r\n this.internalValue.inorderTraversal(action);\r\n };\r\n ObjectValue.prototype.isEqual = function (other) {\r\n if (other instanceof ObjectValue) {\r\n var it1 = this.internalValue.getIterator();\r\n var it2 = other.internalValue.getIterator();\r\n while (it1.hasNext() && it2.hasNext()) {\r\n var next1 = it1.getNext();\r\n var next2 = it2.getNext();\r\n if (next1.key !== next2.key || !next1.value.isEqual(next2.value)) {\r\n return false;\r\n }\r\n }\r\n return !it1.hasNext() && !it2.hasNext();\r\n }\r\n return false;\r\n };\r\n ObjectValue.prototype.compareTo = function (other) {\r\n if (other instanceof ObjectValue) {\r\n var it1 = this.internalValue.getIterator();\r\n var it2 = other.internalValue.getIterator();\r\n while (it1.hasNext() && it2.hasNext()) {\r\n var next1 = it1.getNext();\r\n var next2 = it2.getNext();\r\n var cmp = primitiveComparator(next1.key, next2.key) ||\r\n next1.value.compareTo(next2.value);\r\n if (cmp) {\r\n return cmp;\r\n }\r\n }\r\n // Only equal if both iterators are exhausted\r\n return primitiveComparator(it1.hasNext(), it2.hasNext());\r\n }\r\n else {\r\n return this.defaultCompareTo(other);\r\n }\r\n };\r\n ObjectValue.prototype.set = function (path, to) {\r\n assert(!path.isEmpty(), 'Cannot set field for empty path on ObjectValue');\r\n if (path.length === 1) {\r\n return this.setChild(path.firstSegment(), to);\r\n }\r\n else {\r\n var child = this.child(path.firstSegment());\r\n if (!(child instanceof ObjectValue)) {\r\n child = ObjectValue.EMPTY;\r\n }\r\n var newChild = child.set(path.popFirst(), to);\r\n return this.setChild(path.firstSegment(), newChild);\r\n }\r\n };\r\n ObjectValue.prototype.delete = function (path) {\r\n assert(!path.isEmpty(), 'Cannot delete field for empty path on ObjectValue');\r\n if (path.length === 1) {\r\n return new ObjectValue(this.internalValue.remove(path.firstSegment()));\r\n }\r\n else {\r\n // nested field\r\n var child = this.child(path.firstSegment());\r\n if (child instanceof ObjectValue) {\r\n var newChild = child.delete(path.popFirst());\r\n return new ObjectValue(this.internalValue.insert(path.firstSegment(), newChild));\r\n }\r\n else {\r\n // Don't actually change a primitive value to an object for a delete\r\n return this;\r\n }\r\n }\r\n };\r\n ObjectValue.prototype.contains = function (path) {\r\n return this.field(path) !== undefined;\r\n };\r\n ObjectValue.prototype.field = function (path) {\r\n assert(!path.isEmpty(), \"Can't get field of empty path\");\r\n var field = this;\r\n path.forEach(function (pathSegment) {\r\n if (field instanceof ObjectValue) {\r\n field = field.internalValue.get(pathSegment) || undefined;\r\n }\r\n else {\r\n field = undefined;\r\n }\r\n });\r\n return field;\r\n };\r\n ObjectValue.prototype.toString = function () {\r\n return this.internalValue.toString();\r\n };\r\n ObjectValue.prototype.child = function (childName) {\r\n return this.internalValue.get(childName) || undefined;\r\n };\r\n ObjectValue.prototype.setChild = function (childName, value) {\r\n return new ObjectValue(this.internalValue.insert(childName, value));\r\n };\r\n ObjectValue.EMPTY = new ObjectValue(new SortedMap(primitiveComparator));\r\n return ObjectValue;\r\n}(FieldValue));\r\nvar ArrayValue = /** @class */ (function (_super) {\r\n tslib_1.__extends(ArrayValue, _super);\r\n function ArrayValue(internalValue) {\r\n var _this = _super.call(this) || this;\r\n _this.internalValue = internalValue;\r\n _this.typeOrder = TypeOrder.ArrayValue;\r\n return _this;\r\n }\r\n ArrayValue.prototype.value = function (options) {\r\n return this.internalValue.map(function (v) { return v.value(options); });\r\n };\r\n ArrayValue.prototype.forEach = function (action) {\r\n this.internalValue.forEach(action);\r\n };\r\n ArrayValue.prototype.isEqual = function (other) {\r\n if (other instanceof ArrayValue) {\r\n if (this.internalValue.length !== other.internalValue.length) {\r\n return false;\r\n }\r\n for (var i = 0; i < this.internalValue.length; i++) {\r\n if (!this.internalValue[i].isEqual(other.internalValue[i])) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }\r\n return false;\r\n };\r\n ArrayValue.prototype.compareTo = function (other) {\r\n if (other instanceof ArrayValue) {\r\n var minLength = Math.min(this.internalValue.length, other.internalValue.length);\r\n for (var i = 0; i < minLength; i++) {\r\n var cmp = this.internalValue[i].compareTo(other.internalValue[i]);\r\n if (cmp) {\r\n return cmp;\r\n }\r\n }\r\n return primitiveComparator(this.internalValue.length, other.internalValue.length);\r\n }\r\n else {\r\n return this.defaultCompareTo(other);\r\n }\r\n };\r\n ArrayValue.prototype.toString = function () {\r\n var descriptions = this.internalValue.map(function (v) { return v.toString(); });\r\n return \"[\" + descriptions.join(',') + \"]\";\r\n };\r\n return ArrayValue;\r\n}(FieldValue));\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Untyped Number alias we can use to check for ES6 methods / properties.\r\n// tslint:disable-next-line:no-any variable-name\r\nvar NumberAsAny = Number;\r\n/**\r\n * Minimum safe integer in Javascript because of floating point precision.\r\n * Added to not rely on ES6 features.\r\n */\r\nvar MIN_SAFE_INTEGER = NumberAsAny.MIN_SAFE_INTEGER || -(Math.pow(2, 53) - 1);\r\n/**\r\n * Maximum safe integer in Javascript because of floating point precision.\r\n * Added to not rely on ES6 features.\r\n */\r\nvar MAX_SAFE_INTEGER = NumberAsAny.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1;\r\n/**\r\n * Returns whether an number is an integer, uses native implementation if\r\n * available.\r\n * Added to not rely on ES6 features.\r\n * @param value The value to test for being an integer\r\n */\r\nvar isInteger = NumberAsAny.isInteger ||\r\n (function (value) {\r\n return typeof value === 'number' &&\r\n isFinite(value) &&\r\n Math.floor(value) === value;\r\n });\r\n/**\r\n * Returns whether a variable is either undefined or null.\r\n */\r\nfunction isNullOrUndefined(value) {\r\n return value === null || value === undefined;\r\n}\r\n/**\r\n * Returns whether a value is an integer and in the safe integer range\r\n * @param value The value to test for being an integer and in the safe range\r\n */\r\nfunction isSafeInteger(value) {\r\n return (isInteger(value) &&\r\n value <= MAX_SAFE_INTEGER &&\r\n value >= MIN_SAFE_INTEGER);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar Query = /** @class */ (function () {\r\n /**\r\n * Initializes a Query with a path and optional additional query constraints.\r\n * Path must currently be empty if this is a collection group query.\r\n */\r\n function Query(path, collectionGroup, explicitOrderBy, filters, limit, startAt, endAt) {\r\n if (collectionGroup === void 0) { collectionGroup = null; }\r\n if (explicitOrderBy === void 0) { explicitOrderBy = []; }\r\n if (filters === void 0) { filters = []; }\r\n if (limit === void 0) { limit = null; }\r\n if (startAt === void 0) { startAt = null; }\r\n if (endAt === void 0) { endAt = null; }\r\n this.path = path;\r\n this.collectionGroup = collectionGroup;\r\n this.explicitOrderBy = explicitOrderBy;\r\n this.filters = filters;\r\n this.limit = limit;\r\n this.startAt = startAt;\r\n this.endAt = endAt;\r\n this.memoizedCanonicalId = null;\r\n this.memoizedOrderBy = null;\r\n if (this.startAt) {\r\n this.assertValidBound(this.startAt);\r\n }\r\n if (this.endAt) {\r\n this.assertValidBound(this.endAt);\r\n }\r\n }\r\n Query.atPath = function (path) {\r\n return new Query(path);\r\n };\r\n Object.defineProperty(Query.prototype, \"orderBy\", {\r\n get: function () {\r\n if (this.memoizedOrderBy === null) {\r\n var inequalityField = this.getInequalityFilterField();\r\n var firstOrderByField = this.getFirstOrderByField();\r\n if (inequalityField !== null && firstOrderByField === null) {\r\n // In order to implicitly add key ordering, we must also add the\r\n // inequality filter field for it to be a valid query.\r\n // Note that the default inequality field and key ordering is ascending.\r\n if (inequalityField.isKeyField()) {\r\n this.memoizedOrderBy = [KEY_ORDERING_ASC];\r\n }\r\n else {\r\n this.memoizedOrderBy = [\r\n new OrderBy(inequalityField),\r\n KEY_ORDERING_ASC\r\n ];\r\n }\r\n }\r\n else {\r\n assert(inequalityField === null ||\r\n (firstOrderByField !== null &&\r\n inequalityField.isEqual(firstOrderByField)), 'First orderBy should match inequality field.');\r\n this.memoizedOrderBy = [];\r\n var foundKeyOrdering = false;\r\n for (var _i = 0, _a = this.explicitOrderBy; _i < _a.length; _i++) {\r\n var orderBy = _a[_i];\r\n this.memoizedOrderBy.push(orderBy);\r\n if (orderBy.field.isKeyField()) {\r\n foundKeyOrdering = true;\r\n }\r\n }\r\n if (!foundKeyOrdering) {\r\n // The order of the implicit key ordering always matches the last\r\n // explicit order by\r\n var lastDirection = this.explicitOrderBy.length > 0\r\n ? this.explicitOrderBy[this.explicitOrderBy.length - 1].dir\r\n : Direction.ASCENDING;\r\n this.memoizedOrderBy.push(lastDirection === Direction.ASCENDING\r\n ? KEY_ORDERING_ASC\r\n : KEY_ORDERING_DESC);\r\n }\r\n }\r\n }\r\n return this.memoizedOrderBy;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Query.prototype.addFilter = function (filter) {\r\n assert(this.getInequalityFilterField() == null ||\r\n !(filter instanceof RelationFilter) ||\r\n !filter.isInequality() ||\r\n filter.field.isEqual(this.getInequalityFilterField()), 'Query must only have one inequality field.');\r\n assert(!this.isDocumentQuery(), 'No filtering allowed for document query');\r\n var newFilters = this.filters.concat([filter]);\r\n return new Query(this.path, this.collectionGroup, this.explicitOrderBy.slice(), newFilters, this.limit, this.startAt, this.endAt);\r\n };\r\n Query.prototype.addOrderBy = function (orderBy) {\r\n assert(!this.startAt && !this.endAt, 'Bounds must be set after orderBy');\r\n // TODO(dimond): validate that orderBy does not list the same key twice.\r\n var newOrderBy = this.explicitOrderBy.concat([orderBy]);\r\n return new Query(this.path, this.collectionGroup, newOrderBy, this.filters.slice(), this.limit, this.startAt, this.endAt);\r\n };\r\n Query.prototype.withLimit = function (limit) {\r\n return new Query(this.path, this.collectionGroup, this.explicitOrderBy.slice(), this.filters.slice(), limit, this.startAt, this.endAt);\r\n };\r\n Query.prototype.withStartAt = function (bound) {\r\n return new Query(this.path, this.collectionGroup, this.explicitOrderBy.slice(), this.filters.slice(), this.limit, bound, this.endAt);\r\n };\r\n Query.prototype.withEndAt = function (bound) {\r\n return new Query(this.path, this.collectionGroup, this.explicitOrderBy.slice(), this.filters.slice(), this.limit, this.startAt, bound);\r\n };\r\n /**\r\n * Helper to convert a collection group query into a collection query at a\r\n * specific path. This is used when executing collection group queries, since\r\n * we have to split the query into a set of collection queries at multiple\r\n * paths.\r\n */\r\n Query.prototype.asCollectionQueryAtPath = function (path) {\r\n return new Query(path, \r\n /*collectionGroup=*/ null, this.explicitOrderBy.slice(), this.filters.slice(), this.limit, this.startAt, this.endAt);\r\n };\r\n // TODO(b/29183165): This is used to get a unique string from a query to, for\r\n // example, use as a dictionary key, but the implementation is subject to\r\n // collisions. Make it collision-free.\r\n Query.prototype.canonicalId = function () {\r\n if (this.memoizedCanonicalId === null) {\r\n var canonicalId = this.path.canonicalString();\r\n if (this.isCollectionGroupQuery()) {\r\n canonicalId += '|cg:' + this.collectionGroup;\r\n }\r\n canonicalId += '|f:';\r\n for (var _i = 0, _a = this.filters; _i < _a.length; _i++) {\r\n var filter = _a[_i];\r\n canonicalId += filter.canonicalId();\r\n canonicalId += ',';\r\n }\r\n canonicalId += '|ob:';\r\n // TODO(dimond): make this collision resistant\r\n for (var _b = 0, _c = this.orderBy; _b < _c.length; _b++) {\r\n var orderBy = _c[_b];\r\n canonicalId += orderBy.canonicalId();\r\n canonicalId += ',';\r\n }\r\n if (!isNullOrUndefined(this.limit)) {\r\n canonicalId += '|l:';\r\n canonicalId += this.limit;\r\n }\r\n if (this.startAt) {\r\n canonicalId += '|lb:';\r\n canonicalId += this.startAt.canonicalId();\r\n }\r\n if (this.endAt) {\r\n canonicalId += '|ub:';\r\n canonicalId += this.endAt.canonicalId();\r\n }\r\n this.memoizedCanonicalId = canonicalId;\r\n }\r\n return this.memoizedCanonicalId;\r\n };\r\n Query.prototype.toString = function () {\r\n var str = 'Query(' + this.path.canonicalString();\r\n if (this.isCollectionGroupQuery()) {\r\n str += ' collectionGroup=' + this.collectionGroup;\r\n }\r\n if (this.filters.length > 0) {\r\n str += \", filters: [\" + this.filters.join(', ') + \"]\";\r\n }\r\n if (!isNullOrUndefined(this.limit)) {\r\n str += ', limit: ' + this.limit;\r\n }\r\n if (this.explicitOrderBy.length > 0) {\r\n str += \", orderBy: [\" + this.explicitOrderBy.join(', ') + \"]\";\r\n }\r\n if (this.startAt) {\r\n str += ', startAt: ' + this.startAt.canonicalId();\r\n }\r\n if (this.endAt) {\r\n str += ', endAt: ' + this.endAt.canonicalId();\r\n }\r\n return str + ')';\r\n };\r\n Query.prototype.isEqual = function (other) {\r\n if (this.limit !== other.limit) {\r\n return false;\r\n }\r\n if (this.orderBy.length !== other.orderBy.length) {\r\n return false;\r\n }\r\n for (var i = 0; i < this.orderBy.length; i++) {\r\n if (!this.orderBy[i].isEqual(other.orderBy[i])) {\r\n return false;\r\n }\r\n }\r\n if (this.filters.length !== other.filters.length) {\r\n return false;\r\n }\r\n for (var i = 0; i < this.filters.length; i++) {\r\n if (!this.filters[i].isEqual(other.filters[i])) {\r\n return false;\r\n }\r\n }\r\n if (this.collectionGroup !== other.collectionGroup) {\r\n return false;\r\n }\r\n if (!this.path.isEqual(other.path)) {\r\n return false;\r\n }\r\n if (this.startAt !== null\r\n ? !this.startAt.isEqual(other.startAt)\r\n : other.startAt !== null) {\r\n return false;\r\n }\r\n return this.endAt !== null\r\n ? this.endAt.isEqual(other.endAt)\r\n : other.endAt === null;\r\n };\r\n Query.prototype.docComparator = function (d1, d2) {\r\n var comparedOnKeyField = false;\r\n for (var _i = 0, _a = this.orderBy; _i < _a.length; _i++) {\r\n var orderBy = _a[_i];\r\n var comp = orderBy.compare(d1, d2);\r\n if (comp !== 0)\r\n return comp;\r\n comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField();\r\n }\r\n // Assert that we actually compared by key\r\n assert(comparedOnKeyField, \"orderBy used that doesn't compare on key field\");\r\n return 0;\r\n };\r\n Query.prototype.matches = function (doc) {\r\n return (this.matchesPathAndCollectionGroup(doc) &&\r\n this.matchesOrderBy(doc) &&\r\n this.matchesFilters(doc) &&\r\n this.matchesBounds(doc));\r\n };\r\n Query.prototype.hasLimit = function () {\r\n return !isNullOrUndefined(this.limit);\r\n };\r\n Query.prototype.getFirstOrderByField = function () {\r\n return this.explicitOrderBy.length > 0\r\n ? this.explicitOrderBy[0].field\r\n : null;\r\n };\r\n Query.prototype.getInequalityFilterField = function () {\r\n for (var _i = 0, _a = this.filters; _i < _a.length; _i++) {\r\n var filter = _a[_i];\r\n if (filter instanceof RelationFilter && filter.isInequality()) {\r\n return filter.field;\r\n }\r\n }\r\n return null;\r\n };\r\n Query.prototype.hasArrayContainsFilter = function () {\r\n return (this.filters.find(function (filter) {\r\n return filter instanceof RelationFilter &&\r\n filter.op === RelationOp.ARRAY_CONTAINS;\r\n }) !== undefined);\r\n };\r\n Query.prototype.isDocumentQuery = function () {\r\n return (DocumentKey.isDocumentKey(this.path) &&\r\n this.collectionGroup === null &&\r\n this.filters.length === 0);\r\n };\r\n Query.prototype.isCollectionGroupQuery = function () {\r\n return this.collectionGroup !== null;\r\n };\r\n Query.prototype.matchesPathAndCollectionGroup = function (doc) {\r\n var docPath = doc.key.path;\r\n if (this.collectionGroup !== null) {\r\n // NOTE: this.path is currently always empty since we don't expose Collection\r\n // Group queries rooted at a document path yet.\r\n return (doc.key.hasCollectionId(this.collectionGroup) &&\r\n this.path.isPrefixOf(docPath));\r\n }\r\n else if (DocumentKey.isDocumentKey(this.path)) {\r\n // exact match for document queries\r\n return this.path.isEqual(docPath);\r\n }\r\n else {\r\n // shallow ancestor queries by default\r\n return this.path.isImmediateParentOf(docPath);\r\n }\r\n };\r\n /**\r\n * A document must have a value for every ordering clause in order to show up\r\n * in the results.\r\n */\r\n Query.prototype.matchesOrderBy = function (doc) {\r\n for (var _i = 0, _a = this.explicitOrderBy; _i < _a.length; _i++) {\r\n var orderBy = _a[_i];\r\n // order by key always matches\r\n if (!orderBy.field.isKeyField() &&\r\n doc.field(orderBy.field) === undefined) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n };\r\n Query.prototype.matchesFilters = function (doc) {\r\n for (var _i = 0, _a = this.filters; _i < _a.length; _i++) {\r\n var filter = _a[_i];\r\n if (!filter.matches(doc)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n };\r\n /**\r\n * Makes sure a document is within the bounds, if provided.\r\n */\r\n Query.prototype.matchesBounds = function (doc) {\r\n if (this.startAt && !this.startAt.sortsBeforeDocument(this.orderBy, doc)) {\r\n return false;\r\n }\r\n if (this.endAt && this.endAt.sortsBeforeDocument(this.orderBy, doc)) {\r\n return false;\r\n }\r\n return true;\r\n };\r\n Query.prototype.assertValidBound = function (bound) {\r\n assert(bound.position.length <= this.orderBy.length, 'Bound is longer than orderBy');\r\n };\r\n return Query;\r\n}());\r\nvar Filter = /** @class */ (function () {\r\n function Filter() {\r\n }\r\n /**\r\n * Creates a filter based on the provided arguments.\r\n */\r\n Filter.create = function (field, op, value) {\r\n if (value.isEqual(NullValue.INSTANCE)) {\r\n if (op !== RelationOp.EQUAL) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You can only perform equals comparisons on null.');\r\n }\r\n return new NullFilter(field);\r\n }\r\n else if (value.isEqual(DoubleValue.NAN)) {\r\n if (op !== RelationOp.EQUAL) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You can only perform equals comparisons on NaN.');\r\n }\r\n return new NanFilter(field);\r\n }\r\n else {\r\n return new RelationFilter(field, op, value);\r\n }\r\n };\r\n return Filter;\r\n}());\r\nvar RelationOp = /** @class */ (function () {\r\n function RelationOp(name) {\r\n this.name = name;\r\n }\r\n RelationOp.fromString = function (op) {\r\n switch (op) {\r\n case '<':\r\n return RelationOp.LESS_THAN;\r\n case '<=':\r\n return RelationOp.LESS_THAN_OR_EQUAL;\r\n case '==':\r\n return RelationOp.EQUAL;\r\n case '>=':\r\n return RelationOp.GREATER_THAN_OR_EQUAL;\r\n case '>':\r\n return RelationOp.GREATER_THAN;\r\n case 'array-contains':\r\n return RelationOp.ARRAY_CONTAINS;\r\n default:\r\n return fail('Unknown relation: ' + op);\r\n }\r\n };\r\n RelationOp.prototype.toString = function () {\r\n return this.name;\r\n };\r\n RelationOp.prototype.isEqual = function (other) {\r\n return this.name === other.name;\r\n };\r\n RelationOp.LESS_THAN = new RelationOp('<');\r\n RelationOp.LESS_THAN_OR_EQUAL = new RelationOp('<=');\r\n RelationOp.EQUAL = new RelationOp('==');\r\n RelationOp.GREATER_THAN = new RelationOp('>');\r\n RelationOp.GREATER_THAN_OR_EQUAL = new RelationOp('>=');\r\n RelationOp.ARRAY_CONTAINS = new RelationOp('array-contains');\r\n return RelationOp;\r\n}());\r\nvar RelationFilter = /** @class */ (function (_super) {\r\n tslib_1.__extends(RelationFilter, _super);\r\n function RelationFilter(field, op, value) {\r\n var _this = _super.call(this) || this;\r\n _this.field = field;\r\n _this.op = op;\r\n _this.value = value;\r\n return _this;\r\n }\r\n RelationFilter.prototype.matches = function (doc) {\r\n if (this.field.isKeyField()) {\r\n assert(this.value instanceof RefValue, 'Comparing on key, but filter value not a RefValue');\r\n assert(this.op !== RelationOp.ARRAY_CONTAINS, \"array-contains queries don't make sense on document keys.\");\r\n var refValue = this.value;\r\n var comparison = DocumentKey.comparator(doc.key, refValue.key);\r\n return this.matchesComparison(comparison);\r\n }\r\n else {\r\n var val = doc.field(this.field);\r\n return val !== undefined && this.matchesValue(val);\r\n }\r\n };\r\n RelationFilter.prototype.matchesValue = function (value) {\r\n var _this = this;\r\n if (this.op === RelationOp.ARRAY_CONTAINS) {\r\n return (value instanceof ArrayValue &&\r\n value.internalValue.find(function (element) { return element.isEqual(_this.value); }) !==\r\n undefined);\r\n }\r\n else {\r\n // Only compare types with matching backend order (such as double and int).\r\n return (this.value.typeOrder === value.typeOrder &&\r\n this.matchesComparison(value.compareTo(this.value)));\r\n }\r\n };\r\n RelationFilter.prototype.matchesComparison = function (comparison) {\r\n switch (this.op) {\r\n case RelationOp.LESS_THAN:\r\n return comparison < 0;\r\n case RelationOp.LESS_THAN_OR_EQUAL:\r\n return comparison <= 0;\r\n case RelationOp.EQUAL:\r\n return comparison === 0;\r\n case RelationOp.GREATER_THAN:\r\n return comparison > 0;\r\n case RelationOp.GREATER_THAN_OR_EQUAL:\r\n return comparison >= 0;\r\n default:\r\n return fail('Unknown relation op' + this.op);\r\n }\r\n };\r\n RelationFilter.prototype.isInequality = function () {\r\n return (this.op !== RelationOp.EQUAL && this.op !== RelationOp.ARRAY_CONTAINS);\r\n };\r\n RelationFilter.prototype.canonicalId = function () {\r\n // TODO(b/29183165): Technically, this won't be unique if two values have\r\n // the same description, such as the int 3 and the string \"3\". So we should\r\n // add the types in here somehow, too.\r\n return (this.field.canonicalString() + this.op.toString() + this.value.toString());\r\n };\r\n RelationFilter.prototype.isEqual = function (other) {\r\n if (other instanceof RelationFilter) {\r\n return (this.op.isEqual(other.op) &&\r\n this.field.isEqual(other.field) &&\r\n this.value.isEqual(other.value));\r\n }\r\n else {\r\n return false;\r\n }\r\n };\r\n RelationFilter.prototype.toString = function () {\r\n return this.field.canonicalString() + \" \" + this.op + \" \" + this.value.value();\r\n };\r\n return RelationFilter;\r\n}(Filter));\r\n/**\r\n * Filter that matches 'null' values.\r\n */\r\nvar NullFilter = /** @class */ (function (_super) {\r\n tslib_1.__extends(NullFilter, _super);\r\n function NullFilter(field) {\r\n var _this = _super.call(this) || this;\r\n _this.field = field;\r\n return _this;\r\n }\r\n NullFilter.prototype.matches = function (doc) {\r\n var val = doc.field(this.field);\r\n return val !== undefined && val.value() === null;\r\n };\r\n NullFilter.prototype.canonicalId = function () {\r\n return this.field.canonicalString() + ' IS null';\r\n };\r\n NullFilter.prototype.toString = function () {\r\n return this.field.canonicalString() + \" IS null\";\r\n };\r\n NullFilter.prototype.isEqual = function (other) {\r\n if (other instanceof NullFilter) {\r\n return this.field.isEqual(other.field);\r\n }\r\n else {\r\n return false;\r\n }\r\n };\r\n return NullFilter;\r\n}(Filter));\r\n/**\r\n * Filter that matches 'NaN' values.\r\n */\r\nvar NanFilter = /** @class */ (function (_super) {\r\n tslib_1.__extends(NanFilter, _super);\r\n function NanFilter(field) {\r\n var _this = _super.call(this) || this;\r\n _this.field = field;\r\n return _this;\r\n }\r\n NanFilter.prototype.matches = function (doc) {\r\n var field = doc.field(this.field);\r\n var val = field && field.value();\r\n return typeof val === 'number' && isNaN(val);\r\n };\r\n NanFilter.prototype.canonicalId = function () {\r\n return this.field.canonicalString() + ' IS NaN';\r\n };\r\n NanFilter.prototype.toString = function () {\r\n return this.field.canonicalString() + \" IS NaN\";\r\n };\r\n NanFilter.prototype.isEqual = function (other) {\r\n if (other instanceof NanFilter) {\r\n return this.field.isEqual(other.field);\r\n }\r\n else {\r\n return false;\r\n }\r\n };\r\n return NanFilter;\r\n}(Filter));\r\n/**\r\n * The direction of sorting in an order by.\r\n */\r\nvar Direction = /** @class */ (function () {\r\n function Direction(name) {\r\n this.name = name;\r\n }\r\n Direction.prototype.toString = function () {\r\n return this.name;\r\n };\r\n Direction.ASCENDING = new Direction('asc');\r\n Direction.DESCENDING = new Direction('desc');\r\n return Direction;\r\n}());\r\n/**\r\n * Represents a bound of a query.\r\n *\r\n * The bound is specified with the given components representing a position and\r\n * whether it's just before or just after the position (relative to whatever the\r\n * query order is).\r\n *\r\n * The position represents a logical index position for a query. It's a prefix\r\n * of values for the (potentially implicit) order by clauses of a query.\r\n *\r\n * Bound provides a function to determine whether a document comes before or\r\n * after a bound. This is influenced by whether the position is just before or\r\n * just after the provided values.\r\n */\r\nvar Bound = /** @class */ (function () {\r\n function Bound(position, before) {\r\n this.position = position;\r\n this.before = before;\r\n }\r\n Bound.prototype.canonicalId = function () {\r\n // TODO(b/29183165): Make this collision robust.\r\n var canonicalId = this.before ? 'b:' : 'a:';\r\n for (var _i = 0, _a = this.position; _i < _a.length; _i++) {\r\n var component = _a[_i];\r\n canonicalId += component.toString();\r\n }\r\n return canonicalId;\r\n };\r\n /**\r\n * Returns true if a document sorts before a bound using the provided sort\r\n * order.\r\n */\r\n Bound.prototype.sortsBeforeDocument = function (orderBy, doc) {\r\n assert(this.position.length <= orderBy.length, \"Bound has more components than query's orderBy\");\r\n var comparison = 0;\r\n for (var i = 0; i < this.position.length; i++) {\r\n var orderByComponent = orderBy[i];\r\n var component = this.position[i];\r\n if (orderByComponent.field.isKeyField()) {\r\n assert(component instanceof RefValue, 'Bound has a non-key value where the key path is being used.');\r\n comparison = DocumentKey.comparator(component.key, doc.key);\r\n }\r\n else {\r\n var docValue = doc.field(orderByComponent.field);\r\n assert(docValue !== undefined, 'Field should exist since document matched the orderBy already.');\r\n comparison = component.compareTo(docValue);\r\n }\r\n if (orderByComponent.dir === Direction.DESCENDING) {\r\n comparison = comparison * -1;\r\n }\r\n if (comparison !== 0) {\r\n break;\r\n }\r\n }\r\n return this.before ? comparison <= 0 : comparison < 0;\r\n };\r\n Bound.prototype.isEqual = function (other) {\r\n if (other === null) {\r\n return false;\r\n }\r\n if (this.before !== other.before ||\r\n this.position.length !== other.position.length) {\r\n return false;\r\n }\r\n for (var i = 0; i < this.position.length; i++) {\r\n var thisPosition = this.position[i];\r\n var otherPosition = other.position[i];\r\n return thisPosition.isEqual(otherPosition);\r\n }\r\n return true;\r\n };\r\n return Bound;\r\n}());\r\n/**\r\n * An ordering on a field, in some Direction. Direction defaults to ASCENDING.\r\n */\r\nvar OrderBy = /** @class */ (function () {\r\n function OrderBy(field, dir) {\r\n this.field = field;\r\n if (dir === undefined) {\r\n dir = Direction.ASCENDING;\r\n }\r\n this.dir = dir;\r\n this.isKeyOrderBy = field.isKeyField();\r\n }\r\n OrderBy.prototype.compare = function (d1, d2) {\r\n var comparison = this.isKeyOrderBy\r\n ? Document.compareByKey(d1, d2)\r\n : Document.compareByField(this.field, d1, d2);\r\n switch (this.dir) {\r\n case Direction.ASCENDING:\r\n return comparison;\r\n case Direction.DESCENDING:\r\n return -1 * comparison;\r\n default:\r\n return fail('Unknown direction: ' + this.dir);\r\n }\r\n };\r\n OrderBy.prototype.canonicalId = function () {\r\n // TODO(b/29183165): Make this collision robust.\r\n return this.field.canonicalString() + this.dir.toString();\r\n };\r\n OrderBy.prototype.toString = function () {\r\n return this.field.canonicalString() + \" (\" + this.dir + \")\";\r\n };\r\n OrderBy.prototype.isEqual = function (other) {\r\n return this.dir === other.dir && this.field.isEqual(other.field);\r\n };\r\n return OrderBy;\r\n}());\r\nvar KEY_ORDERING_ASC = new OrderBy(FieldPath.keyField(), Direction.ASCENDING);\r\nvar KEY_ORDERING_DESC = new OrderBy(FieldPath.keyField(), Direction.DESCENDING);\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A version of a document in Firestore. This corresponds to the version\r\n * timestamp, such as update_time or read_time.\r\n */\r\nvar SnapshotVersion = /** @class */ (function () {\r\n function SnapshotVersion(timestamp) {\r\n this.timestamp = timestamp;\r\n }\r\n // TODO(b/34176344): Once we no longer need to use the old alpha protos,\r\n // delete this constructor and use a timestamp-backed version everywhere.\r\n SnapshotVersion.fromMicroseconds = function (value) {\r\n var seconds = Math.floor(value / 1e6);\r\n var nanos = (value % 1e6) * 1e3;\r\n return new SnapshotVersion(new Timestamp(seconds, nanos));\r\n };\r\n SnapshotVersion.fromTimestamp = function (value) {\r\n return new SnapshotVersion(value);\r\n };\r\n SnapshotVersion.forDeletedDoc = function () {\r\n return SnapshotVersion.MIN;\r\n };\r\n SnapshotVersion.prototype.compareTo = function (other) {\r\n return this.timestamp._compareTo(other.timestamp);\r\n };\r\n SnapshotVersion.prototype.isEqual = function (other) {\r\n return this.timestamp.isEqual(other.timestamp);\r\n };\r\n /** Returns a number representation of the version for use in spec tests. */\r\n SnapshotVersion.prototype.toMicroseconds = function () {\r\n // Convert to microseconds.\r\n return this.timestamp.seconds * 1e6 + this.timestamp.nanoseconds / 1000;\r\n };\r\n SnapshotVersion.prototype.toString = function () {\r\n return 'SnapshotVersion(' + this.timestamp.toString() + ')';\r\n };\r\n SnapshotVersion.prototype.toTimestamp = function () {\r\n return this.timestamp;\r\n };\r\n SnapshotVersion.MIN = new SnapshotVersion(new Timestamp(0, 0));\r\n return SnapshotVersion;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** An enumeration of the different purposes we have for queries. */\r\nvar QueryPurpose;\r\n(function (QueryPurpose) {\r\n /** A regular, normal query. */\r\n QueryPurpose[QueryPurpose[\"Listen\"] = 0] = \"Listen\";\r\n /**\r\n * The query was used to refill a query after an existence filter mismatch.\r\n */\r\n QueryPurpose[QueryPurpose[\"ExistenceFilterMismatch\"] = 1] = \"ExistenceFilterMismatch\";\r\n /** The query was used to resolve a limbo document. */\r\n QueryPurpose[QueryPurpose[\"LimboResolution\"] = 2] = \"LimboResolution\";\r\n})(QueryPurpose || (QueryPurpose = {}));\r\n/**\r\n * An immutable set of metadata that the local store tracks for each query.\r\n */\r\nvar QueryData = /** @class */ (function () {\r\n function QueryData(\r\n /** The query being listened to. */\r\n query, \r\n /**\r\n * The target ID to which the query corresponds; Assigned by the\r\n * LocalStore for user listens and by the SyncEngine for limbo watches.\r\n */\r\n targetId, \r\n /** The purpose of the query. */\r\n purpose, \r\n /** The sequence number of the last transaction during which this query data was modified */\r\n sequenceNumber, \r\n /** The latest snapshot version seen for this target. */\r\n snapshotVersion, \r\n /**\r\n * An opaque, server-assigned token that allows watching a query to be\r\n * resumed after disconnecting without retransmitting all the data that\r\n * matches the query. The resume token essentially identifies a point in\r\n * time from which the server should resume sending results.\r\n */\r\n resumeToken) {\r\n if (snapshotVersion === void 0) { snapshotVersion = SnapshotVersion.MIN; }\r\n if (resumeToken === void 0) { resumeToken = emptyByteString(); }\r\n this.query = query;\r\n this.targetId = targetId;\r\n this.purpose = purpose;\r\n this.sequenceNumber = sequenceNumber;\r\n this.snapshotVersion = snapshotVersion;\r\n this.resumeToken = resumeToken;\r\n }\r\n /**\r\n * Creates a new query data instance with an updated snapshot version and\r\n * resume token.\r\n */\r\n QueryData.prototype.copy = function (overwrite) {\r\n return new QueryData(this.query, this.targetId, this.purpose, overwrite.sequenceNumber === undefined\r\n ? this.sequenceNumber\r\n : overwrite.sequenceNumber, overwrite.snapshotVersion === undefined\r\n ? this.snapshotVersion\r\n : overwrite.snapshotVersion, overwrite.resumeToken === undefined\r\n ? this.resumeToken\r\n : overwrite.resumeToken);\r\n };\r\n QueryData.prototype.isEqual = function (other) {\r\n return (this.targetId === other.targetId &&\r\n this.purpose === other.purpose &&\r\n this.sequenceNumber === other.sequenceNumber &&\r\n this.snapshotVersion.isEqual(other.snapshotVersion) &&\r\n this.resumeToken === other.resumeToken &&\r\n this.query.isEqual(other.query));\r\n };\r\n return QueryData;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * SortedSet is an immutable (copy-on-write) collection that holds elements\r\n * in order specified by the provided comparator.\r\n *\r\n * NOTE: if provided comparator returns 0 for two elements, we consider them to\r\n * be equal!\r\n */\r\nvar SortedSet = /** @class */ (function () {\r\n function SortedSet(comparator) {\r\n this.comparator = comparator;\r\n this.data = new SortedMap(this.comparator);\r\n }\r\n /**\r\n * Creates a SortedSet from the keys of the map.\r\n * This is currently implemented as an O(n) copy.\r\n */\r\n SortedSet.fromMapKeys = function (map) {\r\n var keys = new SortedSet(map.comparator);\r\n map.forEach(function (key) {\r\n keys = keys.add(key);\r\n });\r\n return keys;\r\n };\r\n SortedSet.prototype.has = function (elem) {\r\n return this.data.get(elem) !== null;\r\n };\r\n SortedSet.prototype.first = function () {\r\n return this.data.minKey();\r\n };\r\n SortedSet.prototype.last = function () {\r\n return this.data.maxKey();\r\n };\r\n Object.defineProperty(SortedSet.prototype, \"size\", {\r\n get: function () {\r\n return this.data.size;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n SortedSet.prototype.indexOf = function (elem) {\r\n return this.data.indexOf(elem);\r\n };\r\n /** Iterates elements in order defined by \"comparator\" */\r\n SortedSet.prototype.forEach = function (cb) {\r\n this.data.inorderTraversal(function (k, v) {\r\n cb(k);\r\n return false;\r\n });\r\n };\r\n /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */\r\n SortedSet.prototype.forEachInRange = function (range, cb) {\r\n var iter = this.data.getIteratorFrom(range[0]);\r\n while (iter.hasNext()) {\r\n var elem = iter.getNext();\r\n if (this.comparator(elem.key, range[1]) >= 0)\r\n return;\r\n cb(elem.key);\r\n }\r\n };\r\n /**\r\n * Iterates over `elem`s such that: start <= elem until false is returned.\r\n */\r\n SortedSet.prototype.forEachWhile = function (cb, start) {\r\n var iter;\r\n if (start !== undefined) {\r\n iter = this.data.getIteratorFrom(start);\r\n }\r\n else {\r\n iter = this.data.getIterator();\r\n }\r\n while (iter.hasNext()) {\r\n var elem = iter.getNext();\r\n var result = cb(elem.key);\r\n if (!result)\r\n return;\r\n }\r\n };\r\n /** Finds the least element greater than or equal to `elem`. */\r\n SortedSet.prototype.firstAfterOrEqual = function (elem) {\r\n var iter = this.data.getIteratorFrom(elem);\r\n return iter.hasNext() ? iter.getNext().key : null;\r\n };\r\n SortedSet.prototype.getIterator = function () {\r\n return new SortedSetIterator(this.data.getIterator());\r\n };\r\n SortedSet.prototype.getIteratorFrom = function (key) {\r\n return new SortedSetIterator(this.data.getIteratorFrom(key));\r\n };\r\n /** Inserts or updates an element */\r\n SortedSet.prototype.add = function (elem) {\r\n return this.copy(this.data.remove(elem).insert(elem, true));\r\n };\r\n /** Deletes an element */\r\n SortedSet.prototype.delete = function (elem) {\r\n if (!this.has(elem))\r\n return this;\r\n return this.copy(this.data.remove(elem));\r\n };\r\n SortedSet.prototype.isEmpty = function () {\r\n return this.data.isEmpty();\r\n };\r\n SortedSet.prototype.unionWith = function (other) {\r\n var result = this;\r\n other.forEach(function (elem) {\r\n result = result.add(elem);\r\n });\r\n return result;\r\n };\r\n SortedSet.prototype.isEqual = function (other) {\r\n if (!(other instanceof SortedSet))\r\n return false;\r\n if (this.size !== other.size)\r\n return false;\r\n var thisIt = this.data.getIterator();\r\n var otherIt = other.data.getIterator();\r\n while (thisIt.hasNext()) {\r\n var thisElem = thisIt.getNext().key;\r\n var otherElem = otherIt.getNext().key;\r\n if (this.comparator(thisElem, otherElem) !== 0)\r\n return false;\r\n }\r\n return true;\r\n };\r\n SortedSet.prototype.toArray = function () {\r\n var res = [];\r\n this.forEach(function (targetId) {\r\n res.push(targetId);\r\n });\r\n return res;\r\n };\r\n SortedSet.prototype.toString = function () {\r\n var result = [];\r\n this.forEach(function (elem) { return result.push(elem); });\r\n return 'SortedSet(' + result.toString() + ')';\r\n };\r\n SortedSet.prototype.copy = function (data) {\r\n var result = new SortedSet(this.comparator);\r\n result.data = data;\r\n return result;\r\n };\r\n return SortedSet;\r\n}());\r\nvar SortedSetIterator = /** @class */ (function () {\r\n function SortedSetIterator(iter) {\r\n this.iter = iter;\r\n }\r\n SortedSetIterator.prototype.getNext = function () {\r\n return this.iter.getNext().key;\r\n };\r\n SortedSetIterator.prototype.hasNext = function () {\r\n return this.iter.hasNext();\r\n };\r\n return SortedSetIterator;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provides a set of fields that can be used to partially patch a document.\r\n * FieldMask is used in conjunction with ObjectValue.\r\n * Examples:\r\n * foo - Overwrites foo entirely with the provided value. If foo is not\r\n * present in the companion ObjectValue, the field is deleted.\r\n * foo.bar - Overwrites only the field bar of the object foo.\r\n * If foo is not an object, foo is replaced with an object\r\n * containing foo\r\n */\r\nvar FieldMask = /** @class */ (function () {\r\n function FieldMask(fields) {\r\n this.fields = fields;\r\n // TODO(dimond): validation of FieldMask\r\n }\r\n FieldMask.fromSet = function (fields) {\r\n return new FieldMask(fields);\r\n };\r\n FieldMask.fromArray = function (fields) {\r\n var fieldsAsSet = new SortedSet(FieldPath.comparator);\r\n fields.forEach(function (fieldPath) { return (fieldsAsSet = fieldsAsSet.add(fieldPath)); });\r\n return new FieldMask(fieldsAsSet);\r\n };\r\n /**\r\n * Verifies that `fieldPath` is included by at least one field in this field\r\n * mask.\r\n *\r\n * This is an O(n) operation, where `n` is the size of the field mask.\r\n */\r\n FieldMask.prototype.covers = function (fieldPath) {\r\n var found = false;\r\n this.fields.forEach(function (fieldMaskPath) {\r\n if (fieldMaskPath.isPrefixOf(fieldPath)) {\r\n found = true;\r\n }\r\n });\r\n return found;\r\n };\r\n /**\r\n * Applies this field mask to the provided object value and returns an object\r\n * that only contains fields that are specified in both the input object and\r\n * this field mask.\r\n */\r\n FieldMask.prototype.applyTo = function (data) {\r\n var filteredObject = ObjectValue.EMPTY;\r\n this.fields.forEach(function (fieldMaskPath) {\r\n if (fieldMaskPath.isEmpty()) {\r\n return data;\r\n }\r\n else {\r\n var newValue = data.field(fieldMaskPath);\r\n if (newValue !== undefined) {\r\n filteredObject = filteredObject.set(fieldMaskPath, newValue);\r\n }\r\n }\r\n });\r\n return filteredObject;\r\n };\r\n FieldMask.prototype.isEqual = function (other) {\r\n return this.fields.isEqual(other.fields);\r\n };\r\n return FieldMask;\r\n}());\r\n/** A field path and the TransformOperation to perform upon it. */\r\nvar FieldTransform = /** @class */ (function () {\r\n function FieldTransform(field, transform) {\r\n this.field = field;\r\n this.transform = transform;\r\n }\r\n Object.defineProperty(FieldTransform.prototype, \"isIdempotent\", {\r\n /** Whether this field transform is idempotent. */\r\n get: function () {\r\n return this.transform.isIdempotent;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n FieldTransform.prototype.isEqual = function (other) {\r\n return (this.field.isEqual(other.field) && this.transform.isEqual(other.transform));\r\n };\r\n return FieldTransform;\r\n}());\r\n/** The result of successfully applying a mutation to the backend. */\r\nvar MutationResult = /** @class */ (function () {\r\n function MutationResult(\r\n /**\r\n * The version at which the mutation was committed:\r\n *\r\n * - For most operations, this is the updateTime in the WriteResult.\r\n * - For deletes, the commitTime of the WriteResponse (because deletes are\r\n * not stored and have no updateTime).\r\n *\r\n * Note that these versions can be different: No-op writes will not change\r\n * the updateTime even though the commitTime advances.\r\n */\r\n version, \r\n /**\r\n * The resulting fields returned from the backend after a\r\n * TransformMutation has been committed. Contains one FieldValue for each\r\n * FieldTransform that was in the mutation.\r\n *\r\n * Will be null if the mutation was not a TransformMutation.\r\n */\r\n transformResults) {\r\n this.version = version;\r\n this.transformResults = transformResults;\r\n }\r\n return MutationResult;\r\n}());\r\nvar MutationType;\r\n(function (MutationType) {\r\n MutationType[MutationType[\"Set\"] = 0] = \"Set\";\r\n MutationType[MutationType[\"Patch\"] = 1] = \"Patch\";\r\n MutationType[MutationType[\"Transform\"] = 2] = \"Transform\";\r\n MutationType[MutationType[\"Delete\"] = 3] = \"Delete\";\r\n})(MutationType || (MutationType = {}));\r\n/**\r\n * Encodes a precondition for a mutation. This follows the model that the\r\n * backend accepts with the special case of an explicit \"empty\" precondition\r\n * (meaning no precondition).\r\n */\r\nvar Precondition = /** @class */ (function () {\r\n function Precondition(updateTime, exists) {\r\n this.updateTime = updateTime;\r\n this.exists = exists;\r\n assert(updateTime === undefined || exists === undefined, 'Precondition can specify \"exists\" or \"updateTime\" but not both');\r\n }\r\n /** Creates a new Precondition with an exists flag. */\r\n Precondition.exists = function (exists) {\r\n return new Precondition(undefined, exists);\r\n };\r\n /** Creates a new Precondition based on a version a document exists at. */\r\n Precondition.updateTime = function (version) {\r\n return new Precondition(version);\r\n };\r\n Object.defineProperty(Precondition.prototype, \"isNone\", {\r\n /** Returns whether this Precondition is empty. */\r\n get: function () {\r\n return this.updateTime === undefined && this.exists === undefined;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n /**\r\n * Returns true if the preconditions is valid for the given document\r\n * (or null if no document is available).\r\n */\r\n Precondition.prototype.isValidFor = function (maybeDoc) {\r\n if (this.updateTime !== undefined) {\r\n return (maybeDoc instanceof Document &&\r\n maybeDoc.version.isEqual(this.updateTime));\r\n }\r\n else if (this.exists !== undefined) {\r\n return this.exists === maybeDoc instanceof Document;\r\n }\r\n else {\r\n assert(this.isNone, 'Precondition should be empty');\r\n return true;\r\n }\r\n };\r\n Precondition.prototype.isEqual = function (other) {\r\n return (equals(this.updateTime, other.updateTime) &&\r\n this.exists === other.exists);\r\n };\r\n Precondition.NONE = new Precondition();\r\n return Precondition;\r\n}());\r\n/**\r\n * A mutation describes a self-contained change to a document. Mutations can\r\n * create, replace, delete, and update subsets of documents.\r\n *\r\n * Mutations not only act on the value of the document but also it version.\r\n *\r\n * For local mutations (mutations that haven't been committed yet), we preserve\r\n * the existing version for Set, Patch, and Transform mutations. For Delete\r\n * mutations, we reset the version to 0.\r\n *\r\n * Here's the expected transition table.\r\n *\r\n * MUTATION APPLIED TO RESULTS IN\r\n *\r\n * SetMutation Document(v3) Document(v3)\r\n * SetMutation NoDocument(v3) Document(v0)\r\n * SetMutation null Document(v0)\r\n * PatchMutation Document(v3) Document(v3)\r\n * PatchMutation NoDocument(v3) NoDocument(v3)\r\n * PatchMutation null null\r\n * TransformMutation Document(v3) Document(v3)\r\n * TransformMutation NoDocument(v3) NoDocument(v3)\r\n * TransformMutation null null\r\n * DeleteMutation Document(v3) NoDocument(v0)\r\n * DeleteMutation NoDocument(v3) NoDocument(v0)\r\n * DeleteMutation null NoDocument(v0)\r\n *\r\n * For acknowledged mutations, we use the updateTime of the WriteResponse as\r\n * the resulting version for Set, Patch, and Transform mutations. As deletes\r\n * have no explicit update time, we use the commitTime of the WriteResponse for\r\n * Delete mutations.\r\n *\r\n * If a mutation is acknowledged by the backend but fails the precondition check\r\n * locally, we return an `UnknownDocument` and rely on Watch to send us the\r\n * updated version.\r\n *\r\n * Note that TransformMutations don't create Documents (in the case of being\r\n * applied to a NoDocument), even though they would on the backend. This is\r\n * because the client always combines the TransformMutation with a SetMutation\r\n * or PatchMutation and we only want to apply the transform if the prior\r\n * mutation resulted in a Document (always true for a SetMutation, but not\r\n * necessarily for a PatchMutation).\r\n *\r\n * ## Subclassing Notes\r\n *\r\n * Subclasses of Mutation need to implement applyToRemoteDocument() and\r\n * applyToLocalView() to implement the actual behavior of applying the mutation\r\n * to some source document.\r\n */\r\nvar Mutation = /** @class */ (function () {\r\n function Mutation() {\r\n }\r\n Mutation.prototype.verifyKeyMatches = function (maybeDoc) {\r\n if (maybeDoc != null) {\r\n assert(maybeDoc.key.isEqual(this.key), 'Can only apply a mutation to a document with the same key');\r\n }\r\n };\r\n /**\r\n * Returns the version from the given document for use as the result of a\r\n * mutation. Mutations are defined to return the version of the base document\r\n * only if it is an existing document. Deleted and unknown documents have a\r\n * post-mutation version of SnapshotVersion.MIN.\r\n */\r\n Mutation.getPostMutationVersion = function (maybeDoc) {\r\n if (maybeDoc instanceof Document) {\r\n return maybeDoc.version;\r\n }\r\n else {\r\n return SnapshotVersion.MIN;\r\n }\r\n };\r\n return Mutation;\r\n}());\r\n/**\r\n * A mutation that creates or replaces the document at the given key with the\r\n * object value contents.\r\n */\r\nvar SetMutation = /** @class */ (function (_super) {\r\n tslib_1.__extends(SetMutation, _super);\r\n function SetMutation(key, value, precondition) {\r\n var _this = _super.call(this) || this;\r\n _this.key = key;\r\n _this.value = value;\r\n _this.precondition = precondition;\r\n _this.type = MutationType.Set;\r\n return _this;\r\n }\r\n SetMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\r\n this.verifyKeyMatches(maybeDoc);\r\n assert(mutationResult.transformResults == null, 'Transform results received by SetMutation.');\r\n // Unlike applyToLocalView, if we're applying a mutation to a remote\r\n // document the server has accepted the mutation so the precondition must\r\n // have held.\r\n var version = mutationResult.version;\r\n return new Document(this.key, version, this.value, {\r\n hasCommittedMutations: true\r\n });\r\n };\r\n SetMutation.prototype.applyToLocalView = function (maybeDoc, baseDoc, localWriteTime) {\r\n this.verifyKeyMatches(maybeDoc);\r\n if (!this.precondition.isValidFor(maybeDoc)) {\r\n return maybeDoc;\r\n }\r\n var version = Mutation.getPostMutationVersion(maybeDoc);\r\n return new Document(this.key, version, this.value, {\r\n hasLocalMutations: true\r\n });\r\n };\r\n Object.defineProperty(SetMutation.prototype, \"isIdempotent\", {\r\n get: function () {\r\n return true;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(SetMutation.prototype, \"fieldMask\", {\r\n get: function () {\r\n return null;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n SetMutation.prototype.isEqual = function (other) {\r\n return (other instanceof SetMutation &&\r\n this.key.isEqual(other.key) &&\r\n this.value.isEqual(other.value) &&\r\n this.precondition.isEqual(other.precondition));\r\n };\r\n return SetMutation;\r\n}(Mutation));\r\n/**\r\n * A mutation that modifies fields of the document at the given key with the\r\n * given values. The values are applied through a field mask:\r\n *\r\n * * When a field is in both the mask and the values, the corresponding field\r\n * is updated.\r\n * * When a field is in neither the mask nor the values, the corresponding\r\n * field is unmodified.\r\n * * When a field is in the mask but not in the values, the corresponding field\r\n * is deleted.\r\n * * When a field is not in the mask but is in the values, the values map is\r\n * ignored.\r\n */\r\nvar PatchMutation = /** @class */ (function (_super) {\r\n tslib_1.__extends(PatchMutation, _super);\r\n function PatchMutation(key, data, fieldMask, precondition) {\r\n var _this = _super.call(this) || this;\r\n _this.key = key;\r\n _this.data = data;\r\n _this.fieldMask = fieldMask;\r\n _this.precondition = precondition;\r\n _this.type = MutationType.Patch;\r\n return _this;\r\n }\r\n PatchMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\r\n this.verifyKeyMatches(maybeDoc);\r\n assert(mutationResult.transformResults == null, 'Transform results received by PatchMutation.');\r\n if (!this.precondition.isValidFor(maybeDoc)) {\r\n // Since the mutation was not rejected, we know that the precondition\r\n // matched on the backend. We therefore must not have the expected version\r\n // of the document in our cache and return an UnknownDocument with the\r\n // known updateTime.\r\n return new UnknownDocument(this.key, mutationResult.version);\r\n }\r\n var newData = this.patchDocument(maybeDoc);\r\n return new Document(this.key, mutationResult.version, newData, {\r\n hasCommittedMutations: true\r\n });\r\n };\r\n PatchMutation.prototype.applyToLocalView = function (maybeDoc, baseDoc, localWriteTime) {\r\n this.verifyKeyMatches(maybeDoc);\r\n if (!this.precondition.isValidFor(maybeDoc)) {\r\n return maybeDoc;\r\n }\r\n var version = Mutation.getPostMutationVersion(maybeDoc);\r\n var newData = this.patchDocument(maybeDoc);\r\n return new Document(this.key, version, newData, {\r\n hasLocalMutations: true\r\n });\r\n };\r\n Object.defineProperty(PatchMutation.prototype, \"isIdempotent\", {\r\n get: function () {\r\n return true;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n PatchMutation.prototype.isEqual = function (other) {\r\n return (other instanceof PatchMutation &&\r\n this.key.isEqual(other.key) &&\r\n this.fieldMask.isEqual(other.fieldMask) &&\r\n this.precondition.isEqual(other.precondition));\r\n };\r\n /**\r\n * Patches the data of document if available or creates a new document. Note\r\n * that this does not check whether or not the precondition of this patch\r\n * holds.\r\n */\r\n PatchMutation.prototype.patchDocument = function (maybeDoc) {\r\n var data;\r\n if (maybeDoc instanceof Document) {\r\n data = maybeDoc.data;\r\n }\r\n else {\r\n data = ObjectValue.EMPTY;\r\n }\r\n return this.patchObject(data);\r\n };\r\n PatchMutation.prototype.patchObject = function (data) {\r\n var _this = this;\r\n this.fieldMask.fields.forEach(function (fieldPath) {\r\n if (!fieldPath.isEmpty()) {\r\n var newValue = _this.data.field(fieldPath);\r\n if (newValue !== undefined) {\r\n data = data.set(fieldPath, newValue);\r\n }\r\n else {\r\n data = data.delete(fieldPath);\r\n }\r\n }\r\n });\r\n return data;\r\n };\r\n return PatchMutation;\r\n}(Mutation));\r\n/**\r\n * A mutation that modifies specific fields of the document with transform\r\n * operations. Currently the only supported transform is a server timestamp, but\r\n * IP Address, increment(n), etc. could be supported in the future.\r\n *\r\n * It is somewhat similar to a PatchMutation in that it patches specific fields\r\n * and has no effect when applied to a null or NoDocument (see comment on\r\n * Mutation for rationale).\r\n */\r\nvar TransformMutation = /** @class */ (function (_super) {\r\n tslib_1.__extends(TransformMutation, _super);\r\n function TransformMutation(key, fieldTransforms) {\r\n var _this = _super.call(this) || this;\r\n _this.key = key;\r\n _this.fieldTransforms = fieldTransforms;\r\n _this.type = MutationType.Transform;\r\n // NOTE: We set a precondition of exists: true as a safety-check, since we\r\n // always combine TransformMutations with a SetMutation or PatchMutation which\r\n // (if successful) should end up with an existing document.\r\n _this.precondition = Precondition.exists(true);\r\n return _this;\r\n }\r\n TransformMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\r\n this.verifyKeyMatches(maybeDoc);\r\n assert(mutationResult.transformResults != null, 'Transform results missing for TransformMutation.');\r\n if (!this.precondition.isValidFor(maybeDoc)) {\r\n // Since the mutation was not rejected, we know that the precondition\r\n // matched on the backend. We therefore must not have the expected version\r\n // of the document in our cache and return an UnknownDocument with the\r\n // known updateTime.\r\n return new UnknownDocument(this.key, mutationResult.version);\r\n }\r\n var doc = this.requireDocument(maybeDoc);\r\n var transformResults = this.serverTransformResults(maybeDoc, mutationResult.transformResults);\r\n var version = mutationResult.version;\r\n var newData = this.transformObject(doc.data, transformResults);\r\n return new Document(this.key, version, newData, {\r\n hasCommittedMutations: true\r\n });\r\n };\r\n TransformMutation.prototype.applyToLocalView = function (maybeDoc, baseDoc, localWriteTime) {\r\n this.verifyKeyMatches(maybeDoc);\r\n if (!this.precondition.isValidFor(maybeDoc)) {\r\n return maybeDoc;\r\n }\r\n var doc = this.requireDocument(maybeDoc);\r\n var transformResults = this.localTransformResults(localWriteTime, baseDoc);\r\n var newData = this.transformObject(doc.data, transformResults);\r\n return new Document(this.key, doc.version, newData, {\r\n hasLocalMutations: true\r\n });\r\n };\r\n Object.defineProperty(TransformMutation.prototype, \"isIdempotent\", {\r\n get: function () {\r\n for (var _i = 0, _a = this.fieldTransforms; _i < _a.length; _i++) {\r\n var fieldTransform = _a[_i];\r\n if (!fieldTransform.isIdempotent) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(TransformMutation.prototype, \"fieldMask\", {\r\n get: function () {\r\n var fieldMask = new SortedSet(FieldPath.comparator);\r\n this.fieldTransforms.forEach(function (transform) { return (fieldMask = fieldMask.add(transform.field)); });\r\n return new FieldMask(fieldMask);\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n TransformMutation.prototype.isEqual = function (other) {\r\n return (other instanceof TransformMutation &&\r\n this.key.isEqual(other.key) &&\r\n arrayEquals(this.fieldTransforms, other.fieldTransforms) &&\r\n this.precondition.isEqual(other.precondition));\r\n };\r\n /**\r\n * Asserts that the given MaybeDocument is actually a Document and verifies\r\n * that it matches the key for this mutation. Since we only support\r\n * transformations with precondition exists this method is guaranteed to be\r\n * safe.\r\n */\r\n TransformMutation.prototype.requireDocument = function (maybeDoc) {\r\n assert(maybeDoc instanceof Document, 'Unknown MaybeDocument type ' + maybeDoc);\r\n var doc = maybeDoc;\r\n assert(doc.key.isEqual(this.key), 'Can only transform a document with the same key');\r\n return doc;\r\n };\r\n /**\r\n * Creates a list of \"transform results\" (a transform result is a field value\r\n * representing the result of applying a transform) for use after a\r\n * TransformMutation has been acknowledged by the server.\r\n *\r\n * @param baseDoc The document prior to applying this mutation batch.\r\n * @param serverTransformResults The transform results received by the server.\r\n * @return The transform results list.\r\n */\r\n TransformMutation.prototype.serverTransformResults = function (baseDoc, serverTransformResults) {\r\n var transformResults = [];\r\n assert(this.fieldTransforms.length === serverTransformResults.length, \"server transform result count (\" + serverTransformResults.length + \") \" +\r\n (\"should match field transform count (\" + this.fieldTransforms.length + \")\"));\r\n for (var i = 0; i < serverTransformResults.length; i++) {\r\n var fieldTransform = this.fieldTransforms[i];\r\n var transform = fieldTransform.transform;\r\n var previousValue = null;\r\n if (baseDoc instanceof Document) {\r\n previousValue = baseDoc.field(fieldTransform.field) || null;\r\n }\r\n transformResults.push(transform.applyToRemoteDocument(previousValue, serverTransformResults[i]));\r\n }\r\n return transformResults;\r\n };\r\n /**\r\n * Creates a list of \"transform results\" (a transform result is a field value\r\n * representing the result of applying a transform) for use when applying a\r\n * TransformMutation locally.\r\n *\r\n * @param localWriteTime The local time of the transform mutation (used to\r\n * generate ServerTimestampValues).\r\n * @param baseDoc The document prior to applying this mutation batch.\r\n * @return The transform results list.\r\n */\r\n TransformMutation.prototype.localTransformResults = function (localWriteTime, baseDoc) {\r\n var transformResults = [];\r\n for (var _i = 0, _a = this.fieldTransforms; _i < _a.length; _i++) {\r\n var fieldTransform = _a[_i];\r\n var transform = fieldTransform.transform;\r\n var previousValue = null;\r\n if (baseDoc instanceof Document) {\r\n previousValue = baseDoc.field(fieldTransform.field) || null;\r\n }\r\n transformResults.push(transform.applyToLocalView(previousValue, localWriteTime));\r\n }\r\n return transformResults;\r\n };\r\n TransformMutation.prototype.transformObject = function (data, transformResults) {\r\n assert(transformResults.length === this.fieldTransforms.length, 'TransformResults length mismatch.');\r\n for (var i = 0; i < this.fieldTransforms.length; i++) {\r\n var fieldTransform = this.fieldTransforms[i];\r\n var fieldPath = fieldTransform.field;\r\n data = data.set(fieldPath, transformResults[i]);\r\n }\r\n return data;\r\n };\r\n return TransformMutation;\r\n}(Mutation));\r\n/** A mutation that deletes the document at the given key. */\r\nvar DeleteMutation = /** @class */ (function (_super) {\r\n tslib_1.__extends(DeleteMutation, _super);\r\n function DeleteMutation(key, precondition) {\r\n var _this = _super.call(this) || this;\r\n _this.key = key;\r\n _this.precondition = precondition;\r\n _this.type = MutationType.Delete;\r\n return _this;\r\n }\r\n DeleteMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\r\n this.verifyKeyMatches(maybeDoc);\r\n assert(mutationResult.transformResults == null, 'Transform results received by DeleteMutation.');\r\n // Unlike applyToLocalView, if we're applying a mutation to a remote\r\n // document the server has accepted the mutation so the precondition must\r\n // have held.\r\n return new NoDocument(this.key, mutationResult.version, {\r\n hasCommittedMutations: true\r\n });\r\n };\r\n DeleteMutation.prototype.applyToLocalView = function (maybeDoc, baseDoc, localWriteTime) {\r\n this.verifyKeyMatches(maybeDoc);\r\n if (!this.precondition.isValidFor(maybeDoc)) {\r\n return maybeDoc;\r\n }\r\n if (maybeDoc) {\r\n assert(maybeDoc.key.isEqual(this.key), 'Can only apply mutation to document with same key');\r\n }\r\n return new NoDocument(this.key, SnapshotVersion.forDeletedDoc());\r\n };\r\n DeleteMutation.prototype.isEqual = function (other) {\r\n return (other instanceof DeleteMutation &&\r\n this.key.isEqual(other.key) &&\r\n this.precondition.isEqual(other.precondition));\r\n };\r\n Object.defineProperty(DeleteMutation.prototype, \"isIdempotent\", {\r\n get: function () {\r\n return true;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(DeleteMutation.prototype, \"fieldMask\", {\r\n get: function () {\r\n return null;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n return DeleteMutation;\r\n}(Mutation));\n\n/**\r\n * @license\r\n * Copyright 2018 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** Transforms a value into a server-generated timestamp. */\r\nvar ServerTimestampTransform = /** @class */ (function () {\r\n function ServerTimestampTransform() {\r\n this.isIdempotent = true;\r\n }\r\n ServerTimestampTransform.prototype.applyToLocalView = function (previousValue, localWriteTime) {\r\n return new ServerTimestampValue(localWriteTime, previousValue);\r\n };\r\n ServerTimestampTransform.prototype.applyToRemoteDocument = function (previousValue, transformResult) {\r\n return transformResult;\r\n };\r\n ServerTimestampTransform.prototype.isEqual = function (other) {\r\n return other instanceof ServerTimestampTransform;\r\n };\r\n ServerTimestampTransform.instance = new ServerTimestampTransform();\r\n return ServerTimestampTransform;\r\n}());\r\n/** Transforms an array value via a union operation. */\r\nvar ArrayUnionTransformOperation = /** @class */ (function () {\r\n function ArrayUnionTransformOperation(elements) {\r\n this.elements = elements;\r\n this.isIdempotent = true;\r\n }\r\n ArrayUnionTransformOperation.prototype.applyToLocalView = function (previousValue, localWriteTime) {\r\n return this.apply(previousValue);\r\n };\r\n ArrayUnionTransformOperation.prototype.applyToRemoteDocument = function (previousValue, transformResult) {\r\n // The server just sends null as the transform result for array operations,\r\n // so we have to calculate a result the same as we do for local\r\n // applications.\r\n return this.apply(previousValue);\r\n };\r\n ArrayUnionTransformOperation.prototype.apply = function (previousValue) {\r\n var result = coercedFieldValuesArray(previousValue);\r\n var _loop_1 = function (toUnion) {\r\n if (!result.find(function (element) { return element.isEqual(toUnion); })) {\r\n result.push(toUnion);\r\n }\r\n };\r\n for (var _i = 0, _a = this.elements; _i < _a.length; _i++) {\r\n var toUnion = _a[_i];\r\n _loop_1(toUnion);\r\n }\r\n return new ArrayValue(result);\r\n };\r\n ArrayUnionTransformOperation.prototype.isEqual = function (other) {\r\n return (other instanceof ArrayUnionTransformOperation &&\r\n arrayEquals(other.elements, this.elements));\r\n };\r\n return ArrayUnionTransformOperation;\r\n}());\r\n/** Transforms an array value via a remove operation. */\r\nvar ArrayRemoveTransformOperation = /** @class */ (function () {\r\n function ArrayRemoveTransformOperation(elements) {\r\n this.elements = elements;\r\n this.isIdempotent = true;\r\n }\r\n ArrayRemoveTransformOperation.prototype.applyToLocalView = function (previousValue, localWriteTime) {\r\n return this.apply(previousValue);\r\n };\r\n ArrayRemoveTransformOperation.prototype.applyToRemoteDocument = function (previousValue, transformResult) {\r\n // The server just sends null as the transform result for array operations,\r\n // so we have to calculate a result the same as we do for local\r\n // applications.\r\n return this.apply(previousValue);\r\n };\r\n ArrayRemoveTransformOperation.prototype.apply = function (previousValue) {\r\n var result = coercedFieldValuesArray(previousValue);\r\n var _loop_2 = function (toRemove) {\r\n result = result.filter(function (element) { return !element.isEqual(toRemove); });\r\n };\r\n for (var _i = 0, _a = this.elements; _i < _a.length; _i++) {\r\n var toRemove = _a[_i];\r\n _loop_2(toRemove);\r\n }\r\n return new ArrayValue(result);\r\n };\r\n ArrayRemoveTransformOperation.prototype.isEqual = function (other) {\r\n return (other instanceof ArrayRemoveTransformOperation &&\r\n arrayEquals(other.elements, this.elements));\r\n };\r\n return ArrayRemoveTransformOperation;\r\n}());\r\n/**\r\n * Implements the backend semantics for locally computed NUMERIC_ADD (increment)\r\n * transforms. Converts all field values to integers or doubles, but unlike the\r\n * backend does not cap integer values at 2^63. Instead, JavaScript number\r\n * arithmetic is used and precision loss can occur for values greater than 2^53.\r\n */\r\nvar NumericIncrementTransformOperation = /** @class */ (function () {\r\n function NumericIncrementTransformOperation(operand) {\r\n this.operand = operand;\r\n this.isIdempotent = false;\r\n }\r\n NumericIncrementTransformOperation.prototype.applyToLocalView = function (previousValue, localWriteTime) {\r\n // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit\r\n // precision and resolves overflows by reducing precision, we do not\r\n // manually cap overflows at 2^63.\r\n // Return an integer value iff the previous value and the operand is an\r\n // integer.\r\n if (previousValue instanceof IntegerValue &&\r\n this.operand instanceof IntegerValue) {\r\n var sum = previousValue.internalValue + this.operand.internalValue;\r\n return new IntegerValue(sum);\r\n }\r\n else if (previousValue instanceof NumberValue) {\r\n var sum = previousValue.internalValue + this.operand.internalValue;\r\n return new DoubleValue(sum);\r\n }\r\n else {\r\n // If the existing value is not a number, use the value of the transform as\r\n // the new base value.\r\n return this.operand;\r\n }\r\n };\r\n NumericIncrementTransformOperation.prototype.applyToRemoteDocument = function (previousValue, transformResult) {\r\n assert(transformResult !== null, \"Didn't receive transformResult for NUMERIC_ADD transform\");\r\n return transformResult;\r\n };\r\n NumericIncrementTransformOperation.prototype.isEqual = function (other) {\r\n return (other instanceof NumericIncrementTransformOperation &&\r\n this.operand.isEqual(other.operand));\r\n };\r\n return NumericIncrementTransformOperation;\r\n}());\r\nfunction coercedFieldValuesArray(value) {\r\n if (value instanceof ArrayValue) {\r\n return value.internalValue.slice();\r\n }\r\n else {\r\n // coerce to empty array.\r\n return [];\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar ExistenceFilter = /** @class */ (function () {\r\n // TODO(b/33078163): just use simplest form of existence filter for now\r\n function ExistenceFilter(count) {\r\n this.count = count;\r\n }\r\n ExistenceFilter.prototype.isEqual = function (other) {\r\n return other && other.count === this.count;\r\n };\r\n return ExistenceFilter;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Error Codes describing the different ways GRPC can fail. These are copied\r\n * directly from GRPC's sources here:\r\n *\r\n * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\r\n *\r\n * Important! The names of these identifiers matter because the string forms\r\n * are used for reverse lookups from the webchannel stream. Do NOT change the\r\n * names of these identifiers.\r\n */\r\nvar RpcCode;\r\n(function (RpcCode) {\r\n RpcCode[RpcCode[\"OK\"] = 0] = \"OK\";\r\n RpcCode[RpcCode[\"CANCELLED\"] = 1] = \"CANCELLED\";\r\n RpcCode[RpcCode[\"UNKNOWN\"] = 2] = \"UNKNOWN\";\r\n RpcCode[RpcCode[\"INVALID_ARGUMENT\"] = 3] = \"INVALID_ARGUMENT\";\r\n RpcCode[RpcCode[\"DEADLINE_EXCEEDED\"] = 4] = \"DEADLINE_EXCEEDED\";\r\n RpcCode[RpcCode[\"NOT_FOUND\"] = 5] = \"NOT_FOUND\";\r\n RpcCode[RpcCode[\"ALREADY_EXISTS\"] = 6] = \"ALREADY_EXISTS\";\r\n RpcCode[RpcCode[\"PERMISSION_DENIED\"] = 7] = \"PERMISSION_DENIED\";\r\n RpcCode[RpcCode[\"UNAUTHENTICATED\"] = 16] = \"UNAUTHENTICATED\";\r\n RpcCode[RpcCode[\"RESOURCE_EXHAUSTED\"] = 8] = \"RESOURCE_EXHAUSTED\";\r\n RpcCode[RpcCode[\"FAILED_PRECONDITION\"] = 9] = \"FAILED_PRECONDITION\";\r\n RpcCode[RpcCode[\"ABORTED\"] = 10] = \"ABORTED\";\r\n RpcCode[RpcCode[\"OUT_OF_RANGE\"] = 11] = \"OUT_OF_RANGE\";\r\n RpcCode[RpcCode[\"UNIMPLEMENTED\"] = 12] = \"UNIMPLEMENTED\";\r\n RpcCode[RpcCode[\"INTERNAL\"] = 13] = \"INTERNAL\";\r\n RpcCode[RpcCode[\"UNAVAILABLE\"] = 14] = \"UNAVAILABLE\";\r\n RpcCode[RpcCode[\"DATA_LOSS\"] = 15] = \"DATA_LOSS\";\r\n})(RpcCode || (RpcCode = {}));\r\n/**\r\n * Determines whether an error code represents a permanent error when received\r\n * in response to a non-write operation.\r\n *\r\n * See isPermanentWriteError for classifying write errors.\r\n */\r\nfunction isPermanentError(code) {\r\n switch (code) {\r\n case Code.OK:\r\n return fail('Treated status OK as error');\r\n case Code.CANCELLED:\r\n case Code.UNKNOWN:\r\n case Code.DEADLINE_EXCEEDED:\r\n case Code.RESOURCE_EXHAUSTED:\r\n case Code.INTERNAL:\r\n case Code.UNAVAILABLE:\r\n // Unauthenticated means something went wrong with our token and we need\r\n // to retry with new credentials which will happen automatically.\r\n case Code.UNAUTHENTICATED:\r\n return false;\r\n case Code.INVALID_ARGUMENT:\r\n case Code.NOT_FOUND:\r\n case Code.ALREADY_EXISTS:\r\n case Code.PERMISSION_DENIED:\r\n case Code.FAILED_PRECONDITION:\r\n // Aborted might be retried in some scenarios, but that is dependant on\r\n // the context and should handled individually by the calling code.\r\n // See https://cloud.google.com/apis/design/errors.\r\n case Code.ABORTED:\r\n case Code.OUT_OF_RANGE:\r\n case Code.UNIMPLEMENTED:\r\n case Code.DATA_LOSS:\r\n return true;\r\n default:\r\n return fail('Unknown status code: ' + code);\r\n }\r\n}\r\n/**\r\n * Determines whether an error code represents a permanent error when received\r\n * in response to a write operation.\r\n *\r\n * Write operations must be handled specially because as of b/119437764, ABORTED\r\n * errors on the write stream should be retried too (even though ABORTED errors\r\n * are not generally retryable).\r\n *\r\n * Note that during the initial handshake on the write stream an ABORTED error\r\n * signals that we should discard our stream token (i.e. it is permanent). This\r\n * means a handshake error should be classified with isPermanentError, above.\r\n */\r\nfunction isPermanentWriteError(code) {\r\n return isPermanentError(code) && code !== Code.ABORTED;\r\n}\r\n/**\r\n * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.\r\n *\r\n * @returns The Code equivalent to the given status string or undefined if\r\n * there is no match.\r\n */\r\nfunction mapCodeFromRpcStatus(status) {\r\n // tslint:disable-next-line:no-any lookup by string\r\n var code = RpcCode[status];\r\n if (code === undefined) {\r\n return undefined;\r\n }\r\n return mapCodeFromRpcCode(code);\r\n}\r\n/**\r\n * Maps an error Code from GRPC status code number, like 0, 1, or 14. These\r\n * are not the same as HTTP status codes.\r\n *\r\n * @returns The Code equivalent to the given GRPC status code. Fails if there\r\n * is no match.\r\n */\r\nfunction mapCodeFromRpcCode(code) {\r\n if (code === undefined) {\r\n // This shouldn't normally happen, but in certain error cases (like trying\r\n // to send invalid proto messages) we may get an error with no GRPC code.\r\n error('GRPC error has no .code');\r\n return Code.UNKNOWN;\r\n }\r\n switch (code) {\r\n case RpcCode.OK:\r\n return Code.OK;\r\n case RpcCode.CANCELLED:\r\n return Code.CANCELLED;\r\n case RpcCode.UNKNOWN:\r\n return Code.UNKNOWN;\r\n case RpcCode.DEADLINE_EXCEEDED:\r\n return Code.DEADLINE_EXCEEDED;\r\n case RpcCode.RESOURCE_EXHAUSTED:\r\n return Code.RESOURCE_EXHAUSTED;\r\n case RpcCode.INTERNAL:\r\n return Code.INTERNAL;\r\n case RpcCode.UNAVAILABLE:\r\n return Code.UNAVAILABLE;\r\n case RpcCode.UNAUTHENTICATED:\r\n return Code.UNAUTHENTICATED;\r\n case RpcCode.INVALID_ARGUMENT:\r\n return Code.INVALID_ARGUMENT;\r\n case RpcCode.NOT_FOUND:\r\n return Code.NOT_FOUND;\r\n case RpcCode.ALREADY_EXISTS:\r\n return Code.ALREADY_EXISTS;\r\n case RpcCode.PERMISSION_DENIED:\r\n return Code.PERMISSION_DENIED;\r\n case RpcCode.FAILED_PRECONDITION:\r\n return Code.FAILED_PRECONDITION;\r\n case RpcCode.ABORTED:\r\n return Code.ABORTED;\r\n case RpcCode.OUT_OF_RANGE:\r\n return Code.OUT_OF_RANGE;\r\n case RpcCode.UNIMPLEMENTED:\r\n return Code.UNIMPLEMENTED;\r\n case RpcCode.DATA_LOSS:\r\n return Code.DATA_LOSS;\r\n default:\r\n return fail('Unknown status code: ' + code);\r\n }\r\n}\r\n/**\r\n * Maps an RPC code from a Code. This is the reverse operation from\r\n * mapCodeFromRpcCode and should really only be used in tests.\r\n */\r\nfunction mapRpcCodeFromCode(code) {\r\n if (code === undefined) {\r\n return RpcCode.OK;\r\n }\r\n switch (code) {\r\n case Code.OK:\r\n return RpcCode.OK;\r\n case Code.CANCELLED:\r\n return RpcCode.CANCELLED;\r\n case Code.UNKNOWN:\r\n return RpcCode.UNKNOWN;\r\n case Code.DEADLINE_EXCEEDED:\r\n return RpcCode.DEADLINE_EXCEEDED;\r\n case Code.RESOURCE_EXHAUSTED:\r\n return RpcCode.RESOURCE_EXHAUSTED;\r\n case Code.INTERNAL:\r\n return RpcCode.INTERNAL;\r\n case Code.UNAVAILABLE:\r\n return RpcCode.UNAVAILABLE;\r\n case Code.UNAUTHENTICATED:\r\n return RpcCode.UNAUTHENTICATED;\r\n case Code.INVALID_ARGUMENT:\r\n return RpcCode.INVALID_ARGUMENT;\r\n case Code.NOT_FOUND:\r\n return RpcCode.NOT_FOUND;\r\n case Code.ALREADY_EXISTS:\r\n return RpcCode.ALREADY_EXISTS;\r\n case Code.PERMISSION_DENIED:\r\n return RpcCode.PERMISSION_DENIED;\r\n case Code.FAILED_PRECONDITION:\r\n return RpcCode.FAILED_PRECONDITION;\r\n case Code.ABORTED:\r\n return RpcCode.ABORTED;\r\n case Code.OUT_OF_RANGE:\r\n return RpcCode.OUT_OF_RANGE;\r\n case Code.UNIMPLEMENTED:\r\n return RpcCode.UNIMPLEMENTED;\r\n case Code.DATA_LOSS:\r\n return RpcCode.DATA_LOSS;\r\n default:\r\n return fail('Unknown status code: ' + code);\r\n }\r\n}\r\n/**\r\n * Converts an HTTP Status Code to the equivalent error code.\r\n *\r\n * @param status An HTTP Status Code, like 200, 404, 503, etc.\r\n * @returns The equivalent Code. Unknown status codes are mapped to\r\n * Code.UNKNOWN.\r\n */\r\nfunction mapCodeFromHttpStatus(status) {\r\n // The canonical error codes for Google APIs [1] specify mapping onto HTTP\r\n // status codes but the mapping is not bijective. In each case of ambiguity\r\n // this function chooses a primary error.\r\n //\r\n // [1]\r\n // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\r\n switch (status) {\r\n case 200: // OK\r\n return Code.OK;\r\n case 400: // Bad Request\r\n return Code.INVALID_ARGUMENT;\r\n // Other possibilities based on the forward mapping\r\n // return Code.FAILED_PRECONDITION;\r\n // return Code.OUT_OF_RANGE;\r\n case 401: // Unauthorized\r\n return Code.UNAUTHENTICATED;\r\n case 403: // Forbidden\r\n return Code.PERMISSION_DENIED;\r\n case 404: // Not Found\r\n return Code.NOT_FOUND;\r\n case 409: // Conflict\r\n return Code.ABORTED;\r\n // Other possibilities:\r\n // return Code.ALREADY_EXISTS;\r\n case 416: // Range Not Satisfiable\r\n return Code.OUT_OF_RANGE;\r\n case 429: // Too Many Requests\r\n return Code.RESOURCE_EXHAUSTED;\r\n case 499: // Client Closed Request\r\n return Code.CANCELLED;\r\n case 500: // Internal Server Error\r\n return Code.UNKNOWN;\r\n // Other possibilities:\r\n // return Code.INTERNAL;\r\n // return Code.DATA_LOSS;\r\n case 501: // Unimplemented\r\n return Code.UNIMPLEMENTED;\r\n case 503: // Service Unavailable\r\n return Code.UNAVAILABLE;\r\n case 504: // Gateway Timeout\r\n return Code.DEADLINE_EXCEEDED;\r\n default:\r\n if (status >= 200 && status < 300)\r\n return Code.OK;\r\n if (status >= 400 && status < 500)\r\n return Code.FAILED_PRECONDITION;\r\n if (status >= 500 && status < 600)\r\n return Code.INTERNAL;\r\n return Code.UNKNOWN;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar EMPTY_MAYBE_DOCUMENT_MAP = new SortedMap(DocumentKey.comparator);\r\nfunction maybeDocumentMap() {\r\n return EMPTY_MAYBE_DOCUMENT_MAP;\r\n}\r\nfunction nullableMaybeDocumentMap() {\r\n return maybeDocumentMap();\r\n}\r\nvar EMPTY_DOCUMENT_MAP = new SortedMap(DocumentKey.comparator);\r\nfunction documentMap() {\r\n return EMPTY_DOCUMENT_MAP;\r\n}\r\nvar EMPTY_DOCUMENT_VERSION_MAP = new SortedMap(DocumentKey.comparator);\r\nfunction documentVersionMap() {\r\n return EMPTY_DOCUMENT_VERSION_MAP;\r\n}\r\nvar EMPTY_DOCUMENT_KEY_SET = new SortedSet(DocumentKey.comparator);\r\nfunction documentKeySet() {\r\n var keys = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n keys[_i] = arguments[_i];\r\n }\r\n var set = EMPTY_DOCUMENT_KEY_SET;\r\n for (var _a = 0, keys_1 = keys; _a < keys_1.length; _a++) {\r\n var key = keys_1[_a];\r\n set = set.add(key);\r\n }\r\n return set;\r\n}\r\nvar EMPTY_TARGET_ID_SET = new SortedSet(primitiveComparator);\r\nfunction targetIdSet() {\r\n return EMPTY_TARGET_ID_SET;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * DocumentSet is an immutable (copy-on-write) collection that holds documents\r\n * in order specified by the provided comparator. We always add a document key\r\n * comparator on top of what is provided to guarantee document equality based on\r\n * the key.\r\n */\r\nvar DocumentSet = /** @class */ (function () {\r\n /** The default ordering is by key if the comparator is omitted */\r\n function DocumentSet(comp) {\r\n // We are adding document key comparator to the end as it's the only\r\n // guaranteed unique property of a document.\r\n if (comp) {\r\n this.comparator = function (d1, d2) {\r\n return comp(d1, d2) || DocumentKey.comparator(d1.key, d2.key);\r\n };\r\n }\r\n else {\r\n this.comparator = function (d1, d2) {\r\n return DocumentKey.comparator(d1.key, d2.key);\r\n };\r\n }\r\n this.keyedMap = documentMap();\r\n this.sortedSet = new SortedMap(this.comparator);\r\n }\r\n /**\r\n * Returns an empty copy of the existing DocumentSet, using the same\r\n * comparator.\r\n */\r\n DocumentSet.emptySet = function (oldSet) {\r\n return new DocumentSet(oldSet.comparator);\r\n };\r\n DocumentSet.prototype.has = function (key) {\r\n return this.keyedMap.get(key) != null;\r\n };\r\n DocumentSet.prototype.get = function (key) {\r\n return this.keyedMap.get(key);\r\n };\r\n DocumentSet.prototype.first = function () {\r\n return this.sortedSet.minKey();\r\n };\r\n DocumentSet.prototype.last = function () {\r\n return this.sortedSet.maxKey();\r\n };\r\n DocumentSet.prototype.isEmpty = function () {\r\n return this.sortedSet.isEmpty();\r\n };\r\n /**\r\n * Returns the index of the provided key in the document set, or -1 if the\r\n * document key is not present in the set;\r\n */\r\n DocumentSet.prototype.indexOf = function (key) {\r\n var doc = this.keyedMap.get(key);\r\n return doc ? this.sortedSet.indexOf(doc) : -1;\r\n };\r\n Object.defineProperty(DocumentSet.prototype, \"size\", {\r\n get: function () {\r\n return this.sortedSet.size;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n /** Iterates documents in order defined by \"comparator\" */\r\n DocumentSet.prototype.forEach = function (cb) {\r\n this.sortedSet.inorderTraversal(function (k, v) {\r\n cb(k);\r\n return false;\r\n });\r\n };\r\n /** Inserts or updates a document with the same key */\r\n DocumentSet.prototype.add = function (doc) {\r\n // First remove the element if we have it.\r\n var set = this.delete(doc.key);\r\n return set.copy(set.keyedMap.insert(doc.key, doc), set.sortedSet.insert(doc, null));\r\n };\r\n /** Deletes a document with a given key */\r\n DocumentSet.prototype.delete = function (key) {\r\n var doc = this.get(key);\r\n if (!doc) {\r\n return this;\r\n }\r\n return this.copy(this.keyedMap.remove(key), this.sortedSet.remove(doc));\r\n };\r\n DocumentSet.prototype.isEqual = function (other) {\r\n if (!(other instanceof DocumentSet))\r\n return false;\r\n if (this.size !== other.size)\r\n return false;\r\n var thisIt = this.sortedSet.getIterator();\r\n var otherIt = other.sortedSet.getIterator();\r\n while (thisIt.hasNext()) {\r\n var thisDoc = thisIt.getNext().key;\r\n var otherDoc = otherIt.getNext().key;\r\n if (!thisDoc.isEqual(otherDoc))\r\n return false;\r\n }\r\n return true;\r\n };\r\n DocumentSet.prototype.toString = function () {\r\n var docStrings = [];\r\n this.forEach(function (doc) {\r\n docStrings.push(doc.toString());\r\n });\r\n if (docStrings.length === 0) {\r\n return 'DocumentSet ()';\r\n }\r\n else {\r\n return 'DocumentSet (\\n ' + docStrings.join(' \\n') + '\\n)';\r\n }\r\n };\r\n DocumentSet.prototype.copy = function (keyedMap, sortedSet) {\r\n var newSet = new DocumentSet();\r\n newSet.comparator = this.comparator;\r\n newSet.keyedMap = keyedMap;\r\n newSet.sortedSet = sortedSet;\r\n return newSet;\r\n };\r\n return DocumentSet;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar ChangeType;\r\n(function (ChangeType) {\r\n ChangeType[ChangeType[\"Added\"] = 0] = \"Added\";\r\n ChangeType[ChangeType[\"Removed\"] = 1] = \"Removed\";\r\n ChangeType[ChangeType[\"Modified\"] = 2] = \"Modified\";\r\n ChangeType[ChangeType[\"Metadata\"] = 3] = \"Metadata\";\r\n})(ChangeType || (ChangeType = {}));\r\nvar SyncState;\r\n(function (SyncState) {\r\n SyncState[SyncState[\"Local\"] = 0] = \"Local\";\r\n SyncState[SyncState[\"Synced\"] = 1] = \"Synced\";\r\n})(SyncState || (SyncState = {}));\r\n/**\r\n * DocumentChangeSet keeps track of a set of changes to docs in a query, merging\r\n * duplicate events for the same doc.\r\n */\r\nvar DocumentChangeSet = /** @class */ (function () {\r\n function DocumentChangeSet() {\r\n this.changeMap = new SortedMap(DocumentKey.comparator);\r\n }\r\n DocumentChangeSet.prototype.track = function (change) {\r\n var key = change.doc.key;\r\n var oldChange = this.changeMap.get(key);\r\n if (!oldChange) {\r\n this.changeMap = this.changeMap.insert(key, change);\r\n return;\r\n }\r\n // Merge the new change with the existing change.\r\n if (change.type !== ChangeType.Added &&\r\n oldChange.type === ChangeType.Metadata) {\r\n this.changeMap = this.changeMap.insert(key, change);\r\n }\r\n else if (change.type === ChangeType.Metadata &&\r\n oldChange.type !== ChangeType.Removed) {\r\n this.changeMap = this.changeMap.insert(key, {\r\n type: oldChange.type,\r\n doc: change.doc\r\n });\r\n }\r\n else if (change.type === ChangeType.Modified &&\r\n oldChange.type === ChangeType.Modified) {\r\n this.changeMap = this.changeMap.insert(key, {\r\n type: ChangeType.Modified,\r\n doc: change.doc\r\n });\r\n }\r\n else if (change.type === ChangeType.Modified &&\r\n oldChange.type === ChangeType.Added) {\r\n this.changeMap = this.changeMap.insert(key, {\r\n type: ChangeType.Added,\r\n doc: change.doc\r\n });\r\n }\r\n else if (change.type === ChangeType.Removed &&\r\n oldChange.type === ChangeType.Added) {\r\n this.changeMap = this.changeMap.remove(key);\r\n }\r\n else if (change.type === ChangeType.Removed &&\r\n oldChange.type === ChangeType.Modified) {\r\n this.changeMap = this.changeMap.insert(key, {\r\n type: ChangeType.Removed,\r\n doc: oldChange.doc\r\n });\r\n }\r\n else if (change.type === ChangeType.Added &&\r\n oldChange.type === ChangeType.Removed) {\r\n this.changeMap = this.changeMap.insert(key, {\r\n type: ChangeType.Modified,\r\n doc: change.doc\r\n });\r\n }\r\n else {\r\n // This includes these cases, which don't make sense:\r\n // Added->Added\r\n // Removed->Removed\r\n // Modified->Added\r\n // Removed->Modified\r\n // Metadata->Added\r\n // Removed->Metadata\r\n fail('unsupported combination of changes: ' +\r\n JSON.stringify(change) +\r\n ' after ' +\r\n JSON.stringify(oldChange));\r\n }\r\n };\r\n DocumentChangeSet.prototype.getChanges = function () {\r\n var changes = [];\r\n this.changeMap.inorderTraversal(function (key, change) {\r\n changes.push(change);\r\n });\r\n return changes;\r\n };\r\n return DocumentChangeSet;\r\n}());\r\nvar ViewSnapshot = /** @class */ (function () {\r\n function ViewSnapshot(query, docs, oldDocs, docChanges, mutatedKeys, fromCache, syncStateChanged, excludesMetadataChanges) {\r\n this.query = query;\r\n this.docs = docs;\r\n this.oldDocs = oldDocs;\r\n this.docChanges = docChanges;\r\n this.mutatedKeys = mutatedKeys;\r\n this.fromCache = fromCache;\r\n this.syncStateChanged = syncStateChanged;\r\n this.excludesMetadataChanges = excludesMetadataChanges;\r\n }\r\n /** Returns a view snapshot as if all documents in the snapshot were added. */\r\n ViewSnapshot.fromInitialDocuments = function (query, documents, mutatedKeys, fromCache) {\r\n var changes = [];\r\n documents.forEach(function (doc) {\r\n changes.push({ type: ChangeType.Added, doc: doc });\r\n });\r\n return new ViewSnapshot(query, documents, DocumentSet.emptySet(documents), changes, mutatedKeys, fromCache, true, false);\r\n };\r\n Object.defineProperty(ViewSnapshot.prototype, \"hasPendingWrites\", {\r\n get: function () {\r\n return !this.mutatedKeys.isEmpty();\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n ViewSnapshot.prototype.isEqual = function (other) {\r\n if (this.fromCache !== other.fromCache ||\r\n this.syncStateChanged !== other.syncStateChanged ||\r\n !this.mutatedKeys.isEqual(other.mutatedKeys) ||\r\n !this.query.isEqual(other.query) ||\r\n !this.docs.isEqual(other.docs) ||\r\n !this.oldDocs.isEqual(other.oldDocs)) {\r\n return false;\r\n }\r\n var changes = this.docChanges;\r\n var otherChanges = other.docChanges;\r\n if (changes.length !== otherChanges.length) {\r\n return false;\r\n }\r\n for (var i = 0; i < changes.length; i++) {\r\n if (changes[i].type !== otherChanges[i].type ||\r\n !changes[i].doc.isEqual(otherChanges[i].doc)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n };\r\n return ViewSnapshot;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An event from the RemoteStore. It is split into targetChanges (changes to the\r\n * state or the set of documents in our watched targets) and documentUpdates\r\n * (changes to the actual documents).\r\n */\r\nvar RemoteEvent = /** @class */ (function () {\r\n function RemoteEvent(\r\n /**\r\n * The snapshot version this event brings us up to, or MIN if not set.\r\n */\r\n snapshotVersion, \r\n /**\r\n * A map from target to changes to the target. See TargetChange.\r\n */\r\n targetChanges, \r\n /**\r\n * A set of targets that is known to be inconsistent. Listens for these\r\n * targets should be re-established without resume tokens.\r\n */\r\n targetMismatches, \r\n /**\r\n * A set of which documents have changed or been deleted, along with the\r\n * doc's new values (if not deleted).\r\n */\r\n documentUpdates, \r\n /**\r\n * A set of which document updates are due only to limbo resolution targets.\r\n */\r\n resolvedLimboDocuments) {\r\n this.snapshotVersion = snapshotVersion;\r\n this.targetChanges = targetChanges;\r\n this.targetMismatches = targetMismatches;\r\n this.documentUpdates = documentUpdates;\r\n this.resolvedLimboDocuments = resolvedLimboDocuments;\r\n }\r\n /**\r\n * HACK: Views require RemoteEvents in order to determine whether the view is\r\n * CURRENT, but secondary tabs don't receive remote events. So this method is\r\n * used to create a synthesized RemoteEvent that can be used to apply a\r\n * CURRENT status change to a View, for queries executed in a different tab.\r\n */\r\n // PORTING NOTE: Multi-tab only\r\n RemoteEvent.createSynthesizedRemoteEventForCurrentChange = function (targetId, current) {\r\n var _a;\r\n var targetChanges = (_a = {},\r\n _a[targetId] = TargetChange.createSynthesizedTargetChangeForCurrentChange(targetId, current),\r\n _a);\r\n return new RemoteEvent(SnapshotVersion.MIN, targetChanges, targetIdSet(), maybeDocumentMap(), documentKeySet());\r\n };\r\n return RemoteEvent;\r\n}());\r\n/**\r\n * A TargetChange specifies the set of changes for a specific target as part of\r\n * a RemoteEvent. These changes track which documents are added, modified or\r\n * removed, as well as the target's resume token and whether the target is\r\n * marked CURRENT.\r\n * The actual changes *to* documents are not part of the TargetChange since\r\n * documents may be part of multiple targets.\r\n */\r\nvar TargetChange = /** @class */ (function () {\r\n function TargetChange(\r\n /**\r\n * An opaque, server-assigned token that allows watching a query to be resumed\r\n * after disconnecting without retransmitting all the data that matches the\r\n * query. The resume token essentially identifies a point in time from which\r\n * the server should resume sending results.\r\n */\r\n resumeToken, \r\n /**\r\n * The \"current\" (synced) status of this target. Note that \"current\"\r\n * has special meaning in the RPC protocol that implies that a target is\r\n * both up-to-date and consistent with the rest of the watch stream.\r\n */\r\n current, \r\n /**\r\n * The set of documents that were newly assigned to this target as part of\r\n * this remote event.\r\n */\r\n addedDocuments, \r\n /**\r\n * The set of documents that were already assigned to this target but received\r\n * an update during this remote event.\r\n */\r\n modifiedDocuments, \r\n /**\r\n * The set of documents that were removed from this target as part of this\r\n * remote event.\r\n */\r\n removedDocuments) {\r\n this.resumeToken = resumeToken;\r\n this.current = current;\r\n this.addedDocuments = addedDocuments;\r\n this.modifiedDocuments = modifiedDocuments;\r\n this.removedDocuments = removedDocuments;\r\n }\r\n /**\r\n * HACK: Views require TargetChanges in order to determine whether the view is\r\n * CURRENT, but secondary tabs don't receive remote events. So this method is\r\n * used to create a synthesized TargetChanges that can be used to apply a\r\n * CURRENT status change to a View, for queries executed in a different tab.\r\n */\r\n // PORTING NOTE: Multi-tab only\r\n TargetChange.createSynthesizedTargetChangeForCurrentChange = function (targetId, current) {\r\n return new TargetChange(emptyByteString(), current, documentKeySet(), documentKeySet(), documentKeySet());\r\n };\r\n return TargetChange;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Represents a changed document and a list of target ids to which this change\r\n * applies.\r\n *\r\n * If document has been deleted NoDocument will be provided.\r\n */\r\nvar DocumentWatchChange = /** @class */ (function () {\r\n function DocumentWatchChange(\r\n /** The new document applies to all of these targets. */\r\n updatedTargetIds, \r\n /** The new document is removed from all of these targets. */\r\n removedTargetIds, \r\n /** The key of the document for this change. */\r\n key, \r\n /**\r\n * The new document or NoDocument if it was deleted. Is null if the\r\n * document went out of view without the server sending a new document.\r\n */\r\n newDoc) {\r\n this.updatedTargetIds = updatedTargetIds;\r\n this.removedTargetIds = removedTargetIds;\r\n this.key = key;\r\n this.newDoc = newDoc;\r\n }\r\n return DocumentWatchChange;\r\n}());\r\nvar ExistenceFilterChange = /** @class */ (function () {\r\n function ExistenceFilterChange(targetId, existenceFilter) {\r\n this.targetId = targetId;\r\n this.existenceFilter = existenceFilter;\r\n }\r\n return ExistenceFilterChange;\r\n}());\r\nvar WatchTargetChangeState;\r\n(function (WatchTargetChangeState) {\r\n WatchTargetChangeState[WatchTargetChangeState[\"NoChange\"] = 0] = \"NoChange\";\r\n WatchTargetChangeState[WatchTargetChangeState[\"Added\"] = 1] = \"Added\";\r\n WatchTargetChangeState[WatchTargetChangeState[\"Removed\"] = 2] = \"Removed\";\r\n WatchTargetChangeState[WatchTargetChangeState[\"Current\"] = 3] = \"Current\";\r\n WatchTargetChangeState[WatchTargetChangeState[\"Reset\"] = 4] = \"Reset\";\r\n})(WatchTargetChangeState || (WatchTargetChangeState = {}));\r\nvar WatchTargetChange = /** @class */ (function () {\r\n function WatchTargetChange(\r\n /** What kind of change occurred to the watch target. */\r\n state, \r\n /** The target IDs that were added/removed/set. */\r\n targetIds, \r\n /**\r\n * An opaque, server-assigned token that allows watching a query to be\r\n * resumed after disconnecting without retransmitting all the data that\r\n * matches the query. The resume token essentially identifies a point in\r\n * time from which the server should resume sending results.\r\n */\r\n resumeToken, \r\n /** An RPC error indicating why the watch failed. */\r\n cause) {\r\n if (resumeToken === void 0) { resumeToken = emptyByteString(); }\r\n if (cause === void 0) { cause = null; }\r\n this.state = state;\r\n this.targetIds = targetIds;\r\n this.resumeToken = resumeToken;\r\n this.cause = cause;\r\n }\r\n return WatchTargetChange;\r\n}());\r\n/** Tracks the internal state of a Watch target. */\r\nvar TargetState = /** @class */ (function () {\r\n function TargetState() {\r\n /**\r\n * The number of pending responses (adds or removes) that we are waiting on.\r\n * We only consider targets active that have no pending responses.\r\n */\r\n this.pendingResponses = 0;\r\n /**\r\n * Keeps track of the document changes since the last raised snapshot.\r\n *\r\n * These changes are continuously updated as we receive document updates and\r\n * always reflect the current set of changes against the last issued snapshot.\r\n */\r\n this.documentChanges = snapshotChangesMap();\r\n /** See public getters for explanations of these fields. */\r\n this._resumeToken = emptyByteString();\r\n this._current = false;\r\n /**\r\n * Whether this target state should be included in the next snapshot. We\r\n * initialize to true so that newly-added targets are included in the next\r\n * RemoteEvent.\r\n */\r\n this._hasPendingChanges = true;\r\n }\r\n Object.defineProperty(TargetState.prototype, \"current\", {\r\n /**\r\n * Whether this target has been marked 'current'.\r\n *\r\n * 'Current' has special meaning in the RPC protocol: It implies that the\r\n * Watch backend has sent us all changes up to the point at which the target\r\n * was added and that the target is consistent with the rest of the watch\r\n * stream.\r\n */\r\n get: function () {\r\n return this._current;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(TargetState.prototype, \"resumeToken\", {\r\n /** The last resume token sent to us for this target. */\r\n get: function () {\r\n return this._resumeToken;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(TargetState.prototype, \"isPending\", {\r\n /** Whether this target has pending target adds or target removes. */\r\n get: function () {\r\n return this.pendingResponses !== 0;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(TargetState.prototype, \"hasPendingChanges\", {\r\n /** Whether we have modified any state that should trigger a snapshot. */\r\n get: function () {\r\n return this._hasPendingChanges;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n /**\r\n * Applies the resume token to the TargetChange, but only when it has a new\r\n * value. Empty resumeTokens are discarded.\r\n */\r\n TargetState.prototype.updateResumeToken = function (resumeToken) {\r\n if (resumeToken.length > 0) {\r\n this._hasPendingChanges = true;\r\n this._resumeToken = resumeToken;\r\n }\r\n };\r\n /**\r\n * Creates a target change from the current set of changes.\r\n *\r\n * To reset the document changes after raising this snapshot, call\r\n * `clearPendingChanges()`.\r\n */\r\n TargetState.prototype.toTargetChange = function () {\r\n var addedDocuments = documentKeySet();\r\n var modifiedDocuments = documentKeySet();\r\n var removedDocuments = documentKeySet();\r\n this.documentChanges.forEach(function (key, changeType) {\r\n switch (changeType) {\r\n case ChangeType.Added:\r\n addedDocuments = addedDocuments.add(key);\r\n break;\r\n case ChangeType.Modified:\r\n modifiedDocuments = modifiedDocuments.add(key);\r\n break;\r\n case ChangeType.Removed:\r\n removedDocuments = removedDocuments.add(key);\r\n break;\r\n default:\r\n fail('Encountered invalid change type: ' + changeType);\r\n }\r\n });\r\n return new TargetChange(this._resumeToken, this._current, addedDocuments, modifiedDocuments, removedDocuments);\r\n };\r\n /**\r\n * Resets the document changes and sets `hasPendingChanges` to false.\r\n */\r\n TargetState.prototype.clearPendingChanges = function () {\r\n this._hasPendingChanges = false;\r\n this.documentChanges = snapshotChangesMap();\r\n };\r\n TargetState.prototype.addDocumentChange = function (key, changeType) {\r\n this._hasPendingChanges = true;\r\n this.documentChanges = this.documentChanges.insert(key, changeType);\r\n };\r\n TargetState.prototype.removeDocumentChange = function (key) {\r\n this._hasPendingChanges = true;\r\n this.documentChanges = this.documentChanges.remove(key);\r\n };\r\n TargetState.prototype.recordPendingTargetRequest = function () {\r\n this.pendingResponses += 1;\r\n };\r\n TargetState.prototype.recordTargetResponse = function () {\r\n this.pendingResponses -= 1;\r\n };\r\n TargetState.prototype.markCurrent = function () {\r\n this._hasPendingChanges = true;\r\n this._current = true;\r\n };\r\n return TargetState;\r\n}());\r\n/**\r\n * A helper class to accumulate watch changes into a RemoteEvent.\r\n */\r\nvar WatchChangeAggregator = /** @class */ (function () {\r\n function WatchChangeAggregator(metadataProvider) {\r\n this.metadataProvider = metadataProvider;\r\n /** The internal state of all tracked targets. */\r\n this.targetStates = {};\r\n /** Keeps track of the documents to update since the last raised snapshot. */\r\n this.pendingDocumentUpdates = maybeDocumentMap();\r\n /** A mapping of document keys to their set of target IDs. */\r\n this.pendingDocumentTargetMapping = documentTargetMap();\r\n /**\r\n * A list of targets with existence filter mismatches. These targets are\r\n * known to be inconsistent and their listens needs to be re-established by\r\n * RemoteStore.\r\n */\r\n this.pendingTargetResets = new SortedSet(primitiveComparator);\r\n }\r\n /**\r\n * Processes and adds the DocumentWatchChange to the current set of changes.\r\n */\r\n WatchChangeAggregator.prototype.handleDocumentChange = function (docChange) {\r\n for (var _i = 0, _a = docChange.updatedTargetIds; _i < _a.length; _i++) {\r\n var targetId = _a[_i];\r\n if (docChange.newDoc instanceof Document) {\r\n this.addDocumentToTarget(targetId, docChange.newDoc);\r\n }\r\n else if (docChange.newDoc instanceof NoDocument) {\r\n this.removeDocumentFromTarget(targetId, docChange.key, docChange.newDoc);\r\n }\r\n }\r\n for (var _b = 0, _c = docChange.removedTargetIds; _b < _c.length; _b++) {\r\n var targetId = _c[_b];\r\n this.removeDocumentFromTarget(targetId, docChange.key, docChange.newDoc);\r\n }\r\n };\r\n /** Processes and adds the WatchTargetChange to the current set of changes. */\r\n WatchChangeAggregator.prototype.handleTargetChange = function (targetChange) {\r\n var _this = this;\r\n this.forEachTarget(targetChange, function (targetId) {\r\n var targetState = _this.ensureTargetState(targetId);\r\n switch (targetChange.state) {\r\n case WatchTargetChangeState.NoChange:\r\n if (_this.isActiveTarget(targetId)) {\r\n targetState.updateResumeToken(targetChange.resumeToken);\r\n }\r\n break;\r\n case WatchTargetChangeState.Added:\r\n // We need to decrement the number of pending acks needed from watch\r\n // for this targetId.\r\n targetState.recordTargetResponse();\r\n if (!targetState.isPending) {\r\n // We have a freshly added target, so we need to reset any state\r\n // that we had previously. This can happen e.g. when remove and add\r\n // back a target for existence filter mismatches.\r\n targetState.clearPendingChanges();\r\n }\r\n targetState.updateResumeToken(targetChange.resumeToken);\r\n break;\r\n case WatchTargetChangeState.Removed:\r\n // We need to keep track of removed targets to we can post-filter and\r\n // remove any target changes.\r\n // We need to decrement the number of pending acks needed from watch\r\n // for this targetId.\r\n targetState.recordTargetResponse();\r\n if (!targetState.isPending) {\r\n _this.removeTarget(targetId);\r\n }\r\n assert(!targetChange.cause, 'WatchChangeAggregator does not handle errored targets');\r\n break;\r\n case WatchTargetChangeState.Current:\r\n if (_this.isActiveTarget(targetId)) {\r\n targetState.markCurrent();\r\n targetState.updateResumeToken(targetChange.resumeToken);\r\n }\r\n break;\r\n case WatchTargetChangeState.Reset:\r\n if (_this.isActiveTarget(targetId)) {\r\n // Reset the target and synthesizes removes for all existing\r\n // documents. The backend will re-add any documents that still\r\n // match the target before it sends the next global snapshot.\r\n _this.resetTarget(targetId);\r\n targetState.updateResumeToken(targetChange.resumeToken);\r\n }\r\n break;\r\n default:\r\n fail('Unknown target watch change state: ' + targetChange.state);\r\n }\r\n });\r\n };\r\n /**\r\n * Iterates over all targetIds that the watch change applies to: either the\r\n * targetIds explicitly listed in the change or the targetIds of all currently\r\n * active targets.\r\n */\r\n WatchChangeAggregator.prototype.forEachTarget = function (targetChange, fn) {\r\n if (targetChange.targetIds.length > 0) {\r\n targetChange.targetIds.forEach(fn);\r\n }\r\n else {\r\n forEachNumber(this.targetStates, fn);\r\n }\r\n };\r\n /**\r\n * Handles existence filters and synthesizes deletes for filter mismatches.\r\n * Targets that are invalidated by filter mismatches are added to\r\n * `pendingTargetResets`.\r\n */\r\n WatchChangeAggregator.prototype.handleExistenceFilter = function (watchChange) {\r\n var targetId = watchChange.targetId;\r\n var expectedCount = watchChange.existenceFilter.count;\r\n var queryData = this.queryDataForActiveTarget(targetId);\r\n if (queryData) {\r\n var query = queryData.query;\r\n if (query.isDocumentQuery()) {\r\n if (expectedCount === 0) {\r\n // The existence filter told us the document does not exist. We deduce\r\n // that this document does not exist and apply a deleted document to\r\n // our updates. Without applying this deleted document there might be\r\n // another query that will raise this document as part of a snapshot\r\n // until it is resolved, essentially exposing inconsistency between\r\n // queries.\r\n var key = new DocumentKey(query.path);\r\n this.removeDocumentFromTarget(targetId, key, new NoDocument(key, SnapshotVersion.forDeletedDoc()));\r\n }\r\n else {\r\n assert(expectedCount === 1, 'Single document existence filter with count: ' + expectedCount);\r\n }\r\n }\r\n else {\r\n var currentSize = this.getCurrentDocumentCountForTarget(targetId);\r\n if (currentSize !== expectedCount) {\r\n // Existence filter mismatch: We reset the mapping and raise a new\r\n // snapshot with `isFromCache:true`.\r\n this.resetTarget(targetId);\r\n this.pendingTargetResets = this.pendingTargetResets.add(targetId);\r\n }\r\n }\r\n }\r\n };\r\n /**\r\n * Converts the currently accumulated state into a remote event at the\r\n * provided snapshot version. Resets the accumulated changes before returning.\r\n */\r\n WatchChangeAggregator.prototype.createRemoteEvent = function (snapshotVersion) {\r\n var _this = this;\r\n var targetChanges = {};\r\n forEachNumber(this.targetStates, function (targetId, targetState) {\r\n var queryData = _this.queryDataForActiveTarget(targetId);\r\n if (queryData) {\r\n if (targetState.current && queryData.query.isDocumentQuery()) {\r\n // Document queries for document that don't exist can produce an empty\r\n // result set. To update our local cache, we synthesize a document\r\n // delete if we have not previously received the document. This\r\n // resolves the limbo state of the document, removing it from\r\n // limboDocumentRefs.\r\n //\r\n // TODO(dimond): Ideally we would have an explicit lookup query\r\n // instead resulting in an explicit delete message and we could\r\n // remove this special logic.\r\n var key = new DocumentKey(queryData.query.path);\r\n if (_this.pendingDocumentUpdates.get(key) === null &&\r\n !_this.targetContainsDocument(targetId, key)) {\r\n _this.removeDocumentFromTarget(targetId, key, new NoDocument(key, snapshotVersion));\r\n }\r\n }\r\n if (targetState.hasPendingChanges) {\r\n targetChanges[targetId] = targetState.toTargetChange();\r\n targetState.clearPendingChanges();\r\n }\r\n }\r\n });\r\n var resolvedLimboDocuments = documentKeySet();\r\n // We extract the set of limbo-only document updates as the GC logic\r\n // special-cases documents that do not appear in the query cache.\r\n //\r\n // TODO(gsoltis): Expand on this comment once GC is available in the JS\r\n // client.\r\n this.pendingDocumentTargetMapping.forEach(function (key, targets) {\r\n var isOnlyLimboTarget = true;\r\n targets.forEachWhile(function (targetId) {\r\n var queryData = _this.queryDataForActiveTarget(targetId);\r\n if (queryData && queryData.purpose !== QueryPurpose.LimboResolution) {\r\n isOnlyLimboTarget = false;\r\n return false;\r\n }\r\n return true;\r\n });\r\n if (isOnlyLimboTarget) {\r\n resolvedLimboDocuments = resolvedLimboDocuments.add(key);\r\n }\r\n });\r\n var remoteEvent = new RemoteEvent(snapshotVersion, targetChanges, this.pendingTargetResets, this.pendingDocumentUpdates, resolvedLimboDocuments);\r\n this.pendingDocumentUpdates = maybeDocumentMap();\r\n this.pendingDocumentTargetMapping = documentTargetMap();\r\n this.pendingTargetResets = new SortedSet(primitiveComparator);\r\n return remoteEvent;\r\n };\r\n /**\r\n * Adds the provided document to the internal list of document updates and\r\n * its document key to the given target's mapping.\r\n */\r\n // Visible for testing.\r\n WatchChangeAggregator.prototype.addDocumentToTarget = function (targetId, document) {\r\n if (!this.isActiveTarget(targetId)) {\r\n return;\r\n }\r\n var changeType = this.targetContainsDocument(targetId, document.key)\r\n ? ChangeType.Modified\r\n : ChangeType.Added;\r\n var targetState = this.ensureTargetState(targetId);\r\n targetState.addDocumentChange(document.key, changeType);\r\n this.pendingDocumentUpdates = this.pendingDocumentUpdates.insert(document.key, document);\r\n this.pendingDocumentTargetMapping = this.pendingDocumentTargetMapping.insert(document.key, this.ensureDocumentTargetMapping(document.key).add(targetId));\r\n };\r\n /**\r\n * Removes the provided document from the target mapping. If the\r\n * document no longer matches the target, but the document's state is still\r\n * known (e.g. we know that the document was deleted or we received the change\r\n * that caused the filter mismatch), the new document can be provided\r\n * to update the remote document cache.\r\n */\r\n // Visible for testing.\r\n WatchChangeAggregator.prototype.removeDocumentFromTarget = function (targetId, key, updatedDocument) {\r\n if (!this.isActiveTarget(targetId)) {\r\n return;\r\n }\r\n var targetState = this.ensureTargetState(targetId);\r\n if (this.targetContainsDocument(targetId, key)) {\r\n targetState.addDocumentChange(key, ChangeType.Removed);\r\n }\r\n else {\r\n // The document may have entered and left the target before we raised a\r\n // snapshot, so we can just ignore the change.\r\n targetState.removeDocumentChange(key);\r\n }\r\n this.pendingDocumentTargetMapping = this.pendingDocumentTargetMapping.insert(key, this.ensureDocumentTargetMapping(key).delete(targetId));\r\n if (updatedDocument) {\r\n this.pendingDocumentUpdates = this.pendingDocumentUpdates.insert(key, updatedDocument);\r\n }\r\n };\r\n WatchChangeAggregator.prototype.removeTarget = function (targetId) {\r\n delete this.targetStates[targetId];\r\n };\r\n /**\r\n * Returns the current count of documents in the target. This includes both\r\n * the number of documents that the LocalStore considers to be part of the\r\n * target as well as any accumulated changes.\r\n */\r\n WatchChangeAggregator.prototype.getCurrentDocumentCountForTarget = function (targetId) {\r\n var targetState = this.ensureTargetState(targetId);\r\n var targetChange = targetState.toTargetChange();\r\n return (this.metadataProvider.getRemoteKeysForTarget(targetId).size +\r\n targetChange.addedDocuments.size -\r\n targetChange.removedDocuments.size);\r\n };\r\n /**\r\n * Increment the number of acks needed from watch before we can consider the\r\n * server to be 'in-sync' with the client's active targets.\r\n */\r\n WatchChangeAggregator.prototype.recordPendingTargetRequest = function (targetId) {\r\n // For each request we get we need to record we need a response for it.\r\n var targetState = this.ensureTargetState(targetId);\r\n targetState.recordPendingTargetRequest();\r\n };\r\n WatchChangeAggregator.prototype.ensureTargetState = function (targetId) {\r\n if (!this.targetStates[targetId]) {\r\n this.targetStates[targetId] = new TargetState();\r\n }\r\n return this.targetStates[targetId];\r\n };\r\n WatchChangeAggregator.prototype.ensureDocumentTargetMapping = function (key) {\r\n var targetMapping = this.pendingDocumentTargetMapping.get(key);\r\n if (!targetMapping) {\r\n targetMapping = new SortedSet(primitiveComparator);\r\n this.pendingDocumentTargetMapping = this.pendingDocumentTargetMapping.insert(key, targetMapping);\r\n }\r\n return targetMapping;\r\n };\r\n /**\r\n * Verifies that the user is still interested in this target (by calling\r\n * `getQueryDataForTarget()`) and that we are not waiting for pending ADDs\r\n * from watch.\r\n */\r\n WatchChangeAggregator.prototype.isActiveTarget = function (targetId) {\r\n return this.queryDataForActiveTarget(targetId) !== null;\r\n };\r\n /**\r\n * Returns the QueryData for an active target (i.e. a target that the user\r\n * is still interested in that has no outstanding target change requests).\r\n */\r\n WatchChangeAggregator.prototype.queryDataForActiveTarget = function (targetId) {\r\n var targetState = this.targetStates[targetId];\r\n return targetState && targetState.isPending\r\n ? null\r\n : this.metadataProvider.getQueryDataForTarget(targetId);\r\n };\r\n /**\r\n * Resets the state of a Watch target to its initial state (e.g. sets\r\n * 'current' to false, clears the resume token and removes its target mapping\r\n * from all documents).\r\n */\r\n WatchChangeAggregator.prototype.resetTarget = function (targetId) {\r\n var _this = this;\r\n assert(!this.targetStates[targetId].isPending, 'Should only reset active targets');\r\n this.targetStates[targetId] = new TargetState();\r\n // Trigger removal for any documents currently mapped to this target.\r\n // These removals will be part of the initial snapshot if Watch does not\r\n // resend these documents.\r\n var existingKeys = this.metadataProvider.getRemoteKeysForTarget(targetId);\r\n existingKeys.forEach(function (key) {\r\n _this.removeDocumentFromTarget(targetId, key, /*updatedDocument=*/ null);\r\n });\r\n };\r\n /**\r\n * Returns whether the LocalStore considers the document to be part of the\r\n * specified target.\r\n */\r\n WatchChangeAggregator.prototype.targetContainsDocument = function (targetId, key) {\r\n var existingKeys = this.metadataProvider.getRemoteKeysForTarget(targetId);\r\n return existingKeys.has(key);\r\n };\r\n return WatchChangeAggregator;\r\n}());\r\nfunction documentTargetMap() {\r\n return new SortedMap(DocumentKey.comparator);\r\n}\r\nfunction snapshotChangesMap() {\r\n return new SortedMap(DocumentKey.comparator);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar DIRECTIONS = (function () {\r\n var dirs = {};\r\n dirs[Direction.ASCENDING.name] = 'ASCENDING';\r\n dirs[Direction.DESCENDING.name] = 'DESCENDING';\r\n return dirs;\r\n})();\r\nvar OPERATORS = (function () {\r\n var ops = {};\r\n ops[RelationOp.LESS_THAN.name] = 'LESS_THAN';\r\n ops[RelationOp.LESS_THAN_OR_EQUAL.name] = 'LESS_THAN_OR_EQUAL';\r\n ops[RelationOp.GREATER_THAN.name] = 'GREATER_THAN';\r\n ops[RelationOp.GREATER_THAN_OR_EQUAL.name] = 'GREATER_THAN_OR_EQUAL';\r\n ops[RelationOp.EQUAL.name] = 'EQUAL';\r\n ops[RelationOp.ARRAY_CONTAINS.name] = 'ARRAY_CONTAINS';\r\n return ops;\r\n})();\r\n// A RegExp matching ISO 8601 UTC timestamps with optional fraction.\r\nvar ISO_REG_EXP = new RegExp(/^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.(\\d+))?Z$/);\r\nfunction assertPresent(value, description) {\r\n assert(!isNullOrUndefined(value), description + ' is missing');\r\n}\r\nfunction parseInt64(value) {\r\n // TODO(bjornick): Handle int64 greater than 53 bits.\r\n if (typeof value === 'number') {\r\n return value;\r\n }\r\n else if (typeof value === 'string') {\r\n return Number(value);\r\n }\r\n else {\r\n return fail(\"can't parse \" + value);\r\n }\r\n}\r\n/**\r\n * Generates JsonObject values for the Datastore API suitable for sending to\r\n * either GRPC stub methods or via the JSON/HTTP REST API.\r\n * TODO(klimt): We can remove the databaseId argument if we keep the full\r\n * resource name in documents.\r\n */\r\nvar JsonProtoSerializer = /** @class */ (function () {\r\n function JsonProtoSerializer(databaseId, options) {\r\n this.databaseId = databaseId;\r\n this.options = options;\r\n }\r\n JsonProtoSerializer.prototype.emptyByteString = function () {\r\n if (this.options.useProto3Json) {\r\n return '';\r\n }\r\n else {\r\n return new Uint8Array(0);\r\n }\r\n };\r\n JsonProtoSerializer.prototype.unsafeCastProtoByteString = function (byteString) {\r\n // byteStrings can be either string or UInt8Array, but the typings say\r\n // it's always a string. Cast as string to avoid type check failing\r\n return byteString;\r\n };\r\n JsonProtoSerializer.prototype.fromRpcStatus = function (status) {\r\n var code = status.code === undefined\r\n ? Code.UNKNOWN\r\n : mapCodeFromRpcCode(status.code);\r\n return new FirestoreError(code, status.message || '');\r\n };\r\n /**\r\n * Returns a value for a number (or undefined) that's appropriate to put into\r\n * a google.protobuf.Int32Value proto.\r\n * DO NOT USE THIS FOR ANYTHING ELSE.\r\n * This method cheats. It's typed as returning \"number\" because that's what\r\n * our generated proto interfaces say Int32Value must be. But GRPC actually\r\n * expects a { value: } struct.\r\n */\r\n JsonProtoSerializer.prototype.toInt32Value = function (val) {\r\n if (!isNullOrUndefined(val)) {\r\n // tslint:disable-next-line:no-any We need to match generated Proto types.\r\n return { value: val };\r\n }\r\n else {\r\n return undefined;\r\n }\r\n };\r\n /**\r\n * Returns a number (or null) from a google.protobuf.Int32Value proto.\r\n * DO NOT USE THIS FOR ANYTHING ELSE.\r\n * This method cheats. It's typed as accepting \"number\" because that's what\r\n * our generated proto interfaces say Int32Value must be, but it actually\r\n * accepts { value: number } to match our serialization in toInt32Value().\r\n */\r\n JsonProtoSerializer.prototype.fromInt32Value = function (val) {\r\n var result;\r\n if (typeof val === 'object') {\r\n // tslint:disable-next-line:no-any We need to match generated Proto types.\r\n result = val.value;\r\n }\r\n else {\r\n // We accept raw numbers (without the {value: ... } wrapper) for\r\n // compatibility with legacy persisted data.\r\n result = val;\r\n }\r\n return isNullOrUndefined(result) ? null : result;\r\n };\r\n /**\r\n * Returns a value for a Date that's appropriate to put into a proto.\r\n * DO NOT USE THIS FOR ANYTHING ELSE.\r\n * This method cheats. It's typed as returning \"string\" because that's what\r\n * our generated proto interfaces say dates must be. But it's easier and safer\r\n * to actually return a Timestamp proto.\r\n */\r\n JsonProtoSerializer.prototype.toTimestamp = function (timestamp) {\r\n return {\r\n seconds: timestamp.seconds,\r\n nanos: timestamp.nanoseconds\r\n // tslint:disable-next-line:no-any\r\n };\r\n };\r\n JsonProtoSerializer.prototype.fromTimestamp = function (date) {\r\n // The json interface (for the browser) will return an iso timestamp string,\r\n // while the proto js library (for node) will return a\r\n // google.protobuf.Timestamp instance.\r\n if (typeof date === 'string') {\r\n // TODO(b/37282237): Use strings for Proto3 timestamps\r\n // assert(this.options.useProto3Json,\r\n // 'The timestamp string format requires Proto3.');\r\n return this.fromIso8601String(date);\r\n }\r\n else {\r\n assert(!!date, 'Cannot deserialize null or undefined timestamp.');\r\n // TODO(b/37282237): Use strings for Proto3 timestamps\r\n // assert(!this.options.useProto3Json,\r\n // 'The timestamp instance format requires Proto JS.');\r\n var seconds = parseInt64(date.seconds || '0');\r\n var nanos = date.nanos || 0;\r\n return new Timestamp(seconds, nanos);\r\n }\r\n };\r\n JsonProtoSerializer.prototype.fromIso8601String = function (utc) {\r\n // The date string can have higher precision (nanos) than the Date class\r\n // (millis), so we do some custom parsing here.\r\n // Parse the nanos right out of the string.\r\n var nanos = 0;\r\n var fraction = ISO_REG_EXP.exec(utc);\r\n assert(!!fraction, 'invalid timestamp: ' + utc);\r\n if (fraction[1]) {\r\n // Pad the fraction out to 9 digits (nanos).\r\n var nanoStr = fraction[1];\r\n nanoStr = (nanoStr + '000000000').substr(0, 9);\r\n nanos = Number(nanoStr);\r\n }\r\n // Parse the date to get the seconds.\r\n var date = new Date(utc);\r\n var seconds = Math.floor(date.getTime() / 1000);\r\n return new Timestamp(seconds, nanos);\r\n };\r\n /**\r\n * Returns a value for bytes that's appropriate to put in a proto.\r\n * DO NOT USE THIS FOR ANYTHING ELSE.\r\n * This method cheats. It's typed as returning \"string\" because that's what\r\n * our generated proto interfaces say bytes must be. But it should return\r\n * an Uint8Array in Node.\r\n */\r\n JsonProtoSerializer.prototype.toBytes = function (bytes) {\r\n if (this.options.useProto3Json) {\r\n return bytes.toBase64();\r\n }\r\n else {\r\n // The typings say it's a string, but it needs to be a Uint8Array in Node.\r\n return this.unsafeCastProtoByteString(bytes.toUint8Array());\r\n }\r\n };\r\n /**\r\n * Parse the blob from the protos into the internal Blob class. Note that the\r\n * typings assume all blobs are strings, but they are actually Uint8Arrays\r\n * on Node.\r\n */\r\n JsonProtoSerializer.prototype.fromBlob = function (blob) {\r\n if (typeof blob === 'string') {\r\n assert(this.options.useProto3Json, 'Expected bytes to be passed in as Uint8Array, but got a string instead.');\r\n return Blob.fromBase64String(blob);\r\n }\r\n else {\r\n assert(!this.options.useProto3Json, 'Expected bytes to be passed in as string, but got something else instead.');\r\n return Blob.fromUint8Array(blob);\r\n }\r\n };\r\n JsonProtoSerializer.prototype.toVersion = function (version) {\r\n return this.toTimestamp(version.toTimestamp());\r\n };\r\n JsonProtoSerializer.prototype.fromVersion = function (version) {\r\n assert(!!version, \"Trying to deserialize version that isn't set\");\r\n return SnapshotVersion.fromTimestamp(this.fromTimestamp(version));\r\n };\r\n JsonProtoSerializer.prototype.toResourceName = function (databaseId, path) {\r\n return this.fullyQualifiedPrefixPath(databaseId)\r\n .child('documents')\r\n .child(path)\r\n .canonicalString();\r\n };\r\n JsonProtoSerializer.prototype.fromResourceName = function (name) {\r\n var resource = ResourcePath.fromString(name);\r\n assert(this.isValidResourceName(resource), 'Tried to deserialize invalid key ' + resource.toString());\r\n return resource;\r\n };\r\n JsonProtoSerializer.prototype.toName = function (key) {\r\n return this.toResourceName(this.databaseId, key.path);\r\n };\r\n JsonProtoSerializer.prototype.fromName = function (name) {\r\n var resource = this.fromResourceName(name);\r\n assert(resource.get(1) === this.databaseId.projectId, 'Tried to deserialize key from different project: ' +\r\n resource.get(1) +\r\n ' vs ' +\r\n this.databaseId.projectId);\r\n assert((!resource.get(3) && !this.databaseId.database) ||\r\n resource.get(3) === this.databaseId.database, 'Tried to deserialize key from different database: ' +\r\n resource.get(3) +\r\n ' vs ' +\r\n this.databaseId.database);\r\n return new DocumentKey(this.extractLocalPathFromResourceName(resource));\r\n };\r\n JsonProtoSerializer.prototype.toQueryPath = function (path) {\r\n return this.toResourceName(this.databaseId, path);\r\n };\r\n JsonProtoSerializer.prototype.fromQueryPath = function (name) {\r\n var resourceName = this.fromResourceName(name);\r\n // In v1beta1 queries for collections at the root did not have a trailing\r\n // \"/documents\". In v1 all resource paths contain \"/documents\". Preserve the\r\n // ability to read the v1beta1 form for compatibility with queries persisted\r\n // in the local query cache.\r\n if (resourceName.length === 4) {\r\n return ResourcePath.EMPTY_PATH;\r\n }\r\n return this.extractLocalPathFromResourceName(resourceName);\r\n };\r\n Object.defineProperty(JsonProtoSerializer.prototype, \"encodedDatabaseId\", {\r\n get: function () {\r\n var path = new ResourcePath([\r\n 'projects',\r\n this.databaseId.projectId,\r\n 'databases',\r\n this.databaseId.database\r\n ]);\r\n return path.canonicalString();\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n JsonProtoSerializer.prototype.fullyQualifiedPrefixPath = function (databaseId) {\r\n return new ResourcePath([\r\n 'projects',\r\n databaseId.projectId,\r\n 'databases',\r\n databaseId.database\r\n ]);\r\n };\r\n JsonProtoSerializer.prototype.extractLocalPathFromResourceName = function (resourceName) {\r\n assert(resourceName.length > 4 && resourceName.get(4) === 'documents', 'tried to deserialize invalid key ' + resourceName.toString());\r\n return resourceName.popFirst(5);\r\n };\r\n JsonProtoSerializer.prototype.isValidResourceName = function (path) {\r\n // Resource names have at least 4 components (project ID, database ID)\r\n return (path.length >= 4 &&\r\n path.get(0) === 'projects' &&\r\n path.get(2) === 'databases');\r\n };\r\n JsonProtoSerializer.prototype.toValue = function (val) {\r\n if (val instanceof NullValue) {\r\n return { nullValue: 'NULL_VALUE' };\r\n }\r\n else if (val instanceof BooleanValue) {\r\n return { booleanValue: val.value() };\r\n }\r\n else if (val instanceof IntegerValue) {\r\n return { integerValue: '' + val.value() };\r\n }\r\n else if (val instanceof DoubleValue) {\r\n var doubleValue = val.value();\r\n if (this.options.useProto3Json) {\r\n // Proto 3 let's us encode NaN and Infinity as string values as\r\n // expected by the backend. This is currently not checked by our unit\r\n // tests because they rely on protobuf.js.\r\n if (isNaN(doubleValue)) {\r\n return { doubleValue: 'NaN' };\r\n }\r\n else if (doubleValue === Infinity) {\r\n return { doubleValue: 'Infinity' };\r\n }\r\n else if (doubleValue === -Infinity) {\r\n return { doubleValue: '-Infinity' };\r\n }\r\n }\r\n return { doubleValue: val.value() };\r\n }\r\n else if (val instanceof StringValue) {\r\n return { stringValue: val.value() };\r\n }\r\n else if (val instanceof ObjectValue) {\r\n return { mapValue: this.toMapValue(val) };\r\n }\r\n else if (val instanceof ArrayValue) {\r\n return { arrayValue: this.toArrayValue(val) };\r\n }\r\n else if (val instanceof TimestampValue) {\r\n return {\r\n timestampValue: this.toTimestamp(val.internalValue)\r\n };\r\n }\r\n else if (val instanceof GeoPointValue) {\r\n return {\r\n geoPointValue: {\r\n latitude: val.value().latitude,\r\n longitude: val.value().longitude\r\n }\r\n };\r\n }\r\n else if (val instanceof BlobValue) {\r\n return {\r\n bytesValue: this.toBytes(val.value())\r\n };\r\n }\r\n else if (val instanceof RefValue) {\r\n return {\r\n referenceValue: this.toResourceName(val.databaseId, val.key.path)\r\n };\r\n }\r\n else {\r\n return fail('Unknown FieldValue ' + JSON.stringify(val));\r\n }\r\n };\r\n JsonProtoSerializer.prototype.fromValue = function (obj) {\r\n var _this = this;\r\n // tslint:disable-next-line:no-any\r\n var type = obj['value_type'];\r\n if (hasTag(obj, type, 'nullValue')) {\r\n return NullValue.INSTANCE;\r\n }\r\n else if (hasTag(obj, type, 'booleanValue')) {\r\n return BooleanValue.of(obj.booleanValue);\r\n }\r\n else if (hasTag(obj, type, 'integerValue')) {\r\n return new IntegerValue(parseInt64(obj.integerValue));\r\n }\r\n else if (hasTag(obj, type, 'doubleValue')) {\r\n if (this.options.useProto3Json) {\r\n // Proto 3 uses the string values 'NaN' and 'Infinity'.\r\n if (obj.doubleValue === 'NaN') {\r\n return DoubleValue.NAN;\r\n }\r\n else if (obj.doubleValue === 'Infinity') {\r\n return DoubleValue.POSITIVE_INFINITY;\r\n }\r\n else if (obj.doubleValue === '-Infinity') {\r\n return DoubleValue.NEGATIVE_INFINITY;\r\n }\r\n }\r\n return new DoubleValue(obj.doubleValue);\r\n }\r\n else if (hasTag(obj, type, 'stringValue')) {\r\n return new StringValue(obj.stringValue);\r\n }\r\n else if (hasTag(obj, type, 'mapValue')) {\r\n return this.fromFields(obj.mapValue.fields || {});\r\n }\r\n else if (hasTag(obj, type, 'arrayValue')) {\r\n // \"values\" is not present if the array is empty\r\n assertPresent(obj.arrayValue, 'arrayValue');\r\n var values = obj.arrayValue.values || [];\r\n return new ArrayValue(values.map(function (v) { return _this.fromValue(v); }));\r\n }\r\n else if (hasTag(obj, type, 'timestampValue')) {\r\n assertPresent(obj.timestampValue, 'timestampValue');\r\n return new TimestampValue(this.fromTimestamp(obj.timestampValue));\r\n }\r\n else if (hasTag(obj, type, 'geoPointValue')) {\r\n assertPresent(obj.geoPointValue, 'geoPointValue');\r\n var latitude = obj.geoPointValue.latitude || 0;\r\n var longitude = obj.geoPointValue.longitude || 0;\r\n return new GeoPointValue(new GeoPoint(latitude, longitude));\r\n }\r\n else if (hasTag(obj, type, 'bytesValue')) {\r\n assertPresent(obj.bytesValue, 'bytesValue');\r\n var blob = this.fromBlob(obj.bytesValue);\r\n return new BlobValue(blob);\r\n }\r\n else if (hasTag(obj, type, 'referenceValue')) {\r\n assertPresent(obj.referenceValue, 'referenceValue');\r\n var resourceName = this.fromResourceName(obj.referenceValue);\r\n var dbId = new DatabaseId(resourceName.get(1), resourceName.get(3));\r\n var key = new DocumentKey(this.extractLocalPathFromResourceName(resourceName));\r\n return new RefValue(dbId, key);\r\n }\r\n else {\r\n return fail('Unknown Value proto ' + JSON.stringify(obj));\r\n }\r\n };\r\n /** Creates an api.Document from key and fields (but no create/update time) */\r\n JsonProtoSerializer.prototype.toMutationDocument = function (key, fields) {\r\n return {\r\n name: this.toName(key),\r\n fields: this.toFields(fields)\r\n };\r\n };\r\n JsonProtoSerializer.prototype.toDocument = function (document) {\r\n assert(!document.hasLocalMutations, \"Can't serialize documents with mutations.\");\r\n return {\r\n name: this.toName(document.key),\r\n fields: this.toFields(document.data),\r\n updateTime: this.toTimestamp(document.version.toTimestamp())\r\n };\r\n };\r\n JsonProtoSerializer.prototype.fromDocument = function (document, hasCommittedMutations) {\r\n return new Document(this.fromName(document.name), this.fromVersion(document.updateTime), this.fromFields(document.fields || {}), { hasCommittedMutations: !!hasCommittedMutations });\r\n };\r\n JsonProtoSerializer.prototype.toFields = function (fields) {\r\n var _this = this;\r\n var result = {};\r\n fields.forEach(function (key, value) {\r\n result[key] = _this.toValue(value);\r\n });\r\n return result;\r\n };\r\n JsonProtoSerializer.prototype.fromFields = function (object) {\r\n var _this = this;\r\n // Proto map gets mapped to Object, so cast it.\r\n var map = object;\r\n var result = ObjectValue.EMPTY;\r\n forEach(map, function (key, value) {\r\n result = result.set(new FieldPath([key]), _this.fromValue(value));\r\n });\r\n return result;\r\n };\r\n JsonProtoSerializer.prototype.toMapValue = function (map) {\r\n return {\r\n fields: this.toFields(map)\r\n };\r\n };\r\n JsonProtoSerializer.prototype.toArrayValue = function (array) {\r\n var _this = this;\r\n var result = [];\r\n array.forEach(function (value) {\r\n result.push(_this.toValue(value));\r\n });\r\n return { values: result };\r\n };\r\n JsonProtoSerializer.prototype.fromFound = function (doc) {\r\n assert(!!doc.found, 'Tried to deserialize a found document from a missing document.');\r\n assertPresent(doc.found.name, 'doc.found.name');\r\n assertPresent(doc.found.updateTime, 'doc.found.updateTime');\r\n var key = this.fromName(doc.found.name);\r\n var version = this.fromVersion(doc.found.updateTime);\r\n var fields = this.fromFields(doc.found.fields || {});\r\n return new Document(key, version, fields, {}, doc.found);\r\n };\r\n JsonProtoSerializer.prototype.fromMissing = function (result) {\r\n assert(!!result.missing, 'Tried to deserialize a missing document from a found document.');\r\n assert(!!result.readTime, 'Tried to deserialize a missing document without a read time.');\r\n var key = this.fromName(result.missing);\r\n var version = this.fromVersion(result.readTime);\r\n return new NoDocument(key, version);\r\n };\r\n JsonProtoSerializer.prototype.fromMaybeDocument = function (result) {\r\n // tslint:disable-next-line:no-any\r\n var type = result['result'];\r\n if (hasTag(result, type, 'found')) {\r\n return this.fromFound(result);\r\n }\r\n else if (hasTag(result, type, 'missing')) {\r\n return this.fromMissing(result);\r\n }\r\n return fail('invalid batch get response: ' + JSON.stringify(result));\r\n };\r\n JsonProtoSerializer.prototype.toWatchTargetChangeState = function (state) {\r\n switch (state) {\r\n case WatchTargetChangeState.Added:\r\n return 'ADD';\r\n case WatchTargetChangeState.Current:\r\n return 'CURRENT';\r\n case WatchTargetChangeState.NoChange:\r\n return 'NO_CHANGE';\r\n case WatchTargetChangeState.Removed:\r\n return 'REMOVE';\r\n case WatchTargetChangeState.Reset:\r\n return 'RESET';\r\n default:\r\n return fail('Unknown WatchTargetChangeState: ' + state);\r\n }\r\n };\r\n JsonProtoSerializer.prototype.toTestWatchChange = function (watchChange) {\r\n if (watchChange instanceof ExistenceFilterChange) {\r\n return {\r\n filter: {\r\n count: watchChange.existenceFilter.count,\r\n targetId: watchChange.targetId\r\n }\r\n };\r\n }\r\n if (watchChange instanceof DocumentWatchChange) {\r\n if (watchChange.newDoc instanceof Document) {\r\n var doc = watchChange.newDoc;\r\n return {\r\n documentChange: {\r\n document: {\r\n name: this.toName(doc.key),\r\n fields: this.toFields(doc.data),\r\n updateTime: this.toVersion(doc.version)\r\n },\r\n targetIds: watchChange.updatedTargetIds,\r\n removedTargetIds: watchChange.removedTargetIds\r\n }\r\n };\r\n }\r\n else if (watchChange.newDoc instanceof NoDocument) {\r\n var doc = watchChange.newDoc;\r\n return {\r\n documentDelete: {\r\n document: this.toName(doc.key),\r\n readTime: this.toVersion(doc.version),\r\n removedTargetIds: watchChange.removedTargetIds\r\n }\r\n };\r\n }\r\n else if (watchChange.newDoc === null) {\r\n return {\r\n documentRemove: {\r\n document: this.toName(watchChange.key),\r\n removedTargetIds: watchChange.removedTargetIds\r\n }\r\n };\r\n }\r\n }\r\n if (watchChange instanceof WatchTargetChange) {\r\n var cause = undefined;\r\n if (watchChange.cause) {\r\n cause = {\r\n code: mapRpcCodeFromCode(watchChange.cause.code),\r\n message: watchChange.cause.message\r\n };\r\n }\r\n return {\r\n targetChange: {\r\n targetChangeType: this.toWatchTargetChangeState(watchChange.state),\r\n targetIds: watchChange.targetIds,\r\n resumeToken: this.unsafeCastProtoByteString(watchChange.resumeToken),\r\n cause: cause\r\n }\r\n };\r\n }\r\n return fail('Unrecognized watch change: ' + JSON.stringify(watchChange));\r\n };\r\n JsonProtoSerializer.prototype.fromWatchChange = function (change) {\r\n // tslint:disable-next-line:no-any\r\n var type = change['response_type'];\r\n var watchChange;\r\n if (hasTag(change, type, 'targetChange')) {\r\n assertPresent(change.targetChange, 'targetChange');\r\n // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'\r\n // if unset\r\n var state = this.fromWatchTargetChangeState(change.targetChange.targetChangeType || 'NO_CHANGE');\r\n var targetIds = change.targetChange.targetIds || [];\r\n var resumeToken = change.targetChange.resumeToken || this.emptyByteString();\r\n var causeProto = change.targetChange.cause;\r\n var cause = causeProto && this.fromRpcStatus(causeProto);\r\n watchChange = new WatchTargetChange(state, targetIds, resumeToken, cause || null);\r\n }\r\n else if (hasTag(change, type, 'documentChange')) {\r\n assertPresent(change.documentChange, 'documentChange');\r\n assertPresent(change.documentChange.document, 'documentChange.name');\r\n assertPresent(change.documentChange.document.name, 'documentChange.document.name');\r\n assertPresent(change.documentChange.document.updateTime, 'documentChange.document.updateTime');\r\n var entityChange = change.documentChange;\r\n var key = this.fromName(entityChange.document.name);\r\n var version = this.fromVersion(entityChange.document.updateTime);\r\n var fields = this.fromFields(entityChange.document.fields || {});\r\n // The document may soon be re-serialized back to protos in order to store it in local\r\n // persistence. Memoize the encoded form to avoid encoding it again.\r\n var doc = new Document(key, version, fields, {}, entityChange.document);\r\n var updatedTargetIds = entityChange.targetIds || [];\r\n var removedTargetIds = entityChange.removedTargetIds || [];\r\n watchChange = new DocumentWatchChange(updatedTargetIds, removedTargetIds, doc.key, doc);\r\n }\r\n else if (hasTag(change, type, 'documentDelete')) {\r\n assertPresent(change.documentDelete, 'documentDelete');\r\n assertPresent(change.documentDelete.document, 'documentDelete.document');\r\n var docDelete = change.documentDelete;\r\n var key = this.fromName(docDelete.document);\r\n var version = docDelete.readTime\r\n ? this.fromVersion(docDelete.readTime)\r\n : SnapshotVersion.forDeletedDoc();\r\n var doc = new NoDocument(key, version);\r\n var removedTargetIds = docDelete.removedTargetIds || [];\r\n watchChange = new DocumentWatchChange([], removedTargetIds, doc.key, doc);\r\n }\r\n else if (hasTag(change, type, 'documentRemove')) {\r\n assertPresent(change.documentRemove, 'documentRemove');\r\n assertPresent(change.documentRemove.document, 'documentRemove');\r\n var docRemove = change.documentRemove;\r\n var key = this.fromName(docRemove.document);\r\n var removedTargetIds = docRemove.removedTargetIds || [];\r\n watchChange = new DocumentWatchChange([], removedTargetIds, key, null);\r\n }\r\n else if (hasTag(change, type, 'filter')) {\r\n // TODO(dimond): implement existence filter parsing with strategy.\r\n assertPresent(change.filter, 'filter');\r\n assertPresent(change.filter.targetId, 'filter.targetId');\r\n var filter = change.filter;\r\n var count = filter.count || 0;\r\n var existenceFilter = new ExistenceFilter(count);\r\n var targetId = filter.targetId;\r\n watchChange = new ExistenceFilterChange(targetId, existenceFilter);\r\n }\r\n else {\r\n return fail('Unknown change type ' + JSON.stringify(change));\r\n }\r\n return watchChange;\r\n };\r\n JsonProtoSerializer.prototype.fromWatchTargetChangeState = function (state) {\r\n if (state === 'NO_CHANGE') {\r\n return WatchTargetChangeState.NoChange;\r\n }\r\n else if (state === 'ADD') {\r\n return WatchTargetChangeState.Added;\r\n }\r\n else if (state === 'REMOVE') {\r\n return WatchTargetChangeState.Removed;\r\n }\r\n else if (state === 'CURRENT') {\r\n return WatchTargetChangeState.Current;\r\n }\r\n else if (state === 'RESET') {\r\n return WatchTargetChangeState.Reset;\r\n }\r\n else {\r\n return fail('Got unexpected TargetChange.state: ' + state);\r\n }\r\n };\r\n JsonProtoSerializer.prototype.versionFromListenResponse = function (change) {\r\n // We have only reached a consistent snapshot for the entire stream if there\r\n // is a read_time set and it applies to all targets (i.e. the list of\r\n // targets is empty). The backend is guaranteed to send such responses.\r\n // tslint:disable-next-line:no-any\r\n var type = change['response_type'];\r\n if (!hasTag(change, type, 'targetChange')) {\r\n return SnapshotVersion.MIN;\r\n }\r\n var targetChange = change.targetChange;\r\n if (targetChange.targetIds && targetChange.targetIds.length) {\r\n return SnapshotVersion.MIN;\r\n }\r\n if (!targetChange.readTime) {\r\n return SnapshotVersion.MIN;\r\n }\r\n return this.fromVersion(targetChange.readTime);\r\n };\r\n JsonProtoSerializer.prototype.toMutation = function (mutation) {\r\n var _this = this;\r\n var result;\r\n if (mutation instanceof SetMutation) {\r\n result = {\r\n update: this.toMutationDocument(mutation.key, mutation.value)\r\n };\r\n }\r\n else if (mutation instanceof DeleteMutation) {\r\n result = { delete: this.toName(mutation.key) };\r\n }\r\n else if (mutation instanceof PatchMutation) {\r\n result = {\r\n update: this.toMutationDocument(mutation.key, mutation.data),\r\n updateMask: this.toDocumentMask(mutation.fieldMask)\r\n };\r\n }\r\n else if (mutation instanceof TransformMutation) {\r\n result = {\r\n transform: {\r\n document: this.toName(mutation.key),\r\n fieldTransforms: mutation.fieldTransforms.map(function (transform) {\r\n return _this.toFieldTransform(transform);\r\n })\r\n }\r\n };\r\n }\r\n else {\r\n return fail('Unknown mutation type ' + mutation.type);\r\n }\r\n if (!mutation.precondition.isNone) {\r\n result.currentDocument = this.toPrecondition(mutation.precondition);\r\n }\r\n return result;\r\n };\r\n JsonProtoSerializer.prototype.fromMutation = function (proto) {\r\n var _this = this;\r\n var precondition = proto.currentDocument\r\n ? this.fromPrecondition(proto.currentDocument)\r\n : Precondition.NONE;\r\n if (proto.update) {\r\n assertPresent(proto.update.name, 'name');\r\n var key = this.fromName(proto.update.name);\r\n var value = this.fromFields(proto.update.fields || {});\r\n if (proto.updateMask) {\r\n var fieldMask = this.fromDocumentMask(proto.updateMask);\r\n return new PatchMutation(key, value, fieldMask, precondition);\r\n }\r\n else {\r\n return new SetMutation(key, value, precondition);\r\n }\r\n }\r\n else if (proto.delete) {\r\n var key = this.fromName(proto.delete);\r\n return new DeleteMutation(key, precondition);\r\n }\r\n else if (proto.transform) {\r\n var key = this.fromName(proto.transform.document);\r\n var fieldTransforms = proto.transform.fieldTransforms.map(function (transform) {\r\n return _this.fromFieldTransform(transform);\r\n });\r\n assert(precondition.exists === true, 'Transforms only support precondition \"exists == true\"');\r\n return new TransformMutation(key, fieldTransforms);\r\n }\r\n else {\r\n return fail('unknown mutation proto: ' + JSON.stringify(proto));\r\n }\r\n };\r\n JsonProtoSerializer.prototype.toPrecondition = function (precondition) {\r\n assert(!precondition.isNone, \"Can't serialize an empty precondition\");\r\n if (precondition.updateTime !== undefined) {\r\n return {\r\n updateTime: this.toVersion(precondition.updateTime)\r\n };\r\n }\r\n else if (precondition.exists !== undefined) {\r\n return { exists: precondition.exists };\r\n }\r\n else {\r\n return fail('Unknown precondition');\r\n }\r\n };\r\n JsonProtoSerializer.prototype.fromPrecondition = function (precondition) {\r\n if (precondition.updateTime !== undefined) {\r\n return Precondition.updateTime(this.fromVersion(precondition.updateTime));\r\n }\r\n else if (precondition.exists !== undefined) {\r\n return Precondition.exists(precondition.exists);\r\n }\r\n else {\r\n return Precondition.NONE;\r\n }\r\n };\r\n JsonProtoSerializer.prototype.fromWriteResult = function (proto, commitTime) {\r\n var _this = this;\r\n // NOTE: Deletes don't have an updateTime.\r\n var version = proto.updateTime\r\n ? this.fromVersion(proto.updateTime)\r\n : this.fromVersion(commitTime);\r\n var transformResults = null;\r\n if (proto.transformResults && proto.transformResults.length > 0) {\r\n transformResults = proto.transformResults.map(function (result) {\r\n return _this.fromValue(result);\r\n });\r\n }\r\n return new MutationResult(version, transformResults);\r\n };\r\n JsonProtoSerializer.prototype.fromWriteResults = function (protos, commitTime) {\r\n var _this = this;\r\n if (protos && protos.length > 0) {\r\n assert(commitTime !== undefined, 'Received a write result without a commit time');\r\n return protos.map(function (proto) { return _this.fromWriteResult(proto, commitTime); });\r\n }\r\n else {\r\n return [];\r\n }\r\n };\r\n JsonProtoSerializer.prototype.toFieldTransform = function (fieldTransform) {\r\n var _this = this;\r\n var transform = fieldTransform.transform;\r\n if (transform instanceof ServerTimestampTransform) {\r\n return {\r\n fieldPath: fieldTransform.field.canonicalString(),\r\n setToServerValue: 'REQUEST_TIME'\r\n };\r\n }\r\n else if (transform instanceof ArrayUnionTransformOperation) {\r\n return {\r\n fieldPath: fieldTransform.field.canonicalString(),\r\n appendMissingElements: {\r\n values: transform.elements.map(function (v) { return _this.toValue(v); })\r\n }\r\n };\r\n }\r\n else if (transform instanceof ArrayRemoveTransformOperation) {\r\n return {\r\n fieldPath: fieldTransform.field.canonicalString(),\r\n removeAllFromArray: {\r\n values: transform.elements.map(function (v) { return _this.toValue(v); })\r\n }\r\n };\r\n }\r\n else if (transform instanceof NumericIncrementTransformOperation) {\r\n return {\r\n fieldPath: fieldTransform.field.canonicalString(),\r\n increment: this.toValue(transform.operand)\r\n };\r\n }\r\n else {\r\n throw fail('Unknown transform: ' + fieldTransform.transform);\r\n }\r\n };\r\n JsonProtoSerializer.prototype.fromFieldTransform = function (proto) {\r\n var _this = this;\r\n // tslint:disable-next-line:no-any We need to match generated Proto types.\r\n var type = proto['transform_type'];\r\n var transform = null;\r\n if (hasTag(proto, type, 'setToServerValue')) {\r\n assert(proto.setToServerValue === 'REQUEST_TIME', 'Unknown server value transform proto: ' + JSON.stringify(proto));\r\n transform = ServerTimestampTransform.instance;\r\n }\r\n else if (hasTag(proto, type, 'appendMissingElements')) {\r\n var values = proto.appendMissingElements.values || [];\r\n transform = new ArrayUnionTransformOperation(values.map(function (v) { return _this.fromValue(v); }));\r\n }\r\n else if (hasTag(proto, type, 'removeAllFromArray')) {\r\n var values = proto.removeAllFromArray.values || [];\r\n transform = new ArrayRemoveTransformOperation(values.map(function (v) { return _this.fromValue(v); }));\r\n }\r\n else if (hasTag(proto, type, 'increment')) {\r\n var operand = this.fromValue(proto.increment);\r\n assert(operand instanceof NumberValue, 'NUMERIC_ADD transform requires a NumberValue');\r\n transform = new NumericIncrementTransformOperation(operand);\r\n }\r\n else {\r\n fail('Unknown transform proto: ' + JSON.stringify(proto));\r\n }\r\n var fieldPath = FieldPath.fromServerFormat(proto.fieldPath);\r\n return new FieldTransform(fieldPath, transform);\r\n };\r\n JsonProtoSerializer.prototype.toDocumentsTarget = function (query) {\r\n return { documents: [this.toQueryPath(query.path)] };\r\n };\r\n JsonProtoSerializer.prototype.fromDocumentsTarget = function (documentsTarget) {\r\n var count = documentsTarget.documents.length;\r\n assert(count === 1, 'DocumentsTarget contained other than 1 document: ' + count);\r\n var name = documentsTarget.documents[0];\r\n return Query.atPath(this.fromQueryPath(name));\r\n };\r\n JsonProtoSerializer.prototype.toQueryTarget = function (query) {\r\n // Dissect the path into parent, collectionId, and optional key filter.\r\n var result = { structuredQuery: {} };\r\n var path = query.path;\r\n if (query.collectionGroup !== null) {\r\n assert(path.length % 2 === 0, 'Collection Group queries should be within a document path or root.');\r\n result.parent = this.toQueryPath(path);\r\n result.structuredQuery.from = [\r\n {\r\n collectionId: query.collectionGroup,\r\n allDescendants: true\r\n }\r\n ];\r\n }\r\n else {\r\n assert(path.length % 2 !== 0, 'Document queries with filters are not supported.');\r\n result.parent = this.toQueryPath(path.popLast());\r\n result.structuredQuery.from = [{ collectionId: path.lastSegment() }];\r\n }\r\n var where = this.toFilter(query.filters);\r\n if (where) {\r\n result.structuredQuery.where = where;\r\n }\r\n var orderBy = this.toOrder(query.orderBy);\r\n if (orderBy) {\r\n result.structuredQuery.orderBy = orderBy;\r\n }\r\n var limit = this.toInt32Value(query.limit);\r\n if (limit !== undefined) {\r\n result.structuredQuery.limit = limit;\r\n }\r\n if (query.startAt) {\r\n result.structuredQuery.startAt = this.toCursor(query.startAt);\r\n }\r\n if (query.endAt) {\r\n result.structuredQuery.endAt = this.toCursor(query.endAt);\r\n }\r\n return result;\r\n };\r\n JsonProtoSerializer.prototype.fromQueryTarget = function (target) {\r\n var path = this.fromQueryPath(target.parent);\r\n var query = target.structuredQuery;\r\n var fromCount = query.from ? query.from.length : 0;\r\n var collectionGroup = null;\r\n if (fromCount > 0) {\r\n assert(fromCount === 1, 'StructuredQuery.from with more than one collection is not supported.');\r\n var from = query.from[0];\r\n if (from.allDescendants) {\r\n collectionGroup = from.collectionId;\r\n }\r\n else {\r\n path = path.child(from.collectionId);\r\n }\r\n }\r\n var filterBy = [];\r\n if (query.where) {\r\n filterBy = this.fromFilter(query.where);\r\n }\r\n var orderBy = [];\r\n if (query.orderBy) {\r\n orderBy = this.fromOrder(query.orderBy);\r\n }\r\n var limit = null;\r\n if (query.limit) {\r\n limit = this.fromInt32Value(query.limit);\r\n }\r\n var startAt = null;\r\n if (query.startAt) {\r\n startAt = this.fromCursor(query.startAt);\r\n }\r\n var endAt = null;\r\n if (query.endAt) {\r\n endAt = this.fromCursor(query.endAt);\r\n }\r\n return new Query(path, collectionGroup, orderBy, filterBy, limit, startAt, endAt);\r\n };\r\n JsonProtoSerializer.prototype.toListenRequestLabels = function (queryData) {\r\n var value = this.toLabel(queryData.purpose);\r\n if (value == null) {\r\n return null;\r\n }\r\n else {\r\n return {\r\n 'goog-listen-tags': value\r\n };\r\n }\r\n };\r\n JsonProtoSerializer.prototype.toLabel = function (purpose) {\r\n switch (purpose) {\r\n case QueryPurpose.Listen:\r\n return null;\r\n case QueryPurpose.ExistenceFilterMismatch:\r\n return 'existence-filter-mismatch';\r\n case QueryPurpose.LimboResolution:\r\n return 'limbo-document';\r\n default:\r\n return fail('Unrecognized query purpose: ' + purpose);\r\n }\r\n };\r\n JsonProtoSerializer.prototype.toTarget = function (queryData) {\r\n var result;\r\n var query = queryData.query;\r\n if (query.isDocumentQuery()) {\r\n result = { documents: this.toDocumentsTarget(query) };\r\n }\r\n else {\r\n result = { query: this.toQueryTarget(query) };\r\n }\r\n result.targetId = queryData.targetId;\r\n if (queryData.resumeToken.length > 0) {\r\n result.resumeToken = this.unsafeCastProtoByteString(queryData.resumeToken);\r\n }\r\n return result;\r\n };\r\n JsonProtoSerializer.prototype.toFilter = function (filters) {\r\n var _this = this;\r\n if (filters.length === 0)\r\n return;\r\n var protos = filters.map(function (filter) {\r\n return filter instanceof RelationFilter\r\n ? _this.toRelationFilter(filter)\r\n : _this.toUnaryFilter(filter);\r\n });\r\n if (protos.length === 1) {\r\n return protos[0];\r\n }\r\n return { compositeFilter: { op: 'AND', filters: protos } };\r\n };\r\n JsonProtoSerializer.prototype.fromFilter = function (filter) {\r\n var _this = this;\r\n if (!filter) {\r\n return [];\r\n }\r\n else if (filter.unaryFilter !== undefined) {\r\n return [this.fromUnaryFilter(filter)];\r\n }\r\n else if (filter.fieldFilter !== undefined) {\r\n return [this.fromRelationFilter(filter)];\r\n }\r\n else if (filter.compositeFilter !== undefined) {\r\n return filter.compositeFilter\r\n .filters.map(function (f) { return _this.fromFilter(f); })\r\n .reduce(function (accum, current) { return accum.concat(current); });\r\n }\r\n else {\r\n return fail('Unknown filter: ' + JSON.stringify(filter));\r\n }\r\n };\r\n JsonProtoSerializer.prototype.toOrder = function (orderBys) {\r\n var _this = this;\r\n if (orderBys.length === 0)\r\n return;\r\n return orderBys.map(function (order) { return _this.toPropertyOrder(order); });\r\n };\r\n JsonProtoSerializer.prototype.fromOrder = function (orderBys) {\r\n var _this = this;\r\n return orderBys.map(function (order) { return _this.fromPropertyOrder(order); });\r\n };\r\n JsonProtoSerializer.prototype.toCursor = function (cursor) {\r\n var _this = this;\r\n return {\r\n before: cursor.before,\r\n values: cursor.position.map(function (component) { return _this.toValue(component); })\r\n };\r\n };\r\n JsonProtoSerializer.prototype.fromCursor = function (cursor) {\r\n var _this = this;\r\n var before = !!cursor.before;\r\n var position = cursor.values.map(function (component) { return _this.fromValue(component); });\r\n return new Bound(position, before);\r\n };\r\n // visible for testing\r\n JsonProtoSerializer.prototype.toDirection = function (dir) {\r\n return DIRECTIONS[dir.name];\r\n };\r\n // visible for testing\r\n JsonProtoSerializer.prototype.fromDirection = function (dir) {\r\n switch (dir) {\r\n case 'ASCENDING':\r\n return Direction.ASCENDING;\r\n case 'DESCENDING':\r\n return Direction.DESCENDING;\r\n default:\r\n return undefined;\r\n }\r\n };\r\n // visible for testing\r\n JsonProtoSerializer.prototype.toOperatorName = function (op) {\r\n return OPERATORS[op.name];\r\n };\r\n JsonProtoSerializer.prototype.fromOperatorName = function (op) {\r\n switch (op) {\r\n case 'EQUAL':\r\n return RelationOp.EQUAL;\r\n case 'GREATER_THAN':\r\n return RelationOp.GREATER_THAN;\r\n case 'GREATER_THAN_OR_EQUAL':\r\n return RelationOp.GREATER_THAN_OR_EQUAL;\r\n case 'LESS_THAN':\r\n return RelationOp.LESS_THAN;\r\n case 'LESS_THAN_OR_EQUAL':\r\n return RelationOp.LESS_THAN_OR_EQUAL;\r\n case 'ARRAY_CONTAINS':\r\n return RelationOp.ARRAY_CONTAINS;\r\n case 'OPERATOR_UNSPECIFIED':\r\n return fail('Unspecified relation');\r\n default:\r\n return fail('Unknown relation');\r\n }\r\n };\r\n JsonProtoSerializer.prototype.toFieldPathReference = function (path) {\r\n return { fieldPath: path.canonicalString() };\r\n };\r\n JsonProtoSerializer.prototype.fromFieldPathReference = function (fieldReference) {\r\n return FieldPath.fromServerFormat(fieldReference.fieldPath);\r\n };\r\n // visible for testing\r\n JsonProtoSerializer.prototype.toPropertyOrder = function (orderBy) {\r\n return {\r\n field: this.toFieldPathReference(orderBy.field),\r\n direction: this.toDirection(orderBy.dir)\r\n };\r\n };\r\n JsonProtoSerializer.prototype.fromPropertyOrder = function (orderBy) {\r\n return new OrderBy(this.fromFieldPathReference(orderBy.field), this.fromDirection(orderBy.direction));\r\n };\r\n // visible for testing\r\n JsonProtoSerializer.prototype.toRelationFilter = function (filter) {\r\n if (filter instanceof RelationFilter) {\r\n return {\r\n fieldFilter: {\r\n field: this.toFieldPathReference(filter.field),\r\n op: this.toOperatorName(filter.op),\r\n value: this.toValue(filter.value)\r\n }\r\n };\r\n }\r\n else {\r\n return fail('Unrecognized filter: ' + JSON.stringify(filter));\r\n }\r\n };\r\n JsonProtoSerializer.prototype.fromRelationFilter = function (filter) {\r\n return new RelationFilter(this.fromFieldPathReference(filter.fieldFilter.field), this.fromOperatorName(filter.fieldFilter.op), this.fromValue(filter.fieldFilter.value));\r\n };\r\n // visible for testing\r\n JsonProtoSerializer.prototype.toUnaryFilter = function (filter) {\r\n if (filter instanceof NanFilter) {\r\n return {\r\n unaryFilter: {\r\n field: this.toFieldPathReference(filter.field),\r\n op: 'IS_NAN'\r\n }\r\n };\r\n }\r\n else if (filter instanceof NullFilter) {\r\n return {\r\n unaryFilter: {\r\n field: this.toFieldPathReference(filter.field),\r\n op: 'IS_NULL'\r\n }\r\n };\r\n }\r\n else {\r\n return fail('Unrecognized filter: ' + JSON.stringify(filter));\r\n }\r\n };\r\n JsonProtoSerializer.prototype.fromUnaryFilter = function (filter) {\r\n switch (filter.unaryFilter.op) {\r\n case 'IS_NAN':\r\n var nanField = this.fromFieldPathReference(filter.unaryFilter.field);\r\n return new NanFilter(nanField);\r\n case 'IS_NULL':\r\n var nullField = this.fromFieldPathReference(filter.unaryFilter.field);\r\n return new NullFilter(nullField);\r\n case 'OPERATOR_UNSPECIFIED':\r\n return fail('Unspecified filter');\r\n default:\r\n return fail('Unknown filter');\r\n }\r\n };\r\n JsonProtoSerializer.prototype.toDocumentMask = function (fieldMask) {\r\n var canonicalFields = [];\r\n fieldMask.fields.forEach(function (field) {\r\n return canonicalFields.push(field.canonicalString());\r\n });\r\n return {\r\n fieldPaths: canonicalFields\r\n };\r\n };\r\n JsonProtoSerializer.prototype.fromDocumentMask = function (proto) {\r\n var paths = proto.fieldPaths || [];\r\n var fields = paths.map(function (path) { return FieldPath.fromServerFormat(path); });\r\n return FieldMask.fromArray(fields);\r\n };\r\n return JsonProtoSerializer;\r\n}());\r\n/**\r\n * Checks for a specific oneof tag in a protocol buffer message.\r\n *\r\n * This intentionally accommodates two distinct cases:\r\n *\r\n * 1) Messages containing a type tag: these are the format produced by GRPC in\r\n * return values. These may contain default-value mappings for all tags in the\r\n * oneof but the type tag specifies which one was actually set.\r\n *\r\n * 2) Messages that don't contain a type tag: these are the format required by\r\n * GRPC as inputs. If we emitted objects with type tags, ProtoBuf.js would\r\n * choke claiming that the tags aren't fields in the Message.\r\n *\r\n * Allowing both formats here makes the serializer able to consume the outputs\r\n * it produces: for all messages it supports, fromX(toX(value)) == value.\r\n *\r\n * Note that case 2 suffers from ambiguity: if multiple tags are present\r\n * without a type tag then the callers are structured in such a way that the\r\n * first invocation will win. Since we only parse in this mode when parsing\r\n * the output of a serialize method this works, but it's not a general\r\n * solution.\r\n *\r\n * Unfortunately there is no general solution here because proto3 makes it\r\n * impossible to distinguish unset from explicitly set fields: both have the\r\n * default value for the type. Without the type tag but multiple value tags\r\n * it's possible to have default values for each tag in the oneof and not be\r\n * able to know which was actually in effect.\r\n */\r\nfunction hasTag(obj, type, tag) {\r\n return type === tag || (!type && tag in obj);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provides a simple helper class that implements the Stream interface to\r\n * bridge to other implementations that are streams but do not implement the\r\n * interface. The stream callbacks are invoked with the callOn... methods.\r\n */\r\nvar StreamBridge = /** @class */ (function () {\r\n function StreamBridge(args) {\r\n this.sendFn = args.sendFn;\r\n this.closeFn = args.closeFn;\r\n }\r\n StreamBridge.prototype.onOpen = function (callback) {\r\n assert(!this.wrappedOnOpen, 'Called onOpen on stream twice!');\r\n this.wrappedOnOpen = callback;\r\n };\r\n StreamBridge.prototype.onClose = function (callback) {\r\n assert(!this.wrappedOnClose, 'Called onClose on stream twice!');\r\n this.wrappedOnClose = callback;\r\n };\r\n StreamBridge.prototype.onMessage = function (callback) {\r\n assert(!this.wrappedOnMessage, 'Called onMessage on stream twice!');\r\n this.wrappedOnMessage = callback;\r\n };\r\n StreamBridge.prototype.close = function () {\r\n this.closeFn();\r\n };\r\n StreamBridge.prototype.send = function (msg) {\r\n this.sendFn(msg);\r\n };\r\n StreamBridge.prototype.callOnOpen = function () {\r\n assert(this.wrappedOnOpen !== undefined, 'Cannot call onOpen because no callback was set');\r\n this.wrappedOnOpen();\r\n };\r\n StreamBridge.prototype.callOnClose = function (err) {\r\n assert(this.wrappedOnClose !== undefined, 'Cannot call onClose because no callback was set');\r\n this.wrappedOnClose(err);\r\n };\r\n StreamBridge.prototype.callOnMessage = function (msg) {\r\n assert(this.wrappedOnMessage !== undefined, 'Cannot call onMessage because no callback was set');\r\n this.wrappedOnMessage(msg);\r\n };\r\n return StreamBridge;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar LOG_TAG = 'Connection';\r\nvar RPC_STREAM_SERVICE = 'google.firestore.v1.Firestore';\r\nvar RPC_URL_VERSION = 'v1';\r\n/** Maps RPC names to the corresponding REST endpoint name. */\r\nvar RPC_NAME_REST_MAPPING = {\r\n BatchGetDocuments: 'batchGet',\r\n Commit: 'commit'\r\n};\r\n// TODO(b/38203344): The SDK_VERSION is set independently from Firebase because\r\n// we are doing out-of-band releases. Once we release as part of Firebase, we\r\n// should use the Firebase version instead.\r\nvar X_GOOG_API_CLIENT_VALUE = 'gl-js/ fire/' + SDK_VERSION;\r\nvar XHR_TIMEOUT_SECS = 15;\r\nvar WebChannelConnection = /** @class */ (function () {\r\n function WebChannelConnection(info) {\r\n this.databaseId = info.databaseId;\r\n var proto = info.ssl ? 'https' : 'http';\r\n this.baseUrl = proto + '://' + info.host;\r\n this.forceLongPolling = info.forceLongPolling;\r\n }\r\n /**\r\n * Modifies the headers for a request, adding any authorization token if\r\n * present and any additional headers for the request.\r\n */\r\n WebChannelConnection.prototype.modifyHeadersForRequest = function (headers, token) {\r\n if (token) {\r\n for (var header in token.authHeaders) {\r\n if (token.authHeaders.hasOwnProperty(header)) {\r\n headers[header] = token.authHeaders[header];\r\n }\r\n }\r\n }\r\n headers['X-Goog-Api-Client'] = X_GOOG_API_CLIENT_VALUE;\r\n };\r\n WebChannelConnection.prototype.invokeRPC = function (rpcName, request, token) {\r\n var _this = this;\r\n var url = this.makeUrl(rpcName);\r\n return new Promise(function (resolve, reject) {\r\n // tslint:disable-next-line:no-any XhrIo doesn't have TS typings.\r\n var xhr = new webchannelWrapper.XhrIo();\r\n xhr.listenOnce(webchannelWrapper.EventType.COMPLETE, function () {\r\n try {\r\n switch (xhr.getLastErrorCode()) {\r\n case webchannelWrapper.ErrorCode.NO_ERROR:\r\n var json = xhr.getResponseJson();\r\n debug(LOG_TAG, 'XHR received:', JSON.stringify(json));\r\n resolve(json);\r\n break;\r\n case webchannelWrapper.ErrorCode.TIMEOUT:\r\n debug(LOG_TAG, 'RPC \"' + rpcName + '\" timed out');\r\n reject(new FirestoreError(Code.DEADLINE_EXCEEDED, 'Request time out'));\r\n break;\r\n case webchannelWrapper.ErrorCode.HTTP_ERROR:\r\n var status_1 = xhr.getStatus();\r\n debug(LOG_TAG, 'RPC \"' + rpcName + '\" failed with status:', status_1, 'response text:', xhr.getResponseText());\r\n if (status_1 > 0) {\r\n reject(new FirestoreError(mapCodeFromHttpStatus(status_1), 'Server responded with status ' + xhr.getStatusText()));\r\n }\r\n else {\r\n // If we received an HTTP_ERROR but there's no status code,\r\n // it's most probably a connection issue\r\n debug(LOG_TAG, 'RPC \"' + rpcName + '\" failed');\r\n reject(new FirestoreError(Code.UNAVAILABLE, 'Connection failed.'));\r\n }\r\n break;\r\n default:\r\n fail('RPC \"' +\r\n rpcName +\r\n '\" failed with unanticipated ' +\r\n 'webchannel error ' +\r\n xhr.getLastErrorCode() +\r\n ': ' +\r\n xhr.getLastError() +\r\n ', giving up.');\r\n }\r\n }\r\n finally {\r\n debug(LOG_TAG, 'RPC \"' + rpcName + '\" completed.');\r\n }\r\n });\r\n var requestString = JSON.stringify(request);\r\n debug(LOG_TAG, 'XHR sending: ', url + ' ' + requestString);\r\n // Content-Type: text/plain will avoid preflight requests which might\r\n // mess with CORS and redirects by proxies. If we add custom headers\r\n // we will need to change this code to potentially use the\r\n // $httpOverwrite parameter supported by ESF to avoid\r\n // triggering preflight requests.\r\n var headers = { 'Content-Type': 'text/plain' };\r\n _this.modifyHeadersForRequest(headers, token);\r\n xhr.send(url, 'POST', requestString, headers, XHR_TIMEOUT_SECS);\r\n });\r\n };\r\n WebChannelConnection.prototype.invokeStreamingRPC = function (rpcName, request, token) {\r\n // The REST API automatically aggregates all of the streamed results, so we\r\n // can just use the normal invoke() method.\r\n return this.invokeRPC(rpcName, request, token);\r\n };\r\n WebChannelConnection.prototype.openStream = function (rpcName, token) {\r\n var urlParts = [\r\n this.baseUrl,\r\n '/',\r\n RPC_STREAM_SERVICE,\r\n '/',\r\n rpcName,\r\n '/channel'\r\n ];\r\n var webchannelTransport = webchannelWrapper.createWebChannelTransport();\r\n var request = {\r\n // Background channel test avoids the initial two test calls and decreases\r\n // initial cold start time.\r\n // TODO(dimond): wenboz@ mentioned this might affect use with proxies and\r\n // we should monitor closely for any reports.\r\n backgroundChannelTest: true,\r\n // Required for backend stickiness, routing behavior is based on this\r\n // parameter.\r\n httpSessionIdParam: 'gsessionid',\r\n initMessageHeaders: {},\r\n messageUrlParams: {\r\n // This param is used to improve routing and project isolation by the\r\n // backend and must be included in every request.\r\n database: \"projects/\" + this.databaseId.projectId + \"/databases/\" + this.databaseId.database\r\n },\r\n sendRawJson: true,\r\n supportsCrossDomainXhr: true,\r\n internalChannelParams: {\r\n // Override the default timeout (randomized between 10-20 seconds) since\r\n // a large write batch on a slow internet connection may take a long\r\n // time to send to the backend. Rather than have WebChannel impose a\r\n // tight timeout which could lead to infinite timeouts and retries, we\r\n // set it very large (5-10 minutes) and rely on the browser's builtin\r\n // timeouts to kick in if the request isn't working.\r\n forwardChannelRequestTimeoutMs: 10 * 60 * 1000\r\n },\r\n forceLongPolling: this.forceLongPolling\r\n };\r\n this.modifyHeadersForRequest(request.initMessageHeaders, token);\r\n // Sending the custom headers we just added to request.initMessageHeaders\r\n // (Authorization, etc.) will trigger the browser to make a CORS preflight\r\n // request because the XHR will no longer meet the criteria for a \"simple\"\r\n // CORS request:\r\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests\r\n //\r\n // Therefore to avoid the CORS preflight request (an extra network\r\n // roundtrip), we use the httpHeadersOverwriteParam option to specify that\r\n // the headers should instead be encoded into a special \"$httpHeaders\" query\r\n // parameter, which is recognized by the webchannel backend. This is\r\n // formally defined here:\r\n // https://github.com/google/closure-library/blob/b0e1815b13fb92a46d7c9b3c30de5d6a396a3245/closure/goog/net/rpc/httpcors.js#L32\r\n //\r\n // But for some unclear reason (see\r\n // https://github.com/firebase/firebase-js-sdk/issues/703), this breaks\r\n // ReactNative and so we exclude it, which just means ReactNative may be\r\n // subject to the extra network roundtrip for CORS preflight.\r\n if (!util.isReactNative()) {\r\n request['httpHeadersOverwriteParam'] = '$httpHeaders';\r\n }\r\n var url = urlParts.join('');\r\n debug(LOG_TAG, 'Creating WebChannel: ' + url + ' ' + request);\r\n // tslint:disable-next-line:no-any Because listen isn't defined on it.\r\n var channel = webchannelTransport.createWebChannel(url, request);\r\n // WebChannel supports sending the first message with the handshake - saving\r\n // a network round trip. However, it will have to call send in the same\r\n // JS event loop as open. In order to enforce this, we delay actually\r\n // opening the WebChannel until send is called. Whether we have called\r\n // open is tracked with this variable.\r\n var opened = false;\r\n // A flag to determine whether the stream was closed (by us or through an\r\n // error/close event) to avoid delivering multiple close events or sending\r\n // on a closed stream\r\n var closed = false;\r\n var streamBridge = new StreamBridge({\r\n sendFn: function (msg) {\r\n if (!closed) {\r\n if (!opened) {\r\n debug(LOG_TAG, 'Opening WebChannel transport.');\r\n channel.open();\r\n opened = true;\r\n }\r\n debug(LOG_TAG, 'WebChannel sending:', msg);\r\n channel.send(msg);\r\n }\r\n else {\r\n debug(LOG_TAG, 'Not sending because WebChannel is closed:', msg);\r\n }\r\n },\r\n closeFn: function () { return channel.close(); }\r\n });\r\n // Closure events are guarded and exceptions are swallowed, so catch any\r\n // exception and rethrow using a setTimeout so they become visible again.\r\n // Note that eventually this function could go away if we are confident\r\n // enough the code is exception free.\r\n var unguardedEventListen = function (type, fn) {\r\n // TODO(dimond): closure typing seems broken because WebChannel does\r\n // not implement goog.events.Listenable\r\n channel.listen(type, function (param) {\r\n try {\r\n fn(param);\r\n }\r\n catch (e) {\r\n setTimeout(function () {\r\n throw e;\r\n }, 0);\r\n }\r\n });\r\n };\r\n unguardedEventListen(webchannelWrapper.WebChannel.EventType.OPEN, function () {\r\n if (!closed) {\r\n debug(LOG_TAG, 'WebChannel transport opened.');\r\n }\r\n });\r\n unguardedEventListen(webchannelWrapper.WebChannel.EventType.CLOSE, function () {\r\n if (!closed) {\r\n closed = true;\r\n debug(LOG_TAG, 'WebChannel transport closed');\r\n streamBridge.callOnClose();\r\n }\r\n });\r\n unguardedEventListen(webchannelWrapper.WebChannel.EventType.ERROR, function (err) {\r\n if (!closed) {\r\n closed = true;\r\n debug(LOG_TAG, 'WebChannel transport errored:', err);\r\n streamBridge.callOnClose(new FirestoreError(Code.UNAVAILABLE, 'The operation could not be completed'));\r\n }\r\n });\r\n unguardedEventListen(webchannelWrapper.WebChannel.EventType.MESSAGE, function (msg) {\r\n if (!closed) {\r\n var msgData = msg.data[0];\r\n assert(!!msgData, 'Got a webchannel message without data.');\r\n // TODO(b/35143891): There is a bug in One Platform that caused errors\r\n // (and only errors) to be wrapped in an extra array. To be forward\r\n // compatible with the bug we need to check either condition. The latter\r\n // can be removed once the fix has been rolled out.\r\n var error = \r\n // tslint:disable-next-line:no-any msgData.error is not typed.\r\n msgData.error || (msgData[0] && msgData[0].error);\r\n if (error) {\r\n debug(LOG_TAG, 'WebChannel received error:', error);\r\n // error.status will be a string like 'OK' or 'NOT_FOUND'.\r\n var status_2 = error.status;\r\n var code = mapCodeFromRpcStatus(status_2);\r\n var message = error.message;\r\n if (code === undefined) {\r\n code = Code.INTERNAL;\r\n message =\r\n 'Unknown error status: ' +\r\n status_2 +\r\n ' with message ' +\r\n error.message;\r\n }\r\n // Mark closed so no further events are propagated\r\n closed = true;\r\n streamBridge.callOnClose(new FirestoreError(code, message));\r\n channel.close();\r\n }\r\n else {\r\n debug(LOG_TAG, 'WebChannel received:', msgData);\r\n streamBridge.callOnMessage(msgData);\r\n }\r\n }\r\n });\r\n setTimeout(function () {\r\n // Technically we could/should wait for the WebChannel opened event,\r\n // but because we want to send the first message with the WebChannel\r\n // handshake we pretend the channel opened here (asynchronously), and\r\n // then delay the actual open until the first message is sent.\r\n streamBridge.callOnOpen();\r\n }, 0);\r\n return streamBridge;\r\n };\r\n // visible for testing\r\n WebChannelConnection.prototype.makeUrl = function (rpcName) {\r\n var urlRpcName = RPC_NAME_REST_MAPPING[rpcName];\r\n assert(urlRpcName !== undefined, 'Unknown REST mapping for: ' + rpcName);\r\n var url = [this.baseUrl, '/', RPC_URL_VERSION];\r\n url.push('/projects/');\r\n url.push(this.databaseId.projectId);\r\n url.push('/databases/');\r\n url.push(this.databaseId.database);\r\n url.push('/documents');\r\n url.push(':');\r\n url.push(urlRpcName);\r\n return url.join('');\r\n };\r\n return WebChannelConnection;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar BrowserPlatform = /** @class */ (function () {\r\n function BrowserPlatform() {\r\n this.emptyByteString = '';\r\n this.base64Available = typeof atob !== 'undefined';\r\n }\r\n Object.defineProperty(BrowserPlatform.prototype, \"document\", {\r\n get: function () {\r\n return typeof document !== 'undefined' ? document : null;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(BrowserPlatform.prototype, \"window\", {\r\n get: function () {\r\n return typeof window !== 'undefined' ? window : null;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n BrowserPlatform.prototype.loadConnection = function (databaseInfo) {\r\n return Promise.resolve(new WebChannelConnection(databaseInfo));\r\n };\r\n BrowserPlatform.prototype.newSerializer = function (databaseId) {\r\n return new JsonProtoSerializer(databaseId, { useProto3Json: true });\r\n };\r\n BrowserPlatform.prototype.formatJSON = function (value) {\r\n return JSON.stringify(value);\r\n };\r\n BrowserPlatform.prototype.atob = function (encoded) {\r\n return atob(encoded);\r\n };\r\n BrowserPlatform.prototype.btoa = function (raw) {\r\n return btoa(raw);\r\n };\r\n return BrowserPlatform;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * This code needs to run before Firestore is used. This can be achieved in\r\n * several ways:\r\n * 1) Through the JSCompiler compiling this code and then (automatically)\r\n * executing it before exporting the Firestore symbols.\r\n * 2) Through importing this module first in a Firestore main module\r\n */\r\nPlatformSupport.setPlatform(new BrowserPlatform());\n\n/**\r\n * @license\r\n * Copyright 2018 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to\r\n * exceed. All subsequent calls to next will return increasing values. If provided with a\r\n * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as\r\n * well as write out sequence numbers that it produces via `next()`.\r\n */\r\nvar ListenSequence = /** @class */ (function () {\r\n function ListenSequence(previousValue, sequenceNumberSyncer) {\r\n var _this = this;\r\n this.previousValue = previousValue;\r\n if (sequenceNumberSyncer) {\r\n sequenceNumberSyncer.sequenceNumberHandler = function (sequenceNumber) {\r\n return _this.setPreviousValue(sequenceNumber);\r\n };\r\n this.writeNewSequenceNumber = function (sequenceNumber) {\r\n return sequenceNumberSyncer.writeSequenceNumber(sequenceNumber);\r\n };\r\n }\r\n }\r\n ListenSequence.prototype.setPreviousValue = function (externalPreviousValue) {\r\n this.previousValue = Math.max(externalPreviousValue, this.previousValue);\r\n return this.previousValue;\r\n };\r\n ListenSequence.prototype.next = function () {\r\n var nextValue = ++this.previousValue;\r\n if (this.writeNewSequenceNumber) {\r\n this.writeNewSequenceNumber(nextValue);\r\n }\r\n return nextValue;\r\n };\r\n ListenSequence.INVALID = -1;\r\n return ListenSequence;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar Deferred = /** @class */ (function () {\r\n function Deferred() {\r\n var _this = this;\r\n this.promise = new Promise(function (resolve, reject) {\r\n _this.resolve = resolve;\r\n _this.reject = reject;\r\n });\r\n }\r\n return Deferred;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Wellknown \"timer\" IDs used when scheduling delayed operations on the\r\n * AsyncQueue. These IDs can then be used from tests to check for the presence\r\n * of operations or to run them early.\r\n *\r\n * The string values are used when encoding these timer IDs in JSON spec tests.\r\n */\r\nvar TimerId;\r\n(function (TimerId) {\r\n /** All can be used with runDelayedOperationsEarly() to run all timers. */\r\n TimerId[\"All\"] = \"all\";\r\n /**\r\n * The following 4 timers are used in persistent_stream.ts for the listen and\r\n * write streams. The \"Idle\" timer is used to close the stream due to\r\n * inactivity. The \"ConnectionBackoff\" timer is used to restart a stream once\r\n * the appropriate backoff delay has elapsed.\r\n */\r\n TimerId[\"ListenStreamIdle\"] = \"listen_stream_idle\";\r\n TimerId[\"ListenStreamConnectionBackoff\"] = \"listen_stream_connection_backoff\";\r\n TimerId[\"WriteStreamIdle\"] = \"write_stream_idle\";\r\n TimerId[\"WriteStreamConnectionBackoff\"] = \"write_stream_connection_backoff\";\r\n /**\r\n * A timer used in online_state_tracker.ts to transition from\r\n * OnlineState.Unknown to Offline after a set timeout, rather than waiting\r\n * indefinitely for success or failure.\r\n */\r\n TimerId[\"OnlineStateTimeout\"] = \"online_state_timeout\";\r\n /**\r\n * A timer used to update the client metadata in IndexedDb, which is used\r\n * to determine the primary leaseholder.\r\n */\r\n TimerId[\"ClientMetadataRefresh\"] = \"client_metadata_refresh\";\r\n /** A timer used to periodically attempt LRU Garbage collection */\r\n TimerId[\"LruGarbageCollection\"] = \"lru_garbage_collection\";\r\n})(TimerId || (TimerId = {}));\r\n/**\r\n * Represents an operation scheduled to be run in the future on an AsyncQueue.\r\n *\r\n * It is created via DelayedOperation.createAndSchedule().\r\n *\r\n * Supports cancellation (via cancel()) and early execution (via skipDelay()).\r\n */\r\nvar DelayedOperation = /** @class */ (function () {\r\n function DelayedOperation(asyncQueue, timerId, targetTimeMs, op, removalCallback) {\r\n this.asyncQueue = asyncQueue;\r\n this.timerId = timerId;\r\n this.targetTimeMs = targetTimeMs;\r\n this.op = op;\r\n this.removalCallback = removalCallback;\r\n this.deferred = new Deferred();\r\n this.then = this.deferred.promise.then.bind(this.deferred.promise);\r\n this.catch = this.deferred.promise.catch.bind(this.deferred.promise);\r\n // It's normal for the deferred promise to be canceled (due to cancellation)\r\n // and so we attach a dummy catch callback to avoid\r\n // 'UnhandledPromiseRejectionWarning' log spam.\r\n this.deferred.promise.catch(function (err) { });\r\n }\r\n /**\r\n * Creates and returns a DelayedOperation that has been scheduled to be\r\n * executed on the provided asyncQueue after the provided delayMs.\r\n *\r\n * @param asyncQueue The queue to schedule the operation on.\r\n * @param id A Timer ID identifying the type of operation this is.\r\n * @param delayMs The delay (ms) before the operation should be scheduled.\r\n * @param op The operation to run.\r\n * @param removalCallback A callback to be called synchronously once the\r\n * operation is executed or canceled, notifying the AsyncQueue to remove it\r\n * from its delayedOperations list.\r\n * PORTING NOTE: This exists to prevent making removeDelayedOperation() and\r\n * the DelayedOperation class public.\r\n */\r\n DelayedOperation.createAndSchedule = function (asyncQueue, timerId, delayMs, op, removalCallback) {\r\n var targetTime = Date.now() + delayMs;\r\n var delayedOp = new DelayedOperation(asyncQueue, timerId, targetTime, op, removalCallback);\r\n delayedOp.start(delayMs);\r\n return delayedOp;\r\n };\r\n /**\r\n * Starts the timer. This is called immediately after construction by\r\n * createAndSchedule().\r\n */\r\n DelayedOperation.prototype.start = function (delayMs) {\r\n var _this = this;\r\n this.timerHandle = setTimeout(function () { return _this.handleDelayElapsed(); }, delayMs);\r\n };\r\n /**\r\n * Queues the operation to run immediately (if it hasn't already been run or\r\n * canceled).\r\n */\r\n DelayedOperation.prototype.skipDelay = function () {\r\n return this.handleDelayElapsed();\r\n };\r\n /**\r\n * Cancels the operation if it hasn't already been executed or canceled. The\r\n * promise will be rejected.\r\n *\r\n * As long as the operation has not yet been run, calling cancel() provides a\r\n * guarantee that the operation will not be run.\r\n */\r\n DelayedOperation.prototype.cancel = function (reason) {\r\n if (this.timerHandle !== null) {\r\n this.clearTimeout();\r\n this.deferred.reject(new FirestoreError(Code.CANCELLED, 'Operation cancelled' + (reason ? ': ' + reason : '')));\r\n }\r\n };\r\n DelayedOperation.prototype.handleDelayElapsed = function () {\r\n var _this = this;\r\n this.asyncQueue.enqueueAndForget(function () {\r\n if (_this.timerHandle !== null) {\r\n _this.clearTimeout();\r\n return _this.op().then(function (result) {\r\n return _this.deferred.resolve(result);\r\n });\r\n }\r\n else {\r\n return Promise.resolve();\r\n }\r\n });\r\n };\r\n DelayedOperation.prototype.clearTimeout = function () {\r\n if (this.timerHandle !== null) {\r\n this.removalCallback(this);\r\n clearTimeout(this.timerHandle);\r\n this.timerHandle = null;\r\n }\r\n };\r\n return DelayedOperation;\r\n}());\r\nvar AsyncQueue = /** @class */ (function () {\r\n function AsyncQueue() {\r\n // The last promise in the queue.\r\n this.tail = Promise.resolve();\r\n // Operations scheduled to be queued in the future. Operations are\r\n // automatically removed after they are run or canceled.\r\n this.delayedOperations = [];\r\n // Flag set while there's an outstanding AsyncQueue operation, used for\r\n // assertion sanity-checks.\r\n this.operationInProgress = false;\r\n }\r\n /**\r\n * Adds a new operation to the queue without waiting for it to complete (i.e.\r\n * we ignore the Promise result).\r\n */\r\n AsyncQueue.prototype.enqueueAndForget = function (op) {\r\n // tslint:disable-next-line:no-floating-promises\r\n this.enqueue(op);\r\n };\r\n /**\r\n * Adds a new operation to the queue. Returns a promise that will be resolved\r\n * when the promise returned by the new operation is (with its value).\r\n */\r\n AsyncQueue.prototype.enqueue = function (op) {\r\n var _this = this;\r\n this.verifyNotFailed();\r\n var newTail = this.tail.then(function () {\r\n _this.operationInProgress = true;\r\n return op()\r\n .catch(function (error$1) {\r\n _this.failure = error$1;\r\n _this.operationInProgress = false;\r\n var message = error$1.stack || error$1.message || '';\r\n error('INTERNAL UNHANDLED ERROR: ', message);\r\n // Escape the promise chain and throw the error globally so that\r\n // e.g. any global crash reporting library detects and reports it.\r\n // (but not for simulated errors in our tests since this breaks mocha)\r\n if (message.indexOf('Firestore Test Simulated Error') < 0) {\r\n setTimeout(function () {\r\n throw error$1;\r\n }, 0);\r\n }\r\n // Re-throw the error so that this.tail becomes a rejected Promise and\r\n // all further attempts to chain (via .then) will just short-circuit\r\n // and return the rejected Promise.\r\n throw error$1;\r\n })\r\n .then(function (result) {\r\n _this.operationInProgress = false;\r\n return result;\r\n });\r\n });\r\n this.tail = newTail;\r\n return newTail;\r\n };\r\n /**\r\n * Schedules an operation to be queued on the AsyncQueue once the specified\r\n * `delayMs` has elapsed. The returned CancelablePromise can be used to cancel\r\n * the operation prior to its running.\r\n */\r\n AsyncQueue.prototype.enqueueAfterDelay = function (timerId, delayMs, op) {\r\n var _this = this;\r\n this.verifyNotFailed();\r\n assert(delayMs >= 0, \"Attempted to schedule an operation with a negative delay of \" + delayMs);\r\n // While not necessarily harmful, we currently don't expect to have multiple\r\n // ops with the same timer id in the queue, so defensively reject them.\r\n assert(!this.containsDelayedOperation(timerId), \"Attempted to schedule multiple operations with timer id \" + timerId + \".\");\r\n var delayedOp = DelayedOperation.createAndSchedule(this, timerId, delayMs, op, function (op) { return _this.removeDelayedOperation(op); });\r\n this.delayedOperations.push(delayedOp);\r\n return delayedOp;\r\n };\r\n AsyncQueue.prototype.verifyNotFailed = function () {\r\n if (this.failure) {\r\n fail('AsyncQueue is already failed: ' +\r\n (this.failure.stack || this.failure.message));\r\n }\r\n };\r\n /**\r\n * Verifies there's an operation currently in-progress on the AsyncQueue.\r\n * Unfortunately we can't verify that the running code is in the promise chain\r\n * of that operation, so this isn't a foolproof check, but it should be enough\r\n * to catch some bugs.\r\n */\r\n AsyncQueue.prototype.verifyOperationInProgress = function () {\r\n assert(this.operationInProgress, 'verifyOpInProgress() called when no op in progress on this queue.');\r\n };\r\n /**\r\n * Waits until all currently queued tasks are finished executing. Delayed\r\n * operations are not run.\r\n */\r\n AsyncQueue.prototype.drain = function () {\r\n return this.enqueue(function () { return Promise.resolve(); });\r\n };\r\n /**\r\n * For Tests: Determine if a delayed operation with a particular TimerId\r\n * exists.\r\n */\r\n AsyncQueue.prototype.containsDelayedOperation = function (timerId) {\r\n for (var _i = 0, _a = this.delayedOperations; _i < _a.length; _i++) {\r\n var op = _a[_i];\r\n if (op.timerId === timerId) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n };\r\n /**\r\n * For Tests: Runs some or all delayed operations early.\r\n *\r\n * @param lastTimerId Delayed operations up to and including this TimerId will\r\n * be drained. Throws if no such operation exists. Pass TimerId.All to run\r\n * all delayed operations.\r\n * @returns a Promise that resolves once all operations have been run.\r\n */\r\n AsyncQueue.prototype.runDelayedOperationsEarly = function (lastTimerId) {\r\n var _this = this;\r\n // Note that draining may generate more delayed ops, so we do that first.\r\n return this.drain().then(function () {\r\n assert(lastTimerId === TimerId.All ||\r\n _this.containsDelayedOperation(lastTimerId), \"Attempted to drain to missing operation \" + lastTimerId);\r\n // Run ops in the same order they'd run if they ran naturally.\r\n _this.delayedOperations.sort(function (a, b) { return a.targetTimeMs - b.targetTimeMs; });\r\n for (var _i = 0, _a = _this.delayedOperations; _i < _a.length; _i++) {\r\n var op = _a[_i];\r\n op.skipDelay();\r\n if (lastTimerId !== TimerId.All && op.timerId === lastTimerId) {\r\n break;\r\n }\r\n }\r\n return _this.drain();\r\n });\r\n };\r\n /** Called once a DelayedOperation is run or canceled. */\r\n AsyncQueue.prototype.removeDelayedOperation = function (op) {\r\n // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.\r\n var index = this.delayedOperations.indexOf(op);\r\n assert(index >= 0, 'Delayed operation not found.');\r\n this.delayedOperations.splice(index, 1);\r\n };\r\n return AsyncQueue;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar escapeChar = '\\u0001';\r\nvar encodedSeparatorChar = '\\u0001';\r\nvar encodedNul = '\\u0010';\r\nvar encodedEscape = '\\u0011';\r\n/**\r\n * Encodes a resource path into a IndexedDb-compatible string form.\r\n */\r\nfunction encode(path) {\r\n var result = '';\r\n for (var i = 0; i < path.length; i++) {\r\n if (result.length > 0) {\r\n result = encodeSeparator(result);\r\n }\r\n result = encodeSegment(path.get(i), result);\r\n }\r\n return encodeSeparator(result);\r\n}\r\n/** Encodes a single segment of a resource path into the given result */\r\nfunction encodeSegment(segment, resultBuf) {\r\n var result = resultBuf;\r\n var length = segment.length;\r\n for (var i = 0; i < length; i++) {\r\n var c = segment.charAt(i);\r\n switch (c) {\r\n case '\\0':\r\n result += escapeChar + encodedNul;\r\n break;\r\n case escapeChar:\r\n result += escapeChar + encodedEscape;\r\n break;\r\n default:\r\n result += c;\r\n }\r\n }\r\n return result;\r\n}\r\n/** Encodes a path separator into the given result */\r\nfunction encodeSeparator(result) {\r\n return result + escapeChar + encodedSeparatorChar;\r\n}\r\n/**\r\n * Decodes the given IndexedDb-compatible string form of a resource path into\r\n * a ResourcePath instance. Note that this method is not suitable for use with\r\n * decoding resource names from the server; those are One Platform format\r\n * strings.\r\n */\r\nfunction decode(path) {\r\n // Event the empty path must encode as a path of at least length 2. A path\r\n // with exactly 2 must be the empty path.\r\n var length = path.length;\r\n assert(length >= 2, 'Invalid path ' + path);\r\n if (length === 2) {\r\n assert(path.charAt(0) === escapeChar && path.charAt(1) === encodedSeparatorChar, 'Non-empty path ' + path + ' had length 2');\r\n return ResourcePath.EMPTY_PATH;\r\n }\r\n // Escape characters cannot exist past the second-to-last position in the\r\n // source value.\r\n var lastReasonableEscapeIndex = length - 2;\r\n var segments = [];\r\n var segmentBuilder = '';\r\n for (var start = 0; start < length;) {\r\n // The last two characters of a valid encoded path must be a separator, so\r\n // there must be an end to this segment.\r\n var end = path.indexOf(escapeChar, start);\r\n if (end < 0 || end > lastReasonableEscapeIndex) {\r\n fail('Invalid encoded resource path: \"' + path + '\"');\r\n }\r\n var next = path.charAt(end + 1);\r\n switch (next) {\r\n case encodedSeparatorChar:\r\n var currentPiece = path.substring(start, end);\r\n var segment = void 0;\r\n if (segmentBuilder.length === 0) {\r\n // Avoid copying for the common case of a segment that excludes \\0\r\n // and \\001\r\n segment = currentPiece;\r\n }\r\n else {\r\n segmentBuilder += currentPiece;\r\n segment = segmentBuilder;\r\n segmentBuilder = '';\r\n }\r\n segments.push(segment);\r\n break;\r\n case encodedNul:\r\n segmentBuilder += path.substring(start, end);\r\n segmentBuilder += '\\0';\r\n break;\r\n case encodedEscape:\r\n // The escape character can be used in the output to encode itself.\r\n segmentBuilder += path.substring(start, end + 1);\r\n break;\r\n default:\r\n fail('Invalid encoded resource path: \"' + path + '\"');\r\n }\r\n start = end + 2;\r\n }\r\n return new ResourcePath(segments);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar BATCHID_UNKNOWN = -1;\r\n/**\r\n * A batch of mutations that will be sent as one unit to the backend.\r\n */\r\nvar MutationBatch = /** @class */ (function () {\r\n /**\r\n * @param batchId The unique ID of this mutation batch.\r\n * @param localWriteTime The original write time of this mutation.\r\n * @param baseMutations Mutations that are used to populate the base\r\n * values when this mutation is applied locally. This can be used to locally\r\n * overwrite values that are persisted in the remote document cache. Base\r\n * mutations are never sent to the backend.\r\n * @param mutations The user-provided mutations in this mutation batch.\r\n * User-provided mutations are applied both locally and remotely on the\r\n * backend.\r\n */\r\n function MutationBatch(batchId, localWriteTime, baseMutations, mutations) {\r\n this.batchId = batchId;\r\n this.localWriteTime = localWriteTime;\r\n this.baseMutations = baseMutations;\r\n this.mutations = mutations;\r\n assert(mutations.length > 0, 'Cannot create an empty mutation batch');\r\n }\r\n /**\r\n * Applies all the mutations in this MutationBatch to the specified document\r\n * to create a new remote document\r\n *\r\n * @param docKey The key of the document to apply mutations to.\r\n * @param maybeDoc The document to apply mutations to.\r\n * @param batchResult The result of applying the MutationBatch to the\r\n * backend.\r\n */\r\n MutationBatch.prototype.applyToRemoteDocument = function (docKey, maybeDoc, batchResult) {\r\n if (maybeDoc) {\r\n assert(maybeDoc.key.isEqual(docKey), \"applyToRemoteDocument: key \" + docKey + \" should match maybeDoc key\\n \" + maybeDoc.key);\r\n }\r\n var mutationResults = batchResult.mutationResults;\r\n assert(mutationResults.length === this.mutations.length, \"Mismatch between mutations length\\n (\" + this.mutations.length + \") and mutation results length\\n (\" + mutationResults.length + \").\");\r\n for (var i = 0; i < this.mutations.length; i++) {\r\n var mutation = this.mutations[i];\r\n if (mutation.key.isEqual(docKey)) {\r\n var mutationResult = mutationResults[i];\r\n maybeDoc = mutation.applyToRemoteDocument(maybeDoc, mutationResult);\r\n }\r\n }\r\n return maybeDoc;\r\n };\r\n /**\r\n * Computes the local view of a document given all the mutations in this\r\n * batch.\r\n *\r\n * @param docKey The key of the document to apply mutations to.\r\n * @param maybeDoc The document to apply mutations to.\r\n */\r\n MutationBatch.prototype.applyToLocalView = function (docKey, maybeDoc) {\r\n if (maybeDoc) {\r\n assert(maybeDoc.key.isEqual(docKey), \"applyToLocalDocument: key \" + docKey + \" should match maybeDoc key\\n \" + maybeDoc.key);\r\n }\r\n // First, apply the base state. This allows us to apply non-idempotent\r\n // transform against a consistent set of values.\r\n for (var _i = 0, _a = this.baseMutations; _i < _a.length; _i++) {\r\n var mutation = _a[_i];\r\n if (mutation.key.isEqual(docKey)) {\r\n maybeDoc = mutation.applyToLocalView(maybeDoc, maybeDoc, this.localWriteTime);\r\n }\r\n }\r\n var baseDoc = maybeDoc;\r\n // Second, apply all user-provided mutations.\r\n for (var _b = 0, _c = this.mutations; _b < _c.length; _b++) {\r\n var mutation = _c[_b];\r\n if (mutation.key.isEqual(docKey)) {\r\n maybeDoc = mutation.applyToLocalView(maybeDoc, baseDoc, this.localWriteTime);\r\n }\r\n }\r\n return maybeDoc;\r\n };\r\n /**\r\n * Computes the local view for all provided documents given the mutations in\r\n * this batch.\r\n */\r\n MutationBatch.prototype.applyToLocalDocumentSet = function (maybeDocs) {\r\n var _this = this;\r\n // TODO(mrschmidt): This implementation is O(n^2). If we apply the mutations\r\n // directly (as done in `applyToLocalView()`), we can reduce the complexity\r\n // to O(n).\r\n var mutatedDocuments = maybeDocs;\r\n this.mutations.forEach(function (m) {\r\n var mutatedDocument = _this.applyToLocalView(m.key, maybeDocs.get(m.key));\r\n if (mutatedDocument) {\r\n mutatedDocuments = mutatedDocuments.insert(m.key, mutatedDocument);\r\n }\r\n });\r\n return mutatedDocuments;\r\n };\r\n MutationBatch.prototype.keys = function () {\r\n return this.mutations.reduce(function (keys, m) { return keys.add(m.key); }, documentKeySet());\r\n };\r\n MutationBatch.prototype.isEqual = function (other) {\r\n return (this.batchId === other.batchId &&\r\n arrayEquals(this.mutations, other.mutations) &&\r\n arrayEquals(this.baseMutations, other.baseMutations));\r\n };\r\n return MutationBatch;\r\n}());\r\n/** The result of applying a mutation batch to the backend. */\r\nvar MutationBatchResult = /** @class */ (function () {\r\n function MutationBatchResult(batch, commitVersion, mutationResults, streamToken, \r\n /**\r\n * A pre-computed mapping from each mutated document to the resulting\r\n * version.\r\n */\r\n docVersions) {\r\n this.batch = batch;\r\n this.commitVersion = commitVersion;\r\n this.mutationResults = mutationResults;\r\n this.streamToken = streamToken;\r\n this.docVersions = docVersions;\r\n }\r\n /**\r\n * Creates a new MutationBatchResult for the given batch and results. There\r\n * must be one result for each mutation in the batch. This static factory\r\n * caches a document=>version mapping (docVersions).\r\n */\r\n MutationBatchResult.from = function (batch, commitVersion, results, streamToken) {\r\n assert(batch.mutations.length === results.length, 'Mutations sent ' +\r\n batch.mutations.length +\r\n ' must equal results received ' +\r\n results.length);\r\n var versionMap = documentVersionMap();\r\n var mutations = batch.mutations;\r\n for (var i = 0; i < mutations.length; i++) {\r\n versionMap = versionMap.insert(mutations[i].key, results[i].version);\r\n }\r\n return new MutationBatchResult(batch, commitVersion, results, streamToken, versionMap);\r\n };\r\n return MutationBatchResult;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * PersistencePromise<> is essentially a re-implementation of Promise<> except\r\n * it has a .next() method instead of .then() and .next() and .catch() callbacks\r\n * are executed synchronously when a PersistencePromise resolves rather than\r\n * asynchronously (Promise<> implementations use setImmediate() or similar).\r\n *\r\n * This is necessary to interoperate with IndexedDB which will automatically\r\n * commit transactions if control is returned to the event loop without\r\n * synchronously initiating another operation on the transaction.\r\n *\r\n * NOTE: .then() and .catch() only allow a single consumer, unlike normal\r\n * Promises.\r\n */\r\nvar PersistencePromise = /** @class */ (function () {\r\n function PersistencePromise(callback) {\r\n var _this = this;\r\n // NOTE: next/catchCallback will always point to our own wrapper functions,\r\n // not the user's raw next() or catch() callbacks.\r\n // tslint:disable-next-line:no-any Accept any result type for the next call in the Promise chain.\r\n this.nextCallback = null;\r\n // tslint:disable-next-line:no-any Accept any result type for the error handler.\r\n this.catchCallback = null;\r\n // When the operation resolves, we'll set result or error and mark isDone.\r\n this.result = undefined;\r\n this.error = undefined;\r\n this.isDone = false;\r\n // Set to true when .then() or .catch() are called and prevents additional\r\n // chaining.\r\n this.callbackAttached = false;\r\n callback(function (value) {\r\n _this.isDone = true;\r\n _this.result = value;\r\n if (_this.nextCallback) {\r\n // value should be defined unless T is Void, but we can't express\r\n // that in the type system.\r\n _this.nextCallback(value);\r\n }\r\n }, function (error) {\r\n _this.isDone = true;\r\n _this.error = error;\r\n if (_this.catchCallback) {\r\n _this.catchCallback(error);\r\n }\r\n });\r\n }\r\n PersistencePromise.prototype.catch = function (fn) {\r\n return this.next(undefined, fn);\r\n };\r\n PersistencePromise.prototype.next = function (nextFn, catchFn) {\r\n var _this = this;\r\n if (this.callbackAttached) {\r\n fail('Called next() or catch() twice for PersistencePromise');\r\n }\r\n this.callbackAttached = true;\r\n if (this.isDone) {\r\n if (!this.error) {\r\n return this.wrapSuccess(nextFn, this.result);\r\n }\r\n else {\r\n return this.wrapFailure(catchFn, this.error);\r\n }\r\n }\r\n else {\r\n return new PersistencePromise(function (resolve, reject) {\r\n _this.nextCallback = function (value) {\r\n _this.wrapSuccess(nextFn, value).next(resolve, reject);\r\n };\r\n _this.catchCallback = function (error) {\r\n _this.wrapFailure(catchFn, error).next(resolve, reject);\r\n };\r\n });\r\n }\r\n };\r\n PersistencePromise.prototype.toPromise = function () {\r\n var _this = this;\r\n return new Promise(function (resolve, reject) {\r\n _this.next(resolve, reject);\r\n });\r\n };\r\n PersistencePromise.prototype.wrapUserFunction = function (fn) {\r\n try {\r\n var result = fn();\r\n if (result instanceof PersistencePromise) {\r\n return result;\r\n }\r\n else {\r\n return PersistencePromise.resolve(result);\r\n }\r\n }\r\n catch (e) {\r\n return PersistencePromise.reject(e);\r\n }\r\n };\r\n PersistencePromise.prototype.wrapSuccess = function (nextFn, value) {\r\n if (nextFn) {\r\n return this.wrapUserFunction(function () { return nextFn(value); });\r\n }\r\n else {\r\n // If there's no nextFn, then R must be the same as T but we\r\n // can't express that in the type system.\r\n // tslint:disable-next-line:no-any\r\n return PersistencePromise.resolve(value);\r\n }\r\n };\r\n PersistencePromise.prototype.wrapFailure = function (catchFn, error) {\r\n if (catchFn) {\r\n return this.wrapUserFunction(function () { return catchFn(error); });\r\n }\r\n else {\r\n return PersistencePromise.reject(error);\r\n }\r\n };\r\n PersistencePromise.resolve = function (result) {\r\n return new PersistencePromise(function (resolve, reject) {\r\n resolve(result);\r\n });\r\n };\r\n PersistencePromise.reject = function (error) {\r\n return new PersistencePromise(function (resolve, reject) {\r\n reject(error);\r\n });\r\n };\r\n PersistencePromise.waitFor = function (\r\n // tslint:disable-next-line:no-any Accept all Promise types in waitFor().\r\n all) {\r\n return new PersistencePromise(function (resolve, reject) {\r\n var expectedCount = 0;\r\n var resolvedCount = 0;\r\n var done = false;\r\n all.forEach(function (element) {\r\n ++expectedCount;\r\n element.next(function () {\r\n ++resolvedCount;\r\n if (done && resolvedCount === expectedCount) {\r\n resolve();\r\n }\r\n }, function (err) { return reject(err); });\r\n });\r\n done = true;\r\n if (resolvedCount === expectedCount) {\r\n resolve();\r\n }\r\n });\r\n };\r\n /**\r\n * Given an array of predicate functions that asynchronously evaluate to a\r\n * boolean, implements a short-circuiting `or` between the results. Predicates\r\n * will be evaluated until one of them returns `true`, then stop. The final\r\n * result will be whether any of them returned `true`.\r\n */\r\n PersistencePromise.or = function (predicates) {\r\n var p = PersistencePromise.resolve(false);\r\n var _loop_1 = function (predicate) {\r\n p = p.next(function (isTrue) {\r\n if (isTrue) {\r\n return PersistencePromise.resolve(isTrue);\r\n }\r\n else {\r\n return predicate();\r\n }\r\n });\r\n };\r\n for (var _i = 0, predicates_1 = predicates; _i < predicates_1.length; _i++) {\r\n var predicate = predicates_1[_i];\r\n _loop_1(predicate);\r\n }\r\n return p;\r\n };\r\n /**\r\n * Given an iterable, call the given function on each element in the\r\n * collection and wait for all of the resulting concurrent PersistencePromises\r\n * to resolve.\r\n */\r\n PersistencePromise.forEach = function (collection, f) {\r\n var _this = this;\r\n var promises = [];\r\n collection.forEach(function (r, s) {\r\n promises.push(f.call(_this, r, s));\r\n });\r\n return this.waitFor(promises);\r\n };\r\n return PersistencePromise;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** A mutation queue for a specific user, backed by IndexedDB. */\r\nvar IndexedDbMutationQueue = /** @class */ (function () {\r\n function IndexedDbMutationQueue(\r\n /**\r\n * The normalized userId (e.g. null UID => \"\" userId) used to store /\r\n * retrieve mutations.\r\n */\r\n userId, serializer, indexManager, referenceDelegate) {\r\n this.userId = userId;\r\n this.serializer = serializer;\r\n this.indexManager = indexManager;\r\n this.referenceDelegate = referenceDelegate;\r\n /**\r\n * Caches the document keys for pending mutation batches. If the mutation\r\n * has been removed from IndexedDb, the cached value may continue to\r\n * be used to retrieve the batch's document keys. To remove a cached value\r\n * locally, `removeCachedMutationKeys()` should be invoked either directly\r\n * or through `removeMutationBatches()`.\r\n *\r\n * With multi-tab, when the primary client acknowledges or rejects a mutation,\r\n * this cache is used by secondary clients to invalidate the local\r\n * view of the documents that were previously affected by the mutation.\r\n */\r\n // PORTING NOTE: Multi-tab only.\r\n this.documentKeysByBatchId = {};\r\n }\r\n /**\r\n * Creates a new mutation queue for the given user.\r\n * @param user The user for which to create a mutation queue.\r\n * @param serializer The serializer to use when persisting to IndexedDb.\r\n */\r\n IndexedDbMutationQueue.forUser = function (user, serializer, indexManager, referenceDelegate) {\r\n // TODO(mcg): Figure out what constraints there are on userIDs\r\n // In particular, are there any reserved characters? are empty ids allowed?\r\n // For the moment store these together in the same mutations table assuming\r\n // that empty userIDs aren't allowed.\r\n assert(user.uid !== '', 'UserID must not be an empty string.');\r\n var userId = user.isAuthenticated() ? user.uid : '';\r\n return new IndexedDbMutationQueue(userId, serializer, indexManager, referenceDelegate);\r\n };\r\n IndexedDbMutationQueue.prototype.checkEmpty = function (transaction) {\r\n var empty = true;\r\n var range = IDBKeyRange.bound([this.userId, Number.NEGATIVE_INFINITY], [this.userId, Number.POSITIVE_INFINITY]);\r\n return mutationsStore(transaction)\r\n .iterate({ index: DbMutationBatch.userMutationsIndex, range: range }, function (key, value, control) {\r\n empty = false;\r\n control.done();\r\n })\r\n .next(function () { return empty; });\r\n };\r\n IndexedDbMutationQueue.prototype.acknowledgeBatch = function (transaction, batch, streamToken) {\r\n return this.getMutationQueueMetadata(transaction).next(function (metadata) {\r\n metadata.lastStreamToken = convertStreamToken(streamToken);\r\n return mutationQueuesStore(transaction).put(metadata);\r\n });\r\n };\r\n IndexedDbMutationQueue.prototype.getLastStreamToken = function (transaction) {\r\n return this.getMutationQueueMetadata(transaction).next(function (metadata) { return metadata.lastStreamToken; });\r\n };\r\n IndexedDbMutationQueue.prototype.setLastStreamToken = function (transaction, streamToken) {\r\n return this.getMutationQueueMetadata(transaction).next(function (metadata) {\r\n metadata.lastStreamToken = convertStreamToken(streamToken);\r\n return mutationQueuesStore(transaction).put(metadata);\r\n });\r\n };\r\n IndexedDbMutationQueue.prototype.addMutationBatch = function (transaction, localWriteTime, baseMutations, mutations) {\r\n var _this = this;\r\n var documentStore = documentMutationsStore(transaction);\r\n var mutationStore = mutationsStore(transaction);\r\n // The IndexedDb implementation in Chrome (and Firefox) does not handle\r\n // compound indices that include auto-generated keys correctly. To ensure\r\n // that the index entry is added correctly in all browsers, we perform two\r\n // writes: The first write is used to retrieve the next auto-generated Batch\r\n // ID, and the second write populates the index and stores the actual\r\n // mutation batch.\r\n // See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972\r\n // tslint:disable-next-line:no-any We write an empty object to obtain key\r\n return mutationStore.add({}).next(function (batchId) {\r\n assert(typeof batchId === 'number', 'Auto-generated key is not a number');\r\n var batch = new MutationBatch(batchId, localWriteTime, baseMutations, mutations);\r\n var dbBatch = _this.serializer.toDbMutationBatch(_this.userId, batch);\r\n _this.documentKeysByBatchId[batchId] = batch.keys();\r\n var promises = [];\r\n for (var _i = 0, mutations_1 = mutations; _i < mutations_1.length; _i++) {\r\n var mutation = mutations_1[_i];\r\n var indexKey = DbDocumentMutation.key(_this.userId, mutation.key.path, batchId);\r\n promises.push(mutationStore.put(dbBatch));\r\n promises.push(documentStore.put(indexKey, DbDocumentMutation.PLACEHOLDER));\r\n promises.push(_this.indexManager.addToCollectionParentIndex(transaction, mutation.key.path.popLast()));\r\n }\r\n return PersistencePromise.waitFor(promises).next(function () { return batch; });\r\n });\r\n };\r\n IndexedDbMutationQueue.prototype.lookupMutationBatch = function (transaction, batchId) {\r\n var _this = this;\r\n return mutationsStore(transaction)\r\n .get(batchId)\r\n .next(function (dbBatch) {\r\n if (dbBatch) {\r\n assert(dbBatch.userId === _this.userId, \"Unexpected user '\" + dbBatch.userId + \"' for mutation batch \" + batchId);\r\n return _this.serializer.fromDbMutationBatch(dbBatch);\r\n }\r\n return null;\r\n });\r\n };\r\n IndexedDbMutationQueue.prototype.lookupMutationKeys = function (transaction, batchId) {\r\n var _this = this;\r\n if (this.documentKeysByBatchId[batchId]) {\r\n return PersistencePromise.resolve(this.documentKeysByBatchId[batchId]);\r\n }\r\n else {\r\n return this.lookupMutationBatch(transaction, batchId).next(function (batch) {\r\n if (batch) {\r\n var keys = batch.keys();\r\n _this.documentKeysByBatchId[batchId] = keys;\r\n return keys;\r\n }\r\n else {\r\n return null;\r\n }\r\n });\r\n }\r\n };\r\n IndexedDbMutationQueue.prototype.getNextMutationBatchAfterBatchId = function (transaction, batchId) {\r\n var _this = this;\r\n return this.getMutationQueueMetadata(transaction).next(function (metadata) {\r\n var nextBatchId = batchId + 1;\r\n var range = IDBKeyRange.lowerBound([_this.userId, nextBatchId]);\r\n var foundBatch = null;\r\n return mutationsStore(transaction)\r\n .iterate({ index: DbMutationBatch.userMutationsIndex, range: range }, function (key, dbBatch, control) {\r\n if (dbBatch.userId === _this.userId) {\r\n assert(dbBatch.batchId >= nextBatchId, 'Should have found mutation after ' + nextBatchId);\r\n foundBatch = _this.serializer.fromDbMutationBatch(dbBatch);\r\n }\r\n control.done();\r\n })\r\n .next(function () { return foundBatch; });\r\n });\r\n };\r\n IndexedDbMutationQueue.prototype.getAllMutationBatches = function (transaction) {\r\n var _this = this;\r\n var range = IDBKeyRange.bound([this.userId, BATCHID_UNKNOWN], [this.userId, Number.POSITIVE_INFINITY]);\r\n return mutationsStore(transaction)\r\n .loadAll(DbMutationBatch.userMutationsIndex, range)\r\n .next(function (dbBatches) {\r\n return dbBatches.map(function (dbBatch) { return _this.serializer.fromDbMutationBatch(dbBatch); });\r\n });\r\n };\r\n IndexedDbMutationQueue.prototype.getAllMutationBatchesAffectingDocumentKey = function (transaction, documentKey) {\r\n var _this = this;\r\n // Scan the document-mutation index starting with a prefix starting with\r\n // the given documentKey.\r\n var indexPrefix = DbDocumentMutation.prefixForPath(this.userId, documentKey.path);\r\n var indexStart = IDBKeyRange.lowerBound(indexPrefix);\r\n var results = [];\r\n return documentMutationsStore(transaction)\r\n .iterate({ range: indexStart }, function (indexKey, _, control) {\r\n var userID = indexKey[0], encodedPath = indexKey[1], batchId = indexKey[2];\r\n // Only consider rows matching exactly the specific key of\r\n // interest. Note that because we order by path first, and we\r\n // order terminators before path separators, we'll encounter all\r\n // the index rows for documentKey contiguously. In particular, all\r\n // the rows for documentKey will occur before any rows for\r\n // documents nested in a subcollection beneath documentKey so we\r\n // can stop as soon as we hit any such row.\r\n var path = decode(encodedPath);\r\n if (userID !== _this.userId || !documentKey.path.isEqual(path)) {\r\n control.done();\r\n return;\r\n }\r\n // Look up the mutation batch in the store.\r\n return mutationsStore(transaction)\r\n .get(batchId)\r\n .next(function (mutation) {\r\n if (!mutation) {\r\n throw fail('Dangling document-mutation reference found: ' +\r\n indexKey +\r\n ' which points to ' +\r\n batchId);\r\n }\r\n assert(mutation.userId === _this.userId, \"Unexpected user '\" + mutation.userId + \"' for mutation batch \" + batchId);\r\n results.push(_this.serializer.fromDbMutationBatch(mutation));\r\n });\r\n })\r\n .next(function () { return results; });\r\n };\r\n IndexedDbMutationQueue.prototype.getAllMutationBatchesAffectingDocumentKeys = function (transaction, documentKeys) {\r\n var _this = this;\r\n var uniqueBatchIDs = new SortedSet(primitiveComparator);\r\n var promises = [];\r\n documentKeys.forEach(function (documentKey) {\r\n var indexStart = DbDocumentMutation.prefixForPath(_this.userId, documentKey.path);\r\n var range = IDBKeyRange.lowerBound(indexStart);\r\n var promise = documentMutationsStore(transaction).iterate({ range: range }, function (indexKey, _, control) {\r\n var userID = indexKey[0], encodedPath = indexKey[1], batchID = indexKey[2];\r\n // Only consider rows matching exactly the specific key of\r\n // interest. Note that because we order by path first, and we\r\n // order terminators before path separators, we'll encounter all\r\n // the index rows for documentKey contiguously. In particular, all\r\n // the rows for documentKey will occur before any rows for\r\n // documents nested in a subcollection beneath documentKey so we\r\n // can stop as soon as we hit any such row.\r\n var path = decode(encodedPath);\r\n if (userID !== _this.userId || !documentKey.path.isEqual(path)) {\r\n control.done();\r\n return;\r\n }\r\n uniqueBatchIDs = uniqueBatchIDs.add(batchID);\r\n });\r\n promises.push(promise);\r\n });\r\n return PersistencePromise.waitFor(promises).next(function () {\r\n return _this.lookupMutationBatches(transaction, uniqueBatchIDs);\r\n });\r\n };\r\n IndexedDbMutationQueue.prototype.getAllMutationBatchesAffectingQuery = function (transaction, query) {\r\n var _this = this;\r\n assert(!query.isDocumentQuery(), \"Document queries shouldn't go down this path\");\r\n assert(!query.isCollectionGroupQuery(), 'CollectionGroup queries should be handled in LocalDocumentsView');\r\n var queryPath = query.path;\r\n var immediateChildrenLength = queryPath.length + 1;\r\n // TODO(mcg): Actually implement a single-collection query\r\n //\r\n // This is actually executing an ancestor query, traversing the whole\r\n // subtree below the collection which can be horrifically inefficient for\r\n // some structures. The right way to solve this is to implement the full\r\n // value index, but that's not in the cards in the near future so this is\r\n // the best we can do for the moment.\r\n //\r\n // Since we don't yet index the actual properties in the mutations, our\r\n // current approach is to just return all mutation batches that affect\r\n // documents in the collection being queried.\r\n var indexPrefix = DbDocumentMutation.prefixForPath(this.userId, queryPath);\r\n var indexStart = IDBKeyRange.lowerBound(indexPrefix);\r\n // Collect up unique batchIDs encountered during a scan of the index. Use a\r\n // SortedSet to accumulate batch IDs so they can be traversed in order in a\r\n // scan of the main table.\r\n var uniqueBatchIDs = new SortedSet(primitiveComparator);\r\n return documentMutationsStore(transaction)\r\n .iterate({ range: indexStart }, function (indexKey, _, control) {\r\n var userID = indexKey[0], encodedPath = indexKey[1], batchID = indexKey[2];\r\n var path = decode(encodedPath);\r\n if (userID !== _this.userId || !queryPath.isPrefixOf(path)) {\r\n control.done();\r\n return;\r\n }\r\n // Rows with document keys more than one segment longer than the\r\n // query path can't be matches. For example, a query on 'rooms'\r\n // can't match the document /rooms/abc/messages/xyx.\r\n // TODO(mcg): we'll need a different scanner when we implement\r\n // ancestor queries.\r\n if (path.length !== immediateChildrenLength) {\r\n return;\r\n }\r\n uniqueBatchIDs = uniqueBatchIDs.add(batchID);\r\n })\r\n .next(function () { return _this.lookupMutationBatches(transaction, uniqueBatchIDs); });\r\n };\r\n IndexedDbMutationQueue.prototype.lookupMutationBatches = function (transaction, batchIDs) {\r\n var _this = this;\r\n var results = [];\r\n var promises = [];\r\n // TODO(rockwood): Implement this using iterate.\r\n batchIDs.forEach(function (batchId) {\r\n promises.push(mutationsStore(transaction)\r\n .get(batchId)\r\n .next(function (mutation) {\r\n if (mutation === null) {\r\n throw fail('Dangling document-mutation reference found, ' +\r\n 'which points to ' +\r\n batchId);\r\n }\r\n assert(mutation.userId === _this.userId, \"Unexpected user '\" + mutation.userId + \"' for mutation batch \" + batchId);\r\n results.push(_this.serializer.fromDbMutationBatch(mutation));\r\n }));\r\n });\r\n return PersistencePromise.waitFor(promises).next(function () { return results; });\r\n };\r\n IndexedDbMutationQueue.prototype.removeMutationBatch = function (transaction, batch) {\r\n var _this = this;\r\n return removeMutationBatch(transaction.simpleDbTransaction, this.userId, batch).next(function (removedDocuments) {\r\n _this.removeCachedMutationKeys(batch.batchId);\r\n return PersistencePromise.forEach(removedDocuments, function (key) {\r\n return _this.referenceDelegate.removeMutationReference(transaction, key);\r\n });\r\n });\r\n };\r\n IndexedDbMutationQueue.prototype.removeCachedMutationKeys = function (batchId) {\r\n delete this.documentKeysByBatchId[batchId];\r\n };\r\n IndexedDbMutationQueue.prototype.performConsistencyCheck = function (txn) {\r\n var _this = this;\r\n return this.checkEmpty(txn).next(function (empty) {\r\n if (!empty) {\r\n return PersistencePromise.resolve();\r\n }\r\n // Verify that there are no entries in the documentMutations index if\r\n // the queue is empty.\r\n var startRange = IDBKeyRange.lowerBound(DbDocumentMutation.prefixForUser(_this.userId));\r\n var danglingMutationReferences = [];\r\n return documentMutationsStore(txn)\r\n .iterate({ range: startRange }, function (key, _, control) {\r\n var userID = key[0];\r\n if (userID !== _this.userId) {\r\n control.done();\r\n return;\r\n }\r\n else {\r\n var path = decode(key[1]);\r\n danglingMutationReferences.push(path);\r\n }\r\n })\r\n .next(function () {\r\n assert(danglingMutationReferences.length === 0, 'Document leak -- detected dangling mutation references when queue is empty. ' +\r\n 'Dangling keys: ' +\r\n danglingMutationReferences.map(function (p) { return p.canonicalString(); }));\r\n });\r\n });\r\n };\r\n IndexedDbMutationQueue.prototype.containsKey = function (txn, key) {\r\n return mutationQueueContainsKey(txn, this.userId, key);\r\n };\r\n // PORTING NOTE: Multi-tab only (state is held in memory in other clients).\r\n /** Returns the mutation queue's metadata from IndexedDb. */\r\n IndexedDbMutationQueue.prototype.getMutationQueueMetadata = function (transaction) {\r\n var _this = this;\r\n return mutationQueuesStore(transaction)\r\n .get(this.userId)\r\n .next(function (metadata) {\r\n return (metadata ||\r\n new DbMutationQueue(_this.userId, BATCHID_UNKNOWN, \r\n /*lastStreamToken=*/ ''));\r\n });\r\n };\r\n return IndexedDbMutationQueue;\r\n}());\r\n/**\r\n * @return true if the mutation queue for the given user contains a pending\r\n * mutation for the given key.\r\n */\r\nfunction mutationQueueContainsKey(txn, userId, key) {\r\n var indexKey = DbDocumentMutation.prefixForPath(userId, key.path);\r\n var encodedPath = indexKey[1];\r\n var startRange = IDBKeyRange.lowerBound(indexKey);\r\n var containsKey = false;\r\n return documentMutationsStore(txn)\r\n .iterate({ range: startRange, keysOnly: true }, function (key, value, control) {\r\n var userID = key[0], keyPath = key[1], /*batchID*/ _ = key[2];\r\n if (userID === userId && keyPath === encodedPath) {\r\n containsKey = true;\r\n }\r\n control.done();\r\n })\r\n .next(function () { return containsKey; });\r\n}\r\n/** Returns true if any mutation queue contains the given document. */\r\nfunction mutationQueuesContainKey(txn, docKey) {\r\n var found = false;\r\n return mutationQueuesStore(txn)\r\n .iterateSerial(function (userId) {\r\n return mutationQueueContainsKey(txn, userId, docKey).next(function (containsKey) {\r\n if (containsKey) {\r\n found = true;\r\n }\r\n return PersistencePromise.resolve(!containsKey);\r\n });\r\n })\r\n .next(function () { return found; });\r\n}\r\n/**\r\n * Delete a mutation batch and the associated document mutations.\r\n * @return A PersistencePromise of the document mutations that were removed.\r\n */\r\nfunction removeMutationBatch(txn, userId, batch) {\r\n var mutationStore = txn.store(DbMutationBatch.store);\r\n var indexTxn = txn.store(DbDocumentMutation.store);\r\n var promises = [];\r\n var range = IDBKeyRange.only(batch.batchId);\r\n var numDeleted = 0;\r\n var removePromise = mutationStore.iterate({ range: range }, function (key, value, control) {\r\n numDeleted++;\r\n return control.delete();\r\n });\r\n promises.push(removePromise.next(function () {\r\n assert(numDeleted === 1, 'Dangling document-mutation reference found: Missing batch ' +\r\n batch.batchId);\r\n }));\r\n var removedDocuments = [];\r\n for (var _i = 0, _a = batch.mutations; _i < _a.length; _i++) {\r\n var mutation = _a[_i];\r\n var indexKey = DbDocumentMutation.key(userId, mutation.key.path, batch.batchId);\r\n promises.push(indexTxn.delete(indexKey));\r\n removedDocuments.push(mutation.key);\r\n }\r\n return PersistencePromise.waitFor(promises).next(function () { return removedDocuments; });\r\n}\r\nfunction convertStreamToken(token) {\r\n if (token instanceof Uint8Array) {\r\n // TODO(b/78771403): Convert tokens to strings during deserialization\r\n assert(process.env.USE_MOCK_PERSISTENCE === 'YES', 'Persisting non-string stream tokens is only supported with mock persistence.');\r\n return token.toString();\r\n }\r\n else {\r\n return token;\r\n }\r\n}\r\n/**\r\n * Helper to get a typed SimpleDbStore for the mutations object store.\r\n */\r\nfunction mutationsStore(txn) {\r\n return IndexedDbPersistence.getStore(txn, DbMutationBatch.store);\r\n}\r\n/**\r\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\r\n */\r\nfunction documentMutationsStore(txn) {\r\n return IndexedDbPersistence.getStore(txn, DbDocumentMutation.store);\r\n}\r\n/**\r\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\r\n */\r\nfunction mutationQueuesStore(txn) {\r\n return IndexedDbPersistence.getStore(txn, DbMutationQueue.store);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar RESERVED_BITS = 1;\r\nvar GeneratorIds;\r\n(function (GeneratorIds) {\r\n GeneratorIds[GeneratorIds[\"QueryCache\"] = 0] = \"QueryCache\";\r\n GeneratorIds[GeneratorIds[\"SyncEngine\"] = 1] = \"SyncEngine\"; // The target IDs for limbo detection are odd (end in 1).\r\n})(GeneratorIds || (GeneratorIds = {}));\r\n/**\r\n * Generates monotonically increasing target IDs for sending targets to the\r\n * watch stream.\r\n *\r\n * The client constructs two generators, one for the query cache (via\r\n * forQueryCache()), and one for limbo documents (via forSyncEngine()). These\r\n * two generators produce non-overlapping IDs (by using even and odd IDs\r\n * respectively).\r\n *\r\n * By separating the target ID space, the query cache can generate target IDs\r\n * that persist across client restarts, while sync engine can independently\r\n * generate in-memory target IDs that are transient and can be reused after a\r\n * restart.\r\n */\r\n// TODO(mrschmidt): Explore removing this class in favor of generating these IDs\r\n// directly in SyncEngine and LocalStore.\r\nvar TargetIdGenerator = /** @class */ (function () {\r\n /**\r\n * Instantiates a new TargetIdGenerator. If a seed is provided, the generator\r\n * will use the seed value as the next target ID.\r\n */\r\n function TargetIdGenerator(generatorId, seed) {\r\n this.generatorId = generatorId;\r\n assert((generatorId & RESERVED_BITS) === generatorId, \"Generator ID \" + generatorId + \" contains more than \" + RESERVED_BITS + \" reserved bits\");\r\n this.seek(seed !== undefined ? seed : this.generatorId);\r\n }\r\n TargetIdGenerator.prototype.next = function () {\r\n var nextId = this.nextId;\r\n this.nextId += 1 << RESERVED_BITS;\r\n return nextId;\r\n };\r\n /**\r\n * Returns the ID that follows the given ID. Subsequent calls to `next()`\r\n * use the newly returned target ID as their base.\r\n */\r\n // PORTING NOTE: Multi-tab only.\r\n TargetIdGenerator.prototype.after = function (targetId) {\r\n this.seek(targetId + (1 << RESERVED_BITS));\r\n return this.next();\r\n };\r\n TargetIdGenerator.prototype.seek = function (targetId) {\r\n assert((targetId & RESERVED_BITS) === this.generatorId, 'Cannot supply target ID from different generator ID');\r\n this.nextId = targetId;\r\n };\r\n TargetIdGenerator.forQueryCache = function () {\r\n // We seed the query cache generator to return '2' as its first ID, as there\r\n // is no differentiation in the protocol layer between an unset number and\r\n // the number '0'. If we were to sent a target with target ID '0', the\r\n // backend would consider it unset and replace it with its own ID.\r\n var targetIdGenerator = new TargetIdGenerator(GeneratorIds.QueryCache, 2);\r\n return targetIdGenerator;\r\n };\r\n TargetIdGenerator.forSyncEngine = function () {\r\n // Sync engine assigns target IDs for limbo document detection.\r\n return new TargetIdGenerator(GeneratorIds.SyncEngine);\r\n };\r\n return TargetIdGenerator;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar LOG_TAG$1 = 'SimpleDb';\r\n/**\r\n * Provides a wrapper around IndexedDb with a simplified interface that uses\r\n * Promise-like return values to chain operations. Real promises cannot be used\r\n * since .then() continuations are executed asynchronously (e.g. via\r\n * .setImmediate), which would cause IndexedDB to end the transaction.\r\n * See PersistencePromise for more details.\r\n */\r\nvar SimpleDb = /** @class */ (function () {\r\n function SimpleDb(db) {\r\n this.db = db;\r\n }\r\n /**\r\n * Opens the specified database, creating or upgrading it if necessary.\r\n *\r\n * Note that `version` must not be a downgrade. IndexedDB does not support downgrading the schema\r\n * version. We currently do not support any way to do versioning outside of IndexedDB's versioning\r\n * mechanism, as only version-upgrade transactions are allowed to do things like create\r\n * objectstores.\r\n */\r\n SimpleDb.openOrCreate = function (name, version, schemaConverter) {\r\n assert(SimpleDb.isAvailable(), 'IndexedDB not supported in current environment.');\r\n debug(LOG_TAG$1, 'Opening database:', name);\r\n return new PersistencePromise(function (resolve, reject) {\r\n // TODO(mikelehen): Investigate browser compatibility.\r\n // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB\r\n // suggests IE9 and older WebKit browsers handle upgrade\r\n // differently. They expect setVersion, as described here:\r\n // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion\r\n var request = window.indexedDB.open(name, version);\r\n request.onsuccess = function (event) {\r\n var db = event.target.result;\r\n resolve(new SimpleDb(db));\r\n };\r\n request.onblocked = function () {\r\n reject(new FirestoreError(Code.FAILED_PRECONDITION, 'Cannot upgrade IndexedDB schema while another tab is open. ' +\r\n 'Close all tabs that access Firestore and reload this page to proceed.'));\r\n };\r\n request.onerror = function (event) {\r\n var error = event.target.error;\r\n if (error.name === 'VersionError') {\r\n reject(new FirestoreError(Code.FAILED_PRECONDITION, 'A newer version of the Firestore SDK was previously used and so the persisted ' +\r\n 'data is not compatible with the version of the SDK you are now using. The SDK ' +\r\n 'will operate with persistence disabled. If you need persistence, please ' +\r\n 're-upgrade to a newer version of the SDK or else clear the persisted IndexedDB ' +\r\n 'data for your app to start fresh.'));\r\n }\r\n else {\r\n reject(error);\r\n }\r\n };\r\n request.onupgradeneeded = function (event) {\r\n debug(LOG_TAG$1, 'Database \"' + name + '\" requires upgrade from version:', event.oldVersion);\r\n var db = event.target.result;\r\n // We are provided a version upgrade transaction from the request, so\r\n // we wrap that in a SimpleDbTransaction to allow use of our friendlier\r\n // API for schema migration operations.\r\n var txn = new SimpleDbTransaction(request.transaction);\r\n schemaConverter\r\n .createOrUpgrade(db, txn, event.oldVersion, SCHEMA_VERSION)\r\n .next(function () {\r\n debug(LOG_TAG$1, 'Database upgrade to version ' + SCHEMA_VERSION + ' complete');\r\n });\r\n };\r\n }).toPromise();\r\n };\r\n /** Deletes the specified database. */\r\n SimpleDb.delete = function (name) {\r\n debug(LOG_TAG$1, 'Removing database:', name);\r\n return wrapRequest(window.indexedDB.deleteDatabase(name)).toPromise();\r\n };\r\n /** Returns true if IndexedDB is available in the current environment. */\r\n SimpleDb.isAvailable = function () {\r\n if (typeof window === 'undefined' || window.indexedDB == null) {\r\n return false;\r\n }\r\n // We extensively use indexed array values and compound keys,\r\n // which IE and Edge do not support. However, they still have indexedDB\r\n // defined on the window, so we need to check for them here and make sure\r\n // to return that persistence is not enabled for those browsers.\r\n // For tracking support of this feature, see here:\r\n // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/\r\n // If we are running in Node using the IndexedDBShim, `window` is defined,\r\n // but `window.navigator` is not. In this case, we support IndexedDB and\r\n // return `true`.\r\n if (window.navigator === undefined) {\r\n return process.env.USE_MOCK_PERSISTENCE === 'YES';\r\n }\r\n // Check the UA string to find out the browser.\r\n // TODO(mikelehen): Move this logic into packages/util/environment.ts\r\n var ua = window.navigator.userAgent;\r\n // IE 10\r\n // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';\r\n // IE 11\r\n // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';\r\n // Edge\r\n // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,\r\n // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';\r\n // iOS Safari: Disable for users running iOS version < 10.\r\n var iOSVersion = SimpleDb.getIOSVersion(ua);\r\n var isUnsupportedIOS = 0 < iOSVersion && iOSVersion < 10;\r\n // Android browser: Disable for userse running version < 4.5.\r\n var androidVersion = SimpleDb.getAndroidVersion(ua);\r\n var isUnsupportedAndroid = 0 < androidVersion && androidVersion < 4.5;\r\n if (ua.indexOf('MSIE ') > 0 ||\r\n ua.indexOf('Trident/') > 0 ||\r\n ua.indexOf('Edge/') > 0 ||\r\n isUnsupportedIOS ||\r\n isUnsupportedAndroid) {\r\n return false;\r\n }\r\n else {\r\n return true;\r\n }\r\n };\r\n /** Helper to get a typed SimpleDbStore from a transaction. */\r\n SimpleDb.getStore = function (txn, store) {\r\n return txn.store(store);\r\n };\r\n // visible for testing\r\n /** Parse User Agent to determine iOS version. Returns -1 if not found. */\r\n SimpleDb.getIOSVersion = function (ua) {\r\n var iOSVersionRegex = ua.match(/i(?:phone|pad|pod) os ([\\d_]+)/i);\r\n var version = iOSVersionRegex ? iOSVersionRegex[1].split('_')[0] : '-1';\r\n return Number(version);\r\n };\r\n // visible for testing\r\n /** Parse User Agent to determine Android version. Returns -1 if not found. */\r\n SimpleDb.getAndroidVersion = function (ua) {\r\n var androidVersionRegex = ua.match(/Android ([\\d.]+)/i);\r\n var version = androidVersionRegex\r\n ? androidVersionRegex[1]\r\n .split('.')\r\n .slice(0, 2)\r\n .join('.')\r\n : '-1';\r\n return Number(version);\r\n };\r\n SimpleDb.prototype.runTransaction = function (mode, objectStores, transactionFn) {\r\n var transaction = SimpleDbTransaction.open(this.db, mode, objectStores);\r\n var transactionFnResult = transactionFn(transaction)\r\n .catch(function (error) {\r\n // Abort the transaction if there was an error.\r\n transaction.abort(error);\r\n // We cannot actually recover, and calling `abort()` will cause the transaction's\r\n // completion promise to be rejected. This in turn means that we won't use\r\n // `transactionFnResult` below. We return a rejection here so that we don't add the\r\n // possibility of returning `void` to the type of `transactionFnResult`.\r\n return PersistencePromise.reject(error);\r\n })\r\n .toPromise();\r\n // As noted above, errors are propagated by aborting the transaction. So\r\n // we swallow any error here to avoid the browser logging it as unhandled.\r\n transactionFnResult.catch(function () { });\r\n // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to\r\n // fire), but still return the original transactionFnResult back to the\r\n // caller.\r\n return transaction.completionPromise.then(function () { return transactionFnResult; });\r\n };\r\n SimpleDb.prototype.close = function () {\r\n this.db.close();\r\n };\r\n return SimpleDb;\r\n}());\r\n/**\r\n * A controller for iterating over a key range or index. It allows an iterate\r\n * callback to delete the currently-referenced object, or jump to a new key\r\n * within the key range or index.\r\n */\r\nvar IterationController = /** @class */ (function () {\r\n function IterationController(dbCursor) {\r\n this.dbCursor = dbCursor;\r\n this.shouldStop = false;\r\n this.nextKey = null;\r\n }\r\n Object.defineProperty(IterationController.prototype, \"isDone\", {\r\n get: function () {\r\n return this.shouldStop;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(IterationController.prototype, \"skipToKey\", {\r\n get: function () {\r\n return this.nextKey;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(IterationController.prototype, \"cursor\", {\r\n set: function (value) {\r\n this.dbCursor = value;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n /**\r\n * This function can be called to stop iteration at any point.\r\n */\r\n IterationController.prototype.done = function () {\r\n this.shouldStop = true;\r\n };\r\n /**\r\n * This function can be called to skip to that next key, which could be\r\n * an index or a primary key.\r\n */\r\n IterationController.prototype.skip = function (key) {\r\n this.nextKey = key;\r\n };\r\n /**\r\n * Delete the current cursor value from the object store.\r\n *\r\n * NOTE: You CANNOT do this with a keysOnly query.\r\n */\r\n IterationController.prototype.delete = function () {\r\n return wrapRequest(this.dbCursor.delete());\r\n };\r\n return IterationController;\r\n}());\r\n/**\r\n * Wraps an IDBTransaction and exposes a store() method to get a handle to a\r\n * specific object store.\r\n */\r\nvar SimpleDbTransaction = /** @class */ (function () {\r\n function SimpleDbTransaction(transaction) {\r\n var _this = this;\r\n this.transaction = transaction;\r\n this.aborted = false;\r\n /**\r\n * A promise that resolves with the result of the IndexedDb transaction.\r\n */\r\n this.completionDeferred = new Deferred();\r\n this.transaction.oncomplete = function () {\r\n _this.completionDeferred.resolve();\r\n };\r\n this.transaction.onabort = function () {\r\n if (transaction.error) {\r\n _this.completionDeferred.reject(transaction.error);\r\n }\r\n else {\r\n _this.completionDeferred.resolve();\r\n }\r\n };\r\n this.transaction.onerror = function (event) {\r\n _this.completionDeferred.reject(event.target.error);\r\n };\r\n }\r\n SimpleDbTransaction.open = function (db, mode, objectStoreNames) {\r\n return new SimpleDbTransaction(db.transaction(objectStoreNames, mode));\r\n };\r\n Object.defineProperty(SimpleDbTransaction.prototype, \"completionPromise\", {\r\n get: function () {\r\n return this.completionDeferred.promise;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n SimpleDbTransaction.prototype.abort = function (error) {\r\n if (error) {\r\n this.completionDeferred.reject(error);\r\n }\r\n if (!this.aborted) {\r\n debug(LOG_TAG$1, 'Aborting transaction:', error ? error.message : 'Client-initiated abort');\r\n this.aborted = true;\r\n this.transaction.abort();\r\n }\r\n };\r\n /**\r\n * Returns a SimpleDbStore for the specified store. All\r\n * operations performed on the SimpleDbStore happen within the context of this\r\n * transaction and it cannot be used anymore once the transaction is\r\n * completed.\r\n *\r\n * Note that we can't actually enforce that the KeyType and ValueType are\r\n * correct, but they allow type safety through the rest of the consuming code.\r\n */\r\n SimpleDbTransaction.prototype.store = function (storeName) {\r\n var store = this.transaction.objectStore(storeName);\r\n assert(!!store, 'Object store not part of transaction: ' + storeName);\r\n return new SimpleDbStore(store);\r\n };\r\n return SimpleDbTransaction;\r\n}());\r\n/**\r\n * A wrapper around an IDBObjectStore providing an API that:\r\n *\r\n * 1) Has generic KeyType / ValueType parameters to provide strongly-typed\r\n * methods for acting against the object store.\r\n * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every\r\n * method return a PersistencePromise instead.\r\n * 3) Provides a higher-level API to avoid needing to do excessive wrapping of\r\n * intermediate IndexedDB types (IDBCursorWithValue, etc.)\r\n */\r\nvar SimpleDbStore = /** @class */ (function () {\r\n function SimpleDbStore(store) {\r\n this.store = store;\r\n }\r\n SimpleDbStore.prototype.put = function (keyOrValue, value) {\r\n var request;\r\n if (value !== undefined) {\r\n debug(LOG_TAG$1, 'PUT', this.store.name, keyOrValue, value);\r\n request = this.store.put(value, keyOrValue);\r\n }\r\n else {\r\n debug(LOG_TAG$1, 'PUT', this.store.name, '', keyOrValue);\r\n request = this.store.put(keyOrValue);\r\n }\r\n return wrapRequest(request);\r\n };\r\n /**\r\n * Adds a new value into an Object Store and returns the new key. Similar to\r\n * IndexedDb's `add()`, this method will fail on primary key collisions.\r\n *\r\n * @param value The object to write.\r\n * @return The key of the value to add.\r\n */\r\n SimpleDbStore.prototype.add = function (value) {\r\n debug(LOG_TAG$1, 'ADD', this.store.name, value, value);\r\n var request = this.store.add(value);\r\n return wrapRequest(request);\r\n };\r\n /**\r\n * Gets the object with the specified key from the specified store, or null\r\n * if no object exists with the specified key.\r\n *\r\n * @key The key of the object to get.\r\n * @return The object with the specified key or null if no object exists.\r\n */\r\n SimpleDbStore.prototype.get = function (key) {\r\n var _this = this;\r\n var request = this.store.get(key);\r\n // tslint:disable-next-line:no-any We're doing an unsafe cast to ValueType.\r\n return wrapRequest(request).next(function (result) {\r\n // Normalize nonexistence to null.\r\n if (result === undefined) {\r\n result = null;\r\n }\r\n debug(LOG_TAG$1, 'GET', _this.store.name, key, result);\r\n return result;\r\n });\r\n };\r\n SimpleDbStore.prototype.delete = function (key) {\r\n debug(LOG_TAG$1, 'DELETE', this.store.name, key);\r\n var request = this.store.delete(key);\r\n return wrapRequest(request);\r\n };\r\n /**\r\n * If we ever need more of the count variants, we can add overloads. For now,\r\n * all we need is to count everything in a store.\r\n *\r\n * Returns the number of rows in the store.\r\n */\r\n SimpleDbStore.prototype.count = function () {\r\n debug(LOG_TAG$1, 'COUNT', this.store.name);\r\n var request = this.store.count();\r\n return wrapRequest(request);\r\n };\r\n SimpleDbStore.prototype.loadAll = function (indexOrRange, range) {\r\n var cursor = this.cursor(this.options(indexOrRange, range));\r\n var results = [];\r\n return this.iterateCursor(cursor, function (key, value) {\r\n results.push(value);\r\n }).next(function () {\r\n return results;\r\n });\r\n };\r\n SimpleDbStore.prototype.deleteAll = function (indexOrRange, range) {\r\n debug(LOG_TAG$1, 'DELETE ALL', this.store.name);\r\n var options = this.options(indexOrRange, range);\r\n options.keysOnly = false;\r\n var cursor = this.cursor(options);\r\n return this.iterateCursor(cursor, function (key, value, control) {\r\n // NOTE: Calling delete() on a cursor is documented as more efficient than\r\n // calling delete() on an object store with a single key\r\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete),\r\n // however, this requires us *not* to use a keysOnly cursor\r\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/delete). We\r\n // may want to compare the performance of each method.\r\n return control.delete();\r\n });\r\n };\r\n SimpleDbStore.prototype.iterate = function (optionsOrCallback, callback) {\r\n var options;\r\n if (!callback) {\r\n options = {};\r\n callback = optionsOrCallback;\r\n }\r\n else {\r\n options = optionsOrCallback;\r\n }\r\n var cursor = this.cursor(options);\r\n return this.iterateCursor(cursor, callback);\r\n };\r\n /**\r\n * Iterates over a store, but waits for the given callback to complete for\r\n * each entry before iterating the next entry. This allows the callback to do\r\n * asynchronous work to determine if this iteration should continue.\r\n *\r\n * The provided callback should return `true` to continue iteration, and\r\n * `false` otherwise.\r\n */\r\n SimpleDbStore.prototype.iterateSerial = function (callback) {\r\n var cursorRequest = this.cursor({});\r\n return new PersistencePromise(function (resolve, reject) {\r\n cursorRequest.onerror = function (event) {\r\n reject(event.target.error);\r\n };\r\n cursorRequest.onsuccess = function (event) {\r\n var cursor = event.target.result;\r\n if (!cursor) {\r\n resolve();\r\n return;\r\n }\r\n callback(cursor.primaryKey, cursor.value).next(function (shouldContinue) {\r\n if (shouldContinue) {\r\n cursor.continue();\r\n }\r\n else {\r\n resolve();\r\n }\r\n });\r\n };\r\n });\r\n };\r\n SimpleDbStore.prototype.iterateCursor = function (cursorRequest, fn) {\r\n var results = [];\r\n return new PersistencePromise(function (resolve, reject) {\r\n cursorRequest.onerror = function (event) {\r\n reject(event.target.error);\r\n };\r\n cursorRequest.onsuccess = function (event) {\r\n var cursor = event.target.result;\r\n if (!cursor) {\r\n resolve();\r\n return;\r\n }\r\n var controller = new IterationController(cursor);\r\n var userResult = fn(cursor.primaryKey, cursor.value, controller);\r\n if (userResult instanceof PersistencePromise) {\r\n var userPromise = userResult.catch(function (err) {\r\n controller.done();\r\n return PersistencePromise.reject(err);\r\n });\r\n results.push(userPromise);\r\n }\r\n if (controller.isDone) {\r\n resolve();\r\n }\r\n else if (controller.skipToKey === null) {\r\n cursor.continue();\r\n }\r\n else {\r\n cursor.continue(controller.skipToKey);\r\n }\r\n };\r\n }).next(function () {\r\n return PersistencePromise.waitFor(results);\r\n });\r\n };\r\n SimpleDbStore.prototype.options = function (indexOrRange, range) {\r\n var indexName = undefined;\r\n if (indexOrRange !== undefined) {\r\n if (typeof indexOrRange === 'string') {\r\n indexName = indexOrRange;\r\n }\r\n else {\r\n assert(range === undefined, '3rd argument must not be defined if 2nd is a range.');\r\n range = indexOrRange;\r\n }\r\n }\r\n return { index: indexName, range: range };\r\n };\r\n SimpleDbStore.prototype.cursor = function (options) {\r\n var direction = 'next';\r\n if (options.reverse) {\r\n direction = 'prev';\r\n }\r\n if (options.index) {\r\n var index = this.store.index(options.index);\r\n if (options.keysOnly) {\r\n return index.openKeyCursor(options.range, direction);\r\n }\r\n else {\r\n return index.openCursor(options.range, direction);\r\n }\r\n }\r\n else {\r\n return this.store.openCursor(options.range, direction);\r\n }\r\n };\r\n return SimpleDbStore;\r\n}());\r\n/**\r\n * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror\r\n * handlers to resolve / reject the PersistencePromise as appropriate.\r\n */\r\nfunction wrapRequest(request) {\r\n return new PersistencePromise(function (resolve, reject) {\r\n request.onsuccess = function (event) {\r\n var result = event.target.result;\r\n resolve(result);\r\n };\r\n request.onerror = function (event) {\r\n reject(event.target.error);\r\n };\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar IndexedDbQueryCache = /** @class */ (function () {\r\n function IndexedDbQueryCache(referenceDelegate, serializer) {\r\n this.referenceDelegate = referenceDelegate;\r\n this.serializer = serializer;\r\n // PORTING NOTE: We don't cache global metadata for the query cache, since\r\n // some of it (in particular `highestTargetId`) can be modified by secondary\r\n // tabs. We could perhaps be more granular (and e.g. still cache\r\n // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go\r\n // to IndexedDb whenever we need to read metadata. We can revisit if it turns\r\n // out to have a meaningful performance impact.\r\n this.targetIdGenerator = TargetIdGenerator.forQueryCache();\r\n }\r\n IndexedDbQueryCache.prototype.allocateTargetId = function (transaction) {\r\n var _this = this;\r\n return this.retrieveMetadata(transaction).next(function (metadata) {\r\n metadata.highestTargetId = _this.targetIdGenerator.after(metadata.highestTargetId);\r\n return _this.saveMetadata(transaction, metadata).next(function () { return metadata.highestTargetId; });\r\n });\r\n };\r\n IndexedDbQueryCache.prototype.getLastRemoteSnapshotVersion = function (transaction) {\r\n return this.retrieveMetadata(transaction).next(function (metadata) {\r\n return SnapshotVersion.fromTimestamp(new Timestamp(metadata.lastRemoteSnapshotVersion.seconds, metadata.lastRemoteSnapshotVersion.nanoseconds));\r\n });\r\n };\r\n IndexedDbQueryCache.prototype.getHighestSequenceNumber = function (transaction) {\r\n return getHighestListenSequenceNumber(transaction.simpleDbTransaction);\r\n };\r\n IndexedDbQueryCache.prototype.setTargetsMetadata = function (transaction, highestListenSequenceNumber, lastRemoteSnapshotVersion) {\r\n var _this = this;\r\n return this.retrieveMetadata(transaction).next(function (metadata) {\r\n metadata.highestListenSequenceNumber = highestListenSequenceNumber;\r\n if (lastRemoteSnapshotVersion) {\r\n metadata.lastRemoteSnapshotVersion = lastRemoteSnapshotVersion.toTimestamp();\r\n }\r\n if (highestListenSequenceNumber > metadata.highestListenSequenceNumber) {\r\n metadata.highestListenSequenceNumber = highestListenSequenceNumber;\r\n }\r\n return _this.saveMetadata(transaction, metadata);\r\n });\r\n };\r\n IndexedDbQueryCache.prototype.addQueryData = function (transaction, queryData) {\r\n var _this = this;\r\n return this.saveQueryData(transaction, queryData).next(function () {\r\n return _this.retrieveMetadata(transaction).next(function (metadata) {\r\n metadata.targetCount += 1;\r\n _this.updateMetadataFromQueryData(queryData, metadata);\r\n return _this.saveMetadata(transaction, metadata);\r\n });\r\n });\r\n };\r\n IndexedDbQueryCache.prototype.updateQueryData = function (transaction, queryData) {\r\n return this.saveQueryData(transaction, queryData);\r\n };\r\n IndexedDbQueryCache.prototype.removeQueryData = function (transaction, queryData) {\r\n var _this = this;\r\n return this.removeMatchingKeysForTargetId(transaction, queryData.targetId)\r\n .next(function () { return targetsStore(transaction).delete(queryData.targetId); })\r\n .next(function () { return _this.retrieveMetadata(transaction); })\r\n .next(function (metadata) {\r\n assert(metadata.targetCount > 0, 'Removing from an empty query cache');\r\n metadata.targetCount -= 1;\r\n return _this.saveMetadata(transaction, metadata);\r\n });\r\n };\r\n /**\r\n * Drops any targets with sequence number less than or equal to the upper bound, excepting those\r\n * present in `activeTargetIds`. Document associations for the removed targets are also removed.\r\n * Returns the number of targets removed.\r\n */\r\n IndexedDbQueryCache.prototype.removeTargets = function (txn, upperBound, activeTargetIds) {\r\n var _this = this;\r\n var count = 0;\r\n var promises = [];\r\n return targetsStore(txn)\r\n .iterate(function (key, value) {\r\n var queryData = _this.serializer.fromDbTarget(value);\r\n if (queryData.sequenceNumber <= upperBound &&\r\n activeTargetIds[queryData.targetId] === undefined) {\r\n count++;\r\n promises.push(_this.removeQueryData(txn, queryData));\r\n }\r\n })\r\n .next(function () { return PersistencePromise.waitFor(promises); })\r\n .next(function () { return count; });\r\n };\r\n /**\r\n * Call provided function with each `QueryData` that we have cached.\r\n */\r\n IndexedDbQueryCache.prototype.forEachTarget = function (txn, f) {\r\n var _this = this;\r\n return targetsStore(txn).iterate(function (key, value) {\r\n var queryData = _this.serializer.fromDbTarget(value);\r\n f(queryData);\r\n });\r\n };\r\n IndexedDbQueryCache.prototype.retrieveMetadata = function (transaction) {\r\n return retrieveMetadata(transaction.simpleDbTransaction);\r\n };\r\n IndexedDbQueryCache.prototype.saveMetadata = function (transaction, metadata) {\r\n return globalTargetStore(transaction).put(DbTargetGlobal.key, metadata);\r\n };\r\n IndexedDbQueryCache.prototype.saveQueryData = function (transaction, queryData) {\r\n return targetsStore(transaction).put(this.serializer.toDbTarget(queryData));\r\n };\r\n /**\r\n * In-place updates the provided metadata to account for values in the given\r\n * QueryData. Saving is done separately. Returns true if there were any\r\n * changes to the metadata.\r\n */\r\n IndexedDbQueryCache.prototype.updateMetadataFromQueryData = function (queryData, metadata) {\r\n var updated = false;\r\n if (queryData.targetId > metadata.highestTargetId) {\r\n metadata.highestTargetId = queryData.targetId;\r\n updated = true;\r\n }\r\n if (queryData.sequenceNumber > metadata.highestListenSequenceNumber) {\r\n metadata.highestListenSequenceNumber = queryData.sequenceNumber;\r\n updated = true;\r\n }\r\n return updated;\r\n };\r\n IndexedDbQueryCache.prototype.getQueryCount = function (transaction) {\r\n return this.retrieveMetadata(transaction).next(function (metadata) { return metadata.targetCount; });\r\n };\r\n IndexedDbQueryCache.prototype.getQueryData = function (transaction, query) {\r\n var _this = this;\r\n // Iterating by the canonicalId may yield more than one result because\r\n // canonicalId values are not required to be unique per target. This query\r\n // depends on the queryTargets index to be efficient.\r\n var canonicalId = query.canonicalId();\r\n var range = IDBKeyRange.bound([canonicalId, Number.NEGATIVE_INFINITY], [canonicalId, Number.POSITIVE_INFINITY]);\r\n var result = null;\r\n return targetsStore(transaction)\r\n .iterate({ range: range, index: DbTarget.queryTargetsIndexName }, function (key, value, control) {\r\n var found = _this.serializer.fromDbTarget(value);\r\n // After finding a potential match, check that the query is\r\n // actually equal to the requested query.\r\n if (query.isEqual(found.query)) {\r\n result = found;\r\n control.done();\r\n }\r\n })\r\n .next(function () { return result; });\r\n };\r\n IndexedDbQueryCache.prototype.addMatchingKeys = function (txn, keys, targetId) {\r\n var _this = this;\r\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\r\n // IndexedDb.\r\n var promises = [];\r\n var store = documentTargetStore(txn);\r\n keys.forEach(function (key) {\r\n var path = encode(key.path);\r\n promises.push(store.put(new DbTargetDocument(targetId, path)));\r\n promises.push(_this.referenceDelegate.addReference(txn, key));\r\n });\r\n return PersistencePromise.waitFor(promises);\r\n };\r\n IndexedDbQueryCache.prototype.removeMatchingKeys = function (txn, keys, targetId) {\r\n var _this = this;\r\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\r\n // IndexedDb.\r\n var store = documentTargetStore(txn);\r\n return PersistencePromise.forEach(keys, function (key) {\r\n var path = encode(key.path);\r\n return PersistencePromise.waitFor([\r\n store.delete([targetId, path]),\r\n _this.referenceDelegate.removeReference(txn, key)\r\n ]);\r\n });\r\n };\r\n IndexedDbQueryCache.prototype.removeMatchingKeysForTargetId = function (txn, targetId) {\r\n var store = documentTargetStore(txn);\r\n var range = IDBKeyRange.bound([targetId], [targetId + 1], \r\n /*lowerOpen=*/ false, \r\n /*upperOpen=*/ true);\r\n return store.delete(range);\r\n };\r\n IndexedDbQueryCache.prototype.getMatchingKeysForTargetId = function (txn, targetId) {\r\n var range = IDBKeyRange.bound([targetId], [targetId + 1], \r\n /*lowerOpen=*/ false, \r\n /*upperOpen=*/ true);\r\n var store = documentTargetStore(txn);\r\n var result = documentKeySet();\r\n return store\r\n .iterate({ range: range, keysOnly: true }, function (key, _, control) {\r\n var path = decode(key[1]);\r\n var docKey = new DocumentKey(path);\r\n result = result.add(docKey);\r\n })\r\n .next(function () { return result; });\r\n };\r\n IndexedDbQueryCache.prototype.containsKey = function (txn, key) {\r\n var path = encode(key.path);\r\n var range = IDBKeyRange.bound([path], [immediateSuccessor(path)], \r\n /*lowerOpen=*/ false, \r\n /*upperOpen=*/ true);\r\n var count = 0;\r\n return documentTargetStore(txn)\r\n .iterate({\r\n index: DbTargetDocument.documentTargetsIndex,\r\n keysOnly: true,\r\n range: range\r\n }, function (_a, _, control) {\r\n var targetId = _a[0], path = _a[1];\r\n // Having a sentinel row for a document does not count as containing that document;\r\n // For the query cache, containing the document means the document is part of some\r\n // target.\r\n if (targetId !== 0) {\r\n count++;\r\n control.done();\r\n }\r\n })\r\n .next(function () { return count > 0; });\r\n };\r\n IndexedDbQueryCache.prototype.getQueryDataForTarget = function (transaction, targetId) {\r\n var _this = this;\r\n return targetsStore(transaction)\r\n .get(targetId)\r\n .next(function (found) {\r\n if (found) {\r\n return _this.serializer.fromDbTarget(found);\r\n }\r\n else {\r\n return null;\r\n }\r\n });\r\n };\r\n return IndexedDbQueryCache;\r\n}());\r\n/**\r\n * Helper to get a typed SimpleDbStore for the queries object store.\r\n */\r\nfunction targetsStore(txn) {\r\n return IndexedDbPersistence.getStore(txn, DbTarget.store);\r\n}\r\n/**\r\n * Helper to get a typed SimpleDbStore for the target globals object store.\r\n */\r\nfunction globalTargetStore(txn) {\r\n return IndexedDbPersistence.getStore(txn, DbTargetGlobal.store);\r\n}\r\nfunction retrieveMetadata(txn) {\r\n var globalStore = SimpleDb.getStore(txn, DbTargetGlobal.store);\r\n return globalStore.get(DbTargetGlobal.key).next(function (metadata) {\r\n assert(metadata !== null, 'Missing metadata row.');\r\n return metadata;\r\n });\r\n}\r\nfunction getHighestListenSequenceNumber(txn) {\r\n return retrieveMetadata(txn).next(function (targetGlobal) { return targetGlobal.highestListenSequenceNumber; });\r\n}\r\n/**\r\n * Helper to get a typed SimpleDbStore for the document target object store.\r\n */\r\nfunction documentTargetStore(txn) {\r\n return IndexedDbPersistence.getStore(txn, DbTargetDocument.store);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A map implementation that uses objects as keys. Objects must implement the\r\n * Equatable interface and must be immutable. Entries in the map are stored\r\n * together with the key being produced from the mapKeyFn. This map\r\n * automatically handles collisions of keys.\r\n */\r\nvar ObjectMap = /** @class */ (function () {\r\n function ObjectMap(mapKeyFn) {\r\n this.mapKeyFn = mapKeyFn;\r\n /**\r\n * The inner map for a key -> value pair. Due to the possibility of\r\n * collisions we keep a list of entries that we do a linear search through\r\n * to find an actual match. Note that collisions should be rare, so we still\r\n * expect near constant time lookups in practice.\r\n */\r\n this.inner = {};\r\n }\r\n /** Get a value for this key, or undefined if it does not exist. */\r\n ObjectMap.prototype.get = function (key) {\r\n var id = this.mapKeyFn(key);\r\n var matches = this.inner[id];\r\n if (matches === undefined) {\r\n return undefined;\r\n }\r\n for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) {\r\n var _a = matches_1[_i], otherKey = _a[0], value = _a[1];\r\n if (otherKey.isEqual(key)) {\r\n return value;\r\n }\r\n }\r\n return undefined;\r\n };\r\n ObjectMap.prototype.has = function (key) {\r\n return this.get(key) !== undefined;\r\n };\r\n /** Put this key and value in the map. */\r\n ObjectMap.prototype.set = function (key, value) {\r\n var id = this.mapKeyFn(key);\r\n var matches = this.inner[id];\r\n if (matches === undefined) {\r\n this.inner[id] = [[key, value]];\r\n return;\r\n }\r\n for (var i = 0; i < matches.length; i++) {\r\n if (matches[i][0].isEqual(key)) {\r\n matches[i] = [key, value];\r\n return;\r\n }\r\n }\r\n matches.push([key, value]);\r\n };\r\n /**\r\n * Remove this key from the map. Returns a boolean if anything was deleted.\r\n */\r\n ObjectMap.prototype.delete = function (key) {\r\n var id = this.mapKeyFn(key);\r\n var matches = this.inner[id];\r\n if (matches === undefined) {\r\n return false;\r\n }\r\n for (var i = 0; i < matches.length; i++) {\r\n if (matches[i][0].isEqual(key)) {\r\n if (matches.length === 1) {\r\n delete this.inner[id];\r\n }\r\n else {\r\n matches.splice(i, 1);\r\n }\r\n return true;\r\n }\r\n }\r\n return false;\r\n };\r\n ObjectMap.prototype.forEach = function (fn) {\r\n forEach(this.inner, function (_, entries) {\r\n for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {\r\n var _a = entries_1[_i], k = _a[0], v = _a[1];\r\n fn(k, v);\r\n }\r\n });\r\n };\r\n ObjectMap.prototype.isEmpty = function () {\r\n return isEmpty(this.inner);\r\n };\r\n return ObjectMap;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An in-memory buffer of entries to be written to a RemoteDocumentCache.\r\n * It can be used to batch up a set of changes to be written to the cache, but\r\n * additionally supports reading entries back with the `getEntry()` method,\r\n * falling back to the underlying RemoteDocumentCache if no entry is\r\n * buffered.\r\n *\r\n * Entries added to the cache *must* be read first. This is to facilitate\r\n * calculating the size delta of the pending changes.\r\n *\r\n * PORTING NOTE: This class was implemented then removed from other platforms.\r\n * If byte-counting ends up being needed on the other platforms, consider\r\n * porting this class as part of that implementation work.\r\n */\r\nvar RemoteDocumentChangeBuffer = /** @class */ (function () {\r\n function RemoteDocumentChangeBuffer() {\r\n this.changes = maybeDocumentMap();\r\n this.documentSizes = new ObjectMap(function (key) {\r\n return key.toString();\r\n });\r\n }\r\n /** Buffers a `RemoteDocumentCache.addEntry()` call. */\r\n RemoteDocumentChangeBuffer.prototype.addEntry = function (maybeDocument) {\r\n var changes = this.assertChanges();\r\n this.changes = changes.insert(maybeDocument.key, maybeDocument);\r\n };\r\n // NOTE: removeEntry() is intentionally omitted. If it needs to be added in\r\n // the future it must take byte counting into account.\r\n /**\r\n * Looks up an entry in the cache. The buffered changes will first be checked,\r\n * and if no buffered change applies, this will forward to\r\n * `RemoteDocumentCache.getEntry()`.\r\n *\r\n * @param transaction The transaction in which to perform any persistence\r\n * operations.\r\n * @param documentKey The key of the entry to look up.\r\n * @return The cached Document or NoDocument entry, or null if we have nothing\r\n * cached.\r\n */\r\n RemoteDocumentChangeBuffer.prototype.getEntry = function (transaction, documentKey) {\r\n var _this = this;\r\n var changes = this.assertChanges();\r\n var bufferedEntry = changes.get(documentKey);\r\n if (bufferedEntry) {\r\n return PersistencePromise.resolve(bufferedEntry);\r\n }\r\n else {\r\n // Record the size of everything we load from the cache so we can compute a delta later.\r\n return this.getFromCache(transaction, documentKey).next(function (getResult) {\r\n if (getResult === null) {\r\n _this.documentSizes.set(documentKey, 0);\r\n return null;\r\n }\r\n else {\r\n _this.documentSizes.set(documentKey, getResult.size);\r\n return getResult.maybeDocument;\r\n }\r\n });\r\n }\r\n };\r\n /**\r\n * Looks up several entries in the cache, forwarding to\r\n * `RemoteDocumentCache.getEntry()`.\r\n *\r\n * @param transaction The transaction in which to perform any persistence\r\n * operations.\r\n * @param documentKeys The keys of the entries to look up.\r\n * @return A map of cached `Document`s or `NoDocument`s, indexed by key. If an\r\n * entry cannot be found, the corresponding key will be mapped to a null\r\n * value.\r\n */\r\n RemoteDocumentChangeBuffer.prototype.getEntries = function (transaction, documentKeys) {\r\n var _this = this;\r\n // Record the size of everything we load from the cache so we can compute\r\n // a delta later.\r\n return this.getAllFromCache(transaction, documentKeys).next(function (_a) {\r\n var maybeDocuments = _a.maybeDocuments, sizeMap = _a.sizeMap;\r\n // Note: `getAllFromCache` returns two maps instead of a single map from\r\n // keys to `DocumentSizeEntry`s. This is to allow returning the\r\n // `NullableMaybeDocumentMap` directly, without a conversion.\r\n sizeMap.forEach(function (documentKey, size) {\r\n _this.documentSizes.set(documentKey, size);\r\n });\r\n return maybeDocuments;\r\n });\r\n };\r\n /**\r\n * Applies buffered changes to the underlying RemoteDocumentCache, using\r\n * the provided transaction.\r\n */\r\n RemoteDocumentChangeBuffer.prototype.apply = function (transaction) {\r\n var result = this.applyChanges(transaction);\r\n // We should not buffer any more changes.\r\n this.changes = null;\r\n return result;\r\n };\r\n /** Helper to assert this.changes is not null and return it. */\r\n RemoteDocumentChangeBuffer.prototype.assertChanges = function () {\r\n assert(this.changes !== null, 'Changes have already been applied.');\r\n return this.changes;\r\n };\r\n return RemoteDocumentChangeBuffer;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar REMOTE_DOCUMENT_CHANGE_MISSING_ERR_MSG = 'The remote document changelog no longer contains all changes for all ' +\r\n 'local query views. It may be necessary to rebuild these views.';\r\nvar IndexedDbRemoteDocumentCache = /** @class */ (function () {\r\n /**\r\n * @param {LocalSerializer} serializer The document serializer.\r\n * @param {IndexManager} indexManager The query indexes that need to be maintained.\r\n * @param keepDocumentChangeLog Whether to keep a document change log in\r\n * IndexedDb. This change log is required for Multi-Tab synchronization, but\r\n * not needed in clients that don't share access to their remote document\r\n * cache.\r\n */\r\n function IndexedDbRemoteDocumentCache(serializer, indexManager, keepDocumentChangeLog) {\r\n this.serializer = serializer;\r\n this.indexManager = indexManager;\r\n this.keepDocumentChangeLog = keepDocumentChangeLog;\r\n /** The last id read by `getNewDocumentChanges()`. */\r\n this._lastProcessedDocumentChangeId = 0;\r\n }\r\n Object.defineProperty(IndexedDbRemoteDocumentCache.prototype, \"lastProcessedDocumentChangeId\", {\r\n get: function () {\r\n return this._lastProcessedDocumentChangeId;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n /**\r\n * Starts up the remote document cache.\r\n *\r\n * Reads the ID of the last document change from the documentChanges store.\r\n * Existing changes will not be returned as part of\r\n * `getNewDocumentChanges()`.\r\n */\r\n // PORTING NOTE: This is only used for multi-tab synchronization.\r\n IndexedDbRemoteDocumentCache.prototype.start = function (transaction) {\r\n var store = SimpleDb.getStore(transaction, DbRemoteDocumentChanges.store);\r\n return this.synchronizeLastDocumentChangeId(store);\r\n };\r\n /**\r\n * Adds the supplied entries to the cache. Adds the given size delta to the cached size.\r\n */\r\n IndexedDbRemoteDocumentCache.prototype.addEntries = function (transaction, entries, sizeDelta) {\r\n var promises = [];\r\n if (entries.length > 0) {\r\n var documentStore = remoteDocumentsStore(transaction);\r\n var changedKeys = documentKeySet();\r\n for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {\r\n var _a = entries_1[_i], key = _a.key, doc = _a.doc;\r\n promises.push(documentStore.put(dbKey(key), doc));\r\n changedKeys = changedKeys.add(key);\r\n promises.push(this.indexManager.addToCollectionParentIndex(transaction, key.path.popLast()));\r\n }\r\n if (this.keepDocumentChangeLog) {\r\n promises.push(documentChangesStore(transaction).put({\r\n changes: this.serializer.toDbResourcePaths(changedKeys)\r\n }));\r\n }\r\n promises.push(this.updateSize(transaction, sizeDelta));\r\n }\r\n return PersistencePromise.waitFor(promises);\r\n };\r\n /**\r\n * Removes a document from the cache. Note that this method does *not* do any\r\n * size accounting. It is the responsibility of the caller to count the bytes removed\r\n * and issue a final updateSize() call after removing documents.\r\n *\r\n * @param documentKey The key of the document to remove\r\n * @return The size of the document that was removed.\r\n */\r\n IndexedDbRemoteDocumentCache.prototype.removeEntry = function (transaction, documentKey) {\r\n // We don't need to keep changelog for these removals since `removeEntry` is\r\n // only used for garbage collection.\r\n var store = remoteDocumentsStore(transaction);\r\n var key = dbKey(documentKey);\r\n return store.get(key).next(function (document) {\r\n if (document) {\r\n return store.delete(key).next(function () { return dbDocumentSize(document); });\r\n }\r\n else {\r\n return PersistencePromise.resolve(0);\r\n }\r\n });\r\n };\r\n IndexedDbRemoteDocumentCache.prototype.getEntry = function (transaction, documentKey) {\r\n var _this = this;\r\n return remoteDocumentsStore(transaction)\r\n .get(dbKey(documentKey))\r\n .next(function (dbRemoteDoc) {\r\n return dbRemoteDoc\r\n ? _this.serializer.fromDbRemoteDocument(dbRemoteDoc)\r\n : null;\r\n });\r\n };\r\n /**\r\n * Looks up an entry in the cache.\r\n *\r\n * @param documentKey The key of the entry to look up.\r\n * @return The cached MaybeDocument entry and its size, or null if we have nothing cached.\r\n */\r\n IndexedDbRemoteDocumentCache.prototype.getSizedEntry = function (transaction, documentKey) {\r\n var _this = this;\r\n return remoteDocumentsStore(transaction)\r\n .get(dbKey(documentKey))\r\n .next(function (dbRemoteDoc) {\r\n return dbRemoteDoc\r\n ? {\r\n maybeDocument: _this.serializer.fromDbRemoteDocument(dbRemoteDoc),\r\n size: dbDocumentSize(dbRemoteDoc)\r\n }\r\n : null;\r\n });\r\n };\r\n IndexedDbRemoteDocumentCache.prototype.getEntries = function (transaction, documentKeys) {\r\n var _this = this;\r\n var results = nullableMaybeDocumentMap();\r\n return this.forEachDbEntry(transaction, documentKeys, function (key, dbRemoteDoc) {\r\n if (dbRemoteDoc) {\r\n results = results.insert(key, _this.serializer.fromDbRemoteDocument(dbRemoteDoc));\r\n }\r\n else {\r\n results = results.insert(key, null);\r\n }\r\n }).next(function () { return results; });\r\n };\r\n /**\r\n * Looks up several entries in the cache.\r\n *\r\n * @param documentKeys The set of keys entries to look up.\r\n * @return A map of MaybeDocuments indexed by key (if a document cannot be\r\n * found, the key will be mapped to null) and a map of sizes indexed by\r\n * key (zero if the key cannot be found).\r\n */\r\n IndexedDbRemoteDocumentCache.prototype.getSizedEntries = function (transaction, documentKeys) {\r\n var _this = this;\r\n var results = nullableMaybeDocumentMap();\r\n var sizeMap = new SortedMap(DocumentKey.comparator);\r\n return this.forEachDbEntry(transaction, documentKeys, function (key, dbRemoteDoc) {\r\n if (dbRemoteDoc) {\r\n results = results.insert(key, _this.serializer.fromDbRemoteDocument(dbRemoteDoc));\r\n sizeMap = sizeMap.insert(key, dbDocumentSize(dbRemoteDoc));\r\n }\r\n else {\r\n results = results.insert(key, null);\r\n sizeMap = sizeMap.insert(key, 0);\r\n }\r\n }).next(function () {\r\n return { maybeDocuments: results, sizeMap: sizeMap };\r\n });\r\n };\r\n IndexedDbRemoteDocumentCache.prototype.forEachDbEntry = function (transaction, documentKeys, callback) {\r\n if (documentKeys.isEmpty()) {\r\n return PersistencePromise.resolve();\r\n }\r\n var range = IDBKeyRange.bound(documentKeys.first().path.toArray(), documentKeys.last().path.toArray());\r\n var keyIter = documentKeys.getIterator();\r\n var nextKey = keyIter.getNext();\r\n return remoteDocumentsStore(transaction)\r\n .iterate({ range: range }, function (potentialKeyRaw, dbRemoteDoc, control) {\r\n var potentialKey = DocumentKey.fromSegments(potentialKeyRaw);\r\n // Go through keys not found in cache.\r\n while (nextKey && DocumentKey.comparator(nextKey, potentialKey) < 0) {\r\n callback(nextKey, null);\r\n nextKey = keyIter.getNext();\r\n }\r\n if (nextKey && nextKey.isEqual(potentialKey)) {\r\n // Key found in cache.\r\n callback(nextKey, dbRemoteDoc);\r\n nextKey = keyIter.hasNext() ? keyIter.getNext() : null;\r\n }\r\n // Skip to the next key (if there is one).\r\n if (nextKey) {\r\n control.skip(nextKey.path.toArray());\r\n }\r\n else {\r\n control.done();\r\n }\r\n })\r\n .next(function () {\r\n // The rest of the keys are not in the cache. One case where `iterate`\r\n // above won't go through them is when the cache is empty.\r\n while (nextKey) {\r\n callback(nextKey, null);\r\n nextKey = keyIter.hasNext() ? keyIter.getNext() : null;\r\n }\r\n });\r\n };\r\n IndexedDbRemoteDocumentCache.prototype.getDocumentsMatchingQuery = function (transaction, query) {\r\n var _this = this;\r\n assert(!query.isCollectionGroupQuery(), 'CollectionGroup queries should be handled in LocalDocumentsView');\r\n var results = documentMap();\r\n var immediateChildrenPathLength = query.path.length + 1;\r\n // Documents are ordered by key, so we can use a prefix scan to narrow down\r\n // the documents we need to match the query against.\r\n var startKey = query.path.toArray();\r\n var range = IDBKeyRange.lowerBound(startKey);\r\n return remoteDocumentsStore(transaction)\r\n .iterate({ range: range }, function (key, dbRemoteDoc, control) {\r\n // The query is actually returning any path that starts with the query\r\n // path prefix which may include documents in subcollections. For\r\n // example, a query on 'rooms' will return rooms/abc/messages/xyx but we\r\n // shouldn't match it. Fix this by discarding rows with document keys\r\n // more than one segment longer than the query path.\r\n if (key.length !== immediateChildrenPathLength) {\r\n return;\r\n }\r\n var maybeDoc = _this.serializer.fromDbRemoteDocument(dbRemoteDoc);\r\n if (!query.path.isPrefixOf(maybeDoc.key.path)) {\r\n control.done();\r\n }\r\n else if (maybeDoc instanceof Document && query.matches(maybeDoc)) {\r\n results = results.insert(maybeDoc.key, maybeDoc);\r\n }\r\n })\r\n .next(function () { return results; });\r\n };\r\n IndexedDbRemoteDocumentCache.prototype.getNewDocumentChanges = function (transaction) {\r\n var _this = this;\r\n assert(this.keepDocumentChangeLog, 'Can only call getNewDocumentChanges() when document change log is enabled');\r\n var changedKeys = documentKeySet();\r\n var changedDocs = maybeDocumentMap();\r\n var range = IDBKeyRange.lowerBound(this._lastProcessedDocumentChangeId + 1);\r\n var firstIteration = true;\r\n var changesStore = documentChangesStore(transaction);\r\n return changesStore\r\n .iterate({ range: range }, function (_, documentChange) {\r\n if (firstIteration) {\r\n firstIteration = false;\r\n // If our client was throttled for more than 30 minutes, another\r\n // client may have garbage collected the remote document changelog.\r\n if (_this._lastProcessedDocumentChangeId + 1 !== documentChange.id) {\r\n // Reset the `lastProcessedDocumentChangeId` to allow further\r\n // invocations to successfully return the changes after this\r\n // rejection.\r\n return _this.synchronizeLastDocumentChangeId(changesStore).next(function () {\r\n return PersistencePromise.reject(new FirestoreError(Code.DATA_LOSS, REMOTE_DOCUMENT_CHANGE_MISSING_ERR_MSG));\r\n });\r\n }\r\n }\r\n changedKeys = changedKeys.unionWith(_this.serializer.fromDbResourcePaths(documentChange.changes));\r\n _this._lastProcessedDocumentChangeId = documentChange.id;\r\n })\r\n .next(function () {\r\n var documentPromises = [];\r\n changedKeys.forEach(function (key) {\r\n documentPromises.push(_this.getEntry(transaction, key).next(function (maybeDocument) {\r\n var doc = maybeDocument ||\r\n new NoDocument(key, SnapshotVersion.forDeletedDoc());\r\n changedDocs = changedDocs.insert(key, doc);\r\n }));\r\n });\r\n return PersistencePromise.waitFor(documentPromises);\r\n })\r\n .next(function () { return changedDocs; });\r\n };\r\n /**\r\n * Removes all changes in the remote document changelog through `changeId`\r\n * (inclusive).\r\n */\r\n IndexedDbRemoteDocumentCache.prototype.removeDocumentChangesThroughChangeId = function (transaction, changeId) {\r\n var range = IDBKeyRange.upperBound(changeId);\r\n return documentChangesStore(transaction).delete(range);\r\n };\r\n IndexedDbRemoteDocumentCache.prototype.synchronizeLastDocumentChangeId = function (documentChangesStore) {\r\n var _this = this;\r\n // If there are no existing changes, we set `lastProcessedDocumentChangeId`\r\n // to 0 since IndexedDb's auto-generated keys start at 1.\r\n this._lastProcessedDocumentChangeId = 0;\r\n return documentChangesStore.iterate({ keysOnly: true, reverse: true }, function (key, value, control) {\r\n _this._lastProcessedDocumentChangeId = key;\r\n control.done();\r\n });\r\n };\r\n IndexedDbRemoteDocumentCache.prototype.newChangeBuffer = function () {\r\n return new IndexedDbRemoteDocumentChangeBuffer(this);\r\n };\r\n IndexedDbRemoteDocumentCache.prototype.getSize = function (txn) {\r\n return this.getMetadata(txn).next(function (metadata) { return metadata.byteSize; });\r\n };\r\n IndexedDbRemoteDocumentCache.prototype.getMetadata = function (txn) {\r\n return documentGlobalStore(txn)\r\n .get(DbRemoteDocumentGlobal.key)\r\n .next(function (metadata) {\r\n assert(!!metadata, 'Missing document cache metadata');\r\n return metadata;\r\n });\r\n };\r\n IndexedDbRemoteDocumentCache.prototype.setMetadata = function (txn, metadata) {\r\n return documentGlobalStore(txn).put(DbRemoteDocumentGlobal.key, metadata);\r\n };\r\n /**\r\n * Adds the given delta to the cached current size. Callers to removeEntry *must* call this\r\n * afterwards to update the size of the cache.\r\n *\r\n * @param sizeDelta\r\n */\r\n IndexedDbRemoteDocumentCache.prototype.updateSize = function (txn, sizeDelta) {\r\n var _this = this;\r\n return this.getMetadata(txn).next(function (metadata) {\r\n metadata.byteSize += sizeDelta;\r\n return _this.setMetadata(txn, metadata);\r\n });\r\n };\r\n return IndexedDbRemoteDocumentCache;\r\n}());\r\nfunction documentGlobalStore(txn) {\r\n return IndexedDbPersistence.getStore(txn, DbRemoteDocumentGlobal.store);\r\n}\r\n/**\r\n * Handles the details of adding and updating documents in the IndexedDbRemoteDocumentCache\r\n */\r\nvar IndexedDbRemoteDocumentChangeBuffer = /** @class */ (function (_super) {\r\n tslib_1.__extends(IndexedDbRemoteDocumentChangeBuffer, _super);\r\n function IndexedDbRemoteDocumentChangeBuffer(documentCache) {\r\n var _this = _super.call(this) || this;\r\n _this.documentCache = documentCache;\r\n return _this;\r\n }\r\n IndexedDbRemoteDocumentChangeBuffer.prototype.applyChanges = function (transaction) {\r\n var _this = this;\r\n var changes = this.assertChanges();\r\n var delta = 0;\r\n var toApply = [];\r\n changes.forEach(function (key, maybeDocument) {\r\n var doc = _this.documentCache.serializer.toDbRemoteDocument(maybeDocument);\r\n var previousSize = _this.documentSizes.get(key);\r\n // NOTE: if we ever decide we need to support doing writes without\r\n // reading first, this assert will need to change to do the read automatically.\r\n assert(previousSize !== undefined, \"Attempting to change document \" + key.toString() + \" without having read it first\");\r\n var size = dbDocumentSize(doc);\r\n delta += size - previousSize;\r\n toApply.push({ key: key, doc: doc });\r\n });\r\n return this.documentCache.addEntries(transaction, toApply, delta);\r\n };\r\n IndexedDbRemoteDocumentChangeBuffer.prototype.getFromCache = function (transaction, documentKey) {\r\n return this.documentCache.getSizedEntry(transaction, documentKey);\r\n };\r\n IndexedDbRemoteDocumentChangeBuffer.prototype.getAllFromCache = function (transaction, documentKeys) {\r\n return this.documentCache.getSizedEntries(transaction, documentKeys);\r\n };\r\n return IndexedDbRemoteDocumentChangeBuffer;\r\n}(RemoteDocumentChangeBuffer));\r\nfunction isDocumentChangeMissingError(err) {\r\n return (err.code === Code.DATA_LOSS &&\r\n err.message === REMOTE_DOCUMENT_CHANGE_MISSING_ERR_MSG);\r\n}\r\n/**\r\n * Helper to get a typed SimpleDbStore for the remoteDocuments object store.\r\n */\r\nfunction remoteDocumentsStore(txn) {\r\n return IndexedDbPersistence.getStore(txn, DbRemoteDocument.store);\r\n}\r\n/**\r\n * Helper to get a typed SimpleDbStore for the remoteDocumentChanges object\r\n * store.\r\n */\r\nfunction documentChangesStore(txn) {\r\n return IndexedDbPersistence.getStore(txn, DbRemoteDocumentChanges.store);\r\n}\r\nfunction dbKey(docKey) {\r\n return docKey.path.toArray();\r\n}\r\n/**\r\n * Retrusn an approximate size for the given document.\r\n */\r\nfunction dbDocumentSize(doc) {\r\n var value;\r\n if (doc.document) {\r\n value = doc.document;\r\n }\r\n else if (doc.unknownDocument) {\r\n value = doc.unknownDocument;\r\n }\r\n else if (doc.noDocument) {\r\n value = doc.noDocument;\r\n }\r\n else {\r\n throw fail('Unknown remote document type');\r\n }\r\n return JSON.stringify(value).length;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An in-memory implementation of IndexManager.\r\n */\r\nvar MemoryIndexManager = /** @class */ (function () {\r\n function MemoryIndexManager() {\r\n this.collectionParentIndex = new MemoryCollectionParentIndex();\r\n }\r\n MemoryIndexManager.prototype.addToCollectionParentIndex = function (transaction, collectionPath) {\r\n this.collectionParentIndex.add(collectionPath);\r\n return PersistencePromise.resolve();\r\n };\r\n MemoryIndexManager.prototype.getCollectionParents = function (transaction, collectionId) {\r\n return PersistencePromise.resolve(this.collectionParentIndex.getEntries(collectionId));\r\n };\r\n return MemoryIndexManager;\r\n}());\r\n/**\r\n * Internal implementation of the collection-parent index exposed by MemoryIndexManager.\r\n * Also used for in-memory caching by IndexedDbIndexManager and initial index population\r\n * in indexeddb_schema.ts\r\n */\r\nvar MemoryCollectionParentIndex = /** @class */ (function () {\r\n function MemoryCollectionParentIndex() {\r\n this.index = {};\r\n }\r\n // Returns false if the entry already existed.\r\n MemoryCollectionParentIndex.prototype.add = function (collectionPath) {\r\n assert(collectionPath.length % 2 === 1, 'Expected a collection path.');\r\n var collectionId = collectionPath.lastSegment();\r\n var parentPath = collectionPath.popLast();\r\n var existingParents = this.index[collectionId] ||\r\n new SortedSet(ResourcePath.comparator);\r\n var added = !existingParents.has(parentPath);\r\n this.index[collectionId] = existingParents.add(parentPath);\r\n return added;\r\n };\r\n MemoryCollectionParentIndex.prototype.getEntries = function (collectionId) {\r\n var parentPaths = this.index[collectionId] ||\r\n new SortedSet(ResourcePath.comparator);\r\n return parentPaths.toArray();\r\n };\r\n return MemoryCollectionParentIndex;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Schema Version for the Web client:\r\n * 1. Initial version including Mutation Queue, Query Cache, and Remote Document\r\n * Cache\r\n * 2. Used to ensure a targetGlobal object exists and add targetCount to it. No\r\n * longer required because migration 3 unconditionally clears it.\r\n * 3. Dropped and re-created Query Cache to deal with cache corruption related\r\n * to limbo resolution. Addresses\r\n * https://github.com/firebase/firebase-ios-sdk/issues/1548\r\n * 4. Multi-Tab Support.\r\n * 5. Removal of held write acks.\r\n * 6. Create document global for tracking document cache size.\r\n * 7. Ensure every cached document has a sentinel row with a sequence number.\r\n * 8. Add collection-parent index for Collection Group queries.\r\n */\r\nvar SCHEMA_VERSION = 8;\r\n/** Performs database creation and schema upgrades. */\r\nvar SchemaConverter = /** @class */ (function () {\r\n function SchemaConverter(serializer) {\r\n this.serializer = serializer;\r\n }\r\n /**\r\n * Performs database creation and schema upgrades.\r\n *\r\n * Note that in production, this method is only ever used to upgrade the schema\r\n * to SCHEMA_VERSION. Different values of toVersion are only used for testing\r\n * and local feature development.\r\n */\r\n SchemaConverter.prototype.createOrUpgrade = function (db, txn, fromVersion, toVersion) {\r\n var _this = this;\r\n assert(fromVersion < toVersion &&\r\n fromVersion >= 0 &&\r\n toVersion <= SCHEMA_VERSION, \"Unexpected schema upgrade from v\" + fromVersion + \" to v{toVersion}.\");\r\n if (fromVersion < 1 && toVersion >= 1) {\r\n createPrimaryClientStore(db);\r\n createMutationQueue(db);\r\n createQueryCache(db);\r\n createRemoteDocumentCache(db);\r\n }\r\n // Migration 2 to populate the targetGlobal object no longer needed since\r\n // migration 3 unconditionally clears it.\r\n var p = PersistencePromise.resolve();\r\n if (fromVersion < 3 && toVersion >= 3) {\r\n // Brand new clients don't need to drop and recreate--only clients that\r\n // potentially have corrupt data.\r\n if (fromVersion !== 0) {\r\n dropQueryCache(db);\r\n createQueryCache(db);\r\n }\r\n p = p.next(function () { return writeEmptyTargetGlobalEntry(txn); });\r\n }\r\n if (fromVersion < 4 && toVersion >= 4) {\r\n if (fromVersion !== 0) {\r\n // Schema version 3 uses auto-generated keys to generate globally unique\r\n // mutation batch IDs (this was previously ensured internally by the\r\n // client). To migrate to the new schema, we have to read all mutations\r\n // and write them back out. We preserve the existing batch IDs to guarantee\r\n // consistency with other object stores. Any further mutation batch IDs will\r\n // be auto-generated.\r\n p = p.next(function () { return upgradeMutationBatchSchemaAndMigrateData(db, txn); });\r\n }\r\n p = p.next(function () {\r\n createClientMetadataStore(db);\r\n createRemoteDocumentChangesStore(db);\r\n });\r\n }\r\n if (fromVersion < 5 && toVersion >= 5) {\r\n p = p.next(function () { return _this.removeAcknowledgedMutations(txn); });\r\n }\r\n if (fromVersion < 6 && toVersion >= 6) {\r\n p = p.next(function () {\r\n createDocumentGlobalStore(db);\r\n return _this.addDocumentGlobal(txn);\r\n });\r\n }\r\n if (fromVersion < 7 && toVersion >= 7) {\r\n p = p.next(function () { return _this.ensureSequenceNumbers(txn); });\r\n }\r\n if (fromVersion < 8 && toVersion >= 8) {\r\n p = p.next(function () { return _this.createCollectionParentIndex(db, txn); });\r\n }\r\n return p;\r\n };\r\n SchemaConverter.prototype.addDocumentGlobal = function (txn) {\r\n var byteCount = 0;\r\n return txn\r\n .store(DbRemoteDocument.store)\r\n .iterate(function (_, doc) {\r\n byteCount += dbDocumentSize(doc);\r\n })\r\n .next(function () {\r\n var metadata = new DbRemoteDocumentGlobal(byteCount);\r\n return txn\r\n .store(DbRemoteDocumentGlobal.store)\r\n .put(DbRemoteDocumentGlobal.key, metadata);\r\n });\r\n };\r\n SchemaConverter.prototype.removeAcknowledgedMutations = function (txn) {\r\n var _this = this;\r\n var queuesStore = txn.store(DbMutationQueue.store);\r\n var mutationsStore = txn.store(DbMutationBatch.store);\r\n return queuesStore.loadAll().next(function (queues) {\r\n return PersistencePromise.forEach(queues, function (queue) {\r\n var range = IDBKeyRange.bound([queue.userId, BATCHID_UNKNOWN], [queue.userId, queue.lastAcknowledgedBatchId]);\r\n return mutationsStore\r\n .loadAll(DbMutationBatch.userMutationsIndex, range)\r\n .next(function (dbBatches) {\r\n return PersistencePromise.forEach(dbBatches, function (dbBatch) {\r\n assert(dbBatch.userId === queue.userId, \"Cannot process batch \" + dbBatch.batchId + \" from unexpected user\");\r\n var batch = _this.serializer.fromDbMutationBatch(dbBatch);\r\n return removeMutationBatch(txn, queue.userId, batch).next(function () { });\r\n });\r\n });\r\n });\r\n });\r\n };\r\n /**\r\n * Ensures that every document in the remote document cache has a corresponding sentinel row\r\n * with a sequence number. Missing rows are given the most recently used sequence number.\r\n */\r\n SchemaConverter.prototype.ensureSequenceNumbers = function (txn) {\r\n var documentTargetStore = txn.store(DbTargetDocument.store);\r\n var documentsStore = txn.store(DbRemoteDocument.store);\r\n return getHighestListenSequenceNumber(txn).next(function (currentSequenceNumber) {\r\n var writeSentinelKey = function (path) {\r\n return documentTargetStore.put(new DbTargetDocument(0, encode(path), currentSequenceNumber));\r\n };\r\n var promises = [];\r\n return documentsStore\r\n .iterate(function (key, doc) {\r\n var path = new ResourcePath(key);\r\n var docSentinelKey = sentinelKey(path);\r\n promises.push(documentTargetStore.get(docSentinelKey).next(function (maybeSentinel) {\r\n if (!maybeSentinel) {\r\n return writeSentinelKey(path);\r\n }\r\n else {\r\n return PersistencePromise.resolve();\r\n }\r\n }));\r\n })\r\n .next(function () { return PersistencePromise.waitFor(promises); });\r\n });\r\n };\r\n SchemaConverter.prototype.createCollectionParentIndex = function (db, txn) {\r\n // Create the index.\r\n db.createObjectStore(DbCollectionParent.store, {\r\n keyPath: DbCollectionParent.keyPath\r\n });\r\n var collectionParentsStore = txn.store(DbCollectionParent.store);\r\n // Helper to add an index entry iff we haven't already written it.\r\n var cache = new MemoryCollectionParentIndex();\r\n var addEntry = function (collectionPath) {\r\n if (cache.add(collectionPath)) {\r\n var collectionId = collectionPath.lastSegment();\r\n var parentPath = collectionPath.popLast();\r\n return collectionParentsStore.put({\r\n collectionId: collectionId,\r\n parent: encode(parentPath)\r\n });\r\n }\r\n };\r\n // Index existing remote documents.\r\n return txn\r\n .store(DbRemoteDocument.store)\r\n .iterate({ keysOnly: true }, function (pathSegments, _) {\r\n var path = new ResourcePath(pathSegments);\r\n return addEntry(path.popLast());\r\n })\r\n .next(function () {\r\n // Index existing mutations.\r\n return txn\r\n .store(DbDocumentMutation.store)\r\n .iterate({ keysOnly: true }, function (_a, _) {\r\n var userID = _a[0], encodedPath = _a[1], batchId = _a[2];\r\n var path = decode(encodedPath);\r\n return addEntry(path.popLast());\r\n });\r\n });\r\n };\r\n return SchemaConverter;\r\n}());\r\nfunction sentinelKey(path) {\r\n return [0, encode(path)];\r\n}\r\n/**\r\n * Wrapper class to store timestamps (seconds and nanos) in IndexedDb objects.\r\n */\r\nvar DbTimestamp = /** @class */ (function () {\r\n function DbTimestamp(seconds, nanoseconds) {\r\n this.seconds = seconds;\r\n this.nanoseconds = nanoseconds;\r\n }\r\n return DbTimestamp;\r\n}());\r\n/**\r\n * A singleton object to be stored in the 'owner' store in IndexedDb.\r\n *\r\n * A given database can have a single primary tab assigned at a given time. That\r\n * tab must validate that it is still holding the primary lease before every\r\n * operation that requires locked access. The primary tab should regularly\r\n * write an updated timestamp to this lease to prevent other tabs from\r\n * \"stealing\" the primary lease\r\n */\r\nvar DbPrimaryClient = /** @class */ (function () {\r\n function DbPrimaryClient(ownerId, \r\n /** Whether to allow shared access from multiple tabs. */\r\n allowTabSynchronization, leaseTimestampMs) {\r\n this.ownerId = ownerId;\r\n this.allowTabSynchronization = allowTabSynchronization;\r\n this.leaseTimestampMs = leaseTimestampMs;\r\n }\r\n /**\r\n * Name of the IndexedDb object store.\r\n *\r\n * Note that the name 'owner' is chosen to ensure backwards compatibility with\r\n * older clients that only supported single locked access to the persistence\r\n * layer.\r\n */\r\n DbPrimaryClient.store = 'owner';\r\n /**\r\n * The key string used for the single object that exists in the\r\n * DbPrimaryClient store.\r\n */\r\n DbPrimaryClient.key = 'owner';\r\n return DbPrimaryClient;\r\n}());\r\nfunction createPrimaryClientStore(db) {\r\n db.createObjectStore(DbPrimaryClient.store);\r\n}\r\n/**\r\n * An object to be stored in the 'mutationQueues' store in IndexedDb.\r\n *\r\n * Each user gets a single queue of MutationBatches to apply to the server.\r\n * DbMutationQueue tracks the metadata about the queue.\r\n */\r\nvar DbMutationQueue = /** @class */ (function () {\r\n function DbMutationQueue(\r\n /**\r\n * The normalized user ID to which this queue belongs.\r\n */\r\n userId, \r\n /**\r\n * An identifier for the highest numbered batch that has been acknowledged\r\n * by the server. All MutationBatches in this queue with batchIds less\r\n * than or equal to this value are considered to have been acknowledged by\r\n * the server.\r\n *\r\n * NOTE: this is deprecated and no longer used by the code.\r\n */\r\n lastAcknowledgedBatchId, \r\n /**\r\n * A stream token that was previously sent by the server.\r\n *\r\n * See StreamingWriteRequest in datastore.proto for more details about\r\n * usage.\r\n *\r\n * After sending this token, earlier tokens may not be used anymore so\r\n * only a single stream token is retained.\r\n */\r\n lastStreamToken) {\r\n this.userId = userId;\r\n this.lastAcknowledgedBatchId = lastAcknowledgedBatchId;\r\n this.lastStreamToken = lastStreamToken;\r\n }\r\n /** Name of the IndexedDb object store. */\r\n DbMutationQueue.store = 'mutationQueues';\r\n /** Keys are automatically assigned via the userId property. */\r\n DbMutationQueue.keyPath = 'userId';\r\n return DbMutationQueue;\r\n}());\r\n/**\r\n * An object to be stored in the 'mutations' store in IndexedDb.\r\n *\r\n * Represents a batch of user-level mutations intended to be sent to the server\r\n * in a single write. Each user-level batch gets a separate DbMutationBatch\r\n * with a new batchId.\r\n */\r\nvar DbMutationBatch = /** @class */ (function () {\r\n function DbMutationBatch(\r\n /**\r\n * The normalized user ID to which this batch belongs.\r\n */\r\n userId, \r\n /**\r\n * An identifier for this batch, allocated using an auto-generated key.\r\n */\r\n batchId, \r\n /**\r\n * The local write time of the batch, stored as milliseconds since the\r\n * epoch.\r\n */\r\n localWriteTimeMs, \r\n /**\r\n * A list of \"mutations\" that represent a partial base state from when this\r\n * write batch was initially created. During local application of the write\r\n * batch, these baseMutations are applied prior to the real writes in order\r\n * to override certain document fields from the remote document cache. This\r\n * is necessary in the case of non-idempotent writes (e.g. `increment()`\r\n * transforms) to make sure that the local view of the modified documents\r\n * doesn't flicker if the remote document cache receives the result of the\r\n * non-idempotent write before the write is removed from the queue.\r\n *\r\n * These mutations are never sent to the backend.\r\n */\r\n baseMutations, \r\n /**\r\n * A list of mutations to apply. All mutations will be applied atomically.\r\n *\r\n * Mutations are serialized via JsonProtoSerializer.toMutation().\r\n */\r\n mutations) {\r\n this.userId = userId;\r\n this.batchId = batchId;\r\n this.localWriteTimeMs = localWriteTimeMs;\r\n this.baseMutations = baseMutations;\r\n this.mutations = mutations;\r\n }\r\n /** Name of the IndexedDb object store. */\r\n DbMutationBatch.store = 'mutations';\r\n /** Keys are automatically assigned via the userId, batchId properties. */\r\n DbMutationBatch.keyPath = 'batchId';\r\n /** The index name for lookup of mutations by user. */\r\n DbMutationBatch.userMutationsIndex = 'userMutationsIndex';\r\n /** The user mutations index is keyed by [userId, batchId] pairs. */\r\n DbMutationBatch.userMutationsKeyPath = ['userId', 'batchId'];\r\n return DbMutationBatch;\r\n}());\r\nfunction createMutationQueue(db) {\r\n db.createObjectStore(DbMutationQueue.store, {\r\n keyPath: DbMutationQueue.keyPath\r\n });\r\n var mutationBatchesStore = db.createObjectStore(DbMutationBatch.store, {\r\n keyPath: DbMutationBatch.keyPath,\r\n autoIncrement: true\r\n });\r\n mutationBatchesStore.createIndex(DbMutationBatch.userMutationsIndex, DbMutationBatch.userMutationsKeyPath, { unique: true });\r\n db.createObjectStore(DbDocumentMutation.store);\r\n}\r\n/**\r\n * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads\r\n * and rewrites all data.\r\n */\r\nfunction upgradeMutationBatchSchemaAndMigrateData(db, txn) {\r\n var v1MutationsStore = txn.store(DbMutationBatch.store);\r\n return v1MutationsStore.loadAll().next(function (existingMutations) {\r\n db.deleteObjectStore(DbMutationBatch.store);\r\n var mutationsStore = db.createObjectStore(DbMutationBatch.store, {\r\n keyPath: DbMutationBatch.keyPath,\r\n autoIncrement: true\r\n });\r\n mutationsStore.createIndex(DbMutationBatch.userMutationsIndex, DbMutationBatch.userMutationsKeyPath, { unique: true });\r\n var v3MutationsStore = txn.store(DbMutationBatch.store);\r\n var writeAll = existingMutations.map(function (mutation) {\r\n return v3MutationsStore.put(mutation);\r\n });\r\n return PersistencePromise.waitFor(writeAll);\r\n });\r\n}\r\n/**\r\n * An object to be stored in the 'documentMutations' store in IndexedDb.\r\n *\r\n * A manually maintained index of all the mutation batches that affect a given\r\n * document key. The rows in this table are references based on the contents of\r\n * DbMutationBatch.mutations.\r\n */\r\nvar DbDocumentMutation = /** @class */ (function () {\r\n function DbDocumentMutation() {\r\n }\r\n /**\r\n * Creates a [userId] key for use in the DbDocumentMutations index to iterate\r\n * over all of a user's document mutations.\r\n */\r\n DbDocumentMutation.prefixForUser = function (userId) {\r\n return [userId];\r\n };\r\n /**\r\n * Creates a [userId, encodedPath] key for use in the DbDocumentMutations\r\n * index to iterate over all at document mutations for a given path or lower.\r\n */\r\n DbDocumentMutation.prefixForPath = function (userId, path) {\r\n return [userId, encode(path)];\r\n };\r\n /**\r\n * Creates a full index key of [userId, encodedPath, batchId] for inserting\r\n * and deleting into the DbDocumentMutations index.\r\n */\r\n DbDocumentMutation.key = function (userId, path, batchId) {\r\n return [userId, encode(path), batchId];\r\n };\r\n DbDocumentMutation.store = 'documentMutations';\r\n /**\r\n * Because we store all the useful information for this store in the key,\r\n * there is no useful information to store as the value. The raw (unencoded)\r\n * path cannot be stored because IndexedDb doesn't store prototype\r\n * information.\r\n */\r\n DbDocumentMutation.PLACEHOLDER = new DbDocumentMutation();\r\n return DbDocumentMutation;\r\n}());\r\nfunction createRemoteDocumentCache(db) {\r\n db.createObjectStore(DbRemoteDocument.store);\r\n}\r\n/**\r\n * Represents the known absence of a document at a particular version.\r\n * Stored in IndexedDb as part of a DbRemoteDocument object.\r\n */\r\nvar DbNoDocument = /** @class */ (function () {\r\n function DbNoDocument(path, readTime) {\r\n this.path = path;\r\n this.readTime = readTime;\r\n }\r\n return DbNoDocument;\r\n}());\r\n/**\r\n * Represents a document that is known to exist but whose data is unknown.\r\n * Stored in IndexedDb as part of a DbRemoteDocument object.\r\n */\r\nvar DbUnknownDocument = /** @class */ (function () {\r\n function DbUnknownDocument(path, version) {\r\n this.path = path;\r\n this.version = version;\r\n }\r\n return DbUnknownDocument;\r\n}());\r\n/**\r\n * An object to be stored in the 'remoteDocuments' store in IndexedDb.\r\n * It represents either:\r\n *\r\n * - A complete document.\r\n * - A \"no document\" representing a document that is known not to exist (at\r\n * some version).\r\n * - An \"unknown document\" representing a document that is known to exist (at\r\n * some version) but whose contents are unknown.\r\n *\r\n * Note: This is the persisted equivalent of a MaybeDocument and could perhaps\r\n * be made more general if necessary.\r\n */\r\nvar DbRemoteDocument = /** @class */ (function () {\r\n function DbRemoteDocument(\r\n /**\r\n * Set to an instance of DbUnknownDocument if the data for a document is\r\n * not known, but it is known that a document exists at the specified\r\n * version (e.g. it had a successful update applied to it)\r\n */\r\n unknownDocument, \r\n /**\r\n * Set to an instance of a DbNoDocument if it is known that no document\r\n * exists.\r\n */\r\n noDocument, \r\n /**\r\n * Set to an instance of a Document if there's a cached version of the\r\n * document.\r\n */\r\n document, \r\n /**\r\n * Documents that were written to the remote document store based on\r\n * a write acknowledgment are marked with `hasCommittedMutations`. These\r\n * documents are potentially inconsistent with the backend's copy and use\r\n * the write's commit version as their document version.\r\n */\r\n hasCommittedMutations) {\r\n this.unknownDocument = unknownDocument;\r\n this.noDocument = noDocument;\r\n this.document = document;\r\n this.hasCommittedMutations = hasCommittedMutations;\r\n }\r\n DbRemoteDocument.store = 'remoteDocuments';\r\n return DbRemoteDocument;\r\n}());\r\n/**\r\n * Contains a single entry that has metadata about the remote document cache.\r\n */\r\nvar DbRemoteDocumentGlobal = /** @class */ (function () {\r\n /**\r\n * @param byteSize Approximately the total size in bytes of all the documents in the document\r\n * cache.\r\n */\r\n function DbRemoteDocumentGlobal(byteSize) {\r\n this.byteSize = byteSize;\r\n }\r\n DbRemoteDocumentGlobal.store = 'remoteDocumentGlobal';\r\n DbRemoteDocumentGlobal.key = 'remoteDocumentGlobalKey';\r\n return DbRemoteDocumentGlobal;\r\n}());\r\nfunction createDocumentGlobalStore(db) {\r\n db.createObjectStore(DbRemoteDocumentGlobal.store);\r\n}\r\n/**\r\n * An object to be stored in the 'targets' store in IndexedDb.\r\n *\r\n * This is based on and should be kept in sync with the proto used in the iOS\r\n * client.\r\n *\r\n * Each query the client listens to against the server is tracked on disk so\r\n * that the query can be efficiently resumed on restart.\r\n */\r\nvar DbTarget = /** @class */ (function () {\r\n function DbTarget(\r\n /**\r\n * An auto-generated sequential numeric identifier for the query.\r\n *\r\n * Queries are stored using their canonicalId as the key, but these\r\n * canonicalIds can be quite long so we additionally assign a unique\r\n * queryId which can be used by referenced data structures (e.g.\r\n * indexes) to minimize the on-disk cost.\r\n */\r\n targetId, \r\n /**\r\n * The canonical string representing this query. This is not unique.\r\n */\r\n canonicalId, \r\n /**\r\n * The last readTime received from the Watch Service for this query.\r\n *\r\n * This is the same value as TargetChange.read_time in the protos.\r\n */\r\n readTime, \r\n /**\r\n * An opaque, server-assigned token that allows watching a query to be\r\n * resumed after disconnecting without retransmitting all the data\r\n * that matches the query. The resume token essentially identifies a\r\n * point in time from which the server should resume sending results.\r\n *\r\n * This is related to the snapshotVersion in that the resumeToken\r\n * effectively also encodes that value, but the resumeToken is opaque\r\n * and sometimes encodes additional information.\r\n *\r\n * A consequence of this is that the resumeToken should be used when\r\n * asking the server to reason about where this client is in the watch\r\n * stream, but the client should use the snapshotVersion for its own\r\n * purposes.\r\n *\r\n * This is the same value as TargetChange.resume_token in the protos.\r\n */\r\n resumeToken, \r\n /**\r\n * A sequence number representing the last time this query was\r\n * listened to, used for garbage collection purposes.\r\n *\r\n * Conventionally this would be a timestamp value, but device-local\r\n * clocks are unreliable and they must be able to create new listens\r\n * even while disconnected. Instead this should be a monotonically\r\n * increasing number that's incremented on each listen call.\r\n *\r\n * This is different from the queryId since the queryId is an\r\n * immutable identifier assigned to the Query on first use while\r\n * lastListenSequenceNumber is updated every time the query is\r\n * listened to.\r\n */\r\n lastListenSequenceNumber, \r\n /**\r\n * The query for this target.\r\n *\r\n * Because canonical ids are not unique we must store the actual query. We\r\n * use the proto to have an object we can persist without having to\r\n * duplicate translation logic to and from a `Query` object.\r\n */\r\n query) {\r\n this.targetId = targetId;\r\n this.canonicalId = canonicalId;\r\n this.readTime = readTime;\r\n this.resumeToken = resumeToken;\r\n this.lastListenSequenceNumber = lastListenSequenceNumber;\r\n this.query = query;\r\n }\r\n DbTarget.store = 'targets';\r\n /** Keys are automatically assigned via the targetId property. */\r\n DbTarget.keyPath = 'targetId';\r\n /** The name of the queryTargets index. */\r\n DbTarget.queryTargetsIndexName = 'queryTargetsIndex';\r\n /**\r\n * The index of all canonicalIds to the targets that they match. This is not\r\n * a unique mapping because canonicalId does not promise a unique name for all\r\n * possible queries, so we append the targetId to make the mapping unique.\r\n */\r\n DbTarget.queryTargetsKeyPath = ['canonicalId', 'targetId'];\r\n return DbTarget;\r\n}());\r\n/**\r\n * An object representing an association between a target and a document, or a\r\n * sentinel row marking the last sequence number at which a document was used.\r\n * Each document cached must have a corresponding sentinel row before lru\r\n * garbage collection is enabled.\r\n *\r\n * The target associations and sentinel rows are co-located so that orphaned\r\n * documents and their sequence numbers can be identified efficiently via a scan\r\n * of this store.\r\n */\r\nvar DbTargetDocument = /** @class */ (function () {\r\n function DbTargetDocument(\r\n /**\r\n * The targetId identifying a target or 0 for a sentinel row.\r\n */\r\n targetId, \r\n /**\r\n * The path to the document, as encoded in the key.\r\n */\r\n path, \r\n /**\r\n * If this is a sentinel row, this should be the sequence number of the last\r\n * time the document specified by `path` was used. Otherwise, it should be\r\n * `undefined`.\r\n */\r\n sequenceNumber) {\r\n this.targetId = targetId;\r\n this.path = path;\r\n this.sequenceNumber = sequenceNumber;\r\n assert((targetId === 0) === (sequenceNumber !== undefined), \r\n // tslint:disable-next-line:max-line-length\r\n 'A target-document row must either have targetId == 0 and a defined sequence number, or a non-zero targetId and no sequence number');\r\n }\r\n /** Name of the IndexedDb object store. */\r\n DbTargetDocument.store = 'targetDocuments';\r\n /** Keys are automatically assigned via the targetId, path properties. */\r\n DbTargetDocument.keyPath = ['targetId', 'path'];\r\n /** The index name for the reverse index. */\r\n DbTargetDocument.documentTargetsIndex = 'documentTargetsIndex';\r\n /** We also need to create the reverse index for these properties. */\r\n DbTargetDocument.documentTargetsKeyPath = ['path', 'targetId'];\r\n return DbTargetDocument;\r\n}());\r\n/**\r\n * A record of global state tracked across all Targets, tracked separately\r\n * to avoid the need for extra indexes.\r\n *\r\n * This should be kept in-sync with the proto used in the iOS client.\r\n */\r\nvar DbTargetGlobal = /** @class */ (function () {\r\n function DbTargetGlobal(\r\n /**\r\n * The highest numbered target id across all targets.\r\n *\r\n * See DbTarget.targetId.\r\n */\r\n highestTargetId, \r\n /**\r\n * The highest numbered lastListenSequenceNumber across all targets.\r\n *\r\n * See DbTarget.lastListenSequenceNumber.\r\n */\r\n highestListenSequenceNumber, \r\n /**\r\n * A global snapshot version representing the last consistent snapshot we\r\n * received from the backend. This is monotonically increasing and any\r\n * snapshots received from the backend prior to this version (e.g. for\r\n * targets resumed with a resumeToken) should be suppressed (buffered)\r\n * until the backend has caught up to this snapshot version again. This\r\n * prevents our cache from ever going backwards in time.\r\n */\r\n lastRemoteSnapshotVersion, \r\n /**\r\n * The number of targets persisted.\r\n */\r\n targetCount) {\r\n this.highestTargetId = highestTargetId;\r\n this.highestListenSequenceNumber = highestListenSequenceNumber;\r\n this.lastRemoteSnapshotVersion = lastRemoteSnapshotVersion;\r\n this.targetCount = targetCount;\r\n }\r\n /**\r\n * The key string used for the single object that exists in the\r\n * DbTargetGlobal store.\r\n */\r\n DbTargetGlobal.key = 'targetGlobalKey';\r\n DbTargetGlobal.store = 'targetGlobal';\r\n return DbTargetGlobal;\r\n}());\r\n/**\r\n * An object representing an association between a Collection id (e.g. 'messages')\r\n * to a parent path (e.g. '/chats/123') that contains it as a (sub)collection.\r\n * This is used to efficiently find all collections to query when performing\r\n * a Collection Group query.\r\n */\r\nvar DbCollectionParent = /** @class */ (function () {\r\n function DbCollectionParent(\r\n /**\r\n * The collectionId (e.g. 'messages')\r\n */\r\n collectionId, \r\n /**\r\n * The path to the parent (either a document location or an empty path for\r\n * a root-level collection).\r\n */\r\n parent) {\r\n this.collectionId = collectionId;\r\n this.parent = parent;\r\n }\r\n /** Name of the IndexedDb object store. */\r\n DbCollectionParent.store = 'collectionParents';\r\n /** Keys are automatically assigned via the collectionId, parent properties. */\r\n DbCollectionParent.keyPath = ['collectionId', 'parent'];\r\n return DbCollectionParent;\r\n}());\r\nfunction createQueryCache(db) {\r\n var targetDocumentsStore = db.createObjectStore(DbTargetDocument.store, {\r\n keyPath: DbTargetDocument.keyPath\r\n });\r\n targetDocumentsStore.createIndex(DbTargetDocument.documentTargetsIndex, DbTargetDocument.documentTargetsKeyPath, { unique: true });\r\n var targetStore = db.createObjectStore(DbTarget.store, {\r\n keyPath: DbTarget.keyPath\r\n });\r\n // NOTE: This is unique only because the TargetId is the suffix.\r\n targetStore.createIndex(DbTarget.queryTargetsIndexName, DbTarget.queryTargetsKeyPath, { unique: true });\r\n db.createObjectStore(DbTargetGlobal.store);\r\n}\r\nfunction dropQueryCache(db) {\r\n db.deleteObjectStore(DbTargetDocument.store);\r\n db.deleteObjectStore(DbTarget.store);\r\n db.deleteObjectStore(DbTargetGlobal.store);\r\n}\r\n/**\r\n * Creates the target global singleton row.\r\n *\r\n * @param {IDBTransaction} txn The version upgrade transaction for indexeddb\r\n */\r\nfunction writeEmptyTargetGlobalEntry(txn) {\r\n var globalStore = txn.store(DbTargetGlobal.store);\r\n var metadata = new DbTargetGlobal(\r\n /*highestTargetId=*/ 0, \r\n /*lastListenSequenceNumber=*/ 0, SnapshotVersion.MIN.toTimestamp(), \r\n /*targetCount=*/ 0);\r\n return globalStore.put(DbTargetGlobal.key, metadata);\r\n}\r\n/**\r\n * An object store to store the keys of changed documents. This is used to\r\n * facilitate storing document changelogs in the Remote Document Cache.\r\n *\r\n * PORTING NOTE: This is used for change propagation during multi-tab syncing\r\n * and not needed on iOS and Android.\r\n */\r\nvar DbRemoteDocumentChanges = /** @class */ (function () {\r\n function DbRemoteDocumentChanges(\r\n /** The keys of the changed documents. */\r\n changes) {\r\n this.changes = changes;\r\n }\r\n /** Name of the IndexedDb object store. */\r\n DbRemoteDocumentChanges.store = 'remoteDocumentChanges';\r\n /** Keys are auto-generated via the `id` property. */\r\n DbRemoteDocumentChanges.keyPath = 'id';\r\n return DbRemoteDocumentChanges;\r\n}());\r\nfunction createRemoteDocumentChangesStore(db) {\r\n db.createObjectStore(DbRemoteDocumentChanges.store, {\r\n keyPath: 'id',\r\n autoIncrement: true\r\n });\r\n}\r\n/**\r\n * A record of the metadata state of each client.\r\n *\r\n * PORTING NOTE: This is used to synchronize multi-tab state and does not need\r\n * to be ported to iOS or Android.\r\n */\r\nvar DbClientMetadata = /** @class */ (function () {\r\n function DbClientMetadata(\r\n /** The auto-generated client id assigned at client startup. */\r\n clientId, \r\n /** The last time this state was updated. */\r\n updateTimeMs, \r\n /** Whether the client's network connection is enabled. */\r\n networkEnabled, \r\n /** Whether this client is running in a foreground tab. */\r\n inForeground, \r\n /**\r\n * The last change read from the DbRemoteDocumentChanges store.\r\n * Can be undefined for backwards compatibility.\r\n */\r\n lastProcessedDocumentChangeId) {\r\n this.clientId = clientId;\r\n this.updateTimeMs = updateTimeMs;\r\n this.networkEnabled = networkEnabled;\r\n this.inForeground = inForeground;\r\n this.lastProcessedDocumentChangeId = lastProcessedDocumentChangeId;\r\n }\r\n /** Name of the IndexedDb object store. */\r\n DbClientMetadata.store = 'clientMetadata';\r\n /** Keys are automatically assigned via the clientId properties. */\r\n DbClientMetadata.keyPath = 'clientId';\r\n return DbClientMetadata;\r\n}());\r\nfunction createClientMetadataStore(db) {\r\n db.createObjectStore(DbClientMetadata.store, {\r\n keyPath: DbClientMetadata.keyPath\r\n });\r\n}\r\n// Visible for testing\r\nvar V1_STORES = [\r\n DbMutationQueue.store,\r\n DbMutationBatch.store,\r\n DbDocumentMutation.store,\r\n DbRemoteDocument.store,\r\n DbTarget.store,\r\n DbPrimaryClient.store,\r\n DbTargetGlobal.store,\r\n DbTargetDocument.store\r\n];\r\n// V2 is no longer usable (see comment at top of file)\r\n// Visible for testing\r\nvar V3_STORES = V1_STORES;\r\n// Visible for testing\r\nvar V4_STORES = V3_STORES.concat([\r\n DbClientMetadata.store,\r\n DbRemoteDocumentChanges.store\r\n]);\r\n// V5 does not change the set of stores.\r\nvar V6_STORES = V4_STORES.concat([DbRemoteDocumentGlobal.store]);\r\n// V7 does not change the set of stores.\r\nvar V8_STORES = V6_STORES.concat([DbCollectionParent.store]);\r\n/**\r\n * The list of all default IndexedDB stores used throughout the SDK. This is\r\n * used when creating transactions so that access across all stores is done\r\n * atomically.\r\n */\r\nvar ALL_STORES = V8_STORES;\n\n/**\r\n * @license\r\n * Copyright 2019 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A persisted implementation of IndexManager.\r\n */\r\nvar IndexedDbIndexManager = /** @class */ (function () {\r\n function IndexedDbIndexManager() {\r\n /**\r\n * An in-memory copy of the index entries we've already written since the SDK\r\n * launched. Used to avoid re-writing the same entry repeatedly.\r\n *\r\n * This is *NOT* a complete cache of what's in persistence and so can never be used to\r\n * satisfy reads.\r\n */\r\n this.collectionParentsCache = new MemoryCollectionParentIndex();\r\n }\r\n IndexedDbIndexManager.prototype.addToCollectionParentIndex = function (transaction, collectionPath) {\r\n assert(collectionPath.length % 2 === 1, 'Expected a collection path.');\r\n if (this.collectionParentsCache.add(collectionPath)) {\r\n assert(collectionPath.length >= 1, 'Invalid collection path.');\r\n var collectionId = collectionPath.lastSegment();\r\n var parentPath = collectionPath.popLast();\r\n return collectionParentsStore(transaction).put({\r\n collectionId: collectionId,\r\n parent: encode(parentPath)\r\n });\r\n }\r\n return PersistencePromise.resolve();\r\n };\r\n IndexedDbIndexManager.prototype.getCollectionParents = function (transaction, collectionId) {\r\n var parentPaths = [];\r\n var range = IDBKeyRange.bound([collectionId, ''], [immediateSuccessor(collectionId), ''], \r\n /*lowerOpen=*/ false, \r\n /*upperOpen=*/ true);\r\n return collectionParentsStore(transaction)\r\n .loadAll(range)\r\n .next(function (entries) {\r\n for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {\r\n var entry = entries_1[_i];\r\n // This collectionId guard shouldn't be necessary (and isn't as long\r\n // as we're running in a real browser), but there's a bug in\r\n // indexeddbshim that breaks our range in our tests running in node:\r\n // https://github.com/axemclion/IndexedDBShim/issues/334\r\n if (entry.collectionId !== collectionId) {\r\n break;\r\n }\r\n parentPaths.push(decode(entry.parent));\r\n }\r\n return parentPaths;\r\n });\r\n };\r\n return IndexedDbIndexManager;\r\n}());\r\n/**\r\n * Helper to get a typed SimpleDbStore for the collectionParents\r\n * document store.\r\n */\r\nfunction collectionParentsStore(txn) {\r\n return IndexedDbPersistence.getStore(txn, DbCollectionParent.store);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** Serializer for values stored in the LocalStore. */\r\nvar LocalSerializer = /** @class */ (function () {\r\n function LocalSerializer(remoteSerializer) {\r\n this.remoteSerializer = remoteSerializer;\r\n }\r\n /** Decodes a remote document from storage locally to a Document. */\r\n LocalSerializer.prototype.fromDbRemoteDocument = function (remoteDoc) {\r\n if (remoteDoc.document) {\r\n return this.remoteSerializer.fromDocument(remoteDoc.document, !!remoteDoc.hasCommittedMutations);\r\n }\r\n else if (remoteDoc.noDocument) {\r\n var key = DocumentKey.fromSegments(remoteDoc.noDocument.path);\r\n var version = this.fromDbTimestamp(remoteDoc.noDocument.readTime);\r\n return new NoDocument(key, version, {\r\n hasCommittedMutations: !!remoteDoc.hasCommittedMutations\r\n });\r\n }\r\n else if (remoteDoc.unknownDocument) {\r\n var key = DocumentKey.fromSegments(remoteDoc.unknownDocument.path);\r\n var version = this.fromDbTimestamp(remoteDoc.unknownDocument.version);\r\n return new UnknownDocument(key, version);\r\n }\r\n else {\r\n return fail('Unexpected DbRemoteDocument');\r\n }\r\n };\r\n /** Encodes a document for storage locally. */\r\n LocalSerializer.prototype.toDbRemoteDocument = function (maybeDoc) {\r\n if (maybeDoc instanceof Document) {\r\n var doc = maybeDoc.proto\r\n ? maybeDoc.proto\r\n : this.remoteSerializer.toDocument(maybeDoc);\r\n var hasCommittedMutations = maybeDoc.hasCommittedMutations;\r\n return new DbRemoteDocument(\r\n /* unknownDocument= */ null, \r\n /* noDocument= */ null, doc, hasCommittedMutations);\r\n }\r\n else if (maybeDoc instanceof NoDocument) {\r\n var path = maybeDoc.key.path.toArray();\r\n var readTime = this.toDbTimestamp(maybeDoc.version);\r\n var hasCommittedMutations = maybeDoc.hasCommittedMutations;\r\n return new DbRemoteDocument(\r\n /* unknownDocument= */ null, new DbNoDocument(path, readTime), \r\n /* document= */ null, hasCommittedMutations);\r\n }\r\n else if (maybeDoc instanceof UnknownDocument) {\r\n var path = maybeDoc.key.path.toArray();\r\n var readTime = this.toDbTimestamp(maybeDoc.version);\r\n return new DbRemoteDocument(new DbUnknownDocument(path, readTime), \r\n /* noDocument= */ null, \r\n /* document= */ null, \r\n /* hasCommittedMutations= */ true);\r\n }\r\n else {\r\n return fail('Unexpected MaybeDocumment');\r\n }\r\n };\r\n LocalSerializer.prototype.toDbTimestamp = function (snapshotVersion) {\r\n var timestamp = snapshotVersion.toTimestamp();\r\n return new DbTimestamp(timestamp.seconds, timestamp.nanoseconds);\r\n };\r\n LocalSerializer.prototype.fromDbTimestamp = function (dbTimestamp) {\r\n var timestamp = new Timestamp(dbTimestamp.seconds, dbTimestamp.nanoseconds);\r\n return SnapshotVersion.fromTimestamp(timestamp);\r\n };\r\n /** Encodes a batch of mutations into a DbMutationBatch for local storage. */\r\n LocalSerializer.prototype.toDbMutationBatch = function (userId, batch) {\r\n var _this = this;\r\n var serializedBaseMutations = batch.baseMutations.map(function (m) {\r\n return _this.remoteSerializer.toMutation(m);\r\n });\r\n var serializedMutations = batch.mutations.map(function (m) {\r\n return _this.remoteSerializer.toMutation(m);\r\n });\r\n return new DbMutationBatch(userId, batch.batchId, batch.localWriteTime.toMillis(), serializedBaseMutations, serializedMutations);\r\n };\r\n /** Decodes a DbMutationBatch into a MutationBatch */\r\n LocalSerializer.prototype.fromDbMutationBatch = function (dbBatch) {\r\n var _this = this;\r\n var baseMutations = (dbBatch.baseMutations || []).map(function (m) {\r\n return _this.remoteSerializer.fromMutation(m);\r\n });\r\n var mutations = dbBatch.mutations.map(function (m) {\r\n return _this.remoteSerializer.fromMutation(m);\r\n });\r\n var timestamp = Timestamp.fromMillis(dbBatch.localWriteTimeMs);\r\n return new MutationBatch(dbBatch.batchId, timestamp, baseMutations, mutations);\r\n };\r\n /*\r\n * Encodes a set of document keys into an array of EncodedResourcePaths.\r\n */\r\n LocalSerializer.prototype.toDbResourcePaths = function (keys) {\r\n var encodedKeys = [];\r\n keys.forEach(function (key) {\r\n encodedKeys.push(encode(key.path));\r\n });\r\n return encodedKeys;\r\n };\r\n /** Decodes an array of EncodedResourcePaths into a set of document keys. */\r\n LocalSerializer.prototype.fromDbResourcePaths = function (encodedPaths) {\r\n var keys = documentKeySet();\r\n for (var _i = 0, encodedPaths_1 = encodedPaths; _i < encodedPaths_1.length; _i++) {\r\n var documentKey = encodedPaths_1[_i];\r\n keys = keys.add(new DocumentKey(decode(documentKey)));\r\n }\r\n return keys;\r\n };\r\n /** Decodes a DbTarget into QueryData */\r\n LocalSerializer.prototype.fromDbTarget = function (dbTarget) {\r\n var version = this.fromDbTimestamp(dbTarget.readTime);\r\n var query;\r\n if (isDocumentQuery(dbTarget.query)) {\r\n query = this.remoteSerializer.fromDocumentsTarget(dbTarget.query);\r\n }\r\n else {\r\n query = this.remoteSerializer.fromQueryTarget(dbTarget.query);\r\n }\r\n return new QueryData(query, dbTarget.targetId, QueryPurpose.Listen, dbTarget.lastListenSequenceNumber, version, dbTarget.resumeToken);\r\n };\r\n /** Encodes QueryData into a DbTarget for storage locally. */\r\n LocalSerializer.prototype.toDbTarget = function (queryData) {\r\n assert(QueryPurpose.Listen === queryData.purpose, 'Only queries with purpose ' +\r\n QueryPurpose.Listen +\r\n ' may be stored, got ' +\r\n queryData.purpose);\r\n var dbTimestamp = this.toDbTimestamp(queryData.snapshotVersion);\r\n var queryProto;\r\n if (queryData.query.isDocumentQuery()) {\r\n queryProto = this.remoteSerializer.toDocumentsTarget(queryData.query);\r\n }\r\n else {\r\n queryProto = this.remoteSerializer.toQueryTarget(queryData.query);\r\n }\r\n var resumeToken;\r\n if (queryData.resumeToken instanceof Uint8Array) {\r\n // TODO(b/78771403): Convert tokens to strings during deserialization\r\n assert(process.env.USE_MOCK_PERSISTENCE === 'YES', 'Persisting non-string stream tokens is only supported with mock persistence .');\r\n resumeToken = queryData.resumeToken.toString();\r\n }\r\n else {\r\n resumeToken = queryData.resumeToken;\r\n }\r\n // lastListenSequenceNumber is always 0 until we do real GC.\r\n return new DbTarget(queryData.targetId, queryData.query.canonicalId(), dbTimestamp, resumeToken, queryData.sequenceNumber, queryProto);\r\n };\r\n return LocalSerializer;\r\n}());\r\n/**\r\n * A helper function for figuring out what kind of query has been stored.\r\n */\r\nfunction isDocumentQuery(dbQuery) {\r\n return dbQuery.documents !== undefined;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2018 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction bufferEntryComparator(_a, _b) {\r\n var aSequence = _a[0], aIndex = _a[1];\r\n var bSequence = _b[0], bIndex = _b[1];\r\n var seqCmp = primitiveComparator(aSequence, bSequence);\r\n if (seqCmp === 0) {\r\n // This order doesn't matter, but we can bias against churn by sorting\r\n // entries created earlier as less than newer entries.\r\n return primitiveComparator(aIndex, bIndex);\r\n }\r\n else {\r\n return seqCmp;\r\n }\r\n}\r\n/**\r\n * Used to calculate the nth sequence number. Keeps a rolling buffer of the\r\n * lowest n values passed to `addElement`, and finally reports the largest of\r\n * them in `maxValue`.\r\n */\r\nvar RollingSequenceNumberBuffer = /** @class */ (function () {\r\n function RollingSequenceNumberBuffer(maxElements) {\r\n this.maxElements = maxElements;\r\n this.buffer = new SortedSet(bufferEntryComparator);\r\n this.previousIndex = 0;\r\n }\r\n RollingSequenceNumberBuffer.prototype.nextIndex = function () {\r\n return ++this.previousIndex;\r\n };\r\n RollingSequenceNumberBuffer.prototype.addElement = function (sequenceNumber) {\r\n var entry = [sequenceNumber, this.nextIndex()];\r\n if (this.buffer.size < this.maxElements) {\r\n this.buffer = this.buffer.add(entry);\r\n }\r\n else {\r\n var highestValue = this.buffer.last();\r\n if (bufferEntryComparator(entry, highestValue) < 0) {\r\n this.buffer = this.buffer.delete(highestValue).add(entry);\r\n }\r\n }\r\n };\r\n Object.defineProperty(RollingSequenceNumberBuffer.prototype, \"maxValue\", {\r\n get: function () {\r\n // Guaranteed to be non-empty. If we decide we are not collecting any\r\n // sequence numbers, nthSequenceNumber below short-circuits. If we have\r\n // decided that we are collecting n sequence numbers, it's because n is some\r\n // percentage of the existing sequence numbers. That means we should never\r\n // be in a situation where we are collecting sequence numbers but don't\r\n // actually have any.\r\n return this.buffer.last()[0];\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n return RollingSequenceNumberBuffer;\r\n}());\r\nvar GC_DID_NOT_RUN = {\r\n didRun: false,\r\n sequenceNumbersCollected: 0,\r\n targetsRemoved: 0,\r\n documentsRemoved: 0\r\n};\r\nvar LruParams = /** @class */ (function () {\r\n function LruParams(\r\n // When we attempt to collect, we will only do so if the cache size is greater than this\r\n // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped.\r\n cacheSizeCollectionThreshold, \r\n // The percentage of sequence numbers that we will attempt to collect\r\n percentileToCollect, \r\n // A cap on the total number of sequence numbers that will be collected. This prevents\r\n // us from collecting a huge number of sequence numbers if the cache has grown very large.\r\n maximumSequenceNumbersToCollect) {\r\n this.cacheSizeCollectionThreshold = cacheSizeCollectionThreshold;\r\n this.percentileToCollect = percentileToCollect;\r\n this.maximumSequenceNumbersToCollect = maximumSequenceNumbersToCollect;\r\n }\r\n LruParams.withCacheSize = function (cacheSize) {\r\n return new LruParams(cacheSize, LruParams.DEFAULT_COLLECTION_PERCENTILE, LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT);\r\n };\r\n LruParams.COLLECTION_DISABLED = -1;\r\n LruParams.MINIMUM_CACHE_SIZE_BYTES = 1 * 1024 * 1024;\r\n LruParams.DEFAULT_CACHE_SIZE_BYTES = 40 * 1024 * 1024;\r\n LruParams.DEFAULT_COLLECTION_PERCENTILE = 10;\r\n LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1000;\r\n LruParams.DEFAULT = new LruParams(LruParams.DEFAULT_CACHE_SIZE_BYTES, LruParams.DEFAULT_COLLECTION_PERCENTILE, LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT);\r\n LruParams.DISABLED = new LruParams(LruParams.COLLECTION_DISABLED, 0, 0);\r\n return LruParams;\r\n}());\r\n/** How long we wait to try running LRU GC after SDK initialization. */\r\nvar INITIAL_GC_DELAY_MS = 1 * 60 * 1000;\r\n/** Minimum amount of time between GC checks, after the first one. */\r\nvar REGULAR_GC_DELAY_MS = 5 * 60 * 1000;\r\n/**\r\n * This class is responsible for the scheduling of LRU garbage collection. It handles checking\r\n * whether or not GC is enabled, as well as which delay to use before the next run.\r\n */\r\nvar LruScheduler = /** @class */ (function () {\r\n function LruScheduler(garbageCollector, asyncQueue, localStore) {\r\n this.garbageCollector = garbageCollector;\r\n this.asyncQueue = asyncQueue;\r\n this.localStore = localStore;\r\n this.gcTask = null;\r\n }\r\n LruScheduler.prototype.start = function () {\r\n assert(this.gcTask === null, 'Cannot start an already started LruScheduler');\r\n if (this.garbageCollector.params.cacheSizeCollectionThreshold !==\r\n LruParams.COLLECTION_DISABLED) {\r\n this.scheduleGC();\r\n }\r\n };\r\n LruScheduler.prototype.stop = function () {\r\n if (this.gcTask) {\r\n this.gcTask.cancel();\r\n this.gcTask = null;\r\n }\r\n };\r\n Object.defineProperty(LruScheduler.prototype, \"started\", {\r\n get: function () {\r\n return this.gcTask !== null;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n LruScheduler.prototype.scheduleGC = function () {\r\n var _this = this;\r\n assert(this.gcTask === null, 'Cannot schedule GC while a task is pending');\r\n var delay = this.hasRun ? REGULAR_GC_DELAY_MS : INITIAL_GC_DELAY_MS;\r\n debug('LruGarbageCollector', \"Garbage collection scheduled in \" + delay + \"ms\");\r\n this.gcTask = this.asyncQueue.enqueueAfterDelay(TimerId.LruGarbageCollection, delay, function () {\r\n _this.gcTask = null;\r\n _this.hasRun = true;\r\n return _this.localStore\r\n .collectGarbage(_this.garbageCollector)\r\n .then(function () { return _this.scheduleGC(); })\r\n .catch(ignoreIfPrimaryLeaseLoss);\r\n });\r\n };\r\n return LruScheduler;\r\n}());\r\n/** Implements the steps for LRU garbage collection. */\r\nvar LruGarbageCollector = /** @class */ (function () {\r\n function LruGarbageCollector(delegate, params) {\r\n this.delegate = delegate;\r\n this.params = params;\r\n }\r\n /** Given a percentile of target to collect, returns the number of targets to collect. */\r\n LruGarbageCollector.prototype.calculateTargetCount = function (txn, percentile) {\r\n return this.delegate.getSequenceNumberCount(txn).next(function (targetCount) {\r\n return Math.floor((percentile / 100.0) * targetCount);\r\n });\r\n };\r\n /** Returns the nth sequence number, counting in order from the smallest. */\r\n LruGarbageCollector.prototype.nthSequenceNumber = function (txn, n) {\r\n var _this = this;\r\n if (n === 0) {\r\n return PersistencePromise.resolve(ListenSequence.INVALID);\r\n }\r\n var buffer = new RollingSequenceNumberBuffer(n);\r\n return this.delegate\r\n .forEachTarget(txn, function (target) { return buffer.addElement(target.sequenceNumber); })\r\n .next(function () {\r\n return _this.delegate.forEachOrphanedDocumentSequenceNumber(txn, function (sequenceNumber) { return buffer.addElement(sequenceNumber); });\r\n })\r\n .next(function () { return buffer.maxValue; });\r\n };\r\n /**\r\n * Removes targets with a sequence number equal to or less than the given upper bound, and removes\r\n * document associations with those targets.\r\n */\r\n LruGarbageCollector.prototype.removeTargets = function (txn, upperBound, activeTargetIds) {\r\n return this.delegate.removeTargets(txn, upperBound, activeTargetIds);\r\n };\r\n /**\r\n * Removes documents that have a sequence number equal to or less than the upper bound and are not\r\n * otherwise pinned.\r\n */\r\n LruGarbageCollector.prototype.removeOrphanedDocuments = function (txn, upperBound) {\r\n return this.delegate.removeOrphanedDocuments(txn, upperBound);\r\n };\r\n LruGarbageCollector.prototype.collect = function (txn, activeTargetIds) {\r\n var _this = this;\r\n if (this.params.cacheSizeCollectionThreshold === LruParams.COLLECTION_DISABLED) {\r\n debug('LruGarbageCollector', 'Garbage collection skipped; disabled');\r\n return PersistencePromise.resolve(GC_DID_NOT_RUN);\r\n }\r\n return this.getCacheSize(txn).next(function (cacheSize) {\r\n if (cacheSize < _this.params.cacheSizeCollectionThreshold) {\r\n debug('LruGarbageCollector', \"Garbage collection skipped; Cache size \" + cacheSize + \" \" +\r\n (\"is lower than threshold \" + _this.params.cacheSizeCollectionThreshold));\r\n return GC_DID_NOT_RUN;\r\n }\r\n else {\r\n return _this.runGarbageCollection(txn, activeTargetIds);\r\n }\r\n });\r\n };\r\n LruGarbageCollector.prototype.getCacheSize = function (txn) {\r\n return this.delegate.getCacheSize(txn);\r\n };\r\n LruGarbageCollector.prototype.runGarbageCollection = function (txn, activeTargetIds) {\r\n var _this = this;\r\n var upperBoundSequenceNumber;\r\n var sequenceNumbersToCollect, targetsRemoved;\r\n // Timestamps for various pieces of the process\r\n var startTs, countedTargetsTs, foundUpperBoundTs, removedTargetsTs, removedDocumentsTs;\r\n startTs = Date.now();\r\n return this.calculateTargetCount(txn, this.params.percentileToCollect)\r\n .next(function (sequenceNumbers) {\r\n // Cap at the configured max\r\n if (sequenceNumbers > _this.params.maximumSequenceNumbersToCollect) {\r\n debug('LruGarbageCollector', 'Capping sequence numbers to collect down ' +\r\n (\"to the maximum of \" + _this.params.maximumSequenceNumbersToCollect + \" \") +\r\n (\"from \" + sequenceNumbers));\r\n sequenceNumbersToCollect = _this.params\r\n .maximumSequenceNumbersToCollect;\r\n }\r\n else {\r\n sequenceNumbersToCollect = sequenceNumbers;\r\n }\r\n countedTargetsTs = Date.now();\r\n return _this.nthSequenceNumber(txn, sequenceNumbersToCollect);\r\n })\r\n .next(function (upperBound) {\r\n upperBoundSequenceNumber = upperBound;\r\n foundUpperBoundTs = Date.now();\r\n return _this.removeTargets(txn, upperBoundSequenceNumber, activeTargetIds);\r\n })\r\n .next(function (numTargetsRemoved) {\r\n targetsRemoved = numTargetsRemoved;\r\n removedTargetsTs = Date.now();\r\n return _this.removeOrphanedDocuments(txn, upperBoundSequenceNumber);\r\n })\r\n .next(function (documentsRemoved) {\r\n removedDocumentsTs = Date.now();\r\n if (getLogLevel() <= LogLevel.DEBUG) {\r\n var desc = 'LRU Garbage Collection\\n' +\r\n (\"\\tCounted targets in \" + (countedTargetsTs - startTs) + \"ms\\n\") +\r\n (\"\\tDetermined least recently used \" + sequenceNumbersToCollect + \" in \") +\r\n (foundUpperBoundTs - countedTargetsTs + \"ms\\n\") +\r\n (\"\\tRemoved \" + targetsRemoved + \" targets in \") +\r\n (removedTargetsTs - foundUpperBoundTs + \"ms\\n\") +\r\n (\"\\tRemoved \" + documentsRemoved + \" documents in \") +\r\n (removedDocumentsTs - removedTargetsTs + \"ms\\n\") +\r\n (\"Total Duration: \" + (removedDocumentsTs - startTs) + \"ms\");\r\n debug('LruGarbageCollector', desc);\r\n }\r\n return PersistencePromise.resolve({\r\n didRun: true,\r\n sequenceNumbersCollected: sequenceNumbersToCollect,\r\n targetsRemoved: targetsRemoved,\r\n documentsRemoved: documentsRemoved\r\n });\r\n });\r\n };\r\n return LruGarbageCollector;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Opaque interface representing a persistence transaction.\r\n *\r\n * When you call Persistence.runTransaction(), it will create a transaction and\r\n * pass it to your callback. You then pass it to any method that operates\r\n * on persistence.\r\n */\r\nvar PersistenceTransaction = /** @class */ (function () {\r\n function PersistenceTransaction() {\r\n }\r\n return PersistenceTransaction;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar LOG_TAG$2 = 'IndexedDbPersistence';\r\n/**\r\n * Oldest acceptable age in milliseconds for client metadata before the client\r\n * is considered inactive and its associated data (such as the remote document\r\n * cache changelog) is garbage collected.\r\n */\r\nvar MAX_CLIENT_AGE_MS = 30 * 60 * 1000; // 30 minutes\r\n/**\r\n * Oldest acceptable metadata age for clients that may participate in the\r\n * primary lease election. Clients that have not updated their client metadata\r\n * within 5 seconds are not eligible to receive a primary lease.\r\n */\r\nvar MAX_PRIMARY_ELIGIBLE_AGE_MS = 5000;\r\n/**\r\n * The interval at which clients will update their metadata, including\r\n * refreshing their primary lease if held or potentially trying to acquire it if\r\n * not held.\r\n *\r\n * Primary clients may opportunistically refresh their metadata earlier\r\n * if they're already performing an IndexedDB operation.\r\n */\r\nvar CLIENT_METADATA_REFRESH_INTERVAL_MS = 4000;\r\n/** User-facing error when the primary lease is required but not available. */\r\nvar PRIMARY_LEASE_LOST_ERROR_MSG = 'The current tab is not in the required state to perform this operation. ' +\r\n 'It might be necessary to refresh the browser tab.';\r\nvar PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG = 'Another tab has exclusive access to the persistence layer. ' +\r\n 'To allow shared access, make sure to invoke ' +\r\n '`enablePersistence()` with `experimentalTabSynchronization:true` in all tabs.';\r\nvar UNSUPPORTED_PLATFORM_ERROR_MSG = 'This platform is either missing' +\r\n ' IndexedDB or is known to have an incomplete implementation. Offline' +\r\n ' persistence has been disabled.';\r\n// The format of the LocalStorage key that stores zombied client is:\r\n// firestore_zombie__\r\nvar ZOMBIED_CLIENTS_KEY_PREFIX = 'firestore_zombie';\r\nvar IndexedDbTransaction = /** @class */ (function (_super) {\r\n tslib_1.__extends(IndexedDbTransaction, _super);\r\n function IndexedDbTransaction(simpleDbTransaction, currentSequenceNumber) {\r\n var _this = _super.call(this) || this;\r\n _this.simpleDbTransaction = simpleDbTransaction;\r\n _this.currentSequenceNumber = currentSequenceNumber;\r\n return _this;\r\n }\r\n return IndexedDbTransaction;\r\n}(PersistenceTransaction));\r\nvar IndexedDbPersistence = /** @class */ (function () {\r\n // Note that `multiClientParams` must be present to enable multi-client support while multi-tab\r\n // is still experimental. When multi-client is switched to always on, `multiClientParams` will\r\n // no longer be optional.\r\n function IndexedDbPersistence(persistenceKey, clientId, platform, queue, serializer, lruParams, multiClientParams) {\r\n this.persistenceKey = persistenceKey;\r\n this.clientId = clientId;\r\n this.queue = queue;\r\n this.multiClientParams = multiClientParams;\r\n this._started = false;\r\n this.isPrimary = false;\r\n this.networkEnabled = true;\r\n this.inForeground = false;\r\n /** The last time we garbage collected the Remote Document Changelog. */\r\n this.lastGarbageCollectionTime = Number.NEGATIVE_INFINITY;\r\n /** A listener to notify on primary state changes. */\r\n this.primaryStateListener = function (_) { return Promise.resolve(); };\r\n if (!IndexedDbPersistence.isAvailable()) {\r\n throw new FirestoreError(Code.UNIMPLEMENTED, UNSUPPORTED_PLATFORM_ERROR_MSG);\r\n }\r\n this.referenceDelegate = new IndexedDbLruDelegate(this, lruParams);\r\n this.dbName = persistenceKey + IndexedDbPersistence.MAIN_DATABASE;\r\n this.serializer = new LocalSerializer(serializer);\r\n this.document = platform.document;\r\n this.allowTabSynchronization = multiClientParams !== undefined;\r\n this.queryCache = new IndexedDbQueryCache(this.referenceDelegate, this.serializer);\r\n this.indexManager = new IndexedDbIndexManager();\r\n this.remoteDocumentCache = new IndexedDbRemoteDocumentCache(this.serializer, this.indexManager, \r\n /*keepDocumentChangeLog=*/ this.allowTabSynchronization);\r\n if (platform.window && platform.window.localStorage) {\r\n this.window = platform.window;\r\n this.webStorage = this.window.localStorage;\r\n }\r\n else {\r\n throw new FirestoreError(Code.UNIMPLEMENTED, 'IndexedDB persistence is only available on platforms that support LocalStorage.');\r\n }\r\n }\r\n IndexedDbPersistence.getStore = function (txn, store) {\r\n if (txn instanceof IndexedDbTransaction) {\r\n return SimpleDb.getStore(txn.simpleDbTransaction, store);\r\n }\r\n else {\r\n throw fail('IndexedDbPersistence must use instances of IndexedDbTransaction');\r\n }\r\n };\r\n IndexedDbPersistence.createIndexedDbPersistence = function (persistenceKey, clientId, platform, queue, serializer, lruParams) {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n var persistence;\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n persistence = new IndexedDbPersistence(persistenceKey, clientId, platform, queue, serializer, lruParams);\r\n return [4 /*yield*/, persistence.start()];\r\n case 1:\r\n _a.sent();\r\n return [2 /*return*/, persistence];\r\n }\r\n });\r\n });\r\n };\r\n IndexedDbPersistence.createMultiClientIndexedDbPersistence = function (persistenceKey, clientId, platform, queue, serializer, lruParams, multiClientParams) {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n var persistence;\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n persistence = new IndexedDbPersistence(persistenceKey, clientId, platform, queue, serializer, lruParams, multiClientParams);\r\n return [4 /*yield*/, persistence.start()];\r\n case 1:\r\n _a.sent();\r\n return [2 /*return*/, persistence];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * Attempt to start IndexedDb persistence.\r\n *\r\n * @return {Promise} Whether persistence was enabled.\r\n */\r\n IndexedDbPersistence.prototype.start = function () {\r\n var _this = this;\r\n assert(!this.started, 'IndexedDbPersistence double-started!');\r\n assert(this.window !== null, \"Expected 'window' to be defined\");\r\n return SimpleDb.openOrCreate(this.dbName, SCHEMA_VERSION, new SchemaConverter(this.serializer))\r\n .then(function (db) {\r\n _this.simpleDb = db;\r\n // NOTE: This is expected to fail sometimes (in the case of another tab already\r\n // having the persistence lock), so it's the first thing we should do.\r\n return _this.updateClientMetadataAndTryBecomePrimary();\r\n })\r\n .then(function () {\r\n _this.attachVisibilityHandler();\r\n _this.attachWindowUnloadHook();\r\n _this.scheduleClientMetadataAndPrimaryLeaseRefreshes();\r\n return _this.startRemoteDocumentCache();\r\n })\r\n .then(function () {\r\n return _this.simpleDb.runTransaction('readonly', [DbTargetGlobal.store], function (txn) {\r\n return getHighestListenSequenceNumber(txn).next(function (highestListenSequenceNumber) {\r\n var sequenceNumberSyncer = _this.multiClientParams\r\n ? _this.multiClientParams.sequenceNumberSyncer\r\n : undefined;\r\n _this.listenSequence = new ListenSequence(highestListenSequenceNumber, sequenceNumberSyncer);\r\n });\r\n });\r\n })\r\n .then(function () {\r\n _this._started = true;\r\n })\r\n .catch(function (reason) {\r\n _this.simpleDb && _this.simpleDb.close();\r\n return Promise.reject(reason);\r\n });\r\n };\r\n IndexedDbPersistence.prototype.startRemoteDocumentCache = function () {\r\n var _this = this;\r\n return this.simpleDb.runTransaction('readonly', ALL_STORES, function (txn) {\r\n return _this.remoteDocumentCache.start(txn);\r\n });\r\n };\r\n IndexedDbPersistence.prototype.setPrimaryStateListener = function (primaryStateListener) {\r\n var _this = this;\r\n this.primaryStateListener = function (primaryState) { return tslib_1.__awaiter(_this, void 0, void 0, function () {\r\n return tslib_1.__generator(this, function (_a) {\r\n if (this.started) {\r\n return [2 /*return*/, primaryStateListener(primaryState)];\r\n }\r\n return [2 /*return*/];\r\n });\r\n }); };\r\n return primaryStateListener(this.isPrimary);\r\n };\r\n IndexedDbPersistence.prototype.setNetworkEnabled = function (networkEnabled) {\r\n var _this = this;\r\n if (this.networkEnabled !== networkEnabled) {\r\n this.networkEnabled = networkEnabled;\r\n // Schedule a primary lease refresh for immediate execution. The eventual\r\n // lease update will be propagated via `primaryStateListener`.\r\n this.queue.enqueueAndForget(function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (!this.started) return [3 /*break*/, 2];\r\n return [4 /*yield*/, this.updateClientMetadataAndTryBecomePrimary()];\r\n case 1:\r\n _a.sent();\r\n _a.label = 2;\r\n case 2: return [2 /*return*/];\r\n }\r\n });\r\n }); });\r\n }\r\n };\r\n /**\r\n * Updates the client metadata in IndexedDb and attempts to either obtain or\r\n * extend the primary lease for the local client. Asynchronously notifies the\r\n * primary state listener if the client either newly obtained or released its\r\n * primary lease.\r\n */\r\n IndexedDbPersistence.prototype.updateClientMetadataAndTryBecomePrimary = function () {\r\n var _this = this;\r\n return this.simpleDb.runTransaction('readwrite', ALL_STORES, function (txn) {\r\n var metadataStore = clientMetadataStore(txn);\r\n return metadataStore\r\n .put(new DbClientMetadata(_this.clientId, Date.now(), _this.networkEnabled, _this.inForeground, _this.remoteDocumentCache.lastProcessedDocumentChangeId))\r\n .next(function () {\r\n if (_this.isPrimary) {\r\n return _this.verifyPrimaryLease(txn).next(function (success) {\r\n if (!success) {\r\n _this.isPrimary = false;\r\n _this.queue.enqueueAndForget(function () {\r\n return _this.primaryStateListener(false);\r\n });\r\n }\r\n });\r\n }\r\n })\r\n .next(function () { return _this.canActAsPrimary(txn); })\r\n .next(function (canActAsPrimary) {\r\n var wasPrimary = _this.isPrimary;\r\n _this.isPrimary = canActAsPrimary;\r\n if (wasPrimary !== _this.isPrimary) {\r\n _this.queue.enqueueAndForget(function () {\r\n return _this.primaryStateListener(_this.isPrimary);\r\n });\r\n }\r\n if (wasPrimary && !_this.isPrimary) {\r\n return _this.releasePrimaryLeaseIfHeld(txn);\r\n }\r\n else if (_this.isPrimary) {\r\n return _this.acquireOrExtendPrimaryLease(txn);\r\n }\r\n });\r\n });\r\n };\r\n IndexedDbPersistence.prototype.verifyPrimaryLease = function (txn) {\r\n var _this = this;\r\n var store = primaryClientStore(txn);\r\n return store.get(DbPrimaryClient.key).next(function (primaryClient) {\r\n return PersistencePromise.resolve(_this.isLocalClient(primaryClient));\r\n });\r\n };\r\n IndexedDbPersistence.prototype.removeClientMetadata = function (txn) {\r\n var metadataStore = clientMetadataStore(txn);\r\n return metadataStore.delete(this.clientId);\r\n };\r\n /**\r\n * If the garbage collection threshold has passed, prunes the\r\n * RemoteDocumentChanges and the ClientMetadata store based on the last update\r\n * time of all clients.\r\n */\r\n IndexedDbPersistence.prototype.maybeGarbageCollectMultiClientState = function () {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n var activeClients_1, inactiveClients_1;\r\n var _this = this;\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (!(this.isPrimary &&\r\n !this.isWithinAge(this.lastGarbageCollectionTime, MAX_CLIENT_AGE_MS))) return [3 /*break*/, 2];\r\n this.lastGarbageCollectionTime = Date.now();\r\n inactiveClients_1 = [];\r\n return [4 /*yield*/, this.runTransaction('maybeGarbageCollectMultiClientState', 'readwrite-primary', function (txn) {\r\n var metadataStore = IndexedDbPersistence.getStore(txn, DbClientMetadata.store);\r\n return metadataStore\r\n .loadAll()\r\n .next(function (existingClients) {\r\n activeClients_1 = _this.filterActiveClients(existingClients, MAX_CLIENT_AGE_MS);\r\n inactiveClients_1 = existingClients.filter(function (client) { return activeClients_1.indexOf(client) === -1; });\r\n })\r\n .next(function () {\r\n // Delete metadata for clients that are no longer considered active.\r\n return PersistencePromise.forEach(inactiveClients_1, function (inactiveClient) {\r\n return metadataStore.delete(inactiveClient.clientId);\r\n });\r\n })\r\n .next(function () {\r\n // Retrieve the minimum change ID from the set of active clients.\r\n // The primary client doesn't read from the document change log,\r\n // and hence we exclude it when we determine the minimum\r\n // `lastProcessedDocumentChangeId`.\r\n activeClients_1 = activeClients_1.filter(function (client) { return client.clientId !== _this.clientId; });\r\n if (activeClients_1.length > 0) {\r\n var processedChangeIds = activeClients_1.map(function (client) { return client.lastProcessedDocumentChangeId || 0; });\r\n var oldestChangeId = Math.min.apply(Math, processedChangeIds);\r\n return _this.remoteDocumentCache.removeDocumentChangesThroughChangeId(txn, oldestChangeId);\r\n }\r\n });\r\n })];\r\n case 1:\r\n _a.sent();\r\n // Delete potential leftover entries that may continue to mark the\r\n // inactive clients as zombied in LocalStorage.\r\n // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for\r\n // the client atomically, but we can't. So we opt to delete the IndexedDb\r\n // entries first to avoid potentially reviving a zombied client.\r\n inactiveClients_1.forEach(function (inactiveClient) {\r\n _this.window.localStorage.removeItem(_this.zombiedClientLocalStorageKey(inactiveClient.clientId));\r\n });\r\n _a.label = 2;\r\n case 2: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * Schedules a recurring timer to update the client metadata and to either\r\n * extend or acquire the primary lease if the client is eligible.\r\n */\r\n IndexedDbPersistence.prototype.scheduleClientMetadataAndPrimaryLeaseRefreshes = function () {\r\n var _this = this;\r\n this.clientMetadataRefresher = this.queue.enqueueAfterDelay(TimerId.ClientMetadataRefresh, CLIENT_METADATA_REFRESH_INTERVAL_MS, function () {\r\n return _this.updateClientMetadataAndTryBecomePrimary()\r\n .then(function () { return _this.maybeGarbageCollectMultiClientState(); })\r\n .then(function () { return _this.scheduleClientMetadataAndPrimaryLeaseRefreshes(); });\r\n });\r\n };\r\n /** Checks whether `client` is the local client. */\r\n IndexedDbPersistence.prototype.isLocalClient = function (client) {\r\n return client ? client.ownerId === this.clientId : false;\r\n };\r\n /**\r\n * Evaluate the state of all active clients and determine whether the local\r\n * client is or can act as the holder of the primary lease. Returns whether\r\n * the client is eligible for the lease, but does not actually acquire it.\r\n * May return 'false' even if there is no active leaseholder and another\r\n * (foreground) client should become leaseholder instead.\r\n */\r\n IndexedDbPersistence.prototype.canActAsPrimary = function (txn) {\r\n var _this = this;\r\n var store = primaryClientStore(txn);\r\n return store\r\n .get(DbPrimaryClient.key)\r\n .next(function (currentPrimary) {\r\n var currentLeaseIsValid = currentPrimary !== null &&\r\n _this.isWithinAge(currentPrimary.leaseTimestampMs, MAX_PRIMARY_ELIGIBLE_AGE_MS) &&\r\n !_this.isClientZombied(currentPrimary.ownerId);\r\n // A client is eligible for the primary lease if:\r\n // - its network is enabled and the client's tab is in the foreground.\r\n // - its network is enabled and no other client's tab is in the\r\n // foreground.\r\n // - every clients network is disabled and the client's tab is in the\r\n // foreground.\r\n // - every clients network is disabled and no other client's tab is in\r\n // the foreground.\r\n if (currentLeaseIsValid) {\r\n if (_this.isLocalClient(currentPrimary) && _this.networkEnabled) {\r\n return true;\r\n }\r\n if (!_this.isLocalClient(currentPrimary)) {\r\n if (!currentPrimary.allowTabSynchronization) {\r\n // Fail the `canActAsPrimary` check if the current leaseholder has\r\n // not opted into multi-tab synchronization. If this happens at\r\n // client startup, we reject the Promise returned by\r\n // `enablePersistence()` and the user can continue to use Firestore\r\n // with in-memory persistence.\r\n // If this fails during a lease refresh, we will instead block the\r\n // AsyncQueue from executing further operations. Note that this is\r\n // acceptable since mixing & matching different `synchronizeTabs`\r\n // settings is not supported.\r\n //\r\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can\r\n // no longer be turned off.\r\n throw new FirestoreError(Code.FAILED_PRECONDITION, PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG);\r\n }\r\n return false;\r\n }\r\n }\r\n if (_this.networkEnabled && _this.inForeground) {\r\n return true;\r\n }\r\n return clientMetadataStore(txn)\r\n .loadAll()\r\n .next(function (existingClients) {\r\n // Process all existing clients and determine whether at least one of\r\n // them is better suited to obtain the primary lease.\r\n var preferredCandidate = _this.filterActiveClients(existingClients, MAX_PRIMARY_ELIGIBLE_AGE_MS).find(function (otherClient) {\r\n if (_this.clientId !== otherClient.clientId) {\r\n var otherClientHasBetterNetworkState = !_this.networkEnabled && otherClient.networkEnabled;\r\n var otherClientHasBetterVisibility = !_this.inForeground && otherClient.inForeground;\r\n var otherClientHasSameNetworkState = _this.networkEnabled === otherClient.networkEnabled;\r\n if (otherClientHasBetterNetworkState ||\r\n (otherClientHasBetterVisibility &&\r\n otherClientHasSameNetworkState)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n });\r\n return preferredCandidate === undefined;\r\n });\r\n })\r\n .next(function (canActAsPrimary) {\r\n if (_this.isPrimary !== canActAsPrimary) {\r\n debug(LOG_TAG$2, \"Client \" + (canActAsPrimary ? 'is' : 'is not') + \" eligible for a primary lease.\");\r\n }\r\n return canActAsPrimary;\r\n });\r\n };\r\n IndexedDbPersistence.prototype.shutdown = function () {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n var _this = this;\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n // The shutdown() operations are idempotent and can be called even when\r\n // start() aborted (e.g. because it couldn't acquire the persistence lease).\r\n this._started = false;\r\n this.markClientZombied();\r\n if (this.clientMetadataRefresher) {\r\n this.clientMetadataRefresher.cancel();\r\n }\r\n this.detachVisibilityHandler();\r\n this.detachWindowUnloadHook();\r\n return [4 /*yield*/, this.simpleDb.runTransaction('readwrite', [DbPrimaryClient.store, DbClientMetadata.store], function (txn) {\r\n return _this.releasePrimaryLeaseIfHeld(txn).next(function () {\r\n return _this.removeClientMetadata(txn);\r\n });\r\n })];\r\n case 1:\r\n _a.sent();\r\n this.simpleDb.close();\r\n // Remove the entry marking the client as zombied from LocalStorage since\r\n // we successfully deleted its metadata from IndexedDb.\r\n this.removeClientZombiedEntry();\r\n return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * Returns clients that are not zombied and have an updateTime within the\r\n * provided threshold.\r\n */\r\n IndexedDbPersistence.prototype.filterActiveClients = function (clients, activityThresholdMs) {\r\n var _this = this;\r\n return clients.filter(function (client) {\r\n return _this.isWithinAge(client.updateTimeMs, activityThresholdMs) &&\r\n !_this.isClientZombied(client.clientId);\r\n });\r\n };\r\n IndexedDbPersistence.prototype.getActiveClients = function () {\r\n var _this = this;\r\n return this.simpleDb.runTransaction('readonly', [DbClientMetadata.store], function (txn) {\r\n return clientMetadataStore(txn)\r\n .loadAll()\r\n .next(function (clients) {\r\n return _this.filterActiveClients(clients, MAX_CLIENT_AGE_MS).map(function (clientMetadata) { return clientMetadata.clientId; });\r\n });\r\n });\r\n };\r\n IndexedDbPersistence.clearPersistence = function (persistenceKey) {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n var dbName;\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (!IndexedDbPersistence.isAvailable()) {\r\n return [2 /*return*/, Promise.resolve()];\r\n }\r\n dbName = persistenceKey + IndexedDbPersistence.MAIN_DATABASE;\r\n return [4 /*yield*/, SimpleDb.delete(dbName)];\r\n case 1:\r\n _a.sent();\r\n return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n Object.defineProperty(IndexedDbPersistence.prototype, \"started\", {\r\n get: function () {\r\n return this._started;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n IndexedDbPersistence.prototype.getMutationQueue = function (user) {\r\n assert(this.started, 'Cannot initialize MutationQueue before persistence is started.');\r\n return IndexedDbMutationQueue.forUser(user, this.serializer, this.indexManager, this.referenceDelegate);\r\n };\r\n IndexedDbPersistence.prototype.getQueryCache = function () {\r\n assert(this.started, 'Cannot initialize QueryCache before persistence is started.');\r\n return this.queryCache;\r\n };\r\n IndexedDbPersistence.prototype.getRemoteDocumentCache = function () {\r\n assert(this.started, 'Cannot initialize RemoteDocumentCache before persistence is started.');\r\n return this.remoteDocumentCache;\r\n };\r\n IndexedDbPersistence.prototype.getIndexManager = function () {\r\n assert(this.started, 'Cannot initialize IndexManager before persistence is started.');\r\n return this.indexManager;\r\n };\r\n IndexedDbPersistence.prototype.runTransaction = function (action, mode, transactionOperation) {\r\n var _this = this;\r\n debug(LOG_TAG$2, 'Starting transaction:', action);\r\n // Do all transactions as readwrite against all object stores, since we\r\n // are the only reader/writer.\r\n return this.simpleDb.runTransaction(mode === 'readonly' ? 'readonly' : 'readwrite', ALL_STORES, function (simpleDbTxn) {\r\n if (mode === 'readwrite-primary') {\r\n // While we merely verify that we have (or can acquire) the lease\r\n // immediately, we wait to extend the primary lease until after\r\n // executing transactionOperation(). This ensures that even if the\r\n // transactionOperation takes a long time, we'll use a recent\r\n // leaseTimestampMs in the extended (or newly acquired) lease.\r\n return _this.verifyPrimaryLease(simpleDbTxn)\r\n .next(function (success) {\r\n if (!success) {\r\n error(\"Failed to obtain primary lease for action '\" + action + \"'.\");\r\n _this.isPrimary = false;\r\n _this.queue.enqueueAndForget(function () {\r\n return _this.primaryStateListener(false);\r\n });\r\n throw new FirestoreError(Code.FAILED_PRECONDITION, PRIMARY_LEASE_LOST_ERROR_MSG);\r\n }\r\n return transactionOperation(new IndexedDbTransaction(simpleDbTxn, _this.listenSequence.next()));\r\n })\r\n .next(function (result) {\r\n return _this.acquireOrExtendPrimaryLease(simpleDbTxn).next(function () { return result; });\r\n });\r\n }\r\n else {\r\n return _this.verifyAllowTabSynchronization(simpleDbTxn).next(function () {\r\n return transactionOperation(new IndexedDbTransaction(simpleDbTxn, _this.listenSequence.next()));\r\n });\r\n }\r\n });\r\n };\r\n /**\r\n * Verifies that the current tab is the primary leaseholder or alternatively\r\n * that the leaseholder has opted into multi-tab synchronization.\r\n */\r\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer\r\n // be turned off.\r\n IndexedDbPersistence.prototype.verifyAllowTabSynchronization = function (txn) {\r\n var _this = this;\r\n var store = primaryClientStore(txn);\r\n return store.get(DbPrimaryClient.key).next(function (currentPrimary) {\r\n var currentLeaseIsValid = currentPrimary !== null &&\r\n _this.isWithinAge(currentPrimary.leaseTimestampMs, MAX_PRIMARY_ELIGIBLE_AGE_MS) &&\r\n !_this.isClientZombied(currentPrimary.ownerId);\r\n if (currentLeaseIsValid && !_this.isLocalClient(currentPrimary)) {\r\n if (!currentPrimary.allowTabSynchronization) {\r\n throw new FirestoreError(Code.FAILED_PRECONDITION, PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG);\r\n }\r\n }\r\n });\r\n };\r\n /**\r\n * Obtains or extends the new primary lease for the local client. This\r\n * method does not verify that the client is eligible for this lease.\r\n */\r\n IndexedDbPersistence.prototype.acquireOrExtendPrimaryLease = function (txn) {\r\n var newPrimary = new DbPrimaryClient(this.clientId, this.allowTabSynchronization, Date.now());\r\n return primaryClientStore(txn).put(DbPrimaryClient.key, newPrimary);\r\n };\r\n IndexedDbPersistence.isAvailable = function () {\r\n return SimpleDb.isAvailable();\r\n };\r\n /**\r\n * Generates a string used as a prefix when storing data in IndexedDB and\r\n * LocalStorage.\r\n */\r\n IndexedDbPersistence.buildStoragePrefix = function (databaseInfo) {\r\n // Use two different prefix formats:\r\n //\r\n // * firestore / persistenceKey / projectID . databaseID / ...\r\n // * firestore / persistenceKey / projectID / ...\r\n //\r\n // projectIDs are DNS-compatible names and cannot contain dots\r\n // so there's no danger of collisions.\r\n var database = databaseInfo.databaseId.projectId;\r\n if (!databaseInfo.databaseId.isDefaultDatabase) {\r\n database += '.' + databaseInfo.databaseId.database;\r\n }\r\n return 'firestore/' + databaseInfo.persistenceKey + '/' + database + '/';\r\n };\r\n /** Checks the primary lease and removes it if we are the current primary. */\r\n IndexedDbPersistence.prototype.releasePrimaryLeaseIfHeld = function (txn) {\r\n var _this = this;\r\n var store = primaryClientStore(txn);\r\n return store.get(DbPrimaryClient.key).next(function (primaryClient) {\r\n if (_this.isLocalClient(primaryClient)) {\r\n debug(LOG_TAG$2, 'Releasing primary lease.');\r\n return store.delete(DbPrimaryClient.key);\r\n }\r\n else {\r\n return PersistencePromise.resolve();\r\n }\r\n });\r\n };\r\n /** Verifies that `updateTimeMs` is within `maxAgeMs`. */\r\n IndexedDbPersistence.prototype.isWithinAge = function (updateTimeMs, maxAgeMs) {\r\n var now = Date.now();\r\n var minAcceptable = now - maxAgeMs;\r\n var maxAcceptable = now;\r\n if (updateTimeMs < minAcceptable) {\r\n return false;\r\n }\r\n else if (updateTimeMs > maxAcceptable) {\r\n error(\"Detected an update time that is in the future: \" + updateTimeMs + \" > \" + maxAcceptable);\r\n return false;\r\n }\r\n return true;\r\n };\r\n IndexedDbPersistence.prototype.attachVisibilityHandler = function () {\r\n var _this = this;\r\n if (this.document !== null &&\r\n typeof this.document.addEventListener === 'function') {\r\n this.documentVisibilityHandler = function () {\r\n _this.queue.enqueueAndForget(function () {\r\n _this.inForeground = _this.document.visibilityState === 'visible';\r\n return _this.updateClientMetadataAndTryBecomePrimary();\r\n });\r\n };\r\n this.document.addEventListener('visibilitychange', this.documentVisibilityHandler);\r\n this.inForeground = this.document.visibilityState === 'visible';\r\n }\r\n };\r\n IndexedDbPersistence.prototype.detachVisibilityHandler = function () {\r\n if (this.documentVisibilityHandler) {\r\n assert(this.document !== null &&\r\n typeof this.document.addEventListener === 'function', \"Expected 'document.addEventListener' to be a function\");\r\n this.document.removeEventListener('visibilitychange', this.documentVisibilityHandler);\r\n this.documentVisibilityHandler = null;\r\n }\r\n };\r\n /**\r\n * Attaches a window.unload handler that will synchronously write our\r\n * clientId to a \"zombie client id\" location in LocalStorage. This can be used\r\n * by tabs trying to acquire the primary lease to determine that the lease\r\n * is no longer valid even if the timestamp is recent. This is particularly\r\n * important for the refresh case (so the tab correctly re-acquires the\r\n * primary lease). LocalStorage is used for this rather than IndexedDb because\r\n * it is a synchronous API and so can be used reliably from an unload\r\n * handler.\r\n */\r\n IndexedDbPersistence.prototype.attachWindowUnloadHook = function () {\r\n var _this = this;\r\n if (typeof this.window.addEventListener === 'function') {\r\n this.windowUnloadHandler = function () {\r\n // Note: In theory, this should be scheduled on the AsyncQueue since it\r\n // accesses internal state. We execute this code directly during shutdown\r\n // to make sure it gets a chance to run.\r\n _this.markClientZombied();\r\n _this.queue.enqueueAndForget(function () {\r\n // Attempt graceful shutdown (including releasing our primary lease),\r\n // but there's no guarantee it will complete.\r\n return _this.shutdown();\r\n });\r\n };\r\n this.window.addEventListener('unload', this.windowUnloadHandler);\r\n }\r\n };\r\n IndexedDbPersistence.prototype.detachWindowUnloadHook = function () {\r\n if (this.windowUnloadHandler) {\r\n assert(typeof this.window.removeEventListener === 'function', \"Expected 'window.removeEventListener' to be a function\");\r\n this.window.removeEventListener('unload', this.windowUnloadHandler);\r\n this.windowUnloadHandler = null;\r\n }\r\n };\r\n /**\r\n * Returns whether a client is \"zombied\" based on its LocalStorage entry.\r\n * Clients become zombied when their tab closes without running all of the\r\n * cleanup logic in `shutdown()`.\r\n */\r\n IndexedDbPersistence.prototype.isClientZombied = function (clientId) {\r\n try {\r\n var isZombied = this.webStorage.getItem(this.zombiedClientLocalStorageKey(clientId)) !==\r\n null;\r\n debug(LOG_TAG$2, \"Client '\" + clientId + \"' \" + (isZombied ? 'is' : 'is not') + \" zombied in LocalStorage\");\r\n return isZombied;\r\n }\r\n catch (e) {\r\n // Gracefully handle if LocalStorage isn't working.\r\n error(LOG_TAG$2, 'Failed to get zombied client id.', e);\r\n return false;\r\n }\r\n };\r\n /**\r\n * Record client as zombied (a client that had its tab closed). Zombied\r\n * clients are ignored during primary tab selection.\r\n */\r\n IndexedDbPersistence.prototype.markClientZombied = function () {\r\n try {\r\n this.webStorage.setItem(this.zombiedClientLocalStorageKey(this.clientId), String(Date.now()));\r\n }\r\n catch (e) {\r\n // Gracefully handle if LocalStorage isn't available / working.\r\n error('Failed to set zombie client id.', e);\r\n }\r\n };\r\n /** Removes the zombied client entry if it exists. */\r\n IndexedDbPersistence.prototype.removeClientZombiedEntry = function () {\r\n try {\r\n this.webStorage.removeItem(this.zombiedClientLocalStorageKey(this.clientId));\r\n }\r\n catch (e) {\r\n // Ignore\r\n }\r\n };\r\n IndexedDbPersistence.prototype.zombiedClientLocalStorageKey = function (clientId) {\r\n return ZOMBIED_CLIENTS_KEY_PREFIX + \"_\" + this.persistenceKey + \"_\" + clientId;\r\n };\r\n /**\r\n * The name of the main (and currently only) IndexedDB database. this name is\r\n * appended to the prefix provided to the IndexedDbPersistence constructor.\r\n */\r\n IndexedDbPersistence.MAIN_DATABASE = 'main';\r\n return IndexedDbPersistence;\r\n}());\r\nfunction isPrimaryLeaseLostError(err) {\r\n return (err.code === Code.FAILED_PRECONDITION &&\r\n err.message === PRIMARY_LEASE_LOST_ERROR_MSG);\r\n}\r\n/**\r\n * Verifies the error thrown by a LocalStore operation. If a LocalStore\r\n * operation fails because the primary lease has been taken by another client,\r\n * we ignore the error (the persistence layer will immediately call\r\n * `applyPrimaryLease` to propagate the primary state change). All other errors\r\n * are re-thrown.\r\n *\r\n * @param err An error returned by a LocalStore operation.\r\n * @return A Promise that resolves after we recovered, or the original error.\r\n */\r\nfunction ignoreIfPrimaryLeaseLoss(err) {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n return tslib_1.__generator(this, function (_a) {\r\n if (isPrimaryLeaseLostError(err)) {\r\n debug(LOG_TAG$2, 'Unexpectedly lost primary lease');\r\n }\r\n else {\r\n throw err;\r\n }\r\n return [2 /*return*/];\r\n });\r\n });\r\n}\r\n/**\r\n * Helper to get a typed SimpleDbStore for the primary client object store.\r\n */\r\nfunction primaryClientStore(txn) {\r\n return txn.store(DbPrimaryClient.store);\r\n}\r\n/**\r\n * Helper to get a typed SimpleDbStore for the client metadata object store.\r\n */\r\nfunction clientMetadataStore(txn) {\r\n return txn.store(DbClientMetadata.store);\r\n}\r\n/** Provides LRU functionality for IndexedDB persistence. */\r\nvar IndexedDbLruDelegate = /** @class */ (function () {\r\n function IndexedDbLruDelegate(db, params) {\r\n this.db = db;\r\n this.garbageCollector = new LruGarbageCollector(this, params);\r\n }\r\n IndexedDbLruDelegate.prototype.getSequenceNumberCount = function (txn) {\r\n var docCountPromise = this.orphanedDocmentCount(txn);\r\n var targetCountPromise = this.db.getQueryCache().getQueryCount(txn);\r\n return targetCountPromise.next(function (targetCount) {\r\n return docCountPromise.next(function (docCount) { return targetCount + docCount; });\r\n });\r\n };\r\n IndexedDbLruDelegate.prototype.orphanedDocmentCount = function (txn) {\r\n var orphanedCount = 0;\r\n return this.forEachOrphanedDocumentSequenceNumber(txn, function (_) {\r\n orphanedCount++;\r\n }).next(function () { return orphanedCount; });\r\n };\r\n IndexedDbLruDelegate.prototype.forEachTarget = function (txn, f) {\r\n return this.db.getQueryCache().forEachTarget(txn, f);\r\n };\r\n IndexedDbLruDelegate.prototype.forEachOrphanedDocumentSequenceNumber = function (txn, f) {\r\n return this.forEachOrphanedDocument(txn, function (docKey, sequenceNumber) {\r\n return f(sequenceNumber);\r\n });\r\n };\r\n IndexedDbLruDelegate.prototype.setInMemoryPins = function (inMemoryPins) {\r\n this.inMemoryPins = inMemoryPins;\r\n };\r\n IndexedDbLruDelegate.prototype.addReference = function (txn, key) {\r\n return writeSentinelKey(txn, key);\r\n };\r\n IndexedDbLruDelegate.prototype.removeReference = function (txn, key) {\r\n return writeSentinelKey(txn, key);\r\n };\r\n IndexedDbLruDelegate.prototype.removeTargets = function (txn, upperBound, activeTargetIds) {\r\n return this.db\r\n .getQueryCache()\r\n .removeTargets(txn, upperBound, activeTargetIds);\r\n };\r\n IndexedDbLruDelegate.prototype.removeMutationReference = function (txn, key) {\r\n return writeSentinelKey(txn, key);\r\n };\r\n /**\r\n * Returns true if anything would prevent this document from being garbage\r\n * collected, given that the document in question is not present in any\r\n * targets and has a sequence number less than or equal to the upper bound for\r\n * the collection run.\r\n */\r\n IndexedDbLruDelegate.prototype.isPinned = function (txn, docKey) {\r\n if (this.inMemoryPins.containsKey(docKey)) {\r\n return PersistencePromise.resolve(true);\r\n }\r\n else {\r\n return mutationQueuesContainKey(txn, docKey);\r\n }\r\n };\r\n IndexedDbLruDelegate.prototype.removeOrphanedDocuments = function (txn, upperBound) {\r\n var _this = this;\r\n var count = 0;\r\n var bytesRemoved = 0;\r\n var promises = [];\r\n var iteration = this.forEachOrphanedDocument(txn, function (docKey, sequenceNumber) {\r\n if (sequenceNumber <= upperBound) {\r\n var p = _this.isPinned(txn, docKey).next(function (isPinned) {\r\n if (!isPinned) {\r\n count++;\r\n return _this.removeOrphanedDocument(txn, docKey).next(function (documentBytes) {\r\n bytesRemoved += documentBytes;\r\n });\r\n }\r\n });\r\n promises.push(p);\r\n }\r\n });\r\n // Wait for iteration first to make sure we have a chance to add all of the\r\n // removal promises to the array.\r\n return iteration\r\n .next(function () { return PersistencePromise.waitFor(promises); })\r\n .next(function () {\r\n return _this.db.getRemoteDocumentCache().updateSize(txn, -bytesRemoved);\r\n })\r\n .next(function () { return count; });\r\n };\r\n /**\r\n * Clears a document from the cache. The document is assumed to be orphaned, so target-document\r\n * associations are not queried. We remove it from the remote document cache, as well as remove\r\n * its sentinel row.\r\n */\r\n IndexedDbLruDelegate.prototype.removeOrphanedDocument = function (txn, docKey) {\r\n var totalBytesRemoved = 0;\r\n var documentCache = this.db.getRemoteDocumentCache();\r\n return PersistencePromise.waitFor([\r\n documentTargetStore(txn).delete(sentinelKey$1(docKey)),\r\n documentCache.removeEntry(txn, docKey).next(function (bytesRemoved) {\r\n totalBytesRemoved += bytesRemoved;\r\n })\r\n ]).next(function () { return totalBytesRemoved; });\r\n };\r\n IndexedDbLruDelegate.prototype.removeTarget = function (txn, queryData) {\r\n var updated = queryData.copy({\r\n sequenceNumber: txn.currentSequenceNumber\r\n });\r\n return this.db.getQueryCache().updateQueryData(txn, updated);\r\n };\r\n IndexedDbLruDelegate.prototype.updateLimboDocument = function (txn, key) {\r\n return writeSentinelKey(txn, key);\r\n };\r\n /**\r\n * Call provided function for each document in the cache that is 'orphaned'. Orphaned\r\n * means not a part of any target, so the only entry in the target-document index for\r\n * that document will be the sentinel row (targetId 0), which will also have the sequence\r\n * number for the last time the document was accessed.\r\n */\r\n IndexedDbLruDelegate.prototype.forEachOrphanedDocument = function (txn, f) {\r\n var store = documentTargetStore(txn);\r\n var nextToReport = ListenSequence.INVALID;\r\n var nextPath;\r\n return store\r\n .iterate({\r\n index: DbTargetDocument.documentTargetsIndex\r\n }, function (_a, _b) {\r\n var targetId = _a[0], docKey = _a[1];\r\n var path = _b.path, sequenceNumber = _b.sequenceNumber;\r\n if (targetId === 0) {\r\n // if nextToReport is valid, report it, this is a new key so the\r\n // last one must not be a member of any targets.\r\n if (nextToReport !== ListenSequence.INVALID) {\r\n f(new DocumentKey(decode(nextPath)), nextToReport);\r\n }\r\n // set nextToReport to be this sequence number. It's the next one we\r\n // might report, if we don't find any targets for this document.\r\n // Note that the sequence number must be defined when the targetId\r\n // is 0.\r\n nextToReport = sequenceNumber;\r\n nextPath = path;\r\n }\r\n else {\r\n // set nextToReport to be invalid, we know we don't need to report\r\n // this one since we found a target for it.\r\n nextToReport = ListenSequence.INVALID;\r\n }\r\n })\r\n .next(function () {\r\n // Since we report sequence numbers after getting to the next key, we\r\n // need to check if the last key we iterated over was an orphaned\r\n // document and report it.\r\n if (nextToReport !== ListenSequence.INVALID) {\r\n f(new DocumentKey(decode(nextPath)), nextToReport);\r\n }\r\n });\r\n };\r\n IndexedDbLruDelegate.prototype.getCacheSize = function (txn) {\r\n return this.db.getRemoteDocumentCache().getSize(txn);\r\n };\r\n return IndexedDbLruDelegate;\r\n}());\r\nfunction sentinelKey$1(key) {\r\n return [0, encode(key.path)];\r\n}\r\n/**\r\n * @return A value suitable for writing a sentinel row in the target-document\r\n * store.\r\n */\r\nfunction sentinelRow(key, sequenceNumber) {\r\n return new DbTargetDocument(0, encode(key.path), sequenceNumber);\r\n}\r\nfunction writeSentinelKey(txn, key) {\r\n return documentTargetStore(txn).put(sentinelRow(key, txn.currentSequenceNumber));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A readonly view of the local state of all documents we're tracking (i.e. we\r\n * have a cached version in remoteDocumentCache or local mutations for the\r\n * document). The view is computed by applying the mutations in the\r\n * MutationQueue to the RemoteDocumentCache.\r\n */\r\nvar LocalDocumentsView = /** @class */ (function () {\r\n function LocalDocumentsView(remoteDocumentCache, mutationQueue, indexManager) {\r\n this.remoteDocumentCache = remoteDocumentCache;\r\n this.mutationQueue = mutationQueue;\r\n this.indexManager = indexManager;\r\n }\r\n /**\r\n * Get the local view of the document identified by `key`.\r\n *\r\n * @return Local view of the document or null if we don't have any cached\r\n * state for it.\r\n */\r\n LocalDocumentsView.prototype.getDocument = function (transaction, key) {\r\n var _this = this;\r\n return this.mutationQueue\r\n .getAllMutationBatchesAffectingDocumentKey(transaction, key)\r\n .next(function (batches) { return _this.getDocumentInternal(transaction, key, batches); });\r\n };\r\n /** Internal version of `getDocument` that allows reusing batches. */\r\n LocalDocumentsView.prototype.getDocumentInternal = function (transaction, key, inBatches) {\r\n return this.remoteDocumentCache.getEntry(transaction, key).next(function (doc) {\r\n for (var _i = 0, inBatches_1 = inBatches; _i < inBatches_1.length; _i++) {\r\n var batch = inBatches_1[_i];\r\n doc = batch.applyToLocalView(key, doc);\r\n }\r\n return doc;\r\n });\r\n };\r\n // Returns the view of the given `docs` as they would appear after applying\r\n // all mutations in the given `batches`.\r\n LocalDocumentsView.prototype.applyLocalMutationsToDocuments = function (transaction, docs, batches) {\r\n var results = nullableMaybeDocumentMap();\r\n docs.forEach(function (key, localView) {\r\n for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {\r\n var batch = batches_1[_i];\r\n localView = batch.applyToLocalView(key, localView);\r\n }\r\n results = results.insert(key, localView);\r\n });\r\n return results;\r\n };\r\n /**\r\n * Gets the local view of the documents identified by `keys`.\r\n *\r\n * If we don't have cached state for a document in `keys`, a NoDocument will\r\n * be stored for that key in the resulting set.\r\n */\r\n LocalDocumentsView.prototype.getDocuments = function (transaction, keys) {\r\n var _this = this;\r\n return this.remoteDocumentCache\r\n .getEntries(transaction, keys)\r\n .next(function (docs) { return _this.getLocalViewOfDocuments(transaction, docs); });\r\n };\r\n /**\r\n * Similar to `getDocuments`, but creates the local view from the given\r\n * `baseDocs` without retrieving documents from the local store.\r\n */\r\n LocalDocumentsView.prototype.getLocalViewOfDocuments = function (transaction, baseDocs) {\r\n var _this = this;\r\n return this.mutationQueue\r\n .getAllMutationBatchesAffectingDocumentKeys(transaction, baseDocs)\r\n .next(function (batches) {\r\n var docs = _this.applyLocalMutationsToDocuments(transaction, baseDocs, batches);\r\n var results = maybeDocumentMap();\r\n docs.forEach(function (key, maybeDoc) {\r\n // TODO(http://b/32275378): Don't conflate missing / deleted.\r\n if (!maybeDoc) {\r\n maybeDoc = new NoDocument(key, SnapshotVersion.forDeletedDoc());\r\n }\r\n results = results.insert(key, maybeDoc);\r\n });\r\n return results;\r\n });\r\n };\r\n /** Performs a query against the local view of all documents. */\r\n LocalDocumentsView.prototype.getDocumentsMatchingQuery = function (transaction, query) {\r\n if (query.isDocumentQuery()) {\r\n return this.getDocumentsMatchingDocumentQuery(transaction, query.path);\r\n }\r\n else if (query.isCollectionGroupQuery()) {\r\n return this.getDocumentsMatchingCollectionGroupQuery(transaction, query);\r\n }\r\n else {\r\n return this.getDocumentsMatchingCollectionQuery(transaction, query);\r\n }\r\n };\r\n LocalDocumentsView.prototype.getDocumentsMatchingDocumentQuery = function (transaction, docPath) {\r\n // Just do a simple document lookup.\r\n return this.getDocument(transaction, new DocumentKey(docPath)).next(function (maybeDoc) {\r\n var result = documentMap();\r\n if (maybeDoc instanceof Document) {\r\n result = result.insert(maybeDoc.key, maybeDoc);\r\n }\r\n return result;\r\n });\r\n };\r\n LocalDocumentsView.prototype.getDocumentsMatchingCollectionGroupQuery = function (transaction, query) {\r\n var _this = this;\r\n assert(query.path.isEmpty(), 'Currently we only support collection group queries at the root.');\r\n var collectionId = query.collectionGroup;\r\n var results = documentMap();\r\n return this.indexManager\r\n .getCollectionParents(transaction, collectionId)\r\n .next(function (parents) {\r\n // Perform a collection query against each parent that contains the\r\n // collectionId and aggregate the results.\r\n return PersistencePromise.forEach(parents, function (parent) {\r\n var collectionQuery = query.asCollectionQueryAtPath(parent.child(collectionId));\r\n return _this.getDocumentsMatchingCollectionQuery(transaction, collectionQuery).next(function (r) {\r\n r.forEach(function (key, doc) {\r\n results = results.insert(key, doc);\r\n });\r\n });\r\n }).next(function () { return results; });\r\n });\r\n };\r\n LocalDocumentsView.prototype.getDocumentsMatchingCollectionQuery = function (transaction, query) {\r\n var _this = this;\r\n // Query the remote documents and overlay mutations.\r\n var results;\r\n return this.remoteDocumentCache\r\n .getDocumentsMatchingQuery(transaction, query)\r\n .next(function (queryResults) {\r\n results = queryResults;\r\n return _this.mutationQueue.getAllMutationBatchesAffectingQuery(transaction, query);\r\n })\r\n .next(function (matchingMutationBatches) {\r\n for (var _i = 0, matchingMutationBatches_1 = matchingMutationBatches; _i < matchingMutationBatches_1.length; _i++) {\r\n var batch = matchingMutationBatches_1[_i];\r\n for (var _a = 0, _b = batch.mutations; _a < _b.length; _a++) {\r\n var mutation = _b[_a];\r\n var key = mutation.key;\r\n // Only process documents belonging to the collection.\r\n if (!query.path.isImmediateParentOf(key.path)) {\r\n continue;\r\n }\r\n var baseDoc = results.get(key);\r\n var mutatedDoc = mutation.applyToLocalView(baseDoc, baseDoc, batch.localWriteTime);\r\n if (mutatedDoc instanceof Document) {\r\n results = results.insert(key, mutatedDoc);\r\n }\r\n else {\r\n results = results.remove(key);\r\n }\r\n }\r\n }\r\n })\r\n .next(function () {\r\n // Finally, filter out any documents that don't actually match\r\n // the query.\r\n results.forEach(function (key, doc) {\r\n if (!query.matches(doc)) {\r\n results = results.remove(key);\r\n }\r\n });\r\n return results;\r\n });\r\n };\r\n return LocalDocumentsView;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A collection of references to a document from some kind of numbered entity\r\n * (either a target ID or batch ID). As references are added to or removed from\r\n * the set corresponding events are emitted to a registered garbage collector.\r\n *\r\n * Each reference is represented by a DocumentReference object. Each of them\r\n * contains enough information to uniquely identify the reference. They are all\r\n * stored primarily in a set sorted by key. A document is considered garbage if\r\n * there's no references in that set (this can be efficiently checked thanks to\r\n * sorting by key).\r\n *\r\n * ReferenceSet also keeps a secondary set that contains references sorted by\r\n * IDs. This one is used to efficiently implement removal of all references by\r\n * some target ID.\r\n */\r\nvar ReferenceSet = /** @class */ (function () {\r\n function ReferenceSet() {\r\n // A set of outstanding references to a document sorted by key.\r\n this.refsByKey = new SortedSet(DocReference.compareByKey);\r\n // A set of outstanding references to a document sorted by target id.\r\n this.refsByTarget = new SortedSet(DocReference.compareByTargetId);\r\n }\r\n /** Returns true if the reference set contains no references. */\r\n ReferenceSet.prototype.isEmpty = function () {\r\n return this.refsByKey.isEmpty();\r\n };\r\n /** Adds a reference to the given document key for the given ID. */\r\n ReferenceSet.prototype.addReference = function (key, id) {\r\n var ref = new DocReference(key, id);\r\n this.refsByKey = this.refsByKey.add(ref);\r\n this.refsByTarget = this.refsByTarget.add(ref);\r\n };\r\n /** Add references to the given document keys for the given ID. */\r\n ReferenceSet.prototype.addReferences = function (keys, id) {\r\n var _this = this;\r\n keys.forEach(function (key) { return _this.addReference(key, id); });\r\n };\r\n /**\r\n * Removes a reference to the given document key for the given\r\n * ID.\r\n */\r\n ReferenceSet.prototype.removeReference = function (key, id) {\r\n this.removeRef(new DocReference(key, id));\r\n };\r\n ReferenceSet.prototype.removeReferences = function (keys, id) {\r\n var _this = this;\r\n keys.forEach(function (key) { return _this.removeReference(key, id); });\r\n };\r\n /**\r\n * Clears all references with a given ID. Calls removeRef() for each key\r\n * removed.\r\n */\r\n ReferenceSet.prototype.removeReferencesForId = function (id) {\r\n var _this = this;\r\n var emptyKey = DocumentKey.EMPTY;\r\n var startRef = new DocReference(emptyKey, id);\r\n var endRef = new DocReference(emptyKey, id + 1);\r\n var keys = [];\r\n this.refsByTarget.forEachInRange([startRef, endRef], function (ref) {\r\n _this.removeRef(ref);\r\n keys.push(ref.key);\r\n });\r\n return keys;\r\n };\r\n ReferenceSet.prototype.removeAllReferences = function () {\r\n var _this = this;\r\n this.refsByKey.forEach(function (ref) { return _this.removeRef(ref); });\r\n };\r\n ReferenceSet.prototype.removeRef = function (ref) {\r\n this.refsByKey = this.refsByKey.delete(ref);\r\n this.refsByTarget = this.refsByTarget.delete(ref);\r\n };\r\n ReferenceSet.prototype.referencesForId = function (id) {\r\n var emptyKey = DocumentKey.EMPTY;\r\n var startRef = new DocReference(emptyKey, id);\r\n var endRef = new DocReference(emptyKey, id + 1);\r\n var keys = documentKeySet();\r\n this.refsByTarget.forEachInRange([startRef, endRef], function (ref) {\r\n keys = keys.add(ref.key);\r\n });\r\n return keys;\r\n };\r\n ReferenceSet.prototype.containsKey = function (key) {\r\n var ref = new DocReference(key, 0);\r\n var firstRef = this.refsByKey.firstAfterOrEqual(ref);\r\n return firstRef !== null && key.isEqual(firstRef.key);\r\n };\r\n return ReferenceSet;\r\n}());\r\nvar DocReference = /** @class */ (function () {\r\n function DocReference(key, targetOrBatchId) {\r\n this.key = key;\r\n this.targetOrBatchId = targetOrBatchId;\r\n }\r\n /** Compare by key then by ID */\r\n DocReference.compareByKey = function (left, right) {\r\n return (DocumentKey.comparator(left.key, right.key) ||\r\n primitiveComparator(left.targetOrBatchId, right.targetOrBatchId));\r\n };\r\n /** Compare by ID then by key */\r\n DocReference.compareByTargetId = function (left, right) {\r\n return (primitiveComparator(left.targetOrBatchId, right.targetOrBatchId) ||\r\n DocumentKey.comparator(left.key, right.key));\r\n };\r\n return DocReference;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar LOG_TAG$3 = 'LocalStore';\r\n/**\r\n * Local storage in the Firestore client. Coordinates persistence components\r\n * like the mutation queue and remote document cache to present a\r\n * latency-compensated view of stored data.\r\n *\r\n * The LocalStore is responsible for accepting mutations from the Sync Engine.\r\n * Writes from the client are put into a queue as provisional Mutations until\r\n * they are processed by the RemoteStore and confirmed as having been written\r\n * to the server.\r\n *\r\n * The local store provides the local version of documents that have been\r\n * modified locally. It maintains the constraint:\r\n *\r\n * LocalDocument = RemoteDocument + Active(LocalMutations)\r\n *\r\n * (Active mutations are those that are enqueued and have not been previously\r\n * acknowledged or rejected).\r\n *\r\n * The RemoteDocument (\"ground truth\") state is provided via the\r\n * applyChangeBatch method. It will be some version of a server-provided\r\n * document OR will be a server-provided document PLUS acknowledged mutations:\r\n *\r\n * RemoteDocument' = RemoteDocument + Acknowledged(LocalMutations)\r\n *\r\n * Note that this \"dirty\" version of a RemoteDocument will not be identical to a\r\n * server base version, since it has LocalMutations added to it pending getting\r\n * an authoritative copy from the server.\r\n *\r\n * Since LocalMutations can be rejected by the server, we have to be able to\r\n * revert a LocalMutation that has already been applied to the LocalDocument\r\n * (typically done by replaying all remaining LocalMutations to the\r\n * RemoteDocument to re-apply).\r\n *\r\n * The LocalStore is responsible for the garbage collection of the documents it\r\n * contains. For now, it every doc referenced by a view, the mutation queue, or\r\n * the RemoteStore.\r\n *\r\n * It also maintains the persistence of mapping queries to resume tokens and\r\n * target ids. It needs to know this data about queries to properly know what\r\n * docs it would be allowed to garbage collect.\r\n *\r\n * The LocalStore must be able to efficiently execute queries against its local\r\n * cache of the documents, to provide the initial set of results before any\r\n * remote changes have been received.\r\n *\r\n * Note: In TypeScript, most methods return Promises since the implementation\r\n * may rely on fetching data from IndexedDB which is async.\r\n * These Promises will only be rejected on an I/O error or other internal\r\n * (unexpected) failure (e.g. failed assert) and always represent an\r\n * unrecoverable error (should be caught / reported by the async_queue).\r\n */\r\nvar LocalStore = /** @class */ (function () {\r\n function LocalStore(\r\n /** Manages our in-memory or durable persistence. */\r\n persistence, initialUser) {\r\n this.persistence = persistence;\r\n /**\r\n * The set of document references maintained by any local views.\r\n */\r\n this.localViewReferences = new ReferenceSet();\r\n /** Maps a targetID to data about its query. */\r\n this.queryDataByTarget = {};\r\n assert(persistence.started, 'LocalStore was passed an unstarted persistence implementation');\r\n this.persistence.referenceDelegate.setInMemoryPins(this.localViewReferences);\r\n this.mutationQueue = persistence.getMutationQueue(initialUser);\r\n this.remoteDocuments = persistence.getRemoteDocumentCache();\r\n this.queryCache = persistence.getQueryCache();\r\n this.localDocuments = new LocalDocumentsView(this.remoteDocuments, this.mutationQueue, this.persistence.getIndexManager());\r\n }\r\n /**\r\n * Tells the LocalStore that the currently authenticated user has changed.\r\n *\r\n * In response the local store switches the mutation queue to the new user and\r\n * returns any resulting document changes.\r\n */\r\n // PORTING NOTE: Android and iOS only return the documents affected by the\r\n // change.\r\n LocalStore.prototype.handleUserChange = function (user) {\r\n var _this = this;\r\n return this.persistence.runTransaction('Handle user change', 'readonly', function (txn) {\r\n // Swap out the mutation queue, grabbing the pending mutation batches\r\n // before and after.\r\n var oldBatches;\r\n return _this.mutationQueue\r\n .getAllMutationBatches(txn)\r\n .next(function (promisedOldBatches) {\r\n oldBatches = promisedOldBatches;\r\n _this.mutationQueue = _this.persistence.getMutationQueue(user);\r\n // Recreate our LocalDocumentsView using the new\r\n // MutationQueue.\r\n _this.localDocuments = new LocalDocumentsView(_this.remoteDocuments, _this.mutationQueue, _this.persistence.getIndexManager());\r\n return _this.mutationQueue.getAllMutationBatches(txn);\r\n })\r\n .next(function (newBatches) {\r\n var removedBatchIds = [];\r\n var addedBatchIds = [];\r\n // Union the old/new changed keys.\r\n var changedKeys = documentKeySet();\r\n for (var _i = 0, oldBatches_1 = oldBatches; _i < oldBatches_1.length; _i++) {\r\n var batch = oldBatches_1[_i];\r\n removedBatchIds.push(batch.batchId);\r\n for (var _a = 0, _b = batch.mutations; _a < _b.length; _a++) {\r\n var mutation = _b[_a];\r\n changedKeys = changedKeys.add(mutation.key);\r\n }\r\n }\r\n for (var _c = 0, newBatches_1 = newBatches; _c < newBatches_1.length; _c++) {\r\n var batch = newBatches_1[_c];\r\n addedBatchIds.push(batch.batchId);\r\n for (var _d = 0, _e = batch.mutations; _d < _e.length; _d++) {\r\n var mutation = _e[_d];\r\n changedKeys = changedKeys.add(mutation.key);\r\n }\r\n }\r\n // Return the set of all (potentially) changed documents and the list\r\n // of mutation batch IDs that were affected by change.\r\n return _this.localDocuments\r\n .getDocuments(txn, changedKeys)\r\n .next(function (affectedDocuments) {\r\n return {\r\n affectedDocuments: affectedDocuments,\r\n removedBatchIds: removedBatchIds,\r\n addedBatchIds: addedBatchIds\r\n };\r\n });\r\n });\r\n });\r\n };\r\n /* Accept locally generated Mutations and commit them to storage. */\r\n LocalStore.prototype.localWrite = function (mutations) {\r\n var _this = this;\r\n var localWriteTime = Timestamp.now();\r\n var keys = mutations.reduce(function (keys, m) { return keys.add(m.key); }, documentKeySet());\r\n return this.persistence.runTransaction('Locally write mutations', 'readwrite', function (txn) {\r\n // Load and apply all existing mutations. This lets us compute the\r\n // current base state for all non-idempotent transforms before applying\r\n // any additional user-provided writes.\r\n return _this.localDocuments\r\n .getDocuments(txn, keys)\r\n .next(function (existingDocs) {\r\n // For non-idempotent mutations (such as `FieldValue.increment()`),\r\n // we record the base state in a separate patch mutation. This is\r\n // later used to guarantee consistent values and prevents flicker\r\n // even if the backend sends us an update that already includes our\r\n // transform.\r\n var baseMutations = [];\r\n for (var _i = 0, mutations_1 = mutations; _i < mutations_1.length; _i++) {\r\n var mutation = mutations_1[_i];\r\n var maybeDoc = existingDocs.get(mutation.key);\r\n if (!mutation.isIdempotent) {\r\n // Theoretically, we should only include non-idempotent fields\r\n // in this field mask as this mask is used to populate the base\r\n // state for all DocumentTransforms. By including all fields,\r\n // we incorrectly prevent rebasing of idempotent transforms\r\n // (such as `arrayUnion()`) when any non-idempotent transforms\r\n // are present.\r\n var fieldMask = mutation.fieldMask;\r\n if (fieldMask) {\r\n var baseValues = maybeDoc instanceof Document\r\n ? fieldMask.applyTo(maybeDoc.data)\r\n : ObjectValue.EMPTY;\r\n // NOTE: The base state should only be applied if there's some\r\n // existing document to override, so use a Precondition of\r\n // exists=true\r\n baseMutations.push(new PatchMutation(mutation.key, baseValues, fieldMask, Precondition.exists(true)));\r\n }\r\n }\r\n }\r\n return _this.mutationQueue\r\n .addMutationBatch(txn, localWriteTime, baseMutations, mutations)\r\n .next(function (batch) {\r\n var changes = batch.applyToLocalDocumentSet(existingDocs);\r\n return { batchId: batch.batchId, changes: changes };\r\n });\r\n });\r\n });\r\n };\r\n /** Returns the local view of the documents affected by a mutation batch. */\r\n // PORTING NOTE: Multi-tab only.\r\n LocalStore.prototype.lookupMutationDocuments = function (batchId) {\r\n var _this = this;\r\n return this.persistence.runTransaction('Lookup mutation documents', 'readonly', function (txn) {\r\n return _this.mutationQueue\r\n .lookupMutationKeys(txn, batchId)\r\n .next(function (keys) {\r\n if (keys) {\r\n return _this.localDocuments.getDocuments(txn, keys);\r\n }\r\n else {\r\n return PersistencePromise.resolve(null);\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * Acknowledge the given batch.\r\n *\r\n * On the happy path when a batch is acknowledged, the local store will\r\n *\r\n * + remove the batch from the mutation queue;\r\n * + apply the changes to the remote document cache;\r\n * + recalculate the latency compensated view implied by those changes (there\r\n * may be mutations in the queue that affect the documents but haven't been\r\n * acknowledged yet); and\r\n * + give the changed documents back the sync engine\r\n *\r\n * @returns The resulting (modified) documents.\r\n */\r\n LocalStore.prototype.acknowledgeBatch = function (batchResult) {\r\n var _this = this;\r\n return this.persistence.runTransaction('Acknowledge batch', 'readwrite-primary', function (txn) {\r\n var affected = batchResult.batch.keys();\r\n var documentBuffer = _this.remoteDocuments.newChangeBuffer();\r\n return _this.mutationQueue\r\n .acknowledgeBatch(txn, batchResult.batch, batchResult.streamToken)\r\n .next(function () {\r\n return _this.applyWriteToRemoteDocuments(txn, batchResult, documentBuffer);\r\n })\r\n .next(function () { return documentBuffer.apply(txn); })\r\n .next(function () { return _this.mutationQueue.performConsistencyCheck(txn); })\r\n .next(function () { return _this.localDocuments.getDocuments(txn, affected); });\r\n });\r\n };\r\n /**\r\n * Remove mutations from the MutationQueue for the specified batch;\r\n * LocalDocuments will be recalculated.\r\n *\r\n * @returns The resulting modified documents.\r\n */\r\n LocalStore.prototype.rejectBatch = function (batchId) {\r\n var _this = this;\r\n return this.persistence.runTransaction('Reject batch', 'readwrite-primary', function (txn) {\r\n var affectedKeys;\r\n return _this.mutationQueue\r\n .lookupMutationBatch(txn, batchId)\r\n .next(function (batch) {\r\n assert(batch !== null, 'Attempt to reject nonexistent batch!');\r\n affectedKeys = batch.keys();\r\n return _this.mutationQueue.removeMutationBatch(txn, batch);\r\n })\r\n .next(function () {\r\n return _this.mutationQueue.performConsistencyCheck(txn);\r\n })\r\n .next(function () {\r\n return _this.localDocuments.getDocuments(txn, affectedKeys);\r\n });\r\n });\r\n };\r\n /** Returns the last recorded stream token for the current user. */\r\n LocalStore.prototype.getLastStreamToken = function () {\r\n var _this = this;\r\n return this.persistence.runTransaction('Get last stream token', 'readonly', function (txn) {\r\n return _this.mutationQueue.getLastStreamToken(txn);\r\n });\r\n };\r\n /**\r\n * Sets the stream token for the current user without acknowledging any\r\n * mutation batch. This is usually only useful after a stream handshake or in\r\n * response to an error that requires clearing the stream token.\r\n */\r\n LocalStore.prototype.setLastStreamToken = function (streamToken) {\r\n var _this = this;\r\n return this.persistence.runTransaction('Set last stream token', 'readwrite-primary', function (txn) {\r\n return _this.mutationQueue.setLastStreamToken(txn, streamToken);\r\n });\r\n };\r\n /**\r\n * Returns the last consistent snapshot processed (used by the RemoteStore to\r\n * determine whether to buffer incoming snapshots from the backend).\r\n */\r\n LocalStore.prototype.getLastRemoteSnapshotVersion = function () {\r\n var _this = this;\r\n return this.persistence.runTransaction('Get last remote snapshot version', 'readonly', function (txn) { return _this.queryCache.getLastRemoteSnapshotVersion(txn); });\r\n };\r\n /**\r\n * Update the \"ground-state\" (remote) documents. We assume that the remote\r\n * event reflects any write batches that have been acknowledged or rejected\r\n * (i.e. we do not re-apply local mutations to updates from this event).\r\n *\r\n * LocalDocuments are re-calculated if there are remaining mutations in the\r\n * queue.\r\n */\r\n LocalStore.prototype.applyRemoteEvent = function (remoteEvent) {\r\n var _this = this;\r\n var documentBuffer = this.remoteDocuments.newChangeBuffer();\r\n return this.persistence.runTransaction('Apply remote event', 'readwrite-primary', function (txn) {\r\n var promises = [];\r\n var authoritativeUpdates = documentKeySet();\r\n forEachNumber(remoteEvent.targetChanges, function (targetId, change) {\r\n // Do not ref/unref unassigned targetIds - it may lead to leaks.\r\n var queryData = _this.queryDataByTarget[targetId];\r\n if (!queryData)\r\n return;\r\n // When a global snapshot contains updates (either add or modify) we\r\n // can completely trust these updates as authoritative and blindly\r\n // apply them to our cache (as a defensive measure to promote\r\n // self-healing in the unfortunate case that our cache is ever somehow\r\n // corrupted / out-of-sync).\r\n //\r\n // If the document is only updated while removing it from a target\r\n // then watch isn't obligated to send the absolute latest version: it\r\n // can send the first version that caused the document not to match.\r\n change.addedDocuments.forEach(function (key) {\r\n authoritativeUpdates = authoritativeUpdates.add(key);\r\n });\r\n change.modifiedDocuments.forEach(function (key) {\r\n authoritativeUpdates = authoritativeUpdates.add(key);\r\n });\r\n promises.push(_this.queryCache\r\n .removeMatchingKeys(txn, change.removedDocuments, targetId)\r\n .next(function () {\r\n return _this.queryCache.addMatchingKeys(txn, change.addedDocuments, targetId);\r\n }));\r\n // Update the resume token if the change includes one. Don't clear\r\n // any preexisting value.\r\n var resumeToken = change.resumeToken;\r\n if (resumeToken.length > 0) {\r\n var oldQueryData = queryData;\r\n queryData = queryData.copy({\r\n resumeToken: resumeToken,\r\n snapshotVersion: remoteEvent.snapshotVersion\r\n });\r\n _this.queryDataByTarget[targetId] = queryData;\r\n if (LocalStore.shouldPersistQueryData(oldQueryData, queryData, change)) {\r\n promises.push(_this.queryCache.updateQueryData(txn, queryData));\r\n }\r\n }\r\n });\r\n var changedDocs = maybeDocumentMap();\r\n var updatedKeys = documentKeySet();\r\n remoteEvent.documentUpdates.forEach(function (key, doc) {\r\n updatedKeys = updatedKeys.add(key);\r\n });\r\n // Each loop iteration only affects its \"own\" doc, so it's safe to get all the remote\r\n // documents in advance in a single call.\r\n promises.push(documentBuffer.getEntries(txn, updatedKeys).next(function (existingDocs) {\r\n remoteEvent.documentUpdates.forEach(function (key, doc) {\r\n var existingDoc = existingDocs.get(key);\r\n // If a document update isn't authoritative, make sure we don't\r\n // apply an old document version to the remote cache. We make an\r\n // exception for SnapshotVersion.MIN which can happen for\r\n // manufactured events (e.g. in the case of a limbo document\r\n // resolution failing).\r\n if (existingDoc == null ||\r\n doc.version.isEqual(SnapshotVersion.MIN) ||\r\n (authoritativeUpdates.has(doc.key) &&\r\n !existingDoc.hasPendingWrites) ||\r\n doc.version.compareTo(existingDoc.version) >= 0) {\r\n documentBuffer.addEntry(doc);\r\n changedDocs = changedDocs.insert(key, doc);\r\n }\r\n else {\r\n debug(LOG_TAG$3, 'Ignoring outdated watch update for ', key, '. Current version:', existingDoc.version, ' Watch version:', doc.version);\r\n }\r\n if (remoteEvent.resolvedLimboDocuments.has(key)) {\r\n promises.push(_this.persistence.referenceDelegate.updateLimboDocument(txn, key));\r\n }\r\n });\r\n }));\r\n // HACK: The only reason we allow a null snapshot version is so that we\r\n // can synthesize remote events when we get permission denied errors while\r\n // trying to resolve the state of a locally cached document that is in\r\n // limbo.\r\n var remoteVersion = remoteEvent.snapshotVersion;\r\n if (!remoteVersion.isEqual(SnapshotVersion.MIN)) {\r\n var updateRemoteVersion = _this.queryCache\r\n .getLastRemoteSnapshotVersion(txn)\r\n .next(function (lastRemoteVersion) {\r\n assert(remoteVersion.compareTo(lastRemoteVersion) >= 0, 'Watch stream reverted to previous snapshot?? ' +\r\n remoteVersion +\r\n ' < ' +\r\n lastRemoteVersion);\r\n return _this.queryCache.setTargetsMetadata(txn, txn.currentSequenceNumber, remoteVersion);\r\n });\r\n promises.push(updateRemoteVersion);\r\n }\r\n return PersistencePromise.waitFor(promises)\r\n .next(function () { return documentBuffer.apply(txn); })\r\n .next(function () {\r\n return _this.localDocuments.getLocalViewOfDocuments(txn, changedDocs);\r\n });\r\n });\r\n };\r\n /**\r\n * Returns true if the newQueryData should be persisted during an update of\r\n * an active target. QueryData should always be persisted when a target is\r\n * being released and should not call this function.\r\n *\r\n * While the target is active, QueryData updates can be omitted when nothing\r\n * about the target has changed except metadata like the resume token or\r\n * snapshot version. Occasionally it's worth the extra write to prevent these\r\n * values from getting too stale after a crash, but this doesn't have to be\r\n * too frequent.\r\n */\r\n LocalStore.shouldPersistQueryData = function (oldQueryData, newQueryData, change) {\r\n // Avoid clearing any existing value\r\n if (newQueryData.resumeToken.length === 0)\r\n return false;\r\n // Any resume token is interesting if there isn't one already.\r\n if (oldQueryData.resumeToken.length === 0)\r\n return true;\r\n // Don't allow resume token changes to be buffered indefinitely. This\r\n // allows us to be reasonably up-to-date after a crash and avoids needing\r\n // to loop over all active queries on shutdown. Especially in the browser\r\n // we may not get time to do anything interesting while the current tab is\r\n // closing.\r\n var timeDelta = newQueryData.snapshotVersion.toMicroseconds() -\r\n oldQueryData.snapshotVersion.toMicroseconds();\r\n if (timeDelta >= this.RESUME_TOKEN_MAX_AGE_MICROS)\r\n return true;\r\n // Otherwise if the only thing that has changed about a target is its resume\r\n // token it's not worth persisting. Note that the RemoteStore keeps an\r\n // in-memory view of the currently active targets which includes the current\r\n // resume token, so stream failure or user changes will still use an\r\n // up-to-date resume token regardless of what we do here.\r\n var changes = change.addedDocuments.size +\r\n change.modifiedDocuments.size +\r\n change.removedDocuments.size;\r\n return changes > 0;\r\n };\r\n /**\r\n * Notify local store of the changed views to locally pin documents.\r\n */\r\n LocalStore.prototype.notifyLocalViewChanges = function (viewChanges) {\r\n var _this = this;\r\n return this.persistence.runTransaction('notifyLocalViewChanges', 'readwrite', function (txn) {\r\n return PersistencePromise.forEach(viewChanges, function (viewChange) {\r\n _this.localViewReferences.addReferences(viewChange.addedKeys, viewChange.targetId);\r\n _this.localViewReferences.removeReferences(viewChange.removedKeys, viewChange.targetId);\r\n return PersistencePromise.forEach(viewChange.removedKeys, function (key) {\r\n return _this.persistence.referenceDelegate.removeReference(txn, key);\r\n });\r\n });\r\n });\r\n };\r\n /**\r\n * Gets the mutation batch after the passed in batchId in the mutation queue\r\n * or null if empty.\r\n * @param afterBatchId If provided, the batch to search after.\r\n * @returns The next mutation or null if there wasn't one.\r\n */\r\n LocalStore.prototype.nextMutationBatch = function (afterBatchId) {\r\n var _this = this;\r\n return this.persistence.runTransaction('Get next mutation batch', 'readonly', function (txn) {\r\n if (afterBatchId === undefined) {\r\n afterBatchId = BATCHID_UNKNOWN;\r\n }\r\n return _this.mutationQueue.getNextMutationBatchAfterBatchId(txn, afterBatchId);\r\n });\r\n };\r\n /**\r\n * Read the current value of a Document with a given key or null if not\r\n * found - used for testing.\r\n */\r\n LocalStore.prototype.readDocument = function (key) {\r\n var _this = this;\r\n return this.persistence.runTransaction('read document', 'readonly', function (txn) {\r\n return _this.localDocuments.getDocument(txn, key);\r\n });\r\n };\r\n /**\r\n * Assigns the given query an internal ID so that its results can be pinned so\r\n * they don't get GC'd. A query must be allocated in the local store before\r\n * the store can be used to manage its view.\r\n */\r\n LocalStore.prototype.allocateQuery = function (query) {\r\n var _this = this;\r\n return this.persistence.runTransaction('Allocate query', 'readwrite', function (txn) {\r\n var queryData;\r\n return _this.queryCache\r\n .getQueryData(txn, query)\r\n .next(function (cached) {\r\n if (cached) {\r\n // This query has been listened to previously, so reuse the\r\n // previous targetID.\r\n // TODO(mcg): freshen last accessed date?\r\n queryData = cached;\r\n return PersistencePromise.resolve();\r\n }\r\n else {\r\n return _this.queryCache.allocateTargetId(txn).next(function (targetId) {\r\n queryData = new QueryData(query, targetId, QueryPurpose.Listen, txn.currentSequenceNumber);\r\n return _this.queryCache.addQueryData(txn, queryData);\r\n });\r\n }\r\n })\r\n .next(function () {\r\n assert(!_this.queryDataByTarget[queryData.targetId], 'Tried to allocate an already allocated query: ' + query);\r\n _this.queryDataByTarget[queryData.targetId] = queryData;\r\n return queryData;\r\n });\r\n });\r\n };\r\n /**\r\n * Unpin all the documents associated with the given query. If\r\n * `keepPersistedQueryData` is set to false and Eager GC enabled, the method\r\n * directly removes the associated query data from the query cache.\r\n */\r\n // PORTING NOTE: `keepPersistedQueryData` is multi-tab only.\r\n LocalStore.prototype.releaseQuery = function (query, keepPersistedQueryData) {\r\n var _this = this;\r\n var mode = keepPersistedQueryData ? 'readwrite' : 'readwrite-primary';\r\n return this.persistence.runTransaction('Release query', mode, function (txn) {\r\n return _this.queryCache\r\n .getQueryData(txn, query)\r\n .next(function (queryData) {\r\n assert(queryData != null, 'Tried to release nonexistent query: ' + query);\r\n var targetId = queryData.targetId;\r\n var cachedQueryData = _this.queryDataByTarget[targetId];\r\n // References for documents sent via Watch are automatically removed when we delete a\r\n // query's target data from the reference delegate. Since this does not remove references\r\n // for locally mutated documents, we have to remove the target associations for these\r\n // documents manually.\r\n var removed = _this.localViewReferences.removeReferencesForId(targetId);\r\n delete _this.queryDataByTarget[targetId];\r\n if (!keepPersistedQueryData) {\r\n return PersistencePromise.forEach(removed, function (key) {\r\n return _this.persistence.referenceDelegate.removeReference(txn, key);\r\n }).next(function () {\r\n return _this.persistence.referenceDelegate.removeTarget(txn, cachedQueryData);\r\n });\r\n }\r\n else {\r\n return PersistencePromise.resolve();\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * Runs the specified query against all the documents in the local store and\r\n * returns the results.\r\n */\r\n LocalStore.prototype.executeQuery = function (query) {\r\n var _this = this;\r\n return this.persistence.runTransaction('Execute query', 'readonly', function (txn) {\r\n return _this.localDocuments.getDocumentsMatchingQuery(txn, query);\r\n });\r\n };\r\n /**\r\n * Returns the keys of the documents that are associated with the given\r\n * target id in the remote table.\r\n */\r\n LocalStore.prototype.remoteDocumentKeys = function (targetId) {\r\n var _this = this;\r\n return this.persistence.runTransaction('Remote document keys', 'readonly', function (txn) {\r\n return _this.queryCache.getMatchingKeysForTargetId(txn, targetId);\r\n });\r\n };\r\n // PORTING NOTE: Multi-tab only.\r\n LocalStore.prototype.getActiveClients = function () {\r\n return this.persistence.getActiveClients();\r\n };\r\n // PORTING NOTE: Multi-tab only.\r\n LocalStore.prototype.removeCachedMutationBatchMetadata = function (batchId) {\r\n this.mutationQueue.removeCachedMutationKeys(batchId);\r\n };\r\n // PORTING NOTE: Multi-tab only.\r\n LocalStore.prototype.setNetworkEnabled = function (networkEnabled) {\r\n this.persistence.setNetworkEnabled(networkEnabled);\r\n };\r\n LocalStore.prototype.applyWriteToRemoteDocuments = function (txn, batchResult, documentBuffer) {\r\n var _this = this;\r\n var batch = batchResult.batch;\r\n var docKeys = batch.keys();\r\n var promiseChain = PersistencePromise.resolve();\r\n docKeys.forEach(function (docKey) {\r\n promiseChain = promiseChain\r\n .next(function () {\r\n return documentBuffer.getEntry(txn, docKey);\r\n })\r\n .next(function (remoteDoc) {\r\n var doc = remoteDoc;\r\n var ackVersion = batchResult.docVersions.get(docKey);\r\n assert(ackVersion !== null, 'ackVersions should contain every doc in the write.');\r\n if (!doc || doc.version.compareTo(ackVersion) < 0) {\r\n doc = batch.applyToRemoteDocument(docKey, doc, batchResult);\r\n if (!doc) {\r\n assert(!remoteDoc, 'Mutation batch ' +\r\n batch +\r\n ' applied to document ' +\r\n remoteDoc +\r\n ' resulted in null');\r\n }\r\n else {\r\n documentBuffer.addEntry(doc);\r\n }\r\n }\r\n });\r\n });\r\n return promiseChain.next(function () {\r\n return _this.mutationQueue.removeMutationBatch(txn, batch);\r\n });\r\n };\r\n LocalStore.prototype.collectGarbage = function (garbageCollector) {\r\n var _this = this;\r\n return this.persistence.runTransaction('Collect garbage', 'readwrite-primary', function (txn) { return garbageCollector.collect(txn, _this.queryDataByTarget); });\r\n };\r\n // PORTING NOTE: Multi-tab only.\r\n LocalStore.prototype.getQueryForTarget = function (targetId) {\r\n var _this = this;\r\n if (this.queryDataByTarget[targetId]) {\r\n return Promise.resolve(this.queryDataByTarget[targetId].query);\r\n }\r\n else {\r\n return this.persistence.runTransaction('Get query data', 'readonly', function (txn) {\r\n return _this.queryCache\r\n .getQueryDataForTarget(txn, targetId)\r\n .next(function (queryData) { return (queryData ? queryData.query : null); });\r\n });\r\n }\r\n };\r\n // PORTING NOTE: Multi-tab only.\r\n LocalStore.prototype.getNewDocumentChanges = function () {\r\n var _this = this;\r\n return this.persistence.runTransaction('Get new document changes', 'readonly', function (txn) {\r\n return _this.remoteDocuments.getNewDocumentChanges(txn);\r\n });\r\n };\r\n /**\r\n * The maximum time to leave a resume token buffered without writing it out.\r\n * This value is arbitrary: it's long enough to avoid several writes\r\n * (possibly indefinitely if updates come more frequently than this) but\r\n * short enough that restarting after crashing will still have a pretty\r\n * recent resume token.\r\n */\r\n LocalStore.RESUME_TOKEN_MAX_AGE_MICROS = 5 * 60 * 1e6;\r\n return LocalStore;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar MemoryMutationQueue = /** @class */ (function () {\r\n function MemoryMutationQueue(indexManager, referenceDelegate) {\r\n this.indexManager = indexManager;\r\n this.referenceDelegate = referenceDelegate;\r\n /**\r\n * The set of all mutations that have been sent but not yet been applied to\r\n * the backend.\r\n */\r\n this.mutationQueue = [];\r\n /** Next value to use when assigning sequential IDs to each mutation batch. */\r\n this.nextBatchId = 1;\r\n /** The last received stream token from the server, used to acknowledge which\r\n * responses the client has processed. Stream tokens are opaque checkpoint\r\n * markers whose only real value is their inclusion in the next request.\r\n */\r\n this.lastStreamToken = emptyByteString();\r\n /** An ordered mapping between documents and the mutations batch IDs. */\r\n this.batchesByDocumentKey = new SortedSet(DocReference.compareByKey);\r\n }\r\n MemoryMutationQueue.prototype.checkEmpty = function (transaction) {\r\n return PersistencePromise.resolve(this.mutationQueue.length === 0);\r\n };\r\n MemoryMutationQueue.prototype.acknowledgeBatch = function (transaction, batch, streamToken) {\r\n var batchId = batch.batchId;\r\n var batchIndex = this.indexOfExistingBatchId(batchId, 'acknowledged');\r\n assert(batchIndex === 0, 'Can only acknowledge the first batch in the mutation queue');\r\n // Verify that the batch in the queue is the one to be acknowledged.\r\n var check = this.mutationQueue[batchIndex];\r\n assert(batchId === check.batchId, 'Queue ordering failure: expected batch ' +\r\n batchId +\r\n ', got batch ' +\r\n check.batchId);\r\n this.lastStreamToken = streamToken;\r\n return PersistencePromise.resolve();\r\n };\r\n MemoryMutationQueue.prototype.getLastStreamToken = function (transaction) {\r\n return PersistencePromise.resolve(this.lastStreamToken);\r\n };\r\n MemoryMutationQueue.prototype.setLastStreamToken = function (transaction, streamToken) {\r\n this.lastStreamToken = streamToken;\r\n return PersistencePromise.resolve();\r\n };\r\n MemoryMutationQueue.prototype.addMutationBatch = function (transaction, localWriteTime, baseMutations, mutations) {\r\n assert(mutations.length !== 0, 'Mutation batches should not be empty');\r\n var batchId = this.nextBatchId;\r\n this.nextBatchId++;\r\n if (this.mutationQueue.length > 0) {\r\n var prior = this.mutationQueue[this.mutationQueue.length - 1];\r\n assert(prior.batchId < batchId, 'Mutation batchIDs must be monotonically increasing order');\r\n }\r\n var batch = new MutationBatch(batchId, localWriteTime, baseMutations, mutations);\r\n this.mutationQueue.push(batch);\r\n // Track references by document key and index collection parents.\r\n for (var _i = 0, mutations_1 = mutations; _i < mutations_1.length; _i++) {\r\n var mutation = mutations_1[_i];\r\n this.batchesByDocumentKey = this.batchesByDocumentKey.add(new DocReference(mutation.key, batchId));\r\n this.indexManager.addToCollectionParentIndex(transaction, mutation.key.path.popLast());\r\n }\r\n return PersistencePromise.resolve(batch);\r\n };\r\n MemoryMutationQueue.prototype.lookupMutationBatch = function (transaction, batchId) {\r\n return PersistencePromise.resolve(this.findMutationBatch(batchId));\r\n };\r\n MemoryMutationQueue.prototype.lookupMutationKeys = function (transaction, batchId) {\r\n var mutationBatch = this.findMutationBatch(batchId);\r\n assert(mutationBatch != null, 'Failed to find local mutation batch.');\r\n return PersistencePromise.resolve(mutationBatch.keys());\r\n };\r\n MemoryMutationQueue.prototype.getNextMutationBatchAfterBatchId = function (transaction, batchId) {\r\n var nextBatchId = batchId + 1;\r\n // The requested batchId may still be out of range so normalize it to the\r\n // start of the queue.\r\n var rawIndex = this.indexOfBatchId(nextBatchId);\r\n var index = rawIndex < 0 ? 0 : rawIndex;\r\n return PersistencePromise.resolve(this.mutationQueue.length > index ? this.mutationQueue[index] : null);\r\n };\r\n MemoryMutationQueue.prototype.getAllMutationBatches = function (transaction) {\r\n return PersistencePromise.resolve(this.mutationQueue.slice());\r\n };\r\n MemoryMutationQueue.prototype.getAllMutationBatchesAffectingDocumentKey = function (transaction, documentKey) {\r\n var _this = this;\r\n var start = new DocReference(documentKey, 0);\r\n var end = new DocReference(documentKey, Number.POSITIVE_INFINITY);\r\n var result = [];\r\n this.batchesByDocumentKey.forEachInRange([start, end], function (ref) {\r\n assert(documentKey.isEqual(ref.key), \"Should only iterate over a single key's batches\");\r\n var batch = _this.findMutationBatch(ref.targetOrBatchId);\r\n assert(batch !== null, 'Batches in the index must exist in the main table');\r\n result.push(batch);\r\n });\r\n return PersistencePromise.resolve(result);\r\n };\r\n MemoryMutationQueue.prototype.getAllMutationBatchesAffectingDocumentKeys = function (transaction, documentKeys) {\r\n var _this = this;\r\n var uniqueBatchIDs = new SortedSet(primitiveComparator);\r\n documentKeys.forEach(function (documentKey) {\r\n var start = new DocReference(documentKey, 0);\r\n var end = new DocReference(documentKey, Number.POSITIVE_INFINITY);\r\n _this.batchesByDocumentKey.forEachInRange([start, end], function (ref) {\r\n assert(documentKey.isEqual(ref.key), \"For each key, should only iterate over a single key's batches\");\r\n uniqueBatchIDs = uniqueBatchIDs.add(ref.targetOrBatchId);\r\n });\r\n });\r\n return PersistencePromise.resolve(this.findMutationBatches(uniqueBatchIDs));\r\n };\r\n MemoryMutationQueue.prototype.getAllMutationBatchesAffectingQuery = function (transaction, query) {\r\n assert(!query.isCollectionGroupQuery(), 'CollectionGroup queries should be handled in LocalDocumentsView');\r\n // Use the query path as a prefix for testing if a document matches the\r\n // query.\r\n var prefix = query.path;\r\n var immediateChildrenPathLength = prefix.length + 1;\r\n // Construct a document reference for actually scanning the index. Unlike\r\n // the prefix the document key in this reference must have an even number of\r\n // segments. The empty segment can be used a suffix of the query path\r\n // because it precedes all other segments in an ordered traversal.\r\n var startPath = prefix;\r\n if (!DocumentKey.isDocumentKey(startPath)) {\r\n startPath = startPath.child('');\r\n }\r\n var start = new DocReference(new DocumentKey(startPath), 0);\r\n // Find unique batchIDs referenced by all documents potentially matching the\r\n // query.\r\n var uniqueBatchIDs = new SortedSet(primitiveComparator);\r\n this.batchesByDocumentKey.forEachWhile(function (ref) {\r\n var rowKeyPath = ref.key.path;\r\n if (!prefix.isPrefixOf(rowKeyPath)) {\r\n return false;\r\n }\r\n else {\r\n // Rows with document keys more than one segment longer than the query\r\n // path can't be matches. For example, a query on 'rooms' can't match\r\n // the document /rooms/abc/messages/xyx.\r\n // TODO(mcg): we'll need a different scanner when we implement\r\n // ancestor queries.\r\n if (rowKeyPath.length === immediateChildrenPathLength) {\r\n uniqueBatchIDs = uniqueBatchIDs.add(ref.targetOrBatchId);\r\n }\r\n return true;\r\n }\r\n }, start);\r\n return PersistencePromise.resolve(this.findMutationBatches(uniqueBatchIDs));\r\n };\r\n MemoryMutationQueue.prototype.findMutationBatches = function (batchIDs) {\r\n var _this = this;\r\n // Construct an array of matching batches, sorted by batchID to ensure that\r\n // multiple mutations affecting the same document key are applied in order.\r\n var result = [];\r\n batchIDs.forEach(function (batchId) {\r\n var batch = _this.findMutationBatch(batchId);\r\n if (batch !== null) {\r\n result.push(batch);\r\n }\r\n });\r\n return result;\r\n };\r\n MemoryMutationQueue.prototype.removeMutationBatch = function (transaction, batch) {\r\n var _this = this;\r\n // Find the position of the first batch for removal. This need not be the\r\n // first entry in the queue.\r\n var batchIndex = this.indexOfExistingBatchId(batch.batchId, 'removed');\r\n assert(batchIndex === 0, 'Can only remove the first entry of the mutation queue');\r\n this.mutationQueue.shift();\r\n var references = this.batchesByDocumentKey;\r\n return PersistencePromise.forEach(batch.mutations, function (mutation) {\r\n var ref = new DocReference(mutation.key, batch.batchId);\r\n references = references.delete(ref);\r\n return _this.referenceDelegate.removeMutationReference(transaction, mutation.key);\r\n }).next(function () {\r\n _this.batchesByDocumentKey = references;\r\n });\r\n };\r\n MemoryMutationQueue.prototype.removeCachedMutationKeys = function (batchId) {\r\n // No-op since the memory mutation queue does not maintain a separate cache.\r\n };\r\n MemoryMutationQueue.prototype.containsKey = function (txn, key) {\r\n var ref = new DocReference(key, 0);\r\n var firstRef = this.batchesByDocumentKey.firstAfterOrEqual(ref);\r\n return PersistencePromise.resolve(key.isEqual(firstRef && firstRef.key));\r\n };\r\n MemoryMutationQueue.prototype.performConsistencyCheck = function (txn) {\r\n if (this.mutationQueue.length === 0) {\r\n assert(this.batchesByDocumentKey.isEmpty(), 'Document leak -- detected dangling mutation references when queue is empty.');\r\n }\r\n return PersistencePromise.resolve();\r\n };\r\n /**\r\n * Finds the index of the given batchId in the mutation queue and asserts that\r\n * the resulting index is within the bounds of the queue.\r\n *\r\n * @param batchId The batchId to search for\r\n * @param action A description of what the caller is doing, phrased in passive\r\n * form (e.g. \"acknowledged\" in a routine that acknowledges batches).\r\n */\r\n MemoryMutationQueue.prototype.indexOfExistingBatchId = function (batchId, action) {\r\n var index = this.indexOfBatchId(batchId);\r\n assert(index >= 0 && index < this.mutationQueue.length, 'Batches must exist to be ' + action);\r\n return index;\r\n };\r\n /**\r\n * Finds the index of the given batchId in the mutation queue. This operation\r\n * is O(1).\r\n *\r\n * @return The computed index of the batch with the given batchId, based on\r\n * the state of the queue. Note this index can be negative if the requested\r\n * batchId has already been remvoed from the queue or past the end of the\r\n * queue if the batchId is larger than the last added batch.\r\n */\r\n MemoryMutationQueue.prototype.indexOfBatchId = function (batchId) {\r\n if (this.mutationQueue.length === 0) {\r\n // As an index this is past the end of the queue\r\n return 0;\r\n }\r\n // Examine the front of the queue to figure out the difference between the\r\n // batchId and indexes in the array. Note that since the queue is ordered\r\n // by batchId, if the first batch has a larger batchId then the requested\r\n // batchId doesn't exist in the queue.\r\n var firstBatchId = this.mutationQueue[0].batchId;\r\n return batchId - firstBatchId;\r\n };\r\n /**\r\n * A version of lookupMutationBatch that doesn't return a promise, this makes\r\n * other functions that uses this code easier to read and more efficent.\r\n */\r\n MemoryMutationQueue.prototype.findMutationBatch = function (batchId) {\r\n var index = this.indexOfBatchId(batchId);\r\n if (index < 0 || index >= this.mutationQueue.length) {\r\n return null;\r\n }\r\n var batch = this.mutationQueue[index];\r\n assert(batch.batchId === batchId, 'If found batch must match');\r\n return batch;\r\n };\r\n return MemoryMutationQueue;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar MemoryQueryCache = /** @class */ (function () {\r\n function MemoryQueryCache(persistence) {\r\n this.persistence = persistence;\r\n /**\r\n * Maps a query to the data about that query\r\n */\r\n this.queries = new ObjectMap(function (q) { return q.canonicalId(); });\r\n /** The last received snapshot version. */\r\n this.lastRemoteSnapshotVersion = SnapshotVersion.MIN;\r\n /** The highest numbered target ID encountered. */\r\n this.highestTargetId = 0;\r\n /** The highest sequence number encountered. */\r\n this.highestSequenceNumber = 0;\r\n /**\r\n * A ordered bidirectional mapping between documents and the remote target\r\n * IDs.\r\n */\r\n this.references = new ReferenceSet();\r\n this.targetCount = 0;\r\n this.targetIdGenerator = TargetIdGenerator.forQueryCache();\r\n }\r\n MemoryQueryCache.prototype.getTargetCount = function (txn) {\r\n return PersistencePromise.resolve(this.targetCount);\r\n };\r\n MemoryQueryCache.prototype.forEachTarget = function (txn, f) {\r\n this.queries.forEach(function (_, queryData) { return f(queryData); });\r\n return PersistencePromise.resolve();\r\n };\r\n MemoryQueryCache.prototype.getLastRemoteSnapshotVersion = function (transaction) {\r\n return PersistencePromise.resolve(this.lastRemoteSnapshotVersion);\r\n };\r\n MemoryQueryCache.prototype.getHighestSequenceNumber = function (transaction) {\r\n return PersistencePromise.resolve(this.highestSequenceNumber);\r\n };\r\n MemoryQueryCache.prototype.allocateTargetId = function (transaction) {\r\n var nextTargetId = this.targetIdGenerator.after(this.highestTargetId);\r\n this.highestTargetId = nextTargetId;\r\n return PersistencePromise.resolve(nextTargetId);\r\n };\r\n MemoryQueryCache.prototype.setTargetsMetadata = function (transaction, highestListenSequenceNumber, lastRemoteSnapshotVersion) {\r\n if (lastRemoteSnapshotVersion) {\r\n this.lastRemoteSnapshotVersion = lastRemoteSnapshotVersion;\r\n }\r\n if (highestListenSequenceNumber > this.highestSequenceNumber) {\r\n this.highestSequenceNumber = highestListenSequenceNumber;\r\n }\r\n return PersistencePromise.resolve();\r\n };\r\n MemoryQueryCache.prototype.saveQueryData = function (queryData) {\r\n this.queries.set(queryData.query, queryData);\r\n var targetId = queryData.targetId;\r\n if (targetId > this.highestTargetId) {\r\n this.highestTargetId = targetId;\r\n }\r\n if (queryData.sequenceNumber > this.highestSequenceNumber) {\r\n this.highestSequenceNumber = queryData.sequenceNumber;\r\n }\r\n };\r\n MemoryQueryCache.prototype.addQueryData = function (transaction, queryData) {\r\n assert(!this.queries.has(queryData.query), 'Adding a query that already exists');\r\n this.saveQueryData(queryData);\r\n this.targetCount += 1;\r\n return PersistencePromise.resolve();\r\n };\r\n MemoryQueryCache.prototype.updateQueryData = function (transaction, queryData) {\r\n assert(this.queries.has(queryData.query), 'Updating a non-existent query');\r\n this.saveQueryData(queryData);\r\n return PersistencePromise.resolve();\r\n };\r\n MemoryQueryCache.prototype.removeQueryData = function (transaction, queryData) {\r\n assert(this.targetCount > 0, 'Removing a target from an empty cache');\r\n assert(this.queries.has(queryData.query), 'Removing a non-existent target from the cache');\r\n this.queries.delete(queryData.query);\r\n this.references.removeReferencesForId(queryData.targetId);\r\n this.targetCount -= 1;\r\n return PersistencePromise.resolve();\r\n };\r\n MemoryQueryCache.prototype.removeTargets = function (transaction, upperBound, activeTargetIds) {\r\n var _this = this;\r\n var count = 0;\r\n var removals = [];\r\n this.queries.forEach(function (key, queryData) {\r\n if (queryData.sequenceNumber <= upperBound &&\r\n !activeTargetIds[queryData.targetId]) {\r\n _this.queries.delete(key);\r\n removals.push(_this.removeMatchingKeysForTargetId(transaction, queryData.targetId));\r\n count++;\r\n }\r\n });\r\n return PersistencePromise.waitFor(removals).next(function () { return count; });\r\n };\r\n MemoryQueryCache.prototype.getQueryCount = function (transaction) {\r\n return PersistencePromise.resolve(this.targetCount);\r\n };\r\n MemoryQueryCache.prototype.getQueryData = function (transaction, query) {\r\n var queryData = this.queries.get(query) || null;\r\n return PersistencePromise.resolve(queryData);\r\n };\r\n MemoryQueryCache.prototype.getQueryDataForTarget = function (transaction, targetId) {\r\n // This method is only needed for multi-tab and we can't implement it\r\n // efficiently without additional data structures.\r\n return fail('Not yet implemented.');\r\n };\r\n MemoryQueryCache.prototype.addMatchingKeys = function (txn, keys, targetId) {\r\n this.references.addReferences(keys, targetId);\r\n var referenceDelegate = this.persistence.referenceDelegate;\r\n var promises = [];\r\n if (referenceDelegate) {\r\n keys.forEach(function (key) {\r\n promises.push(referenceDelegate.addReference(txn, key));\r\n });\r\n }\r\n return PersistencePromise.waitFor(promises);\r\n };\r\n MemoryQueryCache.prototype.removeMatchingKeys = function (txn, keys, targetId) {\r\n this.references.removeReferences(keys, targetId);\r\n var referenceDelegate = this.persistence.referenceDelegate;\r\n var promises = [];\r\n if (referenceDelegate) {\r\n keys.forEach(function (key) {\r\n promises.push(referenceDelegate.removeReference(txn, key));\r\n });\r\n }\r\n return PersistencePromise.waitFor(promises);\r\n };\r\n MemoryQueryCache.prototype.removeMatchingKeysForTargetId = function (txn, targetId) {\r\n this.references.removeReferencesForId(targetId);\r\n return PersistencePromise.resolve();\r\n };\r\n MemoryQueryCache.prototype.getMatchingKeysForTargetId = function (txn, targetId) {\r\n var matchingKeys = this.references.referencesForId(targetId);\r\n return PersistencePromise.resolve(matchingKeys);\r\n };\r\n MemoryQueryCache.prototype.containsKey = function (txn, key) {\r\n return PersistencePromise.resolve(this.references.containsKey(key));\r\n };\r\n return MemoryQueryCache;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction documentSizeMap() {\r\n return new SortedMap(DocumentKey.comparator);\r\n}\r\nvar MemoryRemoteDocumentCache = /** @class */ (function () {\r\n /**\r\n * @param sizer Used to assess the size of a document. For eager GC, this is expected to just\r\n * return 0 to avoid unnecessarily doing the work of calculating the size.\r\n */\r\n function MemoryRemoteDocumentCache(indexManager, sizer) {\r\n this.indexManager = indexManager;\r\n this.sizer = sizer;\r\n this.docs = documentSizeMap();\r\n this.newDocumentChanges = documentKeySet();\r\n this.size = 0;\r\n }\r\n /**\r\n * Adds the supplied entries to the cache. Adds the given size delta to the cached size.\r\n */\r\n MemoryRemoteDocumentCache.prototype.addEntries = function (transaction, entries, sizeDelta) {\r\n var promises = [];\r\n for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {\r\n var entry = entries_1[_i];\r\n var key = entry.maybeDocument.key;\r\n this.docs = this.docs.insert(key, entry);\r\n this.newDocumentChanges = this.newDocumentChanges.add(key);\r\n promises.push(this.indexManager.addToCollectionParentIndex(transaction, key.path.popLast()));\r\n }\r\n this.size += sizeDelta;\r\n return PersistencePromise.waitFor(promises);\r\n };\r\n /**\r\n * Removes the specified entry from the cache and updates the size as appropriate.\r\n */\r\n MemoryRemoteDocumentCache.prototype.removeEntry = function (transaction, documentKey) {\r\n var entry = this.docs.get(documentKey);\r\n if (entry) {\r\n this.docs = this.docs.remove(documentKey);\r\n this.size -= entry.size;\r\n return PersistencePromise.resolve(entry.size);\r\n }\r\n else {\r\n return PersistencePromise.resolve(0);\r\n }\r\n };\r\n MemoryRemoteDocumentCache.prototype.getEntry = function (transaction, documentKey) {\r\n var entry = this.docs.get(documentKey);\r\n return PersistencePromise.resolve(entry ? entry.maybeDocument : null);\r\n };\r\n /**\r\n * Looks up an entry in the cache.\r\n *\r\n * @param documentKey The key of the entry to look up.\r\n * @return The cached MaybeDocument entry and its size, or null if we have nothing cached.\r\n */\r\n MemoryRemoteDocumentCache.prototype.getSizedEntry = function (transaction, documentKey) {\r\n return PersistencePromise.resolve(this.docs.get(documentKey));\r\n };\r\n MemoryRemoteDocumentCache.prototype.getEntries = function (transaction, documentKeys) {\r\n var _this = this;\r\n var results = nullableMaybeDocumentMap();\r\n documentKeys.forEach(function (documentKey) {\r\n var entry = _this.docs.get(documentKey);\r\n results = results.insert(documentKey, entry ? entry.maybeDocument : null);\r\n });\r\n return PersistencePromise.resolve(results);\r\n };\r\n /**\r\n * Looks up several entries in the cache.\r\n *\r\n * @param documentKeys The set of keys entries to look up.\r\n * @return A map of MaybeDocuments indexed by key (if a document cannot be\r\n * found, the key will be mapped to null) and a map of sizes indexed by\r\n * key (zero if the key cannot be found).\r\n */\r\n MemoryRemoteDocumentCache.prototype.getSizedEntries = function (transaction, documentKeys) {\r\n var _this = this;\r\n var results = nullableMaybeDocumentMap();\r\n var sizeMap = new SortedMap(DocumentKey.comparator);\r\n documentKeys.forEach(function (documentKey) {\r\n var entry = _this.docs.get(documentKey);\r\n results = results.insert(documentKey, entry ? entry.maybeDocument : null);\r\n sizeMap = sizeMap.insert(documentKey, entry ? entry.size : 0);\r\n });\r\n return PersistencePromise.resolve({ maybeDocuments: results, sizeMap: sizeMap });\r\n };\r\n MemoryRemoteDocumentCache.prototype.getDocumentsMatchingQuery = function (transaction, query) {\r\n assert(!query.isCollectionGroupQuery(), 'CollectionGroup queries should be handled in LocalDocumentsView');\r\n var results = documentMap();\r\n // Documents are ordered by key, so we can use a prefix scan to narrow down\r\n // the documents we need to match the query against.\r\n var prefix = new DocumentKey(query.path.child(''));\r\n var iterator = this.docs.getIteratorFrom(prefix);\r\n while (iterator.hasNext()) {\r\n var _a = iterator.getNext(), key = _a.key, maybeDocument = _a.value.maybeDocument;\r\n if (!query.path.isPrefixOf(key.path)) {\r\n break;\r\n }\r\n if (maybeDocument instanceof Document && query.matches(maybeDocument)) {\r\n results = results.insert(maybeDocument.key, maybeDocument);\r\n }\r\n }\r\n return PersistencePromise.resolve(results);\r\n };\r\n MemoryRemoteDocumentCache.prototype.forEachDocumentKey = function (transaction, f) {\r\n return PersistencePromise.forEach(this.docs, function (key) { return f(key); });\r\n };\r\n MemoryRemoteDocumentCache.prototype.getNewDocumentChanges = function (transaction) {\r\n var _this = this;\r\n var changedDocs = maybeDocumentMap();\r\n this.newDocumentChanges.forEach(function (key) {\r\n var entry = _this.docs.get(key);\r\n var changedDoc = entry\r\n ? entry.maybeDocument\r\n : new NoDocument(key, SnapshotVersion.forDeletedDoc());\r\n changedDocs = changedDocs.insert(key, changedDoc);\r\n });\r\n this.newDocumentChanges = documentKeySet();\r\n return PersistencePromise.resolve(changedDocs);\r\n };\r\n MemoryRemoteDocumentCache.prototype.newChangeBuffer = function () {\r\n return new MemoryRemoteDocumentChangeBuffer(this.sizer, this);\r\n };\r\n MemoryRemoteDocumentCache.prototype.getSize = function (txn) {\r\n return PersistencePromise.resolve(this.size);\r\n };\r\n return MemoryRemoteDocumentCache;\r\n}());\r\n/**\r\n * Handles the details of adding and updating documents in the MemoryRemoteDocumentCache.\r\n */\r\nvar MemoryRemoteDocumentChangeBuffer = /** @class */ (function (_super) {\r\n tslib_1.__extends(MemoryRemoteDocumentChangeBuffer, _super);\r\n function MemoryRemoteDocumentChangeBuffer(sizer, documentCache) {\r\n var _this = _super.call(this) || this;\r\n _this.sizer = sizer;\r\n _this.documentCache = documentCache;\r\n return _this;\r\n }\r\n MemoryRemoteDocumentChangeBuffer.prototype.applyChanges = function (transaction) {\r\n var _this = this;\r\n var changes = this.assertChanges();\r\n var delta = 0;\r\n var docs = [];\r\n changes.forEach(function (key, maybeDocument) {\r\n var previousSize = _this.documentSizes.get(key);\r\n assert(previousSize !== undefined, \"Attempting to change document \" + key.toString() + \" without having read it first\");\r\n var size = _this.sizer(maybeDocument);\r\n delta += size - previousSize;\r\n docs.push({ maybeDocument: maybeDocument, size: size });\r\n });\r\n return this.documentCache.addEntries(transaction, docs, delta);\r\n };\r\n MemoryRemoteDocumentChangeBuffer.prototype.getFromCache = function (transaction, documentKey) {\r\n return this.documentCache.getSizedEntry(transaction, documentKey);\r\n };\r\n MemoryRemoteDocumentChangeBuffer.prototype.getAllFromCache = function (transaction, documentKeys) {\r\n return this.documentCache.getSizedEntries(transaction, documentKeys);\r\n };\r\n return MemoryRemoteDocumentChangeBuffer;\r\n}(RemoteDocumentChangeBuffer));\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar LOG_TAG$4 = 'MemoryPersistence';\r\n/**\r\n * A memory-backed instance of Persistence. Data is stored only in RAM and\r\n * not persisted across sessions.\r\n */\r\nvar MemoryPersistence = /** @class */ (function () {\r\n /**\r\n * The constructor accepts a factory for creating a reference delegate. This\r\n * allows both the delegate and this instance to have strong references to\r\n * each other without having nullable fields that would then need to be\r\n * checked or asserted on every access.\r\n */\r\n function MemoryPersistence(clientId, referenceDelegateFactory) {\r\n var _this = this;\r\n this.clientId = clientId;\r\n this.mutationQueues = {};\r\n this.listenSequence = new ListenSequence(0);\r\n this._started = false;\r\n this._started = true;\r\n this.referenceDelegate = referenceDelegateFactory(this);\r\n this.queryCache = new MemoryQueryCache(this);\r\n var sizer = function (doc) {\r\n return _this.referenceDelegate.documentSize(doc);\r\n };\r\n this.indexManager = new MemoryIndexManager();\r\n this.remoteDocumentCache = new MemoryRemoteDocumentCache(this.indexManager, sizer);\r\n }\r\n MemoryPersistence.createLruPersistence = function (clientId, serializer, params) {\r\n var factory = function (p) {\r\n return new MemoryLruDelegate(p, new LocalSerializer(serializer), params);\r\n };\r\n return new MemoryPersistence(clientId, factory);\r\n };\r\n MemoryPersistence.createEagerPersistence = function (clientId) {\r\n var factory = function (p) {\r\n return new MemoryEagerDelegate(p);\r\n };\r\n return new MemoryPersistence(clientId, factory);\r\n };\r\n MemoryPersistence.prototype.shutdown = function () {\r\n // No durable state to ensure is closed on shutdown.\r\n this._started = false;\r\n return Promise.resolve();\r\n };\r\n Object.defineProperty(MemoryPersistence.prototype, \"started\", {\r\n get: function () {\r\n return this._started;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n MemoryPersistence.prototype.getActiveClients = function () {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n return tslib_1.__generator(this, function (_a) {\r\n return [2 /*return*/, [this.clientId]];\r\n });\r\n });\r\n };\r\n MemoryPersistence.prototype.setPrimaryStateListener = function (primaryStateListener) {\r\n // All clients using memory persistence act as primary.\r\n return primaryStateListener(true);\r\n };\r\n MemoryPersistence.prototype.setNetworkEnabled = function (networkEnabled) {\r\n // No op.\r\n };\r\n MemoryPersistence.prototype.getIndexManager = function () {\r\n return this.indexManager;\r\n };\r\n MemoryPersistence.prototype.getMutationQueue = function (user) {\r\n var queue = this.mutationQueues[user.toKey()];\r\n if (!queue) {\r\n queue = new MemoryMutationQueue(this.indexManager, this.referenceDelegate);\r\n this.mutationQueues[user.toKey()] = queue;\r\n }\r\n return queue;\r\n };\r\n MemoryPersistence.prototype.getQueryCache = function () {\r\n return this.queryCache;\r\n };\r\n MemoryPersistence.prototype.getRemoteDocumentCache = function () {\r\n return this.remoteDocumentCache;\r\n };\r\n MemoryPersistence.prototype.runTransaction = function (action, mode, transactionOperation) {\r\n var _this = this;\r\n debug(LOG_TAG$4, 'Starting transaction:', action);\r\n var txn = new MemoryTransaction(this.listenSequence.next());\r\n this.referenceDelegate.onTransactionStarted();\r\n return transactionOperation(txn)\r\n .next(function (result) {\r\n return _this.referenceDelegate\r\n .onTransactionCommitted(txn)\r\n .next(function () { return result; });\r\n })\r\n .toPromise();\r\n };\r\n MemoryPersistence.prototype.mutationQueuesContainKey = function (transaction, key) {\r\n return PersistencePromise.or(values(this.mutationQueues)\r\n .map(function (queue) { return function () { return queue.containsKey(transaction, key); }; }));\r\n };\r\n return MemoryPersistence;\r\n}());\r\n/**\r\n * Memory persistence is not actually transactional, but future implementations\r\n * may have transaction-scoped state.\r\n */\r\nvar MemoryTransaction = /** @class */ (function () {\r\n function MemoryTransaction(currentSequenceNumber) {\r\n this.currentSequenceNumber = currentSequenceNumber;\r\n }\r\n return MemoryTransaction;\r\n}());\r\nvar MemoryEagerDelegate = /** @class */ (function () {\r\n function MemoryEagerDelegate(persistence) {\r\n this.persistence = persistence;\r\n }\r\n MemoryEagerDelegate.prototype.setInMemoryPins = function (inMemoryPins) {\r\n this.inMemoryPins = inMemoryPins;\r\n };\r\n MemoryEagerDelegate.prototype.addReference = function (txn, key) {\r\n this.orphanedDocuments.delete(key);\r\n return PersistencePromise.resolve();\r\n };\r\n MemoryEagerDelegate.prototype.removeReference = function (txn, key) {\r\n this.orphanedDocuments.add(key);\r\n return PersistencePromise.resolve();\r\n };\r\n MemoryEagerDelegate.prototype.removeMutationReference = function (txn, key) {\r\n this.orphanedDocuments.add(key);\r\n return PersistencePromise.resolve();\r\n };\r\n MemoryEagerDelegate.prototype.removeTarget = function (txn, queryData) {\r\n var _this = this;\r\n var cache = this.persistence.getQueryCache();\r\n return cache\r\n .getMatchingKeysForTargetId(txn, queryData.targetId)\r\n .next(function (keys) {\r\n keys.forEach(function (key) { return _this.orphanedDocuments.add(key); });\r\n })\r\n .next(function () { return cache.removeQueryData(txn, queryData); });\r\n };\r\n MemoryEagerDelegate.prototype.onTransactionStarted = function () {\r\n this.orphanedDocuments = new Set();\r\n };\r\n MemoryEagerDelegate.prototype.onTransactionCommitted = function (txn) {\r\n var _this = this;\r\n var cache = this.persistence.getRemoteDocumentCache();\r\n return PersistencePromise.forEach(this.orphanedDocuments, function (key) {\r\n return _this.isReferenced(txn, key).next(function (isReferenced) {\r\n if (!isReferenced) {\r\n // Since this is the eager delegate and memory persistence,\r\n // we don't care about the size of documents. We don't track\r\n // the size of the cache for eager GC.\r\n return cache.removeEntry(txn, key).next(function () { });\r\n }\r\n return PersistencePromise.resolve();\r\n });\r\n });\r\n };\r\n MemoryEagerDelegate.prototype.updateLimboDocument = function (txn, key) {\r\n var _this = this;\r\n return this.isReferenced(txn, key).next(function (isReferenced) {\r\n if (isReferenced) {\r\n _this.orphanedDocuments.delete(key);\r\n }\r\n else {\r\n _this.orphanedDocuments.add(key);\r\n }\r\n });\r\n };\r\n MemoryEagerDelegate.prototype.documentSize = function (doc) {\r\n // For eager GC, we don't care about the document size, there are no size thresholds.\r\n return 0;\r\n };\r\n MemoryEagerDelegate.prototype.isReferenced = function (txn, key) {\r\n var _this = this;\r\n return PersistencePromise.or([\r\n function () { return _this.persistence.getQueryCache().containsKey(txn, key); },\r\n function () { return _this.persistence.mutationQueuesContainKey(txn, key); },\r\n function () { return PersistencePromise.resolve(_this.inMemoryPins.containsKey(key)); }\r\n ]);\r\n };\r\n return MemoryEagerDelegate;\r\n}());\r\nvar MemoryLruDelegate = /** @class */ (function () {\r\n function MemoryLruDelegate(persistence, serializer, lruParams) {\r\n this.persistence = persistence;\r\n this.serializer = serializer;\r\n this.orphanedSequenceNumbers = new ObjectMap(function (k) { return encode(k.path); });\r\n this.garbageCollector = new LruGarbageCollector(this, lruParams);\r\n }\r\n // No-ops, present so memory persistence doesn't have to care which delegate\r\n // it has.\r\n MemoryLruDelegate.prototype.onTransactionStarted = function () { };\r\n MemoryLruDelegate.prototype.onTransactionCommitted = function (txn) {\r\n return PersistencePromise.resolve();\r\n };\r\n MemoryLruDelegate.prototype.forEachTarget = function (txn, f) {\r\n return this.persistence.getQueryCache().forEachTarget(txn, f);\r\n };\r\n MemoryLruDelegate.prototype.getSequenceNumberCount = function (txn) {\r\n var docCountPromise = this.orphanedDocumentCount(txn);\r\n var targetCountPromise = this.persistence\r\n .getQueryCache()\r\n .getTargetCount(txn);\r\n return targetCountPromise.next(function (targetCount) {\r\n return docCountPromise.next(function (docCount) { return targetCount + docCount; });\r\n });\r\n };\r\n MemoryLruDelegate.prototype.orphanedDocumentCount = function (txn) {\r\n var orphanedCount = 0;\r\n return this.forEachOrphanedDocumentSequenceNumber(txn, function (_) {\r\n orphanedCount++;\r\n }).next(function () { return orphanedCount; });\r\n };\r\n MemoryLruDelegate.prototype.forEachOrphanedDocumentSequenceNumber = function (txn, f) {\r\n var _this = this;\r\n return PersistencePromise.forEach(this.orphanedSequenceNumbers, function (key, sequenceNumber) {\r\n // Pass in the exact sequence number as the upper bound so we know it won't be pinned by\r\n // being too recent.\r\n return _this.isPinned(txn, key, sequenceNumber).next(function (isPinned) {\r\n if (!isPinned) {\r\n return f(sequenceNumber);\r\n }\r\n else {\r\n return PersistencePromise.resolve();\r\n }\r\n });\r\n });\r\n };\r\n MemoryLruDelegate.prototype.setInMemoryPins = function (inMemoryPins) {\r\n this.inMemoryPins = inMemoryPins;\r\n };\r\n MemoryLruDelegate.prototype.removeTargets = function (txn, upperBound, activeTargetIds) {\r\n return this.persistence\r\n .getQueryCache()\r\n .removeTargets(txn, upperBound, activeTargetIds);\r\n };\r\n MemoryLruDelegate.prototype.removeOrphanedDocuments = function (txn, upperBound) {\r\n var _this = this;\r\n var count = 0;\r\n var cache = this.persistence.getRemoteDocumentCache();\r\n var p = cache.forEachDocumentKey(txn, function (key) {\r\n return _this.isPinned(txn, key, upperBound).next(function (isPinned) {\r\n if (isPinned) {\r\n return PersistencePromise.resolve();\r\n }\r\n else {\r\n count++;\r\n // The memory remote document cache does its own byte\r\n // accounting on removal. This is ok because updating the size\r\n // for memory persistence does not incur IO.\r\n return cache.removeEntry(txn, key).next();\r\n }\r\n });\r\n });\r\n return p.next(function () { return count; });\r\n };\r\n MemoryLruDelegate.prototype.removeMutationReference = function (txn, key) {\r\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\r\n return PersistencePromise.resolve();\r\n };\r\n MemoryLruDelegate.prototype.removeTarget = function (txn, queryData) {\r\n var updated = queryData.copy({\r\n sequenceNumber: txn.currentSequenceNumber\r\n });\r\n return this.persistence.getQueryCache().updateQueryData(txn, updated);\r\n };\r\n MemoryLruDelegate.prototype.addReference = function (txn, key) {\r\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\r\n return PersistencePromise.resolve();\r\n };\r\n MemoryLruDelegate.prototype.removeReference = function (txn, key) {\r\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\r\n return PersistencePromise.resolve();\r\n };\r\n MemoryLruDelegate.prototype.updateLimboDocument = function (txn, key) {\r\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\r\n return PersistencePromise.resolve();\r\n };\r\n MemoryLruDelegate.prototype.documentSize = function (maybeDoc) {\r\n var remoteDocument = this.serializer.toDbRemoteDocument(maybeDoc);\r\n var value;\r\n if (remoteDocument.document) {\r\n value = remoteDocument.document;\r\n }\r\n else if (remoteDocument.unknownDocument) {\r\n value = remoteDocument.unknownDocument;\r\n }\r\n else if (remoteDocument.noDocument) {\r\n value = remoteDocument.noDocument;\r\n }\r\n else {\r\n throw fail('Unknown remote document type');\r\n }\r\n return JSON.stringify(value).length;\r\n };\r\n MemoryLruDelegate.prototype.isPinned = function (txn, key, upperBound) {\r\n var _this = this;\r\n return PersistencePromise.or([\r\n function () { return _this.persistence.mutationQueuesContainKey(txn, key); },\r\n function () { return PersistencePromise.resolve(_this.inMemoryPins.containsKey(key)); },\r\n function () { return _this.persistence.getQueryCache().containsKey(txn, key); },\r\n function () {\r\n var orphanedAt = _this.orphanedSequenceNumbers.get(key);\r\n return PersistencePromise.resolve(orphanedAt !== undefined && orphanedAt > upperBound);\r\n }\r\n ]);\r\n };\r\n MemoryLruDelegate.prototype.getCacheSize = function (txn) {\r\n return this.persistence.getRemoteDocumentCache().getSize(txn);\r\n };\r\n return MemoryLruDelegate;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar LOG_TAG$5 = 'ExponentialBackoff';\r\n/**\r\n * A helper for running delayed tasks following an exponential backoff curve\r\n * between attempts.\r\n *\r\n * Each delay is made up of a \"base\" delay which follows the exponential\r\n * backoff curve, and a +/- 50% \"jitter\" that is calculated and added to the\r\n * base delay. This prevents clients from accidentally synchronizing their\r\n * delays causing spikes of load to the backend.\r\n */\r\nvar ExponentialBackoff = /** @class */ (function () {\r\n function ExponentialBackoff(\r\n /**\r\n * The AsyncQueue to run backoff operations on.\r\n */\r\n queue, \r\n /**\r\n * The ID to use when scheduling backoff operations on the AsyncQueue.\r\n */\r\n timerId, \r\n /**\r\n * The initial delay (used as the base delay on the first retry attempt).\r\n * Note that jitter will still be applied, so the actual delay could be as\r\n * little as 0.5*initialDelayMs.\r\n */\r\n initialDelayMs, \r\n /**\r\n * The multiplier to use to determine the extended base delay after each\r\n * attempt.\r\n */\r\n backoffFactor, \r\n /**\r\n * The maximum base delay after which no further backoff is performed.\r\n * Note that jitter will still be applied, so the actual delay could be as\r\n * much as 1.5*maxDelayMs.\r\n */\r\n maxDelayMs) {\r\n this.queue = queue;\r\n this.timerId = timerId;\r\n this.initialDelayMs = initialDelayMs;\r\n this.backoffFactor = backoffFactor;\r\n this.maxDelayMs = maxDelayMs;\r\n this.timerPromise = null;\r\n /** The last backoff attempt, as epoch milliseconds. */\r\n this.lastAttemptTime = Date.now();\r\n this.reset();\r\n }\r\n /**\r\n * Resets the backoff delay.\r\n *\r\n * The very next backoffAndWait() will have no delay. If it is called again\r\n * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and\r\n * subsequent ones will increase according to the backoffFactor.\r\n */\r\n ExponentialBackoff.prototype.reset = function () {\r\n this.currentBaseMs = 0;\r\n };\r\n /**\r\n * Resets the backoff delay to the maximum delay (e.g. for use after a\r\n * RESOURCE_EXHAUSTED error).\r\n */\r\n ExponentialBackoff.prototype.resetToMax = function () {\r\n this.currentBaseMs = this.maxDelayMs;\r\n };\r\n /**\r\n * Returns a promise that resolves after currentDelayMs, and increases the\r\n * delay for any subsequent attempts. If there was a pending backoff operation\r\n * already, it will be canceled.\r\n */\r\n ExponentialBackoff.prototype.backoffAndRun = function (op) {\r\n var _this = this;\r\n // Cancel any pending backoff operation.\r\n this.cancel();\r\n // First schedule using the current base (which may be 0 and should be\r\n // honored as such).\r\n var desiredDelayWithJitterMs = Math.floor(this.currentBaseMs + this.jitterDelayMs());\r\n // Guard against lastAttemptTime being in the future due to a clock change.\r\n var delaySoFarMs = Math.max(0, Date.now() - this.lastAttemptTime);\r\n // Guard against the backoff delay already being past.\r\n var remainingDelayMs = Math.max(0, desiredDelayWithJitterMs - delaySoFarMs);\r\n if (this.currentBaseMs > 0) {\r\n debug(LOG_TAG$5, \"Backing off for \" + remainingDelayMs + \" ms \" +\r\n (\"(base delay: \" + this.currentBaseMs + \" ms, \") +\r\n (\"delay with jitter: \" + desiredDelayWithJitterMs + \" ms, \") +\r\n (\"last attempt: \" + delaySoFarMs + \" ms ago)\"));\r\n }\r\n this.timerPromise = this.queue.enqueueAfterDelay(this.timerId, remainingDelayMs, function () {\r\n _this.lastAttemptTime = Date.now();\r\n return op();\r\n });\r\n // Apply backoff factor to determine next delay and ensure it is within\r\n // bounds.\r\n this.currentBaseMs *= this.backoffFactor;\r\n if (this.currentBaseMs < this.initialDelayMs) {\r\n this.currentBaseMs = this.initialDelayMs;\r\n }\r\n if (this.currentBaseMs > this.maxDelayMs) {\r\n this.currentBaseMs = this.maxDelayMs;\r\n }\r\n };\r\n ExponentialBackoff.prototype.cancel = function () {\r\n if (this.timerPromise !== null) {\r\n this.timerPromise.cancel();\r\n this.timerPromise = null;\r\n }\r\n };\r\n /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */\r\n ExponentialBackoff.prototype.jitterDelayMs = function () {\r\n return (Math.random() - 0.5) * this.currentBaseMs;\r\n };\r\n return ExponentialBackoff;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar LOG_TAG$6 = 'PersistentStream';\r\n/**\r\n * PersistentStream can be in one of 5 states (each described in detail below)\r\n * based on the following state transition diagram:\r\n *\r\n * start() called auth & connection succeeded\r\n * INITIAL ----------------> STARTING -----------------------------> OPEN\r\n * ^ | |\r\n * | | error occurred |\r\n * | \\-----------------------------v-----/\r\n * | |\r\n * backoff | |\r\n * elapsed | start() called |\r\n * \\--- BACKOFF <---------------- ERROR\r\n *\r\n * [any state] --------------------------> INITIAL\r\n * stop() called or\r\n * idle timer expired\r\n */\r\nvar PersistentStreamState;\r\n(function (PersistentStreamState) {\r\n /**\r\n * The streaming RPC is not yet running and there's no error condition.\r\n * Calling start() will start the stream immediately without backoff.\r\n * While in this state isStarted() will return false.\r\n */\r\n PersistentStreamState[PersistentStreamState[\"Initial\"] = 0] = \"Initial\";\r\n /**\r\n * The stream is starting, either waiting for an auth token or for the stream\r\n * to successfully open. While in this state, isStarted() will return true but\r\n * isOpen() will return false.\r\n */\r\n PersistentStreamState[PersistentStreamState[\"Starting\"] = 1] = \"Starting\";\r\n /**\r\n * The streaming RPC is up and running. Requests and responses can flow\r\n * freely. Both isStarted() and isOpen() will return true.\r\n */\r\n PersistentStreamState[PersistentStreamState[\"Open\"] = 2] = \"Open\";\r\n /**\r\n * The stream encountered an error. The next start attempt will back off.\r\n * While in this state isStarted() will return false.\r\n */\r\n PersistentStreamState[PersistentStreamState[\"Error\"] = 3] = \"Error\";\r\n /**\r\n * An in-between state after an error where the stream is waiting before\r\n * re-starting. After waiting is complete, the stream will try to open.\r\n * While in this state isStarted() will return true but isOpen() will return\r\n * false.\r\n */\r\n PersistentStreamState[PersistentStreamState[\"Backoff\"] = 4] = \"Backoff\";\r\n})(PersistentStreamState || (PersistentStreamState = {}));\r\n/**\r\n * Initial backoff time in milliseconds after an error.\r\n * Set to 1s according to https://cloud.google.com/apis/design/errors.\r\n */\r\nvar BACKOFF_INITIAL_DELAY_MS = 1000;\r\n/** Maximum backoff time in milliseconds */\r\nvar BACKOFF_MAX_DELAY_MS = 60 * 1000;\r\nvar BACKOFF_FACTOR = 1.5;\r\n/** The time a stream stays open after it is marked idle. */\r\nvar IDLE_TIMEOUT_MS = 60 * 1000;\r\n/**\r\n * A PersistentStream is an abstract base class that represents a streaming RPC\r\n * to the Firestore backend. It's built on top of the connections own support\r\n * for streaming RPCs, and adds several critical features for our clients:\r\n *\r\n * - Exponential backoff on failure\r\n * - Authentication via CredentialsProvider\r\n * - Dispatching all callbacks into the shared worker queue\r\n * - Closing idle streams after 60 seconds of inactivity\r\n *\r\n * Subclasses of PersistentStream implement serialization of models to and\r\n * from the JSON representation of the protocol buffers for a specific\r\n * streaming RPC.\r\n *\r\n * ## Starting and Stopping\r\n *\r\n * Streaming RPCs are stateful and need to be start()ed before messages can\r\n * be sent and received. The PersistentStream will call the onOpen() function\r\n * of the listener once the stream is ready to accept requests.\r\n *\r\n * Should a start() fail, PersistentStream will call the registered onClose()\r\n * listener with a FirestoreError indicating what went wrong.\r\n *\r\n * A PersistentStream can be started and stopped repeatedly.\r\n *\r\n * Generic types:\r\n * SendType: The type of the outgoing message of the underlying\r\n * connection stream\r\n * ReceiveType: The type of the incoming message of the underlying\r\n * connection stream\r\n * ListenerType: The type of the listener that will be used for callbacks\r\n */\r\nvar PersistentStream = /** @class */ (function () {\r\n function PersistentStream(queue, connectionTimerId, idleTimerId, connection, credentialsProvider, listener) {\r\n this.queue = queue;\r\n this.idleTimerId = idleTimerId;\r\n this.connection = connection;\r\n this.credentialsProvider = credentialsProvider;\r\n this.listener = listener;\r\n this.state = PersistentStreamState.Initial;\r\n /**\r\n * A close count that's incremented every time the stream is closed; used by\r\n * getCloseGuardedDispatcher() to invalidate callbacks that happen after\r\n * close.\r\n */\r\n this.closeCount = 0;\r\n this.idleTimer = null;\r\n this.stream = null;\r\n this.backoff = new ExponentialBackoff(queue, connectionTimerId, BACKOFF_INITIAL_DELAY_MS, BACKOFF_FACTOR, BACKOFF_MAX_DELAY_MS);\r\n }\r\n /**\r\n * Returns true if start() has been called and no error has occurred. True\r\n * indicates the stream is open or in the process of opening (which\r\n * encompasses respecting backoff, getting auth tokens, and starting the\r\n * actual RPC). Use isOpen() to determine if the stream is open and ready for\r\n * outbound requests.\r\n */\r\n PersistentStream.prototype.isStarted = function () {\r\n return (this.state === PersistentStreamState.Starting ||\r\n this.state === PersistentStreamState.Open ||\r\n this.state === PersistentStreamState.Backoff);\r\n };\r\n /**\r\n * Returns true if the underlying RPC is open (the onOpen() listener has been\r\n * called) and the stream is ready for outbound requests.\r\n */\r\n PersistentStream.prototype.isOpen = function () {\r\n return this.state === PersistentStreamState.Open;\r\n };\r\n /**\r\n * Starts the RPC. Only allowed if isStarted() returns false. The stream is\r\n * not immediately ready for use: onOpen() will be invoked when the RPC is\r\n * ready for outbound requests, at which point isOpen() will return true.\r\n *\r\n * When start returns, isStarted() will return true.\r\n */\r\n PersistentStream.prototype.start = function () {\r\n if (this.state === PersistentStreamState.Error) {\r\n this.performBackoff();\r\n return;\r\n }\r\n assert(this.state === PersistentStreamState.Initial, 'Already started');\r\n this.auth();\r\n };\r\n /**\r\n * Stops the RPC. This call is idempotent and allowed regardless of the\r\n * current isStarted() state.\r\n *\r\n * When stop returns, isStarted() and isOpen() will both return false.\r\n */\r\n PersistentStream.prototype.stop = function () {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (!this.isStarted()) return [3 /*break*/, 2];\r\n return [4 /*yield*/, this.close(PersistentStreamState.Initial)];\r\n case 1:\r\n _a.sent();\r\n _a.label = 2;\r\n case 2: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * After an error the stream will usually back off on the next attempt to\r\n * start it. If the error warrants an immediate restart of the stream, the\r\n * sender can use this to indicate that the receiver should not back off.\r\n *\r\n * Each error will call the onClose() listener. That function can decide to\r\n * inhibit backoff if required.\r\n */\r\n PersistentStream.prototype.inhibitBackoff = function () {\r\n assert(!this.isStarted(), 'Can only inhibit backoff in a stopped state');\r\n this.state = PersistentStreamState.Initial;\r\n this.backoff.reset();\r\n };\r\n /**\r\n * Marks this stream as idle. If no further actions are performed on the\r\n * stream for one minute, the stream will automatically close itself and\r\n * notify the stream's onClose() handler with Status.OK. The stream will then\r\n * be in a !isStarted() state, requiring the caller to start the stream again\r\n * before further use.\r\n *\r\n * Only streams that are in state 'Open' can be marked idle, as all other\r\n * states imply pending network operations.\r\n */\r\n PersistentStream.prototype.markIdle = function () {\r\n var _this = this;\r\n // Starts the idle time if we are in state 'Open' and are not yet already\r\n // running a timer (in which case the previous idle timeout still applies).\r\n if (this.isOpen() && this.idleTimer === null) {\r\n this.idleTimer = this.queue.enqueueAfterDelay(this.idleTimerId, IDLE_TIMEOUT_MS, function () { return _this.handleIdleCloseTimer(); });\r\n }\r\n };\r\n /** Sends a message to the underlying stream. */\r\n PersistentStream.prototype.sendRequest = function (msg) {\r\n this.cancelIdleCheck();\r\n this.stream.send(msg);\r\n };\r\n /** Called by the idle timer when the stream should close due to inactivity. */\r\n PersistentStream.prototype.handleIdleCloseTimer = function () {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n return tslib_1.__generator(this, function (_a) {\r\n if (this.isOpen()) {\r\n // When timing out an idle stream there's no reason to force the stream into backoff when\r\n // it restarts so set the stream state to Initial instead of Error.\r\n return [2 /*return*/, this.close(PersistentStreamState.Initial)];\r\n }\r\n return [2 /*return*/];\r\n });\r\n });\r\n };\r\n /** Marks the stream as active again. */\r\n PersistentStream.prototype.cancelIdleCheck = function () {\r\n if (this.idleTimer) {\r\n this.idleTimer.cancel();\r\n this.idleTimer = null;\r\n }\r\n };\r\n /**\r\n * Closes the stream and cleans up as necessary:\r\n *\r\n * * closes the underlying GRPC stream;\r\n * * calls the onClose handler with the given 'error';\r\n * * sets internal stream state to 'finalState';\r\n * * adjusts the backoff timer based on the error\r\n *\r\n * A new stream can be opened by calling start().\r\n *\r\n * @param finalState the intended state of the stream after closing.\r\n * @param error the error the connection was closed with.\r\n */\r\n PersistentStream.prototype.close = function (finalState, error$1) {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n assert(this.isStarted(), 'Only started streams should be closed.');\r\n assert(finalState === PersistentStreamState.Error || isNullOrUndefined(error$1), \"Can't provide an error when not in an error state.\");\r\n // Cancel any outstanding timers (they're guaranteed not to execute).\r\n this.cancelIdleCheck();\r\n this.backoff.cancel();\r\n // Invalidates any stream-related callbacks (e.g. from auth or the\r\n // underlying stream), guaranteeing they won't execute.\r\n this.closeCount++;\r\n if (finalState !== PersistentStreamState.Error) {\r\n // If this is an intentional close ensure we don't delay our next connection attempt.\r\n this.backoff.reset();\r\n }\r\n else if (error$1 && error$1.code === Code.RESOURCE_EXHAUSTED) {\r\n // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)\r\n error(error$1.toString());\r\n error('Using maximum backoff delay to prevent overloading the backend.');\r\n this.backoff.resetToMax();\r\n }\r\n else if (error$1 && error$1.code === Code.UNAUTHENTICATED) {\r\n // \"unauthenticated\" error means the token was rejected. Try force refreshing it in case it\r\n // just expired.\r\n this.credentialsProvider.invalidateToken();\r\n }\r\n // Clean up the underlying stream because we are no longer interested in events.\r\n if (this.stream !== null) {\r\n this.tearDown();\r\n this.stream.close();\r\n this.stream = null;\r\n }\r\n // This state must be assigned before calling onClose() to allow the callback to\r\n // inhibit backoff or otherwise manipulate the state in its non-started state.\r\n this.state = finalState;\r\n // Notify the listener that the stream closed.\r\n return [4 /*yield*/, this.listener.onClose(error$1)];\r\n case 1:\r\n // Notify the listener that the stream closed.\r\n _a.sent();\r\n return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * Can be overridden to perform additional cleanup before the stream is closed.\r\n * Calling super.tearDown() is not required.\r\n */\r\n PersistentStream.prototype.tearDown = function () { };\r\n PersistentStream.prototype.auth = function () {\r\n var _this = this;\r\n assert(this.state === PersistentStreamState.Initial, 'Must be in initial state to auth');\r\n this.state = PersistentStreamState.Starting;\r\n var dispatchIfNotClosed = this.getCloseGuardedDispatcher(this.closeCount);\r\n // TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below.\r\n var closeCount = this.closeCount;\r\n this.credentialsProvider.getToken().then(function (token) {\r\n // Stream can be stopped while waiting for authentication.\r\n // TODO(mikelehen): We really should just use dispatchIfNotClosed\r\n // and let this dispatch onto the queue, but that opened a spec test can\r\n // of worms that I don't want to deal with in this PR.\r\n if (_this.closeCount === closeCount) {\r\n // Normally we'd have to schedule the callback on the AsyncQueue.\r\n // However, the following calls are safe to be called outside the\r\n // AsyncQueue since they don't chain asynchronous calls\r\n _this.startStream(token);\r\n }\r\n }, function (error) {\r\n dispatchIfNotClosed(function () {\r\n var rpcError = new FirestoreError(Code.UNKNOWN, 'Fetching auth token failed: ' + error.message);\r\n return _this.handleStreamClose(rpcError);\r\n });\r\n });\r\n };\r\n PersistentStream.prototype.startStream = function (token) {\r\n var _this = this;\r\n assert(this.state === PersistentStreamState.Starting, 'Trying to start stream in a non-starting state');\r\n var dispatchIfNotClosed = this.getCloseGuardedDispatcher(this.closeCount);\r\n this.stream = this.startRpc(token);\r\n this.stream.onOpen(function () {\r\n dispatchIfNotClosed(function () {\r\n assert(_this.state === PersistentStreamState.Starting, 'Expected stream to be in state Starting, but was ' + _this.state);\r\n _this.state = PersistentStreamState.Open;\r\n return _this.listener.onOpen();\r\n });\r\n });\r\n this.stream.onClose(function (error) {\r\n dispatchIfNotClosed(function () {\r\n return _this.handleStreamClose(error);\r\n });\r\n });\r\n this.stream.onMessage(function (msg) {\r\n dispatchIfNotClosed(function () {\r\n return _this.onMessage(msg);\r\n });\r\n });\r\n };\r\n PersistentStream.prototype.performBackoff = function () {\r\n var _this = this;\r\n assert(this.state === PersistentStreamState.Error, 'Should only perform backoff when in Error state');\r\n this.state = PersistentStreamState.Backoff;\r\n this.backoff.backoffAndRun(function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {\r\n return tslib_1.__generator(this, function (_a) {\r\n assert(this.state === PersistentStreamState.Backoff, 'Backoff elapsed but state is now: ' + this.state);\r\n this.state = PersistentStreamState.Initial;\r\n this.start();\r\n assert(this.isStarted(), 'PersistentStream should have started');\r\n return [2 /*return*/];\r\n });\r\n }); });\r\n };\r\n // Visible for tests\r\n PersistentStream.prototype.handleStreamClose = function (error) {\r\n assert(this.isStarted(), \"Can't handle server close on non-started stream\");\r\n debug(LOG_TAG$6, \"close with error: \" + error);\r\n this.stream = null;\r\n // In theory the stream could close cleanly, however, in our current model\r\n // we never expect this to happen because if we stop a stream ourselves,\r\n // this callback will never be called. To prevent cases where we retry\r\n // without a backoff accidentally, we set the stream to error in all cases.\r\n return this.close(PersistentStreamState.Error, error);\r\n };\r\n /**\r\n * Returns a \"dispatcher\" function that dispatches operations onto the\r\n * AsyncQueue but only runs them if closeCount remains unchanged. This allows\r\n * us to turn auth / stream callbacks into no-ops if the stream is closed /\r\n * re-opened, etc.\r\n */\r\n PersistentStream.prototype.getCloseGuardedDispatcher = function (startCloseCount) {\r\n var _this = this;\r\n return function (fn) {\r\n _this.queue.enqueueAndForget(function () {\r\n if (_this.closeCount === startCloseCount) {\r\n return fn();\r\n }\r\n else {\r\n debug(LOG_TAG$6, 'stream callback skipped by getCloseGuardedDispatcher.');\r\n return Promise.resolve();\r\n }\r\n });\r\n };\r\n };\r\n return PersistentStream;\r\n}());\r\n/**\r\n * A PersistentStream that implements the Listen RPC.\r\n *\r\n * Once the Listen stream has called the onOpen() listener, any number of\r\n * listen() and unlisten() calls can be made to control what changes will be\r\n * sent from the server for ListenResponses.\r\n */\r\nvar PersistentListenStream = /** @class */ (function (_super) {\r\n tslib_1.__extends(PersistentListenStream, _super);\r\n function PersistentListenStream(queue, connection, credentials, serializer, listener) {\r\n var _this = _super.call(this, queue, TimerId.ListenStreamConnectionBackoff, TimerId.ListenStreamIdle, connection, credentials, listener) || this;\r\n _this.serializer = serializer;\r\n return _this;\r\n }\r\n PersistentListenStream.prototype.startRpc = function (token) {\r\n return this.connection.openStream('Listen', token);\r\n };\r\n PersistentListenStream.prototype.onMessage = function (watchChangeProto) {\r\n // A successful response means the stream is healthy\r\n this.backoff.reset();\r\n var watchChange = this.serializer.fromWatchChange(watchChangeProto);\r\n var snapshot = this.serializer.versionFromListenResponse(watchChangeProto);\r\n return this.listener.onWatchChange(watchChange, snapshot);\r\n };\r\n /**\r\n * Registers interest in the results of the given query. If the query\r\n * includes a resumeToken it will be included in the request. Results that\r\n * affect the query will be streamed back as WatchChange messages that\r\n * reference the targetId.\r\n */\r\n PersistentListenStream.prototype.watch = function (queryData) {\r\n var request = {};\r\n request.database = this.serializer.encodedDatabaseId;\r\n request.addTarget = this.serializer.toTarget(queryData);\r\n var labels = this.serializer.toListenRequestLabels(queryData);\r\n if (labels) {\r\n request.labels = labels;\r\n }\r\n this.sendRequest(request);\r\n };\r\n /**\r\n * Unregisters interest in the results of the query associated with the\r\n * given targetId.\r\n */\r\n PersistentListenStream.prototype.unwatch = function (targetId) {\r\n var request = {};\r\n request.database = this.serializer.encodedDatabaseId;\r\n request.removeTarget = targetId;\r\n this.sendRequest(request);\r\n };\r\n return PersistentListenStream;\r\n}(PersistentStream));\r\n/**\r\n * A Stream that implements the Write RPC.\r\n *\r\n * The Write RPC requires the caller to maintain special streamToken\r\n * state in between calls, to help the server understand which responses the\r\n * client has processed by the time the next request is made. Every response\r\n * will contain a streamToken; this value must be passed to the next\r\n * request.\r\n *\r\n * After calling start() on this stream, the next request must be a handshake,\r\n * containing whatever streamToken is on hand. Once a response to this\r\n * request is received, all pending mutations may be submitted. When\r\n * submitting multiple batches of mutations at the same time, it's\r\n * okay to use the same streamToken for the calls to writeMutations.\r\n *\r\n * TODO(b/33271235): Use proto types\r\n */\r\nvar PersistentWriteStream = /** @class */ (function (_super) {\r\n tslib_1.__extends(PersistentWriteStream, _super);\r\n function PersistentWriteStream(queue, connection, credentials, serializer, listener) {\r\n var _this = _super.call(this, queue, TimerId.WriteStreamConnectionBackoff, TimerId.WriteStreamIdle, connection, credentials, listener) || this;\r\n _this.serializer = serializer;\r\n _this.handshakeComplete_ = false;\r\n return _this;\r\n }\r\n Object.defineProperty(PersistentWriteStream.prototype, \"handshakeComplete\", {\r\n /**\r\n * Tracks whether or not a handshake has been successfully exchanged and\r\n * the stream is ready to accept mutations.\r\n */\r\n get: function () {\r\n return this.handshakeComplete_;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n // Override of PersistentStream.start\r\n PersistentWriteStream.prototype.start = function () {\r\n this.handshakeComplete_ = false;\r\n _super.prototype.start.call(this);\r\n };\r\n PersistentWriteStream.prototype.tearDown = function () {\r\n if (this.handshakeComplete_) {\r\n this.writeMutations([]);\r\n }\r\n };\r\n PersistentWriteStream.prototype.startRpc = function (token) {\r\n return this.connection.openStream('Write', token);\r\n };\r\n PersistentWriteStream.prototype.onMessage = function (responseProto) {\r\n // Always capture the last stream token.\r\n assert(!!responseProto.streamToken, 'Got a write response without a stream token');\r\n this.lastStreamToken = responseProto.streamToken;\r\n if (!this.handshakeComplete_) {\r\n // The first response is always the handshake response\r\n assert(!responseProto.writeResults || responseProto.writeResults.length === 0, 'Got mutation results for handshake');\r\n this.handshakeComplete_ = true;\r\n return this.listener.onHandshakeComplete();\r\n }\r\n else {\r\n // A successful first write response means the stream is healthy,\r\n // Note, that we could consider a successful handshake healthy, however,\r\n // the write itself might be causing an error we want to back off from.\r\n this.backoff.reset();\r\n var results = this.serializer.fromWriteResults(responseProto.writeResults, responseProto.commitTime);\r\n var commitVersion = this.serializer.fromVersion(responseProto.commitTime);\r\n return this.listener.onMutationResult(commitVersion, results);\r\n }\r\n };\r\n /**\r\n * Sends an initial streamToken to the server, performing the handshake\r\n * required to make the StreamingWrite RPC work. Subsequent\r\n * calls should wait until onHandshakeComplete was called.\r\n */\r\n PersistentWriteStream.prototype.writeHandshake = function () {\r\n assert(this.isOpen(), 'Writing handshake requires an opened stream');\r\n assert(!this.handshakeComplete_, 'Handshake already completed');\r\n // TODO(dimond): Support stream resumption. We intentionally do not set the\r\n // stream token on the handshake, ignoring any stream token we might have.\r\n var request = {};\r\n request.database = this.serializer.encodedDatabaseId;\r\n this.sendRequest(request);\r\n };\r\n /** Sends a group of mutations to the Firestore backend to apply. */\r\n PersistentWriteStream.prototype.writeMutations = function (mutations) {\r\n var _this = this;\r\n assert(this.isOpen(), 'Writing mutations requires an opened stream');\r\n assert(this.handshakeComplete_, 'Handshake must be complete before writing mutations');\r\n assert(this.lastStreamToken.length > 0, 'Trying to write mutation without a token');\r\n var request = {\r\n // Protos are typed with string, but we support UInt8Array on Node\r\n // tslint:disable-next-line:no-any\r\n streamToken: this.lastStreamToken,\r\n writes: mutations.map(function (mutation) { return _this.serializer.toMutation(mutation); })\r\n };\r\n this.sendRequest(request);\r\n };\r\n return PersistentWriteStream;\r\n}(PersistentStream));\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Datastore is a wrapper around the external Google Cloud Datastore grpc API,\r\n * which provides an interface that is more convenient for the rest of the\r\n * client SDK architecture to consume.\r\n */\r\nvar Datastore = /** @class */ (function () {\r\n function Datastore(queue, connection, credentials, serializer) {\r\n this.queue = queue;\r\n this.connection = connection;\r\n this.credentials = credentials;\r\n this.serializer = serializer;\r\n }\r\n Datastore.prototype.newPersistentWriteStream = function (listener) {\r\n return new PersistentWriteStream(this.queue, this.connection, this.credentials, this.serializer, listener);\r\n };\r\n Datastore.prototype.newPersistentWatchStream = function (listener) {\r\n return new PersistentListenStream(this.queue, this.connection, this.credentials, this.serializer, listener);\r\n };\r\n Datastore.prototype.commit = function (mutations) {\r\n var _this = this;\r\n var params = {\r\n database: this.serializer.encodedDatabaseId,\r\n writes: mutations.map(function (m) { return _this.serializer.toMutation(m); })\r\n };\r\n return this.invokeRPC('Commit', params).then(function (response) {\r\n return _this.serializer.fromWriteResults(response.writeResults, response.commitTime);\r\n });\r\n };\r\n Datastore.prototype.lookup = function (keys) {\r\n var _this = this;\r\n var params = {\r\n database: this.serializer.encodedDatabaseId,\r\n documents: keys.map(function (k) { return _this.serializer.toName(k); })\r\n };\r\n return this.invokeStreamingRPC('BatchGetDocuments', params).then(function (response) {\r\n var docs = maybeDocumentMap();\r\n response.forEach(function (proto) {\r\n var doc = _this.serializer.fromMaybeDocument(proto);\r\n docs = docs.insert(doc.key, doc);\r\n });\r\n var result = [];\r\n keys.forEach(function (key) {\r\n var doc = docs.get(key);\r\n assert(!!doc, 'Missing entity in write response for ' + key);\r\n result.push(doc);\r\n });\r\n return result;\r\n });\r\n };\r\n /** Gets an auth token and invokes the provided RPC. */\r\n Datastore.prototype.invokeRPC = function (rpcName, request) {\r\n var _this = this;\r\n return this.credentials\r\n .getToken()\r\n .then(function (token) {\r\n return _this.connection.invokeRPC(rpcName, request, token);\r\n })\r\n .catch(function (error) {\r\n if (error.code === Code.UNAUTHENTICATED) {\r\n _this.credentials.invalidateToken();\r\n }\r\n throw error;\r\n });\r\n };\r\n /** Gets an auth token and invokes the provided RPC with streamed results. */\r\n Datastore.prototype.invokeStreamingRPC = function (rpcName, request) {\r\n var _this = this;\r\n return this.credentials\r\n .getToken()\r\n .then(function (token) {\r\n return _this.connection.invokeStreamingRPC(rpcName, request, token);\r\n })\r\n .catch(function (error) {\r\n if (error.code === Code.UNAUTHENTICATED) {\r\n _this.credentials.invalidateToken();\r\n }\r\n throw error;\r\n });\r\n };\r\n return Datastore;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Internal transaction object responsible for accumulating the mutations to\r\n * perform and the base versions for any documents read.\r\n */\r\nvar Transaction = /** @class */ (function () {\r\n function Transaction(datastore) {\r\n this.datastore = datastore;\r\n // The version of each document that was read during this transaction.\r\n this.readVersions = documentVersionMap();\r\n this.mutations = [];\r\n this.committed = false;\r\n }\r\n Transaction.prototype.recordVersion = function (doc) {\r\n var docVersion;\r\n if (doc instanceof Document) {\r\n docVersion = doc.version;\r\n }\r\n else if (doc instanceof NoDocument) {\r\n // For deleted docs, we must use baseVersion 0 when we overwrite them.\r\n docVersion = SnapshotVersion.forDeletedDoc();\r\n }\r\n else {\r\n throw fail('Document in a transaction was a ' + doc.constructor.name);\r\n }\r\n var existingVersion = this.readVersions.get(doc.key);\r\n if (existingVersion !== null) {\r\n if (!docVersion.isEqual(existingVersion)) {\r\n // This transaction will fail no matter what.\r\n throw new FirestoreError(Code.ABORTED, 'Document version changed between two reads.');\r\n }\r\n }\r\n else {\r\n this.readVersions = this.readVersions.insert(doc.key, docVersion);\r\n }\r\n };\r\n Transaction.prototype.lookup = function (keys) {\r\n var _this = this;\r\n if (this.committed) {\r\n return Promise.reject('Transaction has already completed.');\r\n }\r\n if (this.mutations.length > 0) {\r\n return Promise.reject('Transactions lookups are invalid after writes.');\r\n }\r\n return this.datastore.lookup(keys).then(function (docs) {\r\n docs.forEach(function (doc) {\r\n if (doc instanceof NoDocument || doc instanceof Document) {\r\n _this.recordVersion(doc);\r\n }\r\n else {\r\n fail('Document in a transaction was a ' + doc.constructor.name);\r\n }\r\n });\r\n return docs;\r\n });\r\n };\r\n Transaction.prototype.write = function (mutations) {\r\n if (this.committed) {\r\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'Transaction has already completed.');\r\n }\r\n this.mutations = this.mutations.concat(mutations);\r\n };\r\n /**\r\n * Returns the version of this document when it was read in this transaction,\r\n * as a precondition, or no precondition if it was not read.\r\n */\r\n Transaction.prototype.precondition = function (key) {\r\n var version = this.readVersions.get(key);\r\n if (version) {\r\n return Precondition.updateTime(version);\r\n }\r\n else {\r\n return Precondition.NONE;\r\n }\r\n };\r\n /**\r\n * Returns the precondition for a document if the operation is an update.\r\n */\r\n Transaction.prototype.preconditionForUpdate = function (key) {\r\n var version = this.readVersions.get(key);\r\n if (version && version.isEqual(SnapshotVersion.forDeletedDoc())) {\r\n // The document doesn't exist, so fail the transaction.\r\n throw new FirestoreError(Code.FAILED_PRECONDITION, \"Can't update a document that doesn't exist.\");\r\n }\r\n else if (version) {\r\n // Document exists, base precondition on document update time.\r\n return Precondition.updateTime(version);\r\n }\r\n else {\r\n // Document was not read, so we just use the preconditions for a blind\r\n // update.\r\n return Precondition.exists(true);\r\n }\r\n };\r\n Transaction.prototype.set = function (key, data) {\r\n this.write(data.toMutations(key, this.precondition(key)));\r\n };\r\n Transaction.prototype.update = function (key, data) {\r\n this.write(data.toMutations(key, this.preconditionForUpdate(key)));\r\n };\r\n Transaction.prototype.delete = function (key) {\r\n this.write([new DeleteMutation(key, this.precondition(key))]);\r\n // Since the delete will be applied before all following writes, we need to\r\n // ensure that the precondition for the next write will be exists: false.\r\n this.readVersions = this.readVersions.insert(key, SnapshotVersion.forDeletedDoc());\r\n };\r\n Transaction.prototype.commit = function () {\r\n var _this = this;\r\n var unwritten = this.readVersions;\r\n // For each mutation, note that the doc was written.\r\n this.mutations.forEach(function (mutation) {\r\n unwritten = unwritten.remove(mutation.key);\r\n });\r\n if (!unwritten.isEmpty()) {\r\n return Promise.reject(Error('Every document read in a transaction must also be written.'));\r\n }\r\n return this.datastore.commit(this.mutations).then(function () {\r\n _this.committed = true;\r\n });\r\n };\r\n return Transaction;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Describes the online state of the Firestore client. Note that this does not\r\n * indicate whether or not the remote store is trying to connect or not. This is\r\n * primarily used by the View / EventManager code to change their behavior while\r\n * offline (e.g. get() calls shouldn't wait for data from the server and\r\n * snapshot events should set metadata.isFromCache=true).\r\n */\r\nvar OnlineState;\r\n(function (OnlineState) {\r\n /**\r\n * The Firestore client is in an unknown online state. This means the client\r\n * is either not actively trying to establish a connection or it is currently\r\n * trying to establish a connection, but it has not succeeded or failed yet.\r\n * Higher-level components should not operate in offline mode.\r\n */\r\n OnlineState[OnlineState[\"Unknown\"] = 0] = \"Unknown\";\r\n /**\r\n * The client is connected and the connections are healthy. This state is\r\n * reached after a successful connection and there has been at least one\r\n * successful message received from the backends.\r\n */\r\n OnlineState[OnlineState[\"Online\"] = 1] = \"Online\";\r\n /**\r\n * The client is either trying to establish a connection but failing, or it\r\n * has been explicitly marked offline via a call to disableNetwork().\r\n * Higher-level components should operate in offline mode.\r\n */\r\n OnlineState[OnlineState[\"Offline\"] = 2] = \"Offline\";\r\n})(OnlineState || (OnlineState = {}));\r\n/** The source of an online state event. */\r\nvar OnlineStateSource;\r\n(function (OnlineStateSource) {\r\n OnlineStateSource[OnlineStateSource[\"RemoteStore\"] = 0] = \"RemoteStore\";\r\n OnlineStateSource[OnlineStateSource[\"SharedClientState\"] = 1] = \"SharedClientState\";\r\n})(OnlineStateSource || (OnlineStateSource = {}));\n\n/**\r\n * @license\r\n * Copyright 2018 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar LOG_TAG$7 = 'OnlineStateTracker';\r\n// To deal with transient failures, we allow multiple stream attempts before\r\n// giving up and transitioning from OnlineState.Unknown to Offline.\r\n// TODO(mikelehen): This used to be set to 2 as a mitigation for b/66228394.\r\n// @jdimond thinks that bug is sufficiently fixed so that we can set this back\r\n// to 1. If that works okay, we could potentially remove this logic entirely.\r\nvar MAX_WATCH_STREAM_FAILURES = 1;\r\n// To deal with stream attempts that don't succeed or fail in a timely manner,\r\n// we have a timeout for OnlineState to reach Online or Offline.\r\n// If the timeout is reached, we transition to Offline rather than waiting\r\n// indefinitely.\r\nvar ONLINE_STATE_TIMEOUT_MS = 10 * 1000;\r\n/**\r\n * A component used by the RemoteStore to track the OnlineState (that is,\r\n * whether or not the client as a whole should be considered to be online or\r\n * offline), implementing the appropriate heuristics.\r\n *\r\n * In particular, when the client is trying to connect to the backend, we\r\n * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for\r\n * a connection to succeed. If we have too many failures or the timeout elapses,\r\n * then we set the OnlineState to Offline, and the client will behave as if\r\n * it is offline (get()s will return cached data, etc.).\r\n */\r\nvar OnlineStateTracker = /** @class */ (function () {\r\n function OnlineStateTracker(asyncQueue, onlineStateHandler) {\r\n this.asyncQueue = asyncQueue;\r\n this.onlineStateHandler = onlineStateHandler;\r\n /** The current OnlineState. */\r\n this.state = OnlineState.Unknown;\r\n /**\r\n * A count of consecutive failures to open the stream. If it reaches the\r\n * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to\r\n * Offline.\r\n */\r\n this.watchStreamFailures = 0;\r\n /**\r\n * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we\r\n * transition from OnlineState.Unknown to OnlineState.Offline without waiting\r\n * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times).\r\n */\r\n this.onlineStateTimer = null;\r\n /**\r\n * Whether the client should log a warning message if it fails to connect to\r\n * the backend (initially true, cleared after a successful stream, or if we've\r\n * logged the message already).\r\n */\r\n this.shouldWarnClientIsOffline = true;\r\n }\r\n /**\r\n * Called by RemoteStore when a watch stream is started (including on each\r\n * backoff attempt).\r\n *\r\n * If this is the first attempt, it sets the OnlineState to Unknown and starts\r\n * the onlineStateTimer.\r\n */\r\n OnlineStateTracker.prototype.handleWatchStreamStart = function () {\r\n var _this = this;\r\n if (this.watchStreamFailures === 0) {\r\n this.setAndBroadcast(OnlineState.Unknown);\r\n assert(this.onlineStateTimer === null, \"onlineStateTimer shouldn't be started yet\");\r\n this.onlineStateTimer = this.asyncQueue.enqueueAfterDelay(TimerId.OnlineStateTimeout, ONLINE_STATE_TIMEOUT_MS, function () {\r\n _this.onlineStateTimer = null;\r\n assert(_this.state === OnlineState.Unknown, 'Timer should be canceled if we transitioned to a different state.');\r\n _this.logClientOfflineWarningIfNecessary(\"Backend didn't respond within \" + ONLINE_STATE_TIMEOUT_MS / 1000 + \" \" +\r\n \"seconds.\");\r\n _this.setAndBroadcast(OnlineState.Offline);\r\n // NOTE: handleWatchStreamFailure() will continue to increment\r\n // watchStreamFailures even though we are already marked Offline,\r\n // but this is non-harmful.\r\n return Promise.resolve();\r\n });\r\n }\r\n };\r\n /**\r\n * Updates our OnlineState as appropriate after the watch stream reports a\r\n * failure. The first failure moves us to the 'Unknown' state. We then may\r\n * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we\r\n * actually transition to the 'Offline' state.\r\n */\r\n OnlineStateTracker.prototype.handleWatchStreamFailure = function (error) {\r\n if (this.state === OnlineState.Online) {\r\n this.setAndBroadcast(OnlineState.Unknown);\r\n // To get to OnlineState.Online, set() must have been called which would\r\n // have reset our heuristics.\r\n assert(this.watchStreamFailures === 0, 'watchStreamFailures must be 0');\r\n assert(this.onlineStateTimer === null, 'onlineStateTimer must be null');\r\n }\r\n else {\r\n this.watchStreamFailures++;\r\n if (this.watchStreamFailures >= MAX_WATCH_STREAM_FAILURES) {\r\n this.clearOnlineStateTimer();\r\n this.logClientOfflineWarningIfNecessary(\"Connection failed \" + MAX_WATCH_STREAM_FAILURES + \" \" +\r\n (\"times. Most recent error: \" + error.toString()));\r\n this.setAndBroadcast(OnlineState.Offline);\r\n }\r\n }\r\n };\r\n /**\r\n * Explicitly sets the OnlineState to the specified state.\r\n *\r\n * Note that this resets our timers / failure counters, etc. used by our\r\n * Offline heuristics, so must not be used in place of\r\n * handleWatchStreamStart() and handleWatchStreamFailure().\r\n */\r\n OnlineStateTracker.prototype.set = function (newState) {\r\n this.clearOnlineStateTimer();\r\n this.watchStreamFailures = 0;\r\n if (newState === OnlineState.Online) {\r\n // We've connected to watch at least once. Don't warn the developer\r\n // about being offline going forward.\r\n this.shouldWarnClientIsOffline = false;\r\n }\r\n this.setAndBroadcast(newState);\r\n };\r\n OnlineStateTracker.prototype.setAndBroadcast = function (newState) {\r\n if (newState !== this.state) {\r\n this.state = newState;\r\n this.onlineStateHandler(newState);\r\n }\r\n };\r\n OnlineStateTracker.prototype.logClientOfflineWarningIfNecessary = function (details) {\r\n var message = \"Could not reach Cloud Firestore backend. \" + details + \"\\n\" +\r\n \"This typically indicates that your device does not have a healthy \" +\r\n \"Internet connection at the moment. The client will operate in offline \" +\r\n \"mode until it is able to successfully connect to the backend.\";\r\n if (this.shouldWarnClientIsOffline) {\r\n error(message);\r\n this.shouldWarnClientIsOffline = false;\r\n }\r\n else {\r\n debug(LOG_TAG$7, message);\r\n }\r\n };\r\n OnlineStateTracker.prototype.clearOnlineStateTimer = function () {\r\n if (this.onlineStateTimer !== null) {\r\n this.onlineStateTimer.cancel();\r\n this.onlineStateTimer = null;\r\n }\r\n };\r\n return OnlineStateTracker;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar LOG_TAG$8 = 'RemoteStore';\r\n// TODO(b/35853402): Negotiate this with the stream.\r\nvar MAX_PENDING_WRITES = 10;\r\n/**\r\n * RemoteStore - An interface to remotely stored data, basically providing a\r\n * wrapper around the Datastore that is more reliable for the rest of the\r\n * system.\r\n *\r\n * RemoteStore is responsible for maintaining the connection to the server.\r\n * - maintaining a list of active listens.\r\n * - reconnecting when the connection is dropped.\r\n * - resuming all the active listens on reconnect.\r\n *\r\n * RemoteStore handles all incoming events from the Datastore.\r\n * - listening to the watch stream and repackaging the events as RemoteEvents\r\n * - notifying SyncEngine of any changes to the active listens.\r\n *\r\n * RemoteStore takes writes from other components and handles them reliably.\r\n * - pulling pending mutations from LocalStore and sending them to Datastore.\r\n * - retrying mutations that failed because of network problems.\r\n * - acking mutations to the SyncEngine once they are accepted or rejected.\r\n */\r\nvar RemoteStore = /** @class */ (function () {\r\n function RemoteStore(\r\n /**\r\n * The local store, used to fill the write pipeline with outbound mutations.\r\n */\r\n localStore, \r\n /** The client-side proxy for interacting with the backend. */\r\n datastore, asyncQueue, onlineStateHandler) {\r\n this.localStore = localStore;\r\n this.datastore = datastore;\r\n /**\r\n * A list of up to MAX_PENDING_WRITES writes that we have fetched from the\r\n * LocalStore via fillWritePipeline() and have or will send to the write\r\n * stream.\r\n *\r\n * Whenever writePipeline.length > 0 the RemoteStore will attempt to start or\r\n * restart the write stream. When the stream is established the writes in the\r\n * pipeline will be sent in order.\r\n *\r\n * Writes remain in writePipeline until they are acknowledged by the backend\r\n * and thus will automatically be re-sent if the stream is interrupted /\r\n * restarted before they're acknowledged.\r\n *\r\n * Write responses from the backend are linked to their originating request\r\n * purely based on order, and so we can just shift() writes from the front of\r\n * the writePipeline as we receive responses.\r\n */\r\n this.writePipeline = [];\r\n /**\r\n * A mapping of watched targets that the client cares about tracking and the\r\n * user has explicitly called a 'listen' for this target.\r\n *\r\n * These targets may or may not have been sent to or acknowledged by the\r\n * server. On re-establishing the listen stream, these targets should be sent\r\n * to the server. The targets removed with unlistens are removed eagerly\r\n * without waiting for confirmation from the listen stream.\r\n */\r\n this.listenTargets = {};\r\n this.watchChangeAggregator = null;\r\n /**\r\n * Set to true by enableNetwork() and false by disableNetwork() and indicates\r\n * the user-preferred network state.\r\n */\r\n this.networkEnabled = false;\r\n this.isPrimary = false;\r\n this.onlineStateTracker = new OnlineStateTracker(asyncQueue, onlineStateHandler);\r\n // Create streams (but note they're not started yet).\r\n this.watchStream = this.datastore.newPersistentWatchStream({\r\n onOpen: this.onWatchStreamOpen.bind(this),\r\n onClose: this.onWatchStreamClose.bind(this),\r\n onWatchChange: this.onWatchStreamChange.bind(this)\r\n });\r\n this.writeStream = this.datastore.newPersistentWriteStream({\r\n onOpen: this.onWriteStreamOpen.bind(this),\r\n onClose: this.onWriteStreamClose.bind(this),\r\n onHandshakeComplete: this.onWriteHandshakeComplete.bind(this),\r\n onMutationResult: this.onMutationResult.bind(this)\r\n });\r\n }\r\n /**\r\n * Starts up the remote store, creating streams, restoring state from\r\n * LocalStore, etc.\r\n */\r\n RemoteStore.prototype.start = function () {\r\n return this.enableNetwork();\r\n };\r\n /** Re-enables the network. Idempotent. */\r\n RemoteStore.prototype.enableNetwork = function () {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n var _a;\r\n return tslib_1.__generator(this, function (_b) {\r\n switch (_b.label) {\r\n case 0:\r\n this.networkEnabled = true;\r\n if (!this.canUseNetwork()) return [3 /*break*/, 3];\r\n _a = this.writeStream;\r\n return [4 /*yield*/, this.localStore.getLastStreamToken()];\r\n case 1:\r\n _a.lastStreamToken = _b.sent();\r\n if (this.shouldStartWatchStream()) {\r\n this.startWatchStream();\r\n }\r\n else {\r\n this.onlineStateTracker.set(OnlineState.Unknown);\r\n }\r\n // This will start the write stream if necessary.\r\n return [4 /*yield*/, this.fillWritePipeline()];\r\n case 2:\r\n // This will start the write stream if necessary.\r\n _b.sent();\r\n _b.label = 3;\r\n case 3: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * Temporarily disables the network. The network can be re-enabled using\r\n * enableNetwork().\r\n */\r\n RemoteStore.prototype.disableNetwork = function () {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n this.networkEnabled = false;\r\n return [4 /*yield*/, this.disableNetworkInternal()];\r\n case 1:\r\n _a.sent();\r\n // Set the OnlineState to Offline so get()s return from cache, etc.\r\n this.onlineStateTracker.set(OnlineState.Offline);\r\n return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n RemoteStore.prototype.disableNetworkInternal = function () {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, this.writeStream.stop()];\r\n case 1:\r\n _a.sent();\r\n return [4 /*yield*/, this.watchStream.stop()];\r\n case 2:\r\n _a.sent();\r\n if (this.writePipeline.length > 0) {\r\n debug(LOG_TAG$8, \"Stopping write stream with \" + this.writePipeline.length + \" pending writes\");\r\n this.writePipeline = [];\r\n }\r\n this.cleanUpWatchStreamState();\r\n return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n RemoteStore.prototype.shutdown = function () {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n debug(LOG_TAG$8, 'RemoteStore shutting down.');\r\n this.networkEnabled = false;\r\n return [4 /*yield*/, this.disableNetworkInternal()];\r\n case 1:\r\n _a.sent();\r\n // Set the OnlineState to Unknown (rather than Offline) to avoid potentially\r\n // triggering spurious listener events with cached data, etc.\r\n this.onlineStateTracker.set(OnlineState.Unknown);\r\n return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n /** Starts new listen for the given query. Uses resume token if provided */\r\n RemoteStore.prototype.listen = function (queryData) {\r\n assert(!contains(this.listenTargets, queryData.targetId), 'listen called with duplicate targetId!');\r\n // Mark this as something the client is currently listening for.\r\n this.listenTargets[queryData.targetId] = queryData;\r\n if (this.shouldStartWatchStream()) {\r\n // The listen will be sent in onWatchStreamOpen\r\n this.startWatchStream();\r\n }\r\n else if (this.watchStream.isOpen()) {\r\n this.sendWatchRequest(queryData);\r\n }\r\n };\r\n /** Removes the listen from server */\r\n RemoteStore.prototype.unlisten = function (targetId) {\r\n assert(contains(this.listenTargets, targetId), 'unlisten called without assigned target ID!');\r\n delete this.listenTargets[targetId];\r\n if (this.watchStream.isOpen()) {\r\n this.sendUnwatchRequest(targetId);\r\n }\r\n if (isEmpty(this.listenTargets)) {\r\n if (this.watchStream.isOpen()) {\r\n this.watchStream.markIdle();\r\n }\r\n else if (this.canUseNetwork()) {\r\n // Revert to OnlineState.Unknown if the watch stream is not open and we\r\n // have no listeners, since without any listens to send we cannot\r\n // confirm if the stream is healthy and upgrade to OnlineState.Online.\r\n this.onlineStateTracker.set(OnlineState.Unknown);\r\n }\r\n }\r\n };\r\n /** {@link TargetMetadataProvider.getQueryDataForTarget} */\r\n RemoteStore.prototype.getQueryDataForTarget = function (targetId) {\r\n return this.listenTargets[targetId] || null;\r\n };\r\n /** {@link TargetMetadataProvider.getRemoteKeysForTarget} */\r\n RemoteStore.prototype.getRemoteKeysForTarget = function (targetId) {\r\n return this.syncEngine.getRemoteKeysForTarget(targetId);\r\n };\r\n /**\r\n * We need to increment the the expected number of pending responses we're due\r\n * from watch so we wait for the ack to process any messages from this target.\r\n */\r\n RemoteStore.prototype.sendWatchRequest = function (queryData) {\r\n this.watchChangeAggregator.recordPendingTargetRequest(queryData.targetId);\r\n this.watchStream.watch(queryData);\r\n };\r\n /**\r\n * We need to increment the expected number of pending responses we're due\r\n * from watch so we wait for the removal on the server before we process any\r\n * messages from this target.\r\n */\r\n RemoteStore.prototype.sendUnwatchRequest = function (targetId) {\r\n this.watchChangeAggregator.recordPendingTargetRequest(targetId);\r\n this.watchStream.unwatch(targetId);\r\n };\r\n RemoteStore.prototype.startWatchStream = function () {\r\n assert(this.shouldStartWatchStream(), 'startWatchStream() called when shouldStartWatchStream() is false.');\r\n this.watchChangeAggregator = new WatchChangeAggregator(this);\r\n this.watchStream.start();\r\n this.onlineStateTracker.handleWatchStreamStart();\r\n };\r\n /**\r\n * Returns whether the watch stream should be started because it's necessary\r\n * and has not yet been started.\r\n */\r\n RemoteStore.prototype.shouldStartWatchStream = function () {\r\n return (this.canUseNetwork() &&\r\n !this.watchStream.isStarted() &&\r\n !isEmpty(this.listenTargets));\r\n };\r\n RemoteStore.prototype.canUseNetwork = function () {\r\n return this.isPrimary && this.networkEnabled;\r\n };\r\n RemoteStore.prototype.cleanUpWatchStreamState = function () {\r\n this.watchChangeAggregator = null;\r\n };\r\n RemoteStore.prototype.onWatchStreamOpen = function () {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n var _this = this;\r\n return tslib_1.__generator(this, function (_a) {\r\n forEachNumber(this.listenTargets, function (targetId, queryData) {\r\n _this.sendWatchRequest(queryData);\r\n });\r\n return [2 /*return*/];\r\n });\r\n });\r\n };\r\n RemoteStore.prototype.onWatchStreamClose = function (error) {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n return tslib_1.__generator(this, function (_a) {\r\n if (error === undefined) {\r\n // Graceful stop (due to stop() or idle timeout). Make sure that's\r\n // desirable.\r\n assert(!this.shouldStartWatchStream(), 'Watch stream was stopped gracefully while still needed.');\r\n }\r\n this.cleanUpWatchStreamState();\r\n // If we still need the watch stream, retry the connection.\r\n if (this.shouldStartWatchStream()) {\r\n this.onlineStateTracker.handleWatchStreamFailure(error);\r\n this.startWatchStream();\r\n }\r\n else {\r\n // No need to restart watch stream because there are no active targets.\r\n // The online state is set to unknown because there is no active attempt\r\n // at establishing a connection\r\n this.onlineStateTracker.set(OnlineState.Unknown);\r\n }\r\n return [2 /*return*/];\r\n });\r\n });\r\n };\r\n RemoteStore.prototype.onWatchStreamChange = function (watchChange, snapshotVersion) {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n var lastRemoteSnapshotVersion;\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n // Mark the client as online since we got a message from the server\r\n this.onlineStateTracker.set(OnlineState.Online);\r\n if (watchChange instanceof WatchTargetChange &&\r\n watchChange.state === WatchTargetChangeState.Removed &&\r\n watchChange.cause) {\r\n // There was an error on a target, don't wait for a consistent snapshot\r\n // to raise events\r\n return [2 /*return*/, this.handleTargetError(watchChange)];\r\n }\r\n if (watchChange instanceof DocumentWatchChange) {\r\n this.watchChangeAggregator.handleDocumentChange(watchChange);\r\n }\r\n else if (watchChange instanceof ExistenceFilterChange) {\r\n this.watchChangeAggregator.handleExistenceFilter(watchChange);\r\n }\r\n else {\r\n assert(watchChange instanceof WatchTargetChange, 'Expected watchChange to be an instance of WatchTargetChange');\r\n this.watchChangeAggregator.handleTargetChange(watchChange);\r\n }\r\n if (!!snapshotVersion.isEqual(SnapshotVersion.MIN)) return [3 /*break*/, 3];\r\n return [4 /*yield*/, this.localStore.getLastRemoteSnapshotVersion()];\r\n case 1:\r\n lastRemoteSnapshotVersion = _a.sent();\r\n if (!(snapshotVersion.compareTo(lastRemoteSnapshotVersion) >= 0)) return [3 /*break*/, 3];\r\n // We have received a target change with a global snapshot if the snapshot\r\n // version is not equal to SnapshotVersion.MIN.\r\n return [4 /*yield*/, this.raiseWatchSnapshot(snapshotVersion)];\r\n case 2:\r\n // We have received a target change with a global snapshot if the snapshot\r\n // version is not equal to SnapshotVersion.MIN.\r\n _a.sent();\r\n _a.label = 3;\r\n case 3: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * Takes a batch of changes from the Datastore, repackages them as a\r\n * RemoteEvent, and passes that on to the listener, which is typically the\r\n * SyncEngine.\r\n */\r\n RemoteStore.prototype.raiseWatchSnapshot = function (snapshotVersion) {\r\n var _this = this;\r\n assert(!snapshotVersion.isEqual(SnapshotVersion.MIN), \"Can't raise event for unknown SnapshotVersion\");\r\n var remoteEvent = this.watchChangeAggregator.createRemoteEvent(snapshotVersion);\r\n // Update in-memory resume tokens. LocalStore will update the\r\n // persistent view of these when applying the completed RemoteEvent.\r\n forEachNumber(remoteEvent.targetChanges, function (targetId, change) {\r\n if (change.resumeToken.length > 0) {\r\n var queryData = _this.listenTargets[targetId];\r\n // A watched target might have been removed already.\r\n if (queryData) {\r\n _this.listenTargets[targetId] = queryData.copy({\r\n resumeToken: change.resumeToken,\r\n snapshotVersion: snapshotVersion\r\n });\r\n }\r\n }\r\n });\r\n // Re-establish listens for the targets that have been invalidated by\r\n // existence filter mismatches.\r\n remoteEvent.targetMismatches.forEach(function (targetId) {\r\n var queryData = _this.listenTargets[targetId];\r\n if (!queryData) {\r\n // A watched target might have been removed already.\r\n return;\r\n }\r\n // Clear the resume token for the query, since we're in a known mismatch\r\n // state.\r\n _this.listenTargets[targetId] = queryData.copy({\r\n resumeToken: emptyByteString()\r\n });\r\n // Cause a hard reset by unwatching and rewatching immediately, but\r\n // deliberately don't send a resume token so that we get a full update.\r\n _this.sendUnwatchRequest(targetId);\r\n // Mark the query we send as being on behalf of an existence filter\r\n // mismatch, but don't actually retain that in listenTargets. This ensures\r\n // that we flag the first re-listen this way without impacting future\r\n // listens of this target (that might happen e.g. on reconnect).\r\n var requestQueryData = new QueryData(queryData.query, targetId, QueryPurpose.ExistenceFilterMismatch, queryData.sequenceNumber);\r\n _this.sendWatchRequest(requestQueryData);\r\n });\r\n // Finally raise remote event\r\n return this.syncEngine.applyRemoteEvent(remoteEvent);\r\n };\r\n /** Handles an error on a target */\r\n RemoteStore.prototype.handleTargetError = function (watchChange) {\r\n var _this = this;\r\n assert(!!watchChange.cause, 'Handling target error without a cause');\r\n var error = watchChange.cause;\r\n var promiseChain = Promise.resolve();\r\n watchChange.targetIds.forEach(function (targetId) {\r\n promiseChain = promiseChain.then(function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {\r\n return tslib_1.__generator(this, function (_a) {\r\n // A watched target might have been removed already.\r\n if (contains(this.listenTargets, targetId)) {\r\n delete this.listenTargets[targetId];\r\n this.watchChangeAggregator.removeTarget(targetId);\r\n return [2 /*return*/, this.syncEngine.rejectListen(targetId, error)];\r\n }\r\n return [2 /*return*/];\r\n });\r\n }); });\r\n });\r\n return promiseChain;\r\n };\r\n /**\r\n * Attempts to fill our write pipeline with writes from the LocalStore.\r\n *\r\n * Called internally to bootstrap or refill the write pipeline and by\r\n * SyncEngine whenever there are new mutations to process.\r\n *\r\n * Starts the write stream if necessary.\r\n */\r\n RemoteStore.prototype.fillWritePipeline = function () {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n var lastBatchIdRetrieved, batch;\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (!this.canAddToWritePipeline()) return [3 /*break*/, 4];\r\n lastBatchIdRetrieved = this.writePipeline.length > 0\r\n ? this.writePipeline[this.writePipeline.length - 1].batchId\r\n : BATCHID_UNKNOWN;\r\n return [4 /*yield*/, this.localStore.nextMutationBatch(lastBatchIdRetrieved)];\r\n case 1:\r\n batch = _a.sent();\r\n if (!(batch === null)) return [3 /*break*/, 2];\r\n if (this.writePipeline.length === 0) {\r\n this.writeStream.markIdle();\r\n }\r\n return [3 /*break*/, 4];\r\n case 2:\r\n this.addToWritePipeline(batch);\r\n return [4 /*yield*/, this.fillWritePipeline()];\r\n case 3:\r\n _a.sent();\r\n _a.label = 4;\r\n case 4:\r\n if (this.shouldStartWriteStream()) {\r\n this.startWriteStream();\r\n }\r\n return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * Returns true if we can add to the write pipeline (i.e. the network is\r\n * enabled and the write pipeline is not full).\r\n */\r\n RemoteStore.prototype.canAddToWritePipeline = function () {\r\n return (this.canUseNetwork() && this.writePipeline.length < MAX_PENDING_WRITES);\r\n };\r\n // For testing\r\n RemoteStore.prototype.outstandingWrites = function () {\r\n return this.writePipeline.length;\r\n };\r\n /**\r\n * Queues additional writes to be sent to the write stream, sending them\r\n * immediately if the write stream is established.\r\n */\r\n RemoteStore.prototype.addToWritePipeline = function (batch) {\r\n assert(this.canAddToWritePipeline(), 'addToWritePipeline called when pipeline is full');\r\n this.writePipeline.push(batch);\r\n if (this.writeStream.isOpen() && this.writeStream.handshakeComplete) {\r\n this.writeStream.writeMutations(batch.mutations);\r\n }\r\n };\r\n RemoteStore.prototype.shouldStartWriteStream = function () {\r\n return (this.canUseNetwork() &&\r\n !this.writeStream.isStarted() &&\r\n this.writePipeline.length > 0);\r\n };\r\n RemoteStore.prototype.startWriteStream = function () {\r\n assert(this.shouldStartWriteStream(), 'startWriteStream() called when shouldStartWriteStream() is false.');\r\n this.writeStream.start();\r\n };\r\n RemoteStore.prototype.onWriteStreamOpen = function () {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n return tslib_1.__generator(this, function (_a) {\r\n this.writeStream.writeHandshake();\r\n return [2 /*return*/];\r\n });\r\n });\r\n };\r\n RemoteStore.prototype.onWriteHandshakeComplete = function () {\r\n var _this = this;\r\n // Record the stream token.\r\n return this.localStore\r\n .setLastStreamToken(this.writeStream.lastStreamToken)\r\n .then(function () {\r\n // Send the write pipeline now that the stream is established.\r\n for (var _i = 0, _a = _this.writePipeline; _i < _a.length; _i++) {\r\n var batch = _a[_i];\r\n _this.writeStream.writeMutations(batch.mutations);\r\n }\r\n })\r\n .catch(ignoreIfPrimaryLeaseLoss);\r\n };\r\n RemoteStore.prototype.onMutationResult = function (commitVersion, results) {\r\n var _this = this;\r\n // This is a response to a write containing mutations and should be\r\n // correlated to the first write in our write pipeline.\r\n assert(this.writePipeline.length > 0, 'Got result for empty write pipeline');\r\n var batch = this.writePipeline.shift();\r\n var success = MutationBatchResult.from(batch, commitVersion, results, this.writeStream.lastStreamToken);\r\n return this.syncEngine.applySuccessfulWrite(success).then(function () {\r\n // It's possible that with the completion of this mutation another\r\n // slot has freed up.\r\n return _this.fillWritePipeline();\r\n });\r\n };\r\n RemoteStore.prototype.onWriteStreamClose = function (error) {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n var errorHandling;\r\n var _this = this;\r\n return tslib_1.__generator(this, function (_a) {\r\n if (error === undefined) {\r\n // Graceful stop (due to stop() or idle timeout). Make sure that's\r\n // desirable.\r\n assert(!this.shouldStartWriteStream(), 'Write stream was stopped gracefully while still needed.');\r\n }\r\n // If the write stream closed due to an error, invoke the error callbacks if\r\n // there are pending writes.\r\n if (error && this.writePipeline.length > 0) {\r\n errorHandling = void 0;\r\n if (this.writeStream.handshakeComplete) {\r\n // This error affects the actual write.\r\n errorHandling = this.handleWriteError(error);\r\n }\r\n else {\r\n // If there was an error before the handshake has finished, it's\r\n // possible that the server is unable to process the stream token\r\n // we're sending. (Perhaps it's too old?)\r\n errorHandling = this.handleHandshakeError(error);\r\n }\r\n return [2 /*return*/, errorHandling.then(function () {\r\n // The write stream might have been started by refilling the write\r\n // pipeline for failed writes\r\n if (_this.shouldStartWriteStream()) {\r\n _this.startWriteStream();\r\n }\r\n })];\r\n }\r\n return [2 /*return*/];\r\n });\r\n });\r\n };\r\n RemoteStore.prototype.handleHandshakeError = function (error) {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n return tslib_1.__generator(this, function (_a) {\r\n // Reset the token if it's a permanent error, signaling the write stream is\r\n // no longer valid. Note that the handshake does not count as a write: see\r\n // comments on isPermanentWriteError for details.\r\n if (isPermanentError(error.code)) {\r\n debug(LOG_TAG$8, 'RemoteStore error before completed handshake; resetting stream token: ', this.writeStream.lastStreamToken);\r\n this.writeStream.lastStreamToken = emptyByteString();\r\n return [2 /*return*/, this.localStore\r\n .setLastStreamToken(emptyByteString())\r\n .catch(ignoreIfPrimaryLeaseLoss)];\r\n }\r\n return [2 /*return*/];\r\n });\r\n });\r\n };\r\n RemoteStore.prototype.handleWriteError = function (error) {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n var batch;\r\n var _this = this;\r\n return tslib_1.__generator(this, function (_a) {\r\n // Only handle permanent errors here. If it's transient, just let the retry\r\n // logic kick in.\r\n if (isPermanentWriteError(error.code)) {\r\n batch = this.writePipeline.shift();\r\n // In this case it's also unlikely that the server itself is melting\r\n // down -- this was just a bad request so inhibit backoff on the next\r\n // restart.\r\n this.writeStream.inhibitBackoff();\r\n return [2 /*return*/, this.syncEngine\r\n .rejectFailedWrite(batch.batchId, error)\r\n .then(function () {\r\n // It's possible that with the completion of this mutation\r\n // another slot has freed up.\r\n return _this.fillWritePipeline();\r\n })];\r\n }\r\n return [2 /*return*/];\r\n });\r\n });\r\n };\r\n RemoteStore.prototype.createTransaction = function () {\r\n return new Transaction(this.datastore);\r\n };\r\n RemoteStore.prototype.handleCredentialChange = function () {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (!this.canUseNetwork()) return [3 /*break*/, 3];\r\n // Tear down and re-create our network streams. This will ensure we get a fresh auth token\r\n // for the new user and re-fill the write pipeline with new mutations from the LocalStore\r\n // (since mutations are per-user).\r\n debug(LOG_TAG$8, 'RemoteStore restarting streams for new credential');\r\n this.networkEnabled = false;\r\n return [4 /*yield*/, this.disableNetworkInternal()];\r\n case 1:\r\n _a.sent();\r\n this.onlineStateTracker.set(OnlineState.Unknown);\r\n return [4 /*yield*/, this.enableNetwork()];\r\n case 2:\r\n _a.sent();\r\n _a.label = 3;\r\n case 3: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * Toggles the network state when the client gains or loses its primary lease.\r\n */\r\n RemoteStore.prototype.applyPrimaryState = function (isPrimary) {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n this.isPrimary = isPrimary;\r\n if (!(isPrimary && this.networkEnabled)) return [3 /*break*/, 2];\r\n return [4 /*yield*/, this.enableNetwork()];\r\n case 1:\r\n _a.sent();\r\n return [3 /*break*/, 4];\r\n case 2:\r\n if (!!isPrimary) return [3 /*break*/, 4];\r\n return [4 /*yield*/, this.disableNetworkInternal()];\r\n case 3:\r\n _a.sent();\r\n this.onlineStateTracker.set(OnlineState.Unknown);\r\n _a.label = 4;\r\n case 4: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n return RemoteStore;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Holds the listeners and the last received ViewSnapshot for a query being\r\n * tracked by EventManager.\r\n */\r\nvar QueryListenersInfo = /** @class */ (function () {\r\n function QueryListenersInfo() {\r\n this.listeners = [];\r\n }\r\n return QueryListenersInfo;\r\n}());\r\n/**\r\n * EventManager is responsible for mapping queries to query event emitters.\r\n * It handles \"fan-out\". -- Identical queries will re-use the same watch on the\r\n * backend.\r\n */\r\nvar EventManager = /** @class */ (function () {\r\n function EventManager(syncEngine) {\r\n this.syncEngine = syncEngine;\r\n this.queries = new ObjectMap(function (q) {\r\n return q.canonicalId();\r\n });\r\n this.onlineState = OnlineState.Unknown;\r\n this.syncEngine.subscribe(this);\r\n }\r\n EventManager.prototype.listen = function (listener) {\r\n var query = listener.query;\r\n var firstListen = false;\r\n var queryInfo = this.queries.get(query);\r\n if (!queryInfo) {\r\n firstListen = true;\r\n queryInfo = new QueryListenersInfo();\r\n this.queries.set(query, queryInfo);\r\n }\r\n queryInfo.listeners.push(listener);\r\n listener.applyOnlineStateChange(this.onlineState);\r\n if (queryInfo.viewSnap)\r\n listener.onViewSnapshot(queryInfo.viewSnap);\r\n if (firstListen) {\r\n return this.syncEngine.listen(query).then(function (targetId) {\r\n queryInfo.targetId = targetId;\r\n return targetId;\r\n });\r\n }\r\n else {\r\n return Promise.resolve(queryInfo.targetId);\r\n }\r\n };\r\n EventManager.prototype.unlisten = function (listener) {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n var query, lastListen, queryInfo, i;\r\n return tslib_1.__generator(this, function (_a) {\r\n query = listener.query;\r\n lastListen = false;\r\n queryInfo = this.queries.get(query);\r\n if (queryInfo) {\r\n i = queryInfo.listeners.indexOf(listener);\r\n if (i >= 0) {\r\n queryInfo.listeners.splice(i, 1);\r\n lastListen = queryInfo.listeners.length === 0;\r\n }\r\n }\r\n if (lastListen) {\r\n this.queries.delete(query);\r\n return [2 /*return*/, this.syncEngine.unlisten(query)];\r\n }\r\n return [2 /*return*/];\r\n });\r\n });\r\n };\r\n EventManager.prototype.onWatchChange = function (viewSnaps) {\r\n for (var _i = 0, viewSnaps_1 = viewSnaps; _i < viewSnaps_1.length; _i++) {\r\n var viewSnap = viewSnaps_1[_i];\r\n var query = viewSnap.query;\r\n var queryInfo = this.queries.get(query);\r\n if (queryInfo) {\r\n for (var _a = 0, _b = queryInfo.listeners; _a < _b.length; _a++) {\r\n var listener = _b[_a];\r\n listener.onViewSnapshot(viewSnap);\r\n }\r\n queryInfo.viewSnap = viewSnap;\r\n }\r\n }\r\n };\r\n EventManager.prototype.onWatchError = function (query, error) {\r\n var queryInfo = this.queries.get(query);\r\n if (queryInfo) {\r\n for (var _i = 0, _a = queryInfo.listeners; _i < _a.length; _i++) {\r\n var listener = _a[_i];\r\n listener.onError(error);\r\n }\r\n }\r\n // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()\r\n // after an error.\r\n this.queries.delete(query);\r\n };\r\n EventManager.prototype.onOnlineStateChange = function (onlineState) {\r\n this.onlineState = onlineState;\r\n this.queries.forEach(function (_, queryInfo) {\r\n for (var _i = 0, _a = queryInfo.listeners; _i < _a.length; _i++) {\r\n var listener = _a[_i];\r\n listener.applyOnlineStateChange(onlineState);\r\n }\r\n });\r\n };\r\n return EventManager;\r\n}());\r\n/**\r\n * QueryListener takes a series of internal view snapshots and determines\r\n * when to raise the event.\r\n *\r\n * It uses an Observer to dispatch events.\r\n */\r\nvar QueryListener = /** @class */ (function () {\r\n function QueryListener(query, queryObserver, options) {\r\n this.query = query;\r\n this.queryObserver = queryObserver;\r\n /**\r\n * Initial snapshots (e.g. from cache) may not be propagated to the wrapped\r\n * observer. This flag is set to true once we've actually raised an event.\r\n */\r\n this.raisedInitialEvent = false;\r\n this.onlineState = OnlineState.Unknown;\r\n this.options = options || {};\r\n }\r\n QueryListener.prototype.onViewSnapshot = function (snap) {\r\n assert(snap.docChanges.length > 0 || snap.syncStateChanged, 'We got a new snapshot with no changes?');\r\n if (!this.options.includeMetadataChanges) {\r\n // Remove the metadata only changes.\r\n var docChanges = [];\r\n for (var _i = 0, _a = snap.docChanges; _i < _a.length; _i++) {\r\n var docChange = _a[_i];\r\n if (docChange.type !== ChangeType.Metadata) {\r\n docChanges.push(docChange);\r\n }\r\n }\r\n snap = new ViewSnapshot(snap.query, snap.docs, snap.oldDocs, docChanges, snap.mutatedKeys, snap.fromCache, snap.syncStateChanged, \r\n /* excludesMetadataChanges= */ true);\r\n }\r\n if (!this.raisedInitialEvent) {\r\n if (this.shouldRaiseInitialEvent(snap, this.onlineState)) {\r\n this.raiseInitialEvent(snap);\r\n }\r\n }\r\n else if (this.shouldRaiseEvent(snap)) {\r\n this.queryObserver.next(snap);\r\n }\r\n this.snap = snap;\r\n };\r\n QueryListener.prototype.onError = function (error) {\r\n this.queryObserver.error(error);\r\n };\r\n QueryListener.prototype.applyOnlineStateChange = function (onlineState) {\r\n this.onlineState = onlineState;\r\n if (this.snap &&\r\n !this.raisedInitialEvent &&\r\n this.shouldRaiseInitialEvent(this.snap, onlineState)) {\r\n this.raiseInitialEvent(this.snap);\r\n }\r\n };\r\n QueryListener.prototype.shouldRaiseInitialEvent = function (snap, onlineState) {\r\n assert(!this.raisedInitialEvent, 'Determining whether to raise first event but already had first event');\r\n // Always raise the first event when we're synced\r\n if (!snap.fromCache) {\r\n return true;\r\n }\r\n // NOTE: We consider OnlineState.Unknown as online (it should become Offline\r\n // or Online if we wait long enough).\r\n var maybeOnline = onlineState !== OnlineState.Offline;\r\n // Don't raise the event if we're online, aren't synced yet (checked\r\n // above) and are waiting for a sync.\r\n if (this.options.waitForSyncWhenOnline && maybeOnline) {\r\n assert(snap.fromCache, 'Waiting for sync, but snapshot is not from cache');\r\n return false;\r\n }\r\n // Raise data from cache if we have any documents or we are offline\r\n return !snap.docs.isEmpty() || onlineState === OnlineState.Offline;\r\n };\r\n QueryListener.prototype.shouldRaiseEvent = function (snap) {\r\n // We don't need to handle includeDocumentMetadataChanges here because\r\n // the Metadata only changes have already been stripped out if needed.\r\n // At this point the only changes we will see are the ones we should\r\n // propagate.\r\n if (snap.docChanges.length > 0) {\r\n return true;\r\n }\r\n var hasPendingWritesChanged = this.snap && this.snap.hasPendingWrites !== snap.hasPendingWrites;\r\n if (snap.syncStateChanged || hasPendingWritesChanged) {\r\n return this.options.includeMetadataChanges === true;\r\n }\r\n // Generally we should have hit one of the cases above, but it's possible\r\n // to get here if there were only metadata docChanges and they got\r\n // stripped out.\r\n return false;\r\n };\r\n QueryListener.prototype.raiseInitialEvent = function (snap) {\r\n assert(!this.raisedInitialEvent, 'Trying to raise initial events for second time');\r\n snap = ViewSnapshot.fromInitialDocuments(snap.query, snap.docs, snap.mutatedKeys, snap.fromCache);\r\n this.raisedInitialEvent = true;\r\n this.queryObserver.next(snap);\r\n };\r\n return QueryListener;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A set of changes to what documents are currently in view and out of view for\r\n * a given query. These changes are sent to the LocalStore by the View (via\r\n * the SyncEngine) and are used to pin / unpin documents as appropriate.\r\n */\r\nvar LocalViewChanges = /** @class */ (function () {\r\n function LocalViewChanges(targetId, addedKeys, removedKeys) {\r\n this.targetId = targetId;\r\n this.addedKeys = addedKeys;\r\n this.removedKeys = removedKeys;\r\n }\r\n LocalViewChanges.fromSnapshot = function (targetId, viewSnapshot) {\r\n var addedKeys = documentKeySet();\r\n var removedKeys = documentKeySet();\r\n for (var _i = 0, _a = viewSnapshot.docChanges; _i < _a.length; _i++) {\r\n var docChange = _a[_i];\r\n switch (docChange.type) {\r\n case ChangeType.Added:\r\n addedKeys = addedKeys.add(docChange.doc.key);\r\n break;\r\n case ChangeType.Removed:\r\n removedKeys = removedKeys.add(docChange.doc.key);\r\n break;\r\n default:\r\n // do nothing\r\n }\r\n }\r\n return new LocalViewChanges(targetId, addedKeys, removedKeys);\r\n };\r\n return LocalViewChanges;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar AddedLimboDocument = /** @class */ (function () {\r\n function AddedLimboDocument(key) {\r\n this.key = key;\r\n }\r\n return AddedLimboDocument;\r\n}());\r\nvar RemovedLimboDocument = /** @class */ (function () {\r\n function RemovedLimboDocument(key) {\r\n this.key = key;\r\n }\r\n return RemovedLimboDocument;\r\n}());\r\n/**\r\n * View is responsible for computing the final merged truth of what docs are in\r\n * a query. It gets notified of local and remote changes to docs, and applies\r\n * the query filters and limits to determine the most correct possible results.\r\n */\r\nvar View = /** @class */ (function () {\r\n function View(query, \r\n /** Documents included in the remote target */\r\n _syncedDocuments) {\r\n this.query = query;\r\n this._syncedDocuments = _syncedDocuments;\r\n this.syncState = null;\r\n /**\r\n * A flag whether the view is current with the backend. A view is considered\r\n * current after it has seen the current flag from the backend and did not\r\n * lose consistency within the watch stream (e.g. because of an existence\r\n * filter mismatch).\r\n */\r\n this.current = false;\r\n /** Documents in the view but not in the remote target */\r\n this.limboDocuments = documentKeySet();\r\n /** Document Keys that have local changes */\r\n this.mutatedKeys = documentKeySet();\r\n this.documentSet = new DocumentSet(query.docComparator.bind(query));\r\n }\r\n Object.defineProperty(View.prototype, \"syncedDocuments\", {\r\n /**\r\n * The set of remote documents that the server has told us belongs to the target associated with\r\n * this view.\r\n */\r\n get: function () {\r\n return this._syncedDocuments;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n /**\r\n * Iterates over a set of doc changes, applies the query limit, and computes\r\n * what the new results should be, what the changes were, and whether we may\r\n * need to go back to the local cache for more results. Does not make any\r\n * changes to the view.\r\n * @param docChanges The doc changes to apply to this view.\r\n * @param previousChanges If this is being called with a refill, then start\r\n * with this set of docs and changes instead of the current view.\r\n * @return a new set of docs, changes, and refill flag.\r\n */\r\n View.prototype.computeDocChanges = function (docChanges, previousChanges) {\r\n var _this = this;\r\n var changeSet = previousChanges\r\n ? previousChanges.changeSet\r\n : new DocumentChangeSet();\r\n var oldDocumentSet = previousChanges\r\n ? previousChanges.documentSet\r\n : this.documentSet;\r\n var newMutatedKeys = previousChanges\r\n ? previousChanges.mutatedKeys\r\n : this.mutatedKeys;\r\n var newDocumentSet = oldDocumentSet;\r\n var needsRefill = false;\r\n // Track the last doc in a (full) limit. This is necessary, because some\r\n // update (a delete, or an update moving a doc past the old limit) might\r\n // mean there is some other document in the local cache that either should\r\n // come (1) between the old last limit doc and the new last document, in the\r\n // case of updates, or (2) after the new last document, in the case of\r\n // deletes. So we keep this doc at the old limit to compare the updates to.\r\n //\r\n // Note that this should never get used in a refill (when previousChanges is\r\n // set), because there will only be adds -- no deletes or updates.\r\n var lastDocInLimit = this.query.hasLimit() && oldDocumentSet.size === this.query.limit\r\n ? oldDocumentSet.last()\r\n : null;\r\n docChanges.inorderTraversal(function (key, newMaybeDoc) {\r\n var oldDoc = oldDocumentSet.get(key);\r\n var newDoc = newMaybeDoc instanceof Document ? newMaybeDoc : null;\r\n if (newDoc) {\r\n assert(key.isEqual(newDoc.key), 'Mismatching keys found in document changes: ' +\r\n key +\r\n ' != ' +\r\n newDoc.key);\r\n newDoc = _this.query.matches(newDoc) ? newDoc : null;\r\n }\r\n var oldDocHadPendingMutations = oldDoc\r\n ? _this.mutatedKeys.has(oldDoc.key)\r\n : false;\r\n var newDocHasPendingMutations = newDoc\r\n ? newDoc.hasLocalMutations ||\r\n // We only consider committed mutations for documents that were\r\n // mutated during the lifetime of the view.\r\n (_this.mutatedKeys.has(newDoc.key) && newDoc.hasCommittedMutations)\r\n : false;\r\n var changeApplied = false;\r\n // Calculate change\r\n if (oldDoc && newDoc) {\r\n var docsEqual = oldDoc.data.isEqual(newDoc.data);\r\n if (!docsEqual) {\r\n if (!_this.shouldWaitForSyncedDocument(oldDoc, newDoc)) {\r\n changeSet.track({\r\n type: ChangeType.Modified,\r\n doc: newDoc\r\n });\r\n changeApplied = true;\r\n if (lastDocInLimit &&\r\n _this.query.docComparator(newDoc, lastDocInLimit) > 0) {\r\n // This doc moved from inside the limit to after the limit.\r\n // That means there may be some doc in the local cache that's\r\n // actually less than this one.\r\n needsRefill = true;\r\n }\r\n }\r\n }\r\n else if (oldDocHadPendingMutations !== newDocHasPendingMutations) {\r\n changeSet.track({ type: ChangeType.Metadata, doc: newDoc });\r\n changeApplied = true;\r\n }\r\n }\r\n else if (!oldDoc && newDoc) {\r\n changeSet.track({ type: ChangeType.Added, doc: newDoc });\r\n changeApplied = true;\r\n }\r\n else if (oldDoc && !newDoc) {\r\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc });\r\n changeApplied = true;\r\n if (lastDocInLimit) {\r\n // A doc was removed from a full limit query. We'll need to\r\n // requery from the local cache to see if we know about some other\r\n // doc that should be in the results.\r\n needsRefill = true;\r\n }\r\n }\r\n if (changeApplied) {\r\n if (newDoc) {\r\n newDocumentSet = newDocumentSet.add(newDoc);\r\n if (newDocHasPendingMutations) {\r\n newMutatedKeys = newMutatedKeys.add(key);\r\n }\r\n else {\r\n newMutatedKeys = newMutatedKeys.delete(key);\r\n }\r\n }\r\n else {\r\n newDocumentSet = newDocumentSet.delete(key);\r\n newMutatedKeys = newMutatedKeys.delete(key);\r\n }\r\n }\r\n });\r\n if (this.query.hasLimit()) {\r\n while (newDocumentSet.size > this.query.limit) {\r\n var oldDoc = newDocumentSet.last();\r\n newDocumentSet = newDocumentSet.delete(oldDoc.key);\r\n newMutatedKeys = newMutatedKeys.delete(oldDoc.key);\r\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc });\r\n }\r\n }\r\n assert(!needsRefill || !previousChanges, 'View was refilled using docs that themselves needed refilling.');\r\n return {\r\n documentSet: newDocumentSet,\r\n changeSet: changeSet,\r\n needsRefill: needsRefill,\r\n mutatedKeys: newMutatedKeys\r\n };\r\n };\r\n View.prototype.shouldWaitForSyncedDocument = function (oldDoc, newDoc) {\r\n // We suppress the initial change event for documents that were modified as\r\n // part of a write acknowledgment (e.g. when the value of a server transform\r\n // is applied) as Watch will send us the same document again.\r\n // By suppressing the event, we only raise two user visible events (one with\r\n // `hasPendingWrites` and the final state of the document) instead of three\r\n // (one with `hasPendingWrites`, the modified document with\r\n // `hasPendingWrites` and the final state of the document).\r\n return (oldDoc.hasLocalMutations &&\r\n newDoc.hasCommittedMutations &&\r\n !newDoc.hasLocalMutations);\r\n };\r\n /**\r\n * Updates the view with the given ViewDocumentChanges and optionally updates\r\n * limbo docs and sync state from the provided target change.\r\n * @param docChanges The set of changes to make to the view's docs.\r\n * @param updateLimboDocuments Whether to update limbo documents based on this\r\n * change.\r\n * @param targetChange A target change to apply for computing limbo docs and\r\n * sync state.\r\n * @return A new ViewChange with the given docs, changes, and sync state.\r\n */\r\n // PORTING NOTE: The iOS/Android clients always compute limbo document changes.\r\n View.prototype.applyChanges = function (docChanges, updateLimboDocuments, targetChange) {\r\n var _this = this;\r\n assert(!docChanges.needsRefill, 'Cannot apply changes that need a refill');\r\n var oldDocs = this.documentSet;\r\n this.documentSet = docChanges.documentSet;\r\n this.mutatedKeys = docChanges.mutatedKeys;\r\n // Sort changes based on type and query comparator\r\n var changes = docChanges.changeSet.getChanges();\r\n changes.sort(function (c1, c2) {\r\n return (compareChangeType(c1.type, c2.type) ||\r\n _this.query.docComparator(c1.doc, c2.doc));\r\n });\r\n this.applyTargetChange(targetChange);\r\n var limboChanges = updateLimboDocuments\r\n ? this.updateLimboDocuments()\r\n : [];\r\n var synced = this.limboDocuments.size === 0 && this.current;\r\n var newSyncState = synced ? SyncState.Synced : SyncState.Local;\r\n var syncStateChanged = newSyncState !== this.syncState;\r\n this.syncState = newSyncState;\r\n if (changes.length === 0 && !syncStateChanged) {\r\n // no changes\r\n return { limboChanges: limboChanges };\r\n }\r\n else {\r\n var snap = new ViewSnapshot(this.query, docChanges.documentSet, oldDocs, changes, docChanges.mutatedKeys, newSyncState === SyncState.Local, syncStateChanged, \r\n /* excludesMetadataChanges= */ false);\r\n return {\r\n snapshot: snap,\r\n limboChanges: limboChanges\r\n };\r\n }\r\n };\r\n /**\r\n * Applies an OnlineState change to the view, potentially generating a\r\n * ViewChange if the view's syncState changes as a result.\r\n */\r\n View.prototype.applyOnlineStateChange = function (onlineState) {\r\n if (this.current && onlineState === OnlineState.Offline) {\r\n // If we're offline, set `current` to false and then call applyChanges()\r\n // to refresh our syncState and generate a ViewChange as appropriate. We\r\n // are guaranteed to get a new TargetChange that sets `current` back to\r\n // true once the client is back online.\r\n this.current = false;\r\n return this.applyChanges({\r\n documentSet: this.documentSet,\r\n changeSet: new DocumentChangeSet(),\r\n mutatedKeys: this.mutatedKeys,\r\n needsRefill: false\r\n }, \r\n /* updateLimboDocuments= */ false);\r\n }\r\n else {\r\n // No effect, just return a no-op ViewChange.\r\n return { limboChanges: [] };\r\n }\r\n };\r\n /**\r\n * Returns whether the doc for the given key should be in limbo.\r\n */\r\n View.prototype.shouldBeInLimbo = function (key) {\r\n // If the remote end says it's part of this query, it's not in limbo.\r\n if (this._syncedDocuments.has(key)) {\r\n return false;\r\n }\r\n // The local store doesn't think it's a result, so it shouldn't be in limbo.\r\n if (!this.documentSet.has(key)) {\r\n return false;\r\n }\r\n // If there are local changes to the doc, they might explain why the server\r\n // doesn't know that it's part of the query. So don't put it in limbo.\r\n // TODO(klimt): Ideally, we would only consider changes that might actually\r\n // affect this specific query.\r\n if (this.documentSet.get(key).hasLocalMutations) {\r\n return false;\r\n }\r\n // Everything else is in limbo.\r\n return true;\r\n };\r\n /**\r\n * Updates syncedDocuments, current, and limbo docs based on the given change.\r\n * Returns the list of changes to which docs are in limbo.\r\n */\r\n View.prototype.applyTargetChange = function (targetChange) {\r\n var _this = this;\r\n if (targetChange) {\r\n targetChange.addedDocuments.forEach(function (key) { return (_this._syncedDocuments = _this._syncedDocuments.add(key)); });\r\n targetChange.modifiedDocuments.forEach(function (key) {\r\n return assert(_this._syncedDocuments.has(key), \"Modified document \" + key + \" not found in view.\");\r\n });\r\n targetChange.removedDocuments.forEach(function (key) { return (_this._syncedDocuments = _this._syncedDocuments.delete(key)); });\r\n this.current = targetChange.current;\r\n }\r\n };\r\n View.prototype.updateLimboDocuments = function () {\r\n var _this = this;\r\n // We can only determine limbo documents when we're in-sync with the server.\r\n if (!this.current) {\r\n return [];\r\n }\r\n // TODO(klimt): Do this incrementally so that it's not quadratic when\r\n // updating many documents.\r\n var oldLimboDocuments = this.limboDocuments;\r\n this.limboDocuments = documentKeySet();\r\n this.documentSet.forEach(function (doc) {\r\n if (_this.shouldBeInLimbo(doc.key)) {\r\n _this.limboDocuments = _this.limboDocuments.add(doc.key);\r\n }\r\n });\r\n // Diff the new limbo docs with the old limbo docs.\r\n var changes = [];\r\n oldLimboDocuments.forEach(function (key) {\r\n if (!_this.limboDocuments.has(key)) {\r\n changes.push(new RemovedLimboDocument(key));\r\n }\r\n });\r\n this.limboDocuments.forEach(function (key) {\r\n if (!oldLimboDocuments.has(key)) {\r\n changes.push(new AddedLimboDocument(key));\r\n }\r\n });\r\n return changes;\r\n };\r\n /**\r\n * Update the in-memory state of the current view with the state read from\r\n * persistence.\r\n *\r\n * We update the query view whenever a client's primary status changes:\r\n * - When a client transitions from primary to secondary, it can miss\r\n * LocalStorage updates and its query views may temporarily not be\r\n * synchronized with the state on disk.\r\n * - For secondary to primary transitions, the client needs to update the list\r\n * of `syncedDocuments` since secondary clients update their query views\r\n * based purely on synthesized RemoteEvents.\r\n *\r\n * @param localDocs - The documents that match the query according to the\r\n * LocalStore.\r\n * @param remoteKeys - The keys of the documents that match the query\r\n * according to the backend.\r\n *\r\n * @return The ViewChange that resulted from this synchronization.\r\n */\r\n // PORTING NOTE: Multi-tab only.\r\n View.prototype.synchronizeWithPersistedState = function (localDocs, remoteKeys) {\r\n this._syncedDocuments = remoteKeys;\r\n this.limboDocuments = documentKeySet();\r\n var docChanges = this.computeDocChanges(localDocs);\r\n return this.applyChanges(docChanges, /*updateLimboDocuments=*/ true);\r\n };\r\n /**\r\n * Returns a view snapshot as if this query was just listened to. Contains\r\n * a document add for every existing document and the `fromCache` and\r\n * `hasPendingWrites` status of the already established view.\r\n */\r\n // PORTING NOTE: Multi-tab only.\r\n View.prototype.computeInitialSnapshot = function () {\r\n return ViewSnapshot.fromInitialDocuments(this.query, this.documentSet, this.mutatedKeys, this.syncState === SyncState.Local);\r\n };\r\n return View;\r\n}());\r\nfunction compareChangeType(c1, c2) {\r\n var order = function (change) {\r\n switch (change) {\r\n case ChangeType.Added:\r\n return 1;\r\n case ChangeType.Modified:\r\n return 2;\r\n case ChangeType.Metadata:\r\n // A metadata change is converted to a modified change at the public\r\n // api layer. Since we sort by document key and then change type,\r\n // metadata and modified changes must be sorted equivalently.\r\n return 2;\r\n case ChangeType.Removed:\r\n return 0;\r\n default:\r\n return fail('Unknown ChangeType: ' + change);\r\n }\r\n };\r\n return order(c1) - order(c2);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar LOG_TAG$9 = 'SyncEngine';\r\n/**\r\n * QueryView contains all of the data that SyncEngine needs to keep track of for\r\n * a particular query.\r\n */\r\nvar QueryView = /** @class */ (function () {\r\n function QueryView(\r\n /**\r\n * The query itself.\r\n */\r\n query, \r\n /**\r\n * The target number created by the client that is used in the watch\r\n * stream to identify this query.\r\n */\r\n targetId, \r\n /**\r\n * The view is responsible for computing the final merged truth of what\r\n * docs are in the query. It gets notified of local and remote changes,\r\n * and applies the query filters and limits to determine the most correct\r\n * possible results.\r\n */\r\n view) {\r\n this.query = query;\r\n this.targetId = targetId;\r\n this.view = view;\r\n }\r\n return QueryView;\r\n}());\r\n/** Tracks a limbo resolution. */\r\nvar LimboResolution = /** @class */ (function () {\r\n function LimboResolution(key) {\r\n this.key = key;\r\n }\r\n return LimboResolution;\r\n}());\r\n/**\r\n * SyncEngine is the central controller in the client SDK architecture. It is\r\n * the glue code between the EventManager, LocalStore, and RemoteStore. Some of\r\n * SyncEngine's responsibilities include:\r\n * 1. Coordinating client requests and remote events between the EventManager\r\n * and the local and remote data stores.\r\n * 2. Managing a View object for each query, providing the unified view between\r\n * the local and remote data stores.\r\n * 3. Notifying the RemoteStore when the LocalStore has new mutations in its\r\n * queue that need sending to the backend.\r\n *\r\n * The SyncEngine’s methods should only ever be called by methods running in the\r\n * global async queue.\r\n */\r\nvar SyncEngine = /** @class */ (function () {\r\n function SyncEngine(localStore, remoteStore, \r\n // PORTING NOTE: Manages state synchronization in multi-tab environments.\r\n sharedClientState, currentUser) {\r\n this.localStore = localStore;\r\n this.remoteStore = remoteStore;\r\n this.sharedClientState = sharedClientState;\r\n this.currentUser = currentUser;\r\n this.syncEngineListener = null;\r\n this.queryViewsByQuery = new ObjectMap(function (q) {\r\n return q.canonicalId();\r\n });\r\n this.queryViewsByTarget = {};\r\n this.limboTargetsByKey = new SortedMap(DocumentKey.comparator);\r\n this.limboResolutionsByTarget = {};\r\n this.limboDocumentRefs = new ReferenceSet();\r\n /** Stores user completion handlers, indexed by User and BatchId. */\r\n this.mutationUserCallbacks = {};\r\n this.limboTargetIdGenerator = TargetIdGenerator.forSyncEngine();\r\n // The primary state is set to `true` or `false` immediately after Firestore\r\n // startup. In the interim, a client should only be considered primary if\r\n // `isPrimary` is true.\r\n this.isPrimary = undefined;\r\n this.onlineState = OnlineState.Unknown;\r\n }\r\n Object.defineProperty(SyncEngine.prototype, \"isPrimaryClient\", {\r\n // Only used for testing.\r\n get: function () {\r\n return this.isPrimary === true;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n /** Subscribes to SyncEngine notifications. Has to be called exactly once. */\r\n SyncEngine.prototype.subscribe = function (syncEngineListener) {\r\n assert(syncEngineListener !== null, 'SyncEngine listener cannot be null');\r\n assert(this.syncEngineListener === null, 'SyncEngine already has a subscriber.');\r\n this.syncEngineListener = syncEngineListener;\r\n };\r\n /**\r\n * Initiates the new listen, resolves promise when listen enqueued to the\r\n * server. All the subsequent view snapshots or errors are sent to the\r\n * subscribed handlers. Returns the targetId of the query.\r\n */\r\n SyncEngine.prototype.listen = function (query) {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n var targetId, viewSnapshot, queryView, queryData, status_1;\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n this.assertSubscribed('listen()');\r\n queryView = this.queryViewsByQuery.get(query);\r\n if (!queryView) return [3 /*break*/, 1];\r\n // PORTING NOTE: With Multi-Tab Web, it is possible that a query view\r\n // already exists when EventManager calls us for the first time. This\r\n // happens when the primary tab is already listening to this query on\r\n // behalf of another tab and the user of the primary also starts listening\r\n // to the query. EventManager will not have an assigned target ID in this\r\n // case and calls `listen` to obtain this ID.\r\n targetId = queryView.targetId;\r\n this.sharedClientState.addLocalQueryTarget(targetId);\r\n viewSnapshot = queryView.view.computeInitialSnapshot();\r\n return [3 /*break*/, 4];\r\n case 1: return [4 /*yield*/, this.localStore.allocateQuery(query)];\r\n case 2:\r\n queryData = _a.sent();\r\n status_1 = this.sharedClientState.addLocalQueryTarget(queryData.targetId);\r\n targetId = queryData.targetId;\r\n return [4 /*yield*/, this.initializeViewAndComputeSnapshot(queryData, status_1 === 'current')];\r\n case 3:\r\n viewSnapshot = _a.sent();\r\n if (this.isPrimary) {\r\n this.remoteStore.listen(queryData);\r\n }\r\n _a.label = 4;\r\n case 4:\r\n this.syncEngineListener.onWatchChange([viewSnapshot]);\r\n return [2 /*return*/, targetId];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * Registers a view for a previously unknown query and computes its initial\r\n * snapshot.\r\n */\r\n SyncEngine.prototype.initializeViewAndComputeSnapshot = function (queryData, current) {\r\n var _this = this;\r\n var query = queryData.query;\r\n return this.localStore.executeQuery(query).then(function (docs) {\r\n return _this.localStore\r\n .remoteDocumentKeys(queryData.targetId)\r\n .then(function (remoteKeys) {\r\n var view = new View(query, remoteKeys);\r\n var viewDocChanges = view.computeDocChanges(docs);\r\n // tslint:disable-next-line:max-line-length Prettier formats this exceed 100 characters.\r\n var synthesizedTargetChange = TargetChange.createSynthesizedTargetChangeForCurrentChange(queryData.targetId, current && _this.onlineState !== OnlineState.Offline);\r\n var viewChange = view.applyChanges(viewDocChanges, \r\n /* updateLimboDocuments= */ _this.isPrimary === true, synthesizedTargetChange);\r\n assert(viewChange.limboChanges.length === 0, 'View returned limbo docs before target ack from the server.');\r\n assert(!!viewChange.snapshot, 'applyChanges for new view should always return a snapshot');\r\n var data = new QueryView(query, queryData.targetId, view);\r\n _this.queryViewsByQuery.set(query, data);\r\n _this.queryViewsByTarget[queryData.targetId] = data;\r\n return viewChange.snapshot;\r\n });\r\n });\r\n };\r\n /**\r\n * Reconcile the list of synced documents in an existing view with those\r\n * from persistence.\r\n */\r\n // PORTING NOTE: Multi-tab only.\r\n SyncEngine.prototype.synchronizeViewAndComputeSnapshot = function (queryView) {\r\n var _this = this;\r\n return this.localStore.executeQuery(queryView.query).then(function (docs) {\r\n return _this.localStore\r\n .remoteDocumentKeys(queryView.targetId)\r\n .then(function (remoteKeys) { return tslib_1.__awaiter(_this, void 0, void 0, function () {\r\n var viewSnapshot;\r\n return tslib_1.__generator(this, function (_a) {\r\n viewSnapshot = queryView.view.synchronizeWithPersistedState(docs, remoteKeys);\r\n if (this.isPrimary) {\r\n this.updateTrackedLimbos(queryView.targetId, viewSnapshot.limboChanges);\r\n }\r\n return [2 /*return*/, viewSnapshot];\r\n });\r\n }); });\r\n });\r\n };\r\n /** Stops listening to the query. */\r\n SyncEngine.prototype.unlisten = function (query) {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n var queryView, targetRemainsActive;\r\n var _this = this;\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n this.assertSubscribed('unlisten()');\r\n queryView = this.queryViewsByQuery.get(query);\r\n assert(!!queryView, 'Trying to unlisten on query not found:' + query);\r\n if (!this.isPrimary) return [3 /*break*/, 3];\r\n // We need to remove the local query target first to allow us to verify\r\n // whether any other client is still interested in this target.\r\n this.sharedClientState.removeLocalQueryTarget(queryView.targetId);\r\n targetRemainsActive = this.sharedClientState.isActiveQueryTarget(queryView.targetId);\r\n if (!!targetRemainsActive) return [3 /*break*/, 2];\r\n return [4 /*yield*/, this.localStore\r\n .releaseQuery(query, /*keepPersistedQueryData=*/ false)\r\n .then(function () {\r\n _this.sharedClientState.clearQueryState(queryView.targetId);\r\n _this.remoteStore.unlisten(queryView.targetId);\r\n _this.removeAndCleanupQuery(queryView);\r\n })\r\n .catch(ignoreIfPrimaryLeaseLoss)];\r\n case 1:\r\n _a.sent();\r\n _a.label = 2;\r\n case 2: return [3 /*break*/, 5];\r\n case 3:\r\n this.removeAndCleanupQuery(queryView);\r\n return [4 /*yield*/, this.localStore.releaseQuery(query, \r\n /*keepPersistedQueryData=*/ true)];\r\n case 4:\r\n _a.sent();\r\n _a.label = 5;\r\n case 5: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * Initiates the write of local mutation batch which involves adding the\r\n * writes to the mutation queue, notifying the remote store about new\r\n * mutations and raising events for any changes this write caused.\r\n *\r\n * The promise returned by this call is resolved when the above steps\r\n * have completed, *not* when the write was acked by the backend. The\r\n * userCallback is resolved once the write was acked/rejected by the\r\n * backend (or failed locally for any other reason).\r\n */\r\n SyncEngine.prototype.write = function (batch, userCallback) {\r\n var _this = this;\r\n this.assertSubscribed('write()');\r\n return this.localStore\r\n .localWrite(batch)\r\n .then(function (result) {\r\n _this.sharedClientState.addPendingMutation(result.batchId);\r\n _this.addMutationCallback(result.batchId, userCallback);\r\n return _this.emitNewSnapsAndNotifyLocalStore(result.changes);\r\n })\r\n .then(function () {\r\n return _this.remoteStore.fillWritePipeline();\r\n });\r\n };\r\n // TODO(klimt): Wrap the given error in a standard Firestore error object.\r\n SyncEngine.prototype.wrapUpdateFunctionError = function (error) {\r\n return error;\r\n };\r\n /**\r\n * Takes an updateFunction in which a set of reads and writes can be performed\r\n * atomically. In the updateFunction, the client can read and write values\r\n * using the supplied transaction object. After the updateFunction, all\r\n * changes will be committed. If some other client has changed any of the data\r\n * referenced, then the updateFunction will be called again. If the\r\n * updateFunction still fails after the given number of retries, then the\r\n * transaction will be rejection.\r\n *\r\n * The transaction object passed to the updateFunction contains methods for\r\n * accessing documents and collections. Unlike other datastore access, data\r\n * accessed with the transaction will not reflect local changes that have not\r\n * been committed. For this reason, it is required that all reads are\r\n * performed before any writes. Transactions must be performed while online.\r\n *\r\n * The promise returned is resolved when the transaction is fully committed.\r\n */\r\n SyncEngine.prototype.runTransaction = function (updateFunction, retries) {\r\n var _this = this;\r\n if (retries === void 0) { retries = 5; }\r\n assert(retries >= 0, 'Got negative number of retries for transaction.');\r\n var transaction = this.remoteStore.createTransaction();\r\n var wrappedUpdateFunction = function () {\r\n try {\r\n var userPromise = updateFunction(transaction);\r\n if (isNullOrUndefined(userPromise) ||\r\n !userPromise.catch ||\r\n !userPromise.then) {\r\n return Promise.reject(Error('Transaction callback must return a Promise'));\r\n }\r\n return userPromise.catch(function (e) {\r\n return Promise.reject(_this.wrapUpdateFunctionError(e));\r\n });\r\n }\r\n catch (e) {\r\n return Promise.reject(_this.wrapUpdateFunctionError(e));\r\n }\r\n };\r\n return wrappedUpdateFunction().then(function (result) {\r\n return transaction\r\n .commit()\r\n .then(function () {\r\n return result;\r\n })\r\n .catch(function (error) {\r\n if (retries === 0) {\r\n return Promise.reject(error);\r\n }\r\n // TODO(klimt): Put in a retry delay?\r\n return _this.runTransaction(updateFunction, retries - 1);\r\n });\r\n });\r\n };\r\n SyncEngine.prototype.applyRemoteEvent = function (remoteEvent) {\r\n var _this = this;\r\n this.assertSubscribed('applyRemoteEvent()');\r\n return this.localStore\r\n .applyRemoteEvent(remoteEvent)\r\n .then(function (changes) {\r\n // Update `receivedDocument` as appropriate for any limbo targets.\r\n forEach(remoteEvent.targetChanges, function (targetId, targetChange) {\r\n var limboResolution = _this.limboResolutionsByTarget[targetId];\r\n if (limboResolution) {\r\n // Since this is a limbo resolution lookup, it's for a single document\r\n // and it could be added, modified, or removed, but not a combination.\r\n assert(targetChange.addedDocuments.size +\r\n targetChange.modifiedDocuments.size +\r\n targetChange.removedDocuments.size <=\r\n 1, 'Limbo resolution for single document contains multiple changes.');\r\n if (targetChange.addedDocuments.size > 0) {\r\n limboResolution.receivedDocument = true;\r\n }\r\n else if (targetChange.modifiedDocuments.size > 0) {\r\n assert(limboResolution.receivedDocument, 'Received change for limbo target document without add.');\r\n }\r\n else if (targetChange.removedDocuments.size > 0) {\r\n assert(limboResolution.receivedDocument, 'Received remove for limbo target document without add.');\r\n limboResolution.receivedDocument = false;\r\n }\r\n }\r\n });\r\n return _this.emitNewSnapsAndNotifyLocalStore(changes, remoteEvent);\r\n })\r\n .catch(ignoreIfPrimaryLeaseLoss);\r\n };\r\n /**\r\n * Applies an OnlineState change to the sync engine and notifies any views of\r\n * the change.\r\n */\r\n SyncEngine.prototype.applyOnlineStateChange = function (onlineState, source) {\r\n // If we are the secondary client, we explicitly ignore the remote store's\r\n // online state (the local client may go offline, even though the primary\r\n // tab remains online) and only apply the primary tab's online state from\r\n // SharedClientState.\r\n if ((this.isPrimary && source === OnlineStateSource.RemoteStore) ||\r\n (!this.isPrimary && source === OnlineStateSource.SharedClientState)) {\r\n var newViewSnapshots_1 = [];\r\n this.queryViewsByQuery.forEach(function (query, queryView) {\r\n var viewChange = queryView.view.applyOnlineStateChange(onlineState);\r\n assert(viewChange.limboChanges.length === 0, 'OnlineState should not affect limbo documents.');\r\n if (viewChange.snapshot) {\r\n newViewSnapshots_1.push(viewChange.snapshot);\r\n }\r\n });\r\n this.syncEngineListener.onOnlineStateChange(onlineState);\r\n this.syncEngineListener.onWatchChange(newViewSnapshots_1);\r\n this.onlineState = onlineState;\r\n if (this.isPrimary) {\r\n this.sharedClientState.setOnlineState(onlineState);\r\n }\r\n }\r\n };\r\n SyncEngine.prototype.rejectListen = function (targetId, err) {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n var limboResolution, limboKey, documentUpdates, resolvedLimboDocuments, event_1, queryView_1;\r\n var _this = this;\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n this.assertSubscribed('rejectListens()');\r\n // PORTING NOTE: Multi-tab only.\r\n this.sharedClientState.updateQueryState(targetId, 'rejected', err);\r\n limboResolution = this.limboResolutionsByTarget[targetId];\r\n limboKey = limboResolution && limboResolution.key;\r\n if (!limboKey) return [3 /*break*/, 1];\r\n // Since this query failed, we won't want to manually unlisten to it.\r\n // So go ahead and remove it from bookkeeping.\r\n this.limboTargetsByKey = this.limboTargetsByKey.remove(limboKey);\r\n delete this.limboResolutionsByTarget[targetId];\r\n documentUpdates = new SortedMap(DocumentKey.comparator);\r\n documentUpdates = documentUpdates.insert(limboKey, new NoDocument(limboKey, SnapshotVersion.forDeletedDoc()));\r\n resolvedLimboDocuments = documentKeySet().add(limboKey);\r\n event_1 = new RemoteEvent(SnapshotVersion.MIN, \r\n /* targetChanges= */ {}, \r\n /* targetMismatches= */ new SortedSet(primitiveComparator), documentUpdates, resolvedLimboDocuments);\r\n return [2 /*return*/, this.applyRemoteEvent(event_1)];\r\n case 1:\r\n queryView_1 = this.queryViewsByTarget[targetId];\r\n assert(!!queryView_1, 'Unknown targetId: ' + targetId);\r\n return [4 /*yield*/, this.localStore\r\n .releaseQuery(queryView_1.query, /* keepPersistedQueryData */ false)\r\n .then(function () { return _this.removeAndCleanupQuery(queryView_1); })\r\n .catch(ignoreIfPrimaryLeaseLoss)];\r\n case 2:\r\n _a.sent();\r\n this.syncEngineListener.onWatchError(queryView_1.query, err);\r\n _a.label = 3;\r\n case 3: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n // PORTING NOTE: Multi-tab only\r\n SyncEngine.prototype.applyBatchState = function (batchId, batchState, error) {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n var documents;\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n this.assertSubscribed('applyBatchState()');\r\n return [4 /*yield*/, this.localStore.lookupMutationDocuments(batchId)];\r\n case 1:\r\n documents = _a.sent();\r\n if (documents === null) {\r\n // A throttled tab may not have seen the mutation before it was completed\r\n // and removed from the mutation queue, in which case we won't have cached\r\n // the affected documents. In this case we can safely ignore the update\r\n // since that means we didn't apply the mutation locally at all (if we\r\n // had, we would have cached the affected documents), and so we will just\r\n // see any resulting document changes via normal remote document updates\r\n // as applicable.\r\n debug(LOG_TAG$9, 'Cannot apply mutation batch with id: ' + batchId);\r\n return [2 /*return*/];\r\n }\r\n if (!(batchState === 'pending')) return [3 /*break*/, 3];\r\n // If we are the primary client, we need to send this write to the\r\n // backend. Secondary clients will ignore these writes since their remote\r\n // connection is disabled.\r\n return [4 /*yield*/, this.remoteStore.fillWritePipeline()];\r\n case 2:\r\n // If we are the primary client, we need to send this write to the\r\n // backend. Secondary clients will ignore these writes since their remote\r\n // connection is disabled.\r\n _a.sent();\r\n return [3 /*break*/, 4];\r\n case 3:\r\n if (batchState === 'acknowledged' || batchState === 'rejected') {\r\n // NOTE: Both these methods are no-ops for batches that originated from\r\n // other clients.\r\n this.processUserCallback(batchId, error ? error : null);\r\n this.localStore.removeCachedMutationBatchMetadata(batchId);\r\n }\r\n else {\r\n fail(\"Unknown batchState: \" + batchState);\r\n }\r\n _a.label = 4;\r\n case 4: return [4 /*yield*/, this.emitNewSnapsAndNotifyLocalStore(documents)];\r\n case 5:\r\n _a.sent();\r\n return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n SyncEngine.prototype.applySuccessfulWrite = function (mutationBatchResult) {\r\n var _this = this;\r\n this.assertSubscribed('applySuccessfulWrite()');\r\n var batchId = mutationBatchResult.batch.batchId;\r\n // The local store may or may not be able to apply the write result and\r\n // raise events immediately (depending on whether the watcher is caught\r\n // up), so we raise user callbacks first so that they consistently happen\r\n // before listen events.\r\n this.processUserCallback(batchId, /*error=*/ null);\r\n return this.localStore\r\n .acknowledgeBatch(mutationBatchResult)\r\n .then(function (changes) {\r\n _this.sharedClientState.updateMutationState(batchId, 'acknowledged');\r\n return _this.emitNewSnapsAndNotifyLocalStore(changes);\r\n })\r\n .catch(ignoreIfPrimaryLeaseLoss);\r\n };\r\n SyncEngine.prototype.rejectFailedWrite = function (batchId, error) {\r\n var _this = this;\r\n this.assertSubscribed('rejectFailedWrite()');\r\n // The local store may or may not be able to apply the write result and\r\n // raise events immediately (depending on whether the watcher is caught up),\r\n // so we raise user callbacks first so that they consistently happen before\r\n // listen events.\r\n this.processUserCallback(batchId, error);\r\n return this.localStore\r\n .rejectBatch(batchId)\r\n .then(function (changes) {\r\n _this.sharedClientState.updateMutationState(batchId, 'rejected', error);\r\n return _this.emitNewSnapsAndNotifyLocalStore(changes);\r\n })\r\n .catch(ignoreIfPrimaryLeaseLoss);\r\n };\r\n SyncEngine.prototype.addMutationCallback = function (batchId, callback) {\r\n var newCallbacks = this.mutationUserCallbacks[this.currentUser.toKey()];\r\n if (!newCallbacks) {\r\n newCallbacks = new SortedMap(primitiveComparator);\r\n }\r\n newCallbacks = newCallbacks.insert(batchId, callback);\r\n this.mutationUserCallbacks[this.currentUser.toKey()] = newCallbacks;\r\n };\r\n /**\r\n * Resolves or rejects the user callback for the given batch and then discards\r\n * it.\r\n */\r\n SyncEngine.prototype.processUserCallback = function (batchId, error) {\r\n var newCallbacks = this.mutationUserCallbacks[this.currentUser.toKey()];\r\n // NOTE: Mutations restored from persistence won't have callbacks, so it's\r\n // okay for there to be no callback for this ID.\r\n if (newCallbacks) {\r\n var callback = newCallbacks.get(batchId);\r\n if (callback) {\r\n assert(batchId === newCallbacks.minKey(), 'Mutation callbacks processed out-of-order?');\r\n if (error) {\r\n callback.reject(error);\r\n }\r\n else {\r\n callback.resolve();\r\n }\r\n newCallbacks = newCallbacks.remove(batchId);\r\n }\r\n this.mutationUserCallbacks[this.currentUser.toKey()] = newCallbacks;\r\n }\r\n };\r\n SyncEngine.prototype.removeAndCleanupQuery = function (queryView) {\r\n var _this = this;\r\n this.sharedClientState.removeLocalQueryTarget(queryView.targetId);\r\n this.queryViewsByQuery.delete(queryView.query);\r\n delete this.queryViewsByTarget[queryView.targetId];\r\n if (this.isPrimary) {\r\n var limboKeys = this.limboDocumentRefs.referencesForId(queryView.targetId);\r\n this.limboDocumentRefs.removeReferencesForId(queryView.targetId);\r\n limboKeys.forEach(function (limboKey) {\r\n var isReferenced = _this.limboDocumentRefs.containsKey(limboKey);\r\n if (!isReferenced) {\r\n // We removed the last reference for this key\r\n _this.removeLimboTarget(limboKey);\r\n }\r\n });\r\n }\r\n };\r\n SyncEngine.prototype.removeLimboTarget = function (key) {\r\n // It's possible that the target already got removed because the query failed. In that case,\r\n // the key won't exist in `limboTargetsByKey`. Only do the cleanup if we still have the target.\r\n var limboTargetId = this.limboTargetsByKey.get(key);\r\n if (limboTargetId === null) {\r\n // This target already got removed, because the query failed.\r\n return;\r\n }\r\n this.remoteStore.unlisten(limboTargetId);\r\n this.limboTargetsByKey = this.limboTargetsByKey.remove(key);\r\n delete this.limboResolutionsByTarget[limboTargetId];\r\n };\r\n SyncEngine.prototype.updateTrackedLimbos = function (targetId, limboChanges) {\r\n for (var _i = 0, limboChanges_1 = limboChanges; _i < limboChanges_1.length; _i++) {\r\n var limboChange = limboChanges_1[_i];\r\n if (limboChange instanceof AddedLimboDocument) {\r\n this.limboDocumentRefs.addReference(limboChange.key, targetId);\r\n this.trackLimboChange(limboChange);\r\n }\r\n else if (limboChange instanceof RemovedLimboDocument) {\r\n debug(LOG_TAG$9, 'Document no longer in limbo: ' + limboChange.key);\r\n this.limboDocumentRefs.removeReference(limboChange.key, targetId);\r\n var isReferenced = this.limboDocumentRefs.containsKey(limboChange.key);\r\n if (!isReferenced) {\r\n // We removed the last reference for this key\r\n this.removeLimboTarget(limboChange.key);\r\n }\r\n }\r\n else {\r\n fail('Unknown limbo change: ' + JSON.stringify(limboChange));\r\n }\r\n }\r\n };\r\n SyncEngine.prototype.trackLimboChange = function (limboChange) {\r\n var key = limboChange.key;\r\n if (!this.limboTargetsByKey.get(key)) {\r\n debug(LOG_TAG$9, 'New document in limbo: ' + key);\r\n var limboTargetId = this.limboTargetIdGenerator.next();\r\n var query = Query.atPath(key.path);\r\n this.limboResolutionsByTarget[limboTargetId] = new LimboResolution(key);\r\n this.remoteStore.listen(new QueryData(query, limboTargetId, QueryPurpose.LimboResolution, ListenSequence.INVALID));\r\n this.limboTargetsByKey = this.limboTargetsByKey.insert(key, limboTargetId);\r\n }\r\n };\r\n // Visible for testing\r\n SyncEngine.prototype.currentLimboDocs = function () {\r\n return this.limboTargetsByKey;\r\n };\r\n SyncEngine.prototype.emitNewSnapsAndNotifyLocalStore = function (changes, remoteEvent) {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n var newSnaps, docChangesInAllViews, queriesProcessed;\r\n var _this = this;\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n newSnaps = [];\r\n docChangesInAllViews = [];\r\n queriesProcessed = [];\r\n this.queryViewsByQuery.forEach(function (_, queryView) {\r\n queriesProcessed.push(Promise.resolve()\r\n .then(function () {\r\n var viewDocChanges = queryView.view.computeDocChanges(changes);\r\n if (!viewDocChanges.needsRefill) {\r\n return viewDocChanges;\r\n }\r\n // The query has a limit and some docs were removed, so we need\r\n // to re-run the query against the local store to make sure we\r\n // didn't lose any good docs that had been past the limit.\r\n return _this.localStore.executeQuery(queryView.query).then(function (docs) {\r\n return queryView.view.computeDocChanges(docs, viewDocChanges);\r\n });\r\n })\r\n .then(function (viewDocChanges) {\r\n var targetChange = remoteEvent && remoteEvent.targetChanges[queryView.targetId];\r\n var viewChange = queryView.view.applyChanges(viewDocChanges, \r\n /* updateLimboDocuments= */ _this.isPrimary === true, targetChange);\r\n _this.updateTrackedLimbos(queryView.targetId, viewChange.limboChanges);\r\n if (viewChange.snapshot) {\r\n if (_this.isPrimary) {\r\n _this.sharedClientState.updateQueryState(queryView.targetId, viewChange.snapshot.fromCache ? 'not-current' : 'current');\r\n }\r\n newSnaps.push(viewChange.snapshot);\r\n var docChanges = LocalViewChanges.fromSnapshot(queryView.targetId, viewChange.snapshot);\r\n docChangesInAllViews.push(docChanges);\r\n }\r\n }));\r\n });\r\n return [4 /*yield*/, Promise.all(queriesProcessed)];\r\n case 1:\r\n _a.sent();\r\n this.syncEngineListener.onWatchChange(newSnaps);\r\n return [4 /*yield*/, this.localStore.notifyLocalViewChanges(docChangesInAllViews)];\r\n case 2:\r\n _a.sent();\r\n return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n SyncEngine.prototype.assertSubscribed = function (fnName) {\r\n assert(this.syncEngineListener !== null, 'Trying to call ' + fnName + ' before calling subscribe().');\r\n };\r\n SyncEngine.prototype.handleCredentialChange = function (user) {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n var userChanged, result;\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n userChanged = !this.currentUser.isEqual(user);\r\n this.currentUser = user;\r\n if (!userChanged) return [3 /*break*/, 3];\r\n return [4 /*yield*/, this.localStore.handleUserChange(user)];\r\n case 1:\r\n result = _a.sent();\r\n // TODO(b/114226417): Consider calling this only in the primary tab.\r\n this.sharedClientState.handleUserChange(user, result.removedBatchIds, result.addedBatchIds);\r\n return [4 /*yield*/, this.emitNewSnapsAndNotifyLocalStore(result.affectedDocuments)];\r\n case 2:\r\n _a.sent();\r\n _a.label = 3;\r\n case 3: return [4 /*yield*/, this.remoteStore.handleCredentialChange()];\r\n case 4:\r\n _a.sent();\r\n return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n // PORTING NOTE: Multi-tab only\r\n SyncEngine.prototype.applyPrimaryState = function (isPrimary) {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n var activeTargets, activeQueries, _i, activeQueries_1, queryData, activeTargets_1, p_1;\r\n var _this = this;\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (!(isPrimary === true && this.isPrimary !== true)) return [3 /*break*/, 3];\r\n this.isPrimary = true;\r\n return [4 /*yield*/, this.remoteStore.applyPrimaryState(true)];\r\n case 1:\r\n _a.sent();\r\n activeTargets = this.sharedClientState.getAllActiveQueryTargets();\r\n return [4 /*yield*/, this.synchronizeQueryViewsAndRaiseSnapshots(activeTargets.toArray())];\r\n case 2:\r\n activeQueries = _a.sent();\r\n for (_i = 0, activeQueries_1 = activeQueries; _i < activeQueries_1.length; _i++) {\r\n queryData = activeQueries_1[_i];\r\n this.remoteStore.listen(queryData);\r\n }\r\n return [3 /*break*/, 7];\r\n case 3:\r\n if (!(isPrimary === false && this.isPrimary !== false)) return [3 /*break*/, 7];\r\n this.isPrimary = false;\r\n activeTargets_1 = [];\r\n p_1 = Promise.resolve();\r\n forEachNumber(this.queryViewsByTarget, function (targetId, queryView) {\r\n if (_this.sharedClientState.isLocalQueryTarget(targetId)) {\r\n activeTargets_1.push(targetId);\r\n }\r\n else {\r\n p_1 = p_1.then(function () { return _this.unlisten(queryView.query); });\r\n }\r\n _this.remoteStore.unlisten(queryView.targetId);\r\n });\r\n return [4 /*yield*/, p_1];\r\n case 4:\r\n _a.sent();\r\n return [4 /*yield*/, this.synchronizeQueryViewsAndRaiseSnapshots(activeTargets_1)];\r\n case 5:\r\n _a.sent();\r\n this.resetLimboDocuments();\r\n return [4 /*yield*/, this.remoteStore.applyPrimaryState(false)];\r\n case 6:\r\n _a.sent();\r\n _a.label = 7;\r\n case 7: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n // PORTING NOTE: Multi-tab only.\r\n SyncEngine.prototype.resetLimboDocuments = function () {\r\n var _this = this;\r\n forEachNumber(this.limboResolutionsByTarget, function (targetId) {\r\n _this.remoteStore.unlisten(targetId);\r\n });\r\n this.limboDocumentRefs.removeAllReferences();\r\n this.limboResolutionsByTarget = [];\r\n this.limboTargetsByKey = new SortedMap(DocumentKey.comparator);\r\n };\r\n /**\r\n * Reconcile the query views of the provided query targets with the state from\r\n * persistence. Raises snapshots for any changes that affect the local\r\n * client and returns the updated state of all target's query data.\r\n */\r\n // PORTING NOTE: Multi-tab only.\r\n SyncEngine.prototype.synchronizeQueryViewsAndRaiseSnapshots = function (targets) {\r\n var _this = this;\r\n var p = Promise.resolve();\r\n var activeQueries = [];\r\n var newViewSnapshots = [];\r\n var _loop_1 = function (targetId) {\r\n p = p.then(function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {\r\n var queryData, queryView, viewChange, query;\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n queryView = this.queryViewsByTarget[targetId];\r\n if (!queryView) return [3 /*break*/, 4];\r\n // For queries that have a local View, we need to update their state\r\n // in LocalStore (as the resume token and the snapshot version\r\n // might have changed) and reconcile their views with the persisted\r\n // state (the list of syncedDocuments may have gotten out of sync).\r\n return [4 /*yield*/, this.localStore.releaseQuery(queryView.query, \r\n /*keepPersistedQueryData=*/ true)];\r\n case 1:\r\n // For queries that have a local View, we need to update their state\r\n // in LocalStore (as the resume token and the snapshot version\r\n // might have changed) and reconcile their views with the persisted\r\n // state (the list of syncedDocuments may have gotten out of sync).\r\n _a.sent();\r\n return [4 /*yield*/, this.localStore.allocateQuery(queryView.query)];\r\n case 2:\r\n queryData = _a.sent();\r\n return [4 /*yield*/, this.synchronizeViewAndComputeSnapshot(queryView)];\r\n case 3:\r\n viewChange = _a.sent();\r\n if (viewChange.snapshot) {\r\n newViewSnapshots.push(viewChange.snapshot);\r\n }\r\n return [3 /*break*/, 8];\r\n case 4:\r\n assert(this.isPrimary === true, 'A secondary tab should never have an active query without an active view.');\r\n return [4 /*yield*/, this.localStore.getQueryForTarget(targetId)];\r\n case 5:\r\n query = _a.sent();\r\n assert(!!query, \"Query data for target \" + targetId + \" not found\");\r\n return [4 /*yield*/, this.localStore.allocateQuery(query)];\r\n case 6:\r\n queryData = _a.sent();\r\n return [4 /*yield*/, this.initializeViewAndComputeSnapshot(queryData, \r\n /*current=*/ false)];\r\n case 7:\r\n _a.sent();\r\n _a.label = 8;\r\n case 8:\r\n activeQueries.push(queryData);\r\n return [2 /*return*/];\r\n }\r\n });\r\n }); });\r\n };\r\n for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) {\r\n var targetId = targets_1[_i];\r\n _loop_1(targetId);\r\n }\r\n return p.then(function () {\r\n _this.syncEngineListener.onWatchChange(newViewSnapshots);\r\n return activeQueries;\r\n });\r\n };\r\n // PORTING NOTE: Multi-tab only\r\n SyncEngine.prototype.getActiveClients = function () {\r\n return this.localStore.getActiveClients();\r\n };\r\n // PORTING NOTE: Multi-tab only\r\n SyncEngine.prototype.applyTargetState = function (targetId, state, error) {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n var _a, queryView;\r\n var _this = this;\r\n return tslib_1.__generator(this, function (_b) {\r\n switch (_b.label) {\r\n case 0:\r\n if (this.isPrimary) {\r\n // If we receive a target state notification via WebStorage, we are\r\n // either already secondary or another tab has taken the primary lease.\r\n debug(LOG_TAG$9, 'Ignoring unexpected query state notification.');\r\n return [2 /*return*/];\r\n }\r\n if (!this.queryViewsByTarget[targetId]) return [3 /*break*/, 5];\r\n _a = state;\r\n switch (_a) {\r\n case 'current': return [3 /*break*/, 1];\r\n case 'not-current': return [3 /*break*/, 1];\r\n case 'rejected': return [3 /*break*/, 2];\r\n }\r\n return [3 /*break*/, 4];\r\n case 1:\r\n {\r\n return [2 /*return*/, this.localStore.getNewDocumentChanges().then(function (changes) { return tslib_1.__awaiter(_this, void 0, void 0, function () {\r\n var synthesizedRemoteEvent;\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n synthesizedRemoteEvent = RemoteEvent.createSynthesizedRemoteEventForCurrentChange(targetId, state === 'current');\r\n return [4 /*yield*/, this.emitNewSnapsAndNotifyLocalStore(changes, synthesizedRemoteEvent)];\r\n case 1:\r\n _a.sent();\r\n return [2 /*return*/];\r\n }\r\n });\r\n }); }, function (err) { return tslib_1.__awaiter(_this, void 0, void 0, function () {\r\n var activeTargets_2;\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (!isDocumentChangeMissingError(err)) return [3 /*break*/, 2];\r\n activeTargets_2 = [];\r\n forEachNumber(this.queryViewsByTarget, function (target) {\r\n return activeTargets_2.push(target);\r\n });\r\n return [4 /*yield*/, this.synchronizeQueryViewsAndRaiseSnapshots(activeTargets_2)];\r\n case 1:\r\n _a.sent();\r\n return [3 /*break*/, 3];\r\n case 2: throw err;\r\n case 3: return [2 /*return*/];\r\n }\r\n });\r\n }); })];\r\n }\r\n _b.label = 2;\r\n case 2:\r\n queryView = this.queryViewsByTarget[targetId];\r\n this.removeAndCleanupQuery(queryView);\r\n return [4 /*yield*/, this.localStore.releaseQuery(queryView.query, \r\n /*keepPersistedQueryData=*/ true)];\r\n case 3:\r\n _b.sent();\r\n this.syncEngineListener.onWatchError(queryView.query, error);\r\n return [3 /*break*/, 5];\r\n case 4:\r\n fail('Unexpected target state: ' + state);\r\n _b.label = 5;\r\n case 5: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n // PORTING NOTE: Multi-tab only\r\n SyncEngine.prototype.applyActiveTargetsChange = function (added, removed) {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n var _i, added_1, targetId, query, queryData, _loop_2, this_1, _a, removed_1, targetId;\r\n var _this = this;\r\n return tslib_1.__generator(this, function (_b) {\r\n switch (_b.label) {\r\n case 0:\r\n if (!this.isPrimary) {\r\n return [2 /*return*/];\r\n }\r\n _i = 0, added_1 = added;\r\n _b.label = 1;\r\n case 1:\r\n if (!(_i < added_1.length)) return [3 /*break*/, 6];\r\n targetId = added_1[_i];\r\n assert(!this.queryViewsByTarget[targetId], 'Trying to add an already active target');\r\n return [4 /*yield*/, this.localStore.getQueryForTarget(targetId)];\r\n case 2:\r\n query = _b.sent();\r\n assert(!!query, \"Query data for active target \" + targetId + \" not found\");\r\n return [4 /*yield*/, this.localStore.allocateQuery(query)];\r\n case 3:\r\n queryData = _b.sent();\r\n return [4 /*yield*/, this.initializeViewAndComputeSnapshot(queryData, \r\n /*current=*/ false)];\r\n case 4:\r\n _b.sent();\r\n this.remoteStore.listen(queryData);\r\n _b.label = 5;\r\n case 5:\r\n _i++;\r\n return [3 /*break*/, 1];\r\n case 6:\r\n _loop_2 = function (targetId) {\r\n var queryView;\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n queryView = this_1.queryViewsByTarget[targetId];\r\n if (!queryView) return [3 /*break*/, 2];\r\n return [4 /*yield*/, this_1.localStore\r\n .releaseQuery(queryView.query, /*keepPersistedQueryData=*/ false)\r\n .then(function () {\r\n _this.remoteStore.unlisten(targetId);\r\n _this.removeAndCleanupQuery(queryView);\r\n })\r\n .catch(ignoreIfPrimaryLeaseLoss)];\r\n case 1:\r\n _a.sent();\r\n _a.label = 2;\r\n case 2: return [2 /*return*/];\r\n }\r\n });\r\n };\r\n this_1 = this;\r\n _a = 0, removed_1 = removed;\r\n _b.label = 7;\r\n case 7:\r\n if (!(_a < removed_1.length)) return [3 /*break*/, 10];\r\n targetId = removed_1[_a];\r\n return [5 /*yield**/, _loop_2(targetId)];\r\n case 8:\r\n _b.sent();\r\n _b.label = 9;\r\n case 9:\r\n _a++;\r\n return [3 /*break*/, 7];\r\n case 10: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n // PORTING NOTE: Multi-tab only. In other clients, LocalStore is unaware of\r\n // the online state.\r\n SyncEngine.prototype.enableNetwork = function () {\r\n this.localStore.setNetworkEnabled(true);\r\n return this.remoteStore.enableNetwork();\r\n };\r\n // PORTING NOTE: Multi-tab only. In other clients, LocalStore is unaware of\r\n // the online state.\r\n SyncEngine.prototype.disableNetwork = function () {\r\n this.localStore.setNetworkEnabled(false);\r\n return this.remoteStore.disableNetwork();\r\n };\r\n SyncEngine.prototype.getRemoteKeysForTarget = function (targetId) {\r\n var limboResolution = this.limboResolutionsByTarget[targetId];\r\n if (limboResolution && limboResolution.receivedDocument) {\r\n return documentKeySet().add(limboResolution.key);\r\n }\r\n else {\r\n return this.queryViewsByTarget[targetId]\r\n ? this.queryViewsByTarget[targetId].view.syncedDocuments\r\n : documentKeySet();\r\n }\r\n };\r\n return SyncEngine;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Simple wrapper around a nullable UID. Mostly exists to make code more\r\n * readable.\r\n */\r\nvar User = /** @class */ (function () {\r\n function User(uid) {\r\n this.uid = uid;\r\n }\r\n User.prototype.isAuthenticated = function () {\r\n return this.uid != null;\r\n };\r\n /**\r\n * Returns a key representing this user, suitable for inclusion in a\r\n * dictionary.\r\n */\r\n User.prototype.toKey = function () {\r\n if (this.isAuthenticated()) {\r\n return 'uid:' + this.uid;\r\n }\r\n else {\r\n return 'anonymous-user';\r\n }\r\n };\r\n User.prototype.isEqual = function (otherUser) {\r\n return otherUser.uid === this.uid;\r\n };\r\n /** A user with a null UID. */\r\n User.UNAUTHENTICATED = new User(null);\r\n // TODO(mikelehen): Look into getting a proper uid-equivalent for\r\n // non-FirebaseAuth providers.\r\n User.GOOGLE_CREDENTIALS = new User('google-credentials-uid');\r\n User.FIRST_PARTY = new User('first-party-uid');\r\n return User;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2018 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar LOG_TAG$a = 'SharedClientState';\r\n// The format of the LocalStorage key that stores the client state is:\r\n// firestore_clients__\r\nvar CLIENT_STATE_KEY_PREFIX = 'firestore_clients';\r\n// The format of the WebStorage key that stores the mutation state is:\r\n// firestore_mutations__\r\n// (for unauthenticated users)\r\n// or: firestore_mutations___\r\n//\r\n// 'user_uid' is last to avoid needing to escape '_' characters that it might\r\n// contain.\r\nvar MUTATION_BATCH_KEY_PREFIX = 'firestore_mutations';\r\n// The format of the WebStorage key that stores a query target's metadata is:\r\n// firestore_targets__\r\nvar QUERY_TARGET_KEY_PREFIX = 'firestore_targets';\r\n// The WebStorage prefix that stores the primary tab's online state. The\r\n// format of the key is:\r\n// firestore_online_state_\r\nvar ONLINE_STATE_KEY_PREFIX = 'firestore_online_state';\r\n// The WebStorage key prefix for the key that stores the last sequence number allocated. The key\r\n// looks like 'firestore_sequence_number_'.\r\nvar SEQUENCE_NUMBER_KEY_PREFIX = 'firestore_sequence_number';\r\n/**\r\n * Holds the state of a mutation batch, including its user ID, batch ID and\r\n * whether the batch is 'pending', 'acknowledged' or 'rejected'.\r\n */\r\n// Visible for testing\r\nvar MutationMetadata = /** @class */ (function () {\r\n function MutationMetadata(user, batchId, state, error) {\r\n this.user = user;\r\n this.batchId = batchId;\r\n this.state = state;\r\n this.error = error;\r\n assert((error !== undefined) === (state === 'rejected'), \"MutationMetadata must contain an error iff state is 'rejected'\");\r\n }\r\n /**\r\n * Parses a MutationMetadata from its JSON representation in WebStorage.\r\n * Logs a warning and returns null if the format of the data is not valid.\r\n */\r\n MutationMetadata.fromWebStorageEntry = function (user, batchId, value) {\r\n var mutationBatch = JSON.parse(value);\r\n var validData = typeof mutationBatch === 'object' &&\r\n ['pending', 'acknowledged', 'rejected'].indexOf(mutationBatch.state) !==\r\n -1 &&\r\n (mutationBatch.error === undefined ||\r\n typeof mutationBatch.error === 'object');\r\n var firestoreError = undefined;\r\n if (validData && mutationBatch.error) {\r\n validData =\r\n typeof mutationBatch.error.message === 'string' &&\r\n typeof mutationBatch.error.code === 'string';\r\n if (validData) {\r\n firestoreError = new FirestoreError(mutationBatch.error.code, mutationBatch.error.message);\r\n }\r\n }\r\n if (validData) {\r\n return new MutationMetadata(user, batchId, mutationBatch.state, firestoreError);\r\n }\r\n else {\r\n error(LOG_TAG$a, \"Failed to parse mutation state for ID '\" + batchId + \"': \" + value);\r\n return null;\r\n }\r\n };\r\n MutationMetadata.prototype.toWebStorageJSON = function () {\r\n var batchMetadata = {\r\n state: this.state,\r\n updateTimeMs: Date.now() // Modify the existing value to trigger update.\r\n };\r\n if (this.error) {\r\n batchMetadata.error = {\r\n code: this.error.code,\r\n message: this.error.message\r\n };\r\n }\r\n return JSON.stringify(batchMetadata);\r\n };\r\n return MutationMetadata;\r\n}());\r\n/**\r\n * Holds the state of a query target, including its target ID and whether the\r\n * target is 'not-current', 'current' or 'rejected'.\r\n */\r\n// Visible for testing\r\nvar QueryTargetMetadata = /** @class */ (function () {\r\n function QueryTargetMetadata(targetId, state, error) {\r\n this.targetId = targetId;\r\n this.state = state;\r\n this.error = error;\r\n assert((error !== undefined) === (state === 'rejected'), \"QueryTargetMetadata must contain an error iff state is 'rejected'\");\r\n }\r\n /**\r\n * Parses a QueryTargetMetadata from its JSON representation in WebStorage.\r\n * Logs a warning and returns null if the format of the data is not valid.\r\n */\r\n QueryTargetMetadata.fromWebStorageEntry = function (targetId, value) {\r\n var targetState = JSON.parse(value);\r\n var validData = typeof targetState === 'object' &&\r\n ['not-current', 'current', 'rejected'].indexOf(targetState.state) !==\r\n -1 &&\r\n (targetState.error === undefined ||\r\n typeof targetState.error === 'object');\r\n var firestoreError = undefined;\r\n if (validData && targetState.error) {\r\n validData =\r\n typeof targetState.error.message === 'string' &&\r\n typeof targetState.error.code === 'string';\r\n if (validData) {\r\n firestoreError = new FirestoreError(targetState.error.code, targetState.error.message);\r\n }\r\n }\r\n if (validData) {\r\n return new QueryTargetMetadata(targetId, targetState.state, firestoreError);\r\n }\r\n else {\r\n error(LOG_TAG$a, \"Failed to parse target state for ID '\" + targetId + \"': \" + value);\r\n return null;\r\n }\r\n };\r\n QueryTargetMetadata.prototype.toWebStorageJSON = function () {\r\n var targetState = {\r\n state: this.state,\r\n updateTimeMs: Date.now() // Modify the existing value to trigger update.\r\n };\r\n if (this.error) {\r\n targetState.error = {\r\n code: this.error.code,\r\n message: this.error.message\r\n };\r\n }\r\n return JSON.stringify(targetState);\r\n };\r\n return QueryTargetMetadata;\r\n}());\r\n/**\r\n * This class represents the immutable ClientState for a client read from\r\n * WebStorage, containing the list of active query targets.\r\n */\r\nvar RemoteClientState = /** @class */ (function () {\r\n function RemoteClientState(clientId, activeTargetIds) {\r\n this.clientId = clientId;\r\n this.activeTargetIds = activeTargetIds;\r\n }\r\n /**\r\n * Parses a RemoteClientState from the JSON representation in WebStorage.\r\n * Logs a warning and returns null if the format of the data is not valid.\r\n */\r\n RemoteClientState.fromWebStorageEntry = function (clientId, value) {\r\n var clientState = JSON.parse(value);\r\n var validData = typeof clientState === 'object' &&\r\n clientState.activeTargetIds instanceof Array;\r\n var activeTargetIdsSet = targetIdSet();\r\n for (var i = 0; validData && i < clientState.activeTargetIds.length; ++i) {\r\n validData = isSafeInteger(clientState.activeTargetIds[i]);\r\n activeTargetIdsSet = activeTargetIdsSet.add(clientState.activeTargetIds[i]);\r\n }\r\n if (validData) {\r\n return new RemoteClientState(clientId, activeTargetIdsSet);\r\n }\r\n else {\r\n error(LOG_TAG$a, \"Failed to parse client data for instance '\" + clientId + \"': \" + value);\r\n return null;\r\n }\r\n };\r\n return RemoteClientState;\r\n}());\r\n/**\r\n * This class represents the online state for all clients participating in\r\n * multi-tab. The online state is only written to by the primary client, and\r\n * used in secondary clients to update their query views.\r\n */\r\nvar SharedOnlineState = /** @class */ (function () {\r\n function SharedOnlineState(clientId, onlineState) {\r\n this.clientId = clientId;\r\n this.onlineState = onlineState;\r\n }\r\n /**\r\n * Parses a SharedOnlineState from its JSON representation in WebStorage.\r\n * Logs a warning and returns null if the format of the data is not valid.\r\n */\r\n SharedOnlineState.fromWebStorageEntry = function (value) {\r\n var onlineState = JSON.parse(value);\r\n var validData = typeof onlineState === 'object' &&\r\n OnlineState[onlineState.onlineState] !== undefined &&\r\n typeof onlineState.clientId === 'string';\r\n if (validData) {\r\n return new SharedOnlineState(onlineState.clientId, OnlineState[onlineState.onlineState]);\r\n }\r\n else {\r\n error(LOG_TAG$a, \"Failed to parse online state: \" + value);\r\n return null;\r\n }\r\n };\r\n return SharedOnlineState;\r\n}());\r\n/**\r\n * Metadata state of the local client. Unlike `RemoteClientState`, this class is\r\n * mutable and keeps track of all pending mutations, which allows us to\r\n * update the range of pending mutation batch IDs as new mutations are added or\r\n * removed.\r\n *\r\n * The data in `LocalClientState` is not read from WebStorage and instead\r\n * updated via its instance methods. The updated state can be serialized via\r\n * `toWebStorageJSON()`.\r\n */\r\n// Visible for testing.\r\nvar LocalClientState = /** @class */ (function () {\r\n function LocalClientState() {\r\n this.activeTargetIds = targetIdSet();\r\n }\r\n LocalClientState.prototype.addQueryTarget = function (targetId) {\r\n assert(!this.activeTargetIds.has(targetId), \"Target with ID '\" + targetId + \"' already active.\");\r\n this.activeTargetIds = this.activeTargetIds.add(targetId);\r\n };\r\n LocalClientState.prototype.removeQueryTarget = function (targetId) {\r\n this.activeTargetIds = this.activeTargetIds.delete(targetId);\r\n };\r\n /**\r\n * Converts this entry into a JSON-encoded format we can use for WebStorage.\r\n * Does not encode `clientId` as it is part of the key in WebStorage.\r\n */\r\n LocalClientState.prototype.toWebStorageJSON = function () {\r\n var data = {\r\n activeTargetIds: this.activeTargetIds.toArray(),\r\n updateTimeMs: Date.now() // Modify the existing value to trigger update.\r\n };\r\n return JSON.stringify(data);\r\n };\r\n return LocalClientState;\r\n}());\r\n/**\r\n * `WebStorageSharedClientState` uses WebStorage (window.localStorage) as the\r\n * backing store for the SharedClientState. It keeps track of all active\r\n * clients and supports modifications of the local client's data.\r\n */\r\nvar WebStorageSharedClientState = /** @class */ (function () {\r\n function WebStorageSharedClientState(queue, platform, persistenceKey, localClientId, initialUser) {\r\n this.queue = queue;\r\n this.platform = platform;\r\n this.persistenceKey = persistenceKey;\r\n this.localClientId = localClientId;\r\n this.syncEngine = null;\r\n this.onlineStateHandler = null;\r\n this.sequenceNumberHandler = null;\r\n this.activeClients = {};\r\n this.storageListener = this.handleWebStorageEvent.bind(this);\r\n this.started = false;\r\n /**\r\n * Captures WebStorage events that occur before `start()` is called. These\r\n * events are replayed once `WebStorageSharedClientState` is started.\r\n */\r\n this.earlyEvents = [];\r\n if (!WebStorageSharedClientState.isAvailable(this.platform)) {\r\n throw new FirestoreError(Code.UNIMPLEMENTED, 'LocalStorage is not available on this platform.');\r\n }\r\n // Escape the special characters mentioned here:\r\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions\r\n var escapedPersistenceKey = persistenceKey.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\r\n this.storage = this.platform.window.localStorage;\r\n this.currentUser = initialUser;\r\n this.localClientStorageKey = this.toWebStorageClientStateKey(this.localClientId);\r\n this.sequenceNumberKey = SEQUENCE_NUMBER_KEY_PREFIX + \"_\" + persistenceKey;\r\n this.activeClients[this.localClientId] = new LocalClientState();\r\n this.clientStateKeyRe = new RegExp(\"^\" + CLIENT_STATE_KEY_PREFIX + \"_\" + escapedPersistenceKey + \"_([^_]*)$\");\r\n this.mutationBatchKeyRe = new RegExp(\"^\" + MUTATION_BATCH_KEY_PREFIX + \"_\" + escapedPersistenceKey + \"_(\\\\d+)(?:_(.*))?$\");\r\n this.queryTargetKeyRe = new RegExp(\"^\" + QUERY_TARGET_KEY_PREFIX + \"_\" + escapedPersistenceKey + \"_(\\\\d+)$\");\r\n this.onlineStateKey = ONLINE_STATE_KEY_PREFIX + \"_\" + persistenceKey;\r\n // Rather than adding the storage observer during start(), we add the\r\n // storage observer during initialization. This ensures that we collect\r\n // events before other components populate their initial state (during their\r\n // respective start() calls). Otherwise, we might for example miss a\r\n // mutation that is added after LocalStore's start() processed the existing\r\n // mutations but before we observe WebStorage events.\r\n this.platform.window.addEventListener('storage', this.storageListener);\r\n }\r\n /** Returns 'true' if WebStorage is available in the current environment. */\r\n WebStorageSharedClientState.isAvailable = function (platform) {\r\n return !!(platform.window && platform.window.localStorage != null);\r\n };\r\n WebStorageSharedClientState.prototype.start = function () {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n var existingClients, _i, existingClients_1, clientId, storageItem, clientState, onlineStateJSON, onlineState, _a, _b, event_1;\r\n var _this = this;\r\n return tslib_1.__generator(this, function (_c) {\r\n switch (_c.label) {\r\n case 0:\r\n assert(!this.started, 'WebStorageSharedClientState already started');\r\n assert(this.syncEngine !== null, 'syncEngine property must be set before calling start()');\r\n assert(this.onlineStateHandler !== null, 'onlineStateHandler property must be set before calling start()');\r\n return [4 /*yield*/, this.syncEngine.getActiveClients()];\r\n case 1:\r\n existingClients = _c.sent();\r\n for (_i = 0, existingClients_1 = existingClients; _i < existingClients_1.length; _i++) {\r\n clientId = existingClients_1[_i];\r\n if (clientId === this.localClientId) {\r\n continue;\r\n }\r\n storageItem = this.getItem(this.toWebStorageClientStateKey(clientId));\r\n if (storageItem) {\r\n clientState = RemoteClientState.fromWebStorageEntry(clientId, storageItem);\r\n if (clientState) {\r\n this.activeClients[clientState.clientId] = clientState;\r\n }\r\n }\r\n }\r\n this.persistClientState();\r\n onlineStateJSON = this.storage.getItem(this.onlineStateKey);\r\n if (onlineStateJSON) {\r\n onlineState = this.fromWebStorageOnlineState(onlineStateJSON);\r\n if (onlineState) {\r\n this.handleOnlineStateEvent(onlineState);\r\n }\r\n }\r\n for (_a = 0, _b = this.earlyEvents; _a < _b.length; _a++) {\r\n event_1 = _b[_a];\r\n this.handleWebStorageEvent(event_1);\r\n }\r\n this.earlyEvents = [];\r\n // Register a window unload hook to remove the client metadata entry from\r\n // WebStorage even if `shutdown()` was not called.\r\n this.platform.window.addEventListener('unload', function () { return _this.shutdown(); });\r\n this.started = true;\r\n return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n WebStorageSharedClientState.prototype.writeSequenceNumber = function (sequenceNumber) {\r\n this.setItem(this.sequenceNumberKey, JSON.stringify(sequenceNumber));\r\n };\r\n WebStorageSharedClientState.prototype.getAllActiveQueryTargets = function () {\r\n var activeTargets = targetIdSet();\r\n forEach(this.activeClients, function (key, value) {\r\n activeTargets = activeTargets.unionWith(value.activeTargetIds);\r\n });\r\n return activeTargets;\r\n };\r\n WebStorageSharedClientState.prototype.isActiveQueryTarget = function (targetId) {\r\n // This is not using `obj.forEach` since `forEach` doesn't support early\r\n // return.\r\n for (var clientId in this.activeClients) {\r\n if (this.activeClients.hasOwnProperty(clientId)) {\r\n if (this.activeClients[clientId].activeTargetIds.has(targetId)) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n };\r\n WebStorageSharedClientState.prototype.addPendingMutation = function (batchId) {\r\n this.persistMutationState(batchId, 'pending');\r\n };\r\n WebStorageSharedClientState.prototype.updateMutationState = function (batchId, state, error) {\r\n this.persistMutationState(batchId, state, error);\r\n // Once a final mutation result is observed by other clients, they no longer\r\n // access the mutation's metadata entry. Since WebStorage replays events\r\n // in order, it is safe to delete the entry right after updating it.\r\n this.removeMutationState(batchId);\r\n };\r\n WebStorageSharedClientState.prototype.addLocalQueryTarget = function (targetId) {\r\n var queryState = 'not-current';\r\n // Lookup an existing query state if the target ID was already registered\r\n // by another tab\r\n if (this.isActiveQueryTarget(targetId)) {\r\n var storageItem = this.storage.getItem(this.toWebStorageQueryTargetMetadataKey(targetId));\r\n if (storageItem) {\r\n var metadata = QueryTargetMetadata.fromWebStorageEntry(targetId, storageItem);\r\n if (metadata) {\r\n queryState = metadata.state;\r\n }\r\n }\r\n }\r\n this.localClientState.addQueryTarget(targetId);\r\n this.persistClientState();\r\n return queryState;\r\n };\r\n WebStorageSharedClientState.prototype.removeLocalQueryTarget = function (targetId) {\r\n this.localClientState.removeQueryTarget(targetId);\r\n this.persistClientState();\r\n };\r\n WebStorageSharedClientState.prototype.isLocalQueryTarget = function (targetId) {\r\n return this.localClientState.activeTargetIds.has(targetId);\r\n };\r\n WebStorageSharedClientState.prototype.clearQueryState = function (targetId) {\r\n this.removeItem(this.toWebStorageQueryTargetMetadataKey(targetId));\r\n };\r\n WebStorageSharedClientState.prototype.updateQueryState = function (targetId, state, error) {\r\n this.persistQueryTargetState(targetId, state, error);\r\n };\r\n WebStorageSharedClientState.prototype.handleUserChange = function (user, removedBatchIds, addedBatchIds) {\r\n var _this = this;\r\n removedBatchIds.forEach(function (batchId) {\r\n _this.removeMutationState(batchId);\r\n });\r\n this.currentUser = user;\r\n addedBatchIds.forEach(function (batchId) {\r\n _this.addPendingMutation(batchId);\r\n });\r\n };\r\n WebStorageSharedClientState.prototype.setOnlineState = function (onlineState) {\r\n this.persistOnlineState(onlineState);\r\n };\r\n WebStorageSharedClientState.prototype.shutdown = function () {\r\n if (this.started) {\r\n this.platform.window.removeEventListener('storage', this.storageListener);\r\n this.removeItem(this.localClientStorageKey);\r\n this.started = false;\r\n }\r\n };\r\n WebStorageSharedClientState.prototype.getItem = function (key) {\r\n var value = this.storage.getItem(key);\r\n debug(LOG_TAG$a, 'READ', key, value);\r\n return value;\r\n };\r\n WebStorageSharedClientState.prototype.setItem = function (key, value) {\r\n debug(LOG_TAG$a, 'SET', key, value);\r\n this.storage.setItem(key, value);\r\n };\r\n WebStorageSharedClientState.prototype.removeItem = function (key) {\r\n debug(LOG_TAG$a, 'REMOVE', key);\r\n this.storage.removeItem(key);\r\n };\r\n WebStorageSharedClientState.prototype.handleWebStorageEvent = function (event) {\r\n var _this = this;\r\n if (event.storageArea === this.storage) {\r\n debug(LOG_TAG$a, 'EVENT', event.key, event.newValue);\r\n if (event.key === this.localClientStorageKey) {\r\n error('Received WebStorage notification for local change. Another client might have ' +\r\n 'garbage-collected our state');\r\n return;\r\n }\r\n this.queue.enqueueAndForget(function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {\r\n var clientState, clientId, mutationMetadata, queryTargetMetadata, onlineState, sequenceNumber;\r\n return tslib_1.__generator(this, function (_a) {\r\n if (!this.started) {\r\n this.earlyEvents.push(event);\r\n return [2 /*return*/];\r\n }\r\n if (event.key === null) {\r\n return [2 /*return*/];\r\n }\r\n if (this.clientStateKeyRe.test(event.key)) {\r\n if (event.newValue != null) {\r\n clientState = this.fromWebStorageClientState(event.key, event.newValue);\r\n if (clientState) {\r\n return [2 /*return*/, this.handleClientStateEvent(clientState.clientId, clientState)];\r\n }\r\n }\r\n else {\r\n clientId = this.fromWebStorageClientStateKey(event.key);\r\n return [2 /*return*/, this.handleClientStateEvent(clientId, null)];\r\n }\r\n }\r\n else if (this.mutationBatchKeyRe.test(event.key)) {\r\n if (event.newValue !== null) {\r\n mutationMetadata = this.fromWebStorageMutationMetadata(event.key, event.newValue);\r\n if (mutationMetadata) {\r\n return [2 /*return*/, this.handleMutationBatchEvent(mutationMetadata)];\r\n }\r\n }\r\n }\r\n else if (this.queryTargetKeyRe.test(event.key)) {\r\n if (event.newValue !== null) {\r\n queryTargetMetadata = this.fromWebStorageQueryTargetMetadata(event.key, event.newValue);\r\n if (queryTargetMetadata) {\r\n return [2 /*return*/, this.handleQueryTargetEvent(queryTargetMetadata)];\r\n }\r\n }\r\n }\r\n else if (event.key === this.onlineStateKey) {\r\n if (event.newValue !== null) {\r\n onlineState = this.fromWebStorageOnlineState(event.newValue);\r\n if (onlineState) {\r\n return [2 /*return*/, this.handleOnlineStateEvent(onlineState)];\r\n }\r\n }\r\n }\r\n else if (event.key === this.sequenceNumberKey) {\r\n assert(!!this.sequenceNumberHandler, 'Missing sequenceNumberHandler');\r\n sequenceNumber = fromWebStorageSequenceNumber(event.newValue);\r\n if (sequenceNumber !== ListenSequence.INVALID) {\r\n this.sequenceNumberHandler(sequenceNumber);\r\n }\r\n }\r\n return [2 /*return*/];\r\n });\r\n }); });\r\n }\r\n };\r\n Object.defineProperty(WebStorageSharedClientState.prototype, \"localClientState\", {\r\n get: function () {\r\n return this.activeClients[this.localClientId];\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n WebStorageSharedClientState.prototype.persistClientState = function () {\r\n this.setItem(this.localClientStorageKey, this.localClientState.toWebStorageJSON());\r\n };\r\n WebStorageSharedClientState.prototype.persistMutationState = function (batchId, state, error) {\r\n var mutationState = new MutationMetadata(this.currentUser, batchId, state, error);\r\n var mutationKey = this.toWebStorageMutationBatchKey(batchId);\r\n this.setItem(mutationKey, mutationState.toWebStorageJSON());\r\n };\r\n WebStorageSharedClientState.prototype.removeMutationState = function (batchId) {\r\n var mutationKey = this.toWebStorageMutationBatchKey(batchId);\r\n this.removeItem(mutationKey);\r\n };\r\n WebStorageSharedClientState.prototype.persistOnlineState = function (onlineState) {\r\n var entry = {\r\n clientId: this.localClientId,\r\n onlineState: OnlineState[onlineState]\r\n };\r\n this.storage.setItem(this.onlineStateKey, JSON.stringify(entry));\r\n };\r\n WebStorageSharedClientState.prototype.persistQueryTargetState = function (targetId, state, error) {\r\n var targetKey = this.toWebStorageQueryTargetMetadataKey(targetId);\r\n var targetMetadata = new QueryTargetMetadata(targetId, state, error);\r\n this.setItem(targetKey, targetMetadata.toWebStorageJSON());\r\n };\r\n /** Assembles the key for a client state in WebStorage */\r\n WebStorageSharedClientState.prototype.toWebStorageClientStateKey = function (clientId) {\r\n assert(clientId.indexOf('_') === -1, \"Client key cannot contain '_', but was '\" + clientId + \"'\");\r\n return CLIENT_STATE_KEY_PREFIX + \"_\" + this.persistenceKey + \"_\" + clientId;\r\n };\r\n /** Assembles the key for a query state in WebStorage */\r\n WebStorageSharedClientState.prototype.toWebStorageQueryTargetMetadataKey = function (targetId) {\r\n return QUERY_TARGET_KEY_PREFIX + \"_\" + this.persistenceKey + \"_\" + targetId;\r\n };\r\n /** Assembles the key for a mutation batch in WebStorage */\r\n WebStorageSharedClientState.prototype.toWebStorageMutationBatchKey = function (batchId) {\r\n var mutationKey = MUTATION_BATCH_KEY_PREFIX + \"_\" + this.persistenceKey + \"_\" + batchId;\r\n if (this.currentUser.isAuthenticated()) {\r\n mutationKey += \"_\" + this.currentUser.uid;\r\n }\r\n return mutationKey;\r\n };\r\n /**\r\n * Parses a client state key in WebStorage. Returns null if the key does not\r\n * match the expected key format.\r\n */\r\n WebStorageSharedClientState.prototype.fromWebStorageClientStateKey = function (key) {\r\n var match = this.clientStateKeyRe.exec(key);\r\n return match ? match[1] : null;\r\n };\r\n /**\r\n * Parses a client state in WebStorage. Returns 'null' if the value could not\r\n * be parsed.\r\n */\r\n WebStorageSharedClientState.prototype.fromWebStorageClientState = function (key, value) {\r\n var clientId = this.fromWebStorageClientStateKey(key);\r\n assert(clientId !== null, \"Cannot parse client state key '\" + key + \"'\");\r\n return RemoteClientState.fromWebStorageEntry(clientId, value);\r\n };\r\n /**\r\n * Parses a mutation batch state in WebStorage. Returns 'null' if the value\r\n * could not be parsed.\r\n */\r\n WebStorageSharedClientState.prototype.fromWebStorageMutationMetadata = function (key, value) {\r\n var match = this.mutationBatchKeyRe.exec(key);\r\n assert(match !== null, \"Cannot parse mutation batch key '\" + key + \"'\");\r\n var batchId = Number(match[1]);\r\n var userId = match[2] !== undefined ? match[2] : null;\r\n return MutationMetadata.fromWebStorageEntry(new User(userId), batchId, value);\r\n };\r\n /**\r\n * Parses a query target state from WebStorage. Returns 'null' if the value\r\n * could not be parsed.\r\n */\r\n WebStorageSharedClientState.prototype.fromWebStorageQueryTargetMetadata = function (key, value) {\r\n var match = this.queryTargetKeyRe.exec(key);\r\n assert(match !== null, \"Cannot parse query target key '\" + key + \"'\");\r\n var targetId = Number(match[1]);\r\n return QueryTargetMetadata.fromWebStorageEntry(targetId, value);\r\n };\r\n /**\r\n * Parses an online state from WebStorage. Returns 'null' if the value\r\n * could not be parsed.\r\n */\r\n WebStorageSharedClientState.prototype.fromWebStorageOnlineState = function (value) {\r\n return SharedOnlineState.fromWebStorageEntry(value);\r\n };\r\n WebStorageSharedClientState.prototype.handleMutationBatchEvent = function (mutationBatch) {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n return tslib_1.__generator(this, function (_a) {\r\n if (mutationBatch.user.uid !== this.currentUser.uid) {\r\n debug(LOG_TAG$a, \"Ignoring mutation for non-active user \" + mutationBatch.user.uid);\r\n return [2 /*return*/];\r\n }\r\n return [2 /*return*/, this.syncEngine.applyBatchState(mutationBatch.batchId, mutationBatch.state, mutationBatch.error)];\r\n });\r\n });\r\n };\r\n WebStorageSharedClientState.prototype.handleQueryTargetEvent = function (targetMetadata) {\r\n return this.syncEngine.applyTargetState(targetMetadata.targetId, targetMetadata.state, targetMetadata.error);\r\n };\r\n WebStorageSharedClientState.prototype.handleClientStateEvent = function (clientId, clientState) {\r\n var _this = this;\r\n var existingTargets = this.getAllActiveQueryTargets();\r\n if (clientState) {\r\n this.activeClients[clientId] = clientState;\r\n }\r\n else {\r\n delete this.activeClients[clientId];\r\n }\r\n var newTargets = this.getAllActiveQueryTargets();\r\n var addedTargets = [];\r\n var removedTargets = [];\r\n newTargets.forEach(function (targetId) { return tslib_1.__awaiter(_this, void 0, void 0, function () {\r\n return tslib_1.__generator(this, function (_a) {\r\n if (!existingTargets.has(targetId)) {\r\n addedTargets.push(targetId);\r\n }\r\n return [2 /*return*/];\r\n });\r\n }); });\r\n existingTargets.forEach(function (targetId) { return tslib_1.__awaiter(_this, void 0, void 0, function () {\r\n return tslib_1.__generator(this, function (_a) {\r\n if (!newTargets.has(targetId)) {\r\n removedTargets.push(targetId);\r\n }\r\n return [2 /*return*/];\r\n });\r\n }); });\r\n return this.syncEngine.applyActiveTargetsChange(addedTargets, removedTargets);\r\n };\r\n WebStorageSharedClientState.prototype.handleOnlineStateEvent = function (onlineState) {\r\n // We check whether the client that wrote this online state is still active\r\n // by comparing its client ID to the list of clients kept active in\r\n // IndexedDb. If a client does not update their IndexedDb client state\r\n // within 5 seconds, it is considered inactive and we don't emit an online\r\n // state event.\r\n if (this.activeClients[onlineState.clientId]) {\r\n this.onlineStateHandler(onlineState.onlineState);\r\n }\r\n };\r\n return WebStorageSharedClientState;\r\n}());\r\nfunction fromWebStorageSequenceNumber(seqString) {\r\n var sequenceNumber = ListenSequence.INVALID;\r\n if (seqString != null) {\r\n try {\r\n var parsed = JSON.parse(seqString);\r\n assert(typeof parsed === 'number', 'Found non-numeric sequence number');\r\n sequenceNumber = parsed;\r\n }\r\n catch (e) {\r\n error(LOG_TAG$a, 'Failed to read sequence number from WebStorage', e);\r\n }\r\n }\r\n return sequenceNumber;\r\n}\r\n/**\r\n * `MemorySharedClientState` is a simple implementation of SharedClientState for\r\n * clients using memory persistence. The state in this class remains fully\r\n * isolated and no synchronization is performed.\r\n */\r\nvar MemorySharedClientState = /** @class */ (function () {\r\n function MemorySharedClientState() {\r\n this.localState = new LocalClientState();\r\n this.queryState = {};\r\n this.syncEngine = null;\r\n this.onlineStateHandler = null;\r\n this.sequenceNumberHandler = null;\r\n }\r\n MemorySharedClientState.prototype.addPendingMutation = function (batchId) {\r\n // No op.\r\n };\r\n MemorySharedClientState.prototype.updateMutationState = function (batchId, state, error) {\r\n // No op.\r\n };\r\n MemorySharedClientState.prototype.addLocalQueryTarget = function (targetId) {\r\n this.localState.addQueryTarget(targetId);\r\n return this.queryState[targetId] || 'not-current';\r\n };\r\n MemorySharedClientState.prototype.updateQueryState = function (targetId, state, error) {\r\n this.queryState[targetId] = state;\r\n };\r\n MemorySharedClientState.prototype.removeLocalQueryTarget = function (targetId) {\r\n this.localState.removeQueryTarget(targetId);\r\n };\r\n MemorySharedClientState.prototype.isLocalQueryTarget = function (targetId) {\r\n return this.localState.activeTargetIds.has(targetId);\r\n };\r\n MemorySharedClientState.prototype.clearQueryState = function (targetId) {\r\n delete this.queryState[targetId];\r\n };\r\n MemorySharedClientState.prototype.getAllActiveQueryTargets = function () {\r\n return this.localState.activeTargetIds;\r\n };\r\n MemorySharedClientState.prototype.isActiveQueryTarget = function (targetId) {\r\n return this.localState.activeTargetIds.has(targetId);\r\n };\r\n MemorySharedClientState.prototype.start = function () {\r\n this.localState = new LocalClientState();\r\n return Promise.resolve();\r\n };\r\n MemorySharedClientState.prototype.handleUserChange = function (user, removedBatchIds, addedBatchIds) {\r\n // No op.\r\n };\r\n MemorySharedClientState.prototype.setOnlineState = function (onlineState) {\r\n // No op.\r\n };\r\n MemorySharedClientState.prototype.shutdown = function () { };\r\n MemorySharedClientState.prototype.writeSequenceNumber = function (sequenceNumber) { };\r\n return MemorySharedClientState;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar LOG_TAG$b = 'FirestoreClient';\r\n/** The DOMException code for an aborted operation. */\r\nvar DOM_EXCEPTION_ABORTED = 20;\r\n/** The DOMException code for quota exceeded. */\r\nvar DOM_EXCEPTION_QUOTA_EXCEEDED = 22;\r\nvar IndexedDbPersistenceSettings = /** @class */ (function () {\r\n function IndexedDbPersistenceSettings(cacheSizeBytes, experimentalTabSynchronization) {\r\n this.cacheSizeBytes = cacheSizeBytes;\r\n this.experimentalTabSynchronization = experimentalTabSynchronization;\r\n }\r\n IndexedDbPersistenceSettings.prototype.lruParams = function () {\r\n return LruParams.withCacheSize(this.cacheSizeBytes);\r\n };\r\n return IndexedDbPersistenceSettings;\r\n}());\r\nvar MemoryPersistenceSettings = /** @class */ (function () {\r\n function MemoryPersistenceSettings() {\r\n }\r\n return MemoryPersistenceSettings;\r\n}());\r\n/**\r\n * FirestoreClient is a top-level class that constructs and owns all of the\r\n * pieces of the client SDK architecture. It is responsible for creating the\r\n * async queue that is shared by all of the other components in the system.\r\n */\r\nvar FirestoreClient = /** @class */ (function () {\r\n function FirestoreClient(platform, databaseInfo, credentials, \r\n /**\r\n * Asynchronous queue responsible for all of our internal processing. When\r\n * we get incoming work from the user (via public API) or the network\r\n * (incoming GRPC messages), we should always schedule onto this queue.\r\n * This ensures all of our work is properly serialized (e.g. we don't\r\n * start processing a new operation while the previous one is waiting for\r\n * an async I/O to complete).\r\n */\r\n asyncQueue) {\r\n this.platform = platform;\r\n this.databaseInfo = databaseInfo;\r\n this.credentials = credentials;\r\n this.asyncQueue = asyncQueue;\r\n this.clientId = AutoId.newId();\r\n this.isShutdown = false;\r\n }\r\n /**\r\n * Starts up the FirestoreClient, returning only whether or not enabling\r\n * persistence succeeded.\r\n *\r\n * The intent here is to \"do the right thing\" as far as users are concerned.\r\n * Namely, in cases where offline persistence is requested and possible,\r\n * enable it, but otherwise fall back to persistence disabled. For the most\r\n * part we expect this to succeed one way or the other so we don't expect our\r\n * users to actually wait on the firestore.enablePersistence Promise since\r\n * they generally won't care.\r\n *\r\n * Of course some users actually do care about whether or not persistence\r\n * was successfully enabled, so the Promise returned from this method\r\n * indicates this outcome.\r\n *\r\n * This presents a problem though: even before enablePersistence resolves or\r\n * rejects, users may have made calls to e.g. firestore.collection() which\r\n * means that the FirestoreClient in there will be available and will be\r\n * enqueuing actions on the async queue.\r\n *\r\n * Meanwhile any failure of an operation on the async queue causes it to\r\n * panic and reject any further work, on the premise that unhandled errors\r\n * are fatal.\r\n *\r\n * Consequently the fallback is handled internally here in start, and if the\r\n * fallback succeeds we signal success to the async queue even though the\r\n * start() itself signals failure.\r\n *\r\n * @param persistenceSettings Settings object to configure offline\r\n * persistence.\r\n * @returns A deferred result indicating the user-visible result of enabling\r\n * offline persistence. This method will reject this if IndexedDB fails to\r\n * start for any reason. If usePersistence is false this is\r\n * unconditionally resolved.\r\n */\r\n FirestoreClient.prototype.start = function (persistenceSettings) {\r\n var _this = this;\r\n this.verifyNotShutdown();\r\n // We defer our initialization until we get the current user from\r\n // setChangeListener(). We block the async queue until we got the initial\r\n // user and the initialization is completed. This will prevent any scheduled\r\n // work from happening before initialization is completed.\r\n //\r\n // If initializationDone resolved then the FirestoreClient is in a usable\r\n // state.\r\n var initializationDone = new Deferred();\r\n // If usePersistence is true, certain classes of errors while starting are\r\n // recoverable but only by falling back to persistence disabled.\r\n //\r\n // If there's an error in the first case but not in recovery we cannot\r\n // reject the promise blocking the async queue because this will cause the\r\n // async queue to panic.\r\n var persistenceResult = new Deferred();\r\n var initialized = false;\r\n this.credentials.setChangeListener(function (user) {\r\n if (!initialized) {\r\n initialized = true;\r\n _this.initializePersistence(persistenceSettings, persistenceResult, user)\r\n .then(function (maybeLruGc) { return _this.initializeRest(user, maybeLruGc); })\r\n .then(initializationDone.resolve, initializationDone.reject);\r\n }\r\n else {\r\n _this.asyncQueue.enqueueAndForget(function () {\r\n return _this.handleCredentialChange(user);\r\n });\r\n }\r\n });\r\n // Block the async queue until initialization is done\r\n this.asyncQueue.enqueueAndForget(function () {\r\n return initializationDone.promise;\r\n });\r\n // Return only the result of enabling persistence. Note that this does not\r\n // need to await the completion of initializationDone because the result of\r\n // this method should not reflect any other kind of failure to start.\r\n return persistenceResult.promise;\r\n };\r\n /** Enables the network connection and requeues all pending operations. */\r\n FirestoreClient.prototype.enableNetwork = function () {\r\n var _this = this;\r\n this.verifyNotShutdown();\r\n return this.asyncQueue.enqueue(function () {\r\n return _this.syncEngine.enableNetwork();\r\n });\r\n };\r\n /**\r\n * Initializes persistent storage, attempting to use IndexedDB if\r\n * usePersistence is true or memory-only if false.\r\n *\r\n * If IndexedDB fails because it's already open in another tab or because the\r\n * platform can't possibly support our implementation then this method rejects\r\n * the persistenceResult and falls back on memory-only persistence.\r\n *\r\n * @param persistenceSettings Settings object to configure offline persistence\r\n * @param persistenceResult A deferred result indicating the user-visible\r\n * result of enabling offline persistence. This method will reject this if\r\n * IndexedDB fails to start for any reason. If usePersistence is false\r\n * this is unconditionally resolved.\r\n * @returns a Promise indicating whether or not initialization should\r\n * continue, i.e. that one of the persistence implementations actually\r\n * succeeded.\r\n */\r\n FirestoreClient.prototype.initializePersistence = function (persistenceSettings, persistenceResult, user) {\r\n var _this = this;\r\n if (persistenceSettings instanceof IndexedDbPersistenceSettings) {\r\n return this.startIndexedDbPersistence(user, persistenceSettings)\r\n .then(function (maybeLruGc) {\r\n persistenceResult.resolve();\r\n return maybeLruGc;\r\n })\r\n .catch(function (error) {\r\n // Regardless of whether or not the retry succeeds, from an user\r\n // perspective, offline persistence has failed.\r\n persistenceResult.reject(error);\r\n // An unknown failure on the first stage shuts everything down.\r\n if (!_this.canFallback(error)) {\r\n throw error;\r\n }\r\n console.warn('Error enabling offline storage. Falling back to' +\r\n ' storage disabled: ' +\r\n error);\r\n return _this.startMemoryPersistence();\r\n });\r\n }\r\n else {\r\n // When usePersistence == false, enabling offline persistence is defined\r\n // to unconditionally succeed. This allows start() to have the same\r\n // signature for both cases, despite the fact that the returned promise\r\n // is only used in the enablePersistence call.\r\n persistenceResult.resolve();\r\n return this.startMemoryPersistence();\r\n }\r\n };\r\n /**\r\n * Decides whether the provided error allows us to gracefully disable\r\n * persistence (as opposed to crashing the client).\r\n */\r\n FirestoreClient.prototype.canFallback = function (error) {\r\n if (error instanceof FirestoreError) {\r\n return (error.code === Code.FAILED_PRECONDITION ||\r\n error.code === Code.UNIMPLEMENTED);\r\n }\r\n else if (typeof DOMException !== 'undefined' &&\r\n error instanceof DOMException) {\r\n // We fall back to memory persistence if we cannot write the primary\r\n // lease. This can happen can during a schema migration, or if we run out\r\n // of quota when we try to write the primary lease.\r\n // For both the `QuotaExceededError` and the `AbortError`, it is safe to\r\n // fall back to memory persistence since all modifications to IndexedDb\r\n // failed to commit.\r\n return (error.code === DOM_EXCEPTION_QUOTA_EXCEEDED ||\r\n error.code === DOM_EXCEPTION_ABORTED);\r\n }\r\n return true;\r\n };\r\n /**\r\n * Checks that the client has not been shutdown. Ensures that other methods on\r\n * this class cannot be called after the client is shutdown.\r\n */\r\n FirestoreClient.prototype.verifyNotShutdown = function () {\r\n if (this.isShutdown) {\r\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'The client has already been shutdown.');\r\n }\r\n };\r\n /**\r\n * Starts IndexedDB-based persistence.\r\n *\r\n * @returns A promise indicating success or failure.\r\n */\r\n FirestoreClient.prototype.startIndexedDbPersistence = function (user, settings) {\r\n var _this = this;\r\n // TODO(http://b/33384523): For now we just disable garbage collection\r\n // when persistence is enabled.\r\n var storagePrefix = IndexedDbPersistence.buildStoragePrefix(this.databaseInfo);\r\n // Opt to use proto3 JSON in case the platform doesn't support Uint8Array.\r\n var serializer = new JsonProtoSerializer(this.databaseInfo.databaseId, {\r\n useProto3Json: true\r\n });\r\n return Promise.resolve().then(function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {\r\n var persistence, lruParams;\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (settings.experimentalTabSynchronization &&\r\n !WebStorageSharedClientState.isAvailable(this.platform)) {\r\n throw new FirestoreError(Code.UNIMPLEMENTED, 'IndexedDB persistence is only available on platforms that support LocalStorage.');\r\n }\r\n lruParams = settings.lruParams();\r\n if (!settings.experimentalTabSynchronization) return [3 /*break*/, 2];\r\n this.sharedClientState = new WebStorageSharedClientState(this.asyncQueue, this.platform, storagePrefix, this.clientId, user);\r\n return [4 /*yield*/, IndexedDbPersistence.createMultiClientIndexedDbPersistence(storagePrefix, this.clientId, this.platform, this.asyncQueue, serializer, lruParams, { sequenceNumberSyncer: this.sharedClientState })];\r\n case 1:\r\n persistence = _a.sent();\r\n return [3 /*break*/, 4];\r\n case 2:\r\n this.sharedClientState = new MemorySharedClientState();\r\n return [4 /*yield*/, IndexedDbPersistence.createIndexedDbPersistence(storagePrefix, this.clientId, this.platform, this.asyncQueue, serializer, lruParams)];\r\n case 3:\r\n persistence = _a.sent();\r\n _a.label = 4;\r\n case 4:\r\n this.persistence = persistence;\r\n return [2 /*return*/, persistence.referenceDelegate.garbageCollector];\r\n }\r\n });\r\n }); });\r\n };\r\n /**\r\n * Starts Memory-backed persistence. In practice this cannot fail.\r\n *\r\n * @returns A promise that will successfully resolve.\r\n */\r\n FirestoreClient.prototype.startMemoryPersistence = function () {\r\n this.persistence = MemoryPersistence.createEagerPersistence(this.clientId);\r\n this.sharedClientState = new MemorySharedClientState();\r\n return Promise.resolve(null);\r\n };\r\n /**\r\n * Initializes the rest of the FirestoreClient, assuming the initial user\r\n * has been obtained from the credential provider and some persistence\r\n * implementation is available in this.persistence.\r\n */\r\n FirestoreClient.prototype.initializeRest = function (user, maybeLruGc) {\r\n var _this = this;\r\n debug(LOG_TAG$b, 'Initializing. user=', user.uid);\r\n return this.platform\r\n .loadConnection(this.databaseInfo)\r\n .then(function (connection) { return tslib_1.__awaiter(_this, void 0, void 0, function () {\r\n var serializer, datastore, remoteStoreOnlineStateChangedHandler, sharedClientStateOnlineStateChangedHandler;\r\n var _this = this;\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n this.localStore = new LocalStore(this.persistence, user);\r\n if (maybeLruGc) {\r\n // We're running LRU Garbage collection. Set up the scheduler.\r\n this.lruScheduler = new LruScheduler(maybeLruGc, this.asyncQueue, this.localStore);\r\n }\r\n serializer = this.platform.newSerializer(this.databaseInfo.databaseId);\r\n datastore = new Datastore(this.asyncQueue, connection, this.credentials, serializer);\r\n remoteStoreOnlineStateChangedHandler = function (onlineState) {\r\n return _this.syncEngine.applyOnlineStateChange(onlineState, OnlineStateSource.RemoteStore);\r\n };\r\n sharedClientStateOnlineStateChangedHandler = function (onlineState) {\r\n return _this.syncEngine.applyOnlineStateChange(onlineState, OnlineStateSource.SharedClientState);\r\n };\r\n this.remoteStore = new RemoteStore(this.localStore, datastore, this.asyncQueue, remoteStoreOnlineStateChangedHandler);\r\n this.syncEngine = new SyncEngine(this.localStore, this.remoteStore, this.sharedClientState, user);\r\n this.sharedClientState.onlineStateHandler = sharedClientStateOnlineStateChangedHandler;\r\n // Set up wiring between sync engine and other components\r\n this.remoteStore.syncEngine = this.syncEngine;\r\n this.sharedClientState.syncEngine = this.syncEngine;\r\n this.eventMgr = new EventManager(this.syncEngine);\r\n // PORTING NOTE: LocalStore doesn't need an explicit start() on the Web.\r\n return [4 /*yield*/, this.sharedClientState.start()];\r\n case 1:\r\n // PORTING NOTE: LocalStore doesn't need an explicit start() on the Web.\r\n _a.sent();\r\n return [4 /*yield*/, this.remoteStore.start()];\r\n case 2:\r\n _a.sent();\r\n // NOTE: This will immediately call the listener, so we make sure to\r\n // set it after localStore / remoteStore are started.\r\n return [4 /*yield*/, this.persistence.setPrimaryStateListener(function (isPrimary) { return tslib_1.__awaiter(_this, void 0, void 0, function () {\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, this.syncEngine.applyPrimaryState(isPrimary)];\r\n case 1:\r\n _a.sent();\r\n if (this.lruScheduler) {\r\n if (isPrimary && !this.lruScheduler.started) {\r\n this.lruScheduler.start();\r\n }\r\n else if (!isPrimary) {\r\n this.lruScheduler.stop();\r\n }\r\n }\r\n return [2 /*return*/];\r\n }\r\n });\r\n }); })];\r\n case 3:\r\n // NOTE: This will immediately call the listener, so we make sure to\r\n // set it after localStore / remoteStore are started.\r\n _a.sent();\r\n return [2 /*return*/];\r\n }\r\n });\r\n }); });\r\n };\r\n FirestoreClient.prototype.handleCredentialChange = function (user) {\r\n this.asyncQueue.verifyOperationInProgress();\r\n debug(LOG_TAG$b, 'Credential Changed. Current user: ' + user.uid);\r\n return this.syncEngine.handleCredentialChange(user);\r\n };\r\n /** Disables the network connection. Pending operations will not complete. */\r\n FirestoreClient.prototype.disableNetwork = function () {\r\n var _this = this;\r\n this.verifyNotShutdown();\r\n return this.asyncQueue.enqueue(function () {\r\n return _this.syncEngine.disableNetwork();\r\n });\r\n };\r\n FirestoreClient.prototype.shutdown = function () {\r\n var _this = this;\r\n if (this.isShutdown === true) {\r\n return Promise.resolve();\r\n }\r\n return this.asyncQueue.enqueue(function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n // PORTING NOTE: LocalStore does not need an explicit shutdown on web.\r\n if (this.lruScheduler) {\r\n this.lruScheduler.stop();\r\n }\r\n return [4 /*yield*/, this.remoteStore.shutdown()];\r\n case 1:\r\n _a.sent();\r\n return [4 /*yield*/, this.sharedClientState.shutdown()];\r\n case 2:\r\n _a.sent();\r\n return [4 /*yield*/, this.persistence.shutdown()];\r\n case 3:\r\n _a.sent();\r\n // `removeChangeListener` must be called after shutting down the\r\n // RemoteStore as it will prevent the RemoteStore from retrieving\r\n // auth tokens.\r\n this.credentials.removeChangeListener();\r\n this.isShutdown = true;\r\n return [2 /*return*/];\r\n }\r\n });\r\n }); });\r\n };\r\n FirestoreClient.prototype.listen = function (query, observer, options) {\r\n var _this = this;\r\n this.verifyNotShutdown();\r\n var listener = new QueryListener(query, observer, options);\r\n this.asyncQueue.enqueueAndForget(function () {\r\n return _this.eventMgr.listen(listener);\r\n });\r\n return listener;\r\n };\r\n FirestoreClient.prototype.unlisten = function (listener) {\r\n var _this = this;\r\n this.verifyNotShutdown();\r\n this.asyncQueue.enqueueAndForget(function () {\r\n return _this.eventMgr.unlisten(listener);\r\n });\r\n };\r\n FirestoreClient.prototype.getDocumentFromLocalCache = function (docKey) {\r\n var _this = this;\r\n this.verifyNotShutdown();\r\n return this.asyncQueue\r\n .enqueue(function () {\r\n return _this.localStore.readDocument(docKey);\r\n })\r\n .then(function (maybeDoc) {\r\n if (maybeDoc instanceof Document) {\r\n return maybeDoc;\r\n }\r\n else if (maybeDoc instanceof NoDocument) {\r\n return null;\r\n }\r\n else {\r\n throw new FirestoreError(Code.UNAVAILABLE, 'Failed to get document from cache. (However, this document may ' +\r\n \"exist on the server. Run again without setting 'source' in \" +\r\n 'the GetOptions to attempt to retrieve the document from the ' +\r\n 'server.)');\r\n }\r\n });\r\n };\r\n FirestoreClient.prototype.getDocumentsFromLocalCache = function (query) {\r\n var _this = this;\r\n this.verifyNotShutdown();\r\n return this.asyncQueue\r\n .enqueue(function () {\r\n return _this.localStore.executeQuery(query);\r\n })\r\n .then(function (docs) {\r\n var remoteKeys = documentKeySet();\r\n var view = new View(query, remoteKeys);\r\n var viewDocChanges = view.computeDocChanges(docs);\r\n return view.applyChanges(viewDocChanges, \r\n /* updateLimboDocuments= */ false).snapshot;\r\n });\r\n };\r\n FirestoreClient.prototype.write = function (mutations) {\r\n var _this = this;\r\n this.verifyNotShutdown();\r\n var deferred = new Deferred();\r\n this.asyncQueue.enqueueAndForget(function () {\r\n return _this.syncEngine.write(mutations, deferred);\r\n });\r\n return deferred.promise;\r\n };\r\n FirestoreClient.prototype.databaseId = function () {\r\n return this.databaseInfo.databaseId;\r\n };\r\n FirestoreClient.prototype.transaction = function (updateFunction) {\r\n var _this = this;\r\n this.verifyNotShutdown();\r\n // We have to wait for the async queue to be sure syncEngine is initialized.\r\n return this.asyncQueue\r\n .enqueue(function () { return tslib_1.__awaiter(_this, void 0, void 0, function () { return tslib_1.__generator(this, function (_a) {\r\n return [2 /*return*/];\r\n }); }); })\r\n .then(function () { return _this.syncEngine.runTransaction(updateFunction); });\r\n };\r\n return FirestoreClient;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/*\r\n * A wrapper implementation of Observer that will dispatch events\r\n * asynchronously. To allow immediate silencing, a mute call is added which\r\n * causes events scheduled to no longer be raised.\r\n */\r\nvar AsyncObserver = /** @class */ (function () {\r\n function AsyncObserver(observer) {\r\n this.observer = observer;\r\n /**\r\n * When set to true, will not raise future events. Necessary to deal with\r\n * async detachment of listener.\r\n */\r\n this.muted = false;\r\n }\r\n AsyncObserver.prototype.next = function (value) {\r\n this.scheduleEvent(this.observer.next, value);\r\n };\r\n AsyncObserver.prototype.error = function (error) {\r\n this.scheduleEvent(this.observer.error, error);\r\n };\r\n AsyncObserver.prototype.mute = function () {\r\n this.muted = true;\r\n };\r\n AsyncObserver.prototype.scheduleEvent = function (eventHandler, event) {\r\n var _this = this;\r\n if (!this.muted) {\r\n setTimeout(function () {\r\n if (!_this.muted) {\r\n eventHandler(event);\r\n }\r\n }, 0);\r\n }\r\n };\r\n return AsyncObserver;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// The objects that are a part of this API are exposed to third-parties as\r\n// compiled javascript so we want to flag our private members with a leading\r\n// underscore to discourage their use.\r\n// tslint:disable:strip-private-property-underscore\r\n/**\r\n * A FieldPath refers to a field in a document. The path may consist of a single\r\n * field name (referring to a top-level field in the document), or a list of\r\n * field names (referring to a nested field in the document).\r\n */\r\nvar FieldPath$1 = /** @class */ (function () {\r\n /**\r\n * Creates a FieldPath from the provided field names. If more than one field\r\n * name is provided, the path will point to a nested field in a document.\r\n *\r\n * @param fieldNames A list of field names.\r\n */\r\n function FieldPath$1() {\r\n var fieldNames = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n fieldNames[_i] = arguments[_i];\r\n }\r\n validateNamedArrayAtLeastNumberOfElements('FieldPath', fieldNames, 'fieldNames', 1);\r\n for (var i = 0; i < fieldNames.length; ++i) {\r\n validateArgType('FieldPath', 'string', i, fieldNames[i]);\r\n if (fieldNames[i].length === 0) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field name at argument $(i + 1). \" +\r\n 'Field names must not be empty.');\r\n }\r\n }\r\n this._internalPath = new FieldPath(fieldNames);\r\n }\r\n FieldPath$1.documentId = function () {\r\n return FieldPath$1._DOCUMENT_ID;\r\n };\r\n FieldPath$1.prototype.isEqual = function (other) {\r\n if (!(other instanceof FieldPath$1)) {\r\n throw invalidClassError('isEqual', 'FieldPath', 1, other);\r\n }\r\n return this._internalPath.isEqual(other._internalPath);\r\n };\r\n /**\r\n * Internal Note: The backend doesn't technically support querying by\r\n * document ID. Instead it queries by the entire document name (full path\r\n * included), but in the cases we currently support documentId(), the net\r\n * effect is the same.\r\n */\r\n FieldPath$1._DOCUMENT_ID = new FieldPath$1(FieldPath.keyField().canonicalString());\r\n return FieldPath$1;\r\n}());\r\n/**\r\n * Matches any characters in a field path string that are reserved.\r\n */\r\nvar RESERVED = new RegExp('[~\\\\*/\\\\[\\\\]]');\r\n/**\r\n * Parses a field path string into a FieldPath, treating dots as separators.\r\n */\r\nfunction fromDotSeparatedString(path) {\r\n var found = path.search(RESERVED);\r\n if (found >= 0) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field path (\" + path + \"). Paths must not contain \" +\r\n \"'~', '*', '/', '[', or ']'\");\r\n }\r\n try {\r\n return new (FieldPath$1.bind.apply(FieldPath$1, [void 0].concat(path.split('.'))))();\r\n }\r\n catch (e) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field path (\" + path + \"). Paths must not be empty, \" +\r\n \"begin with '.', end with '.', or contain '..'\");\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar OAuthToken = /** @class */ (function () {\r\n function OAuthToken(value, user) {\r\n this.user = user;\r\n this.type = 'OAuth';\r\n this.authHeaders = { Authorization: \"Bearer \" + value };\r\n }\r\n return OAuthToken;\r\n}());\r\n/** A CredentialsProvider that always yields an empty token. */\r\nvar EmptyCredentialsProvider = /** @class */ (function () {\r\n function EmptyCredentialsProvider() {\r\n /**\r\n * Stores the listener registered with setChangeListener()\r\n * This isn't actually necessary since the UID never changes, but we use this\r\n * to verify the listen contract is adhered to in tests.\r\n */\r\n this.changeListener = null;\r\n }\r\n EmptyCredentialsProvider.prototype.getToken = function () {\r\n return Promise.resolve(null);\r\n };\r\n EmptyCredentialsProvider.prototype.invalidateToken = function () { };\r\n EmptyCredentialsProvider.prototype.setChangeListener = function (changeListener) {\r\n assert(!this.changeListener, 'Can only call setChangeListener() once.');\r\n this.changeListener = changeListener;\r\n // Fire with initial user.\r\n changeListener(User.UNAUTHENTICATED);\r\n };\r\n EmptyCredentialsProvider.prototype.removeChangeListener = function () {\r\n assert(this.changeListener !== null, 'removeChangeListener() when no listener registered');\r\n this.changeListener = null;\r\n };\r\n return EmptyCredentialsProvider;\r\n}());\r\nvar FirebaseCredentialsProvider = /** @class */ (function () {\r\n function FirebaseCredentialsProvider(app) {\r\n var _this = this;\r\n this.app = app;\r\n /**\r\n * The auth token listener registered with FirebaseApp, retained here so we\r\n * can unregister it.\r\n */\r\n this.tokenListener = null;\r\n /**\r\n * Counter used to detect if the token changed while a getToken request was\r\n * outstanding.\r\n */\r\n this.tokenCounter = 0;\r\n /** The listener registered with setChangeListener(). */\r\n this.changeListener = null;\r\n this.forceRefresh = false;\r\n this.tokenListener = function () {\r\n _this.tokenCounter++;\r\n _this.currentUser = _this.getUser();\r\n if (_this.changeListener) {\r\n _this.changeListener(_this.currentUser);\r\n }\r\n };\r\n this.tokenCounter = 0;\r\n // Will fire at least once where we set this.currentUser\r\n this.app.INTERNAL.addAuthTokenListener(this.tokenListener);\r\n }\r\n FirebaseCredentialsProvider.prototype.getToken = function () {\r\n var _this = this;\r\n assert(this.tokenListener != null, 'getToken cannot be called after listener removed.');\r\n // Take note of the current value of the tokenCounter so that this method\r\n // can fail (with an ABORTED error) if there is a token change while the\r\n // request is outstanding.\r\n var initialTokenCounter = this.tokenCounter;\r\n var forceRefresh = this.forceRefresh;\r\n this.forceRefresh = false;\r\n return this.app.INTERNAL.getToken(forceRefresh).then(function (tokenData) {\r\n // Cancel the request since the token changed while the request was\r\n // outstanding so the response is potentially for a previous user (which\r\n // user, we can't be sure).\r\n if (_this.tokenCounter !== initialTokenCounter) {\r\n throw new FirestoreError(Code.ABORTED, 'getToken aborted due to token change.');\r\n }\r\n else {\r\n if (tokenData) {\r\n assert(typeof tokenData.accessToken === 'string', 'Invalid tokenData returned from getToken():' + tokenData);\r\n return new OAuthToken(tokenData.accessToken, _this.currentUser);\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n });\r\n };\r\n FirebaseCredentialsProvider.prototype.invalidateToken = function () {\r\n this.forceRefresh = true;\r\n };\r\n FirebaseCredentialsProvider.prototype.setChangeListener = function (changeListener) {\r\n assert(!this.changeListener, 'Can only call setChangeListener() once.');\r\n this.changeListener = changeListener;\r\n // Fire the initial event, but only if we received the initial user\r\n if (this.currentUser) {\r\n changeListener(this.currentUser);\r\n }\r\n };\r\n FirebaseCredentialsProvider.prototype.removeChangeListener = function () {\r\n assert(this.tokenListener != null, 'removeChangeListener() called twice');\r\n assert(this.changeListener !== null, 'removeChangeListener() called when no listener registered');\r\n this.app.INTERNAL.removeAuthTokenListener(this.tokenListener);\r\n this.tokenListener = null;\r\n this.changeListener = null;\r\n };\r\n FirebaseCredentialsProvider.prototype.getUser = function () {\r\n var currentUid = this.app.INTERNAL.getUid();\r\n assert(currentUid === null || typeof currentUid === 'string', 'Received invalid UID: ' + currentUid);\r\n return new User(currentUid);\r\n };\r\n return FirebaseCredentialsProvider;\r\n}());\r\n/*\r\n * FirstPartyToken provides a fresh token each time its value\r\n * is requested, because if the token is too old, requests will be rejected.\r\n * Technically this may no longer be necessary since the SDK should gracefully\r\n * recover from unauthenticated errors (see b/33147818 for context), but it's\r\n * safer to keep the implementation as-is.\r\n */\r\nvar FirstPartyToken = /** @class */ (function () {\r\n function FirstPartyToken(gapi, sessionIndex) {\r\n this.gapi = gapi;\r\n this.sessionIndex = sessionIndex;\r\n this.type = 'FirstParty';\r\n this.user = User.FIRST_PARTY;\r\n }\r\n Object.defineProperty(FirstPartyToken.prototype, \"authHeaders\", {\r\n get: function () {\r\n var headers = {\r\n 'X-Goog-AuthUser': this.sessionIndex\r\n };\r\n var authHeader = this.gapi.auth.getAuthHeaderValueForFirstParty([]);\r\n if (authHeader) {\r\n headers['Authorization'] = authHeader;\r\n }\r\n return headers;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n return FirstPartyToken;\r\n}());\r\n/*\r\n * Provides user credentials required for the Firestore JavaScript SDK\r\n * to authenticate the user, using technique that is only available\r\n * to applications hosted by Google.\r\n */\r\nvar FirstPartyCredentialsProvider = /** @class */ (function () {\r\n function FirstPartyCredentialsProvider(gapi, sessionIndex) {\r\n this.gapi = gapi;\r\n this.sessionIndex = sessionIndex;\r\n }\r\n FirstPartyCredentialsProvider.prototype.getToken = function () {\r\n return Promise.resolve(new FirstPartyToken(this.gapi, this.sessionIndex));\r\n };\r\n FirstPartyCredentialsProvider.prototype.setChangeListener = function (changeListener) {\r\n // Fire with initial uid.\r\n changeListener(User.FIRST_PARTY);\r\n };\r\n FirstPartyCredentialsProvider.prototype.removeChangeListener = function () { };\r\n FirstPartyCredentialsProvider.prototype.invalidateToken = function () { };\r\n return FirstPartyCredentialsProvider;\r\n}());\r\n/**\r\n * Builds a CredentialsProvider depending on the type of\r\n * the credentials passed in.\r\n */\r\nfunction makeCredentialsProvider(credentials) {\r\n if (!credentials) {\r\n return new EmptyCredentialsProvider();\r\n }\r\n switch (credentials.type) {\r\n case 'gapi':\r\n var client = credentials.client;\r\n // Make sure this is a Gapi client.\r\n assert(!!(typeof client === 'object' &&\r\n client !== null &&\r\n client['auth'] &&\r\n client['auth']['getAuthHeaderValueForFirstParty']), 'unexpected gapi interface');\r\n return new FirstPartyCredentialsProvider(client, credentials.sessionIndex || '0');\r\n case 'provider':\r\n return credentials.client;\r\n default:\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'makeCredentialsProvider failed due to invalid credential type');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction isPartialObserver(obj) {\r\n return implementsAnyMethods(obj, ['next', 'error', 'complete']);\r\n}\r\n/**\r\n * Returns true if obj is an object and contains at least one of the specified\r\n * methods.\r\n */\r\nfunction implementsAnyMethods(obj, methods) {\r\n if (typeof obj !== 'object' || obj === null) {\r\n return false;\r\n }\r\n var object = obj;\r\n for (var _i = 0, methods_1 = methods; _i < methods_1.length; _i++) {\r\n var method = methods_1[_i];\r\n if (method in object && typeof object[method] === 'function') {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An opaque base class for FieldValue sentinel objects in our public API,\r\n * with public static methods for creating said sentinel objects.\r\n */\r\n// tslint:disable-next-line:class-as-namespace We use this as a base class.\r\nvar FieldValueImpl = /** @class */ (function () {\r\n function FieldValueImpl(_methodName) {\r\n this._methodName = _methodName;\r\n }\r\n FieldValueImpl.delete = function () {\r\n validateNoArgs('FieldValue.delete', arguments);\r\n return DeleteFieldValueImpl.instance;\r\n };\r\n FieldValueImpl.serverTimestamp = function () {\r\n validateNoArgs('FieldValue.serverTimestamp', arguments);\r\n return ServerTimestampFieldValueImpl.instance;\r\n };\r\n FieldValueImpl.arrayUnion = function () {\r\n var elements = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n elements[_i] = arguments[_i];\r\n }\r\n validateAtLeastNumberOfArgs('FieldValue.arrayUnion', arguments, 1);\r\n // NOTE: We don't actually parse the data until it's used in set() or\r\n // update() since we need access to the Firestore instance.\r\n return new ArrayUnionFieldValueImpl(elements);\r\n };\r\n FieldValueImpl.arrayRemove = function () {\r\n var elements = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n elements[_i] = arguments[_i];\r\n }\r\n validateAtLeastNumberOfArgs('FieldValue.arrayRemove', arguments, 1);\r\n // NOTE: We don't actually parse the data until it's used in set() or\r\n // update() since we need access to the Firestore instance.\r\n return new ArrayRemoveFieldValueImpl(elements);\r\n };\r\n FieldValueImpl.increment = function (n) {\r\n validateArgType('FieldValue.increment', 'number', 1, n);\r\n validateExactNumberOfArgs('FieldValue.increment', arguments, 1);\r\n return new NumericIncrementFieldValueImpl(n);\r\n };\r\n FieldValueImpl.prototype.isEqual = function (other) {\r\n return this === other;\r\n };\r\n return FieldValueImpl;\r\n}());\r\nvar DeleteFieldValueImpl = /** @class */ (function (_super) {\r\n tslib_1.__extends(DeleteFieldValueImpl, _super);\r\n function DeleteFieldValueImpl() {\r\n return _super.call(this, 'FieldValue.delete') || this;\r\n }\r\n /** Singleton instance. */\r\n DeleteFieldValueImpl.instance = new DeleteFieldValueImpl();\r\n return DeleteFieldValueImpl;\r\n}(FieldValueImpl));\r\nvar ServerTimestampFieldValueImpl = /** @class */ (function (_super) {\r\n tslib_1.__extends(ServerTimestampFieldValueImpl, _super);\r\n function ServerTimestampFieldValueImpl() {\r\n return _super.call(this, 'FieldValue.serverTimestamp') || this;\r\n }\r\n /** Singleton instance. */\r\n ServerTimestampFieldValueImpl.instance = new ServerTimestampFieldValueImpl();\r\n return ServerTimestampFieldValueImpl;\r\n}(FieldValueImpl));\r\nvar ArrayUnionFieldValueImpl = /** @class */ (function (_super) {\r\n tslib_1.__extends(ArrayUnionFieldValueImpl, _super);\r\n function ArrayUnionFieldValueImpl(_elements) {\r\n var _this = _super.call(this, 'FieldValue.arrayUnion') || this;\r\n _this._elements = _elements;\r\n return _this;\r\n }\r\n return ArrayUnionFieldValueImpl;\r\n}(FieldValueImpl));\r\nvar ArrayRemoveFieldValueImpl = /** @class */ (function (_super) {\r\n tslib_1.__extends(ArrayRemoveFieldValueImpl, _super);\r\n function ArrayRemoveFieldValueImpl(_elements) {\r\n var _this = _super.call(this, 'FieldValue.arrayRemove') || this;\r\n _this._elements = _elements;\r\n return _this;\r\n }\r\n return ArrayRemoveFieldValueImpl;\r\n}(FieldValueImpl));\r\nvar NumericIncrementFieldValueImpl = /** @class */ (function (_super) {\r\n tslib_1.__extends(NumericIncrementFieldValueImpl, _super);\r\n function NumericIncrementFieldValueImpl(_operand) {\r\n var _this = _super.call(this, 'FieldValue.increment') || this;\r\n _this._operand = _operand;\r\n return _this;\r\n }\r\n return NumericIncrementFieldValueImpl;\r\n}(FieldValueImpl));\r\n// Public instance that disallows construction at runtime. This constructor is\r\n// used when exporting FieldValueImpl on firebase.firestore.FieldValue and will\r\n// be called FieldValue publicly. Internally we still use FieldValueImpl which\r\n// has a type-checked private constructor. Note that FieldValueImpl and\r\n// PublicFieldValue can be used interchangeably in instanceof checks.\r\n// For our internal TypeScript code PublicFieldValue doesn't exist as a type,\r\n// and so we need to use FieldValueImpl as type and export it too.\r\n// tslint:disable-next-line:variable-name We treat this as a class name.\r\nvar PublicFieldValue = makeConstructorPrivate(FieldValueImpl, 'Use FieldValue.() instead.');\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar RESERVED_FIELD_REGEX = /^__.*__$/;\r\n/** The result of parsing document data (e.g. for a setData call). */\r\nvar ParsedSetData = /** @class */ (function () {\r\n function ParsedSetData(data, fieldMask, fieldTransforms) {\r\n this.data = data;\r\n this.fieldMask = fieldMask;\r\n this.fieldTransforms = fieldTransforms;\r\n }\r\n ParsedSetData.prototype.toMutations = function (key, precondition) {\r\n var mutations = [];\r\n if (this.fieldMask !== null) {\r\n mutations.push(new PatchMutation(key, this.data, this.fieldMask, precondition));\r\n }\r\n else {\r\n mutations.push(new SetMutation(key, this.data, precondition));\r\n }\r\n if (this.fieldTransforms.length > 0) {\r\n mutations.push(new TransformMutation(key, this.fieldTransforms));\r\n }\r\n return mutations;\r\n };\r\n return ParsedSetData;\r\n}());\r\n/** The result of parsing \"update\" data (i.e. for an updateData call). */\r\nvar ParsedUpdateData = /** @class */ (function () {\r\n function ParsedUpdateData(data, fieldMask, fieldTransforms) {\r\n this.data = data;\r\n this.fieldMask = fieldMask;\r\n this.fieldTransforms = fieldTransforms;\r\n }\r\n ParsedUpdateData.prototype.toMutations = function (key, precondition) {\r\n var mutations = [\r\n new PatchMutation(key, this.data, this.fieldMask, precondition)\r\n ];\r\n if (this.fieldTransforms.length > 0) {\r\n mutations.push(new TransformMutation(key, this.fieldTransforms));\r\n }\r\n return mutations;\r\n };\r\n return ParsedUpdateData;\r\n}());\r\n/*\r\n * Represents what type of API method provided the data being parsed; useful\r\n * for determining which error conditions apply during parsing and providing\r\n * better error messages.\r\n */\r\nvar UserDataSource;\r\n(function (UserDataSource) {\r\n UserDataSource[UserDataSource[\"Set\"] = 0] = \"Set\";\r\n UserDataSource[UserDataSource[\"Update\"] = 1] = \"Update\";\r\n UserDataSource[UserDataSource[\"MergeSet\"] = 2] = \"MergeSet\";\r\n /**\r\n * Indicates the source is a where clause, cursor bound, arrayUnion()\r\n * element, etc. Of note, isWrite(source) will return false.\r\n */\r\n UserDataSource[UserDataSource[\"Argument\"] = 3] = \"Argument\";\r\n})(UserDataSource || (UserDataSource = {}));\r\nfunction isWrite(dataSource) {\r\n switch (dataSource) {\r\n case UserDataSource.Set: // fall through\r\n case UserDataSource.MergeSet: // fall through\r\n case UserDataSource.Update:\r\n return true;\r\n case UserDataSource.Argument:\r\n return false;\r\n default:\r\n throw fail(\"Unexpected case for UserDataSource: \" + dataSource);\r\n }\r\n}\r\n/** A \"context\" object passed around while parsing user data. */\r\nvar ParseContext = /** @class */ (function () {\r\n /**\r\n * Initializes a ParseContext with the given source and path.\r\n *\r\n * @param dataSource Indicates what kind of API method this data came from.\r\n * @param methodName The name of the method the user called to create this\r\n * ParseContext.\r\n * @param path A path within the object being parsed. This could be an empty\r\n * path (in which case the context represents the root of the data being\r\n * parsed), or a nonempty path (indicating the context represents a nested\r\n * location within the data).\r\n * @param arrayElement Whether or not this context corresponds to an element\r\n * of an array.\r\n * @param fieldTransforms A mutable list of field transforms encountered while\r\n * parsing the data.\r\n * @param fieldMask A mutable list of field paths encountered while parsing\r\n * the data.\r\n *\r\n * TODO(b/34871131): We don't support array paths right now, so path can be\r\n * null to indicate the context represents any location within an array (in\r\n * which case certain features will not work and errors will be somewhat\r\n * compromised).\r\n */\r\n function ParseContext(dataSource, methodName, path, arrayElement, fieldTransforms, fieldMask) {\r\n this.dataSource = dataSource;\r\n this.methodName = methodName;\r\n this.path = path;\r\n this.arrayElement = arrayElement;\r\n // Minor hack: If fieldTransforms is undefined, we assume this is an\r\n // external call and we need to validate the entire path.\r\n if (fieldTransforms === undefined) {\r\n this.validatePath();\r\n }\r\n this.arrayElement = arrayElement !== undefined ? arrayElement : false;\r\n this.fieldTransforms = fieldTransforms || [];\r\n this.fieldMask = fieldMask || [];\r\n }\r\n ParseContext.prototype.childContextForField = function (field) {\r\n var childPath = this.path == null ? null : this.path.child(field);\r\n var context = new ParseContext(this.dataSource, this.methodName, childPath, \r\n /*arrayElement=*/ false, this.fieldTransforms, this.fieldMask);\r\n context.validatePathSegment(field);\r\n return context;\r\n };\r\n ParseContext.prototype.childContextForFieldPath = function (field) {\r\n var childPath = this.path == null ? null : this.path.child(field);\r\n var context = new ParseContext(this.dataSource, this.methodName, childPath, \r\n /*arrayElement=*/ false, this.fieldTransforms, this.fieldMask);\r\n context.validatePath();\r\n return context;\r\n };\r\n ParseContext.prototype.childContextForArray = function (index) {\r\n // TODO(b/34871131): We don't support array paths right now; so make path\r\n // null.\r\n return new ParseContext(this.dataSource, this.methodName, \r\n /*path=*/ null, \r\n /*arrayElement=*/ true, this.fieldTransforms, this.fieldMask);\r\n };\r\n ParseContext.prototype.createError = function (reason) {\r\n var fieldDescription = this.path === null || this.path.isEmpty()\r\n ? ''\r\n : \" (found in field \" + this.path.toString() + \")\";\r\n return new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + this.methodName + \"() called with invalid data. \" +\r\n reason +\r\n fieldDescription);\r\n };\r\n /** Returns 'true' if 'fieldPath' was traversed when creating this context. */\r\n ParseContext.prototype.contains = function (fieldPath) {\r\n return (this.fieldMask.find(function (field) { return fieldPath.isPrefixOf(field); }) !== undefined ||\r\n this.fieldTransforms.find(function (transform) {\r\n return fieldPath.isPrefixOf(transform.field);\r\n }) !== undefined);\r\n };\r\n ParseContext.prototype.validatePath = function () {\r\n // TODO(b/34871131): Remove null check once we have proper paths for fields\r\n // within arrays.\r\n if (this.path === null) {\r\n return;\r\n }\r\n for (var i = 0; i < this.path.length; i++) {\r\n this.validatePathSegment(this.path.get(i));\r\n }\r\n };\r\n ParseContext.prototype.validatePathSegment = function (segment) {\r\n if (isWrite(this.dataSource) && RESERVED_FIELD_REGEX.test(segment)) {\r\n throw this.createError('Document fields cannot begin and end with __');\r\n }\r\n };\r\n return ParseContext;\r\n}());\r\n/**\r\n * A placeholder object for DocumentReferences in this file, in order to\r\n * avoid a circular dependency. See the comments for `DataPreConverter` for\r\n * the full context.\r\n */\r\nvar DocumentKeyReference = /** @class */ (function () {\r\n function DocumentKeyReference(databaseId, key) {\r\n this.databaseId = databaseId;\r\n this.key = key;\r\n }\r\n return DocumentKeyReference;\r\n}());\r\n/**\r\n * Helper for parsing raw user input (provided via the API) into internal model\r\n * classes.\r\n */\r\nvar UserDataConverter = /** @class */ (function () {\r\n function UserDataConverter(preConverter) {\r\n this.preConverter = preConverter;\r\n }\r\n /** Parse document data from a non-merge set() call. */\r\n UserDataConverter.prototype.parseSetData = function (methodName, input) {\r\n var context = new ParseContext(UserDataSource.Set, methodName, FieldPath.EMPTY_PATH);\r\n validatePlainObject('Data must be an object, but it was:', context, input);\r\n var updateData = this.parseData(input, context);\r\n return new ParsedSetData(updateData, \r\n /* fieldMask= */ null, context.fieldTransforms);\r\n };\r\n /** Parse document data from a set() call with '{merge:true}'. */\r\n UserDataConverter.prototype.parseMergeData = function (methodName, input, fieldPaths) {\r\n var context = new ParseContext(UserDataSource.MergeSet, methodName, FieldPath.EMPTY_PATH);\r\n validatePlainObject('Data must be an object, but it was:', context, input);\r\n var updateData = this.parseData(input, context);\r\n var fieldMask;\r\n var fieldTransforms;\r\n if (!fieldPaths) {\r\n fieldMask = FieldMask.fromArray(context.fieldMask);\r\n fieldTransforms = context.fieldTransforms;\r\n }\r\n else {\r\n var validatedFieldPaths = new SortedSet(FieldPath.comparator);\r\n for (var _i = 0, fieldPaths_1 = fieldPaths; _i < fieldPaths_1.length; _i++) {\r\n var stringOrFieldPath = fieldPaths_1[_i];\r\n var fieldPath = void 0;\r\n if (stringOrFieldPath instanceof FieldPath$1) {\r\n fieldPath = stringOrFieldPath._internalPath;\r\n }\r\n else if (typeof stringOrFieldPath === 'string') {\r\n fieldPath = fieldPathFromDotSeparatedString(methodName, stringOrFieldPath);\r\n }\r\n else {\r\n throw fail('Expected stringOrFieldPath to be a string or a FieldPath');\r\n }\r\n if (!context.contains(fieldPath)) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Field '\" + fieldPath + \"' is specified in your field mask but missing from your input data.\");\r\n }\r\n validatedFieldPaths = validatedFieldPaths.add(fieldPath);\r\n }\r\n fieldMask = FieldMask.fromSet(validatedFieldPaths);\r\n fieldTransforms = context.fieldTransforms.filter(function (transform) {\r\n return fieldMask.covers(transform.field);\r\n });\r\n }\r\n return new ParsedSetData(updateData, fieldMask, fieldTransforms);\r\n };\r\n /** Parse update data from an update() call. */\r\n UserDataConverter.prototype.parseUpdateData = function (methodName, input) {\r\n var _this = this;\r\n var context = new ParseContext(UserDataSource.Update, methodName, FieldPath.EMPTY_PATH);\r\n validatePlainObject('Data must be an object, but it was:', context, input);\r\n var fieldMaskPaths = new SortedSet(FieldPath.comparator);\r\n var updateData = ObjectValue.EMPTY;\r\n forEach(input, function (key, value) {\r\n var path = fieldPathFromDotSeparatedString(methodName, key);\r\n var childContext = context.childContextForFieldPath(path);\r\n value = _this.runPreConverter(value, childContext);\r\n if (value instanceof DeleteFieldValueImpl) {\r\n // Add it to the field mask, but don't add anything to updateData.\r\n fieldMaskPaths = fieldMaskPaths.add(path);\r\n }\r\n else {\r\n var parsedValue = _this.parseData(value, childContext);\r\n if (parsedValue != null) {\r\n fieldMaskPaths = fieldMaskPaths.add(path);\r\n updateData = updateData.set(path, parsedValue);\r\n }\r\n }\r\n });\r\n var mask = FieldMask.fromSet(fieldMaskPaths);\r\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\r\n };\r\n /** Parse update data from a list of field/value arguments. */\r\n UserDataConverter.prototype.parseUpdateVarargs = function (methodName, field, value, moreFieldsAndValues) {\r\n var context = new ParseContext(UserDataSource.Update, methodName, FieldPath.EMPTY_PATH);\r\n var keys = [fieldPathFromArgument(methodName, field)];\r\n var values = [value];\r\n if (moreFieldsAndValues.length % 2 !== 0) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + methodName + \"() needs to be called with an even number \" +\r\n 'of arguments that alternate between field names and values.');\r\n }\r\n for (var i = 0; i < moreFieldsAndValues.length; i += 2) {\r\n keys.push(fieldPathFromArgument(methodName, moreFieldsAndValues[i]));\r\n values.push(moreFieldsAndValues[i + 1]);\r\n }\r\n var fieldMaskPaths = new SortedSet(FieldPath.comparator);\r\n var updateData = ObjectValue.EMPTY;\r\n for (var i = 0; i < keys.length; ++i) {\r\n var path = keys[i];\r\n var childContext = context.childContextForFieldPath(path);\r\n var value_1 = this.runPreConverter(values[i], childContext);\r\n if (value_1 instanceof DeleteFieldValueImpl) {\r\n // Add it to the field mask, but don't add anything to updateData.\r\n fieldMaskPaths = fieldMaskPaths.add(path);\r\n }\r\n else {\r\n var parsedValue = this.parseData(value_1, childContext);\r\n if (parsedValue != null) {\r\n fieldMaskPaths = fieldMaskPaths.add(path);\r\n updateData = updateData.set(path, parsedValue);\r\n }\r\n }\r\n }\r\n var mask = FieldMask.fromSet(fieldMaskPaths);\r\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\r\n };\r\n /**\r\n * Parse a \"query value\" (e.g. value in a where filter or a value in a cursor\r\n * bound).\r\n */\r\n UserDataConverter.prototype.parseQueryValue = function (methodName, input) {\r\n var context = new ParseContext(UserDataSource.Argument, methodName, FieldPath.EMPTY_PATH);\r\n var parsed = this.parseData(input, context);\r\n assert(parsed != null, 'Parsed data should not be null.');\r\n assert(context.fieldTransforms.length === 0, 'Field transforms should have been disallowed.');\r\n return parsed;\r\n };\r\n /** Sends data through this.preConverter, handling any thrown errors. */\r\n UserDataConverter.prototype.runPreConverter = function (input, context) {\r\n try {\r\n return this.preConverter(input);\r\n }\r\n catch (e) {\r\n var message = errorMessage(e);\r\n throw context.createError(message);\r\n }\r\n };\r\n /**\r\n * Internal helper for parsing user data.\r\n *\r\n * @param input Data to be parsed.\r\n * @param context A context object representing the current path being parsed,\r\n * the source of the data being parsed, etc.\r\n * @return The parsed value, or null if the value was a FieldValue sentinel\r\n * that should not be included in the resulting parsed data.\r\n */\r\n UserDataConverter.prototype.parseData = function (input, context) {\r\n input = this.runPreConverter(input, context);\r\n if (looksLikeJsonObject(input)) {\r\n validatePlainObject('Unsupported field value:', context, input);\r\n return this.parseObject(input, context);\r\n }\r\n else if (input instanceof FieldValueImpl) {\r\n // FieldValues usually parse into transforms (except FieldValue.delete())\r\n // in which case we do not want to include this field in our parsed data\r\n // (as doing so will overwrite the field directly prior to the transform\r\n // trying to transform it). So we don't add this location to\r\n // context.fieldMask and we return null as our parsing result.\r\n this.parseSentinelFieldValue(input, context);\r\n return null;\r\n }\r\n else {\r\n // If context.path is null we are inside an array and we don't support\r\n // field mask paths more granular than the top-level array.\r\n if (context.path) {\r\n context.fieldMask.push(context.path);\r\n }\r\n if (input instanceof Array) {\r\n // TODO(b/34871131): Include the path containing the array in the error\r\n // message.\r\n if (context.arrayElement) {\r\n throw context.createError('Nested arrays are not supported');\r\n }\r\n return this.parseArray(input, context);\r\n }\r\n else {\r\n return this.parseScalarValue(input, context);\r\n }\r\n }\r\n };\r\n UserDataConverter.prototype.parseObject = function (obj, context) {\r\n var _this = this;\r\n var result = new SortedMap(primitiveComparator);\r\n if (isEmpty(obj)) {\r\n // If we encounter an empty object, we explicitly add it to the update\r\n // mask to ensure that the server creates a map entry.\r\n if (context.path && context.path.length > 0) {\r\n context.fieldMask.push(context.path);\r\n }\r\n }\r\n else {\r\n forEach(obj, function (key, val) {\r\n var parsedValue = _this.parseData(val, context.childContextForField(key));\r\n if (parsedValue != null) {\r\n result = result.insert(key, parsedValue);\r\n }\r\n });\r\n }\r\n return new ObjectValue(result);\r\n };\r\n UserDataConverter.prototype.parseArray = function (array, context) {\r\n var result = [];\r\n var entryIndex = 0;\r\n for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {\r\n var entry = array_1[_i];\r\n var parsedEntry = this.parseData(entry, context.childContextForArray(entryIndex));\r\n if (parsedEntry == null) {\r\n // Just include nulls in the array for fields being replaced with a\r\n // sentinel.\r\n parsedEntry = NullValue.INSTANCE;\r\n }\r\n result.push(parsedEntry);\r\n entryIndex++;\r\n }\r\n return new ArrayValue(result);\r\n };\r\n /**\r\n * \"Parses\" the provided FieldValueImpl, adding any necessary transforms to\r\n * context.fieldTransforms.\r\n */\r\n UserDataConverter.prototype.parseSentinelFieldValue = function (value, context) {\r\n // Sentinels are only supported with writes, and not within arrays.\r\n if (!isWrite(context.dataSource)) {\r\n throw context.createError(value._methodName + \"() can only be used with update() and set()\");\r\n }\r\n if (context.path === null) {\r\n throw context.createError(value._methodName + \"() is not currently supported inside arrays\");\r\n }\r\n if (value instanceof DeleteFieldValueImpl) {\r\n if (context.dataSource === UserDataSource.MergeSet) {\r\n // No transform to add for a delete, but we need to add it to our\r\n // fieldMask so it gets deleted.\r\n context.fieldMask.push(context.path);\r\n }\r\n else if (context.dataSource === UserDataSource.Update) {\r\n assert(context.path.length > 0, 'FieldValue.delete() at the top level should have already' +\r\n ' been handled.');\r\n throw context.createError('FieldValue.delete() can only appear at the top level ' +\r\n 'of your update data');\r\n }\r\n else {\r\n // We shouldn't encounter delete sentinels for queries or non-merge set() calls.\r\n throw context.createError('FieldValue.delete() cannot be used with set() unless you pass ' +\r\n '{merge:true}');\r\n }\r\n }\r\n else if (value instanceof ServerTimestampFieldValueImpl) {\r\n context.fieldTransforms.push(new FieldTransform(context.path, ServerTimestampTransform.instance));\r\n }\r\n else if (value instanceof ArrayUnionFieldValueImpl) {\r\n var parsedElements = this.parseArrayTransformElements(value._methodName, value._elements);\r\n var arrayUnion = new ArrayUnionTransformOperation(parsedElements);\r\n context.fieldTransforms.push(new FieldTransform(context.path, arrayUnion));\r\n }\r\n else if (value instanceof ArrayRemoveFieldValueImpl) {\r\n var parsedElements = this.parseArrayTransformElements(value._methodName, value._elements);\r\n var arrayRemove = new ArrayRemoveTransformOperation(parsedElements);\r\n context.fieldTransforms.push(new FieldTransform(context.path, arrayRemove));\r\n }\r\n else if (value instanceof NumericIncrementFieldValueImpl) {\r\n var operand = this.parseQueryValue('FieldValue.increment', value._operand);\r\n var numericIncrement = new NumericIncrementTransformOperation(operand);\r\n context.fieldTransforms.push(new FieldTransform(context.path, numericIncrement));\r\n }\r\n else {\r\n fail('Unknown FieldValue type: ' + value);\r\n }\r\n };\r\n /**\r\n * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)\r\n *\r\n * @return The parsed value\r\n */\r\n UserDataConverter.prototype.parseScalarValue = function (value, context) {\r\n if (value === null) {\r\n return NullValue.INSTANCE;\r\n }\r\n else if (typeof value === 'number') {\r\n if (isSafeInteger(value)) {\r\n return new IntegerValue(value);\r\n }\r\n else {\r\n return new DoubleValue(value);\r\n }\r\n }\r\n else if (typeof value === 'boolean') {\r\n return BooleanValue.of(value);\r\n }\r\n else if (typeof value === 'string') {\r\n return new StringValue(value);\r\n }\r\n else if (value instanceof Date) {\r\n return new TimestampValue(Timestamp.fromDate(value));\r\n }\r\n else if (value instanceof Timestamp) {\r\n // Firestore backend truncates precision down to microseconds. To ensure\r\n // offline mode works the same with regards to truncation, perform the\r\n // truncation immediately without waiting for the backend to do that.\r\n return new TimestampValue(new Timestamp(value.seconds, Math.floor(value.nanoseconds / 1000) * 1000));\r\n }\r\n else if (value instanceof GeoPoint) {\r\n return new GeoPointValue(value);\r\n }\r\n else if (value instanceof Blob) {\r\n return new BlobValue(value);\r\n }\r\n else if (value instanceof DocumentKeyReference) {\r\n return new RefValue(value.databaseId, value.key);\r\n }\r\n else {\r\n throw context.createError(\"Unsupported field value: \" + valueDescription(value));\r\n }\r\n };\r\n UserDataConverter.prototype.parseArrayTransformElements = function (methodName, elements) {\r\n var _this = this;\r\n return elements.map(function (element, i) {\r\n // Although array transforms are used with writes, the actual elements\r\n // being unioned or removed are not considered writes since they cannot\r\n // contain any FieldValue sentinels, etc.\r\n var context = new ParseContext(UserDataSource.Argument, methodName, FieldPath.EMPTY_PATH);\r\n return _this.parseData(element, context.childContextForArray(i));\r\n });\r\n };\r\n return UserDataConverter;\r\n}());\r\n/**\r\n * Checks whether an object looks like a JSON object that should be converted\r\n * into a struct. Normal class/prototype instances are considered to look like\r\n * JSON objects since they should be converted to a struct value. Arrays, Dates,\r\n * GeoPoints, etc. are not considered to look like JSON objects since they map\r\n * to specific FieldValue types other than ObjectValue.\r\n */\r\nfunction looksLikeJsonObject(input) {\r\n return (typeof input === 'object' &&\r\n input !== null &&\r\n !(input instanceof Array) &&\r\n !(input instanceof Date) &&\r\n !(input instanceof Timestamp) &&\r\n !(input instanceof GeoPoint) &&\r\n !(input instanceof Blob) &&\r\n !(input instanceof DocumentKeyReference) &&\r\n !(input instanceof FieldValueImpl));\r\n}\r\nfunction validatePlainObject(message, context, input) {\r\n if (!looksLikeJsonObject(input) || !isPlainObject(input)) {\r\n var description = valueDescription(input);\r\n if (description === 'an object') {\r\n // Massage the error if it was an object.\r\n throw context.createError(message + ' a custom object');\r\n }\r\n else {\r\n throw context.createError(message + ' ' + description);\r\n }\r\n }\r\n}\r\n/**\r\n * Helper that calls fromDotSeparatedString() but wraps any error thrown.\r\n */\r\nfunction fieldPathFromArgument(methodName, path) {\r\n if (path instanceof FieldPath$1) {\r\n return path._internalPath;\r\n }\r\n else if (typeof path === 'string') {\r\n return fieldPathFromDotSeparatedString(methodName, path);\r\n }\r\n else {\r\n var message = 'Field path arguments must be of type string or FieldPath.';\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + methodName + \"() called with invalid data. \" + message);\r\n }\r\n}\r\n/**\r\n * Wraps fromDotSeparatedString with an error message about the method that\r\n * was thrown.\r\n * @param methodName The publicly visible method name\r\n * @param path The dot-separated string form of a field path which will be split\r\n * on dots.\r\n */\r\nfunction fieldPathFromDotSeparatedString(methodName, path) {\r\n try {\r\n return fromDotSeparatedString(path)._internalPath;\r\n }\r\n catch (e) {\r\n var message = errorMessage(e);\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + methodName + \"() called with invalid data. \" + message);\r\n }\r\n}\r\n/**\r\n * Extracts the message from a caught exception, which should be an Error object\r\n * though JS doesn't guarantee that.\r\n */\r\nfunction errorMessage(error) {\r\n return error instanceof Error ? error.message : error.toString();\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// The objects that are a part of this API are exposed to third-parties as\r\n// compiled javascript so we want to flag our private members with a leading\r\n// underscore to discourage their use.\r\n// tslint:disable:strip-private-property-underscore\r\n// settings() defaults:\r\nvar DEFAULT_HOST = 'firestore.googleapis.com';\r\nvar DEFAULT_SSL = true;\r\nvar DEFAULT_TIMESTAMPS_IN_SNAPSHOTS = true;\r\nvar DEFAULT_FORCE_LONG_POLLING = false;\r\n/**\r\n * Constant used to indicate the LRU garbage collection should be disabled.\r\n * Set this value as the `cacheSizeBytes` on the settings passed to the\r\n * `Firestore` instance.\r\n */\r\nvar CACHE_SIZE_UNLIMITED = LruParams.COLLECTION_DISABLED;\r\n// enablePersistence() defaults:\r\nvar DEFAULT_SYNCHRONIZE_TABS = false;\r\n/**\r\n * A concrete type describing all the values that can be applied via a\r\n * user-supplied firestore.Settings object. This is a separate type so that\r\n * defaults can be supplied and the value can be checked for equality.\r\n */\r\nvar FirestoreSettings = /** @class */ (function () {\r\n function FirestoreSettings(settings) {\r\n if (settings.host === undefined) {\r\n if (settings.ssl !== undefined) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Can't provide ssl option if host option is not set\");\r\n }\r\n this.host = DEFAULT_HOST;\r\n this.ssl = DEFAULT_SSL;\r\n }\r\n else {\r\n validateNamedType('settings', 'non-empty string', 'host', settings.host);\r\n this.host = settings.host;\r\n validateNamedOptionalType('settings', 'boolean', 'ssl', settings.ssl);\r\n this.ssl = defaulted(settings.ssl, DEFAULT_SSL);\r\n }\r\n validateOptionNames('settings', settings, [\r\n 'host',\r\n 'ssl',\r\n 'credentials',\r\n 'timestampsInSnapshots',\r\n 'cacheSizeBytes',\r\n 'experimentalForceLongPolling'\r\n ]);\r\n validateNamedOptionalType('settings', 'object', 'credentials', settings.credentials);\r\n this.credentials = settings.credentials;\r\n validateNamedOptionalType('settings', 'boolean', 'timestampsInSnapshots', settings.timestampsInSnapshots);\r\n // Nobody should set timestampsInSnapshots anymore, but the error depends on\r\n // whether they set it to true or false...\r\n if (settings.timestampsInSnapshots === true) {\r\n error(\"\\n The timestampsInSnapshots setting now defaults to true and you no\\n longer need to explicitly set it. In a future release, the setting\\n will be removed entirely and so it is recommended that you remove it\\n from your firestore.settings() call now.\");\r\n }\r\n else if (settings.timestampsInSnapshots === false) {\r\n error(\"\\n The timestampsInSnapshots setting will soon be removed. YOU MUST UPDATE\\n YOUR CODE.\\n\\n To hide this warning, stop using the timestampsInSnapshots setting in your\\n firestore.settings({ ... }) call.\\n\\n Once you remove the setting, Timestamps stored in Cloud Firestore will be\\n read back as Firebase Timestamp objects instead of as system Date objects.\\n So you will also need to update code expecting a Date to instead expect a\\n Timestamp. For example:\\n\\n // Old:\\n const date = snapshot.get('created_at');\\n // New:\\n const timestamp = snapshot.get('created_at'); const date =\\n timestamp.toDate();\\n\\n Please audit all existing usages of Date when you enable the new\\n behavior.\");\r\n }\r\n this.timestampsInSnapshots = defaulted(settings.timestampsInSnapshots, DEFAULT_TIMESTAMPS_IN_SNAPSHOTS);\r\n validateNamedOptionalType('settings', 'number', 'cacheSizeBytes', settings.cacheSizeBytes);\r\n if (settings.cacheSizeBytes === undefined) {\r\n this.cacheSizeBytes = LruParams.DEFAULT_CACHE_SIZE_BYTES;\r\n }\r\n else {\r\n if (settings.cacheSizeBytes !== CACHE_SIZE_UNLIMITED &&\r\n settings.cacheSizeBytes < LruParams.MINIMUM_CACHE_SIZE_BYTES) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"cacheSizeBytes must be at least \" + LruParams.MINIMUM_CACHE_SIZE_BYTES);\r\n }\r\n else {\r\n this.cacheSizeBytes = settings.cacheSizeBytes;\r\n }\r\n }\r\n validateNamedOptionalType('settings', 'boolean', 'experimentalForceLongPolling', settings.experimentalForceLongPolling);\r\n this.forceLongPolling =\r\n settings.experimentalForceLongPolling === undefined\r\n ? DEFAULT_FORCE_LONG_POLLING\r\n : settings.experimentalForceLongPolling;\r\n }\r\n FirestoreSettings.prototype.isEqual = function (other) {\r\n return (this.host === other.host &&\r\n this.ssl === other.ssl &&\r\n this.timestampsInSnapshots === other.timestampsInSnapshots &&\r\n this.credentials === other.credentials &&\r\n this.cacheSizeBytes === other.cacheSizeBytes &&\r\n this.forceLongPolling === other.forceLongPolling);\r\n };\r\n return FirestoreSettings;\r\n}());\r\nvar FirestoreConfig = /** @class */ (function () {\r\n function FirestoreConfig() {\r\n }\r\n return FirestoreConfig;\r\n}());\r\n/**\r\n * The root reference to the database.\r\n */\r\nvar Firestore = /** @class */ (function () {\r\n function Firestore(databaseIdOrApp) {\r\n var _this = this;\r\n // Public for use in tests.\r\n // TODO(mikelehen): Use modularized initialization instead.\r\n this._queue = new AsyncQueue();\r\n this.INTERNAL = {\r\n delete: function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {\r\n return tslib_1.__generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n // The client must be initalized to ensure that all subsequent API usage\r\n // throws an exception.\r\n this.ensureClientConfigured();\r\n return [4 /*yield*/, this._firestoreClient.shutdown()];\r\n case 1:\r\n _a.sent();\r\n this.clientRunning = false;\r\n return [2 /*return*/];\r\n }\r\n });\r\n }); }\r\n };\r\n this.clientRunning = false;\r\n var config = new FirestoreConfig();\r\n if (typeof databaseIdOrApp.options === 'object') {\r\n // This is very likely a Firebase app object\r\n // TODO(b/34177605): Can we somehow use instanceof?\r\n var app = databaseIdOrApp;\r\n config.firebaseApp = app;\r\n config.databaseId = Firestore.databaseIdFromApp(app);\r\n config.persistenceKey = config.firebaseApp.name;\r\n config.credentials = new FirebaseCredentialsProvider(app);\r\n }\r\n else {\r\n var external_1 = databaseIdOrApp;\r\n if (!external_1.projectId) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Must provide projectId');\r\n }\r\n config.databaseId = new DatabaseId(external_1.projectId, external_1.database);\r\n // Use a default persistenceKey that lines up with FirebaseApp.\r\n config.persistenceKey = '[DEFAULT]';\r\n config.credentials = new EmptyCredentialsProvider();\r\n }\r\n config.settings = new FirestoreSettings({});\r\n this._config = config;\r\n this._databaseId = config.databaseId;\r\n }\r\n Firestore.prototype.settings = function (settingsLiteral) {\r\n validateExactNumberOfArgs('Firestore.settings', arguments, 1);\r\n validateArgType('Firestore.settings', 'object', 1, settingsLiteral);\r\n if (contains(settingsLiteral, 'persistence')) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, '\"persistence\" is now specified with a separate call to ' +\r\n 'firestore.enablePersistence().');\r\n }\r\n var newSettings = new FirestoreSettings(settingsLiteral);\r\n if (this._firestoreClient && !this._config.settings.isEqual(newSettings)) {\r\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore has already been started and its settings can no longer ' +\r\n 'be changed. You can only call settings() before calling any other ' +\r\n 'methods on a Firestore object.');\r\n }\r\n this._config.settings = newSettings;\r\n if (newSettings.credentials !== undefined) {\r\n this._config.credentials = makeCredentialsProvider(newSettings.credentials);\r\n }\r\n };\r\n Firestore.prototype.enableNetwork = function () {\r\n this.ensureClientConfigured();\r\n return this._firestoreClient.enableNetwork();\r\n };\r\n Firestore.prototype.disableNetwork = function () {\r\n this.ensureClientConfigured();\r\n return this._firestoreClient.disableNetwork();\r\n };\r\n Firestore.prototype.enablePersistence = function (settings) {\r\n if (this._firestoreClient) {\r\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore has already been started and persistence can no longer ' +\r\n 'be enabled. You can only call enablePersistence() before calling ' +\r\n 'any other methods on a Firestore object.');\r\n }\r\n return this.configureClient(new IndexedDbPersistenceSettings(this._config.settings.cacheSizeBytes, settings !== undefined &&\r\n defaulted(settings.experimentalTabSynchronization, DEFAULT_SYNCHRONIZE_TABS)));\r\n };\r\n Firestore.prototype._clearPersistence = function () {\r\n if (this.clientRunning) {\r\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'Persistence cannot be cleared while the client is running');\r\n }\r\n var persistenceKey = IndexedDbPersistence.buildStoragePrefix(this.makeDatabaseInfo());\r\n return IndexedDbPersistence.clearPersistence(persistenceKey);\r\n };\r\n Firestore.prototype.ensureClientConfigured = function () {\r\n if (!this._firestoreClient) {\r\n // Kick off starting the client but don't actually wait for it.\r\n // tslint:disable-next-line:no-floating-promises\r\n this.configureClient(new MemoryPersistenceSettings());\r\n }\r\n return this._firestoreClient;\r\n };\r\n Firestore.prototype.makeDatabaseInfo = function () {\r\n return new DatabaseInfo(this._config.databaseId, this._config.persistenceKey, this._config.settings.host, this._config.settings.ssl, this._config.settings.forceLongPolling);\r\n };\r\n Firestore.prototype.configureClient = function (persistenceSettings) {\r\n var _this = this;\r\n assert(!!this._config.settings.host, 'FirestoreSettings.host cannot be falsey');\r\n assert(!this._firestoreClient, 'configureClient() called multiple times');\r\n this.clientRunning = true;\r\n var databaseInfo = this.makeDatabaseInfo();\r\n var preConverter = function (value) {\r\n if (value instanceof DocumentReference) {\r\n var thisDb = _this._config.databaseId;\r\n var otherDb = value.firestore._config.databaseId;\r\n if (!otherDb.isEqual(thisDb)) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Document reference is for database ' +\r\n (otherDb.projectId + \"/\" + otherDb.database + \" but should be \") +\r\n (\"for database \" + thisDb.projectId + \"/\" + thisDb.database));\r\n }\r\n return new DocumentKeyReference(_this._config.databaseId, value._key);\r\n }\r\n else {\r\n return value;\r\n }\r\n };\r\n this._dataConverter = new UserDataConverter(preConverter);\r\n this._firestoreClient = new FirestoreClient(PlatformSupport.getPlatform(), databaseInfo, this._config.credentials, this._queue);\r\n return this._firestoreClient.start(persistenceSettings);\r\n };\r\n Firestore.databaseIdFromApp = function (app) {\r\n var options = app.options;\r\n if (!contains(options, 'projectId')) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, '\"projectId\" not provided in firebase.initializeApp.');\r\n }\r\n var projectId = options['projectId'];\r\n if (!projectId || typeof projectId !== 'string') {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'projectId must be a string in FirebaseApp.options');\r\n }\r\n return new DatabaseId(projectId);\r\n };\r\n Object.defineProperty(Firestore.prototype, \"app\", {\r\n get: function () {\r\n if (!this._config.firebaseApp) {\r\n throw new FirestoreError(Code.FAILED_PRECONDITION, \"Firestore was not initialized using the Firebase SDK. 'app' is \" +\r\n 'not available');\r\n }\r\n return this._config.firebaseApp;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Firestore.prototype.collection = function (pathString) {\r\n validateExactNumberOfArgs('Firestore.collection', arguments, 1);\r\n validateArgType('Firestore.collection', 'non-empty string', 1, pathString);\r\n this.ensureClientConfigured();\r\n return new CollectionReference(ResourcePath.fromString(pathString), this);\r\n };\r\n Firestore.prototype.doc = function (pathString) {\r\n validateExactNumberOfArgs('Firestore.doc', arguments, 1);\r\n validateArgType('Firestore.doc', 'non-empty string', 1, pathString);\r\n this.ensureClientConfigured();\r\n return DocumentReference.forPath(ResourcePath.fromString(pathString), this);\r\n };\r\n // TODO(b/116617988): Fix name, uncomment d.ts definitions, and update CHANGELOG.md.\r\n Firestore.prototype._collectionGroup = function (collectionId) {\r\n validateExactNumberOfArgs('Firestore.collectionGroup', arguments, 1);\r\n validateArgType('Firestore.collectionGroup', 'non-empty string', 1, collectionId);\r\n if (collectionId.indexOf('/') >= 0) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid collection ID '\" + collectionId + \"' passed to function \" +\r\n \"Firestore.collectionGroup(). Collection IDs must not contain '/'.\");\r\n }\r\n this.ensureClientConfigured();\r\n return new Query$1(new Query(ResourcePath.EMPTY_PATH, collectionId), this);\r\n };\r\n Firestore.prototype.runTransaction = function (updateFunction) {\r\n var _this = this;\r\n validateExactNumberOfArgs('Firestore.runTransaction', arguments, 1);\r\n validateArgType('Firestore.runTransaction', 'function', 1, updateFunction);\r\n return this.ensureClientConfigured().transaction(function (transaction) {\r\n return updateFunction(new Transaction$1(_this, transaction));\r\n });\r\n };\r\n Firestore.prototype.batch = function () {\r\n this.ensureClientConfigured();\r\n return new WriteBatch(this);\r\n };\r\n Object.defineProperty(Firestore, \"logLevel\", {\r\n get: function () {\r\n switch (getLogLevel()) {\r\n case LogLevel.DEBUG:\r\n return 'debug';\r\n case LogLevel.ERROR:\r\n return 'error';\r\n case LogLevel.SILENT:\r\n return 'silent';\r\n default:\r\n return fail('Unknown log level: ' + getLogLevel());\r\n }\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Firestore.setLogLevel = function (level) {\r\n validateExactNumberOfArgs('Firestore.setLogLevel', arguments, 1);\r\n validateArgType('Firestore.setLogLevel', 'non-empty string', 1, level);\r\n switch (level) {\r\n case 'debug':\r\n setLogLevel(LogLevel.DEBUG);\r\n break;\r\n case 'error':\r\n setLogLevel(LogLevel.ERROR);\r\n break;\r\n case 'silent':\r\n setLogLevel(LogLevel.SILENT);\r\n break;\r\n default:\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid log level: ' + level);\r\n }\r\n };\r\n // Note: this is not a property because the minifier can't work correctly with\r\n // the way TypeScript compiler outputs properties.\r\n Firestore.prototype._areTimestampsInSnapshotsEnabled = function () {\r\n return this._config.settings.timestampsInSnapshots;\r\n };\r\n return Firestore;\r\n}());\r\n/**\r\n * A reference to a transaction.\r\n */\r\nvar Transaction$1 = /** @class */ (function () {\r\n function Transaction(_firestore, _transaction) {\r\n this._firestore = _firestore;\r\n this._transaction = _transaction;\r\n }\r\n Transaction.prototype.get = function (documentRef) {\r\n var _this = this;\r\n validateExactNumberOfArgs('Transaction.get', arguments, 1);\r\n var ref = validateReference('Transaction.get', documentRef, this._firestore);\r\n return this._transaction\r\n .lookup([ref._key])\r\n .then(function (docs) {\r\n if (!docs || docs.length !== 1) {\r\n return fail('Mismatch in docs returned from document lookup.');\r\n }\r\n var doc = docs[0];\r\n if (doc instanceof NoDocument) {\r\n return new DocumentSnapshot(_this._firestore, ref._key, null, \r\n /* fromCache= */ false, \r\n /* hasPendingWrites= */ false);\r\n }\r\n else if (doc instanceof Document) {\r\n return new DocumentSnapshot(_this._firestore, ref._key, doc, \r\n /* fromCache= */ false, \r\n /* hasPendingWrites= */ false);\r\n }\r\n else {\r\n throw fail(\"BatchGetDocumentsRequest returned unexpected document type: \" + doc.constructor.name);\r\n }\r\n });\r\n };\r\n Transaction.prototype.set = function (documentRef, value, options) {\r\n validateBetweenNumberOfArgs('Transaction.set', arguments, 2, 3);\r\n var ref = validateReference('Transaction.set', documentRef, this._firestore);\r\n options = validateSetOptions('Transaction.set', options);\r\n var parsed = options.merge || options.mergeFields\r\n ? this._firestore._dataConverter.parseMergeData('Transaction.set', value, options.mergeFields)\r\n : this._firestore._dataConverter.parseSetData('Transaction.set', value);\r\n this._transaction.set(ref._key, parsed);\r\n return this;\r\n };\r\n Transaction.prototype.update = function (documentRef, fieldOrUpdateData, value) {\r\n var moreFieldsAndValues = [];\r\n for (var _i = 3; _i < arguments.length; _i++) {\r\n moreFieldsAndValues[_i - 3] = arguments[_i];\r\n }\r\n var ref;\r\n var parsed;\r\n if (typeof fieldOrUpdateData === 'string' ||\r\n fieldOrUpdateData instanceof FieldPath$1) {\r\n validateAtLeastNumberOfArgs('Transaction.update', arguments, 3);\r\n ref = validateReference('Transaction.update', documentRef, this._firestore);\r\n parsed = this._firestore._dataConverter.parseUpdateVarargs('Transaction.update', fieldOrUpdateData, value, moreFieldsAndValues);\r\n }\r\n else {\r\n validateExactNumberOfArgs('Transaction.update', arguments, 2);\r\n ref = validateReference('Transaction.update', documentRef, this._firestore);\r\n parsed = this._firestore._dataConverter.parseUpdateData('Transaction.update', fieldOrUpdateData);\r\n }\r\n this._transaction.update(ref._key, parsed);\r\n return this;\r\n };\r\n Transaction.prototype.delete = function (documentRef) {\r\n validateExactNumberOfArgs('Transaction.delete', arguments, 1);\r\n var ref = validateReference('Transaction.delete', documentRef, this._firestore);\r\n this._transaction.delete(ref._key);\r\n return this;\r\n };\r\n return Transaction;\r\n}());\r\nvar WriteBatch = /** @class */ (function () {\r\n function WriteBatch(_firestore) {\r\n this._firestore = _firestore;\r\n this._mutations = [];\r\n this._committed = false;\r\n }\r\n WriteBatch.prototype.set = function (documentRef, value, options) {\r\n validateBetweenNumberOfArgs('WriteBatch.set', arguments, 2, 3);\r\n this.verifyNotCommitted();\r\n var ref = validateReference('WriteBatch.set', documentRef, this._firestore);\r\n options = validateSetOptions('WriteBatch.set', options);\r\n var parsed = options.merge || options.mergeFields\r\n ? this._firestore._dataConverter.parseMergeData('WriteBatch.set', value, options.mergeFields)\r\n : this._firestore._dataConverter.parseSetData('WriteBatch.set', value);\r\n this._mutations = this._mutations.concat(parsed.toMutations(ref._key, Precondition.NONE));\r\n return this;\r\n };\r\n WriteBatch.prototype.update = function (documentRef, fieldOrUpdateData, value) {\r\n var moreFieldsAndValues = [];\r\n for (var _i = 3; _i < arguments.length; _i++) {\r\n moreFieldsAndValues[_i - 3] = arguments[_i];\r\n }\r\n this.verifyNotCommitted();\r\n var ref;\r\n var parsed;\r\n if (typeof fieldOrUpdateData === 'string' ||\r\n fieldOrUpdateData instanceof FieldPath$1) {\r\n validateAtLeastNumberOfArgs('WriteBatch.update', arguments, 3);\r\n ref = validateReference('WriteBatch.update', documentRef, this._firestore);\r\n parsed = this._firestore._dataConverter.parseUpdateVarargs('WriteBatch.update', fieldOrUpdateData, value, moreFieldsAndValues);\r\n }\r\n else {\r\n validateExactNumberOfArgs('WriteBatch.update', arguments, 2);\r\n ref = validateReference('WriteBatch.update', documentRef, this._firestore);\r\n parsed = this._firestore._dataConverter.parseUpdateData('WriteBatch.update', fieldOrUpdateData);\r\n }\r\n this._mutations = this._mutations.concat(parsed.toMutations(ref._key, Precondition.exists(true)));\r\n return this;\r\n };\r\n WriteBatch.prototype.delete = function (documentRef) {\r\n validateExactNumberOfArgs('WriteBatch.delete', arguments, 1);\r\n this.verifyNotCommitted();\r\n var ref = validateReference('WriteBatch.delete', documentRef, this._firestore);\r\n this._mutations = this._mutations.concat(new DeleteMutation(ref._key, Precondition.NONE));\r\n return this;\r\n };\r\n WriteBatch.prototype.commit = function () {\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n return tslib_1.__generator(this, function (_a) {\r\n this.verifyNotCommitted();\r\n this._committed = true;\r\n if (this._mutations.length > 0) {\r\n return [2 /*return*/, this._firestore.ensureClientConfigured().write(this._mutations)];\r\n }\r\n return [2 /*return*/];\r\n });\r\n });\r\n };\r\n WriteBatch.prototype.verifyNotCommitted = function () {\r\n if (this._committed) {\r\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'A write batch can no longer be used after commit() ' +\r\n 'has been called.');\r\n }\r\n };\r\n return WriteBatch;\r\n}());\r\n/**\r\n * A reference to a particular document in a collection in the database.\r\n */\r\nvar DocumentReference = /** @class */ (function () {\r\n function DocumentReference(_key, firestore) {\r\n this._key = _key;\r\n this.firestore = firestore;\r\n this._firestoreClient = this.firestore.ensureClientConfigured();\r\n }\r\n DocumentReference.forPath = function (path, firestore) {\r\n if (path.length % 2 !== 0) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid document reference. Document ' +\r\n 'references must have an even number of segments, but ' +\r\n (path.canonicalString() + \" has \" + path.length));\r\n }\r\n return new DocumentReference(new DocumentKey(path), firestore);\r\n };\r\n Object.defineProperty(DocumentReference.prototype, \"id\", {\r\n get: function () {\r\n return this._key.path.lastSegment();\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(DocumentReference.prototype, \"parent\", {\r\n get: function () {\r\n return new CollectionReference(this._key.path.popLast(), this.firestore);\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(DocumentReference.prototype, \"path\", {\r\n get: function () {\r\n return this._key.path.canonicalString();\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n DocumentReference.prototype.collection = function (pathString) {\r\n validateExactNumberOfArgs('DocumentReference.collection', arguments, 1);\r\n validateArgType('DocumentReference.collection', 'non-empty string', 1, pathString);\r\n if (!pathString) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Must provide a non-empty collection name to collection()');\r\n }\r\n var path = ResourcePath.fromString(pathString);\r\n return new CollectionReference(this._key.path.child(path), this.firestore);\r\n };\r\n DocumentReference.prototype.isEqual = function (other) {\r\n if (!(other instanceof DocumentReference)) {\r\n throw invalidClassError('isEqual', 'DocumentReference', 1, other);\r\n }\r\n return this.firestore === other.firestore && this._key.isEqual(other._key);\r\n };\r\n DocumentReference.prototype.set = function (value, options) {\r\n validateBetweenNumberOfArgs('DocumentReference.set', arguments, 1, 2);\r\n options = validateSetOptions('DocumentReference.set', options);\r\n var parsed = options.merge || options.mergeFields\r\n ? this.firestore._dataConverter.parseMergeData('DocumentReference.set', value, options.mergeFields)\r\n : this.firestore._dataConverter.parseSetData('DocumentReference.set', value);\r\n return this._firestoreClient.write(parsed.toMutations(this._key, Precondition.NONE));\r\n };\r\n DocumentReference.prototype.update = function (fieldOrUpdateData, value) {\r\n var moreFieldsAndValues = [];\r\n for (var _i = 2; _i < arguments.length; _i++) {\r\n moreFieldsAndValues[_i - 2] = arguments[_i];\r\n }\r\n var parsed;\r\n if (typeof fieldOrUpdateData === 'string' ||\r\n fieldOrUpdateData instanceof FieldPath$1) {\r\n validateAtLeastNumberOfArgs('DocumentReference.update', arguments, 2);\r\n parsed = this.firestore._dataConverter.parseUpdateVarargs('DocumentReference.update', fieldOrUpdateData, value, moreFieldsAndValues);\r\n }\r\n else {\r\n validateExactNumberOfArgs('DocumentReference.update', arguments, 1);\r\n parsed = this.firestore._dataConverter.parseUpdateData('DocumentReference.update', fieldOrUpdateData);\r\n }\r\n return this._firestoreClient.write(parsed.toMutations(this._key, Precondition.exists(true)));\r\n };\r\n DocumentReference.prototype.delete = function () {\r\n validateExactNumberOfArgs('DocumentReference.delete', arguments, 0);\r\n return this._firestoreClient.write([\r\n new DeleteMutation(this._key, Precondition.NONE)\r\n ]);\r\n };\r\n DocumentReference.prototype.onSnapshot = function () {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n validateBetweenNumberOfArgs('DocumentReference.onSnapshot', arguments, 1, 4);\r\n var options = {\r\n includeMetadataChanges: false\r\n };\r\n var observer;\r\n var currArg = 0;\r\n if (typeof args[currArg] === 'object' &&\r\n !isPartialObserver(args[currArg])) {\r\n options = args[currArg];\r\n validateOptionNames('DocumentReference.onSnapshot', options, [\r\n 'includeMetadataChanges'\r\n ]);\r\n validateNamedOptionalType('DocumentReference.onSnapshot', 'boolean', 'includeMetadataChanges', options.includeMetadataChanges);\r\n currArg++;\r\n }\r\n var internalOptions = {\r\n includeMetadataChanges: options.includeMetadataChanges\r\n };\r\n if (isPartialObserver(args[currArg])) {\r\n observer = args[currArg];\r\n }\r\n else {\r\n validateArgType('DocumentReference.onSnapshot', 'function', currArg, args[currArg]);\r\n validateOptionalArgType('DocumentReference.onSnapshot', 'function', currArg + 1, args[currArg + 1]);\r\n validateOptionalArgType('DocumentReference.onSnapshot', 'function', currArg + 2, args[currArg + 2]);\r\n observer = {\r\n next: args[currArg],\r\n error: args[currArg + 1],\r\n complete: args[currArg + 2]\r\n };\r\n }\r\n return this.onSnapshotInternal(internalOptions, observer);\r\n };\r\n DocumentReference.prototype.onSnapshotInternal = function (options, observer) {\r\n var _this = this;\r\n var errHandler = function (err) {\r\n console.error('Uncaught Error in onSnapshot:', err);\r\n };\r\n if (observer.error) {\r\n errHandler = observer.error.bind(observer);\r\n }\r\n var asyncObserver = new AsyncObserver({\r\n next: function (snapshot) {\r\n if (observer.next) {\r\n assert(snapshot.docs.size <= 1, 'Too many documents returned on a document query');\r\n var doc = snapshot.docs.get(_this._key);\r\n observer.next(new DocumentSnapshot(_this.firestore, _this._key, doc, snapshot.fromCache, snapshot.hasPendingWrites));\r\n }\r\n },\r\n error: errHandler\r\n });\r\n var internalListener = this._firestoreClient.listen(Query.atPath(this._key.path), asyncObserver, options);\r\n return function () {\r\n asyncObserver.mute();\r\n _this._firestoreClient.unlisten(internalListener);\r\n };\r\n };\r\n DocumentReference.prototype.get = function (options) {\r\n var _this = this;\r\n validateBetweenNumberOfArgs('DocumentReference.get', arguments, 0, 1);\r\n validateGetOptions('DocumentReference.get', options);\r\n return new Promise(function (resolve, reject) {\r\n if (options && options.source === 'cache') {\r\n _this.firestore\r\n .ensureClientConfigured()\r\n .getDocumentFromLocalCache(_this._key)\r\n .then(function (doc) {\r\n resolve(new DocumentSnapshot(_this.firestore, _this._key, doc, \r\n /*fromCache=*/ true, doc instanceof Document ? doc.hasLocalMutations : false));\r\n }, reject);\r\n }\r\n else {\r\n _this.getViaSnapshotListener(resolve, reject, options);\r\n }\r\n });\r\n };\r\n DocumentReference.prototype.getViaSnapshotListener = function (resolve, reject, options) {\r\n var unlisten = this.onSnapshotInternal({\r\n includeMetadataChanges: true,\r\n waitForSyncWhenOnline: true\r\n }, {\r\n next: function (snap) {\r\n // Remove query first before passing event to user to avoid\r\n // user actions affecting the now stale query.\r\n unlisten();\r\n if (!snap.exists && snap.metadata.fromCache) {\r\n // TODO(dimond): If we're online and the document doesn't\r\n // exist then we resolve with a doc.exists set to false. If\r\n // we're offline however, we reject the Promise in this\r\n // case. Two options: 1) Cache the negative response from\r\n // the server so we can deliver that even when you're\r\n // offline 2) Actually reject the Promise in the online case\r\n // if the document doesn't exist.\r\n reject(new FirestoreError(Code.UNAVAILABLE, 'Failed to get document because the client is ' + 'offline.'));\r\n }\r\n else if (snap.exists &&\r\n snap.metadata.fromCache &&\r\n options &&\r\n options.source === 'server') {\r\n reject(new FirestoreError(Code.UNAVAILABLE, 'Failed to get document from server. (However, this ' +\r\n 'document does exist in the local cache. Run again ' +\r\n 'without setting source to \"server\" to ' +\r\n 'retrieve the cached document.)'));\r\n }\r\n else {\r\n resolve(snap);\r\n }\r\n },\r\n error: reject\r\n });\r\n };\r\n return DocumentReference;\r\n}());\r\nvar SnapshotMetadata = /** @class */ (function () {\r\n function SnapshotMetadata(hasPendingWrites, fromCache) {\r\n this.hasPendingWrites = hasPendingWrites;\r\n this.fromCache = fromCache;\r\n }\r\n SnapshotMetadata.prototype.isEqual = function (other) {\r\n return (this.hasPendingWrites === other.hasPendingWrites &&\r\n this.fromCache === other.fromCache);\r\n };\r\n return SnapshotMetadata;\r\n}());\r\nvar DocumentSnapshot = /** @class */ (function () {\r\n function DocumentSnapshot(_firestore, _key, _document, _fromCache, _hasPendingWrites) {\r\n this._firestore = _firestore;\r\n this._key = _key;\r\n this._document = _document;\r\n this._fromCache = _fromCache;\r\n this._hasPendingWrites = _hasPendingWrites;\r\n }\r\n DocumentSnapshot.prototype.data = function (options) {\r\n validateBetweenNumberOfArgs('DocumentSnapshot.data', arguments, 0, 1);\r\n options = validateSnapshotOptions('DocumentSnapshot.data', options);\r\n return !this._document\r\n ? undefined\r\n : this.convertObject(this._document.data, FieldValueOptions.fromSnapshotOptions(options, this._firestore._areTimestampsInSnapshotsEnabled()));\r\n };\r\n DocumentSnapshot.prototype.get = function (fieldPath, options) {\r\n validateBetweenNumberOfArgs('DocumentSnapshot.get', arguments, 1, 2);\r\n options = validateSnapshotOptions('DocumentSnapshot.get', options);\r\n if (this._document) {\r\n var value = this._document.data.field(fieldPathFromArgument('DocumentSnapshot.get', fieldPath));\r\n if (value !== undefined) {\r\n return this.convertValue(value, FieldValueOptions.fromSnapshotOptions(options, this._firestore._areTimestampsInSnapshotsEnabled()));\r\n }\r\n }\r\n return undefined;\r\n };\r\n Object.defineProperty(DocumentSnapshot.prototype, \"id\", {\r\n get: function () {\r\n return this._key.path.lastSegment();\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(DocumentSnapshot.prototype, \"ref\", {\r\n get: function () {\r\n return new DocumentReference(this._key, this._firestore);\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(DocumentSnapshot.prototype, \"exists\", {\r\n get: function () {\r\n return this._document !== null;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(DocumentSnapshot.prototype, \"metadata\", {\r\n get: function () {\r\n return new SnapshotMetadata(this._hasPendingWrites, this._fromCache);\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n DocumentSnapshot.prototype.isEqual = function (other) {\r\n if (!(other instanceof DocumentSnapshot)) {\r\n throw invalidClassError('isEqual', 'DocumentSnapshot', 1, other);\r\n }\r\n return (this._firestore === other._firestore &&\r\n this._fromCache === other._fromCache &&\r\n this._key.isEqual(other._key) &&\r\n (this._document === null\r\n ? other._document === null\r\n : this._document.isEqual(other._document)));\r\n };\r\n DocumentSnapshot.prototype.convertObject = function (data, options) {\r\n var _this = this;\r\n var result = {};\r\n data.forEach(function (key, value) {\r\n result[key] = _this.convertValue(value, options);\r\n });\r\n return result;\r\n };\r\n DocumentSnapshot.prototype.convertValue = function (value, options) {\r\n if (value instanceof ObjectValue) {\r\n return this.convertObject(value, options);\r\n }\r\n else if (value instanceof ArrayValue) {\r\n return this.convertArray(value, options);\r\n }\r\n else if (value instanceof RefValue) {\r\n var key = value.value(options);\r\n var database = this._firestore.ensureClientConfigured().databaseId();\r\n if (!value.databaseId.isEqual(database)) {\r\n // TODO(b/64130202): Somehow support foreign references.\r\n error(\"Document \" + this._key.path + \" contains a document \" +\r\n \"reference within a different database (\" +\r\n (value.databaseId.projectId + \"/\" + value.databaseId.database + \") which is not \") +\r\n \"supported. It will be treated as a reference in the current \" +\r\n (\"database (\" + database.projectId + \"/\" + database.database + \") \") +\r\n \"instead.\");\r\n }\r\n return new DocumentReference(key, this._firestore);\r\n }\r\n else {\r\n return value.value(options);\r\n }\r\n };\r\n DocumentSnapshot.prototype.convertArray = function (data, options) {\r\n var _this = this;\r\n return data.internalValue.map(function (value) {\r\n return _this.convertValue(value, options);\r\n });\r\n };\r\n return DocumentSnapshot;\r\n}());\r\nvar QueryDocumentSnapshot = /** @class */ (function (_super) {\r\n tslib_1.__extends(QueryDocumentSnapshot, _super);\r\n function QueryDocumentSnapshot(firestore, key, document, fromCache, hasPendingWrites) {\r\n return _super.call(this, firestore, key, document, fromCache, hasPendingWrites) || this;\r\n }\r\n QueryDocumentSnapshot.prototype.data = function (options) {\r\n var data = _super.prototype.data.call(this, options);\r\n assert(typeof data === 'object', 'Document in a QueryDocumentSnapshot should exist');\r\n return data;\r\n };\r\n return QueryDocumentSnapshot;\r\n}(DocumentSnapshot));\r\nvar Query$1 = /** @class */ (function () {\r\n function Query(_query, firestore) {\r\n this._query = _query;\r\n this.firestore = firestore;\r\n }\r\n Query.prototype.where = function (field, opStr, value) {\r\n validateExactNumberOfArgs('Query.where', arguments, 3);\r\n validateDefined('Query.where', 3, value);\r\n // Enumerated from the WhereFilterOp type in index.d.ts.\r\n var whereFilterOpEnums = ['<', '<=', '==', '>=', '>', 'array-contains'];\r\n validateStringEnum('Query.where', whereFilterOpEnums, 2, opStr);\r\n var fieldValue;\r\n var fieldPath = fieldPathFromArgument('Query.where', field);\r\n var relationOp = RelationOp.fromString(opStr);\r\n if (fieldPath.isKeyField()) {\r\n if (relationOp === RelationOp.ARRAY_CONTAINS) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid Query. You can't perform array-contains queries on \" +\r\n 'FieldPath.documentId() since document IDs are not arrays.');\r\n }\r\n if (typeof value === 'string') {\r\n if (value === '') {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Function Query.where() requires its third parameter to be a ' +\r\n 'valid document ID if the first parameter is ' +\r\n 'FieldPath.documentId(), but it was an empty string.');\r\n }\r\n if (!this._query.isCollectionGroupQuery() &&\r\n value.indexOf('/') !== -1) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid third parameter to Query.where(). When querying a collection by \" +\r\n \"FieldPath.documentId(), the value provided must be a plain document ID, but \" +\r\n (\"'\" + value + \"' contains a slash.\"));\r\n }\r\n var path = this._query.path.child(ResourcePath.fromString(value));\r\n if (!DocumentKey.isDocumentKey(path)) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid third parameter to Query.where(). When querying a collection group by \" +\r\n \"FieldPath.documentId(), the value provided must result in a valid document path, \" +\r\n (\"but '\" + path + \"' is not because it has an odd number of segments (\" + path.length + \").\"));\r\n }\r\n fieldValue = new RefValue(this.firestore._databaseId, new DocumentKey(path));\r\n }\r\n else if (value instanceof DocumentReference) {\r\n var ref = value;\r\n fieldValue = new RefValue(this.firestore._databaseId, ref._key);\r\n }\r\n else {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function Query.where() requires its third parameter to be a \" +\r\n \"string or a DocumentReference if the first parameter is \" +\r\n \"FieldPath.documentId(), but it was: \" +\r\n (valueDescription(value) + \".\"));\r\n }\r\n }\r\n else {\r\n fieldValue = this.firestore._dataConverter.parseQueryValue('Query.where', value);\r\n }\r\n var filter = Filter.create(fieldPath, relationOp, fieldValue);\r\n this.validateNewFilter(filter);\r\n return new Query(this._query.addFilter(filter), this.firestore);\r\n };\r\n Query.prototype.orderBy = function (field, directionStr) {\r\n validateBetweenNumberOfArgs('Query.orderBy', arguments, 1, 2);\r\n validateOptionalArgType('Query.orderBy', 'non-empty string', 2, directionStr);\r\n var direction;\r\n if (directionStr === undefined || directionStr === 'asc') {\r\n direction = Direction.ASCENDING;\r\n }\r\n else if (directionStr === 'desc') {\r\n direction = Direction.DESCENDING;\r\n }\r\n else {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function Query.orderBy() has unknown direction '\" + directionStr + \"', \" +\r\n \"expected 'asc' or 'desc'.\");\r\n }\r\n if (this._query.startAt !== null) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call Query.startAt() or ' +\r\n 'Query.startAfter() before calling Query.orderBy().');\r\n }\r\n if (this._query.endAt !== null) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call Query.endAt() or ' +\r\n 'Query.endBefore() before calling Query.orderBy().');\r\n }\r\n var fieldPath = fieldPathFromArgument('Query.orderBy', field);\r\n var orderBy = new OrderBy(fieldPath, direction);\r\n this.validateNewOrderBy(orderBy);\r\n return new Query(this._query.addOrderBy(orderBy), this.firestore);\r\n };\r\n Query.prototype.limit = function (n) {\r\n validateExactNumberOfArgs('Query.limit', arguments, 1);\r\n validateArgType('Query.limit', 'number', 1, n);\r\n if (n <= 0) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid Query. Query limit (\" + n + \") is invalid. Limit must be \" +\r\n 'positive.');\r\n }\r\n return new Query(this._query.withLimit(n), this.firestore);\r\n };\r\n Query.prototype.startAt = function (docOrField) {\r\n var fields = [];\r\n for (var _i = 1; _i < arguments.length; _i++) {\r\n fields[_i - 1] = arguments[_i];\r\n }\r\n validateAtLeastNumberOfArgs('Query.startAt', arguments, 1);\r\n var bound = this.boundFromDocOrFields('Query.startAt', docOrField, fields, \r\n /*before=*/ true);\r\n return new Query(this._query.withStartAt(bound), this.firestore);\r\n };\r\n Query.prototype.startAfter = function (docOrField) {\r\n var fields = [];\r\n for (var _i = 1; _i < arguments.length; _i++) {\r\n fields[_i - 1] = arguments[_i];\r\n }\r\n validateAtLeastNumberOfArgs('Query.startAfter', arguments, 1);\r\n var bound = this.boundFromDocOrFields('Query.startAfter', docOrField, fields, \r\n /*before=*/ false);\r\n return new Query(this._query.withStartAt(bound), this.firestore);\r\n };\r\n Query.prototype.endBefore = function (docOrField) {\r\n var fields = [];\r\n for (var _i = 1; _i < arguments.length; _i++) {\r\n fields[_i - 1] = arguments[_i];\r\n }\r\n validateAtLeastNumberOfArgs('Query.endBefore', arguments, 1);\r\n var bound = this.boundFromDocOrFields('Query.endBefore', docOrField, fields, \r\n /*before=*/ true);\r\n return new Query(this._query.withEndAt(bound), this.firestore);\r\n };\r\n Query.prototype.endAt = function (docOrField) {\r\n var fields = [];\r\n for (var _i = 1; _i < arguments.length; _i++) {\r\n fields[_i - 1] = arguments[_i];\r\n }\r\n validateAtLeastNumberOfArgs('Query.endAt', arguments, 1);\r\n var bound = this.boundFromDocOrFields('Query.endAt', docOrField, fields, \r\n /*before=*/ false);\r\n return new Query(this._query.withEndAt(bound), this.firestore);\r\n };\r\n Query.prototype.isEqual = function (other) {\r\n if (!(other instanceof Query)) {\r\n throw invalidClassError('isEqual', 'Query', 1, other);\r\n }\r\n return (this.firestore === other.firestore && this._query.isEqual(other._query));\r\n };\r\n /** Helper function to create a bound from a document or fields */\r\n Query.prototype.boundFromDocOrFields = function (methodName, docOrField, fields, before) {\r\n validateDefined(methodName, 1, docOrField);\r\n if (docOrField instanceof DocumentSnapshot) {\r\n if (fields.length > 0) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Too many arguments provided to \" + methodName + \"().\");\r\n }\r\n var snap = docOrField;\r\n if (!snap.exists) {\r\n throw new FirestoreError(Code.NOT_FOUND, \"Can't use a DocumentSnapshot that doesn't exist for \" +\r\n (methodName + \"().\"));\r\n }\r\n return this.boundFromDocument(methodName, snap._document, before);\r\n }\r\n else {\r\n var allFields = [docOrField].concat(fields);\r\n return this.boundFromFields(methodName, allFields, before);\r\n }\r\n };\r\n /**\r\n * Create a Bound from a query and a document.\r\n *\r\n * Note that the Bound will always include the key of the document\r\n * and so only the provided document will compare equal to the returned\r\n * position.\r\n *\r\n * Will throw if the document does not contain all fields of the order by\r\n * of the query or if any of the fields in the order by are an uncommitted\r\n * server timestamp.\r\n */\r\n Query.prototype.boundFromDocument = function (methodName, doc, before) {\r\n var components = [];\r\n // Because people expect to continue/end a query at the exact document\r\n // provided, we need to use the implicit sort order rather than the explicit\r\n // sort order, because it's guaranteed to contain the document key. That way\r\n // the position becomes unambiguous and the query continues/ends exactly at\r\n // the provided document. Without the key (by using the explicit sort\r\n // orders), multiple documents could match the position, yielding duplicate\r\n // results.\r\n for (var _i = 0, _a = this._query.orderBy; _i < _a.length; _i++) {\r\n var orderBy = _a[_i];\r\n if (orderBy.field.isKeyField()) {\r\n components.push(new RefValue(this.firestore._databaseId, doc.key));\r\n }\r\n else {\r\n var value = doc.field(orderBy.field);\r\n if (value instanceof ServerTimestampValue) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You are trying to start or end a query using a ' +\r\n 'document for which the field \"' +\r\n orderBy.field +\r\n '\" is an uncommitted server timestamp. (Since the value of ' +\r\n 'this field is unknown, you cannot start/end a query with it.)');\r\n }\r\n else if (value !== undefined) {\r\n components.push(value);\r\n }\r\n else {\r\n var field = orderBy.field.canonicalString();\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. You are trying to start or end a query using a \" +\r\n (\"document for which the field '\" + field + \"' (used as the \") +\r\n \"orderBy) does not exist.\");\r\n }\r\n }\r\n }\r\n return new Bound(components, before);\r\n };\r\n /**\r\n * Converts a list of field values to a Bound for the given query.\r\n */\r\n Query.prototype.boundFromFields = function (methodName, values, before) {\r\n // Use explicit order by's because it has to match the query the user made\r\n var orderBy = this._query.explicitOrderBy;\r\n if (values.length > orderBy.length) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Too many arguments provided to \" + methodName + \"(). \" +\r\n \"The number of arguments must be less than or equal to the \" +\r\n \"number of Query.orderBy() clauses\");\r\n }\r\n var components = [];\r\n for (var i = 0; i < values.length; i++) {\r\n var rawValue = values[i];\r\n var orderByComponent = orderBy[i];\r\n if (orderByComponent.field.isKeyField()) {\r\n if (typeof rawValue !== 'string') {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. Expected a string for document ID in \" +\r\n (methodName + \"(), but got a \" + typeof rawValue));\r\n }\r\n if (!this._query.isCollectionGroupQuery() &&\r\n rawValue.indexOf('/') !== -1) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. When querying a collection and ordering by FieldPath.documentId(), \" +\r\n (\"the value passed to \" + methodName + \"() must be a plain document ID, but \") +\r\n (\"'\" + rawValue + \"' contains a slash.\"));\r\n }\r\n var path = this._query.path.child(ResourcePath.fromString(rawValue));\r\n if (!DocumentKey.isDocumentKey(path)) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. When querying a collection group and ordering by \" +\r\n (\"FieldPath.documentId(), the value passed to \" + methodName + \"() must result in a \") +\r\n (\"valid document path, but '\" + path + \"' is not because it contains an odd number \") +\r\n \"of segments.\");\r\n }\r\n var key = new DocumentKey(path);\r\n components.push(new RefValue(this.firestore._databaseId, key));\r\n }\r\n else {\r\n var wrapped = this.firestore._dataConverter.parseQueryValue(methodName, rawValue);\r\n components.push(wrapped);\r\n }\r\n }\r\n return new Bound(components, before);\r\n };\r\n Query.prototype.onSnapshot = function () {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n validateBetweenNumberOfArgs('Query.onSnapshot', arguments, 1, 4);\r\n var options = {};\r\n var observer;\r\n var currArg = 0;\r\n if (typeof args[currArg] === 'object' &&\r\n !isPartialObserver(args[currArg])) {\r\n options = args[currArg];\r\n validateOptionNames('Query.onSnapshot', options, [\r\n 'includeMetadataChanges'\r\n ]);\r\n validateNamedOptionalType('Query.onSnapshot', 'boolean', 'includeMetadataChanges', options.includeMetadataChanges);\r\n currArg++;\r\n }\r\n if (isPartialObserver(args[currArg])) {\r\n observer = args[currArg];\r\n }\r\n else {\r\n validateArgType('Query.onSnapshot', 'function', currArg, args[currArg]);\r\n validateOptionalArgType('Query.onSnapshot', 'function', currArg + 1, args[currArg + 1]);\r\n validateOptionalArgType('Query.onSnapshot', 'function', currArg + 2, args[currArg + 2]);\r\n observer = {\r\n next: args[currArg],\r\n error: args[currArg + 1],\r\n complete: args[currArg + 2]\r\n };\r\n }\r\n return this.onSnapshotInternal(options, observer);\r\n };\r\n Query.prototype.onSnapshotInternal = function (options, observer) {\r\n var _this = this;\r\n var errHandler = function (err) {\r\n console.error('Uncaught Error in onSnapshot:', err);\r\n };\r\n if (observer.error) {\r\n errHandler = observer.error.bind(observer);\r\n }\r\n var asyncObserver = new AsyncObserver({\r\n next: function (result) {\r\n if (observer.next) {\r\n observer.next(new QuerySnapshot(_this.firestore, _this._query, result));\r\n }\r\n },\r\n error: errHandler\r\n });\r\n var firestoreClient = this.firestore.ensureClientConfigured();\r\n var internalListener = firestoreClient.listen(this._query, asyncObserver, options);\r\n return function () {\r\n asyncObserver.mute();\r\n firestoreClient.unlisten(internalListener);\r\n };\r\n };\r\n Query.prototype.get = function (options) {\r\n var _this = this;\r\n validateBetweenNumberOfArgs('Query.get', arguments, 0, 1);\r\n validateGetOptions('Query.get', options);\r\n return new Promise(function (resolve, reject) {\r\n if (options && options.source === 'cache') {\r\n _this.firestore\r\n .ensureClientConfigured()\r\n .getDocumentsFromLocalCache(_this._query)\r\n .then(function (viewSnap) {\r\n resolve(new QuerySnapshot(_this.firestore, _this._query, viewSnap));\r\n }, reject);\r\n }\r\n else {\r\n _this.getViaSnapshotListener(resolve, reject, options);\r\n }\r\n });\r\n };\r\n Query.prototype.getViaSnapshotListener = function (resolve, reject, options) {\r\n var unlisten = this.onSnapshotInternal({\r\n includeMetadataChanges: true,\r\n waitForSyncWhenOnline: true\r\n }, {\r\n next: function (result) {\r\n // Remove query first before passing event to user to avoid\r\n // user actions affecting the now stale query.\r\n unlisten();\r\n if (result.metadata.fromCache &&\r\n options &&\r\n options.source === 'server') {\r\n reject(new FirestoreError(Code.UNAVAILABLE, 'Failed to get documents from server. (However, these ' +\r\n 'documents may exist in the local cache. Run again ' +\r\n 'without setting source to \"server\" to ' +\r\n 'retrieve the cached documents.)'));\r\n }\r\n else {\r\n resolve(result);\r\n }\r\n },\r\n error: reject\r\n });\r\n };\r\n Query.prototype.validateNewFilter = function (filter) {\r\n if (filter instanceof RelationFilter) {\r\n if (filter.isInequality()) {\r\n var existingField = this._query.getInequalityFilterField();\r\n if (existingField !== null && !existingField.isEqual(filter.field)) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. All where filters with an inequality' +\r\n ' (<, <=, >, or >=) must be on the same field. But you have' +\r\n (\" inequality filters on '\" + existingField.toString() + \"'\") +\r\n (\" and '\" + filter.field.toString() + \"'\"));\r\n }\r\n var firstOrderByField = this._query.getFirstOrderByField();\r\n if (firstOrderByField !== null) {\r\n this.validateOrderByAndInequalityMatch(filter.field, firstOrderByField);\r\n }\r\n }\r\n else if (filter.op === RelationOp.ARRAY_CONTAINS) {\r\n if (this._query.hasArrayContainsFilter()) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. Queries only support a single array-contains ' +\r\n 'filter.');\r\n }\r\n }\r\n }\r\n };\r\n Query.prototype.validateNewOrderBy = function (orderBy) {\r\n if (this._query.getFirstOrderByField() === null) {\r\n // This is the first order by. It must match any inequality.\r\n var inequalityField = this._query.getInequalityFilterField();\r\n if (inequalityField !== null) {\r\n this.validateOrderByAndInequalityMatch(inequalityField, orderBy.field);\r\n }\r\n }\r\n };\r\n Query.prototype.validateOrderByAndInequalityMatch = function (inequality, orderBy) {\r\n if (!orderBy.isEqual(inequality)) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. You have a where filter with an inequality \" +\r\n (\"(<, <=, >, or >=) on field '\" + inequality.toString() + \"' \") +\r\n (\"and so you must also use '\" + inequality.toString() + \"' \") +\r\n \"as your first Query.orderBy(), but your first Query.orderBy() \" +\r\n (\"is on field '\" + orderBy.toString() + \"' instead.\"));\r\n }\r\n };\r\n return Query;\r\n}());\r\nvar QuerySnapshot = /** @class */ (function () {\r\n function QuerySnapshot(_firestore, _originalQuery, _snapshot) {\r\n this._firestore = _firestore;\r\n this._originalQuery = _originalQuery;\r\n this._snapshot = _snapshot;\r\n this._cachedChanges = null;\r\n this._cachedChangesIncludeMetadataChanges = null;\r\n this.metadata = new SnapshotMetadata(_snapshot.hasPendingWrites, _snapshot.fromCache);\r\n }\r\n Object.defineProperty(QuerySnapshot.prototype, \"docs\", {\r\n get: function () {\r\n var result = [];\r\n this.forEach(function (doc) { return result.push(doc); });\r\n return result;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(QuerySnapshot.prototype, \"empty\", {\r\n get: function () {\r\n return this._snapshot.docs.isEmpty();\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(QuerySnapshot.prototype, \"size\", {\r\n get: function () {\r\n return this._snapshot.docs.size;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n QuerySnapshot.prototype.forEach = function (callback, thisArg) {\r\n var _this = this;\r\n validateBetweenNumberOfArgs('QuerySnapshot.forEach', arguments, 1, 2);\r\n validateArgType('QuerySnapshot.forEach', 'function', 1, callback);\r\n this._snapshot.docs.forEach(function (doc) {\r\n callback.call(thisArg, _this.convertToDocumentImpl(doc));\r\n });\r\n };\r\n Object.defineProperty(QuerySnapshot.prototype, \"query\", {\r\n get: function () {\r\n return new Query$1(this._originalQuery, this._firestore);\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n QuerySnapshot.prototype.docChanges = function (options) {\r\n if (options) {\r\n validateOptionNames('QuerySnapshot.docChanges', options, [\r\n 'includeMetadataChanges'\r\n ]);\r\n validateNamedOptionalType('QuerySnapshot.docChanges', 'boolean', 'includeMetadataChanges', options.includeMetadataChanges);\r\n }\r\n var includeMetadataChanges = !!(options && options.includeMetadataChanges);\r\n if (includeMetadataChanges && this._snapshot.excludesMetadataChanges) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'To include metadata changes with your document changes, you must ' +\r\n 'also pass { includeMetadataChanges:true } to onSnapshot().');\r\n }\r\n if (!this._cachedChanges ||\r\n this._cachedChangesIncludeMetadataChanges !== includeMetadataChanges) {\r\n this._cachedChanges = changesFromSnapshot(this._firestore, includeMetadataChanges, this._snapshot);\r\n this._cachedChangesIncludeMetadataChanges = includeMetadataChanges;\r\n }\r\n return this._cachedChanges;\r\n };\r\n /** Check the equality. The call can be very expensive. */\r\n QuerySnapshot.prototype.isEqual = function (other) {\r\n if (!(other instanceof QuerySnapshot)) {\r\n throw invalidClassError('isEqual', 'QuerySnapshot', 1, other);\r\n }\r\n return (this._firestore === other._firestore &&\r\n this._originalQuery.isEqual(other._originalQuery) &&\r\n this._snapshot.isEqual(other._snapshot));\r\n };\r\n QuerySnapshot.prototype.convertToDocumentImpl = function (doc) {\r\n return new QueryDocumentSnapshot(this._firestore, doc.key, doc, this.metadata.fromCache, this._snapshot.mutatedKeys.has(doc.key));\r\n };\r\n return QuerySnapshot;\r\n}());\r\n// TODO(2018/11/01): As of 2018/04/17 we're changing docChanges from an array\r\n// into a method. Because this is a runtime breaking change and somewhat subtle\r\n// (both Array and Function have a .length, etc.), we'll replace commonly-used\r\n// properties (including Symbol.iterator) to throw a custom error message. In\r\n// ~6 months we can delete the custom error as most folks will have hopefully\r\n// migrated.\r\nfunction throwDocChangesMethodError() {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'QuerySnapshot.docChanges has been changed from a property into a ' +\r\n 'method, so usages like \"querySnapshot.docChanges\" should become ' +\r\n '\"querySnapshot.docChanges()\"');\r\n}\r\nvar docChangesPropertiesToOverride = [\r\n 'length',\r\n 'forEach',\r\n 'map'\r\n].concat((typeof Symbol !== 'undefined' ? [Symbol.iterator] : []));\r\ndocChangesPropertiesToOverride.forEach(function (property) {\r\n /**\r\n * We are (re-)defining properties on QuerySnapshot.prototype.docChanges which\r\n * is a Function. This could fail, in particular in the case of 'length' which\r\n * already exists on Function.prototype and on IE11 is improperly defined with\r\n * `{ configurable: false }`. So we wrap this in a try/catch to ensure that we\r\n * still have a functional SDK.\r\n */\r\n try {\r\n Object.defineProperty(QuerySnapshot.prototype.docChanges, property, {\r\n get: function () { return throwDocChangesMethodError(); }\r\n });\r\n }\r\n catch (err) { } // Ignore this failure intentionally\r\n});\r\nvar CollectionReference = /** @class */ (function (_super) {\r\n tslib_1.__extends(CollectionReference, _super);\r\n function CollectionReference(path, firestore) {\r\n var _this = _super.call(this, Query.atPath(path), firestore) || this;\r\n if (path.length % 2 !== 1) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid collection reference. Collection ' +\r\n 'references must have an odd number of segments, but ' +\r\n (path.canonicalString() + \" has \" + path.length));\r\n }\r\n return _this;\r\n }\r\n Object.defineProperty(CollectionReference.prototype, \"id\", {\r\n get: function () {\r\n return this._query.path.lastSegment();\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(CollectionReference.prototype, \"parent\", {\r\n get: function () {\r\n var parentPath = this._query.path.popLast();\r\n if (parentPath.isEmpty()) {\r\n return null;\r\n }\r\n else {\r\n return new DocumentReference(new DocumentKey(parentPath), this.firestore);\r\n }\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n Object.defineProperty(CollectionReference.prototype, \"path\", {\r\n get: function () {\r\n return this._query.path.canonicalString();\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n CollectionReference.prototype.doc = function (pathString) {\r\n validateBetweenNumberOfArgs('CollectionReference.doc', arguments, 0, 1);\r\n // We allow omission of 'pathString' but explicitly prohibit passing in both\r\n // 'undefined' and 'null'.\r\n if (arguments.length === 0) {\r\n pathString = AutoId.newId();\r\n }\r\n validateArgType('CollectionReference.doc', 'non-empty string', 1, pathString);\r\n if (pathString === '') {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Document path must be a non-empty string');\r\n }\r\n var path = ResourcePath.fromString(pathString);\r\n return DocumentReference.forPath(this._query.path.child(path), this.firestore);\r\n };\r\n CollectionReference.prototype.add = function (value) {\r\n validateExactNumberOfArgs('CollectionReference.add', arguments, 1);\r\n validateArgType('CollectionReference.add', 'object', 1, value);\r\n var docRef = this.doc();\r\n return docRef.set(value).then(function () { return docRef; });\r\n };\r\n return CollectionReference;\r\n}(Query$1));\r\nfunction validateSetOptions(methodName, options) {\r\n if (options === undefined) {\r\n return {\r\n merge: false\r\n };\r\n }\r\n validateOptionNames(methodName, options, ['merge', 'mergeFields']);\r\n validateNamedOptionalType(methodName, 'boolean', 'merge', options.merge);\r\n validateOptionalArrayElements(methodName, 'mergeFields', 'a string or a FieldPath', options.mergeFields, function (element) {\r\n return typeof element === 'string' || element instanceof FieldPath$1;\r\n });\r\n if (options.mergeFields !== undefined && options.merge !== undefined) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid options passed to function \" + methodName + \"(): You cannot specify both \\\"merge\\\" \" +\r\n \"and \\\"mergeFields\\\".\");\r\n }\r\n return options;\r\n}\r\nfunction validateSnapshotOptions(methodName, options) {\r\n if (options === undefined) {\r\n return {};\r\n }\r\n validateOptionNames(methodName, options, ['serverTimestamps']);\r\n validateNamedOptionalPropertyEquals(methodName, 'options', 'serverTimestamps', options.serverTimestamps, ['estimate', 'previous', 'none']);\r\n return options;\r\n}\r\nfunction validateGetOptions(methodName, options) {\r\n validateOptionalArgType(methodName, 'object', 1, options);\r\n if (options) {\r\n validateOptionNames(methodName, options, ['source']);\r\n validateNamedOptionalPropertyEquals(methodName, 'options', 'source', options.source, ['default', 'server', 'cache']);\r\n }\r\n}\r\nfunction validateReference(methodName, documentRef, firestore) {\r\n if (!(documentRef instanceof DocumentReference)) {\r\n throw invalidClassError(methodName, 'DocumentReference', 1, documentRef);\r\n }\r\n else if (documentRef.firestore !== firestore) {\r\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Provided document reference is from a different Firestore instance.');\r\n }\r\n else {\r\n return documentRef;\r\n }\r\n}\r\n/**\r\n * Calculates the array of firestore.DocumentChange's for a given ViewSnapshot.\r\n *\r\n * Exported for testing.\r\n */\r\nfunction changesFromSnapshot(firestore, includeMetadataChanges, snapshot) {\r\n if (snapshot.oldDocs.isEmpty()) {\r\n // Special case the first snapshot because index calculation is easy and\r\n // fast\r\n var lastDoc_1;\r\n var index_1 = 0;\r\n return snapshot.docChanges.map(function (change) {\r\n var doc = new QueryDocumentSnapshot(firestore, change.doc.key, change.doc, snapshot.fromCache, snapshot.mutatedKeys.has(change.doc.key));\r\n assert(change.type === ChangeType.Added, 'Invalid event type for first snapshot');\r\n assert(!lastDoc_1 || snapshot.query.docComparator(lastDoc_1, change.doc) < 0, 'Got added events in wrong order');\r\n lastDoc_1 = change.doc;\r\n return {\r\n type: 'added',\r\n doc: doc,\r\n oldIndex: -1,\r\n newIndex: index_1++\r\n };\r\n });\r\n }\r\n else {\r\n // A DocumentSet that is updated incrementally as changes are applied to use\r\n // to lookup the index of a document.\r\n var indexTracker_1 = snapshot.oldDocs;\r\n return snapshot.docChanges\r\n .filter(function (change) { return includeMetadataChanges || change.type !== ChangeType.Metadata; })\r\n .map(function (change) {\r\n var doc = new QueryDocumentSnapshot(firestore, change.doc.key, change.doc, snapshot.fromCache, snapshot.mutatedKeys.has(change.doc.key));\r\n var oldIndex = -1;\r\n var newIndex = -1;\r\n if (change.type !== ChangeType.Added) {\r\n oldIndex = indexTracker_1.indexOf(change.doc.key);\r\n assert(oldIndex >= 0, 'Index for document not found');\r\n indexTracker_1 = indexTracker_1.delete(change.doc.key);\r\n }\r\n if (change.type !== ChangeType.Removed) {\r\n indexTracker_1 = indexTracker_1.add(change.doc);\r\n newIndex = indexTracker_1.indexOf(change.doc.key);\r\n }\r\n return { type: resultChangeType(change.type), doc: doc, oldIndex: oldIndex, newIndex: newIndex };\r\n });\r\n }\r\n}\r\nfunction resultChangeType(type) {\r\n switch (type) {\r\n case ChangeType.Added:\r\n return 'added';\r\n case ChangeType.Modified:\r\n case ChangeType.Metadata:\r\n return 'modified';\r\n case ChangeType.Removed:\r\n return 'removed';\r\n default:\r\n return fail('Unknown change type: ' + type);\r\n }\r\n}\r\n// Export the classes with a private constructor (it will fail if invoked\r\n// at runtime). Note that this still allows instanceof checks.\r\n// We're treating the variables as class names, so disable checking for lower\r\n// case variable names.\r\n// tslint:disable:variable-name\r\nvar PublicFirestore = makeConstructorPrivate(Firestore, 'Use firebase.firestore() instead.');\r\nvar PublicTransaction = makeConstructorPrivate(Transaction$1, 'Use firebase.firestore().runTransaction() instead.');\r\nvar PublicWriteBatch = makeConstructorPrivate(WriteBatch, 'Use firebase.firestore().batch() instead.');\r\nvar PublicDocumentReference = makeConstructorPrivate(DocumentReference, 'Use firebase.firestore().doc() instead.');\r\nvar PublicDocumentSnapshot = makeConstructorPrivate(DocumentSnapshot);\r\nvar PublicQueryDocumentSnapshot = makeConstructorPrivate(QueryDocumentSnapshot);\r\nvar PublicQuery = makeConstructorPrivate(Query$1);\r\nvar PublicQuerySnapshot = makeConstructorPrivate(QuerySnapshot);\r\nvar PublicCollectionReference = makeConstructorPrivate(CollectionReference, 'Use firebase.firestore().collection() instead.');\r\n// tslint:enable:variable-name\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar firestoreNamespace = {\r\n Firestore: PublicFirestore,\r\n GeoPoint: GeoPoint,\r\n Timestamp: Timestamp,\r\n Blob: PublicBlob,\r\n Transaction: PublicTransaction,\r\n WriteBatch: PublicWriteBatch,\r\n DocumentReference: PublicDocumentReference,\r\n DocumentSnapshot: PublicDocumentSnapshot,\r\n Query: PublicQuery,\r\n QueryDocumentSnapshot: PublicQueryDocumentSnapshot,\r\n QuerySnapshot: PublicQuerySnapshot,\r\n CollectionReference: PublicCollectionReference,\r\n FieldPath: FieldPath$1,\r\n FieldValue: PublicFieldValue,\r\n setLogLevel: Firestore.setLogLevel,\r\n CACHE_SIZE_UNLIMITED: CACHE_SIZE_UNLIMITED\r\n};\r\n/**\r\n * Configures Firestore as part of the Firebase SDK by calling registerService.\r\n */\r\nfunction configureForFirebase(firebase) {\r\n firebase.INTERNAL.registerService('firestore', function (app) { return new Firestore(app); }, shallowCopy(firestoreNamespace));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction registerFirestore(instance) {\r\n configureForFirebase(instance);\r\n}\r\nregisterFirestore(firebase);\n\nexports.registerFirestore = registerFirestore;\n//# sourceMappingURL=index.cjs.js.map\n"],"sourceRoot":""}