{"version":3,"sources":["webpack:///firebase-database.js","webpack:///../database/dist/cjs/src/core/util/util.js","webpack:///../database/dist/cjs/src/core/util/Path.js","webpack:///../database/dist/cjs/src/core/snap/indexes/PriorityIndex.js","webpack:///../database/dist/cjs/src/core/snap/ChildrenNode.js","webpack:///../database/dist/cjs/src/core/snap/Node.js","webpack:///../database/dist/cjs/src/core/util/validation.js","webpack:///../database/dist/cjs/src/core/operation/Operation.js","webpack:///../database/dist/cjs/src/core/view/Change.js","webpack:///../database/dist/cjs/src/core/snap/indexes/KeyIndex.js","webpack:///../database/dist/cjs/src/core/snap/nodeFromJSON.js","webpack:///../database/dist/cjs/src/core/storage/storage.js","webpack:///../database/dist/cjs/src/realtime/Constants.js","webpack:///../database/dist/cjs/src/core/snap/indexes/Index.js","webpack:///../database/dist/cjs/src/core/snap/LeafNode.js","webpack:///../database/dist/cjs/src/core/util/SortedMap.js","webpack:///../database/dist/cjs/src/core/Repo.js","webpack:///../database/dist/cjs/src/core/view/CacheNode.js","webpack:///../database/dist/cjs/src/api/Reference.js","webpack:///../database/dist/cjs/src/api/DataSnapshot.js","webpack:///../database/dist/cjs/src/core/util/ImmutableTree.js","webpack:///../database/dist/cjs/src/core/view/filter/IndexedFilter.js","webpack:///../database/dist/cjs/src/core/stats/StatsManager.js","webpack:///../database/dist/cjs/src/core/RepoManager.js","webpack:///../database/dist/cjs/src/api/Database.js","webpack:///../database/dist/cjs/src/core/util/libs/parser.js","webpack:///../database/dist/cjs/src/core/RepoInfo.js","webpack:///../database/dist/cjs/src/api/onDisconnect.js","webpack:///../database/dist/cjs/src/api/Query.js","webpack:///../database/dist/cjs/src/core/snap/snap.js","webpack:///../database/dist/cjs/src/core/snap/indexes/ValueIndex.js","webpack:///../database/dist/cjs/src/core/snap/IndexMap.js","webpack:///../database/dist/cjs/src/core/snap/childSet.js","webpack:///../database/dist/cjs/src/core/snap/comparators.js","webpack:///../database/dist/cjs/src/core/snap/indexes/PathIndex.js","webpack:///../database/dist/cjs/src/core/util/ServerValues.js","webpack:///../database/dist/cjs/src/core/SparseSnapshotTree.js","webpack:///../database/dist/cjs/src/core/util/CountedSet.js","webpack:///../database/dist/cjs/src/core/operation/Overwrite.js","webpack:///../database/dist/cjs/src/core/SyncPoint.js","webpack:///../database/dist/cjs/src/core/view/ViewCache.js","webpack:///../database/dist/cjs/src/core/stats/StatsListener.js","webpack:///../database/dist/cjs/src/core/PersistentConnection.js","webpack:///../database/dist/cjs/src/core/util/EventEmitter.js","webpack:///../database/dist/cjs/src/realtime/Connection.js","webpack:///../database/dist/cjs/src/realtime/BrowserPollConnection.js","webpack:///../database/dist/cjs/src/realtime/WebSocketConnection.js","webpack:///../database/dist/cjs/src/core/ServerActions.js","webpack:///../database/dist/cjs/src/core/view/filter/RangedFilter.js","webpack:///./database/index.js","webpack:///../database/dist/cjs/index.js","webpack:///../database/dist/cjs/src/core/storage/DOMStorageWrapper.js","webpack:///../database/dist/cjs/src/core/storage/MemoryStorage.js","webpack:///../database/dist/cjs/src/api/TransactionResult.js","webpack:///../database/dist/cjs/src/core/util/NextPushId.js","webpack:///../database/dist/cjs/src/core/view/EventRegistration.js","webpack:///../database/dist/cjs/src/core/view/Event.js","webpack:///../database/dist/cjs/src/core/SyncTree.js","webpack:///../database/dist/cjs/src/core/operation/AckUserWrite.js","webpack:///../database/dist/cjs/src/core/operation/ListenComplete.js","webpack:///../database/dist/cjs/src/core/operation/Merge.js","webpack:///../database/dist/cjs/src/core/view/View.js","webpack:///../database/dist/cjs/src/core/view/ViewProcessor.js","webpack:///../database/dist/cjs/src/core/view/ChildChangeAccumulator.js","webpack:///../database/dist/cjs/src/core/view/CompleteChildSource.js","webpack:///../database/dist/cjs/src/core/view/EventGenerator.js","webpack:///../database/dist/cjs/src/core/WriteTree.js","webpack:///../database/dist/cjs/src/core/CompoundWrite.js","webpack:///../database/dist/cjs/src/core/SnapshotHolder.js","webpack:///../database/dist/cjs/src/core/AuthTokenProvider.js","webpack:///../database/dist/cjs/src/core/stats/StatsCollection.js","webpack:///../database/dist/cjs/src/core/stats/StatsReporter.js","webpack:///../database/dist/cjs/src/core/view/EventQueue.js","webpack:///../database/dist/cjs/src/core/util/VisibilityMonitor.js","webpack:///../database/dist/cjs/src/core/util/OnlineMonitor.js","webpack:///../database/dist/cjs/src/realtime/TransportManager.js","webpack:///../database/dist/cjs/src/realtime/polling/PacketReceiver.js","webpack:///../database/dist/cjs/src/core/ReadonlyRestClient.js","webpack:///../database/dist/cjs/src/core/view/QueryParams.js","webpack:///../database/dist/cjs/src/core/view/filter/LimitedFilter.js","webpack:///../database/dist/cjs/src/core/Repo_transaction.js","webpack:///../database/dist/cjs/src/core/util/Tree.js","webpack:///../database/dist/cjs/src/api/internal.js","webpack:///../database/dist/cjs/src/api/test_access.js"],"names":["webpackJsonpFirebase","module","exports","__webpack_require__","Object","defineProperty","value","util_1","util_2","util_3","util_4","util_5","util_6","storage_1","util_7","LUIDGenerator","id","sha1","str","utf8Bytes","stringToByteArray","Sha1","update","sha1Bytes","digest","base64","encodeByteArray","buildLogMessage_","var_args","_i","arguments","length","message","i","Array","isArray","apply","stringify","logger","firstLog_","enableLogging","logger_","persistent","assert","console","log","bind","SessionStorage","set","remove","get","logWrapper","prefix","concat","error","fatal","Error","warn","warnIfPageIsSecure","window","location","protocol","indexOf","warnAboutUnsupportedMethod","methodName","isInvalidJSONNumber","data","Number","POSITIVE_INFINITY","NEGATIVE_INFINITY","executeWhenDOMReady","fn","isNodeSdk","document","readyState","called_1","wrappedFn_1","body","setTimeout","Math","floor","addEventListener","attachEvent","MIN_NAME","MAX_NAME","nameCompare","a","b","aAsInt","tryParseInt","bAsInt","stringCompare","requireKey","key","obj","ObjectToUniqueKey","keys","k","push","sort","splitStringBySize","segsize","len","dataSegs","c","substring","each","forEach","val","bindCallback","callback","context","doubleToIEEE754String","v","s","e","f","ln","bits","abs","pow","min","LN2","round","reverse","join","hexByteString","hexByte","parseInt","substr","toString","toLowerCase","isChromeExtensionContentScript","test","href","isWindowsStoreApp","Windows","UI","errorForServerCode","code","query","reason","path","toUpperCase","INTEGER_REGEXP_","RegExp","intVal","exceptionGuard","stack","callUserCallback","beingCrawled","search","exportPropGetter","object","name","fnGet","setTimeoutNonBlocking","time","timeout","Path","pathOrString","pieceNum","this","pieces_","split","copyTo","pieceNum_","enumerable","configurable","prototype","getFront","getLength","popFront","getBack","pathString","toUrlEncodedString","encodeURIComponent","String","slice","begin","parent","pieces","child","childPathObj","childPieces","isEmpty","relativePath","outerPath","innerPath","outer","inner","comparePaths","left","right","leftKeys","rightKeys","cmp","equals","other","j","contains","ValidationPath","errorPrefix_","parts_","byteLength_","max","stringLength","checkValid_","pop","last","MAX_PATH_LENGTH_BYTES","MAX_PATH_DEPTH","toErrorString","setNodeFromJSON","nodeFromJSON","setMaxNode","MAX_NODE","tslib_1","Index_1","Node_1","LeafNode_1","PriorityIndex","_super","__extends","compare","aPriority","node","getPriority","bPriority","indexCmp","compareTo","isDefinedOn","indexedValueChanged","oldNode","newNode","minPost","NamedNode","MIN","maxPost","LeafNode","makePost","indexValue","priorityNode","Index","PRIORITY_INDEX","EMPTY_NODE","SortedMap_1","snap_1","PriorityIndex_1","KeyIndex_1","IndexMap_1","comparators_1","ChildrenNode","children_","priorityNode_","indexMap_","lazyHash_","validatePriorityNode","SortedMap","NAME_COMPARATOR","IndexMap","Default","isLeafNode","updatePriority","newPriorityNode","getImmediateChild","childName","getChild","front","hasChild","updateImmediateChild","newChildNode","namedNode","newChildren","newIndexMap","newPriority","removeFromIndexes","insert","addToIndexes","updateChild","newImmediateChild","numChildren","count","exportFormat","numKeys","maxKey","allIntegerKeys","forEachChild","childNode","array","hash","toHash_1","priorityHashText","childHash","getPredecessorChildName","index","idx","resolveIndex_","predecessor","getPredecessorKey","getFirstChildName","indexDefinition","minKey","getFirstChild","getLastChildName","getLastChild","action","inorderTraversal","wrappedNode","getIterator","getIteratorFrom","startPost","iterator","Wrap","next","peek","getNext","getReverseIterator","getReverseIteratorFrom","endPost","withIndex","KEY_INDEX","hasIndex","addIndex","isIndexed","otherChildrenNode","thisIter","otherIter","thisCurrent","otherCurrent","MaxNode","call","defineProperties","MAX","KeyIndex","__EMPTY_NODE","__childrenNodeConstructor","Path_1","INVALID_KEY_REGEX_","INVALID_PATH_REGEX_","MAX_LEAF_SIZE_","isValidKey","isValidPathString","isValidRootPathString","replace","isValidPriority","priority","validateFirebaseDataArg","fnName","argumentNumber","optional","undefined","validateFirebaseData","errorPrefix","path_","hasDotValue_1","hasActualChild_1","validateFirebaseMergePaths","mergePaths","curPath","prevPath","validateFirebaseMergeDataArg","validatePriority","validateEventType","eventType","validateKey","validatePathString","validateRootPathString","validateWritablePath","validateUrl","parsedUrl","repoInfo","host","namespace","validateCredential","cred","validateBoolean","bool","validateString","string","validateObject","validateObjectContainsKey","opt_type","safeGet","OperationType","OperationSource","fromUser","fromServer","queryId","tagged","User","Server","forServerTaggedQuery","Change","type","snapshotNode","oldSnap","prevName","valueChange","snapshot","VALUE","childAddedChange","childKey","CHILD_ADDED","childRemovedChange","CHILD_REMOVED","childChangedChange","newSnapshot","oldSnapshot","CHILD_CHANGED","childMovedChange","CHILD_MOVED","assertionError","json","ChildrenNode_1","jsonLeaf","USE_HINZE","node_1","jsonObj_1","childData","children_1","childrenHavePriority_1","hinzeJsonObj_1","childSet","childSet_1","buildChildSet","NAME_ONLY_COMPARATOR","sortedChildSet","getCompare",".priority","DOMStorageWrapper_1","MemoryStorage_1","createStoragefor","domStorageName","domStorage","setItem","removeItem","DOMStorageWrapper","MemoryStorage","PersistentStorage","PROTOCOL_VERSION","VERSION_PARAM","TRANSPORT_SESSION_PARAM","REFERER_PARAM","FORGE_REF","FORGE_DOMAIN","LAST_SESSION_PARAM","WEBSOCKET","LONG_POLLING","oldWrapped","newWrapped","value_",".value","getValue","toHash","compareToLeafNode_","otherLeaf","otherLeafType","thisLeafType","otherIndex","VALUE_TYPE_ORDER","thisIndex","SortedMapIterator","startKey","comparator","isReverse_","resultGenerator_","nodeStack_","result","hasNext","LLRBNode","color","RED","copy","reverseTraversal","min_","n","fixUp_","removeMin_","isRed_","moveRedLeft_","smallest","rotateRight_","moveRedRight_","rotateLeft_","colorFlip_","nl","nr","checkMaxDepth_","blackDepth","check_","BLACK","LLRBEmptyNode","comparator_","root_","rightParent","resultGenerator","ServerValues_1","nodeFromJSON_1","SparseSnapshotTree_1","SyncTree_1","SnapshotHolder_1","AuthTokenProvider_1","StatsManager_1","StatsReporter_1","StatsListener_1","EventQueue_1","PersistentConnection_1","ReadonlyRestClient_1","Database_1","Repo","repoInfo_","forceRestClient","app","_this","dataUpdateCount","statsListener_","eventQueue_","EventQueue","nextWriteId_","interceptServerDataCallback_","onDisconnect_","SparseSnapshotTree","persistentConnection_","authTokenProvider","AuthTokenProvider","stats_","StatsManager","getCollection","server_","ReadonlyRestClient","onDataUpdate_","onConnectStatus_","authOverride","options","PersistentConnection","onServerInfoUpdate_","addTokenChangeListener","token","refreshAuthToken","statsReporter_","getOrCreateReporter","StatsReporter","transactions_init_","infoData_","SnapshotHolder","infoSyncTree_","SyncTree","startListening","tag","currentHashFn","onComplete","infoEvents","getNode","applyServerOverwrite","stopListening","updateInfo_","serverSyncTree_","listen","status","events","raiseEventsForChangedPath","unlisten","secure","serverTime","offsetNode","offset","Date","getTime","generateServerValues","generateWithValues","timestamp","isMerge","taggedChildren","map","raw","applyTaggedQueryMerge","taggedSnap","applyTaggedQueryOverwrite","changedChildren","applyServerMerge","snap","affectedPath","rerunTransactions_","interceptServerData_","connectStatus","runOnDisconnectEvents_","updates","updateSnapshot","getNextWriteId_","setWithPriority","newVal","log_","serverValues","newNodeUnresolved","resolveDeferredValueSnapshot","writeId","applyUserOverwrite","queueEvents","put","errorReason","success","clearEvents","ackUserWrite","callOnCompleteCallback","abortTransactions_","childrenToMerge","empty","changedKey","changedValue","writeId_1","applyUserMerge","merge","changedPath","resolvedOnDisconnectTree","resolveDeferredValueTree","forEachTree","Empty","onDisconnectCancel","forget","onDisconnectSet","onDisconnectPut","remember","onDisconnectSetWithPriority","onDisconnectUpdate","onDisconnectMerge","addEventCallbackForQuery","eventRegistration","addEventRegistration","raiseEventsAtPath","removeEventCallbackForQuery","removeEventRegistration","interrupt","resume","stats","showDelta","StatsListener","longestName","reduce","previousValue","currentValue","stat","statsIncrementCounter","metric","incrementCounter","includeStat","__database","Database","CacheNode","node_","fullyInitialized_","filtered_","isFullyInitialized","isFiltered","isCompleteForPath","isCompleteForChild","onDisconnect_1","TransactionResult_1","NextPushId_1","Query_1","Repo_1","QueryParams_1","validation_1","SyncPoint_1","Reference","repo","QueryParams","DEFAULT","getKey","validateArgCount","getParent","parentPath","getRoot","ref","databaseProp","database","validateCallback","deferred","Deferred","wrapCallback","promise","objectToMerge","newObjectToMerge","transaction","transactionUpdate","applyLocally","catch","promiseComplete","committed","reject","resolve","TransactionResult","startTransaction","setPriority","now","nextPushId","thennablePushRef","pushRef","then","Promise","onDisconnect","OnDisconnect","Query","__referenceConstructor","SyncPoint","DataSnapshot","ref_","index_","exportVal","toJSON","exists","childPathString","childPath","childRef","hasChildren","getRef","emptyChildrenSingleton","EmptyChildren","ImmutableTree","children","fromObject","tree","childSnap","findRootMostMatchingPathAndValue","predicate","childExistingPathAndValue","findRootMostValueAndPath","subtree","childTree","toSet","newChild","setTree","newTree","fold","fold_","pathSoFar","accum","findOnPath","findOnPath_","pathToFollow","nextChild","foreachOnPath","foreachOnPath_","currentRelativePath","foreach","foreach_","foreachChild","Change_1","IndexedFilter","source","optChangeAccumulator","oldChild","trackChildChange","updateFullNode","newSnap","filtersNodes","getIndexedFilter","getIndex","StatsCollection_1","hashString","collections_","StatsCollection","creatorFunction","reporters_","parser_1","_staticInstance","RepoManager","repos_","useRestClient_","getInstance","appName","dbUrl","databaseFromApp","url","parseRepoInfo","createRepo","deleteRepo","appRepos","toURLString","Reference_1","RepoManager_1","repo_","INTERNAL","DatabaseInternals","checkDeleted_","refFromURL","apiName","parsedURL","goOffline","goOnline","ServerValue","TIMESTAMP",".sv","delete","__awaiter","__generator","_a","decodePath","pathStringDecoded","piece","decodeURIComponent","decodeQuery","queryString","results","startsWith","segment","kv","RepoInfo_1","dataURL","parseURL","subdomain","domain","webSocketOnly","scheme","RepoInfo","port","colonInd","slashInd","questionMarkInd","queryParams","parts","Constants_1","persistenceKey","internalHost","needsQueryParam","isCustomHost","isCacheableHost","isDemoHost","updateHost","newHost","connectionURL","params","connURL","pairs","cancel","ValueIndex_1","PathIndex_1","EventRegistration_1","queryParams_","orderByCalled_","validateQueryEndpoints_","startNode","endNode","hasStart","getIndexStartValue","hasEnd","getIndexEndValue","tooManyArgsError","wrongArgTypeError","getIndexStartName","getIndexEndName","PathIndex","VALUE_INDEX","validateLimit_","hasLimit","hasAnchoredLimit","validateNoPreviousOrderByCall_","getQueryParams","on","cancelCallbackOrContext","ret","getCancelAndContextArgs_","onValueEvent","callbacks","onChildEvent","cancelCallback","container","ValueEventRegistration","ChildEventRegistration","off","validateContextObject","valueCallback","once","userCallback","cancelOrContext","firstCall","onceCallback","err","limitToFirst","limit","limitToLast","orderByChild","parsedPath","newParams","orderBy","orderByKey","orderByPriority","orderByValue","startAt","endAt","equalTo","queryObject","getQueryObject","queryIdentifier","isEqual","sameRepo","samePath","sameQueryIdentifier","ValueIndex","valueNode","_defaultIndexMap","fallbackObject","indexes_","indexSet_","indexKey","sortedMap","existingChildren","childList","sawIndexedValue","iter","newIndex","indexName","newIndexSet","clone","newIndexes","indexedChildren","existingSnap","SortedMap_2","LOG_2","Base12Num","num","current_","mask","bits_","nextBitIsOne","keyFn","mapSortFn","buildBalancedTree","low","high","middle","base12","root","buildPennant","chunkSize","attachPennant","pennant","isOne","indexPath_","extractChild","aChild","bChild","values","resolveDeferredValue","resolvedTree","rawPri","leafNode","childrenNode","CountedSet_1","find","CountedSet","add","self_1","prefixPath","func","item","clear","getCount","Operation_1","Overwrite","OVERWRITE","operationForChild","CacheNode_1","ViewCache_1","View_1","views_","applyOperation","operation","writesCache","optCompleteServerCache","view","events_1","serverCache","serverCacheComplete","eventCache","calcCompleteEventCache","eventCacheComplete","calcCompleteEventChildren","viewCache","ViewCache","View","getInitialEvents","cancelError","removed","cancelEvents","hadCompleteView","hasCompleteView","viewQueryId","getQuery","loadsAllData","getQueryViews","filter","getCompleteServerCache","viewForQuery","getCompleteView","viewExistsForQuery","findValue","eventCache_","serverCache_","updateEventSnap","eventSnap","complete","filtered","updateServerSnap","serverSnap","getEventCache","getCompleteEventSnap","getServerCache","getCompleteServerSnap","collection_","last_","newStats","delta","app_1","VisibilityMonitor_1","OnlineMonitor_1","Connection_1","ServerActions_1","RECONNECT_MIN_DELAY","RECONNECT_MAX_DELAY_DEFAULT","authTokenProvider_","authOverride_","nextPersistentConnectionId_","interruptReasons_","listens_","outstandingPuts_","outstandingPutCount_","onDisconnectRequestQueue_","connected_","reconnectDelay_","maxReconnectDelay_","securityDebugCallback_","lastSessionId","establishConnectionTimer_","visible_","requestCBHash_","requestNumber_","realtime_","authToken_","forceTokenRefresh_","invalidAuthTokenCount_","firstConnection_","lastConnectionAttemptTime_","lastConnectionEstablishedTime_","scheduleConnect_","VisibilityMonitor","onVisible_","OnlineMonitor","onOnline_","sendRequest","onResponse","curReqNum","msg","r","isDefault","listenSpec","hashFn","sendListen_","req","p","payload","warnOnListenWarnings_","removeListen_","warnings","indexSpec","indexPath","tryAuth","reduceReconnectDelayIfAdminCredential_","credential","isAdmin","token_1","authMethod","isValidFormat","requestData","res","onAuthRevoked_","sendUnlisten_","queryObj","sendOnDisconnect_","request","d","response","putInternal","sendPut_","queued","reportStats","onDataMessage_","reqNum","onDataPush_","onListenRevoked_","onSecurityDebugPacket_","onReady_","sessionId","handleTimestamp_","sendConnectStats_","restoreState_","clearTimeout","establishConnection_","visible","online","close","onRealtimeDisconnect_","cancelSentTransactions_","shouldReconnect_","timeSinceLastConnectSucceeded","timeSinceLastConnectAttempt","reconnectDelay","random","onDataMessage_1","onReady_1","connId_1","nextConnectionId_","lastSessionId_1","canceled_1","connection_1","closeFn_1","sendRequestFn","forceRefresh","getToken","accessToken","Connection","CONSTANTS","NODE_ADMIN","serverTimeOffset","q","normalizedPathString","statusCode","explanation","notifyForInvalidToken","queries","shift","clientName","NODE_CLIENT","default","SDK_VERSION","isMobileCordova","isReactNative","currentlyOnline","ServerActions","EventEmitter","allowedEvents_","listeners_","trigger","listeners","validateEventType_","eventData","getInitialEvent","splice","et","TransportManager_1","onMessage_","onKill_","connectionCount","pendingDataMessages","state_","transportManager_","TransportManager","start_","conn","initialTransport","conn_","nextTransportId_","primaryResponsesRequired_","onMessageReceived","connReceiver_","onConnectionLost","disconnReceiver_","tx_","rx_","secondaryConn_","isHealthy_","open","healthyTimeout_ms","healthyTimeout_","bytesReceived","markConnectionHealthy","bytesSent","everConnected","onConnectionLost_","onSecondaryConnectionLost_","onPrimaryMessageReceived_","onSecondaryMessageReceived_","dataMsg","t","sendData_","tryCleanupConnection","connId","onSecondaryControl_","controlData","cmd","upgradeIfSecondaryHealthy_","secondaryResponsesRequired_","parsedData","layer","proceedWithUpgrade_","send","start","onControl_","onPrimaryResponse_","onHandshake_","onConnectionShutdown_","onReset_","sendPingOnPrimaryIfNecessary_","handshake","ts","version","h","onConnectionEstablished_","tryStartUpgrade_","upgradeTransport","startUpgrade_","onMessage","closeConnections_","PacketReceiver_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","BrowserPollConnection","transportSessionId","everConnected_","urlFn","curSegmentNum","myPacketOrderer","PacketReceiver","isClosed_","connectTimeoutTimer_","onClosed_","scriptTagHolder","FirebaseIFrameScriptHolder","args","command","arg1","arg2","incrementIncomingBytes_","password","sendNewPolls","closeAfter","pN","handleResponse","urlParams","uniqueCallbackIdentifier","connectURL","addTag","startLongPoll","addDisconnectPingFrame","forceAllow","forceAllow_","forceDisallow","forceDisallow_","isAvailable","createElement","shutdown_","myDisconnFrame","removeChild","dataStr","base64data","base64Encode","MAX_URL_DATA_SIZE","enqueueSegment","pw","src","style","display","appendChild","commandCB","onMessageCB","outstandingRequests","pendingSegs","currentSerial","myIFrame","createIFrame_","script","iframeContents","doc","write","iframe","contentWindow","contentDocument","alive","innerHTML","myID","myPW","theURL","nodeRestRequest","newRequest_","curDataString","theSeg","seg","addLongPollTag_","segnum","totalsegs","serial","doNewRequest","keepaliveTimeout","readyStateCB","loadCB","doNodeLongPoll","newScript_1","async","onload","onreadystatechange","rstate","parentNode","onerror","process","setWebSocketImpl","impl","WebSocketImpl","MozWebSocket","WebSocket","WebSocketConnection","keepaliveTimer","frames","totalFrames","connectionURL_","device","headers","User-Agent","platform","env","proxy","origin","mySock","onopen","onclose","onmessage","m","handleIncomingFrame","isOldAndroid","navigator","userAgent","oldAndroidRegex","oldAndroidMatch","match","parseFloat","previouslyFailed","isInMemoryStorage","appendFrame_","fullMess","jsonMess","jsonEval","handleNewFrameCount_","frameCount","extractFrameCount_","isNaN","mess","resetKeepAlive","remainingData","sendString_","clearInterval","setInterval","responsesRequiredToBeHealthy","healthyTimeout","IndexedFilter_1","RangedFilter","indexedFilter_","startPost_","getStartPost_","endPost_","getEndPost_","getStartPost","getEndPost","matches","self","startName","endName","registerDatabase","instance","registerService","unused","TEST_ACCESS","DataSnapshot_1","domStorage_","prefix_","prefixedName_","storedVal","getItem","cache_","PUSH_CHARS","lastPushTime","lastRandChars","duplicateTime","timeStampChars","charAt","Event_1","callback_","cancelCallback_","context_","respondsTo","createEvent","change","DataEvent","getEventRunner","ctx","getEventType","cancelCB_1","cb_1","createCancelEvent","CancelEvent","hasAnyCallback","callbacks_","eventToCheck","cancelCB_2","cb_2","otherCount","otherKey","getAnyKey","thisKey","every","cb","getPath","AckUserWrite_1","ImmutableTree_1","ListenComplete_1","Merge_1","Overwrite_1","WriteTree_1","listenProvider_","syncPointTree_","pendingWriteTree_","WriteTree","tagToQueryMap_","queryToTagMap_","newData","addOverwrite","applyOperationToSyncPoints_","addMerge","changeTree","Merge","revert","getWrite","removeWrite","affectedTree_1","AckUserWrite","applyListenComplete","ListenComplete","queryKey","queryKeyForTag_","parseQueryKey_","queryPath","op","applyTaggedOperation_","applyTaggedListenComplete","foundAncestorDefaultView","pathToSyncPoint","sp","syncPoint","childSyncPoint","completeCache","viewAlreadyExists","makeQueryKey_","getNextQueryTag_","childWrites","setupListener_","maybeSyncPoint","removedAndEvents","removingDefault","findIndex","covered","parentSyncPoint","newViews","collectDistinctViewsForSubTree_","newQuery","listener","createListenerForView_","queryForListening_","tagForQuery_","queryToRemove","tagToRemove","removeTags_","writeIdsToExclude","writeTree","maybeChildSyncPoint","childMap","views_1","childViews","removedQuery","removedQueryKey","removedQueryTag","queriesToStop","queries_1","childQueries","queryToStop","splitIndex","nextQueryTag_","applyOperationHelper_","syncPointTree","applyOperationDescendantsHelper_","childOperation","childServerCache","childWritesCache","affectedTree","ACK_USER_WRITE","LISTEN_COMPLETE","MERGE","ViewProcessor_1","EventGenerator_1","query_","initialViewCache","eventRegistrations_","indexFilter","getNodeFilter","processor_","ViewProcessor","initialServerCache","initialEventCache","newServerCache","newEventCache","viewCache_","eventGenerator_","EventGenerator","cache","path_1","registration","maybeEvent","remaining","existing","completeServerCache","oldViewCache","assertIndexed","generateEventsForChanges_","changes","initialChanges","registrations","generateEventsForChanges","ChildChangeAccumulator_1","CompleteChildSource_1","ProcessorResult","filter_","newViewCache","filterServerNode","accumulator","ChildChangeAccumulator","overwrite","applyUserOverwrite_","applyServerOverwrite_","applyUserMerge_","applyServerMerge_","revertUserWrite_","ackUserWrite_","listenComplete_","getChanges","maybeAddValueEvent_","isLeafOrEmpty","oldCompleteSnap","generateEventCacheAfterServerEvent_","changePath","oldEventSnap","shadowingWrite","serverNode","completeChildren","completeEventChildren","completeNode","oldEventNode","updatedPriority","calcEventCacheAfterServerOverwrite","childChangePath","newEventChild","eventChildUpdate","calcCompleteChild","changedSnap","oldServerSnap","serverFilter","newServerNode","NO_COMPLETE_CHILD_SOURCE","WriteTreeCompleteChildSource","getCompleteChild","newEventSnap","cacheHasChild_","curViewCache","writePath","applyMerge_","viewMergeTree","serverChild","childMergeTree","isUnknownDeepMerge","ackPath","changedChildren_1","changedChildren_2","mergePath","serverCachePath","oldServerNode","oldEventCache","serverChildren","changeMap_","oldChange","oldType","getValues","NoCompleteChildSource_","getChildAfterChild","writes_","optCompleteServerCache_","completeServerData","nodes","calcIndexedSlice","eventRegistrations","moves","generateEventsForType_","filteredChanges","compareChanges_","materializedChange","materializeSingleChange_","aWrapped","bWrapped","CompoundWrite_1","visibleWrites_","CompoundWrite","allWrites_","lastWriteId_","WriteTreeRef","addWrite","addWrites","record","writeToRemove","removedWriteWasVisible","removedWriteOverlapsWithOtherWrites","currentWrite","recordContainsPath_","resetTree_","getCompleteWriteData","getCompleteNode","treePath","includeHiddenWrites","childCompoundWrite","hasCompleteWrite","mergeAtPath","layerTree_","layeredCache","shadowingNode","subMerge","completeServerChildren","topLevelSet","merge_1","getCompleteChildren","existingEventSnap","existingServerSnap","childMerge","toIterate","writeRecord","findKey","DefaultFilter_","writes","treeRoot","compoundWrite","deepNode","treePath_","writeTree_","existingServerCache","rootmost","rootMostPath","newWrite","applySubtreeWrite_","priorityWrite_1","rootNode_","newSnapshotNode","app_","removeTokenChangeListener","errorMessage","counters_","amount","deepCopy","FIRST_STATS_MIN_TIME","FIRST_STATS_MAX_TIME","collection","statsToReport_","reportStats_","reportedStats","haveStatsToReport","eventLists_","recursionDepth_","eventDataList","currList","eventPath","EventList","raiseQueuedEventsMatchingPredicate_","sentAll","eventList","raise","events_","eventFn","EventEmitter_1","hidden","visibilityChange","online_","BrowserPollConnection_1","WebSocketConnection_1","initTransports_","isWebSocketsAvailable","isSkipPollConnection","transports_","transports_1","ALL_TRANSPORTS","transport","pendingResponses","currentResponseNum","closeAfterResponse","onClose","responseNum","requestNum","this_1","toProcess","getListenId_","listenId","thisListen","queryStringParamaters","toRestQueryStringParameters","restRequest_","status_1","queryStringParameters","authTokenData","authToken","querystring","xhr","XMLHttpRequest","responseText","LimitedFilter_1","RangedFilter_1","limitSet_","startSet_","startNameSet_","endSet_","endNameSet_","limit_","viewFrom_","indexStartValue_","indexStartName_","indexEndValue_","indexEndName_","isViewFromLeft","WIRE_PROTOCOL_CONSTANTS_","VIEW_FROM_LEFT","getLimit","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","LimitedFilter","REST_CONSTANTS","REST_QUERY_CONSTANTS_","qs","ORDER_BY","START_AT","END_AT","LIMIT_TO_FIRST","LIMIT_TO_LAST","rangedFilter_","reverse_","fullLimitUpdateChild_","inRange","indexCompare_1","foundStartPost","changeAccumulator","indexCmp_1","newChildNamedNode","windowBoundary","oldChildSnap","compareNext","TransactionStatus","Tree_1","MAX_TRANSACTION_RETRIES_","transactionQueueTree_","Tree","watchRef","unwatcher","order","retryCount","abortReason","currentWriteId","currentInputSnapshot","currentOutputSnapshotRaw","currentOutputSnapshotResolved","currentState","getLatestState_","RUN","queueNode","subTree","nodeQueue","setValue","priorityForNode","sendReadyTransactions_","excludeSets","pruneCompletedTransactionsBelowNode_","queue","buildTransactionQueue_","sendTransactionQueue_","setsToIgnore","txn","latestState","snapToSend","latestHash","SENT","dataToSend","pathToSend","COMPLETED","SENT_NEEDS_ABORT","NEEDS_ABORT","rootMostTransactionNode","getAncestorTransactionNode_","rerunTransactionQueue_","txnsToRerun","abortTransaction","currentNode","newDataNode","hasExplicitPriority","oldWriteId","newNodeResolved","lastInput","transactionNode","transactionQueue","aggregateTransactionQueuesForNode_","to","from","forEachAncestor","abortTransactionsOnNode_","forEachDescendant","lastSent","TreeNode","childCount","name_","parent_","pathObj","updateParents_","includeSelf","childrenFirst","forEachImmediateDescendantWithValue","updateChild_","childEmpty","childExists","forceLongPolling","forceWebSockets","setSecurityDebugCallback","interceptServerData","DataConnection","simpleListen","echo","onEcho","RealTimeConnection","hijackHash","newHash","oldPut","opt_onComplete","opt_hash","ConnectionTarget","listens","firebaseRef"],"mappings":";;;;;AAKA,IACQA,sBAAsB,IACvB,CAED,SAAUC,EAAQC,EAASC,GAEjC,YCKAC,QAAAC,eAAAH,EAAA,cAA8CI,OAAA,GAC9C,IAAAC,GAAAJ,EAAA,GACAK,EAAAL,EAAA,GACAM,EAAAN,EAAA,GACAO,EAAAP,EAAA,GACAQ,EAAAR,EAAA,GACAS,EAAAT,EAAA,GACAU,EAAAV,EAAA,IACAW,EAAAX,EAAA,EAKAD,GAAAa,cAAA,WACA,GAAAC,GAAA,CACA,mBACA,MAAAA,SAQAd,EAAAe,KAAA,SAAAC,GACA,GAAAC,GAAAR,EAAAS,kBAAAF,GACAD,EAAA,GAAAP,GAAAW,IACAJ,GAAAK,OAAAH,EACA,IAAAI,GAAAN,EAAAO,QACA,OAAAf,GAAAgB,OAAAC,gBAAAH,GAOA,IAAAI,GAAA,WAEA,OADAC,MACAC,EAAA,EAAoBA,EAAAC,UAAAC,OAAuBF,IAC3CD,EAAAC,GAAAC,UAAAD,EAGA,QADAG,GAAA,GACAC,EAAA,EAAmBA,EAAAL,EAAAG,OAAqBE,IACxCC,MAAAC,QAAAP,EAAAK,KACAL,EAAAK,IACA,gBAAAL,GAAAK,IACA,gBAAAL,GAAAK,GAAAF,OACAC,GAAAL,EAAAS,MAAA,KAAAR,EAAAK,IAEA,gBAAAL,GAAAK,GACAD,GAAApB,EAA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0C,EAAA4B,qBAAA9W,UAAA8a,IAAA0uC,IAMA/zD,EAAAk0D,iBAAA7hC,EAAAO,SAKA5yB,EAAA23B,gBAAA,SAAAjvB,GACA,MAAAA,GAAAivB,mBAMA33B,EAAAm0D,QAAA,SAAAC,GACA,MAAAA,GAAA7qC,KAAA9I,EAAAqf,IAOA9/B,EAAA8f,gBAAA,SAAAA,GACA4Q,EAAAd,YAAAG,cAAAjQ,uBnFk0gBG,KACO,MAAM1c,GACN,KAAUE,OACR","file":"firebase-database.js","sourcesContent":["/*!\n * @license Firebase v4.10.1\n * Build: rev-e70ef37\n * Terms: https://firebase.google.com/terms/\n */\ntry {\n webpackJsonpFirebase([0],[\n/* 0 */,\n/* 1 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\nvar util_3 = __webpack_require__(0);\nvar util_4 = __webpack_require__(0);\nvar util_5 = __webpack_require__(0);\nvar util_6 = __webpack_require__(0);\nvar storage_1 = __webpack_require__(14);\nvar util_7 = __webpack_require__(0);\n/**\n * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).\n * @type {function(): number} Generated ID.\n */\nexports.LUIDGenerator = (function () {\n var id = 1;\n return function () {\n return id++;\n };\n})();\n/**\n * Sha1 hash of the input string\n * @param {!string} str The string to hash\n * @return {!string} The resulting hash\n */\nexports.sha1 = function (str) {\n var utf8Bytes = util_5.stringToByteArray(str);\n var sha1 = new util_4.Sha1();\n sha1.update(utf8Bytes);\n var sha1Bytes = sha1.digest();\n return util_3.base64.encodeByteArray(sha1Bytes);\n};\n/**\n * @param {...*} var_args\n * @return {string}\n * @private\n */\nvar buildLogMessage_ = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var message = '';\n for (var i = 0; i < var_args.length; i++) {\n if (Array.isArray(var_args[i]) ||\n (var_args[i] &&\n typeof var_args[i] === 'object' &&\n typeof var_args[i].length === 'number')) {\n message += buildLogMessage_.apply(null, var_args[i]);\n }\n else if (typeof var_args[i] === 'object') {\n message += util_6.stringify(var_args[i]);\n }\n else {\n message += var_args[i];\n }\n message += ' ';\n }\n return message;\n};\n/**\n * Use this for all debug messages in Firebase.\n * @type {?function(string)}\n */\nexports.logger = null;\n/**\n * Flag to check for log availability on first log message\n * @type {boolean}\n * @private\n */\nvar firstLog_ = true;\n/**\n * The implementation of Firebase.enableLogging (defined here to break dependencies)\n * @param {boolean|?function(string)} logger_ A flag to turn on logging, or a custom logger\n * @param {boolean=} persistent Whether or not to persist logging settings across refreshes\n */\nexports.enableLogging = function (logger_, persistent) {\n util_1.assert(!persistent || (logger_ === true || logger_ === false), \"Can't turn on custom loggers persistently.\");\n if (logger_ === true) {\n if (typeof console !== 'undefined') {\n if (typeof console.log === 'function') {\n exports.logger = console.log.bind(console);\n }\n else if (typeof console.log === 'object') {\n // IE does this.\n exports.logger = function (message) {\n console.log(message);\n };\n }\n }\n if (persistent)\n storage_1.SessionStorage.set('logging_enabled', true);\n }\n else if (typeof logger_ === 'function') {\n exports.logger = logger_;\n }\n else {\n exports.logger = null;\n storage_1.SessionStorage.remove('logging_enabled');\n }\n};\n/**\n *\n * @param {...(string|Arguments)} var_args\n */\nexports.log = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n if (firstLog_ === true) {\n firstLog_ = false;\n if (exports.logger === null && storage_1.SessionStorage.get('logging_enabled') === true)\n exports.enableLogging(true);\n }\n if (exports.logger) {\n var message = buildLogMessage_.apply(null, var_args);\n exports.logger(message);\n }\n};\n/**\n * @param {!string} prefix\n * @return {function(...[*])}\n */\nexports.logWrapper = function (prefix) {\n return function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n exports.log.apply(void 0, [prefix].concat(var_args));\n };\n};\n/**\n * @param {...string} var_args\n */\nexports.error = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n if (typeof console !== 'undefined') {\n var message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_.apply(void 0, var_args);\n if (typeof console.error !== 'undefined') {\n console.error(message);\n }\n else {\n console.log(message);\n }\n }\n};\n/**\n * @param {...string} var_args\n */\nexports.fatal = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var message = buildLogMessage_.apply(void 0, var_args);\n throw new Error('FIREBASE FATAL ERROR: ' + message);\n};\n/**\n * @param {...*} var_args\n */\nexports.warn = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n if (typeof console !== 'undefined') {\n var message = 'FIREBASE WARNING: ' + buildLogMessage_.apply(void 0, var_args);\n if (typeof console.warn !== 'undefined') {\n console.warn(message);\n }\n else {\n console.log(message);\n }\n }\n};\n/**\n * Logs a warning if the containing page uses https. Called when a call to new Firebase\n * does not use https.\n */\nexports.warnIfPageIsSecure = function () {\n // Be very careful accessing browser globals. Who knows what may or may not exist.\n if (typeof window !== 'undefined' &&\n window.location &&\n window.location.protocol &&\n window.location.protocol.indexOf('https:') !== -1) {\n exports.warn('Insecure Firebase access from a secure page. ' +\n 'Please use https in calls to new Firebase().');\n }\n};\n/**\n * @param {!String} methodName\n */\nexports.warnAboutUnsupportedMethod = function (methodName) {\n exports.warn(methodName +\n ' is unsupported and will likely change soon. ' +\n 'Please do not use.');\n};\n/**\n * Returns true if data is NaN, or +/- Infinity.\n * @param {*} data\n * @return {boolean}\n */\nexports.isInvalidJSONNumber = function (data) {\n return (typeof data === 'number' &&\n (data != data || // NaN\n data == Number.POSITIVE_INFINITY ||\n data == Number.NEGATIVE_INFINITY));\n};\n/**\n * @param {function()} fn\n */\nexports.executeWhenDOMReady = function (fn) {\n if (util_7.isNodeSdk() || document.readyState === 'complete') {\n fn();\n }\n else {\n // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which\n // fire before onload), but fall back to onload.\n var called_1 = false;\n var wrappedFn_1 = function () {\n if (!document.body) {\n setTimeout(wrappedFn_1, Math.floor(10));\n return;\n }\n if (!called_1) {\n called_1 = true;\n fn();\n }\n };\n if (document.addEventListener) {\n document.addEventListener('DOMContentLoaded', wrappedFn_1, false);\n // fallback to onload.\n window.addEventListener('load', wrappedFn_1, false);\n }\n else if (document.attachEvent) {\n // IE.\n document.attachEvent('onreadystatechange', function () {\n if (document.readyState === 'complete')\n wrappedFn_1();\n });\n // fallback to onload.\n window.attachEvent('onload', wrappedFn_1);\n // jQuery has an extra hack for IE that we could employ (based on\n // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.\n // I'm hoping we don't need it.\n }\n }\n};\n/**\n * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names\n * @type {!string}\n */\nexports.MIN_NAME = '[MIN_NAME]';\n/**\n * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names\n * @type {!string}\n */\nexports.MAX_NAME = '[MAX_NAME]';\n/**\n * Compares valid Firebase key names, plus min and max name\n * @param {!string} a\n * @param {!string} b\n * @return {!number}\n */\nexports.nameCompare = function (a, b) {\n if (a === b) {\n return 0;\n }\n else if (a === exports.MIN_NAME || b === exports.MAX_NAME) {\n return -1;\n }\n else if (b === exports.MIN_NAME || a === exports.MAX_NAME) {\n return 1;\n }\n else {\n var aAsInt = exports.tryParseInt(a), bAsInt = exports.tryParseInt(b);\n if (aAsInt !== null) {\n if (bAsInt !== null) {\n return aAsInt - bAsInt == 0 ? a.length - b.length : aAsInt - bAsInt;\n }\n else {\n return -1;\n }\n }\n else if (bAsInt !== null) {\n return 1;\n }\n else {\n return a < b ? -1 : 1;\n }\n }\n};\n/**\n * @param {!string} a\n * @param {!string} b\n * @return {!number} comparison result.\n */\nexports.stringCompare = function (a, b) {\n if (a === b) {\n return 0;\n }\n else if (a < b) {\n return -1;\n }\n else {\n return 1;\n }\n};\n/**\n * @param {string} key\n * @param {Object} obj\n * @return {*}\n */\nexports.requireKey = function (key, obj) {\n if (obj && key in obj) {\n return obj[key];\n }\n else {\n throw new Error('Missing required key (' + key + ') in object: ' + util_6.stringify(obj));\n }\n};\n/**\n * @param {*} obj\n * @return {string}\n */\nexports.ObjectToUniqueKey = function (obj) {\n if (typeof obj !== 'object' || obj === null)\n return util_6.stringify(obj);\n var keys = [];\n for (var k in obj) {\n keys.push(k);\n }\n // Export as json, but with the keys sorted.\n keys.sort();\n var key = '{';\n for (var i = 0; i < keys.length; i++) {\n if (i !== 0)\n key += ',';\n key += util_6.stringify(keys[i]);\n key += ':';\n key += exports.ObjectToUniqueKey(obj[keys[i]]);\n }\n key += '}';\n return key;\n};\n/**\n * Splits a string into a number of smaller segments of maximum size\n * @param {!string} str The string\n * @param {!number} segsize The maximum number of chars in the string.\n * @return {Array.} The string, split into appropriately-sized chunks\n */\nexports.splitStringBySize = function (str, segsize) {\n var len = str.length;\n if (len <= segsize) {\n return [str];\n }\n var dataSegs = [];\n for (var c = 0; c < len; c += segsize) {\n if (c + segsize > len) {\n dataSegs.push(str.substring(c, len));\n }\n else {\n dataSegs.push(str.substring(c, c + segsize));\n }\n }\n return dataSegs;\n};\n/**\n * Apply a function to each (key, value) pair in an object or\n * apply a function to each (index, value) pair in an array\n * @param {!(Object|Array)} obj The object or array to iterate over\n * @param {function(?, ?)} fn The function to apply\n */\nexports.each = function (obj, fn) {\n if (Array.isArray(obj)) {\n for (var i = 0; i < obj.length; ++i) {\n fn(i, obj[i]);\n }\n }\n else {\n /**\n * in the conversion of code we removed the goog.object.forEach\n * function which did a value,key callback. We standardized on\n * a single impl that does a key, value callback. So we invert\n * to not have to touch the `each` code points\n */\n util_2.forEach(obj, function (key, val) { return fn(val, key); });\n }\n};\n/**\n * Like goog.bind, but doesn't bother to create a closure if opt_context is null/undefined.\n * @param {function(*)} callback Callback function.\n * @param {?Object=} context Optional context to bind to.\n * @return {function(*)}\n */\nexports.bindCallback = function (callback, context) {\n return context ? callback.bind(context) : callback;\n};\n/**\n * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)\n * I made one modification at the end and removed the NaN / Infinity\n * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.\n * @param {!number} v A double\n * @return {string}\n */\nexports.doubleToIEEE754String = function (v) {\n util_1.assert(!exports.isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL\n var ebits = 11, fbits = 52;\n var bias = (1 << (ebits - 1)) - 1, s, e, f, ln, i, bits, str;\n // Compute sign, exponent, fraction\n // Skip NaN / Infinity handling --MJL.\n if (v === 0) {\n e = 0;\n f = 0;\n s = 1 / v === -Infinity ? 1 : 0;\n }\n else {\n s = v < 0;\n v = Math.abs(v);\n if (v >= Math.pow(2, 1 - bias)) {\n // Normalized\n ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);\n e = ln + bias;\n f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));\n }\n else {\n // Denormalized\n e = 0;\n f = Math.round(v / Math.pow(2, 1 - bias - fbits));\n }\n }\n // Pack sign, exponent, fraction\n bits = [];\n for (i = fbits; i; i -= 1) {\n bits.push(f % 2 ? 1 : 0);\n f = Math.floor(f / 2);\n }\n for (i = ebits; i; i -= 1) {\n bits.push(e % 2 ? 1 : 0);\n e = Math.floor(e / 2);\n }\n bits.push(s ? 1 : 0);\n bits.reverse();\n str = bits.join('');\n // Return the data as a hex string. --MJL\n var hexByteString = '';\n for (i = 0; i < 64; i += 8) {\n var hexByte = parseInt(str.substr(i, 8), 2).toString(16);\n if (hexByte.length === 1)\n hexByte = '0' + hexByte;\n hexByteString = hexByteString + hexByte;\n }\n return hexByteString.toLowerCase();\n};\n/**\n * Used to detect if we're in a Chrome content script (which executes in an\n * isolated environment where long-polling doesn't work).\n * @return {boolean}\n */\nexports.isChromeExtensionContentScript = function () {\n return !!(typeof window === 'object' &&\n window['chrome'] &&\n window['chrome']['extension'] &&\n !/^chrome/.test(window.location.href));\n};\n/**\n * Used to detect if we're in a Windows 8 Store app.\n * @return {boolean}\n */\nexports.isWindowsStoreApp = function () {\n // Check for the presence of a couple WinRT globals\n return typeof Windows === 'object' && typeof Windows.UI === 'object';\n};\n/**\n * Converts a server error code to a Javascript Error\n * @param {!string} code\n * @param {!Query} query\n * @return {Error}\n */\nexports.errorForServerCode = function (code, query) {\n var reason = 'Unknown Error';\n if (code === 'too_big') {\n reason =\n 'The data requested exceeds the maximum size ' +\n 'that can be accessed with a single request.';\n }\n else if (code == 'permission_denied') {\n reason = \"Client doesn't have permission to access the desired data.\";\n }\n else if (code == 'unavailable') {\n reason = 'The service is unavailable';\n }\n var error = new Error(code + ' at ' + query.path.toString() + ': ' + reason);\n error.code = code.toUpperCase();\n return error;\n};\n/**\n * Used to test for integer-looking strings\n * @type {RegExp}\n * @private\n */\nexports.INTEGER_REGEXP_ = new RegExp('^-?\\\\d{1,10}$');\n/**\n * If the string contains a 32-bit integer, return it. Else return null.\n * @param {!string} str\n * @return {?number}\n */\nexports.tryParseInt = function (str) {\n if (exports.INTEGER_REGEXP_.test(str)) {\n var intVal = Number(str);\n if (intVal >= -2147483648 && intVal <= 2147483647) {\n return intVal;\n }\n }\n return null;\n};\n/**\n * Helper to run some code but catch any exceptions and re-throw them later.\n * Useful for preventing user callbacks from breaking internal code.\n *\n * Re-throwing the exception from a setTimeout is a little evil, but it's very\n * convenient (we don't have to try to figure out when is a safe point to\n * re-throw it), and the behavior seems reasonable:\n *\n * * If you aren't pausing on exceptions, you get an error in the console with\n * the correct stack trace.\n * * If you're pausing on all exceptions, the debugger will pause on your\n * exception and then again when we rethrow it.\n * * If you're only pausing on uncaught exceptions, the debugger will only pause\n * on us re-throwing it.\n *\n * @param {!function()} fn The code to guard.\n */\nexports.exceptionGuard = function (fn) {\n try {\n fn();\n }\n catch (e) {\n // Re-throw exception when it's safe.\n setTimeout(function () {\n // It used to be that \"throw e\" would result in a good console error with\n // relevant context, but as of Chrome 39, you just get the firebase.js\n // file/line number where we re-throw it, which is useless. So we log\n // e.stack explicitly.\n var stack = e.stack || '';\n exports.warn('Exception was thrown by user callback.', stack);\n throw e;\n }, Math.floor(0));\n }\n};\n/**\n * Helper function to safely call opt_callback with the specified arguments. It:\n * 1. Turns into a no-op if opt_callback is null or undefined.\n * 2. Wraps the call inside exceptionGuard to prevent exceptions from breaking our state.\n *\n * @param {?Function=} callback Optional onComplete callback.\n * @param {...*} var_args Arbitrary args to be passed to opt_onComplete\n */\nexports.callUserCallback = function (callback) {\n var var_args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n var_args[_i - 1] = arguments[_i];\n }\n if (typeof callback === 'function') {\n exports.exceptionGuard(function () {\n callback.apply(void 0, var_args);\n });\n }\n};\n/**\n * @return {boolean} true if we think we're currently being crawled.\n */\nexports.beingCrawled = function () {\n var userAgent = (typeof window === 'object' &&\n window['navigator'] &&\n window['navigator']['userAgent']) ||\n '';\n // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we\n // believe to support JavaScript/AJAX rendering.\n // NOTE: Google Webmaster Tools doesn't really belong, but their \"This is how a visitor to your website\n // would have seen the page\" is flaky if we don't treat it as a crawler.\n return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);\n};\n/**\n * Export a property of an object using a getter function.\n *\n * @param {!Object} object\n * @param {string} name\n * @param {!function(): *} fnGet\n */\nexports.exportPropGetter = function (object, name, fnGet) {\n Object.defineProperty(object, name, { get: fnGet });\n};\n/**\n * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.\n *\n * It is removed with clearTimeout() as normal.\n *\n * @param {Function} fn Function to run.\n * @param {number} time Milliseconds to wait before running.\n * @return {number|Object} The setTimeout() return value.\n */\nexports.setTimeoutNonBlocking = function (fn, time) {\n var timeout = setTimeout(fn, time);\n if (typeof timeout === 'object' && timeout['unref']) {\n timeout['unref']();\n }\n return timeout;\n};\n\n//# sourceMappingURL=util.js.map\n\n\n/***/ }),\n/* 2 */,\n/* 3 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(1);\nvar util_2 = __webpack_require__(0);\n/**\n * An immutable object representing a parsed path. It's immutable so that you\n * can pass them around to other functions without worrying about them changing\n * it.\n */\nvar Path = /** @class */ (function () {\n /**\n * @param {string|Array.} pathOrString Path string to parse,\n * or another path, or the raw tokens array\n * @param {number=} pieceNum\n */\n function Path(pathOrString, pieceNum) {\n if (pieceNum === void 0) {\n this.pieces_ = pathOrString.split('/');\n // Remove empty pieces.\n var copyTo = 0;\n for (var i = 0; i < this.pieces_.length; i++) {\n if (this.pieces_[i].length > 0) {\n this.pieces_[copyTo] = this.pieces_[i];\n copyTo++;\n }\n }\n this.pieces_.length = copyTo;\n this.pieceNum_ = 0;\n }\n else {\n this.pieces_ = pathOrString;\n this.pieceNum_ = pieceNum;\n }\n }\n Object.defineProperty(Path, \"Empty\", {\n /**\n * Singleton to represent an empty path\n *\n * @const\n */\n get: function () {\n return new Path('');\n },\n enumerable: true,\n configurable: true\n });\n Path.prototype.getFront = function () {\n if (this.pieceNum_ >= this.pieces_.length)\n return null;\n return this.pieces_[this.pieceNum_];\n };\n /**\n * @return {number} The number of segments in this path\n */\n Path.prototype.getLength = function () {\n return this.pieces_.length - this.pieceNum_;\n };\n /**\n * @return {!Path}\n */\n Path.prototype.popFront = function () {\n var pieceNum = this.pieceNum_;\n if (pieceNum < this.pieces_.length) {\n pieceNum++;\n }\n return new Path(this.pieces_, pieceNum);\n };\n /**\n * @return {?string}\n */\n Path.prototype.getBack = function () {\n if (this.pieceNum_ < this.pieces_.length)\n return this.pieces_[this.pieces_.length - 1];\n return null;\n };\n Path.prototype.toString = function () {\n var pathString = '';\n for (var i = this.pieceNum_; i < this.pieces_.length; i++) {\n if (this.pieces_[i] !== '')\n pathString += '/' + this.pieces_[i];\n }\n return pathString || '/';\n };\n Path.prototype.toUrlEncodedString = function () {\n var pathString = '';\n for (var i = this.pieceNum_; i < this.pieces_.length; i++) {\n if (this.pieces_[i] !== '')\n pathString += '/' + encodeURIComponent(String(this.pieces_[i]));\n }\n return pathString || '/';\n };\n /**\n * Shallow copy of the parts of the path.\n *\n * @param {number=} begin\n * @return {!Array}\n */\n Path.prototype.slice = function (begin) {\n if (begin === void 0) { begin = 0; }\n return this.pieces_.slice(this.pieceNum_ + begin);\n };\n /**\n * @return {?Path}\n */\n Path.prototype.parent = function () {\n if (this.pieceNum_ >= this.pieces_.length)\n return null;\n var pieces = [];\n for (var i = this.pieceNum_; i < this.pieces_.length - 1; i++)\n pieces.push(this.pieces_[i]);\n return new Path(pieces, 0);\n };\n /**\n * @param {string|!Path} childPathObj\n * @return {!Path}\n */\n Path.prototype.child = function (childPathObj) {\n var pieces = [];\n for (var i = this.pieceNum_; i < this.pieces_.length; i++)\n pieces.push(this.pieces_[i]);\n if (childPathObj instanceof Path) {\n for (var i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {\n pieces.push(childPathObj.pieces_[i]);\n }\n }\n else {\n var childPieces = childPathObj.split('/');\n for (var i = 0; i < childPieces.length; i++) {\n if (childPieces[i].length > 0)\n pieces.push(childPieces[i]);\n }\n }\n return new Path(pieces, 0);\n };\n /**\n * @return {boolean} True if there are no segments in this path\n */\n Path.prototype.isEmpty = function () {\n return this.pieceNum_ >= this.pieces_.length;\n };\n /**\n * @param {!Path} outerPath\n * @param {!Path} innerPath\n * @return {!Path} The path from outerPath to innerPath\n */\n Path.relativePath = function (outerPath, innerPath) {\n var outer = outerPath.getFront(), inner = innerPath.getFront();\n if (outer === null) {\n return innerPath;\n }\n else if (outer === inner) {\n return Path.relativePath(outerPath.popFront(), innerPath.popFront());\n }\n else {\n throw new Error('INTERNAL ERROR: innerPath (' +\n innerPath +\n ') is not within ' +\n 'outerPath (' +\n outerPath +\n ')');\n }\n };\n /**\n * @param {!Path} left\n * @param {!Path} right\n * @return {number} -1, 0, 1 if left is less, equal, or greater than the right.\n */\n Path.comparePaths = function (left, right) {\n var leftKeys = left.slice();\n var rightKeys = right.slice();\n for (var i = 0; i < leftKeys.length && i < rightKeys.length; i++) {\n var cmp = util_1.nameCompare(leftKeys[i], rightKeys[i]);\n if (cmp !== 0)\n return cmp;\n }\n if (leftKeys.length === rightKeys.length)\n return 0;\n return leftKeys.length < rightKeys.length ? -1 : 1;\n };\n /**\n *\n * @param {Path} other\n * @return {boolean} true if paths are the same.\n */\n Path.prototype.equals = function (other) {\n if (this.getLength() !== other.getLength()) {\n return false;\n }\n for (var i = this.pieceNum_, j = other.pieceNum_; i <= this.pieces_.length; i++, j++) {\n if (this.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n }\n return true;\n };\n /**\n *\n * @param {!Path} other\n * @return {boolean} True if this path is a parent (or the same as) other\n */\n Path.prototype.contains = function (other) {\n var i = this.pieceNum_;\n var j = other.pieceNum_;\n if (this.getLength() > other.getLength()) {\n return false;\n }\n while (i < this.pieces_.length) {\n if (this.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n ++i;\n ++j;\n }\n return true;\n };\n return Path;\n}()); // end Path\nexports.Path = Path;\n/**\n * Dynamic (mutable) path used to count path lengths.\n *\n * This class is used to efficiently check paths for valid\n * length (in UTF8 bytes) and depth (used in path validation).\n *\n * Throws Error exception if path is ever invalid.\n *\n * The definition of a path always begins with '/'.\n */\nvar ValidationPath = /** @class */ (function () {\n /**\n * @param {!Path} path Initial Path.\n * @param {string} errorPrefix_ Prefix for any error messages.\n */\n function ValidationPath(path, errorPrefix_) {\n this.errorPrefix_ = errorPrefix_;\n /** @type {!Array} */\n this.parts_ = path.slice();\n /** @type {number} Initialize to number of '/' chars needed in path. */\n this.byteLength_ = Math.max(1, this.parts_.length);\n for (var i = 0; i < this.parts_.length; i++) {\n this.byteLength_ += util_2.stringLength(this.parts_[i]);\n }\n this.checkValid_();\n }\n Object.defineProperty(ValidationPath, \"MAX_PATH_DEPTH\", {\n /** @const {number} Maximum key depth. */\n get: function () {\n return 32;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ValidationPath, \"MAX_PATH_LENGTH_BYTES\", {\n /** @const {number} Maximum number of (UTF8) bytes in a Firebase path. */\n get: function () {\n return 768;\n },\n enumerable: true,\n configurable: true\n });\n /** @param {string} child */\n ValidationPath.prototype.push = function (child) {\n // Count the needed '/'\n if (this.parts_.length > 0) {\n this.byteLength_ += 1;\n }\n this.parts_.push(child);\n this.byteLength_ += util_2.stringLength(child);\n this.checkValid_();\n };\n ValidationPath.prototype.pop = function () {\n var last = this.parts_.pop();\n this.byteLength_ -= util_2.stringLength(last);\n // Un-count the previous '/'\n if (this.parts_.length > 0) {\n this.byteLength_ -= 1;\n }\n };\n ValidationPath.prototype.checkValid_ = function () {\n if (this.byteLength_ > ValidationPath.MAX_PATH_LENGTH_BYTES) {\n throw new Error(this.errorPrefix_ +\n 'has a key path longer than ' +\n ValidationPath.MAX_PATH_LENGTH_BYTES +\n ' bytes (' +\n this.byteLength_ +\n ').');\n }\n if (this.parts_.length > ValidationPath.MAX_PATH_DEPTH) {\n throw new Error(this.errorPrefix_ +\n 'path specified exceeds the maximum depth that can be written (' +\n ValidationPath.MAX_PATH_DEPTH +\n ') or object contains a cycle ' +\n this.toErrorString());\n }\n };\n /**\n * String for use in error messages - uses '.' notation for path.\n *\n * @return {string}\n */\n ValidationPath.prototype.toErrorString = function () {\n if (this.parts_.length == 0) {\n return '';\n }\n return \"in property '\" + this.parts_.join('.') + \"'\";\n };\n return ValidationPath;\n}());\nexports.ValidationPath = ValidationPath;\n\n//# sourceMappingURL=Path.js.map\n\n\n/***/ }),\n/* 4 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = __webpack_require__(2);\nvar Index_1 = __webpack_require__(16);\nvar util_1 = __webpack_require__(1);\nvar Node_1 = __webpack_require__(6);\nvar LeafNode_1 = __webpack_require__(17);\nvar nodeFromJSON;\nvar MAX_NODE;\nfunction setNodeFromJSON(val) {\n nodeFromJSON = val;\n}\nexports.setNodeFromJSON = setNodeFromJSON;\nfunction setMaxNode(val) {\n MAX_NODE = val;\n}\nexports.setMaxNode = setMaxNode;\n/**\n * @constructor\n * @extends {Index}\n * @private\n */\nvar PriorityIndex = /** @class */ (function (_super) {\n tslib_1.__extends(PriorityIndex, _super);\n function PriorityIndex() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.compare = function (a, b) {\n var aPriority = a.node.getPriority();\n var bPriority = b.node.getPriority();\n var indexCmp = aPriority.compareTo(bPriority);\n if (indexCmp === 0) {\n return util_1.nameCompare(a.name, b.name);\n }\n else {\n return indexCmp;\n }\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.isDefinedOn = function (node) {\n return !node.getPriority().isEmpty();\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.indexedValueChanged = function (oldNode, newNode) {\n return !oldNode.getPriority().equals(newNode.getPriority());\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.maxPost = function () {\n return new Node_1.NamedNode(util_1.MAX_NAME, new LeafNode_1.LeafNode('[PRIORITY-POST]', MAX_NODE));\n };\n /**\n * @param {*} indexValue\n * @param {string} name\n * @return {!NamedNode}\n */\n PriorityIndex.prototype.makePost = function (indexValue, name) {\n var priorityNode = nodeFromJSON(indexValue);\n return new Node_1.NamedNode(name, new LeafNode_1.LeafNode('[PRIORITY-POST]', priorityNode));\n };\n /**\n * @return {!string} String representation for inclusion in a query spec\n */\n PriorityIndex.prototype.toString = function () {\n return '.priority';\n };\n return PriorityIndex;\n}(Index_1.Index));\nexports.PriorityIndex = PriorityIndex;\nexports.PRIORITY_INDEX = new PriorityIndex();\n\n//# sourceMappingURL=PriorityIndex.js.map\n\n\n/***/ }),\n/* 5 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = __webpack_require__(2);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar SortedMap_1 = __webpack_require__(18);\nvar Node_1 = __webpack_require__(6);\nvar snap_1 = __webpack_require__(38);\nvar PriorityIndex_1 = __webpack_require__(4);\nvar KeyIndex_1 = __webpack_require__(12);\nvar IndexMap_1 = __webpack_require__(40);\nvar LeafNode_1 = __webpack_require__(17);\nvar comparators_1 = __webpack_require__(42);\n// TODO: For memory savings, don't store priorityNode_ if it's empty.\nvar EMPTY_NODE;\n/**\n * ChildrenNode is a class for storing internal nodes in a DataSnapshot\n * (i.e. nodes with children). It implements Node and stores the\n * list of children in the children property, sorted by child name.\n *\n * @constructor\n * @implements {Node}\n */\nvar ChildrenNode = /** @class */ (function () {\n /**\n *\n * @param {!SortedMap.} children_ List of children\n * of this node..\n * @param {?Node} priorityNode_ The priority of this node (as a snapshot node).\n * @param {!IndexMap} indexMap_\n */\n function ChildrenNode(children_, priorityNode_, indexMap_) {\n this.children_ = children_;\n this.priorityNode_ = priorityNode_;\n this.indexMap_ = indexMap_;\n this.lazyHash_ = null;\n /**\n * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use\n * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own\n * class instead of an empty ChildrenNode.\n */\n if (this.priorityNode_) {\n snap_1.validatePriorityNode(this.priorityNode_);\n }\n if (this.children_.isEmpty()) {\n util_1.assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');\n }\n }\n Object.defineProperty(ChildrenNode, \"EMPTY_NODE\", {\n get: function () {\n return (EMPTY_NODE ||\n (EMPTY_NODE = new ChildrenNode(new SortedMap_1.SortedMap(comparators_1.NAME_COMPARATOR), null, IndexMap_1.IndexMap.Default)));\n },\n enumerable: true,\n configurable: true\n });\n /** @inheritDoc */\n ChildrenNode.prototype.isLeafNode = function () {\n return false;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getPriority = function () {\n return this.priorityNode_ || EMPTY_NODE;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.updatePriority = function (newPriorityNode) {\n if (this.children_.isEmpty()) {\n // Don't allow priorities on empty nodes\n return this;\n }\n else {\n return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getImmediateChild = function (childName) {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.getPriority();\n }\n else {\n var child = this.children_.get(childName);\n return child === null ? EMPTY_NODE : child;\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getChild = function (path) {\n var front = path.getFront();\n if (front === null)\n return this;\n return this.getImmediateChild(front).getChild(path.popFront());\n };\n /** @inheritDoc */\n ChildrenNode.prototype.hasChild = function (childName) {\n return this.children_.get(childName) !== null;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.updateImmediateChild = function (childName, newChildNode) {\n util_1.assert(newChildNode, 'We should always be passing snapshot nodes');\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n }\n else {\n var namedNode = new Node_1.NamedNode(childName, newChildNode);\n var newChildren = void 0, newIndexMap = void 0, newPriority = void 0;\n if (newChildNode.isEmpty()) {\n newChildren = this.children_.remove(childName);\n newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);\n }\n else {\n newChildren = this.children_.insert(childName, newChildNode);\n newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);\n }\n newPriority = newChildren.isEmpty() ? EMPTY_NODE : this.priorityNode_;\n return new ChildrenNode(newChildren, newPriority, newIndexMap);\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.updateChild = function (path, newChildNode) {\n var front = path.getFront();\n if (front === null) {\n return newChildNode;\n }\n else {\n util_1.assert(path.getFront() !== '.priority' || path.getLength() === 1, '.priority must be the last token in a path');\n var newImmediateChild = this.getImmediateChild(front).updateChild(path.popFront(), newChildNode);\n return this.updateImmediateChild(front, newImmediateChild);\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.isEmpty = function () {\n return this.children_.isEmpty();\n };\n /** @inheritDoc */\n ChildrenNode.prototype.numChildren = function () {\n return this.children_.count();\n };\n /** @inheritDoc */\n ChildrenNode.prototype.val = function (exportFormat) {\n if (this.isEmpty())\n return null;\n var obj = {};\n var numKeys = 0, maxKey = 0, allIntegerKeys = true;\n this.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n obj[key] = childNode.val(exportFormat);\n numKeys++;\n if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {\n maxKey = Math.max(maxKey, Number(key));\n }\n else {\n allIntegerKeys = false;\n }\n });\n if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {\n // convert to array.\n var array = [];\n for (var key in obj)\n array[key] = obj[key];\n return array;\n }\n else {\n if (exportFormat && !this.getPriority().isEmpty()) {\n obj['.priority'] = this.getPriority().val();\n }\n return obj;\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.hash = function () {\n if (this.lazyHash_ === null) {\n var toHash_1 = '';\n if (!this.getPriority().isEmpty())\n toHash_1 +=\n 'priority:' +\n snap_1.priorityHashText(this.getPriority().val()) +\n ':';\n this.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n var childHash = childNode.hash();\n if (childHash !== '')\n toHash_1 += ':' + key + ':' + childHash;\n });\n this.lazyHash_ = toHash_1 === '' ? '' : util_2.sha1(toHash_1);\n }\n return this.lazyHash_;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getPredecessorChildName = function (childName, childNode, index) {\n var idx = this.resolveIndex_(index);\n if (idx) {\n var predecessor = idx.getPredecessorKey(new Node_1.NamedNode(childName, childNode));\n return predecessor ? predecessor.name : null;\n }\n else {\n return this.children_.getPredecessorKey(childName);\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {?string}\n */\n ChildrenNode.prototype.getFirstChildName = function (indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n var minKey = idx.minKey();\n return minKey && minKey.name;\n }\n else {\n return this.children_.minKey();\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {?NamedNode}\n */\n ChildrenNode.prototype.getFirstChild = function (indexDefinition) {\n var minKey = this.getFirstChildName(indexDefinition);\n if (minKey) {\n return new Node_1.NamedNode(minKey, this.children_.get(minKey));\n }\n else {\n return null;\n }\n };\n /**\n * Given an index, return the key name of the largest value we have, according to that index\n * @param {!Index} indexDefinition\n * @return {?string}\n */\n ChildrenNode.prototype.getLastChildName = function (indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n var maxKey = idx.maxKey();\n return maxKey && maxKey.name;\n }\n else {\n return this.children_.maxKey();\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {?NamedNode}\n */\n ChildrenNode.prototype.getLastChild = function (indexDefinition) {\n var maxKey = this.getLastChildName(indexDefinition);\n if (maxKey) {\n return new Node_1.NamedNode(maxKey, this.children_.get(maxKey));\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.forEachChild = function (index, action) {\n var idx = this.resolveIndex_(index);\n if (idx) {\n return idx.inorderTraversal(function (wrappedNode) {\n return action(wrappedNode.name, wrappedNode.node);\n });\n }\n else {\n return this.children_.inorderTraversal(action);\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {SortedMapIterator}\n */\n ChildrenNode.prototype.getIterator = function (indexDefinition) {\n return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);\n };\n /**\n *\n * @param {!NamedNode} startPost\n * @param {!Index} indexDefinition\n * @return {!SortedMapIterator}\n */\n ChildrenNode.prototype.getIteratorFrom = function (startPost, indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getIteratorFrom(startPost, function (key) { return key; });\n }\n else {\n var iterator = this.children_.getIteratorFrom(startPost.name, Node_1.NamedNode.Wrap);\n var next = iterator.peek();\n while (next != null && indexDefinition.compare(next, startPost) < 0) {\n iterator.getNext();\n next = iterator.peek();\n }\n return iterator;\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {!SortedMapIterator}\n */\n ChildrenNode.prototype.getReverseIterator = function (indexDefinition) {\n return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);\n };\n /**\n * @param {!NamedNode} endPost\n * @param {!Index} indexDefinition\n * @return {!SortedMapIterator}\n */\n ChildrenNode.prototype.getReverseIteratorFrom = function (endPost, indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getReverseIteratorFrom(endPost, function (key) {\n return key;\n });\n }\n else {\n var iterator = this.children_.getReverseIteratorFrom(endPost.name, Node_1.NamedNode.Wrap);\n var next = iterator.peek();\n while (next != null && indexDefinition.compare(next, endPost) > 0) {\n iterator.getNext();\n next = iterator.peek();\n }\n return iterator;\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.compareTo = function (other) {\n if (this.isEmpty()) {\n if (other.isEmpty()) {\n return 0;\n }\n else {\n return -1;\n }\n }\n else if (other.isLeafNode() || other.isEmpty()) {\n return 1;\n }\n else if (other === exports.MAX_NODE) {\n return -1;\n }\n else {\n // Must be another node with children.\n return 0;\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.withIndex = function (indexDefinition) {\n if (indexDefinition === KeyIndex_1.KEY_INDEX ||\n this.indexMap_.hasIndex(indexDefinition)) {\n return this;\n }\n else {\n var newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);\n return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.isIndexed = function (index) {\n return index === KeyIndex_1.KEY_INDEX || this.indexMap_.hasIndex(index);\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.equals = function (other) {\n if (other === this) {\n return true;\n }\n else if (other.isLeafNode()) {\n return false;\n }\n else {\n var otherChildrenNode = other;\n if (!this.getPriority().equals(otherChildrenNode.getPriority())) {\n return false;\n }\n else if (this.children_.count() === otherChildrenNode.children_.count()) {\n var thisIter = this.getIterator(PriorityIndex_1.PRIORITY_INDEX);\n var otherIter = otherChildrenNode.getIterator(PriorityIndex_1.PRIORITY_INDEX);\n var thisCurrent = thisIter.getNext();\n var otherCurrent = otherIter.getNext();\n while (thisCurrent && otherCurrent) {\n if (thisCurrent.name !== otherCurrent.name ||\n !thisCurrent.node.equals(otherCurrent.node)) {\n return false;\n }\n thisCurrent = thisIter.getNext();\n otherCurrent = otherIter.getNext();\n }\n return thisCurrent === null && otherCurrent === null;\n }\n else {\n return false;\n }\n }\n };\n /**\n * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used\n * instead.\n *\n * @private\n * @param {!Index} indexDefinition\n * @return {?SortedMap.}\n */\n ChildrenNode.prototype.resolveIndex_ = function (indexDefinition) {\n if (indexDefinition === KeyIndex_1.KEY_INDEX) {\n return null;\n }\n else {\n return this.indexMap_.get(indexDefinition.toString());\n }\n };\n /**\n * @private\n * @type {RegExp}\n */\n ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\\d*)$/;\n return ChildrenNode;\n}());\nexports.ChildrenNode = ChildrenNode;\n/**\n * @constructor\n * @extends {ChildrenNode}\n * @private\n */\nvar MaxNode = /** @class */ (function (_super) {\n tslib_1.__extends(MaxNode, _super);\n function MaxNode() {\n return _super.call(this, new SortedMap_1.SortedMap(comparators_1.NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap_1.IndexMap.Default) || this;\n }\n MaxNode.prototype.compareTo = function (other) {\n if (other === this) {\n return 0;\n }\n else {\n return 1;\n }\n };\n MaxNode.prototype.equals = function (other) {\n // Not that we every compare it, but MAX_NODE is only ever equal to itself\n return other === this;\n };\n MaxNode.prototype.getPriority = function () {\n return this;\n };\n MaxNode.prototype.getImmediateChild = function (childName) {\n return ChildrenNode.EMPTY_NODE;\n };\n MaxNode.prototype.isEmpty = function () {\n return false;\n };\n return MaxNode;\n}(ChildrenNode));\nexports.MaxNode = MaxNode;\n/**\n * Marker that will sort higher than any other snapshot.\n * @type {!MAX_NODE}\n * @const\n */\nexports.MAX_NODE = new MaxNode();\nObject.defineProperties(Node_1.NamedNode, {\n MIN: {\n value: new Node_1.NamedNode(util_2.MIN_NAME, ChildrenNode.EMPTY_NODE)\n },\n MAX: {\n value: new Node_1.NamedNode(util_2.MAX_NAME, exports.MAX_NODE)\n }\n});\n/**\n * Reference Extensions\n */\nKeyIndex_1.KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;\nLeafNode_1.LeafNode.__childrenNodeConstructor = ChildrenNode;\nsnap_1.setMaxNode(exports.MAX_NODE);\nPriorityIndex_1.setMaxNode(exports.MAX_NODE);\n\n//# sourceMappingURL=ChildrenNode.js.map\n\n\n/***/ }),\n/* 6 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n *\n * @param {!string} name\n * @param {!Node} node\n * @constructor\n * @struct\n */\nvar NamedNode = /** @class */ (function () {\n function NamedNode(name, node) {\n this.name = name;\n this.node = node;\n }\n /**\n *\n * @param {!string} name\n * @param {!Node} node\n * @return {NamedNode}\n */\n NamedNode.Wrap = function (name, node) {\n return new NamedNode(name, node);\n };\n return NamedNode;\n}());\nexports.NamedNode = NamedNode;\n\n//# sourceMappingURL=Node.js.map\n\n\n/***/ }),\n/* 7 */,\n/* 8 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = __webpack_require__(3);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar util_3 = __webpack_require__(0);\nvar util_4 = __webpack_require__(0);\n/**\n * True for invalid Firebase keys\n * @type {RegExp}\n * @private\n */\nexports.INVALID_KEY_REGEX_ = /[\\[\\].#$\\/\\u0000-\\u001F\\u007F]/;\n/**\n * True for invalid Firebase paths.\n * Allows '/' in paths.\n * @type {RegExp}\n * @private\n */\nexports.INVALID_PATH_REGEX_ = /[\\[\\].#$\\u0000-\\u001F\\u007F]/;\n/**\n * Maximum number of characters to allow in leaf value\n * @type {number}\n * @private\n */\nexports.MAX_LEAF_SIZE_ = 10 * 1024 * 1024;\n/**\n * @param {*} key\n * @return {boolean}\n */\nexports.isValidKey = function (key) {\n return (typeof key === 'string' && key.length !== 0 && !exports.INVALID_KEY_REGEX_.test(key));\n};\n/**\n * @param {string} pathString\n * @return {boolean}\n */\nexports.isValidPathString = function (pathString) {\n return (typeof pathString === 'string' &&\n pathString.length !== 0 &&\n !exports.INVALID_PATH_REGEX_.test(pathString));\n};\n/**\n * @param {string} pathString\n * @return {boolean}\n */\nexports.isValidRootPathString = function (pathString) {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n return exports.isValidPathString(pathString);\n};\n/**\n * @param {*} priority\n * @return {boolean}\n */\nexports.isValidPriority = function (priority) {\n return (priority === null ||\n typeof priority === 'string' ||\n (typeof priority === 'number' && !util_2.isInvalidJSONNumber(priority)) ||\n (priority && typeof priority === 'object' && util_1.contains(priority, '.sv')));\n};\n/**\n * Pre-validate a datum passed as an argument to Firebase function.\n *\n * @param {string} fnName\n * @param {number} argumentNumber\n * @param {*} data\n * @param {!Path} path\n * @param {boolean} optional\n */\nexports.validateFirebaseDataArg = function (fnName, argumentNumber, data, path, optional) {\n if (optional && data === undefined)\n return;\n exports.validateFirebaseData(util_3.errorPrefix(fnName, argumentNumber, optional), data, path);\n};\n/**\n * Validate a data object client-side before sending to server.\n *\n * @param {string} errorPrefix\n * @param {*} data\n * @param {!Path|!ValidationPath} path_\n */\nexports.validateFirebaseData = function (errorPrefix, data, path_) {\n var path = path_ instanceof Path_1.Path ? new Path_1.ValidationPath(path_, errorPrefix) : path_;\n if (data === undefined) {\n throw new Error(errorPrefix + 'contains undefined ' + path.toErrorString());\n }\n if (typeof data === 'function') {\n throw new Error(errorPrefix +\n 'contains a function ' +\n path.toErrorString() +\n ' with contents = ' +\n data.toString());\n }\n if (util_2.isInvalidJSONNumber(data)) {\n throw new Error(errorPrefix + 'contains ' + data.toString() + ' ' + path.toErrorString());\n }\n // Check max leaf size, but try to avoid the utf8 conversion if we can.\n if (typeof data === 'string' &&\n data.length > exports.MAX_LEAF_SIZE_ / 3 &&\n util_4.stringLength(data) > exports.MAX_LEAF_SIZE_) {\n throw new Error(errorPrefix +\n 'contains a string greater than ' +\n exports.MAX_LEAF_SIZE_ +\n ' utf8 bytes ' +\n path.toErrorString() +\n \" ('\" +\n data.substring(0, 50) +\n \"...')\");\n }\n // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON\n // to save extra walking of large objects.\n if (data && typeof data === 'object') {\n var hasDotValue_1 = false, hasActualChild_1 = false;\n util_1.forEach(data, function (key, value) {\n if (key === '.value') {\n hasDotValue_1 = true;\n }\n else if (key !== '.priority' && key !== '.sv') {\n hasActualChild_1 = true;\n if (!exports.isValidKey(key)) {\n throw new Error(errorPrefix +\n ' contains an invalid key (' +\n key +\n ') ' +\n path.toErrorString() +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\n }\n }\n path.push(key);\n exports.validateFirebaseData(errorPrefix, value, path);\n path.pop();\n });\n if (hasDotValue_1 && hasActualChild_1) {\n throw new Error(errorPrefix +\n ' contains \".value\" child ' +\n path.toErrorString() +\n ' in addition to actual children.');\n }\n }\n};\n/**\n * Pre-validate paths passed in the firebase function.\n *\n * @param {string} errorPrefix\n * @param {Array} mergePaths\n */\nexports.validateFirebaseMergePaths = function (errorPrefix, mergePaths) {\n var i, curPath;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n var keys = curPath.slice();\n for (var j = 0; j < keys.length; j++) {\n if (keys[j] === '.priority' && j === keys.length - 1) {\n // .priority is OK\n }\n else if (!exports.isValidKey(keys[j])) {\n throw new Error(errorPrefix +\n 'contains an invalid key (' +\n keys[j] +\n ') in path ' +\n curPath.toString() +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\n }\n }\n }\n // Check that update keys are not descendants of each other.\n // We rely on the property that sorting guarantees that ancestors come\n // right before descendants.\n mergePaths.sort(Path_1.Path.comparePaths);\n var prevPath = null;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n if (prevPath !== null && prevPath.contains(curPath)) {\n throw new Error(errorPrefix +\n 'contains a path ' +\n prevPath.toString() +\n ' that is ancestor of another path ' +\n curPath.toString());\n }\n prevPath = curPath;\n }\n};\n/**\n * pre-validate an object passed as an argument to firebase function (\n * must be an object - e.g. for firebase.update()).\n *\n * @param {string} fnName\n * @param {number} argumentNumber\n * @param {*} data\n * @param {!Path} path\n * @param {boolean} optional\n */\nexports.validateFirebaseMergeDataArg = function (fnName, argumentNumber, data, path, optional) {\n if (optional && data === undefined)\n return;\n var errorPrefix = util_3.errorPrefix(fnName, argumentNumber, optional);\n if (!(data && typeof data === 'object') || Array.isArray(data)) {\n throw new Error(errorPrefix + ' must be an object containing the children to replace.');\n }\n var mergePaths = [];\n util_1.forEach(data, function (key, value) {\n var curPath = new Path_1.Path(key);\n exports.validateFirebaseData(errorPrefix, value, path.child(curPath));\n if (curPath.getBack() === '.priority') {\n if (!exports.isValidPriority(value)) {\n throw new Error(errorPrefix +\n \"contains an invalid value for '\" +\n curPath.toString() +\n \"', which must be a valid \" +\n 'Firebase priority (a string, finite number, server value, or null).');\n }\n }\n mergePaths.push(curPath);\n });\n exports.validateFirebaseMergePaths(errorPrefix, mergePaths);\n};\nexports.validatePriority = function (fnName, argumentNumber, priority, optional) {\n if (optional && priority === undefined)\n return;\n if (util_2.isInvalidJSONNumber(priority))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'is ' +\n priority.toString() +\n ', but must be a valid Firebase priority (a string, finite number, ' +\n 'server value, or null).');\n // Special case to allow importing data with a .sv.\n if (!exports.isValidPriority(priority))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid Firebase priority ' +\n '(a string, finite number, server value, or null).');\n};\nexports.validateEventType = function (fnName, argumentNumber, eventType, optional) {\n if (optional && eventType === undefined)\n return;\n switch (eventType) {\n case 'value':\n case 'child_added':\n case 'child_removed':\n case 'child_changed':\n case 'child_moved':\n break;\n default:\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid event type = \"value\", \"child_added\", \"child_removed\", ' +\n '\"child_changed\", or \"child_moved\".');\n }\n};\nexports.validateKey = function (fnName, argumentNumber, key, optional) {\n if (optional && key === undefined)\n return;\n if (!exports.isValidKey(key))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'was an invalid key = \"' +\n key +\n '\". Firebase keys must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\").');\n};\nexports.validatePathString = function (fnName, argumentNumber, pathString, optional) {\n if (optional && pathString === undefined)\n return;\n if (!exports.isValidPathString(pathString))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'was an invalid path = \"' +\n pathString +\n '\". Paths must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\"');\n};\nexports.validateRootPathString = function (fnName, argumentNumber, pathString, optional) {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n exports.validatePathString(fnName, argumentNumber, pathString, optional);\n};\nexports.validateWritablePath = function (fnName, path) {\n if (path.getFront() === '.info') {\n throw new Error(fnName + \" failed = Can't modify data under /.info/\");\n }\n};\nexports.validateUrl = function (fnName, argumentNumber, parsedUrl) {\n // TODO = Validate server better.\n var pathString = parsedUrl.path.toString();\n if (!(typeof parsedUrl.repoInfo.host === 'string') ||\n parsedUrl.repoInfo.host.length === 0 ||\n (!exports.isValidKey(parsedUrl.repoInfo.namespace) &&\n parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||\n (pathString.length !== 0 && !exports.isValidRootPathString(pathString))) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, false) +\n 'must be a valid firebase URL and ' +\n 'the path can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\".');\n }\n};\nexports.validateCredential = function (fnName, argumentNumber, cred, optional) {\n if (optional && cred === undefined)\n return;\n if (!(typeof cred === 'string'))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid credential (a string).');\n};\nexports.validateBoolean = function (fnName, argumentNumber, bool, optional) {\n if (optional && bool === undefined)\n return;\n if (typeof bool !== 'boolean')\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) + 'must be a boolean.');\n};\nexports.validateString = function (fnName, argumentNumber, string, optional) {\n if (optional && string === undefined)\n return;\n if (!(typeof string === 'string')) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid string.');\n }\n};\nexports.validateObject = function (fnName, argumentNumber, obj, optional) {\n if (optional && obj === undefined)\n return;\n if (!(obj && typeof obj === 'object') || obj === null) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid object.');\n }\n};\nexports.validateObjectContainsKey = function (fnName, argumentNumber, obj, key, optional, opt_type) {\n var objectContainsKey = obj && typeof obj === 'object' && util_1.contains(obj, key);\n if (!objectContainsKey) {\n if (optional) {\n return;\n }\n else {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must contain the key \"' +\n key +\n '\"');\n }\n }\n if (opt_type) {\n var val = util_1.safeGet(obj, key);\n if ((opt_type === 'number' && !(typeof val === 'number')) ||\n (opt_type === 'string' && !(typeof val === 'string')) ||\n (opt_type === 'boolean' && !(typeof val === 'boolean')) ||\n (opt_type === 'function' && !(typeof val === 'function')) ||\n (opt_type === 'object' && !(typeof val === 'object') && val)) {\n if (optional) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'contains invalid value for key \"' +\n key +\n '\" (must be of type \"' +\n opt_type +\n '\")');\n }\n else {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must contain the key \"' +\n key +\n '\" with type \"' +\n opt_type +\n '\"');\n }\n }\n }\n};\n\n//# sourceMappingURL=validation.js.map\n\n\n/***/ }),\n/* 9 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n *\n * @enum\n */\nvar OperationType;\n(function (OperationType) {\n OperationType[OperationType[\"OVERWRITE\"] = 0] = \"OVERWRITE\";\n OperationType[OperationType[\"MERGE\"] = 1] = \"MERGE\";\n OperationType[OperationType[\"ACK_USER_WRITE\"] = 2] = \"ACK_USER_WRITE\";\n OperationType[OperationType[\"LISTEN_COMPLETE\"] = 3] = \"LISTEN_COMPLETE\";\n})(OperationType = exports.OperationType || (exports.OperationType = {}));\n/**\n * @param {boolean} fromUser\n * @param {boolean} fromServer\n * @param {?string} queryId\n * @param {boolean} tagged\n * @constructor\n */\nvar OperationSource = /** @class */ (function () {\n function OperationSource(fromUser, fromServer, queryId, tagged) {\n this.fromUser = fromUser;\n this.fromServer = fromServer;\n this.queryId = queryId;\n this.tagged = tagged;\n util_1.assert(!tagged || fromServer, 'Tagged queries must be from server.');\n }\n /**\n * @const\n * @type {!OperationSource}\n */\n OperationSource.User = new OperationSource(\n /*fromUser=*/ true, false, null, \n /*tagged=*/ false);\n /**\n * @const\n * @type {!OperationSource}\n */\n OperationSource.Server = new OperationSource(false, \n /*fromServer=*/ true, null, \n /*tagged=*/ false);\n /**\n * @param {string} queryId\n * @return {!OperationSource}\n */\n OperationSource.forServerTaggedQuery = function (queryId) {\n return new OperationSource(false, \n /*fromServer=*/ true, queryId, \n /*tagged=*/ true);\n };\n return OperationSource;\n}());\nexports.OperationSource = OperationSource;\n\n//# sourceMappingURL=Operation.js.map\n\n\n/***/ }),\n/* 10 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * @constructor\n * @struct\n * @param {!string} type The event type\n * @param {!Node} snapshotNode The data\n * @param {string=} childName The name for this child, if it's a child event\n * @param {Node=} oldSnap Used for intermediate processing of child changed events\n * @param {string=} prevName The name for the previous child, if applicable\n */\nvar Change = /** @class */ (function () {\n function Change(type, snapshotNode, childName, oldSnap, prevName) {\n this.type = type;\n this.snapshotNode = snapshotNode;\n this.childName = childName;\n this.oldSnap = oldSnap;\n this.prevName = prevName;\n }\n /**\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.valueChange = function (snapshot) {\n return new Change(Change.VALUE, snapshot);\n };\n /**\n * @param {string} childKey\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.childAddedChange = function (childKey, snapshot) {\n return new Change(Change.CHILD_ADDED, snapshot, childKey);\n };\n /**\n * @param {string} childKey\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.childRemovedChange = function (childKey, snapshot) {\n return new Change(Change.CHILD_REMOVED, snapshot, childKey);\n };\n /**\n * @param {string} childKey\n * @param {!Node} newSnapshot\n * @param {!Node} oldSnapshot\n * @return {!Change}\n */\n Change.childChangedChange = function (childKey, newSnapshot, oldSnapshot) {\n return new Change(Change.CHILD_CHANGED, newSnapshot, childKey, oldSnapshot);\n };\n /**\n * @param {string} childKey\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.childMovedChange = function (childKey, snapshot) {\n return new Change(Change.CHILD_MOVED, snapshot, childKey);\n };\n //event types\n /** Event type for a child added */\n Change.CHILD_ADDED = 'child_added';\n /** Event type for a child removed */\n Change.CHILD_REMOVED = 'child_removed';\n /** Event type for a child changed */\n Change.CHILD_CHANGED = 'child_changed';\n /** Event type for a child moved */\n Change.CHILD_MOVED = 'child_moved';\n /** Event type for a value change */\n Change.VALUE = 'value';\n return Change;\n}());\nexports.Change = Change;\n\n//# sourceMappingURL=Change.js.map\n\n\n/***/ }),\n/* 11 */,\n/* 12 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = __webpack_require__(2);\nvar Index_1 = __webpack_require__(16);\nvar Node_1 = __webpack_require__(6);\nvar util_1 = __webpack_require__(1);\nvar util_2 = __webpack_require__(0);\nvar __EMPTY_NODE;\nvar KeyIndex = /** @class */ (function (_super) {\n tslib_1.__extends(KeyIndex, _super);\n function KeyIndex() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n Object.defineProperty(KeyIndex, \"__EMPTY_NODE\", {\n get: function () {\n return __EMPTY_NODE;\n },\n set: function (val) {\n __EMPTY_NODE = val;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.compare = function (a, b) {\n return util_1.nameCompare(a.name, b.name);\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.isDefinedOn = function (node) {\n // We could probably return true here (since every node has a key), but it's never called\n // so just leaving unimplemented for now.\n throw util_2.assertionError('KeyIndex.isDefinedOn not expected to be called.');\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.indexedValueChanged = function (oldNode, newNode) {\n return false; // The key for a node never changes.\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.maxPost = function () {\n // TODO: This should really be created once and cached in a static property, but\n // NamedNode isn't defined yet, so I can't use it in a static. Bleh.\n return new Node_1.NamedNode(util_1.MAX_NAME, __EMPTY_NODE);\n };\n /**\n * @param {*} indexValue\n * @param {string} name\n * @return {!NamedNode}\n */\n KeyIndex.prototype.makePost = function (indexValue, name) {\n util_2.assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');\n // We just use empty node, but it'll never be compared, since our comparator only looks at name.\n return new Node_1.NamedNode(indexValue, __EMPTY_NODE);\n };\n /**\n * @return {!string} String representation for inclusion in a query spec\n */\n KeyIndex.prototype.toString = function () {\n return '.key';\n };\n return KeyIndex;\n}(Index_1.Index));\nexports.KeyIndex = KeyIndex;\nexports.KEY_INDEX = new KeyIndex();\n\n//# sourceMappingURL=KeyIndex.js.map\n\n\n/***/ }),\n/* 13 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ChildrenNode_1 = __webpack_require__(5);\nvar LeafNode_1 = __webpack_require__(17);\nvar Node_1 = __webpack_require__(6);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\nvar childSet_1 = __webpack_require__(41);\nvar comparators_1 = __webpack_require__(42);\nvar IndexMap_1 = __webpack_require__(40);\nvar PriorityIndex_1 = __webpack_require__(4);\nvar USE_HINZE = true;\n/**\n * Constructs a snapshot node representing the passed JSON and returns it.\n * @param {*} json JSON to create a node for.\n * @param {?string|?number=} priority Optional priority to use. This will be ignored if the\n * passed JSON contains a .priority property.\n * @return {!Node}\n */\nfunction nodeFromJSON(json, priority) {\n if (priority === void 0) { priority = null; }\n if (json === null) {\n return ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n if (typeof json === 'object' && '.priority' in json) {\n priority = json['.priority'];\n }\n util_2.assert(priority === null ||\n typeof priority === 'string' ||\n typeof priority === 'number' ||\n (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);\n if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {\n json = json['.value'];\n }\n // Valid leaf nodes include non-objects or server-value wrapper objects\n if (typeof json !== 'object' || '.sv' in json) {\n var jsonLeaf = json;\n return new LeafNode_1.LeafNode(jsonLeaf, nodeFromJSON(priority));\n }\n if (!(json instanceof Array) && USE_HINZE) {\n var children_1 = [];\n var childrenHavePriority_1 = false;\n var hinzeJsonObj_1 = json;\n util_1.forEach(hinzeJsonObj_1, function (key, child) {\n if (typeof key !== 'string' || key.substring(0, 1) !== '.') {\n // Ignore metadata nodes\n var childNode = nodeFromJSON(hinzeJsonObj_1[key]);\n if (!childNode.isEmpty()) {\n childrenHavePriority_1 =\n childrenHavePriority_1 || !childNode.getPriority().isEmpty();\n children_1.push(new Node_1.NamedNode(key, childNode));\n }\n }\n });\n if (children_1.length == 0) {\n return ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n var childSet = childSet_1.buildChildSet(children_1, comparators_1.NAME_ONLY_COMPARATOR, function (namedNode) { return namedNode.name; }, comparators_1.NAME_COMPARATOR);\n if (childrenHavePriority_1) {\n var sortedChildSet = childSet_1.buildChildSet(children_1, PriorityIndex_1.PRIORITY_INDEX.getCompare());\n return new ChildrenNode_1.ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap_1.IndexMap({ '.priority': sortedChildSet }, { '.priority': PriorityIndex_1.PRIORITY_INDEX }));\n }\n else {\n return new ChildrenNode_1.ChildrenNode(childSet, nodeFromJSON(priority), IndexMap_1.IndexMap.Default);\n }\n }\n else {\n var node_1 = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var jsonObj_1 = json;\n util_1.forEach(jsonObj_1, function (key, childData) {\n if (util_1.contains(jsonObj_1, key)) {\n if (key.substring(0, 1) !== '.') {\n // ignore metadata nodes.\n var childNode = nodeFromJSON(childData);\n if (childNode.isLeafNode() || !childNode.isEmpty())\n node_1 = node_1.updateImmediateChild(key, childNode);\n }\n }\n });\n return node_1.updatePriority(nodeFromJSON(priority));\n }\n}\nexports.nodeFromJSON = nodeFromJSON;\nPriorityIndex_1.setNodeFromJSON(nodeFromJSON);\n\n//# sourceMappingURL=nodeFromJSON.js.map\n\n\n/***/ }),\n/* 14 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar DOMStorageWrapper_1 = __webpack_require__(81);\nvar MemoryStorage_1 = __webpack_require__(82);\n/**\n * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.\n * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change\n * to reflect this type\n *\n * @param {string} domStorageName Name of the underlying storage object\n * (e.g. 'localStorage' or 'sessionStorage').\n * @return {?} Turning off type information until a common interface is defined.\n */\nvar createStoragefor = function (domStorageName) {\n try {\n // NOTE: just accessing \"localStorage\" or \"window['localStorage']\" may throw a security exception,\n // so it must be inside the try/catch.\n if (typeof window !== 'undefined' &&\n typeof window[domStorageName] !== 'undefined') {\n // Need to test cache. Just because it's here doesn't mean it works\n var domStorage = window[domStorageName];\n domStorage.setItem('firebase:sentinel', 'cache');\n domStorage.removeItem('firebase:sentinel');\n return new DOMStorageWrapper_1.DOMStorageWrapper(domStorage);\n }\n }\n catch (e) { }\n // Failed to create wrapper. Just return in-memory storage.\n // TODO: log?\n return new MemoryStorage_1.MemoryStorage();\n};\n/** A storage object that lasts across sessions */\nexports.PersistentStorage = createStoragefor('localStorage');\n/** A storage object that only lasts one session */\nexports.SessionStorage = createStoragefor('sessionStorage');\n\n//# sourceMappingURL=storage.js.map\n\n\n/***/ }),\n/* 15 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PROTOCOL_VERSION = '5';\nexports.VERSION_PARAM = 'v';\nexports.TRANSPORT_SESSION_PARAM = 's';\nexports.REFERER_PARAM = 'r';\nexports.FORGE_REF = 'f';\nexports.FORGE_DOMAIN = 'firebaseio.com';\nexports.LAST_SESSION_PARAM = 'ls';\nexports.WEBSOCKET = 'websocket';\nexports.LONG_POLLING = 'long_polling';\n\n//# sourceMappingURL=Constants.js.map\n\n\n/***/ }),\n/* 16 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Node_1 = __webpack_require__(6);\nvar util_1 = __webpack_require__(1);\n/**\n *\n * @constructor\n */\nvar Index = /** @class */ (function () {\n function Index() {\n }\n /**\n * @return {function(!NamedNode, !NamedNode):number} A standalone comparison function for\n * this index\n */\n Index.prototype.getCompare = function () {\n return this.compare.bind(this);\n };\n /**\n * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,\n * it's possible that the changes are isolated to parts of the snapshot that are not indexed.\n *\n * @param {!Node} oldNode\n * @param {!Node} newNode\n * @return {boolean} True if the portion of the snapshot being indexed changed between oldNode and newNode\n */\n Index.prototype.indexedValueChanged = function (oldNode, newNode) {\n var oldWrapped = new Node_1.NamedNode(util_1.MIN_NAME, oldNode);\n var newWrapped = new Node_1.NamedNode(util_1.MIN_NAME, newNode);\n return this.compare(oldWrapped, newWrapped) !== 0;\n };\n /**\n * @return {!NamedNode} a node wrapper that will sort equal to or less than\n * any other node wrapper, using this index\n */\n Index.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n return Index;\n}());\nexports.Index = Index;\n\n//# sourceMappingURL=Index.js.map\n\n\n/***/ }),\n/* 17 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar snap_1 = __webpack_require__(38);\nvar __childrenNodeConstructor;\n/**\n * LeafNode is a class for storing leaf nodes in a DataSnapshot. It\n * implements Node and stores the value of the node (a string,\n * number, or boolean) accessible via getValue().\n */\nvar LeafNode = /** @class */ (function () {\n /**\n * @implements {Node}\n * @param {!(string|number|boolean|Object)} value_ The value to store in this leaf node.\n * The object type is possible in the event of a deferred value\n * @param {!Node=} priorityNode_ The priority of this node.\n */\n function LeafNode(value_, priorityNode_) {\n if (priorityNode_ === void 0) { priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE; }\n this.value_ = value_;\n this.priorityNode_ = priorityNode_;\n this.lazyHash_ = null;\n util_1.assert(this.value_ !== undefined && this.value_ !== null, \"LeafNode shouldn't be created with null/undefined value.\");\n snap_1.validatePriorityNode(this.priorityNode_);\n }\n Object.defineProperty(LeafNode, \"__childrenNodeConstructor\", {\n get: function () {\n return __childrenNodeConstructor;\n },\n set: function (val) {\n __childrenNodeConstructor = val;\n },\n enumerable: true,\n configurable: true\n });\n /** @inheritDoc */\n LeafNode.prototype.isLeafNode = function () {\n return true;\n };\n /** @inheritDoc */\n LeafNode.prototype.getPriority = function () {\n return this.priorityNode_;\n };\n /** @inheritDoc */\n LeafNode.prototype.updatePriority = function (newPriorityNode) {\n return new LeafNode(this.value_, newPriorityNode);\n };\n /** @inheritDoc */\n LeafNode.prototype.getImmediateChild = function (childName) {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.priorityNode_;\n }\n else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n };\n /** @inheritDoc */\n LeafNode.prototype.getChild = function (path) {\n if (path.isEmpty()) {\n return this;\n }\n else if (path.getFront() === '.priority') {\n return this.priorityNode_;\n }\n else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.hasChild = function () {\n return false;\n };\n /** @inheritDoc */\n LeafNode.prototype.getPredecessorChildName = function (childName, childNode) {\n return null;\n };\n /** @inheritDoc */\n LeafNode.prototype.updateImmediateChild = function (childName, newChildNode) {\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n }\n else if (newChildNode.isEmpty() && childName !== '.priority') {\n return this;\n }\n else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);\n }\n };\n /** @inheritDoc */\n LeafNode.prototype.updateChild = function (path, newChildNode) {\n var front = path.getFront();\n if (front === null) {\n return newChildNode;\n }\n else if (newChildNode.isEmpty() && front !== '.priority') {\n return this;\n }\n else {\n util_1.assert(front !== '.priority' || path.getLength() === 1, '.priority must be the last token in a path');\n return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(path.popFront(), newChildNode));\n }\n };\n /** @inheritDoc */\n LeafNode.prototype.isEmpty = function () {\n return false;\n };\n /** @inheritDoc */\n LeafNode.prototype.numChildren = function () {\n return 0;\n };\n /** @inheritDoc */\n LeafNode.prototype.forEachChild = function (index, action) {\n return false;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.val = function (exportFormat) {\n if (exportFormat && !this.getPriority().isEmpty())\n return {\n '.value': this.getValue(),\n '.priority': this.getPriority().val()\n };\n else\n return this.getValue();\n };\n /** @inheritDoc */\n LeafNode.prototype.hash = function () {\n if (this.lazyHash_ === null) {\n var toHash = '';\n if (!this.priorityNode_.isEmpty())\n toHash +=\n 'priority:' +\n snap_1.priorityHashText(this.priorityNode_.val()) +\n ':';\n var type = typeof this.value_;\n toHash += type + ':';\n if (type === 'number') {\n toHash += util_2.doubleToIEEE754String(this.value_);\n }\n else {\n toHash += this.value_;\n }\n this.lazyHash_ = util_2.sha1(toHash);\n }\n return this.lazyHash_;\n };\n /**\n * Returns the value of the leaf node.\n * @return {Object|string|number|boolean} The value of the node.\n */\n LeafNode.prototype.getValue = function () {\n return this.value_;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.compareTo = function (other) {\n if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {\n return 1;\n }\n else if (other instanceof LeafNode.__childrenNodeConstructor) {\n return -1;\n }\n else {\n util_1.assert(other.isLeafNode(), 'Unknown node type');\n return this.compareToLeafNode_(other);\n }\n };\n /**\n * Comparison specifically for two leaf nodes\n * @param {!LeafNode} otherLeaf\n * @return {!number}\n * @private\n */\n LeafNode.prototype.compareToLeafNode_ = function (otherLeaf) {\n var otherLeafType = typeof otherLeaf.value_;\n var thisLeafType = typeof this.value_;\n var otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);\n var thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);\n util_1.assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);\n util_1.assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);\n if (otherIndex === thisIndex) {\n // Same type, compare values\n if (thisLeafType === 'object') {\n // Deferred value nodes are all equal, but we should also never get to this point...\n return 0;\n }\n else {\n // Note that this works because true > false, all others are number or string comparisons\n if (this.value_ < otherLeaf.value_) {\n return -1;\n }\n else if (this.value_ === otherLeaf.value_) {\n return 0;\n }\n else {\n return 1;\n }\n }\n }\n else {\n return thisIndex - otherIndex;\n }\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.withIndex = function () {\n return this;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.isIndexed = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.equals = function (other) {\n /**\n * @inheritDoc\n */\n if (other === this) {\n return true;\n }\n else if (other.isLeafNode()) {\n var otherLeaf = other;\n return (this.value_ === otherLeaf.value_ &&\n this.priorityNode_.equals(otherLeaf.priorityNode_));\n }\n else {\n return false;\n }\n };\n /**\n * The sort order for comparing leaf nodes of different types. If two leaf nodes have\n * the same type, the comparison falls back to their value\n * @type {Array.}\n * @const\n */\n LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];\n return LeafNode;\n}());\nexports.LeafNode = LeafNode;\n\n//# sourceMappingURL=LeafNode.js.map\n\n\n/***/ }),\n/* 18 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * An iterator over an LLRBNode.\n */\nvar SortedMapIterator = /** @class */ (function () {\n /**\n * @template K, V, T\n * @param {LLRBNode|LLRBEmptyNode} node Node to iterate.\n * @param {?K} startKey\n * @param {function(K, K): number} comparator\n * @param {boolean} isReverse_ Whether or not to iterate in reverse\n * @param {(function(K, V):T)=} resultGenerator_\n */\n function SortedMapIterator(node, startKey, comparator, isReverse_, resultGenerator_) {\n if (resultGenerator_ === void 0) { resultGenerator_ = null; }\n this.isReverse_ = isReverse_;\n this.resultGenerator_ = resultGenerator_;\n /** @private\n * @type {Array.}\n */\n this.nodeStack_ = [];\n var cmp = 1;\n while (!node.isEmpty()) {\n node = node;\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (isReverse_)\n cmp *= -1;\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse_) {\n node = node.left;\n }\n else {\n node = node.right;\n }\n }\n else if (cmp === 0) {\n // This node is exactly equal to our start key. Push it on the stack, but stop iterating;\n this.nodeStack_.push(node);\n break;\n }\n else {\n // This node is greater than our start key, add it to the stack and move to the next one\n this.nodeStack_.push(node);\n if (this.isReverse_) {\n node = node.right;\n }\n else {\n node = node.left;\n }\n }\n }\n }\n SortedMapIterator.prototype.getNext = function () {\n if (this.nodeStack_.length === 0)\n return null;\n var node = this.nodeStack_.pop();\n var result;\n if (this.resultGenerator_)\n result = this.resultGenerator_(node.key, node.value);\n else\n result = { key: node.key, value: node.value };\n if (this.isReverse_) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.right;\n }\n }\n else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.left;\n }\n }\n return result;\n };\n SortedMapIterator.prototype.hasNext = function () {\n return this.nodeStack_.length > 0;\n };\n SortedMapIterator.prototype.peek = function () {\n if (this.nodeStack_.length === 0)\n return null;\n var node = this.nodeStack_[this.nodeStack_.length - 1];\n if (this.resultGenerator_) {\n return this.resultGenerator_(node.key, node.value);\n }\n else {\n return { key: node.key, value: node.value };\n }\n };\n return SortedMapIterator;\n}());\nexports.SortedMapIterator = SortedMapIterator;\n/**\n * Represents a node in a Left-leaning Red-Black tree.\n */\nvar LLRBNode = /** @class */ (function () {\n /**\n * @template K, V\n * @param {!K} key Key associated with this node.\n * @param {!V} value Value associated with this node.\n * @param {?boolean} color Whether this node is red.\n * @param {?(LLRBNode|LLRBEmptyNode)=} left Left child.\n * @param {?(LLRBNode|LLRBEmptyNode)=} right Right child.\n */\n function LLRBNode(key, value, color, left, right) {\n this.key = key;\n this.value = value;\n this.color = color != null ? color : LLRBNode.RED;\n this.left =\n left != null ? left : SortedMap.EMPTY_NODE;\n this.right =\n right != null ? right : SortedMap.EMPTY_NODE;\n }\n /**\n * Returns a copy of the current node, optionally replacing pieces of it.\n *\n * @param {?K} key New key for the node, or null.\n * @param {?V} value New value for the node, or null.\n * @param {?boolean} color New color for the node, or null.\n * @param {?LLRBNode|LLRBEmptyNode} left New left child for the node, or null.\n * @param {?LLRBNode|LLRBEmptyNode} right New right child for the node, or null.\n * @return {!LLRBNode} The node copy.\n */\n LLRBNode.prototype.copy = function (key, value, color, left, right) {\n return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);\n };\n /**\n * @return {number} The total number of nodes in the tree.\n */\n LLRBNode.prototype.count = function () {\n return this.left.count() + 1 + this.right.count();\n };\n /**\n * @return {boolean} True if the tree is empty.\n */\n LLRBNode.prototype.isEmpty = function () {\n return false;\n };\n /**\n * Traverses the tree in key order and calls the specified action function\n * for each node.\n *\n * @param {function(!K, !V):*} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {*} The first truthy value returned by action, or the last falsey\n * value returned by action\n */\n LLRBNode.prototype.inorderTraversal = function (action) {\n return (this.left.inorderTraversal(action) ||\n action(this.key, this.value) ||\n this.right.inorderTraversal(action));\n };\n /**\n * Traverses the tree in reverse key order and calls the specified action function\n * for each node.\n *\n * @param {function(!Object, !Object)} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {*} True if traversal was aborted.\n */\n LLRBNode.prototype.reverseTraversal = function (action) {\n return (this.right.reverseTraversal(action) ||\n action(this.key, this.value) ||\n this.left.reverseTraversal(action));\n };\n /**\n * @return {!Object} The minimum node in the tree.\n * @private\n */\n LLRBNode.prototype.min_ = function () {\n if (this.left.isEmpty()) {\n return this;\n }\n else {\n return this.left.min_();\n }\n };\n /**\n * @return {!K} The maximum key in the tree.\n */\n LLRBNode.prototype.minKey = function () {\n return this.min_().key;\n };\n /**\n * @return {!K} The maximum key in the tree.\n */\n LLRBNode.prototype.maxKey = function () {\n if (this.right.isEmpty()) {\n return this.key;\n }\n else {\n return this.right.maxKey();\n }\n };\n /**\n *\n * @param {!Object} key Key to insert.\n * @param {!Object} value Value to insert.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBNode} New tree, with the key/value added.\n */\n LLRBNode.prototype.insert = function (key, value, comparator) {\n var cmp, n;\n n = this;\n cmp = comparator(key, n.key);\n if (cmp < 0) {\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n }\n else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n }\n else {\n n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));\n }\n return n.fixUp_();\n };\n /**\n * @private\n * @return {!LLRBNode|LLRBEmptyNode} New tree, with the minimum key removed.\n */\n LLRBNode.prototype.removeMin_ = function () {\n if (this.left.isEmpty()) {\n return SortedMap.EMPTY_NODE;\n }\n var n = this;\n if (!n.left.isRed_() && !n.left.left.isRed_())\n n = n.moveRedLeft_();\n n = n.copy(null, null, null, n.left.removeMin_(), null);\n return n.fixUp_();\n };\n /**\n * @param {!Object} key The key of the item to remove.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBNode|LLRBEmptyNode} New tree, with the specified item removed.\n */\n LLRBNode.prototype.remove = function (key, comparator) {\n var n, smallest;\n n = this;\n if (comparator(key, n.key) < 0) {\n if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {\n n = n.moveRedLeft_();\n }\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n }\n else {\n if (n.left.isRed_())\n n = n.rotateRight_();\n if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {\n n = n.moveRedRight_();\n }\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return SortedMap.EMPTY_NODE;\n }\n else {\n smallest = n.right.min_();\n n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp_();\n };\n /**\n * @private\n * @return {boolean} Whether this is a RED node.\n */\n LLRBNode.prototype.isRed_ = function () {\n return this.color;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree after performing any needed rotations.\n */\n LLRBNode.prototype.fixUp_ = function () {\n var n = this;\n if (n.right.isRed_() && !n.left.isRed_())\n n = n.rotateLeft_();\n if (n.left.isRed_() && n.left.left.isRed_())\n n = n.rotateRight_();\n if (n.left.isRed_() && n.right.isRed_())\n n = n.colorFlip_();\n return n;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after moveRedLeft.\n */\n LLRBNode.prototype.moveRedLeft_ = function () {\n var n = this.colorFlip_();\n if (n.right.left.isRed_()) {\n n = n.copy(null, null, null, null, n.right.rotateRight_());\n n = n.rotateLeft_();\n n = n.colorFlip_();\n }\n return n;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after moveRedRight.\n */\n LLRBNode.prototype.moveRedRight_ = function () {\n var n = this.colorFlip_();\n if (n.left.left.isRed_()) {\n n = n.rotateRight_();\n n = n.colorFlip_();\n }\n return n;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after rotateLeft.\n */\n LLRBNode.prototype.rotateLeft_ = function () {\n var nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return this.right.copy(null, null, this.color, nl, null);\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after rotateRight.\n */\n LLRBNode.prototype.rotateRight_ = function () {\n var nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return this.left.copy(null, null, this.color, null, nr);\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after colorFlip.\n */\n LLRBNode.prototype.colorFlip_ = function () {\n var left = this.left.copy(null, null, !this.left.color, null, null);\n var right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n };\n /**\n * For testing.\n *\n * @private\n * @return {boolean} True if all is well.\n */\n LLRBNode.prototype.checkMaxDepth_ = function () {\n var blackDepth = this.check_();\n return Math.pow(2.0, blackDepth) <= this.count() + 1;\n };\n /**\n * @private\n * @return {number} Not sure what this returns exactly. :-).\n */\n LLRBNode.prototype.check_ = function () {\n var blackDepth;\n if (this.isRed_() && this.left.isRed_()) {\n throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');\n }\n if (this.right.isRed_()) {\n throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');\n }\n blackDepth = this.left.check_();\n if (blackDepth !== this.right.check_()) {\n throw new Error('Black depths differ');\n }\n else {\n return blackDepth + (this.isRed_() ? 0 : 1);\n }\n };\n LLRBNode.RED = true;\n LLRBNode.BLACK = false;\n return LLRBNode;\n}());\nexports.LLRBNode = LLRBNode;\n/**\n * Represents an empty node (a leaf node in the Red-Black Tree).\n */\nvar LLRBEmptyNode = /** @class */ (function () {\n function LLRBEmptyNode() {\n }\n /**\n * Returns a copy of the current node.\n *\n * @return {!LLRBEmptyNode} The node copy.\n */\n LLRBEmptyNode.prototype.copy = function (key, value, color, left, right) {\n return this;\n };\n /**\n * Returns a copy of the tree, with the specified key/value added.\n *\n * @param {!K} key Key to be added.\n * @param {!V} value Value to be added.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBNode} New tree, with item added.\n */\n LLRBEmptyNode.prototype.insert = function (key, value, comparator) {\n return new LLRBNode(key, value, null);\n };\n /**\n * Returns a copy of the tree, with the specified key removed.\n *\n * @param {!K} key The key to remove.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBEmptyNode} New tree, with item removed.\n */\n LLRBEmptyNode.prototype.remove = function (key, comparator) {\n return this;\n };\n /**\n * @return {number} The total number of nodes in the tree.\n */\n LLRBEmptyNode.prototype.count = function () {\n return 0;\n };\n /**\n * @return {boolean} True if the tree is empty.\n */\n LLRBEmptyNode.prototype.isEmpty = function () {\n return true;\n };\n /**\n * Traverses the tree in key order and calls the specified action function\n * for each node.\n *\n * @param {function(!K, !V):*} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {boolean} True if traversal was aborted.\n */\n LLRBEmptyNode.prototype.inorderTraversal = function (action) {\n return false;\n };\n /**\n * Traverses the tree in reverse key order and calls the specified action function\n * for each node.\n *\n * @param {function(!K, !V)} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {boolean} True if traversal was aborted.\n */\n LLRBEmptyNode.prototype.reverseTraversal = function (action) {\n return false;\n };\n /**\n * @return {null}\n */\n LLRBEmptyNode.prototype.minKey = function () {\n return null;\n };\n /**\n * @return {null}\n */\n LLRBEmptyNode.prototype.maxKey = function () {\n return null;\n };\n /**\n * @private\n * @return {number} Not sure what this returns exactly. :-).\n */\n LLRBEmptyNode.prototype.check_ = function () {\n return 0;\n };\n /**\n * @private\n * @return {boolean} Whether this node is red.\n */\n LLRBEmptyNode.prototype.isRed_ = function () {\n return false;\n };\n return LLRBEmptyNode;\n}());\nexports.LLRBEmptyNode = LLRBEmptyNode;\n/**\n * An immutable sorted map implementation, based on a Left-leaning Red-Black\n * tree.\n */\nvar SortedMap = /** @class */ (function () {\n /**\n * @template K, V\n * @param {function(K, K):number} comparator_ Key comparator.\n * @param {LLRBNode=} root_ (Optional) Root node for the map.\n */\n function SortedMap(comparator_, root_) {\n if (root_ === void 0) { root_ = SortedMap.EMPTY_NODE; }\n this.comparator_ = comparator_;\n this.root_ = root_;\n }\n /**\n * Returns a copy of the map, with the specified key/value added or replaced.\n * (TODO: We should perhaps rename this method to 'put')\n *\n * @param {!K} key Key to be added.\n * @param {!V} value Value to be added.\n * @return {!SortedMap.} New map, with item added.\n */\n SortedMap.prototype.insert = function (key, value) {\n return new SortedMap(this.comparator_, this.root_\n .insert(key, value, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null));\n };\n /**\n * Returns a copy of the map, with the specified key removed.\n *\n * @param {!K} key The key to remove.\n * @return {!SortedMap.} New map, with item removed.\n */\n SortedMap.prototype.remove = function (key) {\n return new SortedMap(this.comparator_, this.root_\n .remove(key, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null));\n };\n /**\n * Returns the value of the node with the given key, or null.\n *\n * @param {!K} key The key to look up.\n * @return {?V} The value of the node with the given key, or null if the\n * key doesn't exist.\n */\n SortedMap.prototype.get = function (key) {\n var cmp;\n var node = this.root_;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n return node.value;\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else if (cmp > 0) {\n node = node.right;\n }\n }\n return null;\n };\n /**\n * Returns the key of the item *before* the specified key, or null if key is the first item.\n * @param {K} key The key to find the predecessor of\n * @return {?K} The predecessor key.\n */\n SortedMap.prototype.getPredecessorKey = function (key) {\n var cmp, node = this.root_, rightParent = null;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n if (!node.left.isEmpty()) {\n node = node.left;\n while (!node.right.isEmpty())\n node = node.right;\n return node.key;\n }\n else if (rightParent) {\n return rightParent.key;\n }\n else {\n return null; // first item.\n }\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else if (cmp > 0) {\n rightParent = node;\n node = node.right;\n }\n }\n throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');\n };\n /**\n * @return {boolean} True if the map is empty.\n */\n SortedMap.prototype.isEmpty = function () {\n return this.root_.isEmpty();\n };\n /**\n * @return {number} The total number of nodes in the map.\n */\n SortedMap.prototype.count = function () {\n return this.root_.count();\n };\n /**\n * @return {?K} The minimum key in the map.\n */\n SortedMap.prototype.minKey = function () {\n return this.root_.minKey();\n };\n /**\n * @return {?K} The maximum key in the map.\n */\n SortedMap.prototype.maxKey = function () {\n return this.root_.maxKey();\n };\n /**\n * Traverses the map in key order and calls the specified action function\n * for each key/value pair.\n *\n * @param {function(!K, !V):*} action Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @return {*} The first truthy value returned by action, or the last falsey\n * value returned by action\n */\n SortedMap.prototype.inorderTraversal = function (action) {\n return this.root_.inorderTraversal(action);\n };\n /**\n * Traverses the map in reverse key order and calls the specified action function\n * for each key/value pair.\n *\n * @param {function(!Object, !Object)} action Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @return {*} True if the traversal was aborted.\n */\n SortedMap.prototype.reverseTraversal = function (action) {\n return this.root_.reverseTraversal(action);\n };\n /**\n * Returns an iterator over the SortedMap.\n * @template T\n * @param {(function(K, V):T)=} resultGenerator\n * @return {SortedMapIterator.} The iterator.\n */\n SortedMap.prototype.getIterator = function (resultGenerator) {\n return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);\n };\n SortedMap.prototype.getIteratorFrom = function (key, resultGenerator) {\n return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);\n };\n SortedMap.prototype.getReverseIteratorFrom = function (key, resultGenerator) {\n return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);\n };\n SortedMap.prototype.getReverseIterator = function (resultGenerator) {\n return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);\n };\n /**\n * Always use the same empty node, to reduce memory.\n * @const\n */\n SortedMap.EMPTY_NODE = new LLRBEmptyNode();\n return SortedMap;\n}());\nexports.SortedMap = SortedMap;\n\n//# sourceMappingURL=SortedMap.js.map\n\n\n/***/ }),\n/* 19 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ServerValues_1 = __webpack_require__(44);\nvar nodeFromJSON_1 = __webpack_require__(13);\nvar Path_1 = __webpack_require__(3);\nvar SparseSnapshotTree_1 = __webpack_require__(45);\nvar SyncTree_1 = __webpack_require__(87);\nvar SnapshotHolder_1 = __webpack_require__(98);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar util_3 = __webpack_require__(0);\nvar AuthTokenProvider_1 = __webpack_require__(99);\nvar StatsManager_1 = __webpack_require__(26);\nvar StatsReporter_1 = __webpack_require__(101);\nvar StatsListener_1 = __webpack_require__(50);\nvar EventQueue_1 = __webpack_require__(102);\nvar PersistentConnection_1 = __webpack_require__(51);\nvar ReadonlyRestClient_1 = __webpack_require__(107);\nvar Database_1 = __webpack_require__(33);\nvar INTERRUPT_REASON = 'repo_interrupt';\n/**\n * A connection to a single data repository.\n */\nvar Repo = /** @class */ (function () {\n /**\n * @param {!RepoInfo} repoInfo_\n * @param {boolean} forceRestClient\n * @param {!FirebaseApp} app\n */\n function Repo(repoInfo_, forceRestClient, app) {\n var _this = this;\n this.repoInfo_ = repoInfo_;\n this.app = app;\n this.dataUpdateCount = 0;\n this.statsListener_ = null;\n this.eventQueue_ = new EventQueue_1.EventQueue();\n this.nextWriteId_ = 1;\n this.interceptServerDataCallback_ = null;\n // A list of data pieces and paths to be set when this client disconnects.\n this.onDisconnect_ = new SparseSnapshotTree_1.SparseSnapshotTree();\n /**\n * TODO: This should be @private but it's used by test_access.js and internal.js\n * @type {?PersistentConnection}\n */\n this.persistentConnection_ = null;\n /** @type {!AuthTokenProvider} */\n var authTokenProvider = new AuthTokenProvider_1.AuthTokenProvider(app);\n this.stats_ = StatsManager_1.StatsManager.getCollection(repoInfo_);\n if (forceRestClient || util_2.beingCrawled()) {\n this.server_ = new ReadonlyRestClient_1.ReadonlyRestClient(this.repoInfo_, this.onDataUpdate_.bind(this), authTokenProvider);\n // Minor hack: Fire onConnect immediately, since there's no actual connection.\n setTimeout(this.onConnectStatus_.bind(this, true), 0);\n }\n else {\n var authOverride = app.options['databaseAuthVariableOverride'];\n // Validate authOverride\n if (typeof authOverride !== 'undefined' && authOverride !== null) {\n if (typeof authOverride !== 'object') {\n throw new Error('Only objects are supported for option databaseAuthVariableOverride');\n }\n try {\n util_1.stringify(authOverride);\n }\n catch (e) {\n throw new Error('Invalid authOverride provided: ' + e);\n }\n }\n this.persistentConnection_ = new PersistentConnection_1.PersistentConnection(this.repoInfo_, this.onDataUpdate_.bind(this), this.onConnectStatus_.bind(this), this.onServerInfoUpdate_.bind(this), authTokenProvider, authOverride);\n this.server_ = this.persistentConnection_;\n }\n authTokenProvider.addTokenChangeListener(function (token) {\n _this.server_.refreshAuthToken(token);\n });\n // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),\n // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.\n this.statsReporter_ = StatsManager_1.StatsManager.getOrCreateReporter(repoInfo_, function () { return new StatsReporter_1.StatsReporter(_this.stats_, _this.server_); });\n this.transactions_init_();\n // Used for .info.\n this.infoData_ = new SnapshotHolder_1.SnapshotHolder();\n this.infoSyncTree_ = new SyncTree_1.SyncTree({\n startListening: function (query, tag, currentHashFn, onComplete) {\n var infoEvents = [];\n var node = _this.infoData_.getNode(query.path);\n // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events\n // on initial data...\n if (!node.isEmpty()) {\n infoEvents = _this.infoSyncTree_.applyServerOverwrite(query.path, node);\n setTimeout(function () {\n onComplete('ok');\n }, 0);\n }\n return infoEvents;\n },\n stopListening: function () { }\n });\n this.updateInfo_('connected', false);\n this.serverSyncTree_ = new SyncTree_1.SyncTree({\n startListening: function (query, tag, currentHashFn, onComplete) {\n _this.server_.listen(query, currentHashFn, tag, function (status, data) {\n var events = onComplete(status, data);\n _this.eventQueue_.raiseEventsForChangedPath(query.path, events);\n });\n // No synchronous events for network-backed sync trees\n return [];\n },\n stopListening: function (query, tag) {\n _this.server_.unlisten(query, tag);\n }\n });\n }\n /**\n * @return {string} The URL corresponding to the root of this Firebase.\n */\n Repo.prototype.toString = function () {\n return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);\n };\n /**\n * @return {!string} The namespace represented by the repo.\n */\n Repo.prototype.name = function () {\n return this.repoInfo_.namespace;\n };\n /**\n * @return {!number} The time in milliseconds, taking the server offset into account if we have one.\n */\n Repo.prototype.serverTime = function () {\n var offsetNode = this.infoData_.getNode(new Path_1.Path('.info/serverTimeOffset'));\n var offset = offsetNode.val() || 0;\n return new Date().getTime() + offset;\n };\n /**\n * Generate ServerValues using some variables from the repo object.\n * @return {!Object}\n */\n Repo.prototype.generateServerValues = function () {\n return ServerValues_1.generateWithValues({\n timestamp: this.serverTime()\n });\n };\n /**\n * Called by realtime when we get new messages from the server.\n *\n * @private\n * @param {string} pathString\n * @param {*} data\n * @param {boolean} isMerge\n * @param {?number} tag\n */\n Repo.prototype.onDataUpdate_ = function (pathString, data, isMerge, tag) {\n // For testing.\n this.dataUpdateCount++;\n var path = new Path_1.Path(pathString);\n data = this.interceptServerDataCallback_\n ? this.interceptServerDataCallback_(pathString, data)\n : data;\n var events = [];\n if (tag) {\n if (isMerge) {\n var taggedChildren = util_3.map(data, function (raw) {\n return nodeFromJSON_1.nodeFromJSON(raw);\n });\n events = this.serverSyncTree_.applyTaggedQueryMerge(path, taggedChildren, tag);\n }\n else {\n var taggedSnap = nodeFromJSON_1.nodeFromJSON(data);\n events = this.serverSyncTree_.applyTaggedQueryOverwrite(path, taggedSnap, tag);\n }\n }\n else if (isMerge) {\n var changedChildren = util_3.map(data, function (raw) {\n return nodeFromJSON_1.nodeFromJSON(raw);\n });\n events = this.serverSyncTree_.applyServerMerge(path, changedChildren);\n }\n else {\n var snap = nodeFromJSON_1.nodeFromJSON(data);\n events = this.serverSyncTree_.applyServerOverwrite(path, snap);\n }\n var affectedPath = path;\n if (events.length > 0) {\n // Since we have a listener outstanding for each transaction, receiving any events\n // is a proxy for some change having occurred.\n affectedPath = this.rerunTransactions_(path);\n }\n this.eventQueue_.raiseEventsForChangedPath(affectedPath, events);\n };\n /**\n * TODO: This should be @private but it's used by test_access.js and internal.js\n * @param {?function(!string, *):*} callback\n * @private\n */\n Repo.prototype.interceptServerData_ = function (callback) {\n this.interceptServerDataCallback_ = callback;\n };\n /**\n * @param {!boolean} connectStatus\n * @private\n */\n Repo.prototype.onConnectStatus_ = function (connectStatus) {\n this.updateInfo_('connected', connectStatus);\n if (connectStatus === false) {\n this.runOnDisconnectEvents_();\n }\n };\n /**\n * @param {!Object} updates\n * @private\n */\n Repo.prototype.onServerInfoUpdate_ = function (updates) {\n var _this = this;\n util_2.each(updates, function (value, key) {\n _this.updateInfo_(key, value);\n });\n };\n /**\n *\n * @param {!string} pathString\n * @param {*} value\n * @private\n */\n Repo.prototype.updateInfo_ = function (pathString, value) {\n var path = new Path_1.Path('/.info/' + pathString);\n var newNode = nodeFromJSON_1.nodeFromJSON(value);\n this.infoData_.updateSnapshot(path, newNode);\n var events = this.infoSyncTree_.applyServerOverwrite(path, newNode);\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n };\n /**\n * @return {!number}\n * @private\n */\n Repo.prototype.getNextWriteId_ = function () {\n return this.nextWriteId_++;\n };\n /**\n * @param {!Path} path\n * @param {*} newVal\n * @param {number|string|null} newPriority\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.setWithPriority = function (path, newVal, newPriority, onComplete) {\n var _this = this;\n this.log_('set', {\n path: path.toString(),\n value: newVal,\n priority: newPriority\n });\n // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or\n // (b) store unresolved paths on JSON parse\n var serverValues = this.generateServerValues();\n var newNodeUnresolved = nodeFromJSON_1.nodeFromJSON(newVal, newPriority);\n var newNode = ServerValues_1.resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n var writeId = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserOverwrite(path, newNode, writeId, true);\n this.eventQueue_.queueEvents(events);\n this.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), function (status, errorReason) {\n var success = status === 'ok';\n if (!success) {\n util_2.warn('set at ' + path + ' failed: ' + status);\n }\n var clearEvents = _this.serverSyncTree_.ackUserWrite(writeId, !success);\n _this.eventQueue_.raiseEventsForChangedPath(path, clearEvents);\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n var affectedPath = this.abortTransactions_(path);\n this.rerunTransactions_(affectedPath);\n // We queued the events above, so just flush the queue here\n this.eventQueue_.raiseEventsForChangedPath(affectedPath, []);\n };\n /**\n * @param {!Path} path\n * @param {!Object} childrenToMerge\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.update = function (path, childrenToMerge, onComplete) {\n var _this = this;\n this.log_('update', { path: path.toString(), value: childrenToMerge });\n // Start with our existing data and merge each child into it.\n var empty = true;\n var serverValues = this.generateServerValues();\n var changedChildren = {};\n util_3.forEach(childrenToMerge, function (changedKey, changedValue) {\n empty = false;\n var newNodeUnresolved = nodeFromJSON_1.nodeFromJSON(changedValue);\n changedChildren[changedKey] = ServerValues_1.resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n });\n if (!empty) {\n var writeId_1 = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserMerge(path, changedChildren, writeId_1);\n this.eventQueue_.queueEvents(events);\n this.server_.merge(path.toString(), childrenToMerge, function (status, errorReason) {\n var success = status === 'ok';\n if (!success) {\n util_2.warn('update at ' + path + ' failed: ' + status);\n }\n var clearEvents = _this.serverSyncTree_.ackUserWrite(writeId_1, !success);\n var affectedPath = clearEvents.length > 0 ? _this.rerunTransactions_(path) : path;\n _this.eventQueue_.raiseEventsForChangedPath(affectedPath, clearEvents);\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n util_3.forEach(childrenToMerge, function (changedPath) {\n var affectedPath = _this.abortTransactions_(path.child(changedPath));\n _this.rerunTransactions_(affectedPath);\n });\n // We queued the events above, so just flush the queue here\n this.eventQueue_.raiseEventsForChangedPath(path, []);\n }\n else {\n util_2.log(\"update() called with empty data. Don't do anything.\");\n this.callOnCompleteCallback(onComplete, 'ok');\n }\n };\n /**\n * Applies all of the changes stored up in the onDisconnect_ tree.\n * @private\n */\n Repo.prototype.runOnDisconnectEvents_ = function () {\n var _this = this;\n this.log_('onDisconnectEvents');\n var serverValues = this.generateServerValues();\n var resolvedOnDisconnectTree = ServerValues_1.resolveDeferredValueTree(this.onDisconnect_, serverValues);\n var events = [];\n resolvedOnDisconnectTree.forEachTree(Path_1.Path.Empty, function (path, snap) {\n events = events.concat(_this.serverSyncTree_.applyServerOverwrite(path, snap));\n var affectedPath = _this.abortTransactions_(path);\n _this.rerunTransactions_(affectedPath);\n });\n this.onDisconnect_ = new SparseSnapshotTree_1.SparseSnapshotTree();\n this.eventQueue_.raiseEventsForChangedPath(Path_1.Path.Empty, events);\n };\n /**\n * @param {!Path} path\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectCancel = function (path, onComplete) {\n var _this = this;\n this.server_.onDisconnectCancel(path.toString(), function (status, errorReason) {\n if (status === 'ok') {\n _this.onDisconnect_.forget(path);\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Path} path\n * @param {*} value\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectSet = function (path, value, onComplete) {\n var _this = this;\n var newNode = nodeFromJSON_1.nodeFromJSON(value);\n this.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {\n if (status === 'ok') {\n _this.onDisconnect_.remember(path, newNode);\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Path} path\n * @param {*} value\n * @param {*} priority\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectSetWithPriority = function (path, value, priority, onComplete) {\n var _this = this;\n var newNode = nodeFromJSON_1.nodeFromJSON(value, priority);\n this.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {\n if (status === 'ok') {\n _this.onDisconnect_.remember(path, newNode);\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Path} path\n * @param {*} childrenToMerge\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectUpdate = function (path, childrenToMerge, onComplete) {\n var _this = this;\n if (util_3.isEmpty(childrenToMerge)) {\n util_2.log(\"onDisconnect().update() called with empty data. Don't do anything.\");\n this.callOnCompleteCallback(onComplete, 'ok');\n return;\n }\n this.server_.onDisconnectMerge(path.toString(), childrenToMerge, function (status, errorReason) {\n if (status === 'ok') {\n util_3.forEach(childrenToMerge, function (childName, childNode) {\n var newChildNode = nodeFromJSON_1.nodeFromJSON(childNode);\n _this.onDisconnect_.remember(path.child(childName), newChildNode);\n });\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Query} query\n * @param {!EventRegistration} eventRegistration\n */\n Repo.prototype.addEventCallbackForQuery = function (query, eventRegistration) {\n var events;\n if (query.path.getFront() === '.info') {\n events = this.infoSyncTree_.addEventRegistration(query, eventRegistration);\n }\n else {\n events = this.serverSyncTree_.addEventRegistration(query, eventRegistration);\n }\n this.eventQueue_.raiseEventsAtPath(query.path, events);\n };\n /**\n * @param {!Query} query\n * @param {?EventRegistration} eventRegistration\n */\n Repo.prototype.removeEventCallbackForQuery = function (query, eventRegistration) {\n // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof\n // a little bit by handling the return values anyways.\n var events;\n if (query.path.getFront() === '.info') {\n events = this.infoSyncTree_.removeEventRegistration(query, eventRegistration);\n }\n else {\n events = this.serverSyncTree_.removeEventRegistration(query, eventRegistration);\n }\n this.eventQueue_.raiseEventsAtPath(query.path, events);\n };\n Repo.prototype.interrupt = function () {\n if (this.persistentConnection_) {\n this.persistentConnection_.interrupt(INTERRUPT_REASON);\n }\n };\n Repo.prototype.resume = function () {\n if (this.persistentConnection_) {\n this.persistentConnection_.resume(INTERRUPT_REASON);\n }\n };\n Repo.prototype.stats = function (showDelta) {\n if (showDelta === void 0) { showDelta = false; }\n if (typeof console === 'undefined')\n return;\n var stats;\n if (showDelta) {\n if (!this.statsListener_)\n this.statsListener_ = new StatsListener_1.StatsListener(this.stats_);\n stats = this.statsListener_.get();\n }\n else {\n stats = this.stats_.get();\n }\n var longestName = Object.keys(stats).reduce(function (previousValue, currentValue) {\n return Math.max(currentValue.length, previousValue);\n }, 0);\n util_3.forEach(stats, function (stat, value) {\n // pad stat names to be the same length (plus 2 extra spaces).\n for (var i = stat.length; i < longestName + 2; i++)\n stat += ' ';\n console.log(stat + value);\n });\n };\n Repo.prototype.statsIncrementCounter = function (metric) {\n this.stats_.incrementCounter(metric);\n this.statsReporter_.includeStat(metric);\n };\n /**\n * @param {...*} var_args\n * @private\n */\n Repo.prototype.log_ = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var prefix = '';\n if (this.persistentConnection_) {\n prefix = this.persistentConnection_.id + ':';\n }\n util_2.log.apply(void 0, [prefix].concat(var_args));\n };\n /**\n * @param {?function(?Error, *=)} callback\n * @param {!string} status\n * @param {?string=} errorReason\n */\n Repo.prototype.callOnCompleteCallback = function (callback, status, errorReason) {\n if (callback) {\n util_2.exceptionGuard(function () {\n if (status == 'ok') {\n callback(null);\n }\n else {\n var code = (status || 'error').toUpperCase();\n var message = code;\n if (errorReason)\n message += ': ' + errorReason;\n var error = new Error(message);\n error.code = code;\n callback(error);\n }\n });\n }\n };\n Object.defineProperty(Repo.prototype, \"database\", {\n get: function () {\n return this.__database || (this.__database = new Database_1.Database(this));\n },\n enumerable: true,\n configurable: true\n });\n return Repo;\n}());\nexports.Repo = Repo;\n\n//# sourceMappingURL=Repo.js.map\n\n\n/***/ }),\n/* 20 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully\n * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.\n * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks\n * whether a node potentially had children removed due to a filter.\n */\nvar CacheNode = /** @class */ (function () {\n /**\n * @param {!Node} node_\n * @param {boolean} fullyInitialized_\n * @param {boolean} filtered_\n */\n function CacheNode(node_, fullyInitialized_, filtered_) {\n this.node_ = node_;\n this.fullyInitialized_ = fullyInitialized_;\n this.filtered_ = filtered_;\n }\n /**\n * Returns whether this node was fully initialized with either server data or a complete overwrite by the client\n * @return {boolean}\n */\n CacheNode.prototype.isFullyInitialized = function () {\n return this.fullyInitialized_;\n };\n /**\n * Returns whether this node is potentially missing children due to a filter applied to the node\n * @return {boolean}\n */\n CacheNode.prototype.isFiltered = function () {\n return this.filtered_;\n };\n /**\n * @param {!Path} path\n * @return {boolean}\n */\n CacheNode.prototype.isCompleteForPath = function (path) {\n if (path.isEmpty()) {\n return this.isFullyInitialized() && !this.filtered_;\n }\n var childKey = path.getFront();\n return this.isCompleteForChild(childKey);\n };\n /**\n * @param {!string} key\n * @return {boolean}\n */\n CacheNode.prototype.isCompleteForChild = function (key) {\n return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));\n };\n /**\n * @return {!Node}\n */\n CacheNode.prototype.getNode = function () {\n return this.node_;\n };\n return CacheNode;\n}());\nexports.CacheNode = CacheNode;\n\n//# sourceMappingURL=CacheNode.js.map\n\n\n/***/ }),\n/* 21 */,\n/* 22 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = __webpack_require__(2);\nvar onDisconnect_1 = __webpack_require__(36);\nvar TransactionResult_1 = __webpack_require__(83);\nvar util_1 = __webpack_require__(1);\nvar NextPushId_1 = __webpack_require__(84);\nvar Query_1 = __webpack_require__(37);\nvar Repo_1 = __webpack_require__(19);\nvar Path_1 = __webpack_require__(3);\nvar QueryParams_1 = __webpack_require__(108);\nvar validation_1 = __webpack_require__(8);\nvar util_2 = __webpack_require__(0);\nvar util_3 = __webpack_require__(0);\nvar SyncPoint_1 = __webpack_require__(48);\nvar Reference = /** @class */ (function (_super) {\n tslib_1.__extends(Reference, _super);\n /**\n * Call options:\n * new Reference(Repo, Path) or\n * new Reference(url: string, string|RepoManager)\n *\n * Externally - this is the firebase.database.Reference type.\n *\n * @param {!Repo} repo\n * @param {(!Path)} path\n * @extends {Query}\n */\n function Reference(repo, path) {\n var _this = this;\n if (!(repo instanceof Repo_1.Repo)) {\n throw new Error('new Reference() no longer supported - use app.database().');\n }\n // call Query's constructor, passing in the repo and path.\n _this = _super.call(this, repo, path, QueryParams_1.QueryParams.DEFAULT, false) || this;\n return _this;\n }\n /** @return {?string} */\n Reference.prototype.getKey = function () {\n util_2.validateArgCount('Reference.key', 0, 0, arguments.length);\n if (this.path.isEmpty())\n return null;\n else\n return this.path.getBack();\n };\n /**\n * @param {!(string|Path)} pathString\n * @return {!Reference}\n */\n Reference.prototype.child = function (pathString) {\n util_2.validateArgCount('Reference.child', 1, 1, arguments.length);\n if (typeof pathString === 'number') {\n pathString = String(pathString);\n }\n else if (!(pathString instanceof Path_1.Path)) {\n if (this.path.getFront() === null)\n validation_1.validateRootPathString('Reference.child', 1, pathString, false);\n else\n validation_1.validatePathString('Reference.child', 1, pathString, false);\n }\n return new Reference(this.repo, this.path.child(pathString));\n };\n /** @return {?Reference} */\n Reference.prototype.getParent = function () {\n util_2.validateArgCount('Reference.parent', 0, 0, arguments.length);\n var parentPath = this.path.parent();\n return parentPath === null ? null : new Reference(this.repo, parentPath);\n };\n /** @return {!Reference} */\n Reference.prototype.getRoot = function () {\n util_2.validateArgCount('Reference.root', 0, 0, arguments.length);\n var ref = this;\n while (ref.getParent() !== null) {\n ref = ref.getParent();\n }\n return ref;\n };\n /** @return {!Database} */\n Reference.prototype.databaseProp = function () {\n return this.repo.database;\n };\n /**\n * @param {*} newVal\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.set = function (newVal, onComplete) {\n util_2.validateArgCount('Reference.set', 1, 2, arguments.length);\n validation_1.validateWritablePath('Reference.set', this.path);\n validation_1.validateFirebaseDataArg('Reference.set', 1, newVal, this.path, false);\n util_2.validateCallback('Reference.set', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo.setWithPriority(this.path, newVal, \n /*priority=*/ null, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {!Object} objectToMerge\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.update = function (objectToMerge, onComplete) {\n util_2.validateArgCount('Reference.update', 1, 2, arguments.length);\n validation_1.validateWritablePath('Reference.update', this.path);\n if (Array.isArray(objectToMerge)) {\n var newObjectToMerge = {};\n for (var i = 0; i < objectToMerge.length; ++i) {\n newObjectToMerge['' + i] = objectToMerge[i];\n }\n objectToMerge = newObjectToMerge;\n util_1.warn('Passing an Array to Firebase.update() is deprecated. ' +\n 'Use set() if you want to overwrite the existing data, or ' +\n 'an Object with integer keys if you really do want to ' +\n 'only update some of the children.');\n }\n validation_1.validateFirebaseMergeDataArg('Reference.update', 1, objectToMerge, this.path, false);\n util_2.validateCallback('Reference.update', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo.update(this.path, objectToMerge, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*} newVal\n * @param {string|number|null} newPriority\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.setWithPriority = function (newVal, newPriority, onComplete) {\n util_2.validateArgCount('Reference.setWithPriority', 2, 3, arguments.length);\n validation_1.validateWritablePath('Reference.setWithPriority', this.path);\n validation_1.validateFirebaseDataArg('Reference.setWithPriority', 1, newVal, this.path, false);\n validation_1.validatePriority('Reference.setWithPriority', 2, newPriority, false);\n util_2.validateCallback('Reference.setWithPriority', 3, onComplete, true);\n if (this.getKey() === '.length' || this.getKey() === '.keys')\n throw 'Reference.setWithPriority failed: ' +\n this.getKey() +\n ' is a read-only object.';\n var deferred = new util_3.Deferred();\n this.repo.setWithPriority(this.path, newVal, newPriority, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.remove = function (onComplete) {\n util_2.validateArgCount('Reference.remove', 0, 1, arguments.length);\n validation_1.validateWritablePath('Reference.remove', this.path);\n util_2.validateCallback('Reference.remove', 1, onComplete, true);\n return this.set(null, onComplete);\n };\n /**\n * @param {function(*):*} transactionUpdate\n * @param {(function(?Error, boolean, ?DataSnapshot))=} onComplete\n * @param {boolean=} applyLocally\n * @return {!Promise}\n */\n Reference.prototype.transaction = function (transactionUpdate, onComplete, applyLocally) {\n util_2.validateArgCount('Reference.transaction', 1, 3, arguments.length);\n validation_1.validateWritablePath('Reference.transaction', this.path);\n util_2.validateCallback('Reference.transaction', 1, transactionUpdate, false);\n util_2.validateCallback('Reference.transaction', 2, onComplete, true);\n // NOTE: applyLocally is an internal-only option for now. We need to decide if we want to keep it and how\n // to expose it.\n validation_1.validateBoolean('Reference.transaction', 3, applyLocally, true);\n if (this.getKey() === '.length' || this.getKey() === '.keys')\n throw 'Reference.transaction failed: ' +\n this.getKey() +\n ' is a read-only object.';\n if (applyLocally === undefined)\n applyLocally = true;\n var deferred = new util_3.Deferred();\n if (typeof onComplete === 'function') {\n deferred.promise.catch(function () { });\n }\n var promiseComplete = function (error, committed, snapshot) {\n if (error) {\n deferred.reject(error);\n }\n else {\n deferred.resolve(new TransactionResult_1.TransactionResult(committed, snapshot));\n }\n if (typeof onComplete === 'function') {\n onComplete(error, committed, snapshot);\n }\n };\n this.repo.startTransaction(this.path, transactionUpdate, promiseComplete, applyLocally);\n return deferred.promise;\n };\n /**\n * @param {string|number|null} priority\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.setPriority = function (priority, onComplete) {\n util_2.validateArgCount('Reference.setPriority', 1, 2, arguments.length);\n validation_1.validateWritablePath('Reference.setPriority', this.path);\n validation_1.validatePriority('Reference.setPriority', 1, priority, false);\n util_2.validateCallback('Reference.setPriority', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo.setWithPriority(this.path.child('.priority'), priority, null, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*=} value\n * @param {function(?Error)=} onComplete\n * @return {!Reference}\n */\n Reference.prototype.push = function (value, onComplete) {\n util_2.validateArgCount('Reference.push', 0, 2, arguments.length);\n validation_1.validateWritablePath('Reference.push', this.path);\n validation_1.validateFirebaseDataArg('Reference.push', 1, value, this.path, true);\n util_2.validateCallback('Reference.push', 2, onComplete, true);\n var now = this.repo.serverTime();\n var name = NextPushId_1.nextPushId(now);\n // push() returns a ThennableReference whose promise is fulfilled with a regular Reference.\n // We use child() to create handles to two different references. The first is turned into a\n // ThennableReference below by adding then() and catch() methods and is used as the\n // return value of push(). The second remains a regular Reference and is used as the fulfilled\n // value of the first ThennableReference.\n var thennablePushRef = this.child(name);\n var pushRef = this.child(name);\n var promise;\n if (value != null) {\n promise = thennablePushRef.set(value, onComplete).then(function () { return pushRef; });\n }\n else {\n promise = Promise.resolve(pushRef);\n }\n thennablePushRef.then = promise.then.bind(promise);\n thennablePushRef.catch = promise.then.bind(promise, undefined);\n if (typeof onComplete === 'function') {\n promise.catch(function () { });\n }\n return thennablePushRef;\n };\n /**\n * @return {!OnDisconnect}\n */\n Reference.prototype.onDisconnect = function () {\n validation_1.validateWritablePath('Reference.onDisconnect', this.path);\n return new onDisconnect_1.OnDisconnect(this.repo, this.path);\n };\n Object.defineProperty(Reference.prototype, \"database\", {\n get: function () {\n return this.databaseProp();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"key\", {\n get: function () {\n return this.getKey();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"parent\", {\n get: function () {\n return this.getParent();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"root\", {\n get: function () {\n return this.getRoot();\n },\n enumerable: true,\n configurable: true\n });\n return Reference;\n}(Query_1.Query));\nexports.Reference = Reference;\n/**\n * Define reference constructor in various modules\n *\n * We are doing this here to avoid several circular\n * dependency issues\n */\nQuery_1.Query.__referenceConstructor = Reference;\nSyncPoint_1.SyncPoint.__referenceConstructor = Reference;\n\n//# sourceMappingURL=Reference.js.map\n\n\n/***/ }),\n/* 23 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar validation_1 = __webpack_require__(8);\nvar Path_1 = __webpack_require__(3);\nvar PriorityIndex_1 = __webpack_require__(4);\n/**\n * Class representing a firebase data snapshot. It wraps a SnapshotNode and\n * surfaces the public methods (val, forEach, etc.) we want to expose.\n */\nvar DataSnapshot = /** @class */ (function () {\n /**\n * @param {!Node} node_ A SnapshotNode to wrap.\n * @param {!Reference} ref_ The ref of the location this snapshot came from.\n * @param {!Index} index_ The iteration order for this snapshot\n */\n function DataSnapshot(node_, ref_, index_) {\n this.node_ = node_;\n this.ref_ = ref_;\n this.index_ = index_;\n }\n /**\n * Retrieves the snapshot contents as JSON. Returns null if the snapshot is\n * empty.\n *\n * @return {*} JSON representation of the DataSnapshot contents, or null if empty.\n */\n DataSnapshot.prototype.val = function () {\n util_1.validateArgCount('DataSnapshot.val', 0, 0, arguments.length);\n return this.node_.val();\n };\n /**\n * Returns the snapshot contents as JSON, including priorities of node. Suitable for exporting\n * the entire node contents.\n * @return {*} JSON representation of the DataSnapshot contents, or null if empty.\n */\n DataSnapshot.prototype.exportVal = function () {\n util_1.validateArgCount('DataSnapshot.exportVal', 0, 0, arguments.length);\n return this.node_.val(true);\n };\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n DataSnapshot.prototype.toJSON = function () {\n // Optional spacer argument is unnecessary because we're depending on recursion rather than stringifying the content\n util_1.validateArgCount('DataSnapshot.toJSON', 0, 1, arguments.length);\n return this.exportVal();\n };\n /**\n * Returns whether the snapshot contains a non-null value.\n *\n * @return {boolean} Whether the snapshot contains a non-null value, or is empty.\n */\n DataSnapshot.prototype.exists = function () {\n util_1.validateArgCount('DataSnapshot.exists', 0, 0, arguments.length);\n return !this.node_.isEmpty();\n };\n /**\n * Returns a DataSnapshot of the specified child node's contents.\n *\n * @param {!string} childPathString Path to a child.\n * @return {!DataSnapshot} DataSnapshot for child node.\n */\n DataSnapshot.prototype.child = function (childPathString) {\n util_1.validateArgCount('DataSnapshot.child', 0, 1, arguments.length);\n // Ensure the childPath is a string (can be a number)\n childPathString = String(childPathString);\n validation_1.validatePathString('DataSnapshot.child', 1, childPathString, false);\n var childPath = new Path_1.Path(childPathString);\n var childRef = this.ref_.child(childPath);\n return new DataSnapshot(this.node_.getChild(childPath), childRef, PriorityIndex_1.PRIORITY_INDEX);\n };\n /**\n * Returns whether the snapshot contains a child at the specified path.\n *\n * @param {!string} childPathString Path to a child.\n * @return {boolean} Whether the child exists.\n */\n DataSnapshot.prototype.hasChild = function (childPathString) {\n util_1.validateArgCount('DataSnapshot.hasChild', 1, 1, arguments.length);\n validation_1.validatePathString('DataSnapshot.hasChild', 1, childPathString, false);\n var childPath = new Path_1.Path(childPathString);\n return !this.node_.getChild(childPath).isEmpty();\n };\n /**\n * Returns the priority of the object, or null if no priority was set.\n *\n * @return {string|number|null} The priority.\n */\n DataSnapshot.prototype.getPriority = function () {\n util_1.validateArgCount('DataSnapshot.getPriority', 0, 0, arguments.length);\n // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)\n return this.node_.getPriority().val();\n };\n /**\n * Iterates through child nodes and calls the specified action for each one.\n *\n * @param {function(!DataSnapshot)} action Callback function to be called\n * for each child.\n * @return {boolean} True if forEach was canceled by action returning true for\n * one of the child nodes.\n */\n DataSnapshot.prototype.forEach = function (action) {\n var _this = this;\n util_1.validateArgCount('DataSnapshot.forEach', 1, 1, arguments.length);\n util_1.validateCallback('DataSnapshot.forEach', 1, action, false);\n if (this.node_.isLeafNode())\n return false;\n var childrenNode = this.node_;\n // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...\n return !!childrenNode.forEachChild(this.index_, function (key, node) {\n return action(new DataSnapshot(node, _this.ref_.child(key), PriorityIndex_1.PRIORITY_INDEX));\n });\n };\n /**\n * Returns whether this DataSnapshot has children.\n * @return {boolean} True if the DataSnapshot contains 1 or more child nodes.\n */\n DataSnapshot.prototype.hasChildren = function () {\n util_1.validateArgCount('DataSnapshot.hasChildren', 0, 0, arguments.length);\n if (this.node_.isLeafNode())\n return false;\n else\n return !this.node_.isEmpty();\n };\n Object.defineProperty(DataSnapshot.prototype, \"key\", {\n get: function () {\n return this.ref_.getKey();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the number of children for this DataSnapshot.\n * @return {number} The number of children that this DataSnapshot contains.\n */\n DataSnapshot.prototype.numChildren = function () {\n util_1.validateArgCount('DataSnapshot.numChildren', 0, 0, arguments.length);\n return this.node_.numChildren();\n };\n /**\n * @return {Reference} The Firebase reference for the location this snapshot's data came from.\n */\n DataSnapshot.prototype.getRef = function () {\n util_1.validateArgCount('DataSnapshot.ref', 0, 0, arguments.length);\n return this.ref_;\n };\n Object.defineProperty(DataSnapshot.prototype, \"ref\", {\n get: function () {\n return this.getRef();\n },\n enumerable: true,\n configurable: true\n });\n return DataSnapshot;\n}());\nexports.DataSnapshot = DataSnapshot;\n\n//# sourceMappingURL=DataSnapshot.js.map\n\n\n/***/ }),\n/* 24 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar SortedMap_1 = __webpack_require__(18);\nvar Path_1 = __webpack_require__(3);\nvar util_1 = __webpack_require__(1);\nvar util_2 = __webpack_require__(0);\nvar emptyChildrenSingleton;\n/**\n * Singleton empty children collection.\n *\n * @const\n * @type {!SortedMap.>}\n */\nvar EmptyChildren = function () {\n if (!emptyChildrenSingleton) {\n emptyChildrenSingleton = new SortedMap_1.SortedMap(util_1.stringCompare);\n }\n return emptyChildrenSingleton;\n};\n/**\n * A tree with immutable elements.\n */\nvar ImmutableTree = /** @class */ (function () {\n /**\n * @template T\n * @param {?T} value\n * @param {SortedMap.>=} children\n */\n function ImmutableTree(value, children) {\n if (children === void 0) { children = EmptyChildren(); }\n this.value = value;\n this.children = children;\n }\n /**\n * @template T\n * @param {!Object.} obj\n * @return {!ImmutableTree.}\n */\n ImmutableTree.fromObject = function (obj) {\n var tree = ImmutableTree.Empty;\n util_2.forEach(obj, function (childPath, childSnap) {\n tree = tree.set(new Path_1.Path(childPath), childSnap);\n });\n return tree;\n };\n /**\n * True if the value is empty and there are no children\n * @return {boolean}\n */\n ImmutableTree.prototype.isEmpty = function () {\n return this.value === null && this.children.isEmpty();\n };\n /**\n * Given a path and predicate, return the first node and the path to that node\n * where the predicate returns true.\n *\n * TODO Do a perf test -- If we're creating a bunch of {path: value:} objects\n * on the way back out, it may be better to pass down a pathSoFar obj.\n *\n * @param {!Path} relativePath The remainder of the path\n * @param {function(T):boolean} predicate The predicate to satisfy to return a\n * node\n * @return {?{path:!Path, value:!T}}\n */\n ImmutableTree.prototype.findRootMostMatchingPathAndValue = function (relativePath, predicate) {\n if (this.value != null && predicate(this.value)) {\n return { path: Path_1.Path.Empty, value: this.value };\n }\n else {\n if (relativePath.isEmpty()) {\n return null;\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front);\n if (child !== null) {\n var childExistingPathAndValue = child.findRootMostMatchingPathAndValue(relativePath.popFront(), predicate);\n if (childExistingPathAndValue != null) {\n var fullPath = new Path_1.Path(front).child(childExistingPathAndValue.path);\n return { path: fullPath, value: childExistingPathAndValue.value };\n }\n else {\n return null;\n }\n }\n else {\n return null;\n }\n }\n }\n };\n /**\n * Find, if it exists, the shortest subpath of the given path that points a defined\n * value in the tree\n * @param {!Path} relativePath\n * @return {?{path: !Path, value: !T}}\n */\n ImmutableTree.prototype.findRootMostValueAndPath = function (relativePath) {\n return this.findRootMostMatchingPathAndValue(relativePath, function () { return true; });\n };\n /**\n * @param {!Path} relativePath\n * @return {!ImmutableTree.} The subtree at the given path\n */\n ImmutableTree.prototype.subtree = function (relativePath) {\n if (relativePath.isEmpty()) {\n return this;\n }\n else {\n var front = relativePath.getFront();\n var childTree = this.children.get(front);\n if (childTree !== null) {\n return childTree.subtree(relativePath.popFront());\n }\n else {\n return ImmutableTree.Empty;\n }\n }\n };\n /**\n * Sets a value at the specified path.\n *\n * @param {!Path} relativePath Path to set value at.\n * @param {?T} toSet Value to set.\n * @return {!ImmutableTree.} Resulting tree.\n */\n ImmutableTree.prototype.set = function (relativePath, toSet) {\n if (relativePath.isEmpty()) {\n return new ImmutableTree(toSet, this.children);\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front) || ImmutableTree.Empty;\n var newChild = child.set(relativePath.popFront(), toSet);\n var newChildren = this.children.insert(front, newChild);\n return new ImmutableTree(this.value, newChildren);\n }\n };\n /**\n * Removes the value at the specified path.\n *\n * @param {!Path} relativePath Path to value to remove.\n * @return {!ImmutableTree.} Resulting tree.\n */\n ImmutableTree.prototype.remove = function (relativePath) {\n if (relativePath.isEmpty()) {\n if (this.children.isEmpty()) {\n return ImmutableTree.Empty;\n }\n else {\n return new ImmutableTree(null, this.children);\n }\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front);\n if (child) {\n var newChild = child.remove(relativePath.popFront());\n var newChildren = void 0;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n }\n else {\n newChildren = this.children.insert(front, newChild);\n }\n if (this.value === null && newChildren.isEmpty()) {\n return ImmutableTree.Empty;\n }\n else {\n return new ImmutableTree(this.value, newChildren);\n }\n }\n else {\n return this;\n }\n }\n };\n /**\n * Gets a value from the tree.\n *\n * @param {!Path} relativePath Path to get value for.\n * @return {?T} Value at path, or null.\n */\n ImmutableTree.prototype.get = function (relativePath) {\n if (relativePath.isEmpty()) {\n return this.value;\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front);\n if (child) {\n return child.get(relativePath.popFront());\n }\n else {\n return null;\n }\n }\n };\n /**\n * Replace the subtree at the specified path with the given new tree.\n *\n * @param {!Path} relativePath Path to replace subtree for.\n * @param {!ImmutableTree} newTree New tree.\n * @return {!ImmutableTree} Resulting tree.\n */\n ImmutableTree.prototype.setTree = function (relativePath, newTree) {\n if (relativePath.isEmpty()) {\n return newTree;\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front) || ImmutableTree.Empty;\n var newChild = child.setTree(relativePath.popFront(), newTree);\n var newChildren = void 0;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n }\n else {\n newChildren = this.children.insert(front, newChild);\n }\n return new ImmutableTree(this.value, newChildren);\n }\n };\n /**\n * Performs a depth first fold on this tree. Transforms a tree into a single\n * value, given a function that operates on the path to a node, an optional\n * current value, and a map of child names to folded subtrees\n * @template V\n * @param {function(Path, ?T, Object.):V} fn\n * @return {V}\n */\n ImmutableTree.prototype.fold = function (fn) {\n return this.fold_(Path_1.Path.Empty, fn);\n };\n /**\n * Recursive helper for public-facing fold() method\n * @template V\n * @param {!Path} pathSoFar\n * @param {function(Path, ?T, Object.):V} fn\n * @return {V}\n * @private\n */\n ImmutableTree.prototype.fold_ = function (pathSoFar, fn) {\n var accum = {};\n this.children.inorderTraversal(function (childKey, childTree) {\n accum[childKey] = childTree.fold_(pathSoFar.child(childKey), fn);\n });\n return fn(pathSoFar, this.value, accum);\n };\n /**\n * Find the first matching value on the given path. Return the result of applying f to it.\n * @template V\n * @param {!Path} path\n * @param {!function(!Path, !T):?V} f\n * @return {?V}\n */\n ImmutableTree.prototype.findOnPath = function (path, f) {\n return this.findOnPath_(path, Path_1.Path.Empty, f);\n };\n ImmutableTree.prototype.findOnPath_ = function (pathToFollow, pathSoFar, f) {\n var result = this.value ? f(pathSoFar, this.value) : false;\n if (result) {\n return result;\n }\n else {\n if (pathToFollow.isEmpty()) {\n return null;\n }\n else {\n var front = pathToFollow.getFront();\n var nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.findOnPath_(pathToFollow.popFront(), pathSoFar.child(front), f);\n }\n else {\n return null;\n }\n }\n }\n };\n /**\n *\n * @param {!Path} path\n * @param {!function(!Path, !T)} f\n * @returns {!ImmutableTree.}\n */\n ImmutableTree.prototype.foreachOnPath = function (path, f) {\n return this.foreachOnPath_(path, Path_1.Path.Empty, f);\n };\n ImmutableTree.prototype.foreachOnPath_ = function (pathToFollow, currentRelativePath, f) {\n if (pathToFollow.isEmpty()) {\n return this;\n }\n else {\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n var front = pathToFollow.getFront();\n var nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.foreachOnPath_(pathToFollow.popFront(), currentRelativePath.child(front), f);\n }\n else {\n return ImmutableTree.Empty;\n }\n }\n };\n /**\n * Calls the given function for each node in the tree that has a value.\n *\n * @param {function(!Path, !T)} f A function to be called with\n * the path from the root of the tree to a node, and the value at that node.\n * Called in depth-first order.\n */\n ImmutableTree.prototype.foreach = function (f) {\n this.foreach_(Path_1.Path.Empty, f);\n };\n ImmutableTree.prototype.foreach_ = function (currentRelativePath, f) {\n this.children.inorderTraversal(function (childName, childTree) {\n childTree.foreach_(currentRelativePath.child(childName), f);\n });\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n };\n /**\n *\n * @param {function(string, !T)} f\n */\n ImmutableTree.prototype.foreachChild = function (f) {\n this.children.inorderTraversal(function (childName, childTree) {\n if (childTree.value) {\n f(childName, childTree.value);\n }\n });\n };\n ImmutableTree.Empty = new ImmutableTree(null);\n return ImmutableTree;\n}());\nexports.ImmutableTree = ImmutableTree;\n\n//# sourceMappingURL=ImmutableTree.js.map\n\n\n/***/ }),\n/* 25 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Change_1 = __webpack_require__(10);\nvar ChildrenNode_1 = __webpack_require__(5);\nvar PriorityIndex_1 = __webpack_require__(4);\n/**\n * Doesn't really filter nodes but applies an index to the node and keeps track of any changes\n *\n * @constructor\n * @implements {NodeFilter}\n * @param {!Index} index\n */\nvar IndexedFilter = /** @class */ (function () {\n function IndexedFilter(index_) {\n this.index_ = index_;\n }\n IndexedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n util_1.assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');\n var oldChild = snap.getImmediateChild(key);\n // Check if anything actually changed.\n if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {\n // There's an edge case where a child can enter or leave the view because affectedPath was set to null.\n // In this case, affectedPath will appear null in both the old and new snapshots. So we need\n // to avoid treating these cases as \"nothing changed.\"\n if (oldChild.isEmpty() == newChild.isEmpty()) {\n // Nothing changed.\n // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.\n //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');\n return snap;\n }\n }\n if (optChangeAccumulator != null) {\n if (newChild.isEmpty()) {\n if (snap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(key, oldChild));\n }\n else {\n util_1.assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');\n }\n }\n else if (oldChild.isEmpty()) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childAddedChange(key, newChild));\n }\n else {\n optChangeAccumulator.trackChildChange(Change_1.Change.childChangedChange(key, newChild, oldChild));\n }\n }\n if (snap.isLeafNode() && newChild.isEmpty()) {\n return snap;\n }\n else {\n // Make sure the node is indexed\n return snap.updateImmediateChild(key, newChild).withIndex(this.index_);\n }\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n if (optChangeAccumulator != null) {\n if (!oldSnap.isLeafNode()) {\n oldSnap.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n if (!newSnap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(key, childNode));\n }\n });\n }\n if (!newSnap.isLeafNode()) {\n newSnap.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n if (oldSnap.hasChild(key)) {\n var oldChild = oldSnap.getImmediateChild(key);\n if (!oldChild.equals(childNode)) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childChangedChange(key, childNode, oldChild));\n }\n }\n else {\n optChangeAccumulator.trackChildChange(Change_1.Change.childAddedChange(key, childNode));\n }\n });\n }\n }\n return newSnap.withIndex(this.index_);\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n if (oldSnap.isEmpty()) {\n return ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n else {\n return oldSnap.updatePriority(newPriority);\n }\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.filtersNodes = function () {\n return false;\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.getIndexedFilter = function () {\n return this;\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n return IndexedFilter;\n}());\nexports.IndexedFilter = IndexedFilter;\n\n//# sourceMappingURL=IndexedFilter.js.map\n\n\n/***/ }),\n/* 26 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar StatsCollection_1 = __webpack_require__(100);\nvar StatsManager = /** @class */ (function () {\n function StatsManager() {\n }\n StatsManager.getCollection = function (repoInfo) {\n var hashString = repoInfo.toString();\n if (!this.collections_[hashString]) {\n this.collections_[hashString] = new StatsCollection_1.StatsCollection();\n }\n return this.collections_[hashString];\n };\n StatsManager.getOrCreateReporter = function (repoInfo, creatorFunction) {\n var hashString = repoInfo.toString();\n if (!this.reporters_[hashString]) {\n this.reporters_[hashString] = creatorFunction();\n }\n return this.reporters_[hashString];\n };\n StatsManager.collections_ = {};\n StatsManager.reporters_ = {};\n return StatsManager;\n}());\nexports.StatsManager = StatsManager;\n\n//# sourceMappingURL=StatsManager.js.map\n\n\n/***/ }),\n/* 27 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Repo_1 = __webpack_require__(19);\nvar util_2 = __webpack_require__(1);\nvar parser_1 = __webpack_require__(34);\nvar validation_1 = __webpack_require__(8);\n__webpack_require__(110);\n/** @const {string} */\nvar DATABASE_URL_OPTION = 'databaseURL';\nvar _staticInstance;\n/**\n * Creates and caches Repo instances.\n */\nvar RepoManager = /** @class */ (function () {\n function RepoManager() {\n /**\n * @private {!Object.>}\n */\n this.repos_ = {};\n /**\n * If true, new Repos will be created to use ReadonlyRestClient (for testing purposes).\n * @private {boolean}\n */\n this.useRestClient_ = false;\n }\n RepoManager.getInstance = function () {\n if (!_staticInstance) {\n _staticInstance = new RepoManager();\n }\n return _staticInstance;\n };\n // TODO(koss): Remove these functions unless used in tests?\n RepoManager.prototype.interrupt = function () {\n for (var appName in this.repos_) {\n for (var dbUrl in this.repos_[appName]) {\n this.repos_[appName][dbUrl].interrupt();\n }\n }\n };\n RepoManager.prototype.resume = function () {\n for (var appName in this.repos_) {\n for (var dbUrl in this.repos_[appName]) {\n this.repos_[appName][dbUrl].resume();\n }\n }\n };\n /**\n * This function should only ever be called to CREATE a new database instance.\n *\n * @param {!FirebaseApp} app\n * @return {!Database}\n */\n RepoManager.prototype.databaseFromApp = function (app, url) {\n var dbUrl = url || app.options[DATABASE_URL_OPTION];\n if (dbUrl === undefined) {\n util_2.fatal(\"Can't determine Firebase Database URL. Be sure to include \" +\n DATABASE_URL_OPTION +\n ' option when calling firebase.initializeApp().');\n }\n var parsedUrl = parser_1.parseRepoInfo(dbUrl);\n var repoInfo = parsedUrl.repoInfo;\n validation_1.validateUrl('Invalid Firebase Database URL', 1, parsedUrl);\n if (!parsedUrl.path.isEmpty()) {\n util_2.fatal('Database URL must point to the root of a Firebase Database ' +\n '(not including a child path).');\n }\n var repo = this.createRepo(repoInfo, app);\n return repo.database;\n };\n /**\n * Remove the repo and make sure it is disconnected.\n *\n * @param {!Repo} repo\n */\n RepoManager.prototype.deleteRepo = function (repo) {\n var appRepos = util_1.safeGet(this.repos_, repo.app.name);\n // This should never happen...\n if (!appRepos || util_1.safeGet(appRepos, repo.repoInfo_.toURLString()) !== repo) {\n util_2.fatal(\"Database \" + repo.app.name + \"(\" + repo.repoInfo_ + \") has already been deleted.\");\n }\n repo.interrupt();\n delete appRepos[repo.repoInfo_.toURLString()];\n };\n /**\n * Ensures a repo doesn't already exist and then creates one using the\n * provided app.\n *\n * @param {!RepoInfo} repoInfo The metadata about the Repo\n * @param {!FirebaseApp} app\n * @return {!Repo} The Repo object for the specified server / repoName.\n */\n RepoManager.prototype.createRepo = function (repoInfo, app) {\n var appRepos = util_1.safeGet(this.repos_, app.name);\n if (!appRepos) {\n appRepos = {};\n this.repos_[app.name] = appRepos;\n }\n var repo = util_1.safeGet(appRepos, repoInfo.toURLString());\n if (repo) {\n util_2.fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');\n }\n repo = new Repo_1.Repo(repoInfo, this.useRestClient_, app);\n appRepos[repoInfo.toURLString()] = repo;\n return repo;\n };\n /**\n * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.\n * @param {boolean} forceRestClient\n */\n RepoManager.prototype.forceRestClient = function (forceRestClient) {\n this.useRestClient_ = forceRestClient;\n };\n return RepoManager;\n}());\nexports.RepoManager = RepoManager;\n\n//# sourceMappingURL=RepoManager.js.map\n\n\n/***/ }),\n/* 28 */,\n/* 29 */,\n/* 30 */,\n/* 31 */,\n/* 32 */,\n/* 33 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = __webpack_require__(2);\nvar util_1 = __webpack_require__(1);\nvar parser_1 = __webpack_require__(34);\nvar Path_1 = __webpack_require__(3);\nvar Reference_1 = __webpack_require__(22);\nvar Repo_1 = __webpack_require__(19);\nvar RepoManager_1 = __webpack_require__(27);\nvar util_2 = __webpack_require__(0);\nvar validation_1 = __webpack_require__(8);\n/**\n * Class representing a firebase database.\n * @implements {FirebaseService}\n */\nvar Database = /** @class */ (function () {\n /**\n * The constructor should not be called by users of our public API.\n * @param {!Repo} repo_\n */\n function Database(repo_) {\n this.repo_ = repo_;\n if (!(repo_ instanceof Repo_1.Repo)) {\n util_1.fatal(\"Don't call new Database() directly - please use firebase.database().\");\n }\n /** @type {Reference} */\n this.root_ = new Reference_1.Reference(repo_, Path_1.Path.Empty);\n this.INTERNAL = new DatabaseInternals(this);\n }\n Object.defineProperty(Database.prototype, \"app\", {\n get: function () {\n return this.repo_.app;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns a reference to the root or the path specified in opt_pathString.\n * @param {string=} pathString\n * @return {!Reference} Firebase reference.\n */\n Database.prototype.ref = function (pathString) {\n this.checkDeleted_('ref');\n util_2.validateArgCount('database.ref', 0, 1, arguments.length);\n return pathString !== undefined ? this.root_.child(pathString) : this.root_;\n };\n /**\n * Returns a reference to the root or the path specified in url.\n * We throw a exception if the url is not in the same domain as the\n * current repo.\n * @param {string} url\n * @return {!Reference} Firebase reference.\n */\n Database.prototype.refFromURL = function (url) {\n /** @const {string} */\n var apiName = 'database.refFromURL';\n this.checkDeleted_(apiName);\n util_2.validateArgCount(apiName, 1, 1, arguments.length);\n var parsedURL = parser_1.parseRepoInfo(url);\n validation_1.validateUrl(apiName, 1, parsedURL);\n var repoInfo = parsedURL.repoInfo;\n if (repoInfo.host !== this.repo_.repoInfo_.host) {\n util_1.fatal(apiName +\n ': Host name does not match the current database: ' +\n '(found ' +\n repoInfo.host +\n ' but expected ' +\n this.repo_.repoInfo_.host +\n ')');\n }\n return this.ref(parsedURL.path.toString());\n };\n /**\n * @param {string} apiName\n */\n Database.prototype.checkDeleted_ = function (apiName) {\n if (this.repo_ === null) {\n util_1.fatal('Cannot call ' + apiName + ' on a deleted database.');\n }\n };\n // Make individual repo go offline.\n Database.prototype.goOffline = function () {\n util_2.validateArgCount('database.goOffline', 0, 0, arguments.length);\n this.checkDeleted_('goOffline');\n this.repo_.interrupt();\n };\n Database.prototype.goOnline = function () {\n util_2.validateArgCount('database.goOnline', 0, 0, arguments.length);\n this.checkDeleted_('goOnline');\n this.repo_.resume();\n };\n Database.ServerValue = {\n TIMESTAMP: {\n '.sv': 'timestamp'\n }\n };\n return Database;\n}());\nexports.Database = Database;\nvar DatabaseInternals = /** @class */ (function () {\n /** @param {!Database} database */\n function DatabaseInternals(database) {\n this.database = database;\n }\n /** @return {Promise} */\n DatabaseInternals.prototype.delete = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n this.database.checkDeleted_('delete');\n RepoManager_1.RepoManager.getInstance().deleteRepo(this.database.repo_);\n this.database.repo_ = null;\n this.database.root_ = null;\n this.database.INTERNAL = null;\n this.database = null;\n return [2 /*return*/];\n });\n });\n };\n return DatabaseInternals;\n}());\nexports.DatabaseInternals = DatabaseInternals;\n\n//# sourceMappingURL=Database.js.map\n\n\n/***/ }),\n/* 34 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = __webpack_require__(3);\nvar RepoInfo_1 = __webpack_require__(35);\nvar util_1 = __webpack_require__(1);\n/**\n * @param {!string} pathString\n * @return {string}\n */\nfunction decodePath(pathString) {\n var pathStringDecoded = '';\n var pieces = pathString.split('/');\n for (var i = 0; i < pieces.length; i++) {\n if (pieces[i].length > 0) {\n var piece = pieces[i];\n try {\n piece = decodeURIComponent(piece.replace(/\\+/g, ' '));\n }\n catch (e) { }\n pathStringDecoded += '/' + piece;\n }\n }\n return pathStringDecoded;\n}\n/**\n * @param {!string} queryString\n * @return {!{[key:string]:string}} key value hash\n */\nfunction decodeQuery(queryString) {\n var results = {};\n if (queryString.startsWith('?')) {\n queryString = queryString.substring(1);\n }\n for (var _i = 0, _a = queryString.split('&'); _i < _a.length; _i++) {\n var segment = _a[_i];\n if (segment.length === 0) {\n continue;\n }\n var kv = segment.split('=');\n if (kv.length === 2) {\n results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);\n }\n else {\n util_1.warn(\"Invalid query segment '\" + segment + \"' in query '\" + queryString + \"'\");\n }\n }\n return results;\n}\n/**\n *\n * @param {!string} dataURL\n * @return {{repoInfo: !RepoInfo, path: !Path}}\n */\nexports.parseRepoInfo = function (dataURL) {\n var parsedUrl = exports.parseURL(dataURL), namespace = parsedUrl.subdomain;\n if (parsedUrl.domain === 'firebase') {\n util_1.fatal(parsedUrl.host +\n ' is no longer supported. ' +\n 'Please use .firebaseio.com instead');\n }\n // Catch common error of uninitialized namespace value.\n if ((!namespace || namespace == 'undefined') &&\n parsedUrl.domain !== 'localhost') {\n util_1.fatal('Cannot parse Firebase url. Please use https://.firebaseio.com');\n }\n if (!parsedUrl.secure) {\n util_1.warnIfPageIsSecure();\n }\n var webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';\n return {\n repoInfo: new RepoInfo_1.RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly),\n path: new Path_1.Path(parsedUrl.pathString)\n };\n};\n/**\n *\n * @param {!string} dataURL\n * @return {{host: string, port: number, domain: string, subdomain: string, secure: boolean, scheme: string, pathString: string}}\n */\nexports.parseURL = function (dataURL) {\n // Default to empty strings in the event of a malformed string.\n var host = '', domain = '', subdomain = '', pathString = '';\n // Always default to SSL, unless otherwise specified.\n var secure = true, scheme = 'https', port = 443;\n // Don't do any validation here. The caller is responsible for validating the result of parsing.\n if (typeof dataURL === 'string') {\n // Parse scheme.\n var colonInd = dataURL.indexOf('//');\n if (colonInd >= 0) {\n scheme = dataURL.substring(0, colonInd - 1);\n dataURL = dataURL.substring(colonInd + 2);\n }\n // Parse host, path, and query string.\n var slashInd = dataURL.indexOf('/');\n if (slashInd === -1) {\n slashInd = dataURL.length;\n }\n var questionMarkInd = dataURL.indexOf('?');\n if (questionMarkInd === -1) {\n questionMarkInd = dataURL.length;\n }\n host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));\n if (slashInd < questionMarkInd) {\n // For pathString, questionMarkInd will always come after slashInd\n pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));\n }\n var queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));\n // If we have a port, use scheme for determining if it's secure.\n colonInd = host.indexOf(':');\n if (colonInd >= 0) {\n secure = scheme === 'https' || scheme === 'wss';\n port = parseInt(host.substring(colonInd + 1), 10);\n }\n else {\n colonInd = dataURL.length;\n }\n var parts = host.split('.');\n if (parts.length === 3) {\n // Normalize namespaces to lowercase to share storage / connection.\n domain = parts[1];\n subdomain = parts[0].toLowerCase();\n }\n else if (parts.length === 2) {\n domain = parts[0];\n }\n else if (parts[0].slice(0, colonInd).toLowerCase() === 'localhost') {\n domain = 'localhost';\n }\n // Support `ns` query param if subdomain not already set\n if (subdomain === '' && 'ns' in queryParams) {\n subdomain = queryParams['ns'];\n }\n }\n return {\n host: host,\n port: port,\n domain: domain,\n subdomain: subdomain,\n secure: secure,\n scheme: scheme,\n pathString: pathString\n };\n};\n\n//# sourceMappingURL=parser.js.map\n\n\n/***/ }),\n/* 35 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\nvar storage_1 = __webpack_require__(14);\nvar Constants_1 = __webpack_require__(15);\n/**\n * A class that holds metadata about a Repo object\n *\n * @constructor\n */\nvar RepoInfo = /** @class */ (function () {\n /**\n * @param {string} host Hostname portion of the url for the repo\n * @param {boolean} secure Whether or not this repo is accessed over ssl\n * @param {string} namespace The namespace represented by the repo\n * @param {boolean} webSocketOnly Whether to prefer websockets over all other transports (used by Nest).\n * @param {string=} persistenceKey Override the default session persistence storage key\n */\n function RepoInfo(host, secure, namespace, webSocketOnly, persistenceKey) {\n if (persistenceKey === void 0) { persistenceKey = ''; }\n this.secure = secure;\n this.namespace = namespace;\n this.webSocketOnly = webSocketOnly;\n this.persistenceKey = persistenceKey;\n this.host = host.toLowerCase();\n this.domain = this.host.substr(this.host.indexOf('.') + 1);\n this.internalHost = storage_1.PersistentStorage.get('host:' + host) || this.host;\n }\n RepoInfo.prototype.needsQueryParam = function () {\n return this.host !== this.internalHost || this.isCustomHost();\n };\n RepoInfo.prototype.isCacheableHost = function () {\n return this.internalHost.substr(0, 2) === 's-';\n };\n RepoInfo.prototype.isDemoHost = function () {\n return this.domain === 'firebaseio-demo.com';\n };\n RepoInfo.prototype.isCustomHost = function () {\n return (this.domain !== 'firebaseio.com' && this.domain !== 'firebaseio-demo.com');\n };\n RepoInfo.prototype.updateHost = function (newHost) {\n if (newHost !== this.internalHost) {\n this.internalHost = newHost;\n if (this.isCacheableHost()) {\n storage_1.PersistentStorage.set('host:' + this.host, this.internalHost);\n }\n }\n };\n /**\n * Returns the websocket URL for this repo\n * @param {string} type of connection\n * @param {Object} params list\n * @return {string} The URL for this repo\n */\n RepoInfo.prototype.connectionURL = function (type, params) {\n util_1.assert(typeof type === 'string', 'typeof type must == string');\n util_1.assert(typeof params === 'object', 'typeof params must == object');\n var connURL;\n if (type === Constants_1.WEBSOCKET) {\n connURL =\n (this.secure ? 'wss://' : 'ws://') + this.internalHost + '/.ws?';\n }\n else if (type === Constants_1.LONG_POLLING) {\n connURL =\n (this.secure ? 'https://' : 'http://') + this.internalHost + '/.lp?';\n }\n else {\n throw new Error('Unknown connection type: ' + type);\n }\n if (this.needsQueryParam()) {\n params['ns'] = this.namespace;\n }\n var pairs = [];\n util_2.forEach(params, function (key, value) {\n pairs.push(key + '=' + value);\n });\n return connURL + pairs.join('&');\n };\n /** @return {string} */\n RepoInfo.prototype.toString = function () {\n var str = this.toURLString();\n if (this.persistenceKey) {\n str += '<' + this.persistenceKey + '>';\n }\n return str;\n };\n /** @return {string} */\n RepoInfo.prototype.toURLString = function () {\n return (this.secure ? 'https://' : 'http://') + this.host;\n };\n return RepoInfo;\n}());\nexports.RepoInfo = RepoInfo;\n\n//# sourceMappingURL=RepoInfo.js.map\n\n\n/***/ }),\n/* 36 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar validation_1 = __webpack_require__(8);\nvar util_2 = __webpack_require__(1);\nvar util_3 = __webpack_require__(0);\n/**\n * @constructor\n */\nvar OnDisconnect = /** @class */ (function () {\n /**\n * @param {!Repo} repo_\n * @param {!Path} path_\n */\n function OnDisconnect(repo_, path_) {\n this.repo_ = repo_;\n this.path_ = path_;\n }\n /**\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.cancel = function (onComplete) {\n util_1.validateArgCount('OnDisconnect.cancel', 0, 1, arguments.length);\n util_1.validateCallback('OnDisconnect.cancel', 1, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectCancel(this.path_, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.remove = function (onComplete) {\n util_1.validateArgCount('OnDisconnect.remove', 0, 1, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.remove', this.path_);\n util_1.validateCallback('OnDisconnect.remove', 1, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectSet(this.path_, null, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*} value\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.set = function (value, onComplete) {\n util_1.validateArgCount('OnDisconnect.set', 1, 2, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.set', this.path_);\n validation_1.validateFirebaseDataArg('OnDisconnect.set', 1, value, this.path_, false);\n util_1.validateCallback('OnDisconnect.set', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectSet(this.path_, value, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*} value\n * @param {number|string|null} priority\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.setWithPriority = function (value, priority, onComplete) {\n util_1.validateArgCount('OnDisconnect.setWithPriority', 2, 3, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.setWithPriority', this.path_);\n validation_1.validateFirebaseDataArg('OnDisconnect.setWithPriority', 1, value, this.path_, false);\n validation_1.validatePriority('OnDisconnect.setWithPriority', 2, priority, false);\n util_1.validateCallback('OnDisconnect.setWithPriority', 3, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectSetWithPriority(this.path_, value, priority, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {!Object} objectToMerge\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.update = function (objectToMerge, onComplete) {\n util_1.validateArgCount('OnDisconnect.update', 1, 2, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.update', this.path_);\n if (Array.isArray(objectToMerge)) {\n var newObjectToMerge = {};\n for (var i = 0; i < objectToMerge.length; ++i) {\n newObjectToMerge['' + i] = objectToMerge[i];\n }\n objectToMerge = newObjectToMerge;\n util_2.warn('Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the ' +\n 'existing data, or an Object with integer keys if you really do want to only update some of the children.');\n }\n validation_1.validateFirebaseMergeDataArg('OnDisconnect.update', 1, objectToMerge, this.path_, false);\n util_1.validateCallback('OnDisconnect.update', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectUpdate(this.path_, objectToMerge, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n return OnDisconnect;\n}());\nexports.OnDisconnect = OnDisconnect;\n\n//# sourceMappingURL=onDisconnect.js.map\n\n\n/***/ }),\n/* 37 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar KeyIndex_1 = __webpack_require__(12);\nvar PriorityIndex_1 = __webpack_require__(4);\nvar ValueIndex_1 = __webpack_require__(39);\nvar PathIndex_1 = __webpack_require__(43);\nvar util_2 = __webpack_require__(1);\nvar Path_1 = __webpack_require__(3);\nvar validation_1 = __webpack_require__(8);\nvar util_3 = __webpack_require__(0);\nvar EventRegistration_1 = __webpack_require__(85);\nvar util_4 = __webpack_require__(0);\nvar __referenceConstructor;\n/**\n * A Query represents a filter to be applied to a firebase location. This object purely represents the\n * query expression (and exposes our public API to build the query). The actual query logic is in ViewBase.js.\n *\n * Since every Firebase reference is a query, Firebase inherits from this object.\n */\nvar Query = /** @class */ (function () {\n function Query(repo, path, queryParams_, orderByCalled_) {\n this.repo = repo;\n this.path = path;\n this.queryParams_ = queryParams_;\n this.orderByCalled_ = orderByCalled_;\n }\n Object.defineProperty(Query, \"__referenceConstructor\", {\n get: function () {\n util_1.assert(__referenceConstructor, 'Reference.ts has not been loaded');\n return __referenceConstructor;\n },\n set: function (val) {\n __referenceConstructor = val;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Validates start/end values for queries.\n * @param {!QueryParams} params\n * @private\n */\n Query.validateQueryEndpoints_ = function (params) {\n var startNode = null;\n var endNode = null;\n if (params.hasStart()) {\n startNode = params.getIndexStartValue();\n }\n if (params.hasEnd()) {\n endNode = params.getIndexEndValue();\n }\n if (params.getIndex() === KeyIndex_1.KEY_INDEX) {\n var tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +\n 'startAt(), endAt(), or equalTo().';\n var wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), endAt(),' +\n 'or equalTo() must be a string.';\n if (params.hasStart()) {\n var startName = params.getIndexStartName();\n if (startName != util_2.MIN_NAME) {\n throw new Error(tooManyArgsError);\n }\n else if (typeof startNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n if (params.hasEnd()) {\n var endName = params.getIndexEndName();\n if (endName != util_2.MAX_NAME) {\n throw new Error(tooManyArgsError);\n }\n else if (typeof endNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n }\n else if (params.getIndex() === PriorityIndex_1.PRIORITY_INDEX) {\n if ((startNode != null && !validation_1.isValidPriority(startNode)) ||\n (endNode != null && !validation_1.isValidPriority(endNode))) {\n throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +\n 'endAt(), or equalTo() must be a valid priority value (null, a number, or a string).');\n }\n }\n else {\n util_1.assert(params.getIndex() instanceof PathIndex_1.PathIndex ||\n params.getIndex() === ValueIndex_1.VALUE_INDEX, 'unknown index type.');\n if ((startNode != null && typeof startNode === 'object') ||\n (endNode != null && typeof endNode === 'object')) {\n throw new Error('Query: First argument passed to startAt(), endAt(), or equalTo() cannot be ' +\n 'an object.');\n }\n }\n };\n /**\n * Validates that limit* has been called with the correct combination of parameters\n * @param {!QueryParams} params\n * @private\n */\n Query.validateLimit_ = function (params) {\n if (params.hasStart() &&\n params.hasEnd() &&\n params.hasLimit() &&\n !params.hasAnchoredLimit()) {\n throw new Error(\"Query: Can't combine startAt(), endAt(), and limit(). Use limitToFirst() or limitToLast() instead.\");\n }\n };\n /**\n * Validates that no other order by call has been made\n * @param {!string} fnName\n * @private\n */\n Query.prototype.validateNoPreviousOrderByCall_ = function (fnName) {\n if (this.orderByCalled_ === true) {\n throw new Error(fnName + \": You can't combine multiple orderBy calls.\");\n }\n };\n /**\n * @return {!QueryParams}\n */\n Query.prototype.getQueryParams = function () {\n return this.queryParams_;\n };\n /**\n * @return {!Reference}\n */\n Query.prototype.getRef = function () {\n util_3.validateArgCount('Query.ref', 0, 0, arguments.length);\n // This is a slight hack. We cannot goog.require('fb.api.Firebase'), since Firebase requires fb.api.Query.\n // However, we will always export 'Firebase' to the global namespace, so it's guaranteed to exist by the time this\n // method gets called.\n return new Query.__referenceConstructor(this.repo, this.path);\n };\n /**\n * @param {!string} eventType\n * @param {!function(DataSnapshot, string=)} callback\n * @param {(function(Error)|Object)=} cancelCallbackOrContext\n * @param {Object=} context\n * @return {!function(DataSnapshot, string=)}\n */\n Query.prototype.on = function (eventType, callback, cancelCallbackOrContext, context) {\n util_3.validateArgCount('Query.on', 2, 4, arguments.length);\n validation_1.validateEventType('Query.on', 1, eventType, false);\n util_3.validateCallback('Query.on', 2, callback, false);\n var ret = Query.getCancelAndContextArgs_('Query.on', cancelCallbackOrContext, context);\n if (eventType === 'value') {\n this.onValueEvent(callback, ret.cancel, ret.context);\n }\n else {\n var callbacks = {};\n callbacks[eventType] = callback;\n this.onChildEvent(callbacks, ret.cancel, ret.context);\n }\n return callback;\n };\n /**\n * @param {!function(!DataSnapshot)} callback\n * @param {?function(Error)} cancelCallback\n * @param {?Object} context\n * @protected\n */\n Query.prototype.onValueEvent = function (callback, cancelCallback, context) {\n var container = new EventRegistration_1.ValueEventRegistration(callback, cancelCallback || null, context || null);\n this.repo.addEventCallbackForQuery(this, container);\n };\n /**\n * @param {!Object.} callbacks\n * @param {?function(Error)} cancelCallback\n * @param {?Object} context\n * @protected\n */\n Query.prototype.onChildEvent = function (callbacks, cancelCallback, context) {\n var container = new EventRegistration_1.ChildEventRegistration(callbacks, cancelCallback, context);\n this.repo.addEventCallbackForQuery(this, container);\n };\n /**\n * @param {string=} eventType\n * @param {(function(!DataSnapshot, ?string=))=} callback\n * @param {Object=} context\n */\n Query.prototype.off = function (eventType, callback, context) {\n util_3.validateArgCount('Query.off', 0, 3, arguments.length);\n validation_1.validateEventType('Query.off', 1, eventType, true);\n util_3.validateCallback('Query.off', 2, callback, true);\n util_3.validateContextObject('Query.off', 3, context, true);\n var container = null;\n var callbacks = null;\n if (eventType === 'value') {\n var valueCallback = callback || null;\n container = new EventRegistration_1.ValueEventRegistration(valueCallback, null, context || null);\n }\n else if (eventType) {\n if (callback) {\n callbacks = {};\n callbacks[eventType] = callback;\n }\n container = new EventRegistration_1.ChildEventRegistration(callbacks, null, context || null);\n }\n this.repo.removeEventCallbackForQuery(this, container);\n };\n /**\n * Attaches a listener, waits for the first event, and then removes the listener\n * @param {!string} eventType\n * @param {!function(!DataSnapshot, string=)} userCallback\n * @param cancelOrContext\n * @param context\n * @return {!firebase.Promise}\n */\n Query.prototype.once = function (eventType, userCallback, cancelOrContext, context) {\n var _this = this;\n util_3.validateArgCount('Query.once', 1, 4, arguments.length);\n validation_1.validateEventType('Query.once', 1, eventType, false);\n util_3.validateCallback('Query.once', 2, userCallback, true);\n var ret = Query.getCancelAndContextArgs_('Query.once', cancelOrContext, context);\n // TODO: Implement this more efficiently (in particular, use 'get' wire protocol for 'value' event)\n // TODO: consider actually wiring the callbacks into the promise. We cannot do this without a breaking change\n // because the API currently expects callbacks will be called synchronously if the data is cached, but this is\n // against the Promise specification.\n var firstCall = true;\n var deferred = new util_4.Deferred();\n // A dummy error handler in case a user wasn't expecting promises\n deferred.promise.catch(function () { });\n var onceCallback = function (snapshot) {\n // NOTE: Even though we unsubscribe, we may get called multiple times if a single action (e.g. set() with JSON)\n // triggers multiple events (e.g. child_added or child_changed).\n if (firstCall) {\n firstCall = false;\n _this.off(eventType, onceCallback);\n if (userCallback) {\n userCallback.bind(ret.context)(snapshot);\n }\n deferred.resolve(snapshot);\n }\n };\n this.on(eventType, onceCallback, \n /*cancel=*/ function (err) {\n _this.off(eventType, onceCallback);\n if (ret.cancel)\n ret.cancel.bind(ret.context)(err);\n deferred.reject(err);\n });\n return deferred.promise;\n };\n /**\n * Set a limit and anchor it to the start of the window.\n * @param {!number} limit\n * @return {!Query}\n */\n Query.prototype.limitToFirst = function (limit) {\n util_3.validateArgCount('Query.limitToFirst', 1, 1, arguments.length);\n if (typeof limit !== 'number' ||\n Math.floor(limit) !== limit ||\n limit <= 0) {\n throw new Error('Query.limitToFirst: First argument must be a positive integer.');\n }\n if (this.queryParams_.hasLimit()) {\n throw new Error('Query.limitToFirst: Limit was already set (by another call to limit, ' +\n 'limitToFirst, or limitToLast).');\n }\n return new Query(this.repo, this.path, this.queryParams_.limitToFirst(limit), this.orderByCalled_);\n };\n /**\n * Set a limit and anchor it to the end of the window.\n * @param {!number} limit\n * @return {!Query}\n */\n Query.prototype.limitToLast = function (limit) {\n util_3.validateArgCount('Query.limitToLast', 1, 1, arguments.length);\n if (typeof limit !== 'number' ||\n Math.floor(limit) !== limit ||\n limit <= 0) {\n throw new Error('Query.limitToLast: First argument must be a positive integer.');\n }\n if (this.queryParams_.hasLimit()) {\n throw new Error('Query.limitToLast: Limit was already set (by another call to limit, ' +\n 'limitToFirst, or limitToLast).');\n }\n return new Query(this.repo, this.path, this.queryParams_.limitToLast(limit), this.orderByCalled_);\n };\n /**\n * Given a child path, return a new query ordered by the specified grandchild path.\n * @param {!string} path\n * @return {!Query}\n */\n Query.prototype.orderByChild = function (path) {\n util_3.validateArgCount('Query.orderByChild', 1, 1, arguments.length);\n if (path === '$key') {\n throw new Error('Query.orderByChild: \"$key\" is invalid. Use Query.orderByKey() instead.');\n }\n else if (path === '$priority') {\n throw new Error('Query.orderByChild: \"$priority\" is invalid. Use Query.orderByPriority() instead.');\n }\n else if (path === '$value') {\n throw new Error('Query.orderByChild: \"$value\" is invalid. Use Query.orderByValue() instead.');\n }\n validation_1.validatePathString('Query.orderByChild', 1, path, false);\n this.validateNoPreviousOrderByCall_('Query.orderByChild');\n var parsedPath = new Path_1.Path(path);\n if (parsedPath.isEmpty()) {\n throw new Error('Query.orderByChild: cannot pass in empty path. Use Query.orderByValue() instead.');\n }\n var index = new PathIndex_1.PathIndex(parsedPath);\n var newParams = this.queryParams_.orderBy(index);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * Return a new query ordered by the KeyIndex\n * @return {!Query}\n */\n Query.prototype.orderByKey = function () {\n util_3.validateArgCount('Query.orderByKey', 0, 0, arguments.length);\n this.validateNoPreviousOrderByCall_('Query.orderByKey');\n var newParams = this.queryParams_.orderBy(KeyIndex_1.KEY_INDEX);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * Return a new query ordered by the PriorityIndex\n * @return {!Query}\n */\n Query.prototype.orderByPriority = function () {\n util_3.validateArgCount('Query.orderByPriority', 0, 0, arguments.length);\n this.validateNoPreviousOrderByCall_('Query.orderByPriority');\n var newParams = this.queryParams_.orderBy(PriorityIndex_1.PRIORITY_INDEX);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * Return a new query ordered by the ValueIndex\n * @return {!Query}\n */\n Query.prototype.orderByValue = function () {\n util_3.validateArgCount('Query.orderByValue', 0, 0, arguments.length);\n this.validateNoPreviousOrderByCall_('Query.orderByValue');\n var newParams = this.queryParams_.orderBy(ValueIndex_1.VALUE_INDEX);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * @param {number|string|boolean|null} value\n * @param {?string=} name\n * @return {!Query}\n */\n Query.prototype.startAt = function (value, name) {\n if (value === void 0) { value = null; }\n util_3.validateArgCount('Query.startAt', 0, 2, arguments.length);\n validation_1.validateFirebaseDataArg('Query.startAt', 1, value, this.path, true);\n validation_1.validateKey('Query.startAt', 2, name, true);\n var newParams = this.queryParams_.startAt(value, name);\n Query.validateLimit_(newParams);\n Query.validateQueryEndpoints_(newParams);\n if (this.queryParams_.hasStart()) {\n throw new Error('Query.startAt: Starting point was already set (by another call to startAt ' +\n 'or equalTo).');\n }\n // Calling with no params tells us to start at the beginning.\n if (value === undefined) {\n value = null;\n name = null;\n }\n return new Query(this.repo, this.path, newParams, this.orderByCalled_);\n };\n /**\n * @param {number|string|boolean|null} value\n * @param {?string=} name\n * @return {!Query}\n */\n Query.prototype.endAt = function (value, name) {\n if (value === void 0) { value = null; }\n util_3.validateArgCount('Query.endAt', 0, 2, arguments.length);\n validation_1.validateFirebaseDataArg('Query.endAt', 1, value, this.path, true);\n validation_1.validateKey('Query.endAt', 2, name, true);\n var newParams = this.queryParams_.endAt(value, name);\n Query.validateLimit_(newParams);\n Query.validateQueryEndpoints_(newParams);\n if (this.queryParams_.hasEnd()) {\n throw new Error('Query.endAt: Ending point was already set (by another call to endAt or ' +\n 'equalTo).');\n }\n return new Query(this.repo, this.path, newParams, this.orderByCalled_);\n };\n /**\n * Load the selection of children with exactly the specified value, and, optionally,\n * the specified name.\n * @param {number|string|boolean|null} value\n * @param {string=} name\n * @return {!Query}\n */\n Query.prototype.equalTo = function (value, name) {\n util_3.validateArgCount('Query.equalTo', 1, 2, arguments.length);\n validation_1.validateFirebaseDataArg('Query.equalTo', 1, value, this.path, false);\n validation_1.validateKey('Query.equalTo', 2, name, true);\n if (this.queryParams_.hasStart()) {\n throw new Error('Query.equalTo: Starting point was already set (by another call to startAt or ' +\n 'equalTo).');\n }\n if (this.queryParams_.hasEnd()) {\n throw new Error('Query.equalTo: Ending point was already set (by another call to endAt or ' +\n 'equalTo).');\n }\n return this.startAt(value, name).endAt(value, name);\n };\n /**\n * @return {!string} URL for this location.\n */\n Query.prototype.toString = function () {\n util_3.validateArgCount('Query.toString', 0, 0, arguments.length);\n return this.repo.toString() + this.path.toUrlEncodedString();\n };\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users.\n Query.prototype.toJSON = function () {\n // An optional spacer argument is unnecessary for a string.\n util_3.validateArgCount('Query.toJSON', 0, 1, arguments.length);\n return this.toString();\n };\n /**\n * An object representation of the query parameters used by this Query.\n * @return {!Object}\n */\n Query.prototype.queryObject = function () {\n return this.queryParams_.getQueryObject();\n };\n /**\n * @return {!string}\n */\n Query.prototype.queryIdentifier = function () {\n var obj = this.queryObject();\n var id = util_2.ObjectToUniqueKey(obj);\n return id === '{}' ? 'default' : id;\n };\n /**\n * Return true if this query and the provided query are equivalent; otherwise, return false.\n * @param {Query} other\n * @return {boolean}\n */\n Query.prototype.isEqual = function (other) {\n util_3.validateArgCount('Query.isEqual', 1, 1, arguments.length);\n if (!(other instanceof Query)) {\n var error = 'Query.isEqual failed: First argument must be an instance of firebase.database.Query.';\n throw new Error(error);\n }\n var sameRepo = this.repo === other.repo;\n var samePath = this.path.equals(other.path);\n var sameQueryIdentifier = this.queryIdentifier() === other.queryIdentifier();\n return sameRepo && samePath && sameQueryIdentifier;\n };\n /**\n * Helper used by .on and .once to extract the context and or cancel arguments.\n * @param {!string} fnName The function name (on or once)\n * @param {(function(Error)|Object)=} cancelOrContext\n * @param {Object=} context\n * @return {{cancel: ?function(Error), context: ?Object}}\n * @private\n */\n Query.getCancelAndContextArgs_ = function (fnName, cancelOrContext, context) {\n var ret = { cancel: null, context: null };\n if (cancelOrContext && context) {\n ret.cancel = cancelOrContext;\n util_3.validateCallback(fnName, 3, ret.cancel, true);\n ret.context = context;\n util_3.validateContextObject(fnName, 4, ret.context, true);\n }\n else if (cancelOrContext) {\n // we have either a cancel callback or a context.\n if (typeof cancelOrContext === 'object' && cancelOrContext !== null) {\n // it's a context!\n ret.context = cancelOrContext;\n }\n else if (typeof cancelOrContext === 'function') {\n ret.cancel = cancelOrContext;\n }\n else {\n throw new Error(util_3.errorPrefix(fnName, 3, true) +\n ' must either be a cancel callback or a context object.');\n }\n }\n return ret;\n };\n Object.defineProperty(Query.prototype, \"ref\", {\n get: function () {\n return this.getRef();\n },\n enumerable: true,\n configurable: true\n });\n return Query;\n}());\nexports.Query = Query;\n\n//# sourceMappingURL=Query.js.map\n\n\n/***/ }),\n/* 38 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar util_3 = __webpack_require__(0);\nvar MAX_NODE;\nfunction setMaxNode(val) {\n MAX_NODE = val;\n}\nexports.setMaxNode = setMaxNode;\n/**\n * @param {(!string|!number)} priority\n * @return {!string}\n */\nexports.priorityHashText = function (priority) {\n if (typeof priority === 'number')\n return 'number:' + util_2.doubleToIEEE754String(priority);\n else\n return 'string:' + priority;\n};\n/**\n * Validates that a priority snapshot Node is valid.\n *\n * @param {!Node} priorityNode\n */\nexports.validatePriorityNode = function (priorityNode) {\n if (priorityNode.isLeafNode()) {\n var val = priorityNode.val();\n util_1.assert(typeof val === 'string' ||\n typeof val === 'number' ||\n (typeof val === 'object' && util_3.contains(val, '.sv')), 'Priority must be a string or number.');\n }\n else {\n util_1.assert(priorityNode === MAX_NODE || priorityNode.isEmpty(), 'priority of unexpected type.');\n }\n // Don't call getPriority() on MAX_NODE to avoid hitting assertion.\n util_1.assert(priorityNode === MAX_NODE || priorityNode.getPriority().isEmpty(), \"Priority nodes can't have a priority of their own.\");\n};\n\n//# sourceMappingURL=snap.js.map\n\n\n/***/ }),\n/* 39 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = __webpack_require__(2);\nvar Index_1 = __webpack_require__(16);\nvar Node_1 = __webpack_require__(6);\nvar util_1 = __webpack_require__(1);\nvar nodeFromJSON_1 = __webpack_require__(13);\n/**\n * @constructor\n * @extends {Index}\n * @private\n */\nvar ValueIndex = /** @class */ (function (_super) {\n tslib_1.__extends(ValueIndex, _super);\n function ValueIndex() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.compare = function (a, b) {\n var indexCmp = a.node.compareTo(b.node);\n if (indexCmp === 0) {\n return util_1.nameCompare(a.name, b.name);\n }\n else {\n return indexCmp;\n }\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.isDefinedOn = function (node) {\n return true;\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.indexedValueChanged = function (oldNode, newNode) {\n return !oldNode.equals(newNode);\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.maxPost = function () {\n return Node_1.NamedNode.MAX;\n };\n /**\n * @param {*} indexValue\n * @param {string} name\n * @return {!NamedNode}\n */\n ValueIndex.prototype.makePost = function (indexValue, name) {\n var valueNode = nodeFromJSON_1.nodeFromJSON(indexValue);\n return new Node_1.NamedNode(name, valueNode);\n };\n /**\n * @return {!string} String representation for inclusion in a query spec\n */\n ValueIndex.prototype.toString = function () {\n return '.value';\n };\n return ValueIndex;\n}(Index_1.Index));\nexports.ValueIndex = ValueIndex;\nexports.VALUE_INDEX = new ValueIndex();\n\n//# sourceMappingURL=ValueIndex.js.map\n\n\n/***/ }),\n/* 40 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar childSet_1 = __webpack_require__(41);\nvar util_2 = __webpack_require__(0);\nvar Node_1 = __webpack_require__(6);\nvar PriorityIndex_1 = __webpack_require__(4);\nvar KeyIndex_1 = __webpack_require__(12);\nvar _defaultIndexMap;\nvar fallbackObject = {};\n/**\n *\n * @param {Object.>} indexes\n * @param {Object.} indexSet\n * @constructor\n */\nvar IndexMap = /** @class */ (function () {\n function IndexMap(indexes_, indexSet_) {\n this.indexes_ = indexes_;\n this.indexSet_ = indexSet_;\n }\n Object.defineProperty(IndexMap, \"Default\", {\n /**\n * The default IndexMap for nodes without a priority\n * @type {!IndexMap}\n * @const\n */\n get: function () {\n util_1.assert(fallbackObject && PriorityIndex_1.PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');\n _defaultIndexMap =\n _defaultIndexMap ||\n new IndexMap({ '.priority': fallbackObject }, { '.priority': PriorityIndex_1.PRIORITY_INDEX });\n return _defaultIndexMap;\n },\n enumerable: true,\n configurable: true\n });\n /**\n *\n * @param {!string} indexKey\n * @return {?SortedMap.}\n */\n IndexMap.prototype.get = function (indexKey) {\n var sortedMap = util_2.safeGet(this.indexes_, indexKey);\n if (!sortedMap)\n throw new Error('No index defined for ' + indexKey);\n if (sortedMap === fallbackObject) {\n // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the\n // regular child map\n return null;\n }\n else {\n return sortedMap;\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {boolean}\n */\n IndexMap.prototype.hasIndex = function (indexDefinition) {\n return util_2.contains(this.indexSet_, indexDefinition.toString());\n };\n /**\n * @param {!Index} indexDefinition\n * @param {!SortedMap.} existingChildren\n * @return {!IndexMap}\n */\n IndexMap.prototype.addIndex = function (indexDefinition, existingChildren) {\n util_1.assert(indexDefinition !== KeyIndex_1.KEY_INDEX, \"KeyIndex always exists and isn't meant to be added to the IndexMap.\");\n var childList = [];\n var sawIndexedValue = false;\n var iter = existingChildren.getIterator(Node_1.NamedNode.Wrap);\n var next = iter.getNext();\n while (next) {\n sawIndexedValue =\n sawIndexedValue || indexDefinition.isDefinedOn(next.node);\n childList.push(next);\n next = iter.getNext();\n }\n var newIndex;\n if (sawIndexedValue) {\n newIndex = childSet_1.buildChildSet(childList, indexDefinition.getCompare());\n }\n else {\n newIndex = fallbackObject;\n }\n var indexName = indexDefinition.toString();\n var newIndexSet = util_2.clone(this.indexSet_);\n newIndexSet[indexName] = indexDefinition;\n var newIndexes = util_2.clone(this.indexes_);\n newIndexes[indexName] = newIndex;\n return new IndexMap(newIndexes, newIndexSet);\n };\n /**\n * Ensure that this node is properly tracked in any indexes that we're maintaining\n * @param {!NamedNode} namedNode\n * @param {!SortedMap.} existingChildren\n * @return {!IndexMap}\n */\n IndexMap.prototype.addToIndexes = function (namedNode, existingChildren) {\n var _this = this;\n var newIndexes = util_2.map(this.indexes_, function (indexedChildren, indexName) {\n var index = util_2.safeGet(_this.indexSet_, indexName);\n util_1.assert(index, 'Missing index implementation for ' + indexName);\n if (indexedChildren === fallbackObject) {\n // Check to see if we need to index everything\n if (index.isDefinedOn(namedNode.node)) {\n // We need to build this index\n var childList = [];\n var iter = existingChildren.getIterator(Node_1.NamedNode.Wrap);\n var next = iter.getNext();\n while (next) {\n if (next.name != namedNode.name) {\n childList.push(next);\n }\n next = iter.getNext();\n }\n childList.push(namedNode);\n return childSet_1.buildChildSet(childList, index.getCompare());\n }\n else {\n // No change, this remains a fallback\n return fallbackObject;\n }\n }\n else {\n var existingSnap = existingChildren.get(namedNode.name);\n var newChildren = indexedChildren;\n if (existingSnap) {\n newChildren = newChildren.remove(new Node_1.NamedNode(namedNode.name, existingSnap));\n }\n return newChildren.insert(namedNode, namedNode.node);\n }\n });\n return new IndexMap(newIndexes, this.indexSet_);\n };\n /**\n * Create a new IndexMap instance with the given value removed\n * @param {!NamedNode} namedNode\n * @param {!SortedMap.} existingChildren\n * @return {!IndexMap}\n */\n IndexMap.prototype.removeFromIndexes = function (namedNode, existingChildren) {\n var newIndexes = util_2.map(this.indexes_, function (indexedChildren) {\n if (indexedChildren === fallbackObject) {\n // This is the fallback. Just return it, nothing to do in this case\n return indexedChildren;\n }\n else {\n var existingSnap = existingChildren.get(namedNode.name);\n if (existingSnap) {\n return indexedChildren.remove(new Node_1.NamedNode(namedNode.name, existingSnap));\n }\n else {\n // No record of this child\n return indexedChildren;\n }\n }\n });\n return new IndexMap(newIndexes, this.indexSet_);\n };\n return IndexMap;\n}());\nexports.IndexMap = IndexMap;\n\n//# sourceMappingURL=IndexMap.js.map\n\n\n/***/ }),\n/* 41 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar SortedMap_1 = __webpack_require__(18);\nvar SortedMap_2 = __webpack_require__(18);\nvar LOG_2 = Math.log(2);\n/**\n * @constructor\n */\nvar Base12Num = /** @class */ (function () {\n /**\n * @param {number} length\n */\n function Base12Num(length) {\n var logBase2 = function (num) {\n return parseInt((Math.log(num) / LOG_2), 10);\n };\n var bitMask = function (bits) { return parseInt(Array(bits + 1).join('1'), 2); };\n this.count = logBase2(length + 1);\n this.current_ = this.count - 1;\n var mask = bitMask(this.count);\n this.bits_ = (length + 1) & mask;\n }\n /**\n * @return {boolean}\n */\n Base12Num.prototype.nextBitIsOne = function () {\n //noinspection JSBitwiseOperatorUsage\n var result = !(this.bits_ & (0x1 << this.current_));\n this.current_--;\n return result;\n };\n return Base12Num;\n}());\n/**\n * Takes a list of child nodes and constructs a SortedSet using the given comparison\n * function\n *\n * Uses the algorithm described in the paper linked here:\n * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458\n *\n * @template K, V\n * @param {Array.} childList Unsorted list of children\n * @param {function(!NamedNode, !NamedNode):number} cmp The comparison method to be used\n * @param {(function(NamedNode):K)=} keyFn An optional function to extract K from a node wrapper, if K's\n * type is not NamedNode\n * @param {(function(K, K):number)=} mapSortFn An optional override for comparator used by the generated sorted map\n * @return {SortedMap.}\n */\nexports.buildChildSet = function (childList, cmp, keyFn, mapSortFn) {\n childList.sort(cmp);\n var buildBalancedTree = function (low, high) {\n var length = high - low;\n var namedNode;\n var key;\n if (length == 0) {\n return null;\n }\n else if (length == 1) {\n namedNode = childList[low];\n key = keyFn ? keyFn(namedNode) : namedNode;\n return new SortedMap_1.LLRBNode(key, namedNode.node, SortedMap_1.LLRBNode.BLACK, null, null);\n }\n else {\n var middle = parseInt((length / 2), 10) + low;\n var left = buildBalancedTree(low, middle);\n var right = buildBalancedTree(middle + 1, high);\n namedNode = childList[middle];\n key = keyFn ? keyFn(namedNode) : namedNode;\n return new SortedMap_1.LLRBNode(key, namedNode.node, SortedMap_1.LLRBNode.BLACK, left, right);\n }\n };\n var buildFrom12Array = function (base12) {\n var node = null;\n var root = null;\n var index = childList.length;\n var buildPennant = function (chunkSize, color) {\n var low = index - chunkSize;\n var high = index;\n index -= chunkSize;\n var childTree = buildBalancedTree(low + 1, high);\n var namedNode = childList[low];\n var key = keyFn ? keyFn(namedNode) : namedNode;\n attachPennant(new SortedMap_1.LLRBNode(key, namedNode.node, color, null, childTree));\n };\n var attachPennant = function (pennant) {\n if (node) {\n node.left = pennant;\n node = pennant;\n }\n else {\n root = pennant;\n node = pennant;\n }\n };\n for (var i = 0; i < base12.count; ++i) {\n var isOne = base12.nextBitIsOne();\n // The number of nodes taken in each slice is 2^(arr.length - (i + 1))\n var chunkSize = Math.pow(2, base12.count - (i + 1));\n if (isOne) {\n buildPennant(chunkSize, SortedMap_1.LLRBNode.BLACK);\n }\n else {\n // current == 2\n buildPennant(chunkSize, SortedMap_1.LLRBNode.BLACK);\n buildPennant(chunkSize, SortedMap_1.LLRBNode.RED);\n }\n }\n return root;\n };\n var base12 = new Base12Num(childList.length);\n var root = buildFrom12Array(base12);\n return new SortedMap_2.SortedMap(mapSortFn || cmp, root);\n};\n\n//# sourceMappingURL=childSet.js.map\n\n\n/***/ }),\n/* 42 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(1);\nfunction NAME_ONLY_COMPARATOR(left, right) {\n return util_1.nameCompare(left.name, right.name);\n}\nexports.NAME_ONLY_COMPARATOR = NAME_ONLY_COMPARATOR;\nfunction NAME_COMPARATOR(left, right) {\n return util_1.nameCompare(left, right);\n}\nexports.NAME_COMPARATOR = NAME_COMPARATOR;\n\n//# sourceMappingURL=comparators.js.map\n\n\n/***/ }),\n/* 43 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = __webpack_require__(2);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar Index_1 = __webpack_require__(16);\nvar ChildrenNode_1 = __webpack_require__(5);\nvar Node_1 = __webpack_require__(6);\nvar nodeFromJSON_1 = __webpack_require__(13);\n/**\n * @param {!Path} indexPath\n * @constructor\n * @extends {Index}\n */\nvar PathIndex = /** @class */ (function (_super) {\n tslib_1.__extends(PathIndex, _super);\n function PathIndex(indexPath_) {\n var _this = _super.call(this) || this;\n _this.indexPath_ = indexPath_;\n util_1.assert(!indexPath_.isEmpty() && indexPath_.getFront() !== '.priority', \"Can't create PathIndex with empty path or .priority key\");\n return _this;\n }\n /**\n * @param {!Node} snap\n * @return {!Node}\n * @protected\n */\n PathIndex.prototype.extractChild = function (snap) {\n return snap.getChild(this.indexPath_);\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.isDefinedOn = function (node) {\n return !node.getChild(this.indexPath_).isEmpty();\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.compare = function (a, b) {\n var aChild = this.extractChild(a.node);\n var bChild = this.extractChild(b.node);\n var indexCmp = aChild.compareTo(bChild);\n if (indexCmp === 0) {\n return util_2.nameCompare(a.name, b.name);\n }\n else {\n return indexCmp;\n }\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.makePost = function (indexValue, name) {\n var valueNode = nodeFromJSON_1.nodeFromJSON(indexValue);\n var node = ChildrenNode_1.ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);\n return new Node_1.NamedNode(name, node);\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.maxPost = function () {\n var node = ChildrenNode_1.ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, ChildrenNode_1.MAX_NODE);\n return new Node_1.NamedNode(util_2.MAX_NAME, node);\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.toString = function () {\n return this.indexPath_.slice().join('/');\n };\n return PathIndex;\n}(Index_1.Index));\nexports.PathIndex = PathIndex;\n\n//# sourceMappingURL=PathIndex.js.map\n\n\n/***/ }),\n/* 44 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Path_1 = __webpack_require__(3);\nvar SparseSnapshotTree_1 = __webpack_require__(45);\nvar LeafNode_1 = __webpack_require__(17);\nvar nodeFromJSON_1 = __webpack_require__(13);\nvar PriorityIndex_1 = __webpack_require__(4);\n/**\n * Generate placeholders for deferred values.\n * @param {?Object} values\n * @return {!Object}\n */\nexports.generateWithValues = function (values) {\n values = values || {};\n values['timestamp'] = values['timestamp'] || new Date().getTime();\n return values;\n};\n/**\n * Value to use when firing local events. When writing server values, fire\n * local events with an approximate value, otherwise return value as-is.\n * @param {(Object|string|number|boolean)} value\n * @param {!Object} serverValues\n * @return {!(string|number|boolean)}\n */\nexports.resolveDeferredValue = function (value, serverValues) {\n if (!value || typeof value !== 'object') {\n return value;\n }\n else {\n util_1.assert('.sv' in value, 'Unexpected leaf node or priority contents');\n return serverValues[value['.sv']];\n }\n};\n/**\n * Recursively replace all deferred values and priorities in the tree with the\n * specified generated replacement values.\n * @param {!SparseSnapshotTree} tree\n * @param {!Object} serverValues\n * @return {!SparseSnapshotTree}\n */\nexports.resolveDeferredValueTree = function (tree, serverValues) {\n var resolvedTree = new SparseSnapshotTree_1.SparseSnapshotTree();\n tree.forEachTree(new Path_1.Path(''), function (path, node) {\n resolvedTree.remember(path, exports.resolveDeferredValueSnapshot(node, serverValues));\n });\n return resolvedTree;\n};\n/**\n * Recursively replace all deferred values and priorities in the node with the\n * specified generated replacement values. If there are no server values in the node,\n * it'll be returned as-is.\n * @param {!Node} node\n * @param {!Object} serverValues\n * @return {!Node}\n */\nexports.resolveDeferredValueSnapshot = function (node, serverValues) {\n var rawPri = node.getPriority().val();\n var priority = exports.resolveDeferredValue(rawPri, serverValues);\n var newNode;\n if (node.isLeafNode()) {\n var leafNode = node;\n var value = exports.resolveDeferredValue(leafNode.getValue(), serverValues);\n if (value !== leafNode.getValue() ||\n priority !== leafNode.getPriority().val()) {\n return new LeafNode_1.LeafNode(value, nodeFromJSON_1.nodeFromJSON(priority));\n }\n else {\n return node;\n }\n }\n else {\n var childrenNode = node;\n newNode = childrenNode;\n if (priority !== childrenNode.getPriority().val()) {\n newNode = newNode.updatePriority(new LeafNode_1.LeafNode(priority));\n }\n childrenNode.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n var newChildNode = exports.resolveDeferredValueSnapshot(childNode, serverValues);\n if (newChildNode !== childNode) {\n newNode = newNode.updateImmediateChild(childName, newChildNode);\n }\n });\n return newNode;\n }\n};\n\n//# sourceMappingURL=ServerValues.js.map\n\n\n/***/ }),\n/* 45 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = __webpack_require__(3);\nvar PriorityIndex_1 = __webpack_require__(4);\nvar CountedSet_1 = __webpack_require__(46);\n/**\n * Helper class to store a sparse set of snapshots.\n *\n * @constructor\n */\nvar SparseSnapshotTree = /** @class */ (function () {\n function SparseSnapshotTree() {\n /**\n * @private\n * @type {Node}\n */\n this.value_ = null;\n /**\n * @private\n * @type {CountedSet}\n */\n this.children_ = null;\n }\n /**\n * Gets the node stored at the given path if one exists.\n *\n * @param {!Path} path Path to look up snapshot for.\n * @return {?Node} The retrieved node, or null.\n */\n SparseSnapshotTree.prototype.find = function (path) {\n if (this.value_ != null) {\n return this.value_.getChild(path);\n }\n else if (!path.isEmpty() && this.children_ != null) {\n var childKey = path.getFront();\n path = path.popFront();\n if (this.children_.contains(childKey)) {\n var childTree = this.children_.get(childKey);\n return childTree.find(path);\n }\n else {\n return null;\n }\n }\n else {\n return null;\n }\n };\n /**\n * Stores the given node at the specified path. If there is already a node\n * at a shallower path, it merges the new data into that snapshot node.\n *\n * @param {!Path} path Path to look up snapshot for.\n * @param {!Node} data The new data, or null.\n */\n SparseSnapshotTree.prototype.remember = function (path, data) {\n if (path.isEmpty()) {\n this.value_ = data;\n this.children_ = null;\n }\n else if (this.value_ !== null) {\n this.value_ = this.value_.updateChild(path, data);\n }\n else {\n if (this.children_ == null) {\n this.children_ = new CountedSet_1.CountedSet();\n }\n var childKey = path.getFront();\n if (!this.children_.contains(childKey)) {\n this.children_.add(childKey, new SparseSnapshotTree());\n }\n var child = this.children_.get(childKey);\n path = path.popFront();\n child.remember(path, data);\n }\n };\n /**\n * Purge the data at path from the cache.\n *\n * @param {!Path} path Path to look up snapshot for.\n * @return {boolean} True if this node should now be removed.\n */\n SparseSnapshotTree.prototype.forget = function (path) {\n if (path.isEmpty()) {\n this.value_ = null;\n this.children_ = null;\n return true;\n }\n else {\n if (this.value_ !== null) {\n if (this.value_.isLeafNode()) {\n // We're trying to forget a node that doesn't exist\n return false;\n }\n else {\n var value = this.value_;\n this.value_ = null;\n var self_1 = this;\n value.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, tree) {\n self_1.remember(new Path_1.Path(key), tree);\n });\n return this.forget(path);\n }\n }\n else if (this.children_ !== null) {\n var childKey = path.getFront();\n path = path.popFront();\n if (this.children_.contains(childKey)) {\n var safeToRemove = this.children_.get(childKey).forget(path);\n if (safeToRemove) {\n this.children_.remove(childKey);\n }\n }\n if (this.children_.isEmpty()) {\n this.children_ = null;\n return true;\n }\n else {\n return false;\n }\n }\n else {\n return true;\n }\n }\n };\n /**\n * Recursively iterates through all of the stored tree and calls the\n * callback on each one.\n *\n * @param {!Path} prefixPath Path to look up node for.\n * @param {!Function} func The function to invoke for each tree.\n */\n SparseSnapshotTree.prototype.forEachTree = function (prefixPath, func) {\n if (this.value_ !== null) {\n func(prefixPath, this.value_);\n }\n else {\n this.forEachChild(function (key, tree) {\n var path = new Path_1.Path(prefixPath.toString() + '/' + key);\n tree.forEachTree(path, func);\n });\n }\n };\n /**\n * Iterates through each immediate child and triggers the callback.\n *\n * @param {!Function} func The function to invoke for each child.\n */\n SparseSnapshotTree.prototype.forEachChild = function (func) {\n if (this.children_ !== null) {\n this.children_.each(function (key, tree) {\n func(key, tree);\n });\n }\n };\n return SparseSnapshotTree;\n}());\nexports.SparseSnapshotTree = SparseSnapshotTree;\n\n//# sourceMappingURL=SparseSnapshotTree.js.map\n\n\n/***/ }),\n/* 46 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * Implements a set with a count of elements.\n *\n * @template K, V\n */\nvar CountedSet = /** @class */ (function () {\n function CountedSet() {\n this.set = {};\n }\n /**\n * @param {!K} item\n * @param {V} val\n */\n CountedSet.prototype.add = function (item, val) {\n this.set[item] = val !== null ? val : true;\n };\n /**\n * @param {!K} key\n * @return {boolean}\n */\n CountedSet.prototype.contains = function (key) {\n return util_1.contains(this.set, key);\n };\n /**\n * @param {!K} item\n * @return {V}\n */\n CountedSet.prototype.get = function (item) {\n return this.contains(item) ? this.set[item] : undefined;\n };\n /**\n * @param {!K} item\n */\n CountedSet.prototype.remove = function (item) {\n delete this.set[item];\n };\n /**\n * Deletes everything in the set\n */\n CountedSet.prototype.clear = function () {\n this.set = {};\n };\n /**\n * True if there's nothing in the set\n * @return {boolean}\n */\n CountedSet.prototype.isEmpty = function () {\n return util_1.isEmpty(this.set);\n };\n /**\n * @return {number} The number of items in the set\n */\n CountedSet.prototype.count = function () {\n return util_1.getCount(this.set);\n };\n /**\n * Run a function on each k,v pair in the set\n * @param {function(K, V)} fn\n */\n CountedSet.prototype.each = function (fn) {\n util_1.forEach(this.set, function (k, v) { return fn(k, v); });\n };\n /**\n * Mostly for debugging\n * @return {Array.} The keys present in this CountedSet\n */\n CountedSet.prototype.keys = function () {\n var keys = [];\n util_1.forEach(this.set, function (k) {\n keys.push(k);\n });\n return keys;\n };\n return CountedSet;\n}());\nexports.CountedSet = CountedSet;\n\n//# sourceMappingURL=CountedSet.js.map\n\n\n/***/ }),\n/* 47 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = __webpack_require__(9);\nvar Path_1 = __webpack_require__(3);\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @param {!Node} snap\n * @constructor\n * @implements {Operation}\n */\nvar Overwrite = /** @class */ (function () {\n function Overwrite(source, path, snap) {\n this.source = source;\n this.path = path;\n this.snap = snap;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.OVERWRITE;\n }\n Overwrite.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n return new Overwrite(this.source, Path_1.Path.Empty, this.snap.getImmediateChild(childName));\n }\n else {\n return new Overwrite(this.source, this.path.popFront(), this.snap);\n }\n };\n return Overwrite;\n}());\nexports.Overwrite = Overwrite;\n\n//# sourceMappingURL=Overwrite.js.map\n\n\n/***/ }),\n/* 48 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar CacheNode_1 = __webpack_require__(20);\nvar ChildrenNode_1 = __webpack_require__(5);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\nvar ViewCache_1 = __webpack_require__(49);\nvar View_1 = __webpack_require__(91);\nvar __referenceConstructor;\n/**\n * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to\n * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes\n * and user writes (set, transaction, update).\n *\n * It's responsible for:\n * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).\n * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,\n * applyUserOverwrite, etc.)\n */\nvar SyncPoint = /** @class */ (function () {\n function SyncPoint() {\n /**\n * The Views being tracked at this location in the tree, stored as a map where the key is a\n * queryId and the value is the View for that query.\n *\n * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).\n *\n * @type {!Object.}\n * @private\n */\n this.views_ = {};\n }\n Object.defineProperty(SyncPoint, \"__referenceConstructor\", {\n get: function () {\n util_1.assert(__referenceConstructor, 'Reference.ts has not been loaded');\n return __referenceConstructor;\n },\n set: function (val) {\n util_1.assert(!__referenceConstructor, '__referenceConstructor has already been defined');\n __referenceConstructor = val;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @return {boolean}\n */\n SyncPoint.prototype.isEmpty = function () {\n return util_2.isEmpty(this.views_);\n };\n /**\n *\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} optCompleteServerCache\n * @return {!Array.}\n */\n SyncPoint.prototype.applyOperation = function (operation, writesCache, optCompleteServerCache) {\n var queryId = operation.source.queryId;\n if (queryId !== null) {\n var view = util_2.safeGet(this.views_, queryId);\n util_1.assert(view != null, 'SyncTree gave us an op for an invalid query.');\n return view.applyOperation(operation, writesCache, optCompleteServerCache);\n }\n else {\n var events_1 = [];\n util_2.forEach(this.views_, function (key, view) {\n events_1 = events_1.concat(view.applyOperation(operation, writesCache, optCompleteServerCache));\n });\n return events_1;\n }\n };\n /**\n * Add an event callback for the specified query.\n *\n * @param {!Query} query\n * @param {!EventRegistration} eventRegistration\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache Complete server cache, if we have it.\n * @param {boolean} serverCacheComplete\n * @return {!Array.} Events to raise.\n */\n SyncPoint.prototype.addEventRegistration = function (query, eventRegistration, writesCache, serverCache, serverCacheComplete) {\n var queryId = query.queryIdentifier();\n var view = util_2.safeGet(this.views_, queryId);\n if (!view) {\n // TODO: make writesCache take flag for complete server node\n var eventCache = writesCache.calcCompleteEventCache(serverCacheComplete ? serverCache : null);\n var eventCacheComplete = false;\n if (eventCache) {\n eventCacheComplete = true;\n }\n else if (serverCache instanceof ChildrenNode_1.ChildrenNode) {\n eventCache = writesCache.calcCompleteEventChildren(serverCache);\n eventCacheComplete = false;\n }\n else {\n eventCache = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n eventCacheComplete = false;\n }\n var viewCache = new ViewCache_1.ViewCache(new CacheNode_1.CacheNode(\n /** @type {!Node} */ (eventCache), eventCacheComplete, false), new CacheNode_1.CacheNode(\n /** @type {!Node} */ (serverCache), serverCacheComplete, false));\n view = new View_1.View(query, viewCache);\n this.views_[queryId] = view;\n }\n // This is guaranteed to exist now, we just created anything that was missing\n view.addEventRegistration(eventRegistration);\n return view.getInitialEvents(eventRegistration);\n };\n /**\n * Remove event callback(s). Return cancelEvents if a cancelError is specified.\n *\n * If query is the default query, we'll check all views for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified view(s).\n *\n * @param {!Query} query\n * @param {?EventRegistration} eventRegistration If null, remove all callbacks.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {{removed:!Array., events:!Array.}} removed queries and any cancel events\n */\n SyncPoint.prototype.removeEventRegistration = function (query, eventRegistration, cancelError) {\n var queryId = query.queryIdentifier();\n var removed = [];\n var cancelEvents = [];\n var hadCompleteView = this.hasCompleteView();\n if (queryId === 'default') {\n // When you do ref.off(...), we search all views for the registration to remove.\n var self_1 = this;\n util_2.forEach(this.views_, function (viewQueryId, view) {\n cancelEvents = cancelEvents.concat(view.removeEventRegistration(eventRegistration, cancelError));\n if (view.isEmpty()) {\n delete self_1.views_[viewQueryId];\n // We'll deal with complete views later.\n if (!view\n .getQuery()\n .getQueryParams()\n .loadsAllData()) {\n removed.push(view.getQuery());\n }\n }\n });\n }\n else {\n // remove the callback from the specific view.\n var view = util_2.safeGet(this.views_, queryId);\n if (view) {\n cancelEvents = cancelEvents.concat(view.removeEventRegistration(eventRegistration, cancelError));\n if (view.isEmpty()) {\n delete this.views_[queryId];\n // We'll deal with complete views later.\n if (!view\n .getQuery()\n .getQueryParams()\n .loadsAllData()) {\n removed.push(view.getQuery());\n }\n }\n }\n }\n if (hadCompleteView && !this.hasCompleteView()) {\n // We removed our last complete view.\n removed.push(new SyncPoint.__referenceConstructor(query.repo, query.path));\n }\n return { removed: removed, events: cancelEvents };\n };\n /**\n * @return {!Array.}\n */\n SyncPoint.prototype.getQueryViews = function () {\n var _this = this;\n var values = Object.keys(this.views_).map(function (key) { return _this.views_[key]; });\n return values.filter(function (view) {\n return !view\n .getQuery()\n .getQueryParams()\n .loadsAllData();\n });\n };\n /**\n *\n * @param {!Path} path The path to the desired complete snapshot\n * @return {?Node} A complete cache, if it exists\n */\n SyncPoint.prototype.getCompleteServerCache = function (path) {\n var serverCache = null;\n util_2.forEach(this.views_, function (key, view) {\n serverCache = serverCache || view.getCompleteServerCache(path);\n });\n return serverCache;\n };\n /**\n * @param {!Query} query\n * @return {?View}\n */\n SyncPoint.prototype.viewForQuery = function (query) {\n var params = query.getQueryParams();\n if (params.loadsAllData()) {\n return this.getCompleteView();\n }\n else {\n var queryId = query.queryIdentifier();\n return util_2.safeGet(this.views_, queryId);\n }\n };\n /**\n * @param {!Query} query\n * @return {boolean}\n */\n SyncPoint.prototype.viewExistsForQuery = function (query) {\n return this.viewForQuery(query) != null;\n };\n /**\n * @return {boolean}\n */\n SyncPoint.prototype.hasCompleteView = function () {\n return this.getCompleteView() != null;\n };\n /**\n * @return {?View}\n */\n SyncPoint.prototype.getCompleteView = function () {\n var completeView = util_2.findValue(this.views_, function (view) {\n return view\n .getQuery()\n .getQueryParams()\n .loadsAllData();\n });\n return completeView || null;\n };\n return SyncPoint;\n}());\nexports.SyncPoint = SyncPoint;\n\n//# sourceMappingURL=SyncPoint.js.map\n\n\n/***/ }),\n/* 49 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ChildrenNode_1 = __webpack_require__(5);\nvar CacheNode_1 = __webpack_require__(20);\n/**\n * Stores the data we have cached for a view.\n *\n * serverSnap is the cached server data, eventSnap is the cached event data (server data plus any local writes).\n *\n * @constructor\n */\nvar ViewCache = /** @class */ (function () {\n /**\n *\n * @param {!CacheNode} eventCache_\n * @param {!CacheNode} serverCache_\n */\n function ViewCache(eventCache_, serverCache_) {\n this.eventCache_ = eventCache_;\n this.serverCache_ = serverCache_;\n }\n /**\n * @param {!Node} eventSnap\n * @param {boolean} complete\n * @param {boolean} filtered\n * @return {!ViewCache}\n */\n ViewCache.prototype.updateEventSnap = function (eventSnap, complete, filtered) {\n return new ViewCache(new CacheNode_1.CacheNode(eventSnap, complete, filtered), this.serverCache_);\n };\n /**\n * @param {!Node} serverSnap\n * @param {boolean} complete\n * @param {boolean} filtered\n * @return {!ViewCache}\n */\n ViewCache.prototype.updateServerSnap = function (serverSnap, complete, filtered) {\n return new ViewCache(this.eventCache_, new CacheNode_1.CacheNode(serverSnap, complete, filtered));\n };\n /**\n * @return {!CacheNode}\n */\n ViewCache.prototype.getEventCache = function () {\n return this.eventCache_;\n };\n /**\n * @return {?Node}\n */\n ViewCache.prototype.getCompleteEventSnap = function () {\n return this.eventCache_.isFullyInitialized()\n ? this.eventCache_.getNode()\n : null;\n };\n /**\n * @return {!CacheNode}\n */\n ViewCache.prototype.getServerCache = function () {\n return this.serverCache_;\n };\n /**\n * @return {?Node}\n */\n ViewCache.prototype.getCompleteServerSnap = function () {\n return this.serverCache_.isFullyInitialized()\n ? this.serverCache_.getNode()\n : null;\n };\n /**\n * @const\n * @type {ViewCache}\n */\n ViewCache.Empty = new ViewCache(new CacheNode_1.CacheNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, \n /*fullyInitialized=*/ false, \n /*filtered=*/ false), new CacheNode_1.CacheNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, \n /*fullyInitialized=*/ false, \n /*filtered=*/ false));\n return ViewCache;\n}());\nexports.ViewCache = ViewCache;\n\n//# sourceMappingURL=ViewCache.js.map\n\n\n/***/ }),\n/* 50 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * Returns the delta from the previous call to get stats.\n *\n * @param collection_ The collection to \"listen\" to.\n * @constructor\n */\nvar StatsListener = /** @class */ (function () {\n function StatsListener(collection_) {\n this.collection_ = collection_;\n this.last_ = null;\n }\n StatsListener.prototype.get = function () {\n var newStats = this.collection_.get();\n var delta = util_1.clone(newStats);\n if (this.last_) {\n util_1.forEach(this.last_, function (stat, value) {\n delta[stat] = delta[stat] - value;\n });\n }\n this.last_ = newStats;\n return delta;\n };\n return StatsListener;\n}());\nexports.StatsListener = StatsListener;\n\n//# sourceMappingURL=StatsListener.js.map\n\n\n/***/ }),\n/* 51 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = __webpack_require__(2);\nvar app_1 = __webpack_require__(7);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\nvar util_3 = __webpack_require__(0);\nvar util_4 = __webpack_require__(1);\nvar Path_1 = __webpack_require__(3);\nvar VisibilityMonitor_1 = __webpack_require__(103);\nvar OnlineMonitor_1 = __webpack_require__(104);\nvar util_5 = __webpack_require__(0);\nvar Connection_1 = __webpack_require__(53);\nvar util_6 = __webpack_require__(0);\nvar util_7 = __webpack_require__(0);\nvar ServerActions_1 = __webpack_require__(56);\nvar RECONNECT_MIN_DELAY = 1000;\nvar RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)\nvar RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)\nvar RECONNECT_DELAY_MULTIPLIER = 1.3;\nvar RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.\nvar SERVER_KILL_INTERRUPT_REASON = 'server_kill';\n// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.\nvar INVALID_AUTH_TOKEN_THRESHOLD = 3;\n/**\n * Firebase connection. Abstracts wire protocol and handles reconnecting.\n *\n * NOTE: All JSON objects sent to the realtime connection must have property names enclosed\n * in quotes to make sure the closure compiler does not minify them.\n */\nvar PersistentConnection = /** @class */ (function (_super) {\n tslib_1.__extends(PersistentConnection, _super);\n /**\n * @implements {ServerActions}\n * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to\n * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server\n * @param onConnectStatus_\n * @param onServerInfoUpdate_\n * @param authTokenProvider_\n * @param authOverride_\n */\n function PersistentConnection(repoInfo_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, authOverride_) {\n var _this = _super.call(this) || this;\n _this.repoInfo_ = repoInfo_;\n _this.onDataUpdate_ = onDataUpdate_;\n _this.onConnectStatus_ = onConnectStatus_;\n _this.onServerInfoUpdate_ = onServerInfoUpdate_;\n _this.authTokenProvider_ = authTokenProvider_;\n _this.authOverride_ = authOverride_;\n // Used for diagnostic logging.\n _this.id = PersistentConnection.nextPersistentConnectionId_++;\n _this.log_ = util_4.logWrapper('p:' + _this.id + ':');\n /** @private {Object} */\n _this.interruptReasons_ = {};\n _this.listens_ = {};\n _this.outstandingPuts_ = [];\n _this.outstandingPutCount_ = 0;\n _this.onDisconnectRequestQueue_ = [];\n _this.connected_ = false;\n _this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n _this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;\n _this.securityDebugCallback_ = null;\n _this.lastSessionId = null;\n /** @private {number|null} */\n _this.establishConnectionTimer_ = null;\n /** @private {boolean} */\n _this.visible_ = false;\n // Before we get connected, we keep a queue of pending messages to send.\n _this.requestCBHash_ = {};\n _this.requestNumber_ = 0;\n /** @private {?{\n * sendRequest(Object),\n * close()\n * }} */\n _this.realtime_ = null;\n /** @private {string|null} */\n _this.authToken_ = null;\n _this.forceTokenRefresh_ = false;\n _this.invalidAuthTokenCount_ = 0;\n _this.firstConnection_ = true;\n _this.lastConnectionAttemptTime_ = null;\n _this.lastConnectionEstablishedTime_ = null;\n if (authOverride_ && !util_7.isNodeSdk()) {\n throw new Error('Auth override specified in options, but not supported on non Node.js platforms');\n }\n _this.scheduleConnect_(0);\n VisibilityMonitor_1.VisibilityMonitor.getInstance().on('visible', _this.onVisible_, _this);\n if (repoInfo_.host.indexOf('fblocal') === -1) {\n OnlineMonitor_1.OnlineMonitor.getInstance().on('online', _this.onOnline_, _this);\n }\n return _this;\n }\n /**\n * @param {!string} action\n * @param {*} body\n * @param {function(*)=} onResponse\n * @protected\n */\n PersistentConnection.prototype.sendRequest = function (action, body, onResponse) {\n var curReqNum = ++this.requestNumber_;\n var msg = { r: curReqNum, a: action, b: body };\n this.log_(util_2.stringify(msg));\n util_3.assert(this.connected_, \"sendRequest call when we're not connected not allowed.\");\n this.realtime_.sendRequest(msg);\n if (onResponse) {\n this.requestCBHash_[curReqNum] = onResponse;\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.listen = function (query, currentHashFn, tag, onComplete) {\n var queryId = query.queryIdentifier();\n var pathString = query.path.toString();\n this.log_('Listen called for ' + pathString + ' ' + queryId);\n this.listens_[pathString] = this.listens_[pathString] || {};\n util_3.assert(query.getQueryParams().isDefault() ||\n !query.getQueryParams().loadsAllData(), 'listen() called for non-default but complete query');\n util_3.assert(!this.listens_[pathString][queryId], 'listen() called twice for same path/queryId.');\n var listenSpec = {\n onComplete: onComplete,\n hashFn: currentHashFn,\n query: query,\n tag: tag\n };\n this.listens_[pathString][queryId] = listenSpec;\n if (this.connected_) {\n this.sendListen_(listenSpec);\n }\n };\n /**\n * @param {!{onComplete(),\n * hashFn():!string,\n * query: !Query,\n * tag: ?number}} listenSpec\n * @private\n */\n PersistentConnection.prototype.sendListen_ = function (listenSpec) {\n var _this = this;\n var query = listenSpec.query;\n var pathString = query.path.toString();\n var queryId = query.queryIdentifier();\n this.log_('Listen on ' + pathString + ' for ' + queryId);\n var req = { /*path*/ p: pathString };\n var action = 'q';\n // Only bother to send query if it's non-default.\n if (listenSpec.tag) {\n req['q'] = query.queryObject();\n req['t'] = listenSpec.tag;\n }\n req['h'] = listenSpec.hashFn();\n this.sendRequest(action, req, function (message) {\n var payload = message['d'];\n var status = message['s'];\n // print warnings in any case...\n PersistentConnection.warnOnListenWarnings_(payload, query);\n var currentListenSpec = _this.listens_[pathString] && _this.listens_[pathString][queryId];\n // only trigger actions if the listen hasn't been removed and readded\n if (currentListenSpec === listenSpec) {\n _this.log_('listen response', message);\n if (status !== 'ok') {\n _this.removeListen_(pathString, queryId);\n }\n if (listenSpec.onComplete) {\n listenSpec.onComplete(status, payload);\n }\n }\n });\n };\n /**\n * @param {*} payload\n * @param {!Query} query\n * @private\n */\n PersistentConnection.warnOnListenWarnings_ = function (payload, query) {\n if (payload && typeof payload === 'object' && util_1.contains(payload, 'w')) {\n var warnings = util_1.safeGet(payload, 'w');\n if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {\n var indexSpec = '\".indexOn\": \"' +\n query\n .getQueryParams()\n .getIndex()\n .toString() +\n '\"';\n var indexPath = query.path.toString();\n util_4.warn(\"Using an unspecified index. Your data will be downloaded and \" +\n (\"filtered on the client. Consider adding \" + indexSpec + \" at \") +\n (indexPath + \" to your security rules for better performance.\"));\n }\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.refreshAuthToken = function (token) {\n this.authToken_ = token;\n this.log_('Auth token refreshed');\n if (this.authToken_) {\n this.tryAuth();\n }\n else {\n //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete\n //the credential so we dont become authenticated next time we connect.\n if (this.connected_) {\n this.sendRequest('unauth', {}, function () { });\n }\n }\n this.reduceReconnectDelayIfAdminCredential_(token);\n };\n /**\n * @param {!string} credential\n * @private\n */\n PersistentConnection.prototype.reduceReconnectDelayIfAdminCredential_ = function (credential) {\n // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).\n // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.\n var isFirebaseSecret = credential && credential.length === 40;\n if (isFirebaseSecret || util_5.isAdmin(credential)) {\n this.log_('Admin auth credential detected. Reducing max reconnect time.');\n this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n }\n };\n /**\n * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like\n * a auth revoked (the connection is closed).\n */\n PersistentConnection.prototype.tryAuth = function () {\n var _this = this;\n if (this.connected_ && this.authToken_) {\n var token_1 = this.authToken_;\n var authMethod = util_5.isValidFormat(token_1) ? 'auth' : 'gauth';\n var requestData = { cred: token_1 };\n if (this.authOverride_ === null) {\n requestData['noauth'] = true;\n }\n else if (typeof this.authOverride_ === 'object') {\n requestData['authvar'] = this.authOverride_;\n }\n this.sendRequest(authMethod, requestData, function (res) {\n var status = res['s'];\n var data = res['d'] || 'error';\n if (_this.authToken_ === token_1) {\n if (status === 'ok') {\n _this.invalidAuthTokenCount_ = 0;\n }\n else {\n // Triggers reconnect and force refresh for auth token\n _this.onAuthRevoked_(status, data);\n }\n }\n });\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.unlisten = function (query, tag) {\n var pathString = query.path.toString();\n var queryId = query.queryIdentifier();\n this.log_('Unlisten called for ' + pathString + ' ' + queryId);\n util_3.assert(query.getQueryParams().isDefault() ||\n !query.getQueryParams().loadsAllData(), 'unlisten() called for non-default but complete query');\n var listen = this.removeListen_(pathString, queryId);\n if (listen && this.connected_) {\n this.sendUnlisten_(pathString, queryId, query.queryObject(), tag);\n }\n };\n PersistentConnection.prototype.sendUnlisten_ = function (pathString, queryId, queryObj, tag) {\n this.log_('Unlisten on ' + pathString + ' for ' + queryId);\n var req = { /*path*/ p: pathString };\n var action = 'n';\n // Only bother sending queryId if it's non-default.\n if (tag) {\n req['q'] = queryObj;\n req['t'] = tag;\n }\n this.sendRequest(action, req);\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.onDisconnectPut = function (pathString, data, onComplete) {\n if (this.connected_) {\n this.sendOnDisconnect_('o', pathString, data, onComplete);\n }\n else {\n this.onDisconnectRequestQueue_.push({\n pathString: pathString,\n action: 'o',\n data: data,\n onComplete: onComplete\n });\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.onDisconnectMerge = function (pathString, data, onComplete) {\n if (this.connected_) {\n this.sendOnDisconnect_('om', pathString, data, onComplete);\n }\n else {\n this.onDisconnectRequestQueue_.push({\n pathString: pathString,\n action: 'om',\n data: data,\n onComplete: onComplete\n });\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.onDisconnectCancel = function (pathString, onComplete) {\n if (this.connected_) {\n this.sendOnDisconnect_('oc', pathString, null, onComplete);\n }\n else {\n this.onDisconnectRequestQueue_.push({\n pathString: pathString,\n action: 'oc',\n data: null,\n onComplete: onComplete\n });\n }\n };\n PersistentConnection.prototype.sendOnDisconnect_ = function (action, pathString, data, onComplete) {\n var request = { /*path*/ p: pathString, /*data*/ d: data };\n this.log_('onDisconnect ' + action, request);\n this.sendRequest(action, request, function (response) {\n if (onComplete) {\n setTimeout(function () {\n onComplete(response['s'], response['d']);\n }, Math.floor(0));\n }\n });\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {\n this.putInternal('p', pathString, data, onComplete, hash);\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.merge = function (pathString, data, onComplete, hash) {\n this.putInternal('m', pathString, data, onComplete, hash);\n };\n PersistentConnection.prototype.putInternal = function (action, pathString, data, onComplete, hash) {\n var request = {\n /*path*/ p: pathString,\n /*data*/ d: data\n };\n if (hash !== undefined)\n request['h'] = hash;\n // TODO: Only keep track of the most recent put for a given path?\n this.outstandingPuts_.push({\n action: action,\n request: request,\n onComplete: onComplete\n });\n this.outstandingPutCount_++;\n var index = this.outstandingPuts_.length - 1;\n if (this.connected_) {\n this.sendPut_(index);\n }\n else {\n this.log_('Buffering put: ' + pathString);\n }\n };\n PersistentConnection.prototype.sendPut_ = function (index) {\n var _this = this;\n var action = this.outstandingPuts_[index].action;\n var request = this.outstandingPuts_[index].request;\n var onComplete = this.outstandingPuts_[index].onComplete;\n this.outstandingPuts_[index].queued = this.connected_;\n this.sendRequest(action, request, function (message) {\n _this.log_(action + ' response', message);\n delete _this.outstandingPuts_[index];\n _this.outstandingPutCount_--;\n // Clean up array occasionally.\n if (_this.outstandingPutCount_ === 0) {\n _this.outstandingPuts_ = [];\n }\n if (onComplete)\n onComplete(message['s'], message['d']);\n });\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.reportStats = function (stats) {\n var _this = this;\n // If we're not connected, we just drop the stats.\n if (this.connected_) {\n var request = { /*counters*/ c: stats };\n this.log_('reportStats', request);\n this.sendRequest(/*stats*/ 's', request, function (result) {\n var status = result['s'];\n if (status !== 'ok') {\n var errorReason = result['d'];\n _this.log_('reportStats', 'Error sending stats: ' + errorReason);\n }\n });\n }\n };\n /**\n * @param {*} message\n * @private\n */\n PersistentConnection.prototype.onDataMessage_ = function (message) {\n if ('r' in message) {\n // this is a response\n this.log_('from server: ' + util_2.stringify(message));\n var reqNum = message['r'];\n var onResponse = this.requestCBHash_[reqNum];\n if (onResponse) {\n delete this.requestCBHash_[reqNum];\n onResponse(message['b']);\n }\n }\n else if ('error' in message) {\n throw 'A server-side error has occurred: ' + message['error'];\n }\n else if ('a' in message) {\n // a and b are action and body, respectively\n this.onDataPush_(message['a'], message['b']);\n }\n };\n PersistentConnection.prototype.onDataPush_ = function (action, body) {\n this.log_('handleServerMessage', action, body);\n if (action === 'd')\n this.onDataUpdate_(body['p'], body['d'], \n /*isMerge*/ false, body['t']);\n else if (action === 'm')\n this.onDataUpdate_(body['p'], body['d'], \n /*isMerge=*/ true, body['t']);\n else if (action === 'c')\n this.onListenRevoked_(body['p'], body['q']);\n else if (action === 'ac')\n this.onAuthRevoked_(body['s'], body['d']);\n else if (action === 'sd')\n this.onSecurityDebugPacket_(body);\n else\n util_4.error('Unrecognized action received from server: ' +\n util_2.stringify(action) +\n '\\nAre you using the latest client?');\n };\n PersistentConnection.prototype.onReady_ = function (timestamp, sessionId) {\n this.log_('connection ready');\n this.connected_ = true;\n this.lastConnectionEstablishedTime_ = new Date().getTime();\n this.handleTimestamp_(timestamp);\n this.lastSessionId = sessionId;\n if (this.firstConnection_) {\n this.sendConnectStats_();\n }\n this.restoreState_();\n this.firstConnection_ = false;\n this.onConnectStatus_(true);\n };\n PersistentConnection.prototype.scheduleConnect_ = function (timeout) {\n var _this = this;\n util_3.assert(!this.realtime_, \"Scheduling a connect when we're already connected/ing?\");\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n }\n // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating \"Security Error\" in\n // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).\n this.establishConnectionTimer_ = setTimeout(function () {\n _this.establishConnectionTimer_ = null;\n _this.establishConnection_();\n }, Math.floor(timeout));\n };\n /**\n * @param {boolean} visible\n * @private\n */\n PersistentConnection.prototype.onVisible_ = function (visible) {\n // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.\n if (visible &&\n !this.visible_ &&\n this.reconnectDelay_ === this.maxReconnectDelay_) {\n this.log_('Window became visible. Reducing delay.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n this.visible_ = visible;\n };\n PersistentConnection.prototype.onOnline_ = function (online) {\n if (online) {\n this.log_('Browser went online.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n else {\n this.log_('Browser went offline. Killing connection.');\n if (this.realtime_) {\n this.realtime_.close();\n }\n }\n };\n PersistentConnection.prototype.onRealtimeDisconnect_ = function () {\n this.log_('data client disconnected');\n this.connected_ = false;\n this.realtime_ = null;\n // Since we don't know if our sent transactions succeeded or not, we need to cancel them.\n this.cancelSentTransactions_();\n // Clear out the pending requests.\n this.requestCBHash_ = {};\n if (this.shouldReconnect_()) {\n if (!this.visible_) {\n this.log_(\"Window isn't visible. Delaying reconnect.\");\n this.reconnectDelay_ = this.maxReconnectDelay_;\n this.lastConnectionAttemptTime_ = new Date().getTime();\n }\n else if (this.lastConnectionEstablishedTime_) {\n // If we've been connected long enough, reset reconnect delay to minimum.\n var timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;\n if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT)\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n this.lastConnectionEstablishedTime_ = null;\n }\n var timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;\n var reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);\n reconnectDelay = Math.random() * reconnectDelay;\n this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');\n this.scheduleConnect_(reconnectDelay);\n // Adjust reconnect delay for next time.\n this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);\n }\n this.onConnectStatus_(false);\n };\n PersistentConnection.prototype.establishConnection_ = function () {\n if (this.shouldReconnect_()) {\n this.log_('Making a connection attempt');\n this.lastConnectionAttemptTime_ = new Date().getTime();\n this.lastConnectionEstablishedTime_ = null;\n var onDataMessage_1 = this.onDataMessage_.bind(this);\n var onReady_1 = this.onReady_.bind(this);\n var onDisconnect_1 = this.onRealtimeDisconnect_.bind(this);\n var connId_1 = this.id + ':' + PersistentConnection.nextConnectionId_++;\n var self_1 = this;\n var lastSessionId_1 = this.lastSessionId;\n var canceled_1 = false;\n var connection_1 = null;\n var closeFn_1 = function () {\n if (connection_1) {\n connection_1.close();\n }\n else {\n canceled_1 = true;\n onDisconnect_1();\n }\n };\n var sendRequestFn = function (msg) {\n util_3.assert(connection_1, \"sendRequest call when we're not connected not allowed.\");\n connection_1.sendRequest(msg);\n };\n this.realtime_ = {\n close: closeFn_1,\n sendRequest: sendRequestFn\n };\n var forceRefresh = this.forceTokenRefresh_;\n this.forceTokenRefresh_ = false;\n // First fetch auth token, and establish connection after fetching the token was successful\n this.authTokenProvider_\n .getToken(forceRefresh)\n .then(function (result) {\n if (!canceled_1) {\n util_4.log('getToken() completed. Creating connection.');\n self_1.authToken_ = result && result.accessToken;\n connection_1 = new Connection_1.Connection(connId_1, self_1.repoInfo_, onDataMessage_1, onReady_1, onDisconnect_1, \n /* onKill= */ function (reason) {\n util_4.warn(reason + ' (' + self_1.repoInfo_.toString() + ')');\n self_1.interrupt(SERVER_KILL_INTERRUPT_REASON);\n }, lastSessionId_1);\n }\n else {\n util_4.log('getToken() completed but was canceled');\n }\n })\n .then(null, function (error) {\n self_1.log_('Failed to get token: ' + error);\n if (!canceled_1) {\n if (util_6.CONSTANTS.NODE_ADMIN) {\n // This may be a critical error for the Admin Node.js SDK, so log a warning.\n // But getToken() may also just have temporarily failed, so we still want to\n // continue retrying.\n util_4.warn(error);\n }\n closeFn_1();\n }\n });\n }\n };\n /**\n * @param {string} reason\n */\n PersistentConnection.prototype.interrupt = function (reason) {\n util_4.log('Interrupting connection for reason: ' + reason);\n this.interruptReasons_[reason] = true;\n if (this.realtime_) {\n this.realtime_.close();\n }\n else {\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n this.establishConnectionTimer_ = null;\n }\n if (this.connected_) {\n this.onRealtimeDisconnect_();\n }\n }\n };\n /**\n * @param {string} reason\n */\n PersistentConnection.prototype.resume = function (reason) {\n util_4.log('Resuming connection for reason: ' + reason);\n delete this.interruptReasons_[reason];\n if (util_1.isEmpty(this.interruptReasons_)) {\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n };\n PersistentConnection.prototype.handleTimestamp_ = function (timestamp) {\n var delta = timestamp - new Date().getTime();\n this.onServerInfoUpdate_({ serverTimeOffset: delta });\n };\n PersistentConnection.prototype.cancelSentTransactions_ = function () {\n for (var i = 0; i < this.outstandingPuts_.length; i++) {\n var put = this.outstandingPuts_[i];\n if (put && /*hash*/ 'h' in put.request && put.queued) {\n if (put.onComplete)\n put.onComplete('disconnect');\n delete this.outstandingPuts_[i];\n this.outstandingPutCount_--;\n }\n }\n // Clean up array occasionally.\n if (this.outstandingPutCount_ === 0)\n this.outstandingPuts_ = [];\n };\n /**\n * @param {!string} pathString\n * @param {Array.<*>=} query\n * @private\n */\n PersistentConnection.prototype.onListenRevoked_ = function (pathString, query) {\n // Remove the listen and manufacture a \"permission_denied\" error for the failed listen.\n var queryId;\n if (!query) {\n queryId = 'default';\n }\n else {\n queryId = query.map(function (q) { return util_4.ObjectToUniqueKey(q); }).join('$');\n }\n var listen = this.removeListen_(pathString, queryId);\n if (listen && listen.onComplete)\n listen.onComplete('permission_denied');\n };\n /**\n * @param {!string} pathString\n * @param {!string} queryId\n * @return {{queries:Array., onComplete:function(string)}}\n * @private\n */\n PersistentConnection.prototype.removeListen_ = function (pathString, queryId) {\n var normalizedPathString = new Path_1.Path(pathString).toString(); // normalize path.\n var listen;\n if (this.listens_[normalizedPathString] !== undefined) {\n listen = this.listens_[normalizedPathString][queryId];\n delete this.listens_[normalizedPathString][queryId];\n if (util_1.getCount(this.listens_[normalizedPathString]) === 0) {\n delete this.listens_[normalizedPathString];\n }\n }\n else {\n // all listens for this path has already been removed\n listen = undefined;\n }\n return listen;\n };\n PersistentConnection.prototype.onAuthRevoked_ = function (statusCode, explanation) {\n util_4.log('Auth token revoked: ' + statusCode + '/' + explanation);\n this.authToken_ = null;\n this.forceTokenRefresh_ = true;\n this.realtime_.close();\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\n // We'll wait a couple times before logging the warning / increasing the\n // retry period since oauth tokens will report as \"invalid\" if they're\n // just expired. Plus there may be transient issues that resolve themselves.\n this.invalidAuthTokenCount_++;\n if (this.invalidAuthTokenCount_ >= INVALID_AUTH_TOKEN_THRESHOLD) {\n // Set a long reconnect delay because recovery is unlikely\n this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n // Notify the auth token provider that the token is invalid, which will log\n // a warning\n this.authTokenProvider_.notifyForInvalidToken();\n }\n }\n };\n PersistentConnection.prototype.onSecurityDebugPacket_ = function (body) {\n if (this.securityDebugCallback_) {\n this.securityDebugCallback_(body);\n }\n else {\n if ('msg' in body && typeof console !== 'undefined') {\n console.log('FIREBASE: ' + body['msg'].replace('\\n', '\\nFIREBASE: '));\n }\n }\n };\n PersistentConnection.prototype.restoreState_ = function () {\n var _this = this;\n //Re-authenticate ourselves if we have a credential stored.\n this.tryAuth();\n // Puts depend on having received the corresponding data update from the server before they complete, so we must\n // make sure to send listens before puts.\n util_1.forEach(this.listens_, function (pathString, queries) {\n util_1.forEach(queries, function (key, listenSpec) {\n _this.sendListen_(listenSpec);\n });\n });\n for (var i = 0; i < this.outstandingPuts_.length; i++) {\n if (this.outstandingPuts_[i])\n this.sendPut_(i);\n }\n while (this.onDisconnectRequestQueue_.length) {\n var request = this.onDisconnectRequestQueue_.shift();\n this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);\n }\n };\n /**\n * Sends client stats for first connection\n * @private\n */\n PersistentConnection.prototype.sendConnectStats_ = function () {\n var stats = {};\n var clientName = 'js';\n if (util_6.CONSTANTS.NODE_ADMIN) {\n clientName = 'admin_node';\n }\n else if (util_6.CONSTANTS.NODE_CLIENT) {\n clientName = 'node';\n }\n stats['sdk.' + clientName + '.' + app_1.default.SDK_VERSION.replace(/\\./g, '-')] = 1;\n if (util_7.isMobileCordova()) {\n stats['framework.cordova'] = 1;\n }\n else if (util_7.isReactNative()) {\n stats['framework.reactnative'] = 1;\n }\n this.reportStats(stats);\n };\n /**\n * @return {boolean}\n * @private\n */\n PersistentConnection.prototype.shouldReconnect_ = function () {\n var online = OnlineMonitor_1.OnlineMonitor.getInstance().currentlyOnline();\n return util_1.isEmpty(this.interruptReasons_) && online;\n };\n /**\n * @private\n */\n PersistentConnection.nextPersistentConnectionId_ = 0;\n /**\n * Counter for number of connections created. Mainly used for tagging in the logs\n * @type {number}\n * @private\n */\n PersistentConnection.nextConnectionId_ = 0;\n return PersistentConnection;\n}(ServerActions_1.ServerActions));\nexports.PersistentConnection = PersistentConnection;\n\n//# sourceMappingURL=PersistentConnection.js.map\n\n\n/***/ }),\n/* 52 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * Base class to be used if you want to emit events. Call the constructor with\n * the set of allowed event names.\n */\nvar EventEmitter = /** @class */ (function () {\n /**\n * @param {!Array.} allowedEvents_\n */\n function EventEmitter(allowedEvents_) {\n this.allowedEvents_ = allowedEvents_;\n this.listeners_ = {};\n util_1.assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');\n }\n /**\n * To be called by derived classes to trigger events.\n * @param {!string} eventType\n * @param {...*} var_args\n */\n EventEmitter.prototype.trigger = function (eventType) {\n var var_args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n var_args[_i - 1] = arguments[_i];\n }\n if (Array.isArray(this.listeners_[eventType])) {\n // Clone the list, since callbacks could add/remove listeners.\n var listeners = this.listeners_[eventType].slice();\n for (var i = 0; i < listeners.length; i++) {\n listeners[i].callback.apply(listeners[i].context, var_args);\n }\n }\n };\n EventEmitter.prototype.on = function (eventType, callback, context) {\n this.validateEventType_(eventType);\n this.listeners_[eventType] = this.listeners_[eventType] || [];\n this.listeners_[eventType].push({ callback: callback, context: context });\n var eventData = this.getInitialEvent(eventType);\n if (eventData) {\n callback.apply(context, eventData);\n }\n };\n EventEmitter.prototype.off = function (eventType, callback, context) {\n this.validateEventType_(eventType);\n var listeners = this.listeners_[eventType] || [];\n for (var i = 0; i < listeners.length; i++) {\n if (listeners[i].callback === callback &&\n (!context || context === listeners[i].context)) {\n listeners.splice(i, 1);\n return;\n }\n }\n };\n EventEmitter.prototype.validateEventType_ = function (eventType) {\n util_1.assert(this.allowedEvents_.find(function (et) {\n return et === eventType;\n }), 'Unknown event: ' + eventType);\n };\n return EventEmitter;\n}());\nexports.EventEmitter = EventEmitter;\n\n//# sourceMappingURL=EventEmitter.js.map\n\n\n/***/ }),\n/* 53 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(1);\nvar storage_1 = __webpack_require__(14);\nvar Constants_1 = __webpack_require__(15);\nvar TransportManager_1 = __webpack_require__(105);\n// Abort upgrade attempt if it takes longer than 60s.\nvar UPGRADE_TIMEOUT = 60000;\n// For some transports (WebSockets), we need to \"validate\" the transport by exchanging a few requests and responses.\n// If we haven't sent enough requests within 5s, we'll start sending noop ping requests.\nvar DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;\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)\n// then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout\n// but we've sent/received enough bytes, we don't cancel the connection.\nvar BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;\nvar BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;\nvar MESSAGE_TYPE = 't';\nvar MESSAGE_DATA = 'd';\nvar CONTROL_SHUTDOWN = 's';\nvar CONTROL_RESET = 'r';\nvar CONTROL_ERROR = 'e';\nvar CONTROL_PONG = 'o';\nvar SWITCH_ACK = 'a';\nvar END_TRANSMISSION = 'n';\nvar PING = 'p';\nvar SERVER_HELLO = 'h';\n/**\n * Creates a new real-time connection to the server using whichever method works\n * best in the current browser.\n *\n * @constructor\n */\nvar Connection = /** @class */ (function () {\n /**\n * @param {!string} id - an id for this connection\n * @param {!RepoInfo} repoInfo_ - the info for the endpoint to connect to\n * @param {function(Object)} onMessage_ - the callback to be triggered when a server-push message arrives\n * @param {function(number, string)} onReady_ - the callback to be triggered when this connection is ready to send messages.\n * @param {function()} onDisconnect_ - the callback to be triggered when a connection was lost\n * @param {function(string)} onKill_ - the callback to be triggered when this connection has permanently shut down.\n * @param {string=} lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server\n */\n function Connection(id, repoInfo_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {\n this.id = id;\n this.repoInfo_ = repoInfo_;\n this.onMessage_ = onMessage_;\n this.onReady_ = onReady_;\n this.onDisconnect_ = onDisconnect_;\n this.onKill_ = onKill_;\n this.lastSessionId = lastSessionId;\n this.connectionCount = 0;\n this.pendingDataMessages = [];\n this.state_ = 0 /* CONNECTING */;\n this.log_ = util_1.logWrapper('c:' + this.id + ':');\n this.transportManager_ = new TransportManager_1.TransportManager(repoInfo_);\n this.log_('Connection created');\n this.start_();\n }\n /**\n * Starts a connection attempt\n * @private\n */\n Connection.prototype.start_ = function () {\n var _this = this;\n var conn = this.transportManager_.initialTransport();\n this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, undefined, this.lastSessionId);\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;\n var onMessageReceived = this.connReceiver_(this.conn_);\n var onConnectionLost = this.disconnReceiver_(this.conn_);\n this.tx_ = this.conn_;\n this.rx_ = this.conn_;\n this.secondaryConn_ = null;\n this.isHealthy_ = false;\n /*\n * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.\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.\n * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should\n * still have the context of your originating frame.\n */\n setTimeout(function () {\n // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it\n _this.conn_ && _this.conn_.open(onMessageReceived, onConnectionLost);\n }, Math.floor(0));\n var healthyTimeout_ms = conn['healthyTimeout'] || 0;\n if (healthyTimeout_ms > 0) {\n this.healthyTimeout_ = util_1.setTimeoutNonBlocking(function () {\n _this.healthyTimeout_ = null;\n if (!_this.isHealthy_) {\n if (_this.conn_ &&\n _this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {\n _this.log_('Connection exceeded healthy timeout but has received ' +\n _this.conn_.bytesReceived +\n ' bytes. Marking connection healthy.');\n _this.isHealthy_ = true;\n _this.conn_.markConnectionHealthy();\n }\n else if (_this.conn_ &&\n _this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {\n _this.log_('Connection exceeded healthy timeout but has sent ' +\n _this.conn_.bytesSent +\n ' bytes. Leaving connection alive.');\n // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to\n // the server.\n }\n else {\n _this.log_('Closing unhealthy connection after timeout.');\n _this.close();\n }\n }\n }, Math.floor(healthyTimeout_ms));\n }\n };\n /**\n * @return {!string}\n * @private\n */\n Connection.prototype.nextTransportId_ = function () {\n return 'c:' + this.id + ':' + this.connectionCount++;\n };\n Connection.prototype.disconnReceiver_ = function (conn) {\n var _this = this;\n return function (everConnected) {\n if (conn === _this.conn_) {\n _this.onConnectionLost_(everConnected);\n }\n else if (conn === _this.secondaryConn_) {\n _this.log_('Secondary connection lost.');\n _this.onSecondaryConnectionLost_();\n }\n else {\n _this.log_('closing an old connection');\n }\n };\n };\n Connection.prototype.connReceiver_ = function (conn) {\n var _this = this;\n return function (message) {\n if (_this.state_ != 2 /* DISCONNECTED */) {\n if (conn === _this.rx_) {\n _this.onPrimaryMessageReceived_(message);\n }\n else if (conn === _this.secondaryConn_) {\n _this.onSecondaryMessageReceived_(message);\n }\n else {\n _this.log_('message on old connection');\n }\n }\n };\n };\n /**\n *\n * @param {Object} dataMsg An arbitrary data message to be sent to the server\n */\n Connection.prototype.sendRequest = function (dataMsg) {\n // wrap in a data message envelope and send it on\n var msg = { t: 'd', d: dataMsg };\n this.sendData_(msg);\n };\n Connection.prototype.tryCleanupConnection = function () {\n if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {\n this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);\n this.conn_ = this.secondaryConn_;\n this.secondaryConn_ = null;\n // the server will shutdown the old connection\n }\n };\n Connection.prototype.onSecondaryControl_ = function (controlData) {\n if (MESSAGE_TYPE in controlData) {\n var cmd = controlData[MESSAGE_TYPE];\n if (cmd === SWITCH_ACK) {\n this.upgradeIfSecondaryHealthy_();\n }\n else if (cmd === CONTROL_RESET) {\n // Most likely the session wasn't valid. Abandon the switch attempt\n this.log_('Got a reset on secondary, closing it');\n this.secondaryConn_.close();\n // If we were already using this connection for something, than we need to fully close\n if (this.tx_ === this.secondaryConn_ ||\n this.rx_ === this.secondaryConn_) {\n this.close();\n }\n }\n else if (cmd === CONTROL_PONG) {\n this.log_('got pong on secondary.');\n this.secondaryResponsesRequired_--;\n this.upgradeIfSecondaryHealthy_();\n }\n }\n };\n Connection.prototype.onSecondaryMessageReceived_ = function (parsedData) {\n var layer = util_1.requireKey('t', parsedData);\n var data = util_1.requireKey('d', parsedData);\n if (layer == 'c') {\n this.onSecondaryControl_(data);\n }\n else if (layer == 'd') {\n // got a data message, but we're still second connection. Need to buffer it up\n this.pendingDataMessages.push(data);\n }\n else {\n throw new Error('Unknown protocol layer: ' + layer);\n }\n };\n Connection.prototype.upgradeIfSecondaryHealthy_ = function () {\n if (this.secondaryResponsesRequired_ <= 0) {\n this.log_('Secondary connection is healthy.');\n this.isHealthy_ = true;\n this.secondaryConn_.markConnectionHealthy();\n this.proceedWithUpgrade_();\n }\n else {\n // Send a ping to make sure the connection is healthy.\n this.log_('sending ping on secondary.');\n this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });\n }\n };\n Connection.prototype.proceedWithUpgrade_ = function () {\n // tell this connection to consider itself open\n this.secondaryConn_.start();\n // send ack\n this.log_('sending client ack on secondary');\n this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });\n // send end packet on primary transport, switch to sending on this one\n // can receive on this one, buffer responses until end received on primary transport\n this.log_('Ending transmission on primary');\n this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });\n this.tx_ = this.secondaryConn_;\n this.tryCleanupConnection();\n };\n Connection.prototype.onPrimaryMessageReceived_ = function (parsedData) {\n // Must refer to parsedData properties in quotes, so closure doesn't touch them.\n var layer = util_1.requireKey('t', parsedData);\n var data = util_1.requireKey('d', parsedData);\n if (layer == 'c') {\n this.onControl_(data);\n }\n else if (layer == 'd') {\n this.onDataMessage_(data);\n }\n };\n Connection.prototype.onDataMessage_ = function (message) {\n this.onPrimaryResponse_();\n // We don't do anything with data messages, just kick them up a level\n this.onMessage_(message);\n };\n Connection.prototype.onPrimaryResponse_ = function () {\n if (!this.isHealthy_) {\n this.primaryResponsesRequired_--;\n if (this.primaryResponsesRequired_ <= 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n this.conn_.markConnectionHealthy();\n }\n }\n };\n Connection.prototype.onControl_ = function (controlData) {\n var cmd = util_1.requireKey(MESSAGE_TYPE, controlData);\n if (MESSAGE_DATA in controlData) {\n var payload = controlData[MESSAGE_DATA];\n if (cmd === SERVER_HELLO) {\n this.onHandshake_(payload);\n }\n else if (cmd === END_TRANSMISSION) {\n this.log_('recvd end transmission on primary');\n this.rx_ = this.secondaryConn_;\n for (var i = 0; i < this.pendingDataMessages.length; ++i) {\n this.onDataMessage_(this.pendingDataMessages[i]);\n }\n this.pendingDataMessages = [];\n this.tryCleanupConnection();\n }\n else if (cmd === CONTROL_SHUTDOWN) {\n // This was previously the 'onKill' callback passed to the lower-level connection\n // payload in this case is the reason for the shutdown. Generally a human-readable error\n this.onConnectionShutdown_(payload);\n }\n else if (cmd === CONTROL_RESET) {\n // payload in this case is the host we should contact\n this.onReset_(payload);\n }\n else if (cmd === CONTROL_ERROR) {\n util_1.error('Server Error: ' + payload);\n }\n else if (cmd === CONTROL_PONG) {\n this.log_('got pong on primary.');\n this.onPrimaryResponse_();\n this.sendPingOnPrimaryIfNecessary_();\n }\n else {\n util_1.error('Unknown control packet command: ' + cmd);\n }\n }\n };\n /**\n *\n * @param {Object} handshake The handshake data returned from the server\n * @private\n */\n Connection.prototype.onHandshake_ = function (handshake) {\n var timestamp = handshake.ts;\n var version = handshake.v;\n var host = handshake.h;\n this.sessionId = handshake.s;\n this.repoInfo_.updateHost(host);\n // if we've already closed the connection, then don't bother trying to progress further\n if (this.state_ == 0 /* CONNECTING */) {\n this.conn_.start();\n this.onConnectionEstablished_(this.conn_, timestamp);\n if (Constants_1.PROTOCOL_VERSION !== version) {\n util_1.warn('Protocol version mismatch detected');\n }\n // TODO: do we want to upgrade? when? maybe a delay?\n this.tryStartUpgrade_();\n }\n };\n Connection.prototype.tryStartUpgrade_ = function () {\n var conn = this.transportManager_.upgradeTransport();\n if (conn) {\n this.startUpgrade_(conn);\n }\n };\n Connection.prototype.startUpgrade_ = function (conn) {\n var _this = this;\n this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.sessionId);\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n this.secondaryResponsesRequired_ =\n conn['responsesRequiredToBeHealthy'] || 0;\n var onMessage = this.connReceiver_(this.secondaryConn_);\n var onDisconnect = this.disconnReceiver_(this.secondaryConn_);\n this.secondaryConn_.open(onMessage, onDisconnect);\n // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.\n util_1.setTimeoutNonBlocking(function () {\n if (_this.secondaryConn_) {\n _this.log_('Timed out trying to upgrade.');\n _this.secondaryConn_.close();\n }\n }, Math.floor(UPGRADE_TIMEOUT));\n };\n Connection.prototype.onReset_ = function (host) {\n this.log_('Reset packet received. New host: ' + host);\n this.repoInfo_.updateHost(host);\n // TODO: if we're already \"connected\", we need to trigger a disconnect at the next layer up.\n // We don't currently support resets after the connection has already been established\n if (this.state_ === 1 /* CONNECTED */) {\n this.close();\n }\n else {\n // Close whatever connections we have open and start again.\n this.closeConnections_();\n this.start_();\n }\n };\n Connection.prototype.onConnectionEstablished_ = function (conn, timestamp) {\n var _this = this;\n this.log_('Realtime connection established.');\n this.conn_ = conn;\n this.state_ = 1 /* CONNECTED */;\n if (this.onReady_) {\n this.onReady_(timestamp, this.sessionId);\n this.onReady_ = null;\n }\n // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,\n // send some pings.\n if (this.primaryResponsesRequired_ === 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n }\n else {\n util_1.setTimeoutNonBlocking(function () {\n _this.sendPingOnPrimaryIfNecessary_();\n }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));\n }\n };\n Connection.prototype.sendPingOnPrimaryIfNecessary_ = function () {\n // If the connection isn't considered healthy yet, we'll send a noop ping packet request.\n if (!this.isHealthy_ && this.state_ === 1 /* CONNECTED */) {\n this.log_('sending ping on primary.');\n this.sendData_({ t: 'c', d: { t: PING, d: {} } });\n }\n };\n Connection.prototype.onSecondaryConnectionLost_ = function () {\n var conn = this.secondaryConn_;\n this.secondaryConn_ = null;\n if (this.tx_ === conn || this.rx_ === conn) {\n // we are relying on this connection already in some capacity. Therefore, a failure is real\n this.close();\n }\n };\n /**\n *\n * @param {boolean} everConnected Whether or not the connection ever reached a server. Used to determine if\n * we should flush the host cache\n * @private\n */\n Connection.prototype.onConnectionLost_ = function (everConnected) {\n this.conn_ = null;\n // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting\n // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.\n if (!everConnected && this.state_ === 0 /* CONNECTING */) {\n this.log_('Realtime connection failed.');\n // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away\n if (this.repoInfo_.isCacheableHost()) {\n storage_1.PersistentStorage.remove('host:' + this.repoInfo_.host);\n // reset the internal host to what we would show the user, i.e. .firebaseio.com\n this.repoInfo_.internalHost = this.repoInfo_.host;\n }\n }\n else if (this.state_ === 1 /* CONNECTED */) {\n this.log_('Realtime connection lost.');\n }\n this.close();\n };\n /**\n *\n * @param {string} reason\n * @private\n */\n Connection.prototype.onConnectionShutdown_ = function (reason) {\n this.log_('Connection shutdown command received. Shutting down...');\n if (this.onKill_) {\n this.onKill_(reason);\n this.onKill_ = null;\n }\n // We intentionally don't want to fire onDisconnect (kill is a different case),\n // so clear the callback.\n this.onDisconnect_ = null;\n this.close();\n };\n Connection.prototype.sendData_ = function (data) {\n if (this.state_ !== 1 /* CONNECTED */) {\n throw 'Connection is not connected';\n }\n else {\n this.tx_.send(data);\n }\n };\n /**\n * Cleans up this connection, calling the appropriate callbacks\n */\n Connection.prototype.close = function () {\n if (this.state_ !== 2 /* DISCONNECTED */) {\n this.log_('Closing realtime connection.');\n this.state_ = 2 /* DISCONNECTED */;\n this.closeConnections_();\n if (this.onDisconnect_) {\n this.onDisconnect_();\n this.onDisconnect_ = null;\n }\n }\n };\n /**\n *\n * @private\n */\n Connection.prototype.closeConnections_ = function () {\n this.log_('Shutting down all connections');\n if (this.conn_) {\n this.conn_.close();\n this.conn_ = null;\n }\n if (this.secondaryConn_) {\n this.secondaryConn_.close();\n this.secondaryConn_ = null;\n }\n if (this.healthyTimeout_) {\n clearTimeout(this.healthyTimeout_);\n this.healthyTimeout_ = null;\n }\n };\n return Connection;\n}());\nexports.Connection = Connection;\n\n//# sourceMappingURL=Connection.js.map\n\n\n/***/ }),\n/* 54 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(1);\nvar CountedSet_1 = __webpack_require__(46);\nvar StatsManager_1 = __webpack_require__(26);\nvar PacketReceiver_1 = __webpack_require__(106);\nvar Constants_1 = __webpack_require__(15);\nvar util_2 = __webpack_require__(0);\nvar util_3 = __webpack_require__(0);\n// URL query parameters associated with longpolling\nexports.FIREBASE_LONGPOLL_START_PARAM = 'start';\nexports.FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';\nexports.FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';\nexports.FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';\nexports.FIREBASE_LONGPOLL_ID_PARAM = 'id';\nexports.FIREBASE_LONGPOLL_PW_PARAM = 'pw';\nexports.FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';\nexports.FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';\nexports.FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';\nexports.FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';\nexports.FIREBASE_LONGPOLL_DATA_PARAM = 'd';\nexports.FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM = 'disconn';\nexports.FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';\n//Data size constants.\n//TODO: Perf: the maximum length actually differs from browser to browser.\n// We should check what browser we're on and set accordingly.\nvar MAX_URL_DATA_SIZE = 1870;\nvar SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=\nvar MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;\n/**\n * Keepalive period\n * send a fresh request at minimum every 25 seconds. Opera has a maximum request\n * length of 30 seconds that we can't exceed.\n * @const\n * @type {number}\n */\nvar KEEPALIVE_REQUEST_INTERVAL = 25000;\n/**\n * How long to wait before aborting a long-polling connection attempt.\n * @const\n * @type {number}\n */\nvar LP_CONNECT_TIMEOUT = 30000;\n/**\n * This class manages a single long-polling connection.\n *\n * @constructor\n * @implements {Transport}\n */\nvar BrowserPollConnection = /** @class */ (function () {\n /**\n * @param {string} connId An identifier for this connection, used for logging\n * @param {RepoInfo} repoInfo The info for the endpoint to send data to.\n * @param {string=} transportSessionId Optional transportSessionid if we are reconnecting for an existing\n * transport session\n * @param {string=} lastSessionId Optional lastSessionId if the PersistentConnection has already created a\n * connection previously\n */\n function BrowserPollConnection(connId, repoInfo, transportSessionId, lastSessionId) {\n this.connId = connId;\n this.repoInfo = repoInfo;\n this.transportSessionId = transportSessionId;\n this.lastSessionId = lastSessionId;\n this.bytesSent = 0;\n this.bytesReceived = 0;\n this.everConnected_ = false;\n this.log_ = util_1.logWrapper(connId);\n this.stats_ = StatsManager_1.StatsManager.getCollection(repoInfo);\n this.urlFn = function (params) {\n return repoInfo.connectionURL(Constants_1.LONG_POLLING, params);\n };\n }\n /**\n *\n * @param {function(Object)} onMessage Callback when messages arrive\n * @param {function()} onDisconnect Callback with connection lost.\n */\n BrowserPollConnection.prototype.open = function (onMessage, onDisconnect) {\n var _this = this;\n this.curSegmentNum = 0;\n this.onDisconnect_ = onDisconnect;\n this.myPacketOrderer = new PacketReceiver_1.PacketReceiver(onMessage);\n this.isClosed_ = false;\n this.connectTimeoutTimer_ = setTimeout(function () {\n _this.log_('Timed out trying to connect.');\n // Make sure we clear the host cache\n _this.onClosed_();\n _this.connectTimeoutTimer_ = null;\n }, Math.floor(LP_CONNECT_TIMEOUT));\n // Ensure we delay the creation of the iframe until the DOM is loaded.\n util_1.executeWhenDOMReady(function () {\n if (_this.isClosed_)\n return;\n //Set up a callback that gets triggered once a connection is set up.\n _this.scriptTagHolder = new FirebaseIFrameScriptHolder(function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var command = args[0], arg1 = args[1], arg2 = args[2], arg3 = args[3], arg4 = args[4];\n _this.incrementIncomingBytes_(args);\n if (!_this.scriptTagHolder)\n return; // we closed the connection.\n if (_this.connectTimeoutTimer_) {\n clearTimeout(_this.connectTimeoutTimer_);\n _this.connectTimeoutTimer_ = null;\n }\n _this.everConnected_ = true;\n if (command == exports.FIREBASE_LONGPOLL_START_PARAM) {\n _this.id = arg1;\n _this.password = arg2;\n }\n else if (command === exports.FIREBASE_LONGPOLL_CLOSE_COMMAND) {\n // Don't clear the host cache. We got a response from the server, so we know it's reachable\n if (arg1) {\n // We aren't expecting any more data (other than what the server's already in the process of sending us\n // through our already open polls), so don't send any more.\n _this.scriptTagHolder.sendNewPolls = false;\n // arg1 in this case is the last response number sent by the server. We should try to receive\n // all of the responses up to this one before closing\n _this.myPacketOrderer.closeAfter(arg1, function () {\n _this.onClosed_();\n });\n }\n else {\n _this.onClosed_();\n }\n }\n else {\n throw new Error('Unrecognized command received: ' + command);\n }\n }, function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var pN = args[0], data = args[1];\n _this.incrementIncomingBytes_(args);\n _this.myPacketOrderer.handleResponse(pN, data);\n }, function () {\n _this.onClosed_();\n }, _this.urlFn);\n //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results\n //from cache.\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_START_PARAM] = 't';\n urlParams[exports.FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);\n if (_this.scriptTagHolder.uniqueCallbackIdentifier)\n urlParams[exports.FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] = _this.scriptTagHolder.uniqueCallbackIdentifier;\n urlParams[Constants_1.VERSION_PARAM] = Constants_1.PROTOCOL_VERSION;\n if (_this.transportSessionId) {\n urlParams[Constants_1.TRANSPORT_SESSION_PARAM] = _this.transportSessionId;\n }\n if (_this.lastSessionId) {\n urlParams[Constants_1.LAST_SESSION_PARAM] = _this.lastSessionId;\n }\n if (!util_3.isNodeSdk() &&\n typeof location !== 'undefined' &&\n location.href &&\n location.href.indexOf(Constants_1.FORGE_DOMAIN) !== -1) {\n urlParams[Constants_1.REFERER_PARAM] = Constants_1.FORGE_REF;\n }\n var connectURL = _this.urlFn(urlParams);\n _this.log_('Connecting via long-poll to ' + connectURL);\n _this.scriptTagHolder.addTag(connectURL, function () {\n /* do nothing */\n });\n });\n };\n /**\n * Call this when a handshake has completed successfully and we want to consider the connection established\n */\n BrowserPollConnection.prototype.start = function () {\n this.scriptTagHolder.startLongPoll(this.id, this.password);\n this.addDisconnectPingFrame(this.id, this.password);\n };\n /**\n * Forces long polling to be considered as a potential transport\n */\n BrowserPollConnection.forceAllow = function () {\n BrowserPollConnection.forceAllow_ = true;\n };\n /**\n * Forces longpolling to not be considered as a potential transport\n */\n BrowserPollConnection.forceDisallow = function () {\n BrowserPollConnection.forceDisallow_ = true;\n };\n // Static method, use string literal so it can be accessed in a generic way\n BrowserPollConnection.isAvailable = function () {\n // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in\n // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).\n return (BrowserPollConnection.forceAllow_ ||\n (!BrowserPollConnection.forceDisallow_ &&\n typeof document !== 'undefined' &&\n document.createElement != null &&\n !util_1.isChromeExtensionContentScript() &&\n !util_1.isWindowsStoreApp() &&\n !util_3.isNodeSdk()));\n };\n /**\n * No-op for polling\n */\n BrowserPollConnection.prototype.markConnectionHealthy = function () { };\n /**\n * Stops polling and cleans up the iframe\n * @private\n */\n BrowserPollConnection.prototype.shutdown_ = function () {\n this.isClosed_ = true;\n if (this.scriptTagHolder) {\n this.scriptTagHolder.close();\n this.scriptTagHolder = null;\n }\n //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.\n if (this.myDisconnFrame) {\n document.body.removeChild(this.myDisconnFrame);\n this.myDisconnFrame = null;\n }\n if (this.connectTimeoutTimer_) {\n clearTimeout(this.connectTimeoutTimer_);\n this.connectTimeoutTimer_ = null;\n }\n };\n /**\n * Triggered when this transport is closed\n * @private\n */\n BrowserPollConnection.prototype.onClosed_ = function () {\n if (!this.isClosed_) {\n this.log_('Longpoll is closing itself');\n this.shutdown_();\n if (this.onDisconnect_) {\n this.onDisconnect_(this.everConnected_);\n this.onDisconnect_ = null;\n }\n }\n };\n /**\n * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server\n * that we've left.\n */\n BrowserPollConnection.prototype.close = function () {\n if (!this.isClosed_) {\n this.log_('Longpoll is being closed.');\n this.shutdown_();\n }\n };\n /**\n * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then\n * broken into chunks (since URLs have a small maximum length).\n * @param {!Object} data The JSON data to transmit.\n */\n BrowserPollConnection.prototype.send = function (data) {\n var dataStr = util_2.stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n //first, lets get the base64-encoded data\n var base64data = util_2.base64Encode(dataStr);\n //We can only fit a certain amount in each URL, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n var dataSegs = util_1.splitStringBySize(base64data, MAX_PAYLOAD_SIZE);\n //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number\n //of segments so that we can reassemble the packet on the server.\n for (var i = 0; i < dataSegs.length; i++) {\n this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);\n this.curSegmentNum++;\n }\n };\n /**\n * This is how we notify the server that we're leaving.\n * We aren't able to send requests with DHTML on a window close event, but we can\n * trigger XHR requests in some browsers (everything but Opera basically).\n * @param {!string} id\n * @param {!string} pw\n */\n BrowserPollConnection.prototype.addDisconnectPingFrame = function (id, pw) {\n if (util_3.isNodeSdk())\n return;\n this.myDisconnFrame = document.createElement('iframe');\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = id;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = pw;\n this.myDisconnFrame.src = this.urlFn(urlParams);\n this.myDisconnFrame.style.display = 'none';\n document.body.appendChild(this.myDisconnFrame);\n };\n /**\n * Used to track the bytes received by this client\n * @param {*} args\n * @private\n */\n BrowserPollConnection.prototype.incrementIncomingBytes_ = function (args) {\n // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.\n var bytesReceived = util_2.stringify(args).length;\n this.bytesReceived += bytesReceived;\n this.stats_.incrementCounter('bytes_received', bytesReceived);\n };\n return BrowserPollConnection;\n}());\nexports.BrowserPollConnection = BrowserPollConnection;\n/*********************************************************************************************\n * A wrapper around an iframe that is used as a long-polling script holder.\n * @constructor\n *********************************************************************************************/\nvar FirebaseIFrameScriptHolder = /** @class */ (function () {\n /**\n * @param commandCB - The callback to be called when control commands are recevied from the server.\n * @param onMessageCB - The callback to be triggered when responses arrive from the server.\n * @param onDisconnect - The callback to be triggered when this tag holder is closed\n * @param urlFn - A function that provides the URL of the endpoint to send data to.\n */\n function FirebaseIFrameScriptHolder(commandCB, onMessageCB, onDisconnect, urlFn) {\n this.onDisconnect = onDisconnect;\n this.urlFn = urlFn;\n //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause\n //problems in some browsers.\n /**\n * @type {CountedSet.}\n */\n this.outstandingRequests = new CountedSet_1.CountedSet();\n //A queue of the pending segments waiting for transmission to the server.\n this.pendingSegs = [];\n //A serial number. We use this for two things:\n // 1) A way to ensure the browser doesn't cache responses to polls\n // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The\n // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute\n // JSONP code in the order it was added to the iframe.\n this.currentSerial = Math.floor(Math.random() * 100000000);\n // This gets set to false when we're \"closing down\" the connection (e.g. we're switching transports but there's still\n // incoming data from the server that we're waiting for).\n this.sendNewPolls = true;\n if (!util_3.isNodeSdk()) {\n //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the\n //iframes where we put the long-polling script tags. We have two callbacks:\n // 1) Command Callback - Triggered for control issues, like starting a connection.\n // 2) Message Callback - Triggered when new data arrives.\n this.uniqueCallbackIdentifier = util_1.LUIDGenerator();\n window[exports.FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;\n window[exports.FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] = onMessageCB;\n //Create an iframe for us to add script tags to.\n this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();\n // Set the iframe's contents.\n var script = '';\n // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient\n // for ie9, but ie8 needs to do it again in the document itself.\n if (this.myIFrame.src &&\n this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {\n var currentDomain = document.domain;\n script = '';\n }\n var iframeContents = '' + script + '';\n try {\n this.myIFrame.doc.open();\n this.myIFrame.doc.write(iframeContents);\n this.myIFrame.doc.close();\n }\n catch (e) {\n util_1.log('frame writing exception');\n if (e.stack) {\n util_1.log(e.stack);\n }\n util_1.log(e);\n }\n }\n else {\n this.commandCB = commandCB;\n this.onMessageCB = onMessageCB;\n }\n }\n /**\n * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can\n * actually use.\n * @private\n * @return {Element}\n */\n FirebaseIFrameScriptHolder.createIFrame_ = function () {\n var iframe = document.createElement('iframe');\n iframe.style.display = 'none';\n // This is necessary in order to initialize the document inside the iframe\n if (document.body) {\n document.body.appendChild(iframe);\n try {\n // If document.domain has been modified in IE, this will throw an error, and we need to set the\n // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute\n // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.\n var a = iframe.contentWindow.document;\n if (!a) {\n // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.\n util_1.log('No IE domain setting required');\n }\n }\n catch (e) {\n var domain = document.domain;\n iframe.src =\n \"javascript:void((function(){document.open();document.domain='\" +\n domain +\n \"';document.close();})())\";\n }\n }\n else {\n // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this\n // never gets hit.\n throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';\n }\n // Get the document of the iframe in a browser-specific way.\n if (iframe.contentDocument) {\n iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari\n }\n else if (iframe.contentWindow) {\n iframe.doc = iframe.contentWindow.document; // Internet Explorer\n }\n else if (iframe.document) {\n iframe.doc = iframe.document; //others?\n }\n return iframe;\n };\n /**\n * Cancel all outstanding queries and remove the frame.\n */\n FirebaseIFrameScriptHolder.prototype.close = function () {\n var _this = this;\n //Mark this iframe as dead, so no new requests are sent.\n this.alive = false;\n if (this.myIFrame) {\n //We have to actually remove all of the html inside this iframe before removing it from the\n //window, or IE will continue loading and executing the script tags we've already added, which\n //can lead to some errors being thrown. Setting innerHTML seems to be the easiest way to do this.\n this.myIFrame.doc.body.innerHTML = '';\n setTimeout(function () {\n if (_this.myIFrame !== null) {\n document.body.removeChild(_this.myIFrame);\n _this.myIFrame = null;\n }\n }, Math.floor(0));\n }\n if (util_3.isNodeSdk() && this.myID) {\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM] = 't';\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n var theURL = this.urlFn(urlParams);\n FirebaseIFrameScriptHolder.nodeRestRequest(theURL);\n }\n // Protect from being called recursively.\n var onDisconnect = this.onDisconnect;\n if (onDisconnect) {\n this.onDisconnect = null;\n onDisconnect();\n }\n };\n /**\n * Actually start the long-polling session by adding the first script tag(s) to the iframe.\n * @param {!string} id - The ID of this connection\n * @param {!string} pw - The password for this connection\n */\n FirebaseIFrameScriptHolder.prototype.startLongPoll = function (id, pw) {\n this.myID = id;\n this.myPW = pw;\n this.alive = true;\n //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.\n while (this.newRequest_()) { }\n };\n /**\n * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't\n * too many outstanding requests and we are still alive.\n *\n * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if\n * needed.\n */\n FirebaseIFrameScriptHolder.prototype.newRequest_ = function () {\n // We keep one outstanding request open all the time to receive data, but if we need to send data\n // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically\n // close the old request.\n if (this.alive &&\n this.sendNewPolls &&\n this.outstandingRequests.count() < (this.pendingSegs.length > 0 ? 2 : 1)) {\n //construct our url\n this.currentSerial++;\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n urlParams[exports.FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;\n var theURL = this.urlFn(urlParams);\n //Now add as much data as we can.\n var curDataString = '';\n var i = 0;\n while (this.pendingSegs.length > 0) {\n //first, lets see if the next segment will fit.\n var nextSeg = this.pendingSegs[0];\n if (nextSeg.d.length + SEG_HEADER_SIZE + curDataString.length <=\n MAX_URL_DATA_SIZE) {\n //great, the segment will fit. Lets append it.\n var theSeg = this.pendingSegs.shift();\n curDataString =\n curDataString +\n '&' +\n exports.FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +\n i +\n '=' +\n theSeg.seg +\n '&' +\n exports.FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +\n i +\n '=' +\n theSeg.ts +\n '&' +\n exports.FIREBASE_LONGPOLL_DATA_PARAM +\n i +\n '=' +\n theSeg.d;\n i++;\n }\n else {\n break;\n }\n }\n theURL = theURL + curDataString;\n this.addLongPollTag_(theURL, this.currentSerial);\n return true;\n }\n else {\n return false;\n }\n };\n /**\n * Queue a packet for transmission to the server.\n * @param segnum - A sequential id for this packet segment used for reassembly\n * @param totalsegs - The total number of segments in this packet\n * @param data - The data for this segment.\n */\n FirebaseIFrameScriptHolder.prototype.enqueueSegment = function (segnum, totalsegs, data) {\n //add this to the queue of segments to send.\n this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });\n //send the data immediately if there isn't already data being transmitted, unless\n //startLongPoll hasn't been called yet.\n if (this.alive) {\n this.newRequest_();\n }\n };\n /**\n * Add a script tag for a regular long-poll request.\n * @param {!string} url - The URL of the script tag.\n * @param {!number} serial - The serial number of the request.\n * @private\n */\n FirebaseIFrameScriptHolder.prototype.addLongPollTag_ = function (url, serial) {\n var _this = this;\n //remember that we sent this request.\n this.outstandingRequests.add(serial, 1);\n var doNewRequest = function () {\n _this.outstandingRequests.remove(serial);\n _this.newRequest_();\n };\n // If this request doesn't return on its own accord (by the server sending us some data), we'll\n // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.\n var keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));\n var readyStateCB = function () {\n // Request completed. Cancel the keepalive.\n clearTimeout(keepaliveTimeout);\n // Trigger a new request so we can continue receiving data.\n doNewRequest();\n };\n this.addTag(url, readyStateCB);\n };\n /**\n * Add an arbitrary script tag to the iframe.\n * @param {!string} url - The URL for the script tag source.\n * @param {!function()} loadCB - A callback to be triggered once the script has loaded.\n */\n FirebaseIFrameScriptHolder.prototype.addTag = function (url, loadCB) {\n var _this = this;\n if (util_3.isNodeSdk()) {\n this.doNodeLongPoll(url, loadCB);\n }\n else {\n setTimeout(function () {\n try {\n // if we're already closed, don't add this poll\n if (!_this.sendNewPolls)\n return;\n var newScript_1 = _this.myIFrame.doc.createElement('script');\n newScript_1.type = 'text/javascript';\n newScript_1.async = true;\n newScript_1.src = url;\n newScript_1.onload = newScript_1.onreadystatechange = function () {\n var rstate = newScript_1.readyState;\n if (!rstate || rstate === 'loaded' || rstate === 'complete') {\n newScript_1.onload = newScript_1.onreadystatechange = null;\n if (newScript_1.parentNode) {\n newScript_1.parentNode.removeChild(newScript_1);\n }\n loadCB();\n }\n };\n newScript_1.onerror = function () {\n util_1.log('Long-poll script failed to load: ' + url);\n _this.sendNewPolls = false;\n _this.close();\n };\n _this.myIFrame.doc.body.appendChild(newScript_1);\n }\n catch (e) {\n // TODO: we should make this error visible somehow\n }\n }, Math.floor(1));\n }\n };\n return FirebaseIFrameScriptHolder;\n}());\nexports.FirebaseIFrameScriptHolder = FirebaseIFrameScriptHolder;\n\n//# sourceMappingURL=BrowserPollConnection.js.map\n\n\n/***/ }),\n/* 55 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n/* WEBPACK VAR INJECTION */(function(process) {\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar app_1 = __webpack_require__(7);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar StatsManager_1 = __webpack_require__(26);\nvar Constants_1 = __webpack_require__(15);\nvar util_3 = __webpack_require__(0);\nvar storage_1 = __webpack_require__(14);\nvar util_4 = __webpack_require__(0);\nvar util_5 = __webpack_require__(0);\nvar WEBSOCKET_MAX_FRAME_SIZE = 16384;\nvar WEBSOCKET_KEEPALIVE_INTERVAL = 45000;\nvar WebSocketImpl = null;\nif (typeof MozWebSocket !== 'undefined') {\n WebSocketImpl = MozWebSocket;\n}\nelse if (typeof WebSocket !== 'undefined') {\n WebSocketImpl = WebSocket;\n}\nfunction setWebSocketImpl(impl) {\n WebSocketImpl = impl;\n}\nexports.setWebSocketImpl = setWebSocketImpl;\n/**\n * Create a new websocket connection with the given callbacks.\n * @constructor\n * @implements {Transport}\n */\nvar WebSocketConnection = /** @class */ (function () {\n /**\n * @param {string} connId identifier for this transport\n * @param {RepoInfo} repoInfo The info for the websocket endpoint.\n * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport\n * session\n * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection\n */\n function WebSocketConnection(connId, repoInfo, transportSessionId, lastSessionId) {\n this.connId = connId;\n this.keepaliveTimer = null;\n this.frames = null;\n this.totalFrames = 0;\n this.bytesSent = 0;\n this.bytesReceived = 0;\n this.log_ = util_2.logWrapper(this.connId);\n this.stats_ = StatsManager_1.StatsManager.getCollection(repoInfo);\n this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId);\n }\n /**\n * @param {RepoInfo} repoInfo The info for the websocket endpoint.\n * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport\n * session\n * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection\n * @return {string} connection url\n * @private\n */\n WebSocketConnection.connectionURL_ = function (repoInfo, transportSessionId, lastSessionId) {\n var urlParams = {};\n urlParams[Constants_1.VERSION_PARAM] = Constants_1.PROTOCOL_VERSION;\n if (!util_5.isNodeSdk() &&\n typeof location !== 'undefined' &&\n location.href &&\n location.href.indexOf(Constants_1.FORGE_DOMAIN) !== -1) {\n urlParams[Constants_1.REFERER_PARAM] = Constants_1.FORGE_REF;\n }\n if (transportSessionId) {\n urlParams[Constants_1.TRANSPORT_SESSION_PARAM] = transportSessionId;\n }\n if (lastSessionId) {\n urlParams[Constants_1.LAST_SESSION_PARAM] = lastSessionId;\n }\n return repoInfo.connectionURL(Constants_1.WEBSOCKET, urlParams);\n };\n /**\n *\n * @param onMessage Callback when messages arrive\n * @param onDisconnect Callback with connection lost.\n */\n WebSocketConnection.prototype.open = function (onMessage, onDisconnect) {\n var _this = this;\n this.onDisconnect = onDisconnect;\n this.onMessage = onMessage;\n this.log_('Websocket connecting to ' + this.connURL);\n this.everConnected_ = false;\n // Assume failure until proven otherwise.\n storage_1.PersistentStorage.set('previous_websocket_failure', true);\n try {\n if (util_5.isNodeSdk()) {\n var device = util_3.CONSTANTS.NODE_ADMIN ? 'AdminNode' : 'Node';\n // UA Format: Firebase////\n var options = {\n headers: {\n 'User-Agent': \"Firebase/\" + Constants_1.PROTOCOL_VERSION + \"/\" + app_1.default.SDK_VERSION + \"/\" + process.platform + \"/\" + device\n }\n };\n // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.\n var env = process['env'];\n var proxy = this.connURL.indexOf('wss://') == 0\n ? env['HTTPS_PROXY'] || env['https_proxy']\n : env['HTTP_PROXY'] || env['http_proxy'];\n if (proxy) {\n options['proxy'] = { origin: proxy };\n }\n this.mySock = new WebSocketImpl(this.connURL, [], options);\n }\n else {\n this.mySock = new WebSocketImpl(this.connURL);\n }\n }\n catch (e) {\n this.log_('Error instantiating WebSocket.');\n var error = e.message || e.data;\n if (error) {\n this.log_(error);\n }\n this.onClosed_();\n return;\n }\n this.mySock.onopen = function () {\n _this.log_('Websocket connected.');\n _this.everConnected_ = true;\n };\n this.mySock.onclose = function () {\n _this.log_('Websocket connection was disconnected.');\n _this.mySock = null;\n _this.onClosed_();\n };\n this.mySock.onmessage = function (m) {\n _this.handleIncomingFrame(m);\n };\n this.mySock.onerror = function (e) {\n _this.log_('WebSocket error. Closing connection.');\n var error = e.message || e.data;\n if (error) {\n _this.log_(error);\n }\n _this.onClosed_();\n };\n };\n /**\n * No-op for websockets, we don't need to do anything once the connection is confirmed as open\n */\n WebSocketConnection.prototype.start = function () { };\n WebSocketConnection.forceDisallow = function () {\n WebSocketConnection.forceDisallow_ = true;\n };\n WebSocketConnection.isAvailable = function () {\n var isOldAndroid = false;\n if (typeof navigator !== 'undefined' && navigator.userAgent) {\n var oldAndroidRegex = /Android ([0-9]{0,}\\.[0-9]{0,})/;\n var oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);\n if (oldAndroidMatch && oldAndroidMatch.length > 1) {\n if (parseFloat(oldAndroidMatch[1]) < 4.4) {\n isOldAndroid = true;\n }\n }\n }\n return (!isOldAndroid &&\n WebSocketImpl !== null &&\n !WebSocketConnection.forceDisallow_);\n };\n /**\n * Returns true if we previously failed to connect with this transport.\n * @return {boolean}\n */\n WebSocketConnection.previouslyFailed = function () {\n // If our persistent storage is actually only in-memory storage,\n // we default to assuming that it previously failed to be safe.\n return (storage_1.PersistentStorage.isInMemoryStorage ||\n storage_1.PersistentStorage.get('previous_websocket_failure') === true);\n };\n WebSocketConnection.prototype.markConnectionHealthy = function () {\n storage_1.PersistentStorage.remove('previous_websocket_failure');\n };\n WebSocketConnection.prototype.appendFrame_ = function (data) {\n this.frames.push(data);\n if (this.frames.length == this.totalFrames) {\n var fullMess = this.frames.join('');\n this.frames = null;\n var jsonMess = util_4.jsonEval(fullMess);\n //handle the message\n this.onMessage(jsonMess);\n }\n };\n /**\n * @param {number} frameCount The number of frames we are expecting from the server\n * @private\n */\n WebSocketConnection.prototype.handleNewFrameCount_ = function (frameCount) {\n this.totalFrames = frameCount;\n this.frames = [];\n };\n /**\n * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1\n * @param {!String} data\n * @return {?String} Any remaining data to be process, or null if there is none\n * @private\n */\n WebSocketConnection.prototype.extractFrameCount_ = function (data) {\n util_1.assert(this.frames === null, 'We already have a frame buffer');\n // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced\n // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508\n if (data.length <= 6) {\n var frameCount = Number(data);\n if (!isNaN(frameCount)) {\n this.handleNewFrameCount_(frameCount);\n return null;\n }\n }\n this.handleNewFrameCount_(1);\n return data;\n };\n /**\n * Process a websocket frame that has arrived from the server.\n * @param mess The frame data\n */\n WebSocketConnection.prototype.handleIncomingFrame = function (mess) {\n if (this.mySock === null)\n return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.\n var data = mess['data'];\n this.bytesReceived += data.length;\n this.stats_.incrementCounter('bytes_received', data.length);\n this.resetKeepAlive();\n if (this.frames !== null) {\n // we're buffering\n this.appendFrame_(data);\n }\n else {\n // try to parse out a frame count, otherwise, assume 1 and process it\n var remainingData = this.extractFrameCount_(data);\n if (remainingData !== null) {\n this.appendFrame_(remainingData);\n }\n }\n };\n /**\n * Send a message to the server\n * @param {Object} data The JSON object to transmit\n */\n WebSocketConnection.prototype.send = function (data) {\n this.resetKeepAlive();\n var dataStr = util_4.stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n //We can only fit a certain amount in each websocket frame, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n var dataSegs = util_2.splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);\n //Send the length header\n if (dataSegs.length > 1) {\n this.sendString_(String(dataSegs.length));\n }\n //Send the actual data in segments.\n for (var i = 0; i < dataSegs.length; i++) {\n this.sendString_(dataSegs[i]);\n }\n };\n WebSocketConnection.prototype.shutdown_ = function () {\n this.isClosed_ = true;\n if (this.keepaliveTimer) {\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = null;\n }\n if (this.mySock) {\n this.mySock.close();\n this.mySock = null;\n }\n };\n WebSocketConnection.prototype.onClosed_ = function () {\n if (!this.isClosed_) {\n this.log_('WebSocket is closing itself');\n this.shutdown_();\n // since this is an internal close, trigger the close listener\n if (this.onDisconnect) {\n this.onDisconnect(this.everConnected_);\n this.onDisconnect = null;\n }\n }\n };\n /**\n * External-facing close handler.\n * Close the websocket and kill the connection.\n */\n WebSocketConnection.prototype.close = function () {\n if (!this.isClosed_) {\n this.log_('WebSocket is being closed');\n this.shutdown_();\n }\n };\n /**\n * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after\n * the last activity.\n */\n WebSocketConnection.prototype.resetKeepAlive = function () {\n var _this = this;\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = setInterval(function () {\n //If there has been no websocket activity for a while, send a no-op\n if (_this.mySock) {\n _this.sendString_('0');\n }\n _this.resetKeepAlive();\n }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));\n };\n /**\n * Send a string over the websocket.\n *\n * @param {string} str String to send.\n * @private\n */\n WebSocketConnection.prototype.sendString_ = function (str) {\n // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()\n // calls for some unknown reason. We treat these as an error and disconnect.\n // See https://app.asana.com/0/58926111402292/68021340250410\n try {\n this.mySock.send(str);\n }\n catch (e) {\n this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');\n setTimeout(this.onClosed_.bind(this), 0);\n }\n };\n /**\n * Number of response before we consider the connection \"healthy.\"\n * @type {number}\n */\n WebSocketConnection.responsesRequiredToBeHealthy = 2;\n /**\n * Time to wait for the connection te become healthy before giving up.\n * @type {number}\n */\n WebSocketConnection.healthyTimeout = 30000;\n return WebSocketConnection;\n}());\nexports.WebSocketConnection = WebSocketConnection;\n\n//# sourceMappingURL=WebSocketConnection.js.map\n\n/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(28)))\n\n/***/ }),\n/* 56 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Interface defining the set of actions that can be performed against the Firebase server\n * (basically corresponds to our wire protocol).\n *\n * @interface\n */\nvar ServerActions = /** @class */ (function () {\n function ServerActions() {\n }\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n * @param {string=} hash\n */\n ServerActions.prototype.put = function (pathString, data, onComplete, hash) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, ?string)} onComplete\n * @param {string=} hash\n */\n ServerActions.prototype.merge = function (pathString, data, onComplete, hash) { };\n /**\n * Refreshes the auth token for the current connection.\n * @param {string} token The authentication token\n */\n ServerActions.prototype.refreshAuthToken = function (token) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectPut = function (pathString, data, onComplete) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectMerge = function (pathString, data, onComplete) { };\n /**\n * @param {string} pathString\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectCancel = function (pathString, onComplete) { };\n /**\n * @param {Object.} stats\n */\n ServerActions.prototype.reportStats = function (stats) { };\n return ServerActions;\n}());\nexports.ServerActions = ServerActions;\n\n//# sourceMappingURL=ServerActions.js.map\n\n\n/***/ }),\n/* 57 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar IndexedFilter_1 = __webpack_require__(25);\nvar PriorityIndex_1 = __webpack_require__(4);\nvar Node_1 = __webpack_require__(6);\nvar ChildrenNode_1 = __webpack_require__(5);\n/**\n * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node\n *\n * @constructor\n * @implements {NodeFilter}\n */\nvar RangedFilter = /** @class */ (function () {\n /**\n * @param {!QueryParams} params\n */\n function RangedFilter(params) {\n this.indexedFilter_ = new IndexedFilter_1.IndexedFilter(params.getIndex());\n this.index_ = params.getIndex();\n this.startPost_ = RangedFilter.getStartPost_(params);\n this.endPost_ = RangedFilter.getEndPost_(params);\n }\n /**\n * @return {!NamedNode}\n */\n RangedFilter.prototype.getStartPost = function () {\n return this.startPost_;\n };\n /**\n * @return {!NamedNode}\n */\n RangedFilter.prototype.getEndPost = function () {\n return this.endPost_;\n };\n /**\n * @param {!NamedNode} node\n * @return {boolean}\n */\n RangedFilter.prototype.matches = function (node) {\n return (this.index_.compare(this.getStartPost(), node) <= 0 &&\n this.index_.compare(node, this.getEndPost()) <= 0);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n if (!this.matches(new Node_1.NamedNode(key, newChild))) {\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n if (newSnap.isLeafNode()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n newSnap = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n var filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var self = this;\n newSnap.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n if (!self.matches(new Node_1.NamedNode(key, childNode))) {\n filtered = filtered.updateImmediateChild(key, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n });\n return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n // Don't support priorities on queries\n return oldSnap;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.filtersNodes = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.getIndexedFilter = function () {\n return this.indexedFilter_;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @param {!QueryParams} params\n * @return {!NamedNode}\n * @private\n */\n RangedFilter.getStartPost_ = function (params) {\n if (params.hasStart()) {\n var startName = params.getIndexStartName();\n return params.getIndex().makePost(params.getIndexStartValue(), startName);\n }\n else {\n return params.getIndex().minPost();\n }\n };\n /**\n * @param {!QueryParams} params\n * @return {!NamedNode}\n * @private\n */\n RangedFilter.getEndPost_ = function (params) {\n if (params.hasEnd()) {\n var endName = params.getIndexEndName();\n return params.getIndex().makePost(params.getIndexEndValue(), endName);\n }\n else {\n return params.getIndex().maxPost();\n }\n };\n return RangedFilter;\n}());\nexports.RangedFilter = RangedFilter;\n\n//# sourceMappingURL=RangedFilter.js.map\n\n\n/***/ }),\n/* 58 */,\n/* 59 */,\n/* 60 */,\n/* 61 */,\n/* 62 */,\n/* 63 */,\n/* 64 */,\n/* 65 */,\n/* 66 */,\n/* 67 */,\n/* 68 */,\n/* 69 */,\n/* 70 */,\n/* 71 */,\n/* 72 */,\n/* 73 */,\n/* 74 */,\n/* 75 */,\n/* 76 */,\n/* 77 */,\n/* 78 */,\n/* 79 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nmodule.exports = __webpack_require__(80);\n\n\n/***/ }),\n/* 80 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar app_1 = __webpack_require__(7);\nvar Database_1 = __webpack_require__(33);\nexports.Database = Database_1.Database;\nvar Query_1 = __webpack_require__(37);\nexports.Query = Query_1.Query;\nvar Reference_1 = __webpack_require__(22);\nexports.Reference = Reference_1.Reference;\nvar util_1 = __webpack_require__(1);\nexports.enableLogging = util_1.enableLogging;\nvar RepoManager_1 = __webpack_require__(27);\nvar INTERNAL = __webpack_require__(112);\nvar TEST_ACCESS = __webpack_require__(113);\nvar util_2 = __webpack_require__(0);\nvar ServerValue = Database_1.Database.ServerValue;\nexports.ServerValue = ServerValue;\nfunction registerDatabase(instance) {\n // Register the Database Service with the 'firebase' namespace.\n var namespace = instance.INTERNAL.registerService('database', function (app, unused, url) { return RepoManager_1.RepoManager.getInstance().databaseFromApp(app, url); }, \n // firebase.database namespace properties\n {\n Reference: Reference_1.Reference,\n Query: Query_1.Query,\n Database: Database_1.Database,\n enableLogging: util_1.enableLogging,\n INTERNAL: INTERNAL,\n ServerValue: ServerValue,\n TEST_ACCESS: TEST_ACCESS\n }, null, true);\n if (util_2.isNodeSdk()) {\n module.exports = namespace;\n }\n}\nexports.registerDatabase = registerDatabase;\nregisterDatabase(app_1.default);\nvar DataSnapshot_1 = __webpack_require__(23);\nexports.DataSnapshot = DataSnapshot_1.DataSnapshot;\nvar onDisconnect_1 = __webpack_require__(36);\nexports.OnDisconnect = onDisconnect_1.OnDisconnect;\n\n//# sourceMappingURL=index.js.map\n\n\n/***/ }),\n/* 81 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * Wraps a DOM Storage object and:\n * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.\n * - prefixes names with \"firebase:\" to avoid collisions with app data.\n *\n * We automatically (see storage.js) create two such wrappers, one for sessionStorage,\n * and one for localStorage.\n *\n * @constructor\n */\nvar DOMStorageWrapper = /** @class */ (function () {\n /**\n * @param {Storage} domStorage_ The underlying storage object (e.g. localStorage or sessionStorage)\n */\n function DOMStorageWrapper(domStorage_) {\n this.domStorage_ = domStorage_;\n // Use a prefix to avoid collisions with other stuff saved by the app.\n this.prefix_ = 'firebase:';\n }\n /**\n * @param {string} key The key to save the value under\n * @param {?Object} value The value being stored, or null to remove the key.\n */\n DOMStorageWrapper.prototype.set = function (key, value) {\n if (value == null) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n }\n else {\n this.domStorage_.setItem(this.prefixedName_(key), util_1.stringify(value));\n }\n };\n /**\n * @param {string} key\n * @return {*} The value that was stored under this key, or null\n */\n DOMStorageWrapper.prototype.get = function (key) {\n var storedVal = this.domStorage_.getItem(this.prefixedName_(key));\n if (storedVal == null) {\n return null;\n }\n else {\n return util_1.jsonEval(storedVal);\n }\n };\n /**\n * @param {string} key\n */\n DOMStorageWrapper.prototype.remove = function (key) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n };\n /**\n * @param {string} name\n * @return {string}\n */\n DOMStorageWrapper.prototype.prefixedName_ = function (name) {\n return this.prefix_ + name;\n };\n DOMStorageWrapper.prototype.toString = function () {\n return this.domStorage_.toString();\n };\n return DOMStorageWrapper;\n}());\nexports.DOMStorageWrapper = DOMStorageWrapper;\n\n//# sourceMappingURL=DOMStorageWrapper.js.map\n\n\n/***/ }),\n/* 82 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * An in-memory storage implementation that matches the API of DOMStorageWrapper\n * (TODO: create interface for both to implement).\n *\n * @constructor\n */\nvar MemoryStorage = /** @class */ (function () {\n function MemoryStorage() {\n this.cache_ = {};\n this.isInMemoryStorage = true;\n }\n MemoryStorage.prototype.set = function (key, value) {\n if (value == null) {\n delete this.cache_[key];\n }\n else {\n this.cache_[key] = value;\n }\n };\n MemoryStorage.prototype.get = function (key) {\n if (util_1.contains(this.cache_, key)) {\n return this.cache_[key];\n }\n return null;\n };\n MemoryStorage.prototype.remove = function (key) {\n delete this.cache_[key];\n };\n return MemoryStorage;\n}());\nexports.MemoryStorage = MemoryStorage;\n\n//# sourceMappingURL=MemoryStorage.js.map\n\n\n/***/ }),\n/* 83 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar TransactionResult = /** @class */ (function () {\n /**\n * A type for the resolve value of Firebase.transaction.\n * @constructor\n * @dict\n * @param {boolean} committed\n * @param {DataSnapshot} snapshot\n */\n function TransactionResult(committed, snapshot) {\n this.committed = committed;\n this.snapshot = snapshot;\n }\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n TransactionResult.prototype.toJSON = function () {\n util_1.validateArgCount('TransactionResult.toJSON', 0, 1, arguments.length);\n return { committed: this.committed, snapshot: this.snapshot.toJSON() };\n };\n return TransactionResult;\n}());\nexports.TransactionResult = TransactionResult;\n\n//# sourceMappingURL=TransactionResult.js.map\n\n\n/***/ }),\n/* 84 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * Fancy ID generator that creates 20-character string identifiers with the\n * following properties:\n *\n * 1. They're based on timestamp so that they sort *after* any existing ids.\n * 2. They contain 72-bits of random data after the timestamp so that IDs won't\n * collide with other clients' IDs.\n * 3. They sort *lexicographically* (so the timestamp is converted to characters\n * that will sort properly).\n * 4. They're monotonically increasing. Even if you generate more than one in\n * the same timestamp, the latter ones will sort after the former ones. We do\n * this by using the previous random bits but \"incrementing\" them by 1 (only\n * in the case of a timestamp collision).\n */\nexports.nextPushId = (function () {\n // Modeled after base64 web-safe chars, but ordered by ASCII.\n var PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';\n // Timestamp of last push, used to prevent local collisions if you push twice\n // in one ms.\n var lastPushTime = 0;\n // We generate 72-bits of randomness which get turned into 12 characters and\n // appended to the timestamp to prevent collisions with other clients. We\n // store the last characters we generated because in the event of a collision,\n // we'll use those same characters except \"incremented\" by one.\n var lastRandChars = [];\n return function (now) {\n var duplicateTime = now === lastPushTime;\n lastPushTime = now;\n var i;\n var timeStampChars = new Array(8);\n for (i = 7; i >= 0; i--) {\n timeStampChars[i] = PUSH_CHARS.charAt(now % 64);\n // NOTE: Can't use << here because javascript will convert to int and lose\n // the upper bits.\n now = Math.floor(now / 64);\n }\n util_1.assert(now === 0, 'Cannot push at time == 0');\n var id = timeStampChars.join('');\n if (!duplicateTime) {\n for (i = 0; i < 12; i++) {\n lastRandChars[i] = Math.floor(Math.random() * 64);\n }\n }\n else {\n // If the timestamp hasn't changed since last push, use the same random\n // number, except incremented by 1.\n for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {\n lastRandChars[i] = 0;\n }\n lastRandChars[i]++;\n }\n for (i = 0; i < 12; i++) {\n id += PUSH_CHARS.charAt(lastRandChars[i]);\n }\n util_1.assert(id.length === 20, 'nextPushId: Length should be 20.');\n return id;\n };\n})();\n\n//# sourceMappingURL=NextPushId.js.map\n\n\n/***/ }),\n/* 85 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar DataSnapshot_1 = __webpack_require__(23);\nvar Event_1 = __webpack_require__(86);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\n/**\n * Represents registration for 'value' events.\n */\nvar ValueEventRegistration = /** @class */ (function () {\n /**\n * @param {?function(!DataSnapshot)} callback_\n * @param {?function(Error)} cancelCallback_\n * @param {?Object} context_\n */\n function ValueEventRegistration(callback_, cancelCallback_, context_) {\n this.callback_ = callback_;\n this.cancelCallback_ = cancelCallback_;\n this.context_ = context_;\n }\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.respondsTo = function (eventType) {\n return eventType === 'value';\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.createEvent = function (change, query) {\n var index = query.getQueryParams().getIndex();\n return new Event_1.DataEvent('value', this, new DataSnapshot_1.DataSnapshot(change.snapshotNode, query.getRef(), index));\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.getEventRunner = function (eventData) {\n var ctx = this.context_;\n if (eventData.getEventType() === 'cancel') {\n util_2.assert(this.cancelCallback_, 'Raising a cancel event on a listener with no cancel callback');\n var cancelCB_1 = this.cancelCallback_;\n return function () {\n // We know that error exists, we checked above that this is a cancel event\n cancelCB_1.call(ctx, eventData.error);\n };\n }\n else {\n var cb_1 = this.callback_;\n return function () {\n cb_1.call(ctx, eventData.snapshot);\n };\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.createCancelEvent = function (error, path) {\n if (this.cancelCallback_) {\n return new Event_1.CancelEvent(this, error, path);\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.matches = function (other) {\n if (!(other instanceof ValueEventRegistration)) {\n return false;\n }\n else if (!other.callback_ || !this.callback_) {\n // If no callback specified, we consider it to match any callback.\n return true;\n }\n else {\n return (other.callback_ === this.callback_ && other.context_ === this.context_);\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.hasAnyCallback = function () {\n return this.callback_ !== null;\n };\n return ValueEventRegistration;\n}());\nexports.ValueEventRegistration = ValueEventRegistration;\n/**\n * Represents the registration of 1 or more child_xxx events.\n *\n * Currently, it is always exactly 1 child_xxx event, but the idea is we might let you\n * register a group of callbacks together in the future.\n *\n * @constructor\n * @implements {EventRegistration}\n */\nvar ChildEventRegistration = /** @class */ (function () {\n /**\n * @param {?Object.} callbacks_\n * @param {?function(Error)} cancelCallback_\n * @param {Object=} context_\n */\n function ChildEventRegistration(callbacks_, cancelCallback_, context_) {\n this.callbacks_ = callbacks_;\n this.cancelCallback_ = cancelCallback_;\n this.context_ = context_;\n }\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.respondsTo = function (eventType) {\n var eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;\n eventToCheck =\n eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;\n return util_1.contains(this.callbacks_, eventToCheck);\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.createCancelEvent = function (error, path) {\n if (this.cancelCallback_) {\n return new Event_1.CancelEvent(this, error, path);\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.createEvent = function (change, query) {\n util_2.assert(change.childName != null, 'Child events should have a childName.');\n var ref = query.getRef().child(/** @type {!string} */ (change.childName));\n var index = query.getQueryParams().getIndex();\n return new Event_1.DataEvent(change.type, this, new DataSnapshot_1.DataSnapshot(change.snapshotNode, ref, index), change.prevName);\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.getEventRunner = function (eventData) {\n var ctx = this.context_;\n if (eventData.getEventType() === 'cancel') {\n util_2.assert(this.cancelCallback_, 'Raising a cancel event on a listener with no cancel callback');\n var cancelCB_2 = this.cancelCallback_;\n return function () {\n // We know that error exists, we checked above that this is a cancel event\n cancelCB_2.call(ctx, eventData.error);\n };\n }\n else {\n var cb_2 = this.callbacks_[eventData.eventType];\n return function () {\n cb_2.call(ctx, eventData.snapshot, eventData.prevName);\n };\n }\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.matches = function (other) {\n if (other instanceof ChildEventRegistration) {\n if (!this.callbacks_ || !other.callbacks_) {\n return true;\n }\n else if (this.context_ === other.context_) {\n var otherCount = util_1.getCount(other.callbacks_);\n var thisCount = util_1.getCount(this.callbacks_);\n if (otherCount === thisCount) {\n // If count is 1, do an exact match on eventType, if either is defined but null, it's a match.\n // If event types don't match, not a match\n // If count is not 1, exact match across all\n if (otherCount === 1) {\n var otherKey /** @type {!string} */ = util_1.getAnyKey(other.callbacks_);\n var thisKey /** @type {!string} */ = util_1.getAnyKey(this.callbacks_);\n return (thisKey === otherKey &&\n (!other.callbacks_[otherKey] ||\n !this.callbacks_[thisKey] ||\n other.callbacks_[otherKey] === this.callbacks_[thisKey]));\n }\n else {\n // Exact match on each key.\n return util_1.every(this.callbacks_, function (eventType, cb) { return other.callbacks_[eventType] === cb; });\n }\n }\n }\n }\n return false;\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.hasAnyCallback = function () {\n return this.callbacks_ !== null;\n };\n return ChildEventRegistration;\n}());\nexports.ChildEventRegistration = ChildEventRegistration;\n\n//# sourceMappingURL=EventRegistration.js.map\n\n\n/***/ }),\n/* 86 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * Encapsulates the data needed to raise an event\n * @implements {Event}\n */\nvar DataEvent = /** @class */ (function () {\n /**\n * @param {!string} eventType One of: value, child_added, child_changed, child_moved, child_removed\n * @param {!EventRegistration} eventRegistration The function to call to with the event data. User provided\n * @param {!DataSnapshot} snapshot The data backing the event\n * @param {?string=} prevName Optional, the name of the previous child for child_* events.\n */\n function DataEvent(eventType, eventRegistration, snapshot, prevName) {\n this.eventType = eventType;\n this.eventRegistration = eventRegistration;\n this.snapshot = snapshot;\n this.prevName = prevName;\n }\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getPath = function () {\n var ref = this.snapshot.getRef();\n if (this.eventType === 'value') {\n return ref.path;\n }\n else {\n return ref.getParent().path;\n }\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getEventType = function () {\n return this.eventType;\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getEventRunner = function () {\n return this.eventRegistration.getEventRunner(this);\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.toString = function () {\n return (this.getPath().toString() +\n ':' +\n this.eventType +\n ':' +\n util_1.stringify(this.snapshot.exportVal()));\n };\n return DataEvent;\n}());\nexports.DataEvent = DataEvent;\nvar CancelEvent = /** @class */ (function () {\n /**\n * @param {EventRegistration} eventRegistration\n * @param {Error} error\n * @param {!Path} path\n */\n function CancelEvent(eventRegistration, error, path) {\n this.eventRegistration = eventRegistration;\n this.error = error;\n this.path = path;\n }\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getPath = function () {\n return this.path;\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getEventType = function () {\n return 'cancel';\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getEventRunner = function () {\n return this.eventRegistration.getEventRunner(this);\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.toString = function () {\n return this.path.toString() + ':cancel';\n };\n return CancelEvent;\n}());\nexports.CancelEvent = CancelEvent;\n\n//# sourceMappingURL=Event.js.map\n\n\n/***/ }),\n/* 87 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar AckUserWrite_1 = __webpack_require__(88);\nvar ChildrenNode_1 = __webpack_require__(5);\nvar util_3 = __webpack_require__(0);\nvar ImmutableTree_1 = __webpack_require__(24);\nvar ListenComplete_1 = __webpack_require__(89);\nvar Merge_1 = __webpack_require__(90);\nvar Operation_1 = __webpack_require__(9);\nvar Overwrite_1 = __webpack_require__(47);\nvar Path_1 = __webpack_require__(3);\nvar SyncPoint_1 = __webpack_require__(48);\nvar WriteTree_1 = __webpack_require__(96);\n/**\n * SyncTree is the central class for managing event callback registration, data caching, views\n * (query processing), and event generation. There are typically two SyncTree instances for\n * each Repo, one for the normal Firebase data, and one for the .info data.\n *\n * It has a number of responsibilities, including:\n * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).\n * - Applying and caching data changes for user set(), transaction(), and update() calls\n * (applyUserOverwrite(), applyUserMerge()).\n * - Applying and caching data changes for server data changes (applyServerOverwrite(),\n * applyServerMerge()).\n * - Generating user-facing events for server and user changes (all of the apply* methods\n * return the set of events that need to be raised as a result).\n * - Maintaining the appropriate set of server listens to ensure we are always subscribed\n * to the correct set of paths and queries to satisfy the current set of user event\n * callbacks (listens are started/stopped using the provided listenProvider).\n *\n * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual\n * events are returned to the caller rather than raised synchronously.\n *\n * @constructor\n */\nvar SyncTree = /** @class */ (function () {\n /**\n * @param {!ListenProvider} listenProvider_ Used by SyncTree to start / stop listening\n * to server data.\n */\n function SyncTree(listenProvider_) {\n this.listenProvider_ = listenProvider_;\n /**\n * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.\n * @type {!ImmutableTree.}\n * @private\n */\n this.syncPointTree_ = ImmutableTree_1.ImmutableTree.Empty;\n /**\n * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).\n * @type {!WriteTree}\n * @private\n */\n this.pendingWriteTree_ = new WriteTree_1.WriteTree();\n this.tagToQueryMap_ = {};\n this.queryToTagMap_ = {};\n }\n /**\n * Apply the data changes for a user-generated set() or transaction() call.\n *\n * @param {!Path} path\n * @param {!Node} newData\n * @param {number} writeId\n * @param {boolean=} visible\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyUserOverwrite = function (path, newData, writeId, visible) {\n // Record pending write.\n this.pendingWriteTree_.addOverwrite(path, newData, writeId, visible);\n if (!visible) {\n return [];\n }\n else {\n return this.applyOperationToSyncPoints_(new Overwrite_1.Overwrite(Operation_1.OperationSource.User, path, newData));\n }\n };\n /**\n * Apply the data from a user-generated update() call\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} writeId\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyUserMerge = function (path, changedChildren, writeId) {\n // Record pending merge.\n this.pendingWriteTree_.addMerge(path, changedChildren, writeId);\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n return this.applyOperationToSyncPoints_(new Merge_1.Merge(Operation_1.OperationSource.User, path, changeTree));\n };\n /**\n * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().\n *\n * @param {!number} writeId\n * @param {boolean=} revert True if the given write failed and needs to be reverted\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.ackUserWrite = function (writeId, revert) {\n if (revert === void 0) { revert = false; }\n var write = this.pendingWriteTree_.getWrite(writeId);\n var needToReevaluate = this.pendingWriteTree_.removeWrite(writeId);\n if (!needToReevaluate) {\n return [];\n }\n else {\n var affectedTree_1 = ImmutableTree_1.ImmutableTree.Empty;\n if (write.snap != null) {\n // overwrite\n affectedTree_1 = affectedTree_1.set(Path_1.Path.Empty, true);\n }\n else {\n util_3.forEach(write.children, function (pathString, node) {\n affectedTree_1 = affectedTree_1.set(new Path_1.Path(pathString), node);\n });\n }\n return this.applyOperationToSyncPoints_(new AckUserWrite_1.AckUserWrite(write.path, affectedTree_1, revert));\n }\n };\n /**\n * Apply new server data for the specified path..\n *\n * @param {!Path} path\n * @param {!Node} newData\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyServerOverwrite = function (path, newData) {\n return this.applyOperationToSyncPoints_(new Overwrite_1.Overwrite(Operation_1.OperationSource.Server, path, newData));\n };\n /**\n * Apply new server data to be merged in at the specified path.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyServerMerge = function (path, changedChildren) {\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n return this.applyOperationToSyncPoints_(new Merge_1.Merge(Operation_1.OperationSource.Server, path, changeTree));\n };\n /**\n * Apply a listen complete for a query\n *\n * @param {!Path} path\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyListenComplete = function (path) {\n return this.applyOperationToSyncPoints_(new ListenComplete_1.ListenComplete(Operation_1.OperationSource.Server, path));\n };\n /**\n * Apply new server data for the specified tagged query.\n *\n * @param {!Path} path\n * @param {!Node} snap\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedQueryOverwrite = function (path, snap, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey != null) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var op = new Overwrite_1.Overwrite(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath, snap);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // Query must have been removed already\n return [];\n }\n };\n /**\n * Apply server data to be merged in for the specified tagged query.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedQueryMerge = function (path, changedChildren, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n var op = new Merge_1.Merge(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath, changeTree);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n };\n /**\n * Apply a listen complete for a tagged query\n *\n * @param {!Path} path\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedListenComplete = function (path, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var op = new ListenComplete_1.ListenComplete(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n };\n /**\n * Add an event callback for the specified query.\n *\n * @param {!Query} query\n * @param {!EventRegistration} eventRegistration\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.addEventRegistration = function (query, eventRegistration) {\n var path = query.path;\n var serverCache = null;\n var foundAncestorDefaultView = false;\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\n this.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) {\n var relativePath = Path_1.Path.relativePath(pathToSyncPoint, path);\n serverCache = serverCache || sp.getCompleteServerCache(relativePath);\n foundAncestorDefaultView =\n foundAncestorDefaultView || sp.hasCompleteView();\n });\n var syncPoint = this.syncPointTree_.get(path);\n if (!syncPoint) {\n syncPoint = new SyncPoint_1.SyncPoint();\n this.syncPointTree_ = this.syncPointTree_.set(path, syncPoint);\n }\n else {\n foundAncestorDefaultView =\n foundAncestorDefaultView || syncPoint.hasCompleteView();\n serverCache = serverCache || syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var serverCacheComplete;\n if (serverCache != null) {\n serverCacheComplete = true;\n }\n else {\n serverCacheComplete = false;\n serverCache = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var subtree = this.syncPointTree_.subtree(path);\n subtree.foreachChild(function (childName, childSyncPoint) {\n var completeCache = childSyncPoint.getCompleteServerCache(Path_1.Path.Empty);\n if (completeCache) {\n serverCache = serverCache.updateImmediateChild(childName, completeCache);\n }\n });\n }\n var viewAlreadyExists = syncPoint.viewExistsForQuery(query);\n if (!viewAlreadyExists && !query.getQueryParams().loadsAllData()) {\n // We need to track a tag for this query\n var queryKey = SyncTree.makeQueryKey_(query);\n util_1.assert(!(queryKey in this.queryToTagMap_), 'View does not exist, but we have a tag');\n var tag = SyncTree.getNextQueryTag_();\n this.queryToTagMap_[queryKey] = tag;\n // Coerce to string to avoid sparse arrays.\n this.tagToQueryMap_['_' + tag] = queryKey;\n }\n var writesCache = this.pendingWriteTree_.childWrites(path);\n var events = syncPoint.addEventRegistration(query, eventRegistration, writesCache, serverCache, serverCacheComplete);\n if (!viewAlreadyExists && !foundAncestorDefaultView) {\n var view /** @type !View */ = syncPoint.viewForQuery(query);\n events = events.concat(this.setupListener_(query, view));\n }\n return events;\n };\n /**\n * Remove event callback(s).\n *\n * If query is the default query, we'll check all queries for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.\n *\n * @param {!Query} query\n * @param {?EventRegistration} eventRegistration If null, all callbacks are removed.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {!Array.} Cancel events, if cancelError was provided.\n */\n SyncTree.prototype.removeEventRegistration = function (query, eventRegistration, cancelError) {\n var _this = this;\n // Find the syncPoint first. Then deal with whether or not it has matching listeners\n var path = query.path;\n var maybeSyncPoint = this.syncPointTree_.get(path);\n var cancelEvents = [];\n // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without\n // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and\n // not loadsAllData().\n if (maybeSyncPoint &&\n (query.queryIdentifier() === 'default' ||\n maybeSyncPoint.viewExistsForQuery(query))) {\n /**\n * @type {{removed: !Array., events: !Array.}}\n */\n var removedAndEvents = maybeSyncPoint.removeEventRegistration(query, eventRegistration, cancelError);\n if (maybeSyncPoint.isEmpty()) {\n this.syncPointTree_ = this.syncPointTree_.remove(path);\n }\n var removed = removedAndEvents.removed;\n cancelEvents = removedAndEvents.events;\n // We may have just removed one of many listeners and can short-circuit this whole process\n // We may also not have removed a default listener, in which case all of the descendant listeners should already be\n // properly set up.\n //\n // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of\n // queryId === 'default'\n var removingDefault = -1 !==\n removed.findIndex(function (query) {\n return query.getQueryParams().loadsAllData();\n });\n var covered = this.syncPointTree_.findOnPath(path, function (relativePath, parentSyncPoint) {\n return parentSyncPoint.hasCompleteView();\n });\n if (removingDefault && !covered) {\n var subtree = this.syncPointTree_.subtree(path);\n // There are potentially child listeners. Determine what if any listens we need to send before executing the\n // removal\n if (!subtree.isEmpty()) {\n // We need to fold over our subtree and collect the listeners to send\n var newViews = this.collectDistinctViewsForSubTree_(subtree);\n // Ok, we've collected all the listens we need. Set them up.\n for (var i = 0; i < newViews.length; ++i) {\n var view = newViews[i], newQuery = view.getQuery();\n var listener = this.createListenerForView_(view);\n this.listenProvider_.startListening(SyncTree.queryForListening_(newQuery), this.tagForQuery_(newQuery), listener.hashFn, listener.onComplete);\n }\n }\n else {\n // There's nothing below us, so nothing we need to start listening on\n }\n }\n // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query\n // The above block has us covered in terms of making sure we're set up on listens lower in the tree.\n // Also, note that if we have a cancelError, it's already been removed at the provider level.\n if (!covered && removed.length > 0 && !cancelError) {\n // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one\n // default. Otherwise, we need to iterate through and cancel each individual query\n if (removingDefault) {\n // We don't tag default listeners\n var defaultTag = null;\n this.listenProvider_.stopListening(SyncTree.queryForListening_(query), defaultTag);\n }\n else {\n removed.forEach(function (queryToRemove) {\n var tagToRemove = _this.queryToTagMap_[SyncTree.makeQueryKey_(queryToRemove)];\n _this.listenProvider_.stopListening(SyncTree.queryForListening_(queryToRemove), tagToRemove);\n });\n }\n }\n // Now, clear all of the tags we're tracking for the removed listens\n this.removeTags_(removed);\n }\n else {\n // No-op, this listener must've been already removed\n }\n return cancelEvents;\n };\n /**\n * Returns a complete cache, if we have one, of the data at a particular path. The location must have a listener above\n * it, but as this is only used by transaction code, that should always be the case anyways.\n *\n * Note: this method will *include* hidden writes from transaction with applyLocally set to false.\n * @param {!Path} path The path to the data we want\n * @param {Array.=} writeIdsToExclude A specific set to be excluded\n * @return {?Node}\n */\n SyncTree.prototype.calcCompleteEventCache = function (path, writeIdsToExclude) {\n var includeHiddenSets = true;\n var writeTree = this.pendingWriteTree_;\n var serverCache = this.syncPointTree_.findOnPath(path, function (pathSoFar, syncPoint) {\n var relativePath = Path_1.Path.relativePath(pathSoFar, path);\n var serverCache = syncPoint.getCompleteServerCache(relativePath);\n if (serverCache) {\n return serverCache;\n }\n });\n return writeTree.calcCompleteEventCache(path, serverCache, writeIdsToExclude, includeHiddenSets);\n };\n /**\n * This collapses multiple unfiltered views into a single view, since we only need a single\n * listener for them.\n *\n * @param {!ImmutableTree.} subtree\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.collectDistinctViewsForSubTree_ = function (subtree) {\n return subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {\n if (maybeChildSyncPoint && maybeChildSyncPoint.hasCompleteView()) {\n var completeView = maybeChildSyncPoint.getCompleteView();\n return [completeView];\n }\n else {\n // No complete view here, flatten any deeper listens into an array\n var views_1 = [];\n if (maybeChildSyncPoint) {\n views_1 = maybeChildSyncPoint.getQueryViews();\n }\n util_3.forEach(childMap, function (key, childViews) {\n views_1 = views_1.concat(childViews);\n });\n return views_1;\n }\n });\n };\n /**\n * @param {!Array.} queries\n * @private\n */\n SyncTree.prototype.removeTags_ = function (queries) {\n for (var j = 0; j < queries.length; ++j) {\n var removedQuery = queries[j];\n if (!removedQuery.getQueryParams().loadsAllData()) {\n // We should have a tag for this\n var removedQueryKey = SyncTree.makeQueryKey_(removedQuery);\n var removedQueryTag = this.queryToTagMap_[removedQueryKey];\n delete this.queryToTagMap_[removedQueryKey];\n delete this.tagToQueryMap_['_' + removedQueryTag];\n }\n }\n };\n /**\n * Normalizes a query to a query we send the server for listening\n * @param {!Query} query\n * @return {!Query} The normalized query\n * @private\n */\n SyncTree.queryForListening_ = function (query) {\n if (query.getQueryParams().loadsAllData() &&\n !query.getQueryParams().isDefault()) {\n // We treat queries that load all data as default queries\n // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits\n // from Query\n return /** @type {!Query} */ query.getRef();\n }\n else {\n return query;\n }\n };\n /**\n * For a given new listen, manage the de-duplication of outstanding subscriptions.\n *\n * @param {!Query} query\n * @param {!View} view\n * @return {!Array.} This method can return events to support synchronous data sources\n * @private\n */\n SyncTree.prototype.setupListener_ = function (query, view) {\n var path = query.path;\n var tag = this.tagForQuery_(query);\n var listener = this.createListenerForView_(view);\n var events = this.listenProvider_.startListening(SyncTree.queryForListening_(query), tag, listener.hashFn, listener.onComplete);\n var subtree = this.syncPointTree_.subtree(path);\n // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we\n // may need to shadow other listens as well.\n if (tag) {\n util_1.assert(!subtree.value.hasCompleteView(), \"If we're adding a query, it shouldn't be shadowed\");\n }\n else {\n // Shadow everything at or below this location, this is a default listener.\n var queriesToStop = subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {\n if (!relativePath.isEmpty() &&\n maybeChildSyncPoint &&\n maybeChildSyncPoint.hasCompleteView()) {\n return [maybeChildSyncPoint.getCompleteView().getQuery()];\n }\n else {\n // No default listener here, flatten any deeper queries into an array\n var queries_1 = [];\n if (maybeChildSyncPoint) {\n queries_1 = queries_1.concat(maybeChildSyncPoint.getQueryViews().map(function (view) { return view.getQuery(); }));\n }\n util_3.forEach(childMap, function (key, childQueries) {\n queries_1 = queries_1.concat(childQueries);\n });\n return queries_1;\n }\n });\n for (var i = 0; i < queriesToStop.length; ++i) {\n var queryToStop = queriesToStop[i];\n this.listenProvider_.stopListening(SyncTree.queryForListening_(queryToStop), this.tagForQuery_(queryToStop));\n }\n }\n return events;\n };\n /**\n *\n * @param {!View} view\n * @return {{hashFn: function(), onComplete: function(!string, *)}}\n * @private\n */\n SyncTree.prototype.createListenerForView_ = function (view) {\n var _this = this;\n var query = view.getQuery();\n var tag = this.tagForQuery_(query);\n return {\n hashFn: function () {\n var cache = view.getServerCache() || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return cache.hash();\n },\n onComplete: function (status) {\n if (status === 'ok') {\n if (tag) {\n return _this.applyTaggedListenComplete(query.path, tag);\n }\n else {\n return _this.applyListenComplete(query.path);\n }\n }\n else {\n // If a listen failed, kill all of the listeners here, not just the one that triggered the error.\n // Note that this may need to be scoped to just this listener if we change permissions on filtered children\n var error = util_2.errorForServerCode(status, query);\n return _this.removeEventRegistration(query, \n /*eventRegistration*/ null, error);\n }\n }\n };\n };\n /**\n * Given a query, computes a \"queryKey\" suitable for use in our queryToTagMap_.\n * @private\n * @param {!Query} query\n * @return {string}\n */\n SyncTree.makeQueryKey_ = function (query) {\n return query.path.toString() + '$' + query.queryIdentifier();\n };\n /**\n * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.\n * @private\n * @param {!string} queryKey\n * @return {{queryId: !string, path: !Path}}\n */\n SyncTree.parseQueryKey_ = function (queryKey) {\n var splitIndex = queryKey.indexOf('$');\n util_1.assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');\n return {\n queryId: queryKey.substr(splitIndex + 1),\n path: new Path_1.Path(queryKey.substr(0, splitIndex))\n };\n };\n /**\n * Return the query associated with the given tag, if we have one\n * @param {!number} tag\n * @return {?string}\n * @private\n */\n SyncTree.prototype.queryKeyForTag_ = function (tag) {\n return this.tagToQueryMap_['_' + tag];\n };\n /**\n * Return the tag associated with the given query.\n * @param {!Query} query\n * @return {?number}\n * @private\n */\n SyncTree.prototype.tagForQuery_ = function (query) {\n var queryKey = SyncTree.makeQueryKey_(query);\n return util_3.safeGet(this.queryToTagMap_, queryKey);\n };\n /**\n * Static accessor for query tags.\n * @return {number}\n * @private\n */\n SyncTree.getNextQueryTag_ = function () {\n return SyncTree.nextQueryTag_++;\n };\n /**\n * A helper method to apply tagged operations\n *\n * @param {!Path} queryPath\n * @param {!Operation} operation\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.applyTaggedOperation_ = function (queryPath, operation) {\n var syncPoint = this.syncPointTree_.get(queryPath);\n util_1.assert(syncPoint, \"Missing sync point for query tag that we're tracking\");\n var writesCache = this.pendingWriteTree_.childWrites(queryPath);\n return syncPoint.applyOperation(operation, writesCache, \n /*serverCache=*/ null);\n };\n /**\n * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.\n *\n * NOTES:\n * - Descendant SyncPoints will be visited first (since we raise events depth-first).\n \n * - We call applyOperation() on each SyncPoint passing three things:\n * 1. A version of the Operation that has been made relative to the SyncPoint location.\n * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.\n * 3. A snapshot Node with cached server data, if we have it.\n \n * - We concatenate all of the events returned by each SyncPoint and return the result.\n *\n * @param {!Operation} operation\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.applyOperationToSyncPoints_ = function (operation) {\n return this.applyOperationHelper_(operation, this.syncPointTree_, \n /*serverCache=*/ null, this.pendingWriteTree_.childWrites(Path_1.Path.Empty));\n };\n /**\n * Recursive helper for applyOperationToSyncPoints_\n *\n * @private\n * @param {!Operation} operation\n * @param {ImmutableTree.} syncPointTree\n * @param {?Node} serverCache\n * @param {!WriteTreeRef} writesCache\n * @return {!Array.}\n */\n SyncTree.prototype.applyOperationHelper_ = function (operation, syncPointTree, serverCache, writesCache) {\n if (operation.path.isEmpty()) {\n return this.applyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);\n }\n else {\n var syncPoint = syncPointTree.get(Path_1.Path.Empty);\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var events = [];\n var childName = operation.path.getFront();\n var childOperation = operation.operationForChild(childName);\n var childTree = syncPointTree.children.get(childName);\n if (childTree && childOperation) {\n var childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n var childWritesCache = writesCache.child(childName);\n events = events.concat(this.applyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));\n }\n if (syncPoint) {\n events = events.concat(syncPoint.applyOperation(operation, writesCache, serverCache));\n }\n return events;\n }\n };\n /**\n * Recursive helper for applyOperationToSyncPoints_\n *\n * @private\n * @param {!Operation} operation\n * @param {ImmutableTree.} syncPointTree\n * @param {?Node} serverCache\n * @param {!WriteTreeRef} writesCache\n * @return {!Array.}\n */\n SyncTree.prototype.applyOperationDescendantsHelper_ = function (operation, syncPointTree, serverCache, writesCache) {\n var _this = this;\n var syncPoint = syncPointTree.get(Path_1.Path.Empty);\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var events = [];\n syncPointTree.children.inorderTraversal(function (childName, childTree) {\n var childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n var childWritesCache = writesCache.child(childName);\n var childOperation = operation.operationForChild(childName);\n if (childOperation) {\n events = events.concat(_this.applyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));\n }\n });\n if (syncPoint) {\n events = events.concat(syncPoint.applyOperation(operation, writesCache, serverCache));\n }\n return events;\n };\n /**\n * Static tracker for next query tag.\n * @type {number}\n * @private\n */\n SyncTree.nextQueryTag_ = 1;\n return SyncTree;\n}());\nexports.SyncTree = SyncTree;\n\n//# sourceMappingURL=SyncTree.js.map\n\n\n/***/ }),\n/* 88 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Path_1 = __webpack_require__(3);\nvar Operation_1 = __webpack_require__(9);\nvar AckUserWrite = /** @class */ (function () {\n /**\n *\n * @param {!Path} path\n * @param {!ImmutableTree} affectedTree A tree containing true for each affected path. Affected paths can't overlap.\n * @param {!boolean} revert\n */\n function AckUserWrite(\n /**@inheritDoc */ path, \n /**@inheritDoc */ affectedTree, \n /**@inheritDoc */ revert) {\n this.path = path;\n this.affectedTree = affectedTree;\n this.revert = revert;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.ACK_USER_WRITE;\n /** @inheritDoc */\n this.source = Operation_1.OperationSource.User;\n }\n /**\n * @inheritDoc\n */\n AckUserWrite.prototype.operationForChild = function (childName) {\n if (!this.path.isEmpty()) {\n util_1.assert(this.path.getFront() === childName, 'operationForChild called for unrelated child.');\n return new AckUserWrite(this.path.popFront(), this.affectedTree, this.revert);\n }\n else if (this.affectedTree.value != null) {\n util_1.assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');\n // All child locations are affected as well; just return same operation.\n return this;\n }\n else {\n var childTree = this.affectedTree.subtree(new Path_1.Path(childName));\n return new AckUserWrite(Path_1.Path.Empty, childTree, this.revert);\n }\n };\n return AckUserWrite;\n}());\nexports.AckUserWrite = AckUserWrite;\n\n//# sourceMappingURL=AckUserWrite.js.map\n\n\n/***/ }),\n/* 89 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = __webpack_require__(3);\nvar Operation_1 = __webpack_require__(9);\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @constructor\n * @implements {Operation}\n */\nvar ListenComplete = /** @class */ (function () {\n function ListenComplete(source, path) {\n this.source = source;\n this.path = path;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.LISTEN_COMPLETE;\n }\n ListenComplete.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n return new ListenComplete(this.source, Path_1.Path.Empty);\n }\n else {\n return new ListenComplete(this.source, this.path.popFront());\n }\n };\n return ListenComplete;\n}());\nexports.ListenComplete = ListenComplete;\n\n//# sourceMappingURL=ListenComplete.js.map\n\n\n/***/ }),\n/* 90 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = __webpack_require__(9);\nvar Overwrite_1 = __webpack_require__(47);\nvar Path_1 = __webpack_require__(3);\nvar util_1 = __webpack_require__(0);\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @param {!ImmutableTree.} children\n * @constructor\n * @implements {Operation}\n */\nvar Merge = /** @class */ (function () {\n function Merge(\n /**@inheritDoc */ source, \n /**@inheritDoc */ path, \n /**@inheritDoc */ children) {\n this.source = source;\n this.path = path;\n this.children = children;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.MERGE;\n }\n /**\n * @inheritDoc\n */\n Merge.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n var childTree = this.children.subtree(new Path_1.Path(childName));\n if (childTree.isEmpty()) {\n // This child is unaffected\n return null;\n }\n else if (childTree.value) {\n // We have a snapshot for the child in question. This becomes an overwrite of the child.\n return new Overwrite_1.Overwrite(this.source, Path_1.Path.Empty, childTree.value);\n }\n else {\n // This is a merge at a deeper level\n return new Merge(this.source, Path_1.Path.Empty, childTree);\n }\n }\n else {\n util_1.assert(this.path.getFront() === childName, \"Can't get a merge for a child not on the path of the operation\");\n return new Merge(this.source, this.path.popFront(), this.children);\n }\n };\n /**\n * @inheritDoc\n */\n Merge.prototype.toString = function () {\n return ('Operation(' +\n this.path +\n ': ' +\n this.source.toString() +\n ' merge: ' +\n this.children.toString() +\n ')');\n };\n return Merge;\n}());\nexports.Merge = Merge;\n\n//# sourceMappingURL=Merge.js.map\n\n\n/***/ }),\n/* 91 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar IndexedFilter_1 = __webpack_require__(25);\nvar ViewProcessor_1 = __webpack_require__(92);\nvar ChildrenNode_1 = __webpack_require__(5);\nvar CacheNode_1 = __webpack_require__(20);\nvar ViewCache_1 = __webpack_require__(49);\nvar EventGenerator_1 = __webpack_require__(95);\nvar util_1 = __webpack_require__(0);\nvar Operation_1 = __webpack_require__(9);\nvar Change_1 = __webpack_require__(10);\nvar PriorityIndex_1 = __webpack_require__(4);\n/**\n * A view represents a specific location and query that has 1 or more event registrations.\n *\n * It does several things:\n * - Maintains the list of event registrations for this location/query.\n * - Maintains a cache of the data visible for this location/query.\n * - Applies new operations (via applyOperation), updates the cache, and based on the event\n * registrations returns the set of events to be raised.\n * @constructor\n */\nvar View = /** @class */ (function () {\n /**\n *\n * @param {!Query} query_\n * @param {!ViewCache} initialViewCache\n */\n function View(query_, initialViewCache) {\n this.query_ = query_;\n this.eventRegistrations_ = [];\n var params = this.query_.getQueryParams();\n var indexFilter = new IndexedFilter_1.IndexedFilter(params.getIndex());\n var filter = params.getNodeFilter();\n /**\n * @type {ViewProcessor}\n * @private\n */\n this.processor_ = new ViewProcessor_1.ViewProcessor(filter);\n var initialServerCache = initialViewCache.getServerCache();\n var initialEventCache = initialViewCache.getEventCache();\n // Don't filter server node with other filter than index, wait for tagged listen\n var serverSnap = indexFilter.updateFullNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);\n var eventSnap = filter.updateFullNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);\n var newServerCache = new CacheNode_1.CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());\n var newEventCache = new CacheNode_1.CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());\n /**\n * @type {!ViewCache}\n * @private\n */\n this.viewCache_ = new ViewCache_1.ViewCache(newEventCache, newServerCache);\n /**\n * @type {!EventGenerator}\n * @private\n */\n this.eventGenerator_ = new EventGenerator_1.EventGenerator(this.query_);\n }\n /**\n * @return {!Query}\n */\n View.prototype.getQuery = function () {\n return this.query_;\n };\n /**\n * @return {?Node}\n */\n View.prototype.getServerCache = function () {\n return this.viewCache_.getServerCache().getNode();\n };\n /**\n * @param {!Path} path\n * @return {?Node}\n */\n View.prototype.getCompleteServerCache = function (path) {\n var cache = this.viewCache_.getCompleteServerSnap();\n if (cache) {\n // If this isn't a \"loadsAllData\" view, then cache isn't actually a complete cache and\n // we need to see if it contains the child we're interested in.\n if (this.query_.getQueryParams().loadsAllData() ||\n (!path.isEmpty() && !cache.getImmediateChild(path.getFront()).isEmpty())) {\n return cache.getChild(path);\n }\n }\n return null;\n };\n /**\n * @return {boolean}\n */\n View.prototype.isEmpty = function () {\n return this.eventRegistrations_.length === 0;\n };\n /**\n * @param {!EventRegistration} eventRegistration\n */\n View.prototype.addEventRegistration = function (eventRegistration) {\n this.eventRegistrations_.push(eventRegistration);\n };\n /**\n * @param {?EventRegistration} eventRegistration If null, remove all callbacks.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {!Array.} Cancel events, if cancelError was provided.\n */\n View.prototype.removeEventRegistration = function (eventRegistration, cancelError) {\n var cancelEvents = [];\n if (cancelError) {\n util_1.assert(eventRegistration == null, 'A cancel should cancel all event registrations.');\n var path_1 = this.query_.path;\n this.eventRegistrations_.forEach(function (registration) {\n cancelError /** @type {!Error} */ = cancelError;\n var maybeEvent = registration.createCancelEvent(cancelError, path_1);\n if (maybeEvent) {\n cancelEvents.push(maybeEvent);\n }\n });\n }\n if (eventRegistration) {\n var remaining = [];\n for (var i = 0; i < this.eventRegistrations_.length; ++i) {\n var existing = this.eventRegistrations_[i];\n if (!existing.matches(eventRegistration)) {\n remaining.push(existing);\n }\n else if (eventRegistration.hasAnyCallback()) {\n // We're removing just this one\n remaining = remaining.concat(this.eventRegistrations_.slice(i + 1));\n break;\n }\n }\n this.eventRegistrations_ = remaining;\n }\n else {\n this.eventRegistrations_ = [];\n }\n return cancelEvents;\n };\n /**\n * Applies the given Operation, updates our cache, and returns the appropriate events.\n *\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeServerCache\n * @return {!Array.}\n */\n View.prototype.applyOperation = function (operation, writesCache, completeServerCache) {\n if (operation.type === Operation_1.OperationType.MERGE &&\n operation.source.queryId !== null) {\n util_1.assert(this.viewCache_.getCompleteServerSnap(), 'We should always have a full cache before handling merges');\n util_1.assert(this.viewCache_.getCompleteEventSnap(), 'Missing event cache, even though we have a server cache');\n }\n var oldViewCache = this.viewCache_;\n var result = this.processor_.applyOperation(oldViewCache, operation, writesCache, completeServerCache);\n this.processor_.assertIndexed(result.viewCache);\n util_1.assert(result.viewCache.getServerCache().isFullyInitialized() ||\n !oldViewCache.getServerCache().isFullyInitialized(), 'Once a server snap is complete, it should never go back');\n this.viewCache_ = result.viewCache;\n return this.generateEventsForChanges_(result.changes, result.viewCache.getEventCache().getNode(), null);\n };\n /**\n * @param {!EventRegistration} registration\n * @return {!Array.}\n */\n View.prototype.getInitialEvents = function (registration) {\n var eventSnap = this.viewCache_.getEventCache();\n var initialChanges = [];\n if (!eventSnap.getNode().isLeafNode()) {\n var eventNode = eventSnap.getNode();\n eventNode.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n initialChanges.push(Change_1.Change.childAddedChange(key, childNode));\n });\n }\n if (eventSnap.isFullyInitialized()) {\n initialChanges.push(Change_1.Change.valueChange(eventSnap.getNode()));\n }\n return this.generateEventsForChanges_(initialChanges, eventSnap.getNode(), registration);\n };\n /**\n * @private\n * @param {!Array.} changes\n * @param {!Node} eventCache\n * @param {EventRegistration=} eventRegistration\n * @return {!Array.}\n */\n View.prototype.generateEventsForChanges_ = function (changes, eventCache, eventRegistration) {\n var registrations = eventRegistration\n ? [eventRegistration]\n : this.eventRegistrations_;\n return this.eventGenerator_.generateEventsForChanges(changes, eventCache, registrations);\n };\n return View;\n}());\nexports.View = View;\n\n//# sourceMappingURL=View.js.map\n\n\n/***/ }),\n/* 92 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = __webpack_require__(9);\nvar util_1 = __webpack_require__(0);\nvar ChildChangeAccumulator_1 = __webpack_require__(93);\nvar Change_1 = __webpack_require__(10);\nvar ChildrenNode_1 = __webpack_require__(5);\nvar KeyIndex_1 = __webpack_require__(12);\nvar ImmutableTree_1 = __webpack_require__(24);\nvar Path_1 = __webpack_require__(3);\nvar CompleteChildSource_1 = __webpack_require__(94);\n/**\n * @constructor\n * @struct\n */\nvar ProcessorResult = /** @class */ (function () {\n /**\n * @param {!ViewCache} viewCache\n * @param {!Array.} changes\n */\n function ProcessorResult(viewCache, changes) {\n this.viewCache = viewCache;\n this.changes = changes;\n }\n return ProcessorResult;\n}());\nexports.ProcessorResult = ProcessorResult;\n/**\n * @constructor\n */\nvar ViewProcessor = /** @class */ (function () {\n /**\n * @param {!NodeFilter} filter_\n */\n function ViewProcessor(filter_) {\n this.filter_ = filter_;\n }\n /**\n * @param {!ViewCache} viewCache\n */\n ViewProcessor.prototype.assertIndexed = function (viewCache) {\n util_1.assert(viewCache\n .getEventCache()\n .getNode()\n .isIndexed(this.filter_.getIndex()), 'Event snap not indexed');\n util_1.assert(viewCache\n .getServerCache()\n .getNode()\n .isIndexed(this.filter_.getIndex()), 'Server snap not indexed');\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @return {!ProcessorResult}\n */\n ViewProcessor.prototype.applyOperation = function (oldViewCache, operation, writesCache, completeCache) {\n var accumulator = new ChildChangeAccumulator_1.ChildChangeAccumulator();\n var newViewCache, filterServerNode;\n if (operation.type === Operation_1.OperationType.OVERWRITE) {\n var overwrite = operation;\n if (overwrite.source.fromUser) {\n newViewCache = this.applyUserOverwrite_(oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);\n }\n else {\n util_1.assert(overwrite.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered and the\n // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered\n // again\n filterServerNode =\n overwrite.source.tagged ||\n (oldViewCache.getServerCache().isFiltered() &&\n !overwrite.path.isEmpty());\n newViewCache = this.applyServerOverwrite_(oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.MERGE) {\n var merge = operation;\n if (merge.source.fromUser) {\n newViewCache = this.applyUserMerge_(oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);\n }\n else {\n util_1.assert(merge.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered\n filterServerNode =\n merge.source.tagged || oldViewCache.getServerCache().isFiltered();\n newViewCache = this.applyServerMerge_(oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.ACK_USER_WRITE) {\n var ackUserWrite = operation;\n if (!ackUserWrite.revert) {\n newViewCache = this.ackUserWrite_(oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);\n }\n else {\n newViewCache = this.revertUserWrite_(oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.LISTEN_COMPLETE) {\n newViewCache = this.listenComplete_(oldViewCache, operation.path, writesCache, accumulator);\n }\n else {\n throw util_1.assertionError('Unknown operation type: ' + operation.type);\n }\n var changes = accumulator.getChanges();\n ViewProcessor.maybeAddValueEvent_(oldViewCache, newViewCache, changes);\n return new ProcessorResult(newViewCache, changes);\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!ViewCache} newViewCache\n * @param {!Array.} accumulator\n * @private\n */\n ViewProcessor.maybeAddValueEvent_ = function (oldViewCache, newViewCache, accumulator) {\n var eventSnap = newViewCache.getEventCache();\n if (eventSnap.isFullyInitialized()) {\n var isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();\n var oldCompleteSnap = oldViewCache.getCompleteEventSnap();\n if (accumulator.length > 0 ||\n !oldViewCache.getEventCache().isFullyInitialized() ||\n (isLeafOrEmpty &&\n !eventSnap\n .getNode()\n .equals(/** @type {!Node} */ (oldCompleteSnap))) ||\n !eventSnap\n .getNode()\n .getPriority()\n .equals(oldCompleteSnap.getPriority())) {\n accumulator.push(Change_1.Change.valueChange(\n /** @type {!Node} */ newViewCache.getCompleteEventSnap()));\n }\n }\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} changePath\n * @param {!WriteTreeRef} writesCache\n * @param {!CompleteChildSource} source\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.generateEventCacheAfterServerEvent_ = function (viewCache, changePath, writesCache, source, accumulator) {\n var oldEventSnap = viewCache.getEventCache();\n if (writesCache.shadowingWrite(changePath) != null) {\n // we have a shadowing write, ignore changes\n return viewCache;\n }\n else {\n var newEventCache = void 0, serverNode = void 0;\n if (changePath.isEmpty()) {\n // TODO: figure out how this plays with \"sliding ack windows\"\n util_1.assert(viewCache.getServerCache().isFullyInitialized(), 'If change path is empty, we must have complete server data');\n if (viewCache.getServerCache().isFiltered()) {\n // We need to special case this, because we need to only apply writes to complete children, or\n // we might end up raising events for incomplete children. If the server data is filtered deep\n // writes cannot be guaranteed to be complete\n var serverCache = viewCache.getCompleteServerSnap();\n var completeChildren = serverCache instanceof ChildrenNode_1.ChildrenNode\n ? serverCache\n : ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var completeEventChildren = writesCache.calcCompleteEventChildren(completeChildren);\n newEventCache = this.filter_.updateFullNode(viewCache.getEventCache().getNode(), completeEventChildren, accumulator);\n }\n else {\n var completeNode = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n newEventCache = this.filter_.updateFullNode(viewCache.getEventCache().getNode(), completeNode, accumulator);\n }\n }\n else {\n var childKey = changePath.getFront();\n if (childKey == '.priority') {\n util_1.assert(changePath.getLength() == 1, \"Can't have a priority with additional path components\");\n var oldEventNode = oldEventSnap.getNode();\n serverNode = viewCache.getServerCache().getNode();\n // we might have overwrites for this priority\n var updatedPriority = writesCache.calcEventCacheAfterServerOverwrite(changePath, oldEventNode, serverNode);\n if (updatedPriority != null) {\n newEventCache = this.filter_.updatePriority(oldEventNode, updatedPriority);\n }\n else {\n // priority didn't change, keep old node\n newEventCache = oldEventSnap.getNode();\n }\n }\n else {\n var childChangePath = changePath.popFront();\n // update child\n var newEventChild = void 0;\n if (oldEventSnap.isCompleteForChild(childKey)) {\n serverNode = viewCache.getServerCache().getNode();\n var eventChildUpdate = writesCache.calcEventCacheAfterServerOverwrite(changePath, oldEventSnap.getNode(), serverNode);\n if (eventChildUpdate != null) {\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey)\n .updateChild(childChangePath, eventChildUpdate);\n }\n else {\n // Nothing changed, just keep the old child\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey);\n }\n }\n else {\n newEventChild = writesCache.calcCompleteChild(childKey, viewCache.getServerCache());\n }\n if (newEventChild != null) {\n newEventCache = this.filter_.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);\n }\n else {\n // no complete child available or no change\n newEventCache = oldEventSnap.getNode();\n }\n }\n }\n return viewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitialized() || changePath.isEmpty(), this.filter_.filtersNodes());\n }\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Path} changePath\n * @param {!Node} changedSnap\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {boolean} filterServerNode\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyServerOverwrite_ = function (oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {\n var oldServerSnap = oldViewCache.getServerCache();\n var newServerCache;\n var serverFilter = filterServerNode\n ? this.filter_\n : this.filter_.getIndexedFilter();\n if (changePath.isEmpty()) {\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);\n }\n else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {\n // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update\n var newServerNode = oldServerSnap\n .getNode()\n .updateChild(changePath, changedSnap);\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);\n }\n else {\n var childKey = changePath.getFront();\n if (!oldServerSnap.isCompleteForPath(changePath) &&\n changePath.getLength() > 1) {\n // We don't update incomplete nodes with updates intended for other listeners\n return oldViewCache;\n }\n var childChangePath = changePath.popFront();\n var childNode = oldServerSnap.getNode().getImmediateChild(childKey);\n var newChildNode = childNode.updateChild(childChangePath, changedSnap);\n if (childKey == '.priority') {\n newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);\n }\n else {\n newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, CompleteChildSource_1.NO_COMPLETE_CHILD_SOURCE, null);\n }\n }\n var newViewCache = oldViewCache.updateServerSnap(newServerCache, oldServerSnap.isFullyInitialized() || changePath.isEmpty(), serverFilter.filtersNodes());\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);\n return this.generateEventCacheAfterServerEvent_(newViewCache, changePath, writesCache, source, accumulator);\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Path} changePath\n * @param {!Node} changedSnap\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyUserOverwrite_ = function (oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {\n var oldEventSnap = oldViewCache.getEventCache();\n var newViewCache, newEventCache;\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);\n if (changePath.isEmpty()) {\n newEventCache = this.filter_.updateFullNode(oldViewCache.getEventCache().getNode(), changedSnap, accumulator);\n newViewCache = oldViewCache.updateEventSnap(newEventCache, true, this.filter_.filtersNodes());\n }\n else {\n var childKey = changePath.getFront();\n if (childKey === '.priority') {\n newEventCache = this.filter_.updatePriority(oldViewCache.getEventCache().getNode(), changedSnap);\n newViewCache = oldViewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());\n }\n else {\n var childChangePath = changePath.popFront();\n var oldChild = oldEventSnap.getNode().getImmediateChild(childKey);\n var newChild = void 0;\n if (childChangePath.isEmpty()) {\n // Child overwrite, we can replace the child\n newChild = changedSnap;\n }\n else {\n var childNode = source.getCompleteChild(childKey);\n if (childNode != null) {\n if (childChangePath.getBack() === '.priority' &&\n childNode.getChild(childChangePath.parent()).isEmpty()) {\n // This is a priority update on an empty node. If this node exists on the server, the\n // server will send down the priority in the update, so ignore for now\n newChild = childNode;\n }\n else {\n newChild = childNode.updateChild(childChangePath, changedSnap);\n }\n }\n else {\n // There is no complete child node available\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n }\n if (!oldChild.equals(newChild)) {\n var newEventSnap = this.filter_.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);\n newViewCache = oldViewCache.updateEventSnap(newEventSnap, oldEventSnap.isFullyInitialized(), this.filter_.filtersNodes());\n }\n else {\n newViewCache = oldViewCache;\n }\n }\n }\n return newViewCache;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {string} childKey\n * @return {boolean}\n * @private\n */\n ViewProcessor.cacheHasChild_ = function (viewCache, childKey) {\n return viewCache.getEventCache().isCompleteForChild(childKey);\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {ImmutableTree.} changedChildren\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyUserMerge_ = function (viewCache, path, changedChildren, writesCache, serverCache, accumulator) {\n var _this = this;\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n var curViewCache = viewCache;\n changedChildren.foreach(function (relativePath, childNode) {\n var writePath = path.child(relativePath);\n if (ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) {\n curViewCache = _this.applyUserOverwrite_(curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\n }\n });\n changedChildren.foreach(function (relativePath, childNode) {\n var writePath = path.child(relativePath);\n if (!ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) {\n curViewCache = _this.applyUserOverwrite_(curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\n }\n });\n return curViewCache;\n };\n /**\n * @param {!Node} node\n * @param {ImmutableTree.} merge\n * @return {!Node}\n * @private\n */\n ViewProcessor.prototype.applyMerge_ = function (node, merge) {\n merge.foreach(function (relativePath, childNode) {\n node = node.updateChild(relativePath, childNode);\n });\n return node;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!ImmutableTree.} changedChildren\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache\n * @param {boolean} filterServerNode\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyServerMerge_ = function (viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {\n var _this = this;\n // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and\n // wait for the complete data update coming soon.\n if (viewCache\n .getServerCache()\n .getNode()\n .isEmpty() &&\n !viewCache.getServerCache().isFullyInitialized()) {\n return viewCache;\n }\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n var curViewCache = viewCache;\n var viewMergeTree;\n if (path.isEmpty()) {\n viewMergeTree = changedChildren;\n }\n else {\n viewMergeTree = ImmutableTree_1.ImmutableTree.Empty.setTree(path, changedChildren);\n }\n var serverNode = viewCache.getServerCache().getNode();\n viewMergeTree.children.inorderTraversal(function (childKey, childTree) {\n if (serverNode.hasChild(childKey)) {\n var serverChild = viewCache\n .getServerCache()\n .getNode()\n .getImmediateChild(childKey);\n var newChild = _this.applyMerge_(serverChild, childTree);\n curViewCache = _this.applyServerOverwrite_(curViewCache, new Path_1.Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\n }\n });\n viewMergeTree.children.inorderTraversal(function (childKey, childMergeTree) {\n var isUnknownDeepMerge = !viewCache.getServerCache().isCompleteForChild(childKey) &&\n childMergeTree.value == null;\n if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {\n var serverChild = viewCache\n .getServerCache()\n .getNode()\n .getImmediateChild(childKey);\n var newChild = _this.applyMerge_(serverChild, childMergeTree);\n curViewCache = _this.applyServerOverwrite_(curViewCache, new Path_1.Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\n }\n });\n return curViewCache;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} ackPath\n * @param {!ImmutableTree} affectedTree\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.ackUserWrite_ = function (viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {\n if (writesCache.shadowingWrite(ackPath) != null) {\n return viewCache;\n }\n // Only filter server node if it is currently filtered\n var filterServerNode = viewCache.getServerCache().isFiltered();\n // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update\n // now that it won't be shadowed.\n var serverCache = viewCache.getServerCache();\n if (affectedTree.value != null) {\n // This is an overwrite.\n if ((ackPath.isEmpty() && serverCache.isFullyInitialized()) ||\n serverCache.isCompleteForPath(ackPath)) {\n return this.applyServerOverwrite_(viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);\n }\n else if (ackPath.isEmpty()) {\n // This is a goofy edge case where we are acking data at this location but don't have full data. We\n // should just re-apply whatever we have in our cache as a merge.\n var changedChildren_1 = ImmutableTree_1.ImmutableTree.Empty;\n serverCache.getNode().forEachChild(KeyIndex_1.KEY_INDEX, function (name, node) {\n changedChildren_1 = changedChildren_1.set(new Path_1.Path(name), node);\n });\n return this.applyServerMerge_(viewCache, ackPath, changedChildren_1, writesCache, completeCache, filterServerNode, accumulator);\n }\n else {\n return viewCache;\n }\n }\n else {\n // This is a merge.\n var changedChildren_2 = ImmutableTree_1.ImmutableTree.Empty;\n affectedTree.foreach(function (mergePath, value) {\n var serverCachePath = ackPath.child(mergePath);\n if (serverCache.isCompleteForPath(serverCachePath)) {\n changedChildren_2 = changedChildren_2.set(mergePath, serverCache.getNode().getChild(serverCachePath));\n }\n });\n return this.applyServerMerge_(viewCache, ackPath, changedChildren_2, writesCache, completeCache, filterServerNode, accumulator);\n }\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!WriteTreeRef} writesCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.listenComplete_ = function (viewCache, path, writesCache, accumulator) {\n var oldServerNode = viewCache.getServerCache();\n var newViewCache = viewCache.updateServerSnap(oldServerNode.getNode(), oldServerNode.isFullyInitialized() || path.isEmpty(), oldServerNode.isFiltered());\n return this.generateEventCacheAfterServerEvent_(newViewCache, path, writesCache, CompleteChildSource_1.NO_COMPLETE_CHILD_SOURCE, accumulator);\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeServerCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.revertUserWrite_ = function (viewCache, path, writesCache, completeServerCache, accumulator) {\n var complete;\n if (writesCache.shadowingWrite(path) != null) {\n return viewCache;\n }\n else {\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);\n var oldEventCache = viewCache.getEventCache().getNode();\n var newEventCache = void 0;\n if (path.isEmpty() || path.getFront() === '.priority') {\n var newNode = void 0;\n if (viewCache.getServerCache().isFullyInitialized()) {\n newNode = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n }\n else {\n var serverChildren = viewCache.getServerCache().getNode();\n util_1.assert(serverChildren instanceof ChildrenNode_1.ChildrenNode, 'serverChildren would be complete if leaf node');\n newNode = writesCache.calcCompleteEventChildren(serverChildren);\n }\n newNode = newNode;\n newEventCache = this.filter_.updateFullNode(oldEventCache, newNode, accumulator);\n }\n else {\n var childKey = path.getFront();\n var newChild = writesCache.calcCompleteChild(childKey, viewCache.getServerCache());\n if (newChild == null &&\n viewCache.getServerCache().isCompleteForChild(childKey)) {\n newChild = oldEventCache.getImmediateChild(childKey);\n }\n if (newChild != null) {\n newEventCache = this.filter_.updateChild(oldEventCache, childKey, newChild, path.popFront(), source, accumulator);\n }\n else if (viewCache\n .getEventCache()\n .getNode()\n .hasChild(childKey)) {\n // No complete child available, delete the existing one, if any\n newEventCache = this.filter_.updateChild(oldEventCache, childKey, ChildrenNode_1.ChildrenNode.EMPTY_NODE, path.popFront(), source, accumulator);\n }\n else {\n newEventCache = oldEventCache;\n }\n if (newEventCache.isEmpty() &&\n viewCache.getServerCache().isFullyInitialized()) {\n // We might have reverted all child writes. Maybe the old event was a leaf node\n complete = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n if (complete.isLeafNode()) {\n newEventCache = this.filter_.updateFullNode(newEventCache, complete, accumulator);\n }\n }\n }\n complete =\n viewCache.getServerCache().isFullyInitialized() ||\n writesCache.shadowingWrite(Path_1.Path.Empty) != null;\n return viewCache.updateEventSnap(newEventCache, complete, this.filter_.filtersNodes());\n }\n };\n return ViewProcessor;\n}());\nexports.ViewProcessor = ViewProcessor;\n\n//# sourceMappingURL=ViewProcessor.js.map\n\n\n/***/ }),\n/* 93 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Change_1 = __webpack_require__(10);\nvar util_2 = __webpack_require__(0);\n/**\n * @constructor\n */\nvar ChildChangeAccumulator = /** @class */ (function () {\n function ChildChangeAccumulator() {\n this.changeMap_ = {};\n }\n /**\n * @param {!Change} change\n */\n ChildChangeAccumulator.prototype.trackChildChange = function (change) {\n var type = change.type;\n var childKey /** @type {!string} */ = change.childName;\n util_2.assert(type == Change_1.Change.CHILD_ADDED ||\n type == Change_1.Change.CHILD_CHANGED ||\n type == Change_1.Change.CHILD_REMOVED, 'Only child changes supported for tracking');\n util_2.assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');\n var oldChange = util_1.safeGet(this.changeMap_, childKey);\n if (oldChange) {\n var oldType = oldChange.type;\n if (type == Change_1.Change.CHILD_ADDED && oldType == Change_1.Change.CHILD_REMOVED) {\n this.changeMap_[childKey] = Change_1.Change.childChangedChange(childKey, change.snapshotNode, oldChange.snapshotNode);\n }\n else if (type == Change_1.Change.CHILD_REMOVED &&\n oldType == Change_1.Change.CHILD_ADDED) {\n delete this.changeMap_[childKey];\n }\n else if (type == Change_1.Change.CHILD_REMOVED &&\n oldType == Change_1.Change.CHILD_CHANGED) {\n this.changeMap_[childKey] = Change_1.Change.childRemovedChange(childKey, oldChange.oldSnap);\n }\n else if (type == Change_1.Change.CHILD_CHANGED &&\n oldType == Change_1.Change.CHILD_ADDED) {\n this.changeMap_[childKey] = Change_1.Change.childAddedChange(childKey, change.snapshotNode);\n }\n else if (type == Change_1.Change.CHILD_CHANGED &&\n oldType == Change_1.Change.CHILD_CHANGED) {\n this.changeMap_[childKey] = Change_1.Change.childChangedChange(childKey, change.snapshotNode, oldChange.oldSnap);\n }\n else {\n throw util_2.assertionError('Illegal combination of changes: ' +\n change +\n ' occurred after ' +\n oldChange);\n }\n }\n else {\n this.changeMap_[childKey] = change;\n }\n };\n /**\n * @return {!Array.}\n */\n ChildChangeAccumulator.prototype.getChanges = function () {\n return util_1.getValues(this.changeMap_);\n };\n return ChildChangeAccumulator;\n}());\nexports.ChildChangeAccumulator = ChildChangeAccumulator;\n\n//# sourceMappingURL=ChildChangeAccumulator.js.map\n\n\n/***/ }),\n/* 94 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar CacheNode_1 = __webpack_require__(20);\n/**\n * An implementation of CompleteChildSource that never returns any additional children\n *\n * @private\n * @constructor\n * @implements CompleteChildSource\n */\nvar NoCompleteChildSource_ = /** @class */ (function () {\n function NoCompleteChildSource_() {\n }\n /**\n * @inheritDoc\n */\n NoCompleteChildSource_.prototype.getCompleteChild = function (childKey) {\n return null;\n };\n /**\n * @inheritDoc\n */\n NoCompleteChildSource_.prototype.getChildAfterChild = function (index, child, reverse) {\n return null;\n };\n return NoCompleteChildSource_;\n}());\nexports.NoCompleteChildSource_ = NoCompleteChildSource_;\n/**\n * Singleton instance.\n * @const\n * @type {!CompleteChildSource}\n */\nexports.NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();\n/**\n * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or\n * old event caches available to calculate complete children.\n *\n *\n * @implements CompleteChildSource\n */\nvar WriteTreeCompleteChildSource = /** @class */ (function () {\n /**\n * @param {!WriteTreeRef} writes_\n * @param {!ViewCache} viewCache_\n * @param {?Node} optCompleteServerCache_\n */\n function WriteTreeCompleteChildSource(writes_, viewCache_, optCompleteServerCache_) {\n if (optCompleteServerCache_ === void 0) { optCompleteServerCache_ = null; }\n this.writes_ = writes_;\n this.viewCache_ = viewCache_;\n this.optCompleteServerCache_ = optCompleteServerCache_;\n }\n /**\n * @inheritDoc\n */\n WriteTreeCompleteChildSource.prototype.getCompleteChild = function (childKey) {\n var node = this.viewCache_.getEventCache();\n if (node.isCompleteForChild(childKey)) {\n return node.getNode().getImmediateChild(childKey);\n }\n else {\n var serverNode = this.optCompleteServerCache_ != null\n ? new CacheNode_1.CacheNode(this.optCompleteServerCache_, true, false)\n : this.viewCache_.getServerCache();\n return this.writes_.calcCompleteChild(childKey, serverNode);\n }\n };\n /**\n * @inheritDoc\n */\n WriteTreeCompleteChildSource.prototype.getChildAfterChild = function (index, child, reverse) {\n var completeServerData = this.optCompleteServerCache_ != null\n ? this.optCompleteServerCache_\n : this.viewCache_.getCompleteServerSnap();\n var nodes = this.writes_.calcIndexedSlice(completeServerData, child, 1, reverse, index);\n if (nodes.length === 0) {\n return null;\n }\n else {\n return nodes[0];\n }\n };\n return WriteTreeCompleteChildSource;\n}());\nexports.WriteTreeCompleteChildSource = WriteTreeCompleteChildSource;\n\n//# sourceMappingURL=CompleteChildSource.js.map\n\n\n/***/ }),\n/* 95 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Node_1 = __webpack_require__(6);\nvar Change_1 = __webpack_require__(10);\nvar util_1 = __webpack_require__(0);\n/**\n * An EventGenerator is used to convert \"raw\" changes (Change) as computed by the\n * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()\n * for details.\n *\n * @constructor\n */\nvar EventGenerator = /** @class */ (function () {\n /**\n *\n * @param {!Query} query_\n */\n function EventGenerator(query_) {\n this.query_ = query_;\n /**\n * @private\n * @type {!Index}\n */\n this.index_ = this.query_.getQueryParams().getIndex();\n }\n /**\n * Given a set of raw changes (no moved events and prevName not specified yet), and a set of\n * EventRegistrations that should be notified of these changes, generate the actual events to be raised.\n *\n * Notes:\n * - child_moved events will be synthesized at this time for any child_changed events that affect\n * our index.\n * - prevName will be calculated based on the index ordering.\n *\n * @param {!Array.} changes\n * @param {!Node} eventCache\n * @param {!Array.} eventRegistrations\n * @return {!Array.}\n */\n EventGenerator.prototype.generateEventsForChanges = function (changes, eventCache, eventRegistrations) {\n var _this = this;\n var events = [];\n var moves = [];\n changes.forEach(function (change) {\n if (change.type === Change_1.Change.CHILD_CHANGED &&\n _this.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {\n moves.push(Change_1.Change.childMovedChange(change.childName, change.snapshotNode));\n }\n });\n this.generateEventsForType_(events, Change_1.Change.CHILD_REMOVED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_ADDED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_MOVED, moves, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_CHANGED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.VALUE, changes, eventRegistrations, eventCache);\n return events;\n };\n /**\n * Given changes of a single change type, generate the corresponding events.\n *\n * @param {!Array.} events\n * @param {!string} eventType\n * @param {!Array.} changes\n * @param {!Array.} registrations\n * @param {!Node} eventCache\n * @private\n */\n EventGenerator.prototype.generateEventsForType_ = function (events, eventType, changes, registrations, eventCache) {\n var _this = this;\n var filteredChanges = changes.filter(function (change) { return change.type === eventType; });\n filteredChanges.sort(this.compareChanges_.bind(this));\n filteredChanges.forEach(function (change) {\n var materializedChange = _this.materializeSingleChange_(change, eventCache);\n registrations.forEach(function (registration) {\n if (registration.respondsTo(change.type)) {\n events.push(registration.createEvent(materializedChange, _this.query_));\n }\n });\n });\n };\n /**\n * @param {!Change} change\n * @param {!Node} eventCache\n * @return {!Change}\n * @private\n */\n EventGenerator.prototype.materializeSingleChange_ = function (change, eventCache) {\n if (change.type === 'value' || change.type === 'child_removed') {\n return change;\n }\n else {\n change.prevName = eventCache.getPredecessorChildName(\n /** @type {!string} */\n change.childName, change.snapshotNode, this.index_);\n return change;\n }\n };\n /**\n * @param {!Change} a\n * @param {!Change} b\n * @return {number}\n * @private\n */\n EventGenerator.prototype.compareChanges_ = function (a, b) {\n if (a.childName == null || b.childName == null) {\n throw util_1.assertionError('Should only compare child_ events.');\n }\n var aWrapped = new Node_1.NamedNode(a.childName, a.snapshotNode);\n var bWrapped = new Node_1.NamedNode(b.childName, b.snapshotNode);\n return this.index_.compare(aWrapped, bWrapped);\n };\n return EventGenerator;\n}());\nexports.EventGenerator = EventGenerator;\n\n//# sourceMappingURL=EventGenerator.js.map\n\n\n/***/ }),\n/* 96 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\nvar Path_1 = __webpack_require__(3);\nvar CompoundWrite_1 = __webpack_require__(97);\nvar PriorityIndex_1 = __webpack_require__(4);\nvar ChildrenNode_1 = __webpack_require__(5);\n/**\n * WriteTree tracks all pending user-initiated writes and has methods to calculate the result of merging them\n * with underlying server data (to create \"event cache\" data). Pending writes are added with addOverwrite()\n * and addMerge(), and removed with removeWrite().\n *\n * @constructor\n */\nvar WriteTree = /** @class */ (function () {\n function WriteTree() {\n /**\n * A tree tracking the result of applying all visible writes. This does not include transactions with\n * applyLocally=false or writes that are completely shadowed by other writes.\n *\n * @type {!CompoundWrite}\n * @private\n */\n this.visibleWrites_ = CompoundWrite_1.CompoundWrite.Empty;\n /**\n * A list of all pending writes, regardless of visibility and shadowed-ness. Used to calculate arbitrary\n * sets of the changed data, such as hidden writes (from transactions) or changes with certain writes excluded (also\n * used by transactions).\n *\n * @type {!Array.}\n * @private\n */\n this.allWrites_ = [];\n this.lastWriteId_ = -1;\n }\n /**\n * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.\n *\n * @param {!Path} path\n * @return {!WriteTreeRef}\n */\n WriteTree.prototype.childWrites = function (path) {\n return new WriteTreeRef(path, this);\n };\n /**\n * Record a new overwrite from user code.\n *\n * @param {!Path} path\n * @param {!Node} snap\n * @param {!number} writeId\n * @param {boolean=} visible This is set to false by some transactions. It should be excluded from event caches\n */\n WriteTree.prototype.addOverwrite = function (path, snap, writeId, visible) {\n util_2.assert(writeId > this.lastWriteId_, 'Stacking an older write on top of newer ones');\n if (visible === undefined) {\n visible = true;\n }\n this.allWrites_.push({\n path: path,\n snap: snap,\n writeId: writeId,\n visible: visible\n });\n if (visible) {\n this.visibleWrites_ = this.visibleWrites_.addWrite(path, snap);\n }\n this.lastWriteId_ = writeId;\n };\n /**\n * Record a new merge from user code.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} writeId\n */\n WriteTree.prototype.addMerge = function (path, changedChildren, writeId) {\n util_2.assert(writeId > this.lastWriteId_, 'Stacking an older merge on top of newer ones');\n this.allWrites_.push({\n path: path,\n children: changedChildren,\n writeId: writeId,\n visible: true\n });\n this.visibleWrites_ = this.visibleWrites_.addWrites(path, changedChildren);\n this.lastWriteId_ = writeId;\n };\n /**\n * @param {!number} writeId\n * @return {?WriteRecord}\n */\n WriteTree.prototype.getWrite = function (writeId) {\n for (var i = 0; i < this.allWrites_.length; i++) {\n var record = this.allWrites_[i];\n if (record.writeId === writeId) {\n return record;\n }\n }\n return null;\n };\n /**\n * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates\n * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.\n *\n * @param {!number} writeId\n * @return {boolean} true if the write may have been visible (meaning we'll need to reevaluate / raise\n * events as a result).\n */\n WriteTree.prototype.removeWrite = function (writeId) {\n // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied\n // out of order.\n //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;\n //assert(validClear, \"Either we don't have this write, or it's the first one in the queue\");\n var _this = this;\n var idx = this.allWrites_.findIndex(function (s) {\n return s.writeId === writeId;\n });\n util_2.assert(idx >= 0, 'removeWrite called with nonexistent writeId.');\n var writeToRemove = this.allWrites_[idx];\n this.allWrites_.splice(idx, 1);\n var removedWriteWasVisible = writeToRemove.visible;\n var removedWriteOverlapsWithOtherWrites = false;\n var i = this.allWrites_.length - 1;\n while (removedWriteWasVisible && i >= 0) {\n var currentWrite = this.allWrites_[i];\n if (currentWrite.visible) {\n if (i >= idx &&\n this.recordContainsPath_(currentWrite, writeToRemove.path)) {\n // The removed write was completely shadowed by a subsequent write.\n removedWriteWasVisible = false;\n }\n else if (writeToRemove.path.contains(currentWrite.path)) {\n // Either we're covering some writes or they're covering part of us (depending on which came first).\n removedWriteOverlapsWithOtherWrites = true;\n }\n }\n i--;\n }\n if (!removedWriteWasVisible) {\n return false;\n }\n else if (removedWriteOverlapsWithOtherWrites) {\n // There's some shadowing going on. Just rebuild the visible writes from scratch.\n this.resetTree_();\n return true;\n }\n else {\n // There's no shadowing. We can safely just remove the write(s) from visibleWrites.\n if (writeToRemove.snap) {\n this.visibleWrites_ = this.visibleWrites_.removeWrite(writeToRemove.path);\n }\n else {\n var children = writeToRemove.children;\n util_1.forEach(children, function (childName) {\n _this.visibleWrites_ = _this.visibleWrites_.removeWrite(writeToRemove.path.child(childName));\n });\n }\n return true;\n }\n };\n /**\n * Return a complete snapshot for the given path if there's visible write data at that path, else null.\n * No server data is considered.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTree.prototype.getCompleteWriteData = function (path) {\n return this.visibleWrites_.getCompleteNode(path);\n };\n /**\n * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden\n * writes), attempt to calculate a complete snapshot for the given path\n *\n * @param {!Path} treePath\n * @param {?Node} completeServerCache\n * @param {Array.=} writeIdsToExclude An optional set to be excluded\n * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false\n * @return {?Node}\n */\n WriteTree.prototype.calcCompleteEventCache = function (treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {\n if (!writeIdsToExclude && !includeHiddenWrites) {\n var shadowingNode = this.visibleWrites_.getCompleteNode(treePath);\n if (shadowingNode != null) {\n return shadowingNode;\n }\n else {\n var subMerge = this.visibleWrites_.childCompoundWrite(treePath);\n if (subMerge.isEmpty()) {\n return completeServerCache;\n }\n else if (completeServerCache == null &&\n !subMerge.hasCompleteWrite(Path_1.Path.Empty)) {\n // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow\n return null;\n }\n else {\n var layeredCache = completeServerCache || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return subMerge.apply(layeredCache);\n }\n }\n }\n else {\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n if (!includeHiddenWrites && merge.isEmpty()) {\n return completeServerCache;\n }\n else {\n // If the server cache is null, and we don't have a complete cache, we need to return null\n if (!includeHiddenWrites &&\n completeServerCache == null &&\n !merge.hasCompleteWrite(Path_1.Path.Empty)) {\n return null;\n }\n else {\n var filter = function (write) {\n return ((write.visible || includeHiddenWrites) &&\n (!writeIdsToExclude ||\n !~writeIdsToExclude.indexOf(write.writeId)) &&\n (write.path.contains(treePath) || treePath.contains(write.path)));\n };\n var mergeAtPath = WriteTree.layerTree_(this.allWrites_, filter, treePath);\n var layeredCache = completeServerCache || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return mergeAtPath.apply(layeredCache);\n }\n }\n }\n };\n /**\n * With optional, underlying server data, attempt to return a children node of children that we have complete data for.\n * Used when creating new views, to pre-fill their complete event children snapshot.\n *\n * @param {!Path} treePath\n * @param {?ChildrenNode} completeServerChildren\n * @return {!ChildrenNode}\n */\n WriteTree.prototype.calcCompleteEventChildren = function (treePath, completeServerChildren) {\n var completeChildren = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var topLevelSet = this.visibleWrites_.getCompleteNode(treePath);\n if (topLevelSet) {\n if (!topLevelSet.isLeafNode()) {\n // we're shadowing everything. Return the children.\n topLevelSet.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childSnap) {\n completeChildren = completeChildren.updateImmediateChild(childName, childSnap);\n });\n }\n return completeChildren;\n }\n else if (completeServerChildren) {\n // Layer any children we have on top of this\n // We know we don't have a top-level set, so just enumerate existing children\n var merge_1 = this.visibleWrites_.childCompoundWrite(treePath);\n completeServerChildren.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n var node = merge_1\n .childCompoundWrite(new Path_1.Path(childName))\n .apply(childNode);\n completeChildren = completeChildren.updateImmediateChild(childName, node);\n });\n // Add any complete children we have from the set\n merge_1.getCompleteChildren().forEach(function (namedNode) {\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\n });\n return completeChildren;\n }\n else {\n // We don't have anything to layer on top of. Layer on any children we have\n // Note that we can return an empty snap if we have a defined delete\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n merge.getCompleteChildren().forEach(function (namedNode) {\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\n });\n return completeChildren;\n }\n };\n /**\n * Given that the underlying server data has updated, determine what, if anything, needs to be\n * applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events\n *\n * Either existingEventSnap or existingServerSnap must exist\n *\n * @param {!Path} treePath\n * @param {!Path} childPath\n * @param {?Node} existingEventSnap\n * @param {?Node} existingServerSnap\n * @return {?Node}\n */\n WriteTree.prototype.calcEventCacheAfterServerOverwrite = function (treePath, childPath, existingEventSnap, existingServerSnap) {\n util_2.assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');\n var path = treePath.child(childPath);\n if (this.visibleWrites_.hasCompleteWrite(path)) {\n // At this point we can probably guarantee that we're in case 2, meaning no events\n // May need to check visibility while doing the findRootMostValueAndPath call\n return null;\n }\n else {\n // No complete shadowing. We're either partially shadowing or not shadowing at all.\n var childMerge = this.visibleWrites_.childCompoundWrite(path);\n if (childMerge.isEmpty()) {\n // We're not shadowing at all. Case 1\n return existingServerSnap.getChild(childPath);\n }\n else {\n // This could be more efficient if the serverNode + updates doesn't change the eventSnap\n // However this is tricky to find out, since user updates don't necessary change the server\n // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server\n // adds nodes, but doesn't change any existing writes. It is therefore not enough to\n // only check if the updates change the serverNode.\n // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?\n return childMerge.apply(existingServerSnap.getChild(childPath));\n }\n }\n };\n /**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n *\n * @param {!Path} treePath\n * @param {!string} childKey\n * @param {!CacheNode} existingServerSnap\n * @return {?Node}\n */\n WriteTree.prototype.calcCompleteChild = function (treePath, childKey, existingServerSnap) {\n var path = treePath.child(childKey);\n var shadowingNode = this.visibleWrites_.getCompleteNode(path);\n if (shadowingNode != null) {\n return shadowingNode;\n }\n else {\n if (existingServerSnap.isCompleteForChild(childKey)) {\n var childMerge = this.visibleWrites_.childCompoundWrite(path);\n return childMerge.apply(existingServerSnap.getNode().getImmediateChild(childKey));\n }\n else {\n return null;\n }\n }\n };\n /**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTree.prototype.shadowingWrite = function (path) {\n return this.visibleWrites_.getCompleteNode(path);\n };\n /**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window.\n *\n * @param {!Path} treePath\n * @param {?Node} completeServerData\n * @param {!NamedNode} startPost\n * @param {!number} count\n * @param {boolean} reverse\n * @param {!Index} index\n * @return {!Array.}\n */\n WriteTree.prototype.calcIndexedSlice = function (treePath, completeServerData, startPost, count, reverse, index) {\n var toIterate;\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n var shadowingNode = merge.getCompleteNode(Path_1.Path.Empty);\n if (shadowingNode != null) {\n toIterate = shadowingNode;\n }\n else if (completeServerData != null) {\n toIterate = merge.apply(completeServerData);\n }\n else {\n // no children to iterate on\n return [];\n }\n toIterate = toIterate.withIndex(index);\n if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {\n var nodes = [];\n var cmp = index.getCompare();\n var iter = reverse\n ? toIterate.getReverseIteratorFrom(startPost, index)\n : toIterate.getIteratorFrom(startPost, index);\n var next = iter.getNext();\n while (next && nodes.length < count) {\n if (cmp(next, startPost) !== 0) {\n nodes.push(next);\n }\n next = iter.getNext();\n }\n return nodes;\n }\n else {\n return [];\n }\n };\n /**\n * @param {!WriteRecord} writeRecord\n * @param {!Path} path\n * @return {boolean}\n * @private\n */\n WriteTree.prototype.recordContainsPath_ = function (writeRecord, path) {\n if (writeRecord.snap) {\n return writeRecord.path.contains(path);\n }\n else {\n // findKey can return undefined, so use !! to coerce to boolean\n return !!util_1.findKey(writeRecord.children, function (childSnap, childName) {\n return writeRecord.path.child(childName).contains(path);\n });\n }\n };\n /**\n * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots\n * @private\n */\n WriteTree.prototype.resetTree_ = function () {\n this.visibleWrites_ = WriteTree.layerTree_(this.allWrites_, WriteTree.DefaultFilter_, Path_1.Path.Empty);\n if (this.allWrites_.length > 0) {\n this.lastWriteId_ = this.allWrites_[this.allWrites_.length - 1].writeId;\n }\n else {\n this.lastWriteId_ = -1;\n }\n };\n /**\n * The default filter used when constructing the tree. Keep everything that's visible.\n *\n * @param {!WriteRecord} write\n * @return {boolean}\n * @private\n */\n WriteTree.DefaultFilter_ = function (write) {\n return write.visible;\n };\n /**\n * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of\n * event data at that path.\n *\n * @param {!Array.} writes\n * @param {!function(!WriteRecord):boolean} filter\n * @param {!Path} treeRoot\n * @return {!CompoundWrite}\n * @private\n */\n WriteTree.layerTree_ = function (writes, filter, treeRoot) {\n var compoundWrite = CompoundWrite_1.CompoundWrite.Empty;\n for (var i = 0; i < writes.length; ++i) {\n var write = writes[i];\n // Theory, a later set will either:\n // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction\n // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction\n if (filter(write)) {\n var writePath = write.path;\n var relativePath = void 0;\n if (write.snap) {\n if (treeRoot.contains(writePath)) {\n relativePath = Path_1.Path.relativePath(treeRoot, writePath);\n compoundWrite = compoundWrite.addWrite(relativePath, write.snap);\n }\n else if (writePath.contains(treeRoot)) {\n relativePath = Path_1.Path.relativePath(writePath, treeRoot);\n compoundWrite = compoundWrite.addWrite(Path_1.Path.Empty, write.snap.getChild(relativePath));\n }\n else {\n // There is no overlap between root path and write path, ignore write\n }\n }\n else if (write.children) {\n if (treeRoot.contains(writePath)) {\n relativePath = Path_1.Path.relativePath(treeRoot, writePath);\n compoundWrite = compoundWrite.addWrites(relativePath, write.children);\n }\n else if (writePath.contains(treeRoot)) {\n relativePath = Path_1.Path.relativePath(writePath, treeRoot);\n if (relativePath.isEmpty()) {\n compoundWrite = compoundWrite.addWrites(Path_1.Path.Empty, write.children);\n }\n else {\n var child = util_1.safeGet(write.children, relativePath.getFront());\n if (child) {\n // There exists a child in this node that matches the root path\n var deepNode = child.getChild(relativePath.popFront());\n compoundWrite = compoundWrite.addWrite(Path_1.Path.Empty, deepNode);\n }\n }\n }\n else {\n // There is no overlap between root path and write path, ignore write\n }\n }\n else {\n throw util_2.assertionError('WriteRecord should have .snap or .children');\n }\n }\n }\n return compoundWrite;\n };\n return WriteTree;\n}());\nexports.WriteTree = WriteTree;\n/**\n * A WriteTreeRef wraps a WriteTree and a path, for convenient access to a particular subtree. All of the methods\n * just proxy to the underlying WriteTree.\n *\n * @constructor\n */\nvar WriteTreeRef = /** @class */ (function () {\n /**\n * @param {!Path} path\n * @param {!WriteTree} writeTree\n */\n function WriteTreeRef(path, writeTree) {\n this.treePath_ = path;\n this.writeTree_ = writeTree;\n }\n /**\n * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used\n * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node\n * can lead to a more expensive calculation.\n *\n * @param {?Node} completeServerCache\n * @param {Array.=} writeIdsToExclude Optional writes to exclude.\n * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcCompleteEventCache = function (completeServerCache, writeIdsToExclude, includeHiddenWrites) {\n return this.writeTree_.calcCompleteEventCache(this.treePath_, completeServerCache, writeIdsToExclude, includeHiddenWrites);\n };\n /**\n * If possible, returns a children node containing all of the complete children we have data for. The returned data is a\n * mix of the given server data and write data.\n *\n * @param {?ChildrenNode} completeServerChildren\n * @return {!ChildrenNode}\n */\n WriteTreeRef.prototype.calcCompleteEventChildren = function (completeServerChildren) {\n return this.writeTree_.calcCompleteEventChildren(this.treePath_, completeServerChildren);\n };\n /**\n * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,\n * if anything, needs to be applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events should be raised\n *\n * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert\n *\n * @param {!Path} path\n * @param {?Node} existingEventSnap\n * @param {?Node} existingServerSnap\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcEventCacheAfterServerOverwrite = function (path, existingEventSnap, existingServerSnap) {\n return this.writeTree_.calcEventCacheAfterServerOverwrite(this.treePath_, path, existingEventSnap, existingServerSnap);\n };\n /**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTreeRef.prototype.shadowingWrite = function (path) {\n return this.writeTree_.shadowingWrite(this.treePath_.child(path));\n };\n /**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window\n *\n * @param {?Node} completeServerData\n * @param {!NamedNode} startPost\n * @param {!number} count\n * @param {boolean} reverse\n * @param {!Index} index\n * @return {!Array.}\n */\n WriteTreeRef.prototype.calcIndexedSlice = function (completeServerData, startPost, count, reverse, index) {\n return this.writeTree_.calcIndexedSlice(this.treePath_, completeServerData, startPost, count, reverse, index);\n };\n /**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n *\n * @param {!string} childKey\n * @param {!CacheNode} existingServerCache\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcCompleteChild = function (childKey, existingServerCache) {\n return this.writeTree_.calcCompleteChild(this.treePath_, childKey, existingServerCache);\n };\n /**\n * Return a WriteTreeRef for a child.\n *\n * @param {string} childName\n * @return {!WriteTreeRef}\n */\n WriteTreeRef.prototype.child = function (childName) {\n return new WriteTreeRef(this.treePath_.child(childName), this.writeTree_);\n };\n return WriteTreeRef;\n}());\nexports.WriteTreeRef = WriteTreeRef;\n\n//# sourceMappingURL=WriteTree.js.map\n\n\n/***/ }),\n/* 97 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ImmutableTree_1 = __webpack_require__(24);\nvar Path_1 = __webpack_require__(3);\nvar util_1 = __webpack_require__(0);\nvar Node_1 = __webpack_require__(6);\nvar PriorityIndex_1 = __webpack_require__(4);\nvar util_2 = __webpack_require__(0);\n/**\n * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with\n * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write\n * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write\n * to reflect the write added.\n *\n * @constructor\n * @param {!ImmutableTree.} writeTree\n */\nvar CompoundWrite = /** @class */ (function () {\n function CompoundWrite(writeTree_) {\n this.writeTree_ = writeTree_;\n }\n /**\n * @param {!Path} path\n * @param {!Node} node\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.addWrite = function (path, node) {\n if (path.isEmpty()) {\n return new CompoundWrite(new ImmutableTree_1.ImmutableTree(node));\n }\n else {\n var rootmost = this.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n var rootMostPath = rootmost.path;\n var value = rootmost.value;\n var relativePath = Path_1.Path.relativePath(rootMostPath, path);\n value = value.updateChild(relativePath, node);\n return new CompoundWrite(this.writeTree_.set(rootMostPath, value));\n }\n else {\n var subtree = new ImmutableTree_1.ImmutableTree(node);\n var newWriteTree = this.writeTree_.setTree(path, subtree);\n return new CompoundWrite(newWriteTree);\n }\n }\n };\n /**\n * @param {!Path} path\n * @param {!Object.} updates\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.addWrites = function (path, updates) {\n var newWrite = this;\n util_1.forEach(updates, function (childKey, node) {\n newWrite = newWrite.addWrite(path.child(childKey), node);\n });\n return newWrite;\n };\n /**\n * Will remove a write at the given path and deeper paths. This will not modify a write at a higher\n * location, which must be removed by calling this method with that path.\n *\n * @param {!Path} path The path at which a write and all deeper writes should be removed\n * @return {!CompoundWrite} The new CompoundWrite with the removed path\n */\n CompoundWrite.prototype.removeWrite = function (path) {\n if (path.isEmpty()) {\n return CompoundWrite.Empty;\n }\n else {\n var newWriteTree = this.writeTree_.setTree(path, ImmutableTree_1.ImmutableTree.Empty);\n return new CompoundWrite(newWriteTree);\n }\n };\n /**\n * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be\n * considered \"complete\".\n *\n * @param {!Path} path The path to check for\n * @return {boolean} Whether there is a complete write at that path\n */\n CompoundWrite.prototype.hasCompleteWrite = function (path) {\n return this.getCompleteNode(path) != null;\n };\n /**\n * Returns a node for a path if and only if the node is a \"complete\" overwrite at that path. This will not aggregate\n * writes from deeper paths, but will return child nodes from a more shallow path.\n *\n * @param {!Path} path The path to get a complete write\n * @return {?Node} The node if complete at that path, or null otherwise.\n */\n CompoundWrite.prototype.getCompleteNode = function (path) {\n var rootmost = this.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n return this.writeTree_\n .get(rootmost.path)\n .getChild(Path_1.Path.relativePath(rootmost.path, path));\n }\n else {\n return null;\n }\n };\n /**\n * Returns all children that are guaranteed to be a complete overwrite.\n *\n * @return {!Array.} A list of all complete children.\n */\n CompoundWrite.prototype.getCompleteChildren = function () {\n var children = [];\n var node = this.writeTree_.value;\n if (node != null) {\n // If it's a leaf node, it has no children; so nothing to do.\n if (!node.isLeafNode()) {\n node.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n children.push(new Node_1.NamedNode(childName, childNode));\n });\n }\n }\n else {\n this.writeTree_.children.inorderTraversal(function (childName, childTree) {\n if (childTree.value != null) {\n children.push(new Node_1.NamedNode(childName, childTree.value));\n }\n });\n }\n return children;\n };\n /**\n * @param {!Path} path\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.childCompoundWrite = function (path) {\n if (path.isEmpty()) {\n return this;\n }\n else {\n var shadowingNode = this.getCompleteNode(path);\n if (shadowingNode != null) {\n return new CompoundWrite(new ImmutableTree_1.ImmutableTree(shadowingNode));\n }\n else {\n return new CompoundWrite(this.writeTree_.subtree(path));\n }\n }\n };\n /**\n * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.\n * @return {boolean} Whether this CompoundWrite is empty\n */\n CompoundWrite.prototype.isEmpty = function () {\n return this.writeTree_.isEmpty();\n };\n /**\n * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the\n * node\n * @param {!Node} node The node to apply this CompoundWrite to\n * @return {!Node} The node with all writes applied\n */\n CompoundWrite.prototype.apply = function (node) {\n return CompoundWrite.applySubtreeWrite_(Path_1.Path.Empty, this.writeTree_, node);\n };\n /**\n * @type {!CompoundWrite}\n */\n CompoundWrite.Empty = new CompoundWrite(new ImmutableTree_1.ImmutableTree(null));\n /**\n * @param {!Path} relativePath\n * @param {!ImmutableTree.} writeTree\n * @param {!Node} node\n * @return {!Node}\n * @private\n */\n CompoundWrite.applySubtreeWrite_ = function (relativePath, writeTree, node) {\n if (writeTree.value != null) {\n // Since there a write is always a leaf, we're done here\n return node.updateChild(relativePath, writeTree.value);\n }\n else {\n var priorityWrite_1 = null;\n writeTree.children.inorderTraversal(function (childKey, childTree) {\n if (childKey === '.priority') {\n // Apply priorities at the end so we don't update priorities for either empty nodes or forget\n // to apply priorities to empty nodes that are later filled\n util_2.assert(childTree.value !== null, 'Priority writes must always be leaf nodes');\n priorityWrite_1 = childTree.value;\n }\n else {\n node = CompoundWrite.applySubtreeWrite_(relativePath.child(childKey), childTree, node);\n }\n });\n // If there was a priority write, we only apply it if the node is not empty\n if (!node.getChild(relativePath).isEmpty() && priorityWrite_1 !== null) {\n node = node.updateChild(relativePath.child('.priority'), priorityWrite_1);\n }\n return node;\n }\n };\n return CompoundWrite;\n}());\nexports.CompoundWrite = CompoundWrite;\n\n//# sourceMappingURL=CompoundWrite.js.map\n\n\n/***/ }),\n/* 98 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ChildrenNode_1 = __webpack_require__(5);\n/**\n * Mutable object which basically just stores a reference to the \"latest\" immutable snapshot.\n *\n * @constructor\n */\nvar SnapshotHolder = /** @class */ (function () {\n function SnapshotHolder() {\n this.rootNode_ = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n SnapshotHolder.prototype.getNode = function (path) {\n return this.rootNode_.getChild(path);\n };\n SnapshotHolder.prototype.updateSnapshot = function (path, newSnapshotNode) {\n this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);\n };\n return SnapshotHolder;\n}());\nexports.SnapshotHolder = SnapshotHolder;\n\n//# sourceMappingURL=SnapshotHolder.js.map\n\n\n/***/ }),\n/* 99 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(1);\n/**\n * Abstraction around FirebaseApp's token fetching capabilities.\n */\nvar AuthTokenProvider = /** @class */ (function () {\n /**\n * @param {!FirebaseApp} app_\n */\n function AuthTokenProvider(app_) {\n this.app_ = app_;\n }\n /**\n * @param {boolean} forceRefresh\n * @return {!Promise}\n */\n AuthTokenProvider.prototype.getToken = function (forceRefresh) {\n return this.app_['INTERNAL']['getToken'](forceRefresh).then(null, \n // .catch\n function (error) {\n // TODO: Need to figure out all the cases this is raised and whether\n // this makes sense.\n if (error && error.code === 'auth/token-not-initialized') {\n util_1.log('Got auth/token-not-initialized error. Treating as null token.');\n return null;\n }\n else {\n return Promise.reject(error);\n }\n });\n };\n AuthTokenProvider.prototype.addTokenChangeListener = function (listener) {\n // TODO: We might want to wrap the listener and call it with no args to\n // avoid a leaky abstraction, but that makes removing the listener harder.\n this.app_['INTERNAL']['addAuthTokenListener'](listener);\n };\n AuthTokenProvider.prototype.removeTokenChangeListener = function (listener) {\n this.app_['INTERNAL']['removeAuthTokenListener'](listener);\n };\n AuthTokenProvider.prototype.notifyForInvalidToken = function () {\n var errorMessage = 'Provided authentication credentials for the app named \"' +\n this.app_.name +\n '\" are invalid. This usually indicates your app was not ' +\n 'initialized correctly. ';\n if ('credential' in this.app_.options) {\n errorMessage +=\n 'Make sure the \"credential\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n }\n else if ('serviceAccount' in this.app_.options) {\n errorMessage +=\n 'Make sure the \"serviceAccount\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n }\n else {\n errorMessage +=\n 'Make sure the \"apiKey\" and \"databaseURL\" properties provided to ' +\n 'initializeApp() match the values provided for your app at ' +\n 'https://console.firebase.google.com/.';\n }\n util_1.warn(errorMessage);\n };\n return AuthTokenProvider;\n}());\nexports.AuthTokenProvider = AuthTokenProvider;\n\n//# sourceMappingURL=AuthTokenProvider.js.map\n\n\n/***/ }),\n/* 100 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\n/**\n * Tracks a collection of stats.\n *\n * @constructor\n */\nvar StatsCollection = /** @class */ (function () {\n function StatsCollection() {\n this.counters_ = {};\n }\n StatsCollection.prototype.incrementCounter = function (name, amount) {\n if (amount === void 0) { amount = 1; }\n if (!util_2.contains(this.counters_, name))\n this.counters_[name] = 0;\n this.counters_[name] += amount;\n };\n StatsCollection.prototype.get = function () {\n return util_1.deepCopy(this.counters_);\n };\n return StatsCollection;\n}());\nexports.StatsCollection = StatsCollection;\n\n//# sourceMappingURL=StatsCollection.js.map\n\n\n/***/ }),\n/* 101 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar StatsListener_1 = __webpack_require__(50);\n// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably\n// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10\n// seconds to try to ensure the Firebase connection is established / settled.\nvar FIRST_STATS_MIN_TIME = 10 * 1000;\nvar FIRST_STATS_MAX_TIME = 30 * 1000;\n// We'll continue to report stats on average every 5 minutes.\nvar REPORT_STATS_INTERVAL = 5 * 60 * 1000;\n/**\n * @constructor\n */\nvar StatsReporter = /** @class */ (function () {\n /**\n * @param collection\n * @param server_\n */\n function StatsReporter(collection, server_) {\n this.server_ = server_;\n this.statsToReport_ = {};\n this.statsListener_ = new StatsListener_1.StatsListener(collection);\n var timeout = FIRST_STATS_MIN_TIME +\n (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();\n util_2.setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));\n }\n StatsReporter.prototype.includeStat = function (stat) {\n this.statsToReport_[stat] = true;\n };\n StatsReporter.prototype.reportStats_ = function () {\n var _this = this;\n var stats = this.statsListener_.get();\n var reportedStats = {};\n var haveStatsToReport = false;\n util_1.forEach(stats, function (stat, value) {\n if (value > 0 && util_1.contains(_this.statsToReport_, stat)) {\n reportedStats[stat] = value;\n haveStatsToReport = true;\n }\n });\n if (haveStatsToReport) {\n this.server_.reportStats(reportedStats);\n }\n // queue our next run.\n util_2.setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));\n };\n return StatsReporter;\n}());\nexports.StatsReporter = StatsReporter;\n\n//# sourceMappingURL=StatsReporter.js.map\n\n\n/***/ }),\n/* 102 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(1);\n/**\n * The event queue serves a few purposes:\n * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more\n * events being queued.\n * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,\n * raiseQueuedEvents() is called again, the \"inner\" call will pick up raising events where the \"outer\" call\n * left off, ensuring that the events are still raised synchronously and in order.\n * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued\n * events are raised synchronously.\n *\n * NOTE: This can all go away if/when we move to async events.\n *\n * @constructor\n */\nvar EventQueue = /** @class */ (function () {\n function EventQueue() {\n /**\n * @private\n * @type {!Array.}\n */\n this.eventLists_ = [];\n /**\n * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.\n * @private\n * @type {!number}\n */\n this.recursionDepth_ = 0;\n }\n /**\n * @param {!Array.} eventDataList The new events to queue.\n */\n EventQueue.prototype.queueEvents = function (eventDataList) {\n // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.\n var currList = null;\n for (var i = 0; i < eventDataList.length; i++) {\n var eventData = eventDataList[i];\n var eventPath = eventData.getPath();\n if (currList !== null && !eventPath.equals(currList.getPath())) {\n this.eventLists_.push(currList);\n currList = null;\n }\n if (currList === null) {\n currList = new EventList(eventPath);\n }\n currList.add(eventData);\n }\n if (currList) {\n this.eventLists_.push(currList);\n }\n };\n /**\n * Queues the specified events and synchronously raises all events (including previously queued ones)\n * for the specified path.\n *\n * It is assumed that the new events are all for the specified path.\n *\n * @param {!Path} path The path to raise events for.\n * @param {!Array.} eventDataList The new events to raise.\n */\n EventQueue.prototype.raiseEventsAtPath = function (path, eventDataList) {\n this.queueEvents(eventDataList);\n this.raiseQueuedEventsMatchingPredicate_(function (eventPath) {\n return eventPath.equals(path);\n });\n };\n /**\n * Queues the specified events and synchronously raises all events (including previously queued ones) for\n * locations related to the specified change path (i.e. all ancestors and descendants).\n *\n * It is assumed that the new events are all related (ancestor or descendant) to the specified path.\n *\n * @param {!Path} changedPath The path to raise events for.\n * @param {!Array.} eventDataList The events to raise\n */\n EventQueue.prototype.raiseEventsForChangedPath = function (changedPath, eventDataList) {\n this.queueEvents(eventDataList);\n this.raiseQueuedEventsMatchingPredicate_(function (eventPath) {\n return eventPath.contains(changedPath) || changedPath.contains(eventPath);\n });\n };\n /**\n * @param {!function(!Path):boolean} predicate\n * @private\n */\n EventQueue.prototype.raiseQueuedEventsMatchingPredicate_ = function (predicate) {\n this.recursionDepth_++;\n var sentAll = true;\n for (var i = 0; i < this.eventLists_.length; i++) {\n var eventList = this.eventLists_[i];\n if (eventList) {\n var eventPath = eventList.getPath();\n if (predicate(eventPath)) {\n this.eventLists_[i].raise();\n this.eventLists_[i] = null;\n }\n else {\n sentAll = false;\n }\n }\n }\n if (sentAll) {\n this.eventLists_ = [];\n }\n this.recursionDepth_--;\n };\n return EventQueue;\n}());\nexports.EventQueue = EventQueue;\n/**\n * @param {!Path} path\n * @constructor\n */\nvar EventList = /** @class */ (function () {\n function EventList(path_) {\n this.path_ = path_;\n /**\n * @type {!Array.}\n * @private\n */\n this.events_ = [];\n }\n /**\n * @param {!Event} eventData\n */\n EventList.prototype.add = function (eventData) {\n this.events_.push(eventData);\n };\n /**\n * Iterates through the list and raises each event\n */\n EventList.prototype.raise = function () {\n for (var i = 0; i < this.events_.length; i++) {\n var eventData = this.events_[i];\n if (eventData !== null) {\n this.events_[i] = null;\n var eventFn = eventData.getEventRunner();\n if (util_1.logger) {\n util_1.log('event: ' + eventData.toString());\n }\n util_1.exceptionGuard(eventFn);\n }\n }\n };\n /**\n * @return {!Path}\n */\n EventList.prototype.getPath = function () {\n return this.path_;\n };\n return EventList;\n}());\nexports.EventList = EventList;\n\n//# sourceMappingURL=EventQueue.js.map\n\n\n/***/ }),\n/* 103 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = __webpack_require__(2);\nvar EventEmitter_1 = __webpack_require__(52);\nvar util_1 = __webpack_require__(0);\n/**\n * @extends {EventEmitter}\n */\nvar VisibilityMonitor = /** @class */ (function (_super) {\n tslib_1.__extends(VisibilityMonitor, _super);\n function VisibilityMonitor() {\n var _this = _super.call(this, ['visible']) || this;\n var hidden;\n var visibilityChange;\n if (typeof document !== 'undefined' &&\n typeof document.addEventListener !== 'undefined') {\n if (typeof document['hidden'] !== 'undefined') {\n // Opera 12.10 and Firefox 18 and later support\n visibilityChange = 'visibilitychange';\n hidden = 'hidden';\n }\n else if (typeof document['mozHidden'] !== 'undefined') {\n visibilityChange = 'mozvisibilitychange';\n hidden = 'mozHidden';\n }\n else if (typeof document['msHidden'] !== 'undefined') {\n visibilityChange = 'msvisibilitychange';\n hidden = 'msHidden';\n }\n else if (typeof document['webkitHidden'] !== 'undefined') {\n visibilityChange = 'webkitvisibilitychange';\n hidden = 'webkitHidden';\n }\n }\n // Initially, we always assume we are visible. This ensures that in browsers\n // without page visibility support or in cases where we are never visible\n // (e.g. chrome extension), we act as if we are visible, i.e. don't delay\n // reconnects\n _this.visible_ = true;\n if (visibilityChange) {\n document.addEventListener(visibilityChange, function () {\n var visible = !document[hidden];\n if (visible !== _this.visible_) {\n _this.visible_ = visible;\n _this.trigger('visible', visible);\n }\n }, false);\n }\n return _this;\n }\n VisibilityMonitor.getInstance = function () {\n return new VisibilityMonitor();\n };\n /**\n * @param {!string} eventType\n * @return {Array.}\n */\n VisibilityMonitor.prototype.getInitialEvent = function (eventType) {\n util_1.assert(eventType === 'visible', 'Unknown event type: ' + eventType);\n return [this.visible_];\n };\n return VisibilityMonitor;\n}(EventEmitter_1.EventEmitter));\nexports.VisibilityMonitor = VisibilityMonitor;\n\n//# sourceMappingURL=VisibilityMonitor.js.map\n\n\n/***/ }),\n/* 104 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = __webpack_require__(2);\nvar util_1 = __webpack_require__(0);\nvar EventEmitter_1 = __webpack_require__(52);\nvar util_2 = __webpack_require__(0);\n/**\n * Monitors online state (as reported by window.online/offline events).\n *\n * The expectation is that this could have many false positives (thinks we are online\n * when we're not), but no false negatives. So we can safely use it to determine when\n * we definitely cannot reach the internet.\n *\n * @extends {EventEmitter}\n */\nvar OnlineMonitor = /** @class */ (function (_super) {\n tslib_1.__extends(OnlineMonitor, _super);\n function OnlineMonitor() {\n var _this = _super.call(this, ['online']) || this;\n _this.online_ = true;\n // We've had repeated complaints that Cordova apps can get stuck \"offline\", e.g.\n // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810\n // It would seem that the 'online' event does not always fire consistently. So we disable it\n // for Cordova.\n if (typeof window !== 'undefined' &&\n typeof window.addEventListener !== 'undefined' &&\n !util_2.isMobileCordova()) {\n window.addEventListener('online', function () {\n if (!_this.online_) {\n _this.online_ = true;\n _this.trigger('online', true);\n }\n }, false);\n window.addEventListener('offline', function () {\n if (_this.online_) {\n _this.online_ = false;\n _this.trigger('online', false);\n }\n }, false);\n }\n return _this;\n }\n OnlineMonitor.getInstance = function () {\n return new OnlineMonitor();\n };\n /**\n * @param {!string} eventType\n * @return {Array.}\n */\n OnlineMonitor.prototype.getInitialEvent = function (eventType) {\n util_1.assert(eventType === 'online', 'Unknown event type: ' + eventType);\n return [this.online_];\n };\n /**\n * @return {boolean}\n */\n OnlineMonitor.prototype.currentlyOnline = function () {\n return this.online_;\n };\n return OnlineMonitor;\n}(EventEmitter_1.EventEmitter));\nexports.OnlineMonitor = OnlineMonitor;\n\n//# sourceMappingURL=OnlineMonitor.js.map\n\n\n/***/ }),\n/* 105 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar BrowserPollConnection_1 = __webpack_require__(54);\nvar WebSocketConnection_1 = __webpack_require__(55);\nvar util_1 = __webpack_require__(1);\n/**\n * Currently simplistic, this class manages what transport a Connection should use at various stages of its\n * lifecycle.\n *\n * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if\n * they are available.\n * @constructor\n */\nvar TransportManager = /** @class */ (function () {\n /**\n * @param {!RepoInfo} repoInfo Metadata around the namespace we're connecting to\n */\n function TransportManager(repoInfo) {\n this.initTransports_(repoInfo);\n }\n Object.defineProperty(TransportManager, \"ALL_TRANSPORTS\", {\n /**\n * @const\n * @type {!Array.}\n */\n get: function () {\n return [BrowserPollConnection_1.BrowserPollConnection, WebSocketConnection_1.WebSocketConnection];\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @param {!RepoInfo} repoInfo\n * @private\n */\n TransportManager.prototype.initTransports_ = function (repoInfo) {\n var isWebSocketsAvailable = WebSocketConnection_1.WebSocketConnection && WebSocketConnection_1.WebSocketConnection['isAvailable']();\n var isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection_1.WebSocketConnection.previouslyFailed();\n if (repoInfo.webSocketOnly) {\n if (!isWebSocketsAvailable)\n util_1.warn(\"wss:// URL used, but browser isn't known to support websockets. Trying anyway.\");\n isSkipPollConnection = true;\n }\n if (isSkipPollConnection) {\n this.transports_ = [WebSocketConnection_1.WebSocketConnection];\n }\n else {\n var transports_1 = (this.transports_ = []);\n util_1.each(TransportManager.ALL_TRANSPORTS, function (i, transport) {\n if (transport && transport['isAvailable']()) {\n transports_1.push(transport);\n }\n });\n }\n };\n /**\n * @return {function(new:Transport, !string, !RepoInfo, string=, string=)} The constructor for the\n * initial transport to use\n */\n TransportManager.prototype.initialTransport = function () {\n if (this.transports_.length > 0) {\n return this.transports_[0];\n }\n else {\n throw new Error('No transports available');\n }\n };\n /**\n * @return {?function(new:Transport, function(),function(), string=)} The constructor for the next\n * transport, or null\n */\n TransportManager.prototype.upgradeTransport = function () {\n if (this.transports_.length > 1) {\n return this.transports_[1];\n }\n else {\n return null;\n }\n };\n return TransportManager;\n}());\nexports.TransportManager = TransportManager;\n\n//# sourceMappingURL=TransportManager.js.map\n\n\n/***/ }),\n/* 106 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(1);\n/**\n * This class ensures the packets from the server arrive in order\n * This class takes data from the server and ensures it gets passed into the callbacks in order.\n * @constructor\n */\nvar PacketReceiver = /** @class */ (function () {\n /**\n * @param onMessage_\n */\n function PacketReceiver(onMessage_) {\n this.onMessage_ = onMessage_;\n this.pendingResponses = [];\n this.currentResponseNum = 0;\n this.closeAfterResponse = -1;\n this.onClose = null;\n }\n PacketReceiver.prototype.closeAfter = function (responseNum, callback) {\n this.closeAfterResponse = responseNum;\n this.onClose = callback;\n if (this.closeAfterResponse < this.currentResponseNum) {\n this.onClose();\n this.onClose = null;\n }\n };\n /**\n * Each message from the server comes with a response number, and an array of data. The responseNumber\n * allows us to ensure that we process them in the right order, since we can't be guaranteed that all\n * browsers will respond in the same order as the requests we sent\n * @param {number} requestNum\n * @param {Array} data\n */\n PacketReceiver.prototype.handleResponse = function (requestNum, data) {\n var _this = this;\n this.pendingResponses[requestNum] = data;\n var _loop_1 = function () {\n var toProcess = this_1.pendingResponses[this_1.currentResponseNum];\n delete this_1.pendingResponses[this_1.currentResponseNum];\n var _loop_2 = function (i) {\n if (toProcess[i]) {\n util_1.exceptionGuard(function () {\n _this.onMessage_(toProcess[i]);\n });\n }\n };\n for (var i = 0; i < toProcess.length; ++i) {\n _loop_2(i);\n }\n if (this_1.currentResponseNum === this_1.closeAfterResponse) {\n if (this_1.onClose) {\n this_1.onClose();\n this_1.onClose = null;\n }\n return \"break\";\n }\n this_1.currentResponseNum++;\n };\n var this_1 = this;\n while (this.pendingResponses[this.currentResponseNum]) {\n var state_1 = _loop_1();\n if (state_1 === \"break\")\n break;\n }\n };\n return PacketReceiver;\n}());\nexports.PacketReceiver = PacketReceiver;\n\n//# sourceMappingURL=PacketReceiver.js.map\n\n\n/***/ }),\n/* 107 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = __webpack_require__(2);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar util_3 = __webpack_require__(0);\nvar util_4 = __webpack_require__(0);\nvar util_5 = __webpack_require__(0);\nvar ServerActions_1 = __webpack_require__(56);\n/**\n * An implementation of ServerActions that communicates with the server via REST requests.\n * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full\n * persistent connection (using WebSockets or long-polling)\n */\nvar ReadonlyRestClient = /** @class */ (function (_super) {\n tslib_1.__extends(ReadonlyRestClient, _super);\n /**\n * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to\n * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server\n * @param {AuthTokenProvider} authTokenProvider_\n * @implements {ServerActions}\n */\n function ReadonlyRestClient(repoInfo_, onDataUpdate_, authTokenProvider_) {\n var _this = _super.call(this) || this;\n _this.repoInfo_ = repoInfo_;\n _this.onDataUpdate_ = onDataUpdate_;\n _this.authTokenProvider_ = authTokenProvider_;\n /** @private {function(...[*])} */\n _this.log_ = util_2.logWrapper('p:rest:');\n /**\n * We don't actually need to track listens, except to prevent us calling an onComplete for a listen\n * that's been removed. :-/\n *\n * @private {!Object.}\n */\n _this.listens_ = {};\n return _this;\n }\n ReadonlyRestClient.prototype.reportStats = function (stats) {\n throw new Error('Method not implemented.');\n };\n /**\n * @param {!Query} query\n * @param {?number=} tag\n * @return {string}\n * @private\n */\n ReadonlyRestClient.getListenId_ = function (query, tag) {\n if (tag !== undefined) {\n return 'tag$' + tag;\n }\n else {\n util_1.assert(query.getQueryParams().isDefault(), \"should have a tag if it's not a default query.\");\n return query.path.toString();\n }\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.listen = function (query, currentHashFn, tag, onComplete) {\n var _this = this;\n var pathString = query.path.toString();\n this.log_('Listen called for ' + pathString + ' ' + query.queryIdentifier());\n // Mark this listener so we can tell if it's removed.\n var listenId = ReadonlyRestClient.getListenId_(query, tag);\n var thisListen = {};\n this.listens_[listenId] = thisListen;\n var queryStringParamaters = query\n .getQueryParams()\n .toRestQueryStringParameters();\n this.restRequest_(pathString + '.json', queryStringParamaters, function (error, result) {\n var data = result;\n if (error === 404) {\n data = null;\n error = null;\n }\n if (error === null) {\n _this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);\n }\n if (util_4.safeGet(_this.listens_, listenId) === thisListen) {\n var status_1;\n if (!error) {\n status_1 = 'ok';\n }\n else if (error == 401) {\n status_1 = 'permission_denied';\n }\n else {\n status_1 = 'rest_error:' + error;\n }\n onComplete(status_1, null);\n }\n });\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.unlisten = function (query, tag) {\n var listenId = ReadonlyRestClient.getListenId_(query, tag);\n delete this.listens_[listenId];\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.refreshAuthToken = function (token) {\n // no-op since we just always call getToken.\n };\n /**\n * Performs a REST request to the given path, with the provided query string parameters,\n * and any auth credentials we have.\n *\n * @param {!string} pathString\n * @param {!Object.} queryStringParameters\n * @param {?function(?number, *=)} callback\n * @private\n */\n ReadonlyRestClient.prototype.restRequest_ = function (pathString, queryStringParameters, callback) {\n var _this = this;\n if (queryStringParameters === void 0) { queryStringParameters = {}; }\n queryStringParameters['format'] = 'export';\n this.authTokenProvider_\n .getToken(/*forceRefresh=*/ false)\n .then(function (authTokenData) {\n var authToken = authTokenData && authTokenData.accessToken;\n if (authToken) {\n queryStringParameters['auth'] = authToken;\n }\n var url = (_this.repoInfo_.secure ? 'https://' : 'http://') +\n _this.repoInfo_.host +\n pathString +\n '?' +\n util_5.querystring(queryStringParameters);\n _this.log_('Sending REST request for ' + url);\n var xhr = new XMLHttpRequest();\n xhr.onreadystatechange = function () {\n if (callback && xhr.readyState === 4) {\n _this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);\n var res = null;\n if (xhr.status >= 200 && xhr.status < 300) {\n try {\n res = util_3.jsonEval(xhr.responseText);\n }\n catch (e) {\n util_2.warn('Failed to parse JSON response for ' +\n url +\n ': ' +\n xhr.responseText);\n }\n callback(null, res);\n }\n else {\n // 401 and 404 are expected.\n if (xhr.status !== 401 && xhr.status !== 404) {\n util_2.warn('Got unsuccessful REST response for ' +\n url +\n ' Status: ' +\n xhr.status);\n }\n callback(xhr.status);\n }\n callback = null;\n }\n };\n xhr.open('GET', url, /*asynchronous=*/ true);\n xhr.send();\n });\n };\n return ReadonlyRestClient;\n}(ServerActions_1.ServerActions));\nexports.ReadonlyRestClient = ReadonlyRestClient;\n\n//# sourceMappingURL=ReadonlyRestClient.js.map\n\n\n/***/ }),\n/* 108 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar KeyIndex_1 = __webpack_require__(12);\nvar PriorityIndex_1 = __webpack_require__(4);\nvar ValueIndex_1 = __webpack_require__(39);\nvar PathIndex_1 = __webpack_require__(43);\nvar IndexedFilter_1 = __webpack_require__(25);\nvar LimitedFilter_1 = __webpack_require__(109);\nvar RangedFilter_1 = __webpack_require__(57);\nvar util_3 = __webpack_require__(0);\n/**\n * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a\n * range to be returned for a particular location. It is assumed that validation of parameters is done at the\n * user-facing API level, so it is not done here.\n * @constructor\n */\nvar QueryParams = /** @class */ (function () {\n function QueryParams() {\n this.limitSet_ = false;\n this.startSet_ = false;\n this.startNameSet_ = false;\n this.endSet_ = false;\n this.endNameSet_ = false;\n this.limit_ = 0;\n this.viewFrom_ = '';\n this.indexStartValue_ = null;\n this.indexStartName_ = '';\n this.indexEndValue_ = null;\n this.indexEndName_ = '';\n this.index_ = PriorityIndex_1.PRIORITY_INDEX;\n }\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasStart = function () {\n return this.startSet_;\n };\n /**\n * @return {boolean} True if it would return from left.\n */\n QueryParams.prototype.isViewFromLeft = function () {\n if (this.viewFrom_ === '') {\n // limit(), rather than limitToFirst or limitToLast was called.\n // This means that only one of startSet_ and endSet_ is true. Use them\n // to calculate which side of the view to anchor to. If neither is set,\n // anchor to the end.\n return this.startSet_;\n }\n else {\n return (this.viewFrom_ === QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT);\n }\n };\n /**\n * Only valid to call if hasStart() returns true\n * @return {*}\n */\n QueryParams.prototype.getIndexStartValue = function () {\n util_1.assert(this.startSet_, 'Only valid if start has been set');\n return this.indexStartValue_;\n };\n /**\n * Only valid to call if hasStart() returns true.\n * Returns the starting key name for the range defined by these query parameters\n * @return {!string}\n */\n QueryParams.prototype.getIndexStartName = function () {\n util_1.assert(this.startSet_, 'Only valid if start has been set');\n if (this.startNameSet_) {\n return this.indexStartName_;\n }\n else {\n return util_2.MIN_NAME;\n }\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasEnd = function () {\n return this.endSet_;\n };\n /**\n * Only valid to call if hasEnd() returns true.\n * @return {*}\n */\n QueryParams.prototype.getIndexEndValue = function () {\n util_1.assert(this.endSet_, 'Only valid if end has been set');\n return this.indexEndValue_;\n };\n /**\n * Only valid to call if hasEnd() returns true.\n * Returns the end key name for the range defined by these query parameters\n * @return {!string}\n */\n QueryParams.prototype.getIndexEndName = function () {\n util_1.assert(this.endSet_, 'Only valid if end has been set');\n if (this.endNameSet_) {\n return this.indexEndName_;\n }\n else {\n return util_2.MAX_NAME;\n }\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasLimit = function () {\n return this.limitSet_;\n };\n /**\n * @return {boolean} True if a limit has been set and it has been explicitly anchored\n */\n QueryParams.prototype.hasAnchoredLimit = function () {\n return this.limitSet_ && this.viewFrom_ !== '';\n };\n /**\n * Only valid to call if hasLimit() returns true\n * @return {!number}\n */\n QueryParams.prototype.getLimit = function () {\n util_1.assert(this.limitSet_, 'Only valid if limit has been set');\n return this.limit_;\n };\n /**\n * @return {!Index}\n */\n QueryParams.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @return {!QueryParams}\n * @private\n */\n QueryParams.prototype.copy_ = function () {\n var copy = new QueryParams();\n copy.limitSet_ = this.limitSet_;\n copy.limit_ = this.limit_;\n copy.startSet_ = this.startSet_;\n copy.indexStartValue_ = this.indexStartValue_;\n copy.startNameSet_ = this.startNameSet_;\n copy.indexStartName_ = this.indexStartName_;\n copy.endSet_ = this.endSet_;\n copy.indexEndValue_ = this.indexEndValue_;\n copy.endNameSet_ = this.endNameSet_;\n copy.indexEndName_ = this.indexEndName_;\n copy.index_ = this.index_;\n copy.viewFrom_ = this.viewFrom_;\n return copy;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limit = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = '';\n return newParams;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limitToFirst = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT;\n return newParams;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limitToLast = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_RIGHT;\n return newParams;\n };\n /**\n * @param {*} indexValue\n * @param {?string=} key\n * @return {!QueryParams}\n */\n QueryParams.prototype.startAt = function (indexValue, key) {\n var newParams = this.copy_();\n newParams.startSet_ = true;\n if (!(indexValue !== undefined)) {\n indexValue = null;\n }\n newParams.indexStartValue_ = indexValue;\n if (key != null) {\n newParams.startNameSet_ = true;\n newParams.indexStartName_ = key;\n }\n else {\n newParams.startNameSet_ = false;\n newParams.indexStartName_ = '';\n }\n return newParams;\n };\n /**\n * @param {*} indexValue\n * @param {?string=} key\n * @return {!QueryParams}\n */\n QueryParams.prototype.endAt = function (indexValue, key) {\n var newParams = this.copy_();\n newParams.endSet_ = true;\n if (!(indexValue !== undefined)) {\n indexValue = null;\n }\n newParams.indexEndValue_ = indexValue;\n if (key !== undefined) {\n newParams.endNameSet_ = true;\n newParams.indexEndName_ = key;\n }\n else {\n newParams.endNameSet_ = false;\n newParams.indexEndName_ = '';\n }\n return newParams;\n };\n /**\n * @param {!Index} index\n * @return {!QueryParams}\n */\n QueryParams.prototype.orderBy = function (index) {\n var newParams = this.copy_();\n newParams.index_ = index;\n return newParams;\n };\n /**\n * @return {!Object}\n */\n QueryParams.prototype.getQueryObject = function () {\n var WIRE_PROTOCOL_CONSTANTS = QueryParams.WIRE_PROTOCOL_CONSTANTS_;\n var obj = {};\n if (this.startSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE] = this.indexStartValue_;\n if (this.startNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME] = this.indexStartName_;\n }\n }\n if (this.endSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE] = this.indexEndValue_;\n if (this.endNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME] = this.indexEndName_;\n }\n }\n if (this.limitSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.LIMIT] = this.limit_;\n var viewFrom = this.viewFrom_;\n if (viewFrom === '') {\n if (this.isViewFromLeft()) {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n }\n else {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT;\n }\n }\n obj[WIRE_PROTOCOL_CONSTANTS.VIEW_FROM] = viewFrom;\n }\n // For now, priority index is the default, so we only specify if it's some other index\n if (this.index_ !== PriorityIndex_1.PRIORITY_INDEX) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX] = this.index_.toString();\n }\n return obj;\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.loadsAllData = function () {\n return !(this.startSet_ || this.endSet_ || this.limitSet_);\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.isDefault = function () {\n return this.loadsAllData() && this.index_ == PriorityIndex_1.PRIORITY_INDEX;\n };\n /**\n * @return {!NodeFilter}\n */\n QueryParams.prototype.getNodeFilter = function () {\n if (this.loadsAllData()) {\n return new IndexedFilter_1.IndexedFilter(this.getIndex());\n }\n else if (this.hasLimit()) {\n return new LimitedFilter_1.LimitedFilter(this);\n }\n else {\n return new RangedFilter_1.RangedFilter(this);\n }\n };\n /**\n * Returns a set of REST query string parameters representing this query.\n *\n * @return {!Object.} query string parameters\n */\n QueryParams.prototype.toRestQueryStringParameters = function () {\n var REST_CONSTANTS = QueryParams.REST_QUERY_CONSTANTS_;\n var qs = {};\n if (this.isDefault()) {\n return qs;\n }\n var orderBy;\n if (this.index_ === PriorityIndex_1.PRIORITY_INDEX) {\n orderBy = REST_CONSTANTS.PRIORITY_INDEX;\n }\n else if (this.index_ === ValueIndex_1.VALUE_INDEX) {\n orderBy = REST_CONSTANTS.VALUE_INDEX;\n }\n else if (this.index_ === KeyIndex_1.KEY_INDEX) {\n orderBy = REST_CONSTANTS.KEY_INDEX;\n }\n else {\n util_1.assert(this.index_ instanceof PathIndex_1.PathIndex, 'Unrecognized index type!');\n orderBy = this.index_.toString();\n }\n qs[REST_CONSTANTS.ORDER_BY] = util_3.stringify(orderBy);\n if (this.startSet_) {\n qs[REST_CONSTANTS.START_AT] = util_3.stringify(this.indexStartValue_);\n if (this.startNameSet_) {\n qs[REST_CONSTANTS.START_AT] += ',' + util_3.stringify(this.indexStartName_);\n }\n }\n if (this.endSet_) {\n qs[REST_CONSTANTS.END_AT] = util_3.stringify(this.indexEndValue_);\n if (this.endNameSet_) {\n qs[REST_CONSTANTS.END_AT] += ',' + util_3.stringify(this.indexEndName_);\n }\n }\n if (this.limitSet_) {\n if (this.isViewFromLeft()) {\n qs[REST_CONSTANTS.LIMIT_TO_FIRST] = this.limit_;\n }\n else {\n qs[REST_CONSTANTS.LIMIT_TO_LAST] = this.limit_;\n }\n }\n return qs;\n };\n /**\n * Wire Protocol Constants\n * @const\n * @enum {string}\n * @private\n */\n QueryParams.WIRE_PROTOCOL_CONSTANTS_ = {\n INDEX_START_VALUE: 'sp',\n INDEX_START_NAME: 'sn',\n INDEX_END_VALUE: 'ep',\n INDEX_END_NAME: 'en',\n LIMIT: 'l',\n VIEW_FROM: 'vf',\n VIEW_FROM_LEFT: 'l',\n VIEW_FROM_RIGHT: 'r',\n INDEX: 'i'\n };\n /**\n * REST Query Constants\n * @const\n * @enum {string}\n * @private\n */\n QueryParams.REST_QUERY_CONSTANTS_ = {\n ORDER_BY: 'orderBy',\n PRIORITY_INDEX: '$priority',\n VALUE_INDEX: '$value',\n KEY_INDEX: '$key',\n START_AT: 'startAt',\n END_AT: 'endAt',\n LIMIT_TO_FIRST: 'limitToFirst',\n LIMIT_TO_LAST: 'limitToLast'\n };\n /**\n * Default, empty query parameters\n * @type {!QueryParams}\n * @const\n */\n QueryParams.DEFAULT = new QueryParams();\n return QueryParams;\n}());\nexports.QueryParams = QueryParams;\n\n//# sourceMappingURL=QueryParams.js.map\n\n\n/***/ }),\n/* 109 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar RangedFilter_1 = __webpack_require__(57);\nvar ChildrenNode_1 = __webpack_require__(5);\nvar Node_1 = __webpack_require__(6);\nvar util_1 = __webpack_require__(0);\nvar Change_1 = __webpack_require__(10);\n/**\n * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible\n *\n * @constructor\n * @implements {NodeFilter}\n */\nvar LimitedFilter = /** @class */ (function () {\n /**\n * @param {!QueryParams} params\n */\n function LimitedFilter(params) {\n this.rangedFilter_ = new RangedFilter_1.RangedFilter(params);\n this.index_ = params.getIndex();\n this.limit_ = params.getLimit();\n this.reverse_ = !params.isViewFromLeft();\n }\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n if (!this.rangedFilter_.matches(new Node_1.NamedNode(key, newChild))) {\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n if (snap.getImmediateChild(key).equals(newChild)) {\n // No change\n return snap;\n }\n else if (snap.numChildren() < this.limit_) {\n return this.rangedFilter_\n .getIndexedFilter()\n .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\n }\n else {\n return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);\n }\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n var filtered;\n if (newSnap.isLeafNode() || newSnap.isEmpty()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n filtered = ChildrenNode_1.ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n }\n else {\n if (this.limit_ * 2 < newSnap.numChildren() &&\n newSnap.isIndexed(this.index_)) {\n // Easier to build up a snapshot, since what we're given has more than twice the elements we want\n filtered = ChildrenNode_1.ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n // anchor to the startPost, endPost, or last element as appropriate\n var iterator = void 0;\n if (this.reverse_) {\n iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);\n }\n else {\n iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);\n }\n var count = 0;\n while (iterator.hasNext() && count < this.limit_) {\n var next = iterator.getNext();\n var inRange = void 0;\n if (this.reverse_) {\n inRange =\n this.index_.compare(this.rangedFilter_.getStartPost(), next) <= 0;\n }\n else {\n inRange =\n this.index_.compare(next, this.rangedFilter_.getEndPost()) <= 0;\n }\n if (inRange) {\n filtered = filtered.updateImmediateChild(next.name, next.node);\n count++;\n }\n else {\n // if we have reached the end post, we cannot keep adding elemments\n break;\n }\n }\n }\n else {\n // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one\n filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var startPost = void 0;\n var endPost = void 0;\n var cmp = void 0;\n var iterator = void 0;\n if (this.reverse_) {\n iterator = filtered.getReverseIterator(this.index_);\n startPost = this.rangedFilter_.getEndPost();\n endPost = this.rangedFilter_.getStartPost();\n var indexCompare_1 = this.index_.getCompare();\n cmp = function (a, b) { return indexCompare_1(b, a); };\n }\n else {\n iterator = filtered.getIterator(this.index_);\n startPost = this.rangedFilter_.getStartPost();\n endPost = this.rangedFilter_.getEndPost();\n cmp = this.index_.getCompare();\n }\n var count = 0;\n var foundStartPost = false;\n while (iterator.hasNext()) {\n var next = iterator.getNext();\n if (!foundStartPost && cmp(startPost, next) <= 0) {\n // start adding\n foundStartPost = true;\n }\n var inRange = foundStartPost && count < this.limit_ && cmp(next, endPost) <= 0;\n if (inRange) {\n count++;\n }\n else {\n filtered = filtered.updateImmediateChild(next.name, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n }\n }\n }\n return this.rangedFilter_\n .getIndexedFilter()\n .updateFullNode(oldSnap, filtered, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n // Don't support priorities on queries\n return oldSnap;\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.filtersNodes = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.getIndexedFilter = function () {\n return this.rangedFilter_.getIndexedFilter();\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @param {!Node} snap\n * @param {string} childKey\n * @param {!Node} childSnap\n * @param {!CompleteChildSource} source\n * @param {?ChildChangeAccumulator} changeAccumulator\n * @return {!Node}\n * @private\n */\n LimitedFilter.prototype.fullLimitUpdateChild_ = function (snap, childKey, childSnap, source, changeAccumulator) {\n // TODO: rename all cache stuff etc to general snap terminology\n var cmp;\n if (this.reverse_) {\n var indexCmp_1 = this.index_.getCompare();\n cmp = function (a, b) { return indexCmp_1(b, a); };\n }\n else {\n cmp = this.index_.getCompare();\n }\n var oldEventCache = snap;\n util_1.assert(oldEventCache.numChildren() == this.limit_, '');\n var newChildNamedNode = new Node_1.NamedNode(childKey, childSnap);\n var windowBoundary = this.reverse_\n ? oldEventCache.getFirstChild(this.index_)\n : oldEventCache.getLastChild(this.index_);\n var inRange = this.rangedFilter_.matches(newChildNamedNode);\n if (oldEventCache.hasChild(childKey)) {\n var oldChildSnap = oldEventCache.getImmediateChild(childKey);\n var nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);\n while (nextChild != null &&\n (nextChild.name == childKey || oldEventCache.hasChild(nextChild.name))) {\n // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't\n // been applied to the limited filter yet. Ignore this next child which will be updated later in\n // the limited filter...\n nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);\n }\n var compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);\n var remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;\n if (remainsInWindow) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childChangedChange(childKey, childSnap, oldChildSnap));\n }\n return oldEventCache.updateImmediateChild(childKey, childSnap);\n }\n else {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(childKey, oldChildSnap));\n }\n var newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);\n if (nextChildInRange) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childAddedChange(nextChild.name, nextChild.node));\n }\n return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);\n }\n else {\n return newEventCache;\n }\n }\n }\n else if (childSnap.isEmpty()) {\n // we're deleting a node, but it was not in the window, so ignore it\n return snap;\n }\n else if (inRange) {\n if (cmp(windowBoundary, newChildNamedNode) >= 0) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(windowBoundary.name, windowBoundary.node));\n changeAccumulator.trackChildChange(Change_1.Change.childAddedChange(childKey, childSnap));\n }\n return oldEventCache\n .updateImmediateChild(childKey, childSnap)\n .updateImmediateChild(windowBoundary.name, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n else {\n return snap;\n }\n }\n else {\n return snap;\n }\n };\n return LimitedFilter;\n}());\nexports.LimitedFilter = LimitedFilter;\n\n//# sourceMappingURL=LimitedFilter.js.map\n\n\n/***/ }),\n/* 110 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Reference_1 = __webpack_require__(22);\nvar DataSnapshot_1 = __webpack_require__(23);\nvar Path_1 = __webpack_require__(3);\nvar Tree_1 = __webpack_require__(111);\nvar PriorityIndex_1 = __webpack_require__(4);\nvar util_2 = __webpack_require__(1);\nvar ServerValues_1 = __webpack_require__(44);\nvar validation_1 = __webpack_require__(8);\nvar util_3 = __webpack_require__(0);\nvar nodeFromJSON_1 = __webpack_require__(13);\nvar ChildrenNode_1 = __webpack_require__(5);\nvar Repo_1 = __webpack_require__(19);\n// TODO: This is pretty messy. Ideally, a lot of this would move into FirebaseData, or a transaction-specific\n// component used by FirebaseData, but it has ties to user callbacks (transaction update and onComplete) as well\n// as the realtime connection (to send transactions to the server). So that all needs to be decoupled first.\n// For now it's part of Repo, but in its own file.\n/**\n * @enum {number}\n */\nvar TransactionStatus;\n(function (TransactionStatus) {\n // We've run the transaction and updated transactionResultData_ with the result, but it isn't currently sent to the\n // server. A transaction will go from RUN -> SENT -> RUN if it comes back from the server as rejected due to\n // mismatched hash.\n TransactionStatus[TransactionStatus[\"RUN\"] = 0] = \"RUN\";\n // We've run the transaction and sent it to the server and it's currently outstanding (hasn't come back as accepted\n // or rejected yet).\n TransactionStatus[TransactionStatus[\"SENT\"] = 1] = \"SENT\";\n // Temporary state used to mark completed transactions (whether successful or aborted). The transaction will be\n // removed when we get a chance to prune completed ones.\n TransactionStatus[TransactionStatus[\"COMPLETED\"] = 2] = \"COMPLETED\";\n // Used when an already-sent transaction needs to be aborted (e.g. due to a conflicting set() call that was made).\n // If it comes back as unsuccessful, we'll abort it.\n TransactionStatus[TransactionStatus[\"SENT_NEEDS_ABORT\"] = 3] = \"SENT_NEEDS_ABORT\";\n // Temporary state used to mark transactions that need to be aborted.\n TransactionStatus[TransactionStatus[\"NEEDS_ABORT\"] = 4] = \"NEEDS_ABORT\";\n})(TransactionStatus = exports.TransactionStatus || (exports.TransactionStatus = {}));\n/**\n * If a transaction does not succeed after 25 retries, we abort it. Among other things this ensure that if there's\n * ever a bug causing a mismatch between client / server hashes for some data, we won't retry indefinitely.\n * @type {number}\n * @const\n * @private\n */\nRepo_1.Repo.MAX_TRANSACTION_RETRIES_ = 25;\n/**\n * Setup the transaction data structures\n * @private\n */\nRepo_1.Repo.prototype.transactions_init_ = function () {\n /**\n * Stores queues of outstanding transactions for Firebase locations.\n *\n * @type {!Tree.>}\n * @private\n */\n this.transactionQueueTree_ = new Tree_1.Tree();\n};\n/**\n * Creates a new transaction, adds it to the transactions we're tracking, and sends it to the server if possible.\n *\n * @param {!Path} path Path at which to do transaction.\n * @param {function(*):*} transactionUpdate Update callback.\n * @param {?function(?Error, boolean, ?DataSnapshot)} onComplete Completion callback.\n * @param {boolean} applyLocally Whether or not to make intermediate results visible\n */\nRepo_1.Repo.prototype.startTransaction = function (path, transactionUpdate, onComplete, applyLocally) {\n this.log_('transaction on ' + path);\n // Add a watch to make sure we get server updates.\n var valueCallback = function () { };\n var watchRef = new Reference_1.Reference(this, path);\n watchRef.on('value', valueCallback);\n var unwatcher = function () {\n watchRef.off('value', valueCallback);\n };\n // Initialize transaction.\n var transaction = {\n path: path,\n update: transactionUpdate,\n onComplete: onComplete,\n // One of TransactionStatus enums.\n status: null,\n // Used when combining transactions at different locations to figure out which one goes first.\n order: util_2.LUIDGenerator(),\n // Whether to raise local events for this transaction.\n applyLocally: applyLocally,\n // Count of how many times we've retried the transaction.\n retryCount: 0,\n // Function to call to clean up our .on() listener.\n unwatcher: unwatcher,\n // Stores why a transaction was aborted.\n abortReason: null,\n currentWriteId: null,\n currentInputSnapshot: null,\n currentOutputSnapshotRaw: null,\n currentOutputSnapshotResolved: null\n };\n // Run transaction initially.\n var currentState = this.getLatestState_(path);\n transaction.currentInputSnapshot = currentState;\n var newVal = transaction.update(currentState.val());\n if (newVal === undefined) {\n // Abort transaction.\n transaction.unwatcher();\n transaction.currentOutputSnapshotRaw = null;\n transaction.currentOutputSnapshotResolved = null;\n if (transaction.onComplete) {\n // We just set the input snapshot, so this cast should be safe\n var snapshot = new DataSnapshot_1.DataSnapshot(transaction.currentInputSnapshot, new Reference_1.Reference(this, transaction.path), PriorityIndex_1.PRIORITY_INDEX);\n transaction.onComplete(null, false, snapshot);\n }\n }\n else {\n validation_1.validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);\n // Mark as run and add to our queue.\n transaction.status = TransactionStatus.RUN;\n var queueNode = this.transactionQueueTree_.subTree(path);\n var nodeQueue = queueNode.getValue() || [];\n nodeQueue.push(transaction);\n queueNode.setValue(nodeQueue);\n // Update visibleData and raise events\n // Note: We intentionally raise events after updating all of our transaction state, since the user could\n // start new transactions from the event callbacks.\n var priorityForNode = void 0;\n if (typeof newVal === 'object' &&\n newVal !== null &&\n util_3.contains(newVal, '.priority')) {\n priorityForNode = util_3.safeGet(newVal, '.priority');\n util_1.assert(validation_1.isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +\n 'Priority must be a valid string, finite number, server value, or null.');\n }\n else {\n var currentNode = this.serverSyncTree_.calcCompleteEventCache(path) ||\n ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n priorityForNode = currentNode.getPriority().val();\n }\n priorityForNode /** @type {null|number|string} */ = priorityForNode;\n var serverValues = this.generateServerValues();\n var newNodeUnresolved = nodeFromJSON_1.nodeFromJSON(newVal, priorityForNode);\n var newNode = ServerValues_1.resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n transaction.currentOutputSnapshotRaw = newNodeUnresolved;\n transaction.currentOutputSnapshotResolved = newNode;\n transaction.currentWriteId = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserOverwrite(path, newNode, transaction.currentWriteId, transaction.applyLocally);\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n this.sendReadyTransactions_();\n }\n};\n/**\n * @param {!Path} path\n * @param {Array.=} excludeSets A specific set to exclude\n * @return {Node}\n * @private\n */\nRepo_1.Repo.prototype.getLatestState_ = function (path, excludeSets) {\n return (this.serverSyncTree_.calcCompleteEventCache(path, excludeSets) ||\n ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n};\n/**\n * Sends any already-run transactions that aren't waiting for outstanding transactions to\n * complete.\n *\n * Externally it's called with no arguments, but it calls itself recursively with a particular\n * transactionQueueTree node to recurse through the tree.\n *\n * @param {Tree.>=} node transactionQueueTree node to start at.\n * @private\n */\nRepo_1.Repo.prototype.sendReadyTransactions_ = function (node) {\n var _this = this;\n if (node === void 0) { node = this.transactionQueueTree_; }\n // Before recursing, make sure any completed transactions are removed.\n if (!node) {\n this.pruneCompletedTransactionsBelowNode_(node);\n }\n if (node.getValue() !== null) {\n var queue = this.buildTransactionQueue_(node);\n util_1.assert(queue.length > 0, 'Sending zero length transaction queue');\n var allRun = queue.every(function (transaction) { return transaction.status === TransactionStatus.RUN; });\n // If they're all run (and not sent), we can send them. Else, we must wait.\n if (allRun) {\n this.sendTransactionQueue_(node.path(), queue);\n }\n }\n else if (node.hasChildren()) {\n node.forEachChild(function (childNode) {\n _this.sendReadyTransactions_(childNode);\n });\n }\n};\n/**\n * Given a list of run transactions, send them to the server and then handle the result (success or failure).\n *\n * @param {!Path} path The location of the queue.\n * @param {!Array.} queue Queue of transactions under the specified location.\n * @private\n */\nRepo_1.Repo.prototype.sendTransactionQueue_ = function (path, queue) {\n var _this = this;\n // Mark transactions as sent and increment retry count!\n var setsToIgnore = queue.map(function (txn) {\n return txn.currentWriteId;\n });\n var latestState = this.getLatestState_(path, setsToIgnore);\n var snapToSend = latestState;\n var latestHash = latestState.hash();\n for (var i = 0; i < queue.length; i++) {\n var txn = queue[i];\n util_1.assert(txn.status === TransactionStatus.RUN, 'tryToSendTransactionQueue_: items in queue should all be run.');\n txn.status = TransactionStatus.SENT;\n txn.retryCount++;\n var relativePath = Path_1.Path.relativePath(path, txn.path);\n // If we've gotten to this point, the output snapshot must be defined.\n snapToSend = snapToSend.updateChild(relativePath /**@type {!Node} */, txn.currentOutputSnapshotRaw);\n }\n var dataToSend = snapToSend.val(true);\n var pathToSend = path;\n // Send the put.\n this.server_.put(pathToSend.toString(), dataToSend, function (status) {\n _this.log_('transaction put response', {\n path: pathToSend.toString(),\n status: status\n });\n var events = [];\n if (status === 'ok') {\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n for (var i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.COMPLETED;\n events = events.concat(_this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId));\n if (queue[i].onComplete) {\n // We never unset the output snapshot, and given that this transaction is complete, it should be set\n var node = queue[i].currentOutputSnapshotResolved;\n var ref = new Reference_1.Reference(_this, queue[i].path);\n var snapshot = new DataSnapshot_1.DataSnapshot(node, ref, PriorityIndex_1.PRIORITY_INDEX);\n callbacks.push(queue[i].onComplete.bind(null, null, true, snapshot));\n }\n queue[i].unwatcher();\n }\n // Now remove the completed transactions.\n _this.pruneCompletedTransactionsBelowNode_(_this.transactionQueueTree_.subTree(path));\n // There may be pending transactions that we can now send.\n _this.sendReadyTransactions_();\n _this.eventQueue_.raiseEventsForChangedPath(path, events);\n // Finally, trigger onComplete callbacks.\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n }\n else {\n // transactions are no longer sent. Update their status appropriately.\n if (status === 'datastale') {\n for (var i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT)\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n else\n queue[i].status = TransactionStatus.RUN;\n }\n }\n else {\n util_2.warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);\n for (var i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n queue[i].abortReason = status;\n }\n }\n _this.rerunTransactions_(path);\n }\n }, latestHash);\n};\n/**\n * Finds all transactions dependent on the data at changedPath and reruns them.\n *\n * Should be called any time cached data changes.\n *\n * Return the highest path that was affected by rerunning transactions. This is the path at which events need to\n * be raised for.\n *\n * @param {!Path} changedPath The path in mergedData that changed.\n * @return {!Path} The rootmost path that was affected by rerunning transactions.\n * @private\n */\nRepo_1.Repo.prototype.rerunTransactions_ = function (changedPath) {\n var rootMostTransactionNode = this.getAncestorTransactionNode_(changedPath);\n var path = rootMostTransactionNode.path();\n var queue = this.buildTransactionQueue_(rootMostTransactionNode);\n this.rerunTransactionQueue_(queue, path);\n return path;\n};\n/**\n * Does all the work of rerunning transactions (as well as cleans up aborted transactions and whatnot).\n *\n * @param {Array.} queue The queue of transactions to run.\n * @param {!Path} path The path the queue is for.\n * @private\n */\nRepo_1.Repo.prototype.rerunTransactionQueue_ = function (queue, path) {\n if (queue.length === 0) {\n return; // Nothing to do!\n }\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n var events = [];\n // Ignore all of the sets we're going to re-run.\n var txnsToRerun = queue.filter(function (q) {\n return q.status === TransactionStatus.RUN;\n });\n var setsToIgnore = txnsToRerun.map(function (q) {\n return q.currentWriteId;\n });\n for (var i = 0; i < queue.length; i++) {\n var transaction = queue[i];\n var relativePath = Path_1.Path.relativePath(path, transaction.path);\n var abortTransaction = false, abortReason = void 0;\n util_1.assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');\n if (transaction.status === TransactionStatus.NEEDS_ABORT) {\n abortTransaction = true;\n abortReason = transaction.abortReason;\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n else if (transaction.status === TransactionStatus.RUN) {\n if (transaction.retryCount >= Repo_1.Repo.MAX_TRANSACTION_RETRIES_) {\n abortTransaction = true;\n abortReason = 'maxretry';\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n else {\n // This code reruns a transaction\n var currentNode = this.getLatestState_(transaction.path, setsToIgnore);\n transaction.currentInputSnapshot = currentNode;\n var newData = queue[i].update(currentNode.val());\n if (newData !== undefined) {\n validation_1.validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);\n var newDataNode = nodeFromJSON_1.nodeFromJSON(newData);\n var hasExplicitPriority = typeof newData === 'object' &&\n newData != null &&\n util_3.contains(newData, '.priority');\n if (!hasExplicitPriority) {\n // Keep the old priority if there wasn't a priority explicitly specified.\n newDataNode = newDataNode.updatePriority(currentNode.getPriority());\n }\n var oldWriteId = transaction.currentWriteId;\n var serverValues = this.generateServerValues();\n var newNodeResolved = ServerValues_1.resolveDeferredValueSnapshot(newDataNode, serverValues);\n transaction.currentOutputSnapshotRaw = newDataNode;\n transaction.currentOutputSnapshotResolved = newNodeResolved;\n transaction.currentWriteId = this.getNextWriteId_();\n // Mutates setsToIgnore in place\n setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);\n events = events.concat(this.serverSyncTree_.applyUserOverwrite(transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));\n events = events.concat(this.serverSyncTree_.ackUserWrite(oldWriteId, true));\n }\n else {\n abortTransaction = true;\n abortReason = 'nodata';\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n }\n }\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n events = [];\n if (abortTransaction) {\n // Abort.\n queue[i].status = TransactionStatus.COMPLETED;\n // Removing a listener can trigger pruning which can muck with mergedData/visibleData (as it prunes data).\n // So defer the unwatcher until we're done.\n (function (unwatcher) {\n setTimeout(unwatcher, Math.floor(0));\n })(queue[i].unwatcher);\n if (queue[i].onComplete) {\n if (abortReason === 'nodata') {\n var ref = new Reference_1.Reference(this, queue[i].path);\n // We set this field immediately, so it's safe to cast to an actual snapshot\n var lastInput /** @type {!Node} */ = queue[i].currentInputSnapshot;\n var snapshot = new DataSnapshot_1.DataSnapshot(lastInput, ref, PriorityIndex_1.PRIORITY_INDEX);\n callbacks.push(queue[i].onComplete.bind(null, null, false, snapshot));\n }\n else {\n callbacks.push(queue[i].onComplete.bind(null, new Error(abortReason), false, null));\n }\n }\n }\n }\n // Clean up completed transactions.\n this.pruneCompletedTransactionsBelowNode_(this.transactionQueueTree_);\n // Now fire callbacks, now that we're in a good, known state.\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n // Try to send the transaction result to the server.\n this.sendReadyTransactions_();\n};\n/**\n * Returns the rootmost ancestor node of the specified path that has a pending transaction on it, or just returns\n * the node for the given path if there are no pending transactions on any ancestor.\n *\n * @param {!Path} path The location to start at.\n * @return {!Tree.>} The rootmost node with a transaction.\n * @private\n */\nRepo_1.Repo.prototype.getAncestorTransactionNode_ = function (path) {\n var front;\n // Start at the root and walk deeper into the tree towards path until we find a node with pending transactions.\n var transactionNode = this.transactionQueueTree_;\n while ((front = path.getFront()) !== null &&\n transactionNode.getValue() === null) {\n transactionNode = transactionNode.subTree(front);\n path = path.popFront();\n }\n return transactionNode;\n};\n/**\n * Builds the queue of all transactions at or below the specified transactionNode.\n *\n * @param {!Tree.>} transactionNode\n * @return {Array.} The generated queue.\n * @private\n */\nRepo_1.Repo.prototype.buildTransactionQueue_ = function (transactionNode) {\n // Walk any child transaction queues and aggregate them into a single queue.\n var transactionQueue = [];\n this.aggregateTransactionQueuesForNode_(transactionNode, transactionQueue);\n // Sort them by the order the transactions were created.\n transactionQueue.sort(function (a, b) {\n return a.order - b.order;\n });\n return transactionQueue;\n};\n/**\n * @param {!Tree.>} node\n * @param {Array.} queue\n * @private\n */\nRepo_1.Repo.prototype.aggregateTransactionQueuesForNode_ = function (node, queue) {\n var _this = this;\n var nodeQueue = node.getValue();\n if (nodeQueue !== null) {\n for (var i = 0; i < nodeQueue.length; i++) {\n queue.push(nodeQueue[i]);\n }\n }\n node.forEachChild(function (child) {\n _this.aggregateTransactionQueuesForNode_(child, queue);\n });\n};\n/**\n * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.\n *\n * @param {!Tree.>} node\n * @private\n */\nRepo_1.Repo.prototype.pruneCompletedTransactionsBelowNode_ = function (node) {\n var _this = this;\n var queue = node.getValue();\n if (queue) {\n var to = 0;\n for (var from = 0; from < queue.length; from++) {\n if (queue[from].status !== TransactionStatus.COMPLETED) {\n queue[to] = queue[from];\n to++;\n }\n }\n queue.length = to;\n node.setValue(queue.length > 0 ? queue : null);\n }\n node.forEachChild(function (childNode) {\n _this.pruneCompletedTransactionsBelowNode_(childNode);\n });\n};\n/**\n * Aborts all transactions on ancestors or descendants of the specified path. Called when doing a set() or update()\n * since we consider them incompatible with transactions.\n *\n * @param {!Path} path Path for which we want to abort related transactions.\n * @return {!Path}\n * @private\n */\nRepo_1.Repo.prototype.abortTransactions_ = function (path) {\n var _this = this;\n var affectedPath = this.getAncestorTransactionNode_(path).path();\n var transactionNode = this.transactionQueueTree_.subTree(path);\n transactionNode.forEachAncestor(function (node) {\n _this.abortTransactionsOnNode_(node);\n });\n this.abortTransactionsOnNode_(transactionNode);\n transactionNode.forEachDescendant(function (node) {\n _this.abortTransactionsOnNode_(node);\n });\n return affectedPath;\n};\n/**\n * Abort transactions stored in this transaction queue node.\n *\n * @param {!Tree.>} node Node to abort transactions for.\n * @private\n */\nRepo_1.Repo.prototype.abortTransactionsOnNode_ = function (node) {\n var queue = node.getValue();\n if (queue !== null) {\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n // Go through queue. Any already-sent transactions must be marked for abort, while the unsent ones\n // can be immediately aborted and removed.\n var events = [];\n var lastSent = -1;\n for (var i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) {\n // Already marked. No action needed.\n }\n else if (queue[i].status === TransactionStatus.SENT) {\n util_1.assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');\n lastSent = i;\n // Mark transaction for abort when it comes back.\n queue[i].status = TransactionStatus.SENT_NEEDS_ABORT;\n queue[i].abortReason = 'set';\n }\n else {\n util_1.assert(queue[i].status === TransactionStatus.RUN, 'Unexpected transaction status in abort');\n // We can abort it immediately.\n queue[i].unwatcher();\n events = events.concat(this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId, true));\n if (queue[i].onComplete) {\n var snapshot = null;\n callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, snapshot));\n }\n }\n }\n if (lastSent === -1) {\n // We're not waiting for any sent transactions. We can clear the queue.\n node.setValue(null);\n }\n else {\n // Remove the transactions we aborted.\n queue.length = lastSent + 1;\n }\n // Now fire the callbacks.\n this.eventQueue_.raiseEventsForChangedPath(node.path(), events);\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n }\n};\n\n//# sourceMappingURL=Repo_transaction.js.map\n\n\n/***/ }),\n/* 111 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Path_1 = __webpack_require__(3);\nvar util_2 = __webpack_require__(0);\n/**\n * Node in a Tree.\n */\nvar TreeNode = /** @class */ (function () {\n function TreeNode() {\n // TODO: Consider making accessors that create children and value lazily or\n // separate Internal / Leaf 'types'.\n this.children = {};\n this.childCount = 0;\n this.value = null;\n }\n return TreeNode;\n}());\nexports.TreeNode = TreeNode;\n/**\n * A light-weight tree, traversable by path. Nodes can have both values and children.\n * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty\n * children.\n */\nvar Tree = /** @class */ (function () {\n /**\n * @template T\n * @param {string=} name_ Optional name of the node.\n * @param {Tree=} parent_ Optional parent node.\n * @param {TreeNode=} node_ Optional node to wrap.\n */\n function Tree(name_, parent_, node_) {\n if (name_ === void 0) { name_ = ''; }\n if (parent_ === void 0) { parent_ = null; }\n if (node_ === void 0) { node_ = new TreeNode(); }\n this.name_ = name_;\n this.parent_ = parent_;\n this.node_ = node_;\n }\n /**\n * Returns a sub-Tree for the given path.\n *\n * @param {!(string|Path)} pathObj Path to look up.\n * @return {!Tree.} Tree for path.\n */\n Tree.prototype.subTree = function (pathObj) {\n // TODO: Require pathObj to be Path?\n var path = pathObj instanceof Path_1.Path ? pathObj : new Path_1.Path(pathObj);\n var child = this, next;\n while ((next = path.getFront()) !== null) {\n var childNode = util_2.safeGet(child.node_.children, next) || new TreeNode();\n child = new Tree(next, child, childNode);\n path = path.popFront();\n }\n return child;\n };\n /**\n * Returns the data associated with this tree node.\n *\n * @return {?T} The data or null if no data exists.\n */\n Tree.prototype.getValue = function () {\n return this.node_.value;\n };\n /**\n * Sets data to this tree node.\n *\n * @param {!T} value Value to set.\n */\n Tree.prototype.setValue = function (value) {\n util_1.assert(typeof value !== 'undefined', 'Cannot set value to undefined');\n this.node_.value = value;\n this.updateParents_();\n };\n /**\n * Clears the contents of the tree node (its value and all children).\n */\n Tree.prototype.clear = function () {\n this.node_.value = null;\n this.node_.children = {};\n this.node_.childCount = 0;\n this.updateParents_();\n };\n /**\n * @return {boolean} Whether the tree has any children.\n */\n Tree.prototype.hasChildren = function () {\n return this.node_.childCount > 0;\n };\n /**\n * @return {boolean} Whether the tree is empty (no value or children).\n */\n Tree.prototype.isEmpty = function () {\n return this.getValue() === null && !this.hasChildren();\n };\n /**\n * Calls action for each child of this tree node.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n */\n Tree.prototype.forEachChild = function (action) {\n var _this = this;\n util_2.forEach(this.node_.children, function (child, childTree) {\n action(new Tree(child, _this, childTree));\n });\n };\n /**\n * Does a depth-first traversal of this node's descendants, calling action for each one.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n * @param {boolean=} includeSelf Whether to call action on this node as well. Defaults to\n * false.\n * @param {boolean=} childrenFirst Whether to call action on children before calling it on\n * parent.\n */\n Tree.prototype.forEachDescendant = function (action, includeSelf, childrenFirst) {\n if (includeSelf && !childrenFirst)\n action(this);\n this.forEachChild(function (child) {\n child.forEachDescendant(action, /*includeSelf=*/ true, childrenFirst);\n });\n if (includeSelf && childrenFirst)\n action(this);\n };\n /**\n * Calls action on each ancestor node.\n *\n * @param {function(!Tree.)} action Action to be called on each parent; return\n * true to abort.\n * @param {boolean=} includeSelf Whether to call action on this node as well.\n * @return {boolean} true if the action callback returned true.\n */\n Tree.prototype.forEachAncestor = function (action, includeSelf) {\n var node = includeSelf ? this : this.parent();\n while (node !== null) {\n if (action(node)) {\n return true;\n }\n node = node.parent();\n }\n return false;\n };\n /**\n * Does a depth-first traversal of this node's descendants. When a descendant with a value\n * is found, action is called on it and traversal does not continue inside the node.\n * Action is *not* called on this node.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n */\n Tree.prototype.forEachImmediateDescendantWithValue = function (action) {\n this.forEachChild(function (child) {\n if (child.getValue() !== null)\n action(child);\n else\n child.forEachImmediateDescendantWithValue(action);\n });\n };\n /**\n * @return {!Path} The path of this tree node, as a Path.\n */\n Tree.prototype.path = function () {\n return new Path_1.Path(this.parent_ === null\n ? this.name_\n : this.parent_.path() + '/' + this.name_);\n };\n /**\n * @return {string} The name of the tree node.\n */\n Tree.prototype.name = function () {\n return this.name_;\n };\n /**\n * @return {?Tree} The parent tree node, or null if this is the root of the tree.\n */\n Tree.prototype.parent = function () {\n return this.parent_;\n };\n /**\n * Adds or removes this child from its parent based on whether it's empty or not.\n *\n * @private\n */\n Tree.prototype.updateParents_ = function () {\n if (this.parent_ !== null)\n this.parent_.updateChild_(this.name_, this);\n };\n /**\n * Adds or removes the passed child to this tree node, depending on whether it's empty.\n *\n * @param {string} childName The name of the child to update.\n * @param {!Tree.} child The child to update.\n * @private\n */\n Tree.prototype.updateChild_ = function (childName, child) {\n var childEmpty = child.isEmpty();\n var childExists = util_2.contains(this.node_.children, childName);\n if (childEmpty && childExists) {\n delete this.node_.children[childName];\n this.node_.childCount--;\n this.updateParents_();\n }\n else if (!childEmpty && !childExists) {\n this.node_.children[childName] = child.node_;\n this.node_.childCount++;\n this.updateParents_();\n }\n };\n return Tree;\n}());\nexports.Tree = Tree;\n\n//# sourceMappingURL=Tree.js.map\n\n\n/***/ }),\n/* 112 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar WebSocketConnection_1 = __webpack_require__(55);\nvar BrowserPollConnection_1 = __webpack_require__(54);\n/**\n * INTERNAL methods for internal-use only (tests, etc.).\n *\n * Customers shouldn't use these or else should be aware that they could break at any time.\n *\n * @const\n */\nexports.forceLongPolling = function () {\n WebSocketConnection_1.WebSocketConnection.forceDisallow();\n BrowserPollConnection_1.BrowserPollConnection.forceAllow();\n};\nexports.forceWebSockets = function () {\n BrowserPollConnection_1.BrowserPollConnection.forceDisallow();\n};\n/* Used by App Manager */\nexports.isWebSocketsAvailable = function () {\n return WebSocketConnection_1.WebSocketConnection['isAvailable']();\n};\nexports.setSecurityDebugCallback = function (ref, callback) {\n ref.repo.persistentConnection_.securityDebugCallback_ = callback;\n};\nexports.stats = function (ref, showDelta) {\n ref.repo.stats(showDelta);\n};\nexports.statsIncrementCounter = function (ref, metric) {\n ref.repo.statsIncrementCounter(metric);\n};\nexports.dataUpdateCount = function (ref) {\n return ref.repo.dataUpdateCount;\n};\nexports.interceptServerData = function (ref, callback) {\n return ref.repo.interceptServerData_(callback);\n};\n\n//# sourceMappingURL=internal.js.map\n\n\n/***/ }),\n/* 113 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar RepoInfo_1 = __webpack_require__(35);\nvar PersistentConnection_1 = __webpack_require__(51);\nvar RepoManager_1 = __webpack_require__(27);\nvar Connection_1 = __webpack_require__(53);\nexports.DataConnection = PersistentConnection_1.PersistentConnection;\n/**\n * @param {!string} pathString\n * @param {function(*)} onComplete\n */\nPersistentConnection_1.PersistentConnection.prototype.simpleListen = function (pathString, onComplete) {\n this.sendRequest('q', { p: pathString }, onComplete);\n};\n/**\n * @param {*} data\n * @param {function(*)} onEcho\n */\nPersistentConnection_1.PersistentConnection.prototype.echo = function (data, onEcho) {\n this.sendRequest('echo', { d: data }, onEcho);\n};\n// RealTimeConnection properties that we use in tests.\nexports.RealTimeConnection = Connection_1.Connection;\n/**\n * @param {function(): string} newHash\n * @return {function()}\n */\nexports.hijackHash = function (newHash) {\n var oldPut = PersistentConnection_1.PersistentConnection.prototype.put;\n PersistentConnection_1.PersistentConnection.prototype.put = function (pathString, data, opt_onComplete, opt_hash) {\n if (opt_hash !== undefined) {\n opt_hash = newHash();\n }\n oldPut.call(this, pathString, data, opt_onComplete, opt_hash);\n };\n return function () {\n PersistentConnection_1.PersistentConnection.prototype.put = oldPut;\n };\n};\n/**\n * @type {function(new:RepoInfo, !string, boolean, !string, boolean): undefined}\n */\nexports.ConnectionTarget = RepoInfo_1.RepoInfo;\n/**\n * @param {!Query} query\n * @return {!string}\n */\nexports.queryIdentifier = function (query) {\n return query.queryIdentifier();\n};\n/**\n * @param {!Query} firebaseRef\n * @return {!Object}\n */\nexports.listens = function (firebaseRef) {\n return firebaseRef.repo.persistentConnection_.listens_;\n};\n/**\n * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.\n *\n * @param {boolean} forceRestClient\n */\nexports.forceRestClient = function (forceRestClient) {\n RepoManager_1.RepoManager.getInstance().forceRestClient(forceRestClient);\n};\n\n//# sourceMappingURL=test_access.js.map\n\n\n/***/ })\n],[79]);\n } catch(error) {\n throw new Error(\n 'Cannot instantiate firebase-database.js - ' +\n 'be sure to load firebase-app.js first.'\n )\n }\n\n\n// WEBPACK FOOTER //\n// firebase-database.js","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar util_3 = require(\"@firebase/util\");\nvar util_4 = require(\"@firebase/util\");\nvar util_5 = require(\"@firebase/util\");\nvar util_6 = require(\"@firebase/util\");\nvar storage_1 = require(\"../storage/storage\");\nvar util_7 = require(\"@firebase/util\");\n/**\n * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).\n * @type {function(): number} Generated ID.\n */\nexports.LUIDGenerator = (function () {\n var id = 1;\n return function () {\n return id++;\n };\n})();\n/**\n * Sha1 hash of the input string\n * @param {!string} str The string to hash\n * @return {!string} The resulting hash\n */\nexports.sha1 = function (str) {\n var utf8Bytes = util_5.stringToByteArray(str);\n var sha1 = new util_4.Sha1();\n sha1.update(utf8Bytes);\n var sha1Bytes = sha1.digest();\n return util_3.base64.encodeByteArray(sha1Bytes);\n};\n/**\n * @param {...*} var_args\n * @return {string}\n * @private\n */\nvar buildLogMessage_ = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var message = '';\n for (var i = 0; i < var_args.length; i++) {\n if (Array.isArray(var_args[i]) ||\n (var_args[i] &&\n typeof var_args[i] === 'object' &&\n typeof var_args[i].length === 'number')) {\n message += buildLogMessage_.apply(null, var_args[i]);\n }\n else if (typeof var_args[i] === 'object') {\n message += util_6.stringify(var_args[i]);\n }\n else {\n message += var_args[i];\n }\n message += ' ';\n }\n return message;\n};\n/**\n * Use this for all debug messages in Firebase.\n * @type {?function(string)}\n */\nexports.logger = null;\n/**\n * Flag to check for log availability on first log message\n * @type {boolean}\n * @private\n */\nvar firstLog_ = true;\n/**\n * The implementation of Firebase.enableLogging (defined here to break dependencies)\n * @param {boolean|?function(string)} logger_ A flag to turn on logging, or a custom logger\n * @param {boolean=} persistent Whether or not to persist logging settings across refreshes\n */\nexports.enableLogging = function (logger_, persistent) {\n util_1.assert(!persistent || (logger_ === true || logger_ === false), \"Can't turn on custom loggers persistently.\");\n if (logger_ === true) {\n if (typeof console !== 'undefined') {\n if (typeof console.log === 'function') {\n exports.logger = console.log.bind(console);\n }\n else if (typeof console.log === 'object') {\n // IE does this.\n exports.logger = function (message) {\n console.log(message);\n };\n }\n }\n if (persistent)\n storage_1.SessionStorage.set('logging_enabled', true);\n }\n else if (typeof logger_ === 'function') {\n exports.logger = logger_;\n }\n else {\n exports.logger = null;\n storage_1.SessionStorage.remove('logging_enabled');\n }\n};\n/**\n *\n * @param {...(string|Arguments)} var_args\n */\nexports.log = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n if (firstLog_ === true) {\n firstLog_ = false;\n if (exports.logger === null && storage_1.SessionStorage.get('logging_enabled') === true)\n exports.enableLogging(true);\n }\n if (exports.logger) {\n var message = buildLogMessage_.apply(null, var_args);\n exports.logger(message);\n }\n};\n/**\n * @param {!string} prefix\n * @return {function(...[*])}\n */\nexports.logWrapper = function (prefix) {\n return function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n exports.log.apply(void 0, [prefix].concat(var_args));\n };\n};\n/**\n * @param {...string} var_args\n */\nexports.error = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n if (typeof console !== 'undefined') {\n var message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_.apply(void 0, var_args);\n if (typeof console.error !== 'undefined') {\n console.error(message);\n }\n else {\n console.log(message);\n }\n }\n};\n/**\n * @param {...string} var_args\n */\nexports.fatal = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var message = buildLogMessage_.apply(void 0, var_args);\n throw new Error('FIREBASE FATAL ERROR: ' + message);\n};\n/**\n * @param {...*} var_args\n */\nexports.warn = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n if (typeof console !== 'undefined') {\n var message = 'FIREBASE WARNING: ' + buildLogMessage_.apply(void 0, var_args);\n if (typeof console.warn !== 'undefined') {\n console.warn(message);\n }\n else {\n console.log(message);\n }\n }\n};\n/**\n * Logs a warning if the containing page uses https. Called when a call to new Firebase\n * does not use https.\n */\nexports.warnIfPageIsSecure = function () {\n // Be very careful accessing browser globals. Who knows what may or may not exist.\n if (typeof window !== 'undefined' &&\n window.location &&\n window.location.protocol &&\n window.location.protocol.indexOf('https:') !== -1) {\n exports.warn('Insecure Firebase access from a secure page. ' +\n 'Please use https in calls to new Firebase().');\n }\n};\n/**\n * @param {!String} methodName\n */\nexports.warnAboutUnsupportedMethod = function (methodName) {\n exports.warn(methodName +\n ' is unsupported and will likely change soon. ' +\n 'Please do not use.');\n};\n/**\n * Returns true if data is NaN, or +/- Infinity.\n * @param {*} data\n * @return {boolean}\n */\nexports.isInvalidJSONNumber = function (data) {\n return (typeof data === 'number' &&\n (data != data || // NaN\n data == Number.POSITIVE_INFINITY ||\n data == Number.NEGATIVE_INFINITY));\n};\n/**\n * @param {function()} fn\n */\nexports.executeWhenDOMReady = function (fn) {\n if (util_7.isNodeSdk() || document.readyState === 'complete') {\n fn();\n }\n else {\n // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which\n // fire before onload), but fall back to onload.\n var called_1 = false;\n var wrappedFn_1 = function () {\n if (!document.body) {\n setTimeout(wrappedFn_1, Math.floor(10));\n return;\n }\n if (!called_1) {\n called_1 = true;\n fn();\n }\n };\n if (document.addEventListener) {\n document.addEventListener('DOMContentLoaded', wrappedFn_1, false);\n // fallback to onload.\n window.addEventListener('load', wrappedFn_1, false);\n }\n else if (document.attachEvent) {\n // IE.\n document.attachEvent('onreadystatechange', function () {\n if (document.readyState === 'complete')\n wrappedFn_1();\n });\n // fallback to onload.\n window.attachEvent('onload', wrappedFn_1);\n // jQuery has an extra hack for IE that we could employ (based on\n // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.\n // I'm hoping we don't need it.\n }\n }\n};\n/**\n * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names\n * @type {!string}\n */\nexports.MIN_NAME = '[MIN_NAME]';\n/**\n * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names\n * @type {!string}\n */\nexports.MAX_NAME = '[MAX_NAME]';\n/**\n * Compares valid Firebase key names, plus min and max name\n * @param {!string} a\n * @param {!string} b\n * @return {!number}\n */\nexports.nameCompare = function (a, b) {\n if (a === b) {\n return 0;\n }\n else if (a === exports.MIN_NAME || b === exports.MAX_NAME) {\n return -1;\n }\n else if (b === exports.MIN_NAME || a === exports.MAX_NAME) {\n return 1;\n }\n else {\n var aAsInt = exports.tryParseInt(a), bAsInt = exports.tryParseInt(b);\n if (aAsInt !== null) {\n if (bAsInt !== null) {\n return aAsInt - bAsInt == 0 ? a.length - b.length : aAsInt - bAsInt;\n }\n else {\n return -1;\n }\n }\n else if (bAsInt !== null) {\n return 1;\n }\n else {\n return a < b ? -1 : 1;\n }\n }\n};\n/**\n * @param {!string} a\n * @param {!string} b\n * @return {!number} comparison result.\n */\nexports.stringCompare = function (a, b) {\n if (a === b) {\n return 0;\n }\n else if (a < b) {\n return -1;\n }\n else {\n return 1;\n }\n};\n/**\n * @param {string} key\n * @param {Object} obj\n * @return {*}\n */\nexports.requireKey = function (key, obj) {\n if (obj && key in obj) {\n return obj[key];\n }\n else {\n throw new Error('Missing required key (' + key + ') in object: ' + util_6.stringify(obj));\n }\n};\n/**\n * @param {*} obj\n * @return {string}\n */\nexports.ObjectToUniqueKey = function (obj) {\n if (typeof obj !== 'object' || obj === null)\n return util_6.stringify(obj);\n var keys = [];\n for (var k in obj) {\n keys.push(k);\n }\n // Export as json, but with the keys sorted.\n keys.sort();\n var key = '{';\n for (var i = 0; i < keys.length; i++) {\n if (i !== 0)\n key += ',';\n key += util_6.stringify(keys[i]);\n key += ':';\n key += exports.ObjectToUniqueKey(obj[keys[i]]);\n }\n key += '}';\n return key;\n};\n/**\n * Splits a string into a number of smaller segments of maximum size\n * @param {!string} str The string\n * @param {!number} segsize The maximum number of chars in the string.\n * @return {Array.} The string, split into appropriately-sized chunks\n */\nexports.splitStringBySize = function (str, segsize) {\n var len = str.length;\n if (len <= segsize) {\n return [str];\n }\n var dataSegs = [];\n for (var c = 0; c < len; c += segsize) {\n if (c + segsize > len) {\n dataSegs.push(str.substring(c, len));\n }\n else {\n dataSegs.push(str.substring(c, c + segsize));\n }\n }\n return dataSegs;\n};\n/**\n * Apply a function to each (key, value) pair in an object or\n * apply a function to each (index, value) pair in an array\n * @param {!(Object|Array)} obj The object or array to iterate over\n * @param {function(?, ?)} fn The function to apply\n */\nexports.each = function (obj, fn) {\n if (Array.isArray(obj)) {\n for (var i = 0; i < obj.length; ++i) {\n fn(i, obj[i]);\n }\n }\n else {\n /**\n * in the conversion of code we removed the goog.object.forEach\n * function which did a value,key callback. We standardized on\n * a single impl that does a key, value callback. So we invert\n * to not have to touch the `each` code points\n */\n util_2.forEach(obj, function (key, val) { return fn(val, key); });\n }\n};\n/**\n * Like goog.bind, but doesn't bother to create a closure if opt_context is null/undefined.\n * @param {function(*)} callback Callback function.\n * @param {?Object=} context Optional context to bind to.\n * @return {function(*)}\n */\nexports.bindCallback = function (callback, context) {\n return context ? callback.bind(context) : callback;\n};\n/**\n * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)\n * I made one modification at the end and removed the NaN / Infinity\n * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.\n * @param {!number} v A double\n * @return {string}\n */\nexports.doubleToIEEE754String = function (v) {\n util_1.assert(!exports.isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL\n var ebits = 11, fbits = 52;\n var bias = (1 << (ebits - 1)) - 1, s, e, f, ln, i, bits, str;\n // Compute sign, exponent, fraction\n // Skip NaN / Infinity handling --MJL.\n if (v === 0) {\n e = 0;\n f = 0;\n s = 1 / v === -Infinity ? 1 : 0;\n }\n else {\n s = v < 0;\n v = Math.abs(v);\n if (v >= Math.pow(2, 1 - bias)) {\n // Normalized\n ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);\n e = ln + bias;\n f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));\n }\n else {\n // Denormalized\n e = 0;\n f = Math.round(v / Math.pow(2, 1 - bias - fbits));\n }\n }\n // Pack sign, exponent, fraction\n bits = [];\n for (i = fbits; i; i -= 1) {\n bits.push(f % 2 ? 1 : 0);\n f = Math.floor(f / 2);\n }\n for (i = ebits; i; i -= 1) {\n bits.push(e % 2 ? 1 : 0);\n e = Math.floor(e / 2);\n }\n bits.push(s ? 1 : 0);\n bits.reverse();\n str = bits.join('');\n // Return the data as a hex string. --MJL\n var hexByteString = '';\n for (i = 0; i < 64; i += 8) {\n var hexByte = parseInt(str.substr(i, 8), 2).toString(16);\n if (hexByte.length === 1)\n hexByte = '0' + hexByte;\n hexByteString = hexByteString + hexByte;\n }\n return hexByteString.toLowerCase();\n};\n/**\n * Used to detect if we're in a Chrome content script (which executes in an\n * isolated environment where long-polling doesn't work).\n * @return {boolean}\n */\nexports.isChromeExtensionContentScript = function () {\n return !!(typeof window === 'object' &&\n window['chrome'] &&\n window['chrome']['extension'] &&\n !/^chrome/.test(window.location.href));\n};\n/**\n * Used to detect if we're in a Windows 8 Store app.\n * @return {boolean}\n */\nexports.isWindowsStoreApp = function () {\n // Check for the presence of a couple WinRT globals\n return typeof Windows === 'object' && typeof Windows.UI === 'object';\n};\n/**\n * Converts a server error code to a Javascript Error\n * @param {!string} code\n * @param {!Query} query\n * @return {Error}\n */\nexports.errorForServerCode = function (code, query) {\n var reason = 'Unknown Error';\n if (code === 'too_big') {\n reason =\n 'The data requested exceeds the maximum size ' +\n 'that can be accessed with a single request.';\n }\n else if (code == 'permission_denied') {\n reason = \"Client doesn't have permission to access the desired data.\";\n }\n else if (code == 'unavailable') {\n reason = 'The service is unavailable';\n }\n var error = new Error(code + ' at ' + query.path.toString() + ': ' + reason);\n error.code = code.toUpperCase();\n return error;\n};\n/**\n * Used to test for integer-looking strings\n * @type {RegExp}\n * @private\n */\nexports.INTEGER_REGEXP_ = new RegExp('^-?\\\\d{1,10}$');\n/**\n * If the string contains a 32-bit integer, return it. Else return null.\n * @param {!string} str\n * @return {?number}\n */\nexports.tryParseInt = function (str) {\n if (exports.INTEGER_REGEXP_.test(str)) {\n var intVal = Number(str);\n if (intVal >= -2147483648 && intVal <= 2147483647) {\n return intVal;\n }\n }\n return null;\n};\n/**\n * Helper to run some code but catch any exceptions and re-throw them later.\n * Useful for preventing user callbacks from breaking internal code.\n *\n * Re-throwing the exception from a setTimeout is a little evil, but it's very\n * convenient (we don't have to try to figure out when is a safe point to\n * re-throw it), and the behavior seems reasonable:\n *\n * * If you aren't pausing on exceptions, you get an error in the console with\n * the correct stack trace.\n * * If you're pausing on all exceptions, the debugger will pause on your\n * exception and then again when we rethrow it.\n * * If you're only pausing on uncaught exceptions, the debugger will only pause\n * on us re-throwing it.\n *\n * @param {!function()} fn The code to guard.\n */\nexports.exceptionGuard = function (fn) {\n try {\n fn();\n }\n catch (e) {\n // Re-throw exception when it's safe.\n setTimeout(function () {\n // It used to be that \"throw e\" would result in a good console error with\n // relevant context, but as of Chrome 39, you just get the firebase.js\n // file/line number where we re-throw it, which is useless. So we log\n // e.stack explicitly.\n var stack = e.stack || '';\n exports.warn('Exception was thrown by user callback.', stack);\n throw e;\n }, Math.floor(0));\n }\n};\n/**\n * Helper function to safely call opt_callback with the specified arguments. It:\n * 1. Turns into a no-op if opt_callback is null or undefined.\n * 2. Wraps the call inside exceptionGuard to prevent exceptions from breaking our state.\n *\n * @param {?Function=} callback Optional onComplete callback.\n * @param {...*} var_args Arbitrary args to be passed to opt_onComplete\n */\nexports.callUserCallback = function (callback) {\n var var_args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n var_args[_i - 1] = arguments[_i];\n }\n if (typeof callback === 'function') {\n exports.exceptionGuard(function () {\n callback.apply(void 0, var_args);\n });\n }\n};\n/**\n * @return {boolean} true if we think we're currently being crawled.\n */\nexports.beingCrawled = function () {\n var userAgent = (typeof window === 'object' &&\n window['navigator'] &&\n window['navigator']['userAgent']) ||\n '';\n // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we\n // believe to support JavaScript/AJAX rendering.\n // NOTE: Google Webmaster Tools doesn't really belong, but their \"This is how a visitor to your website\n // would have seen the page\" is flaky if we don't treat it as a crawler.\n return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);\n};\n/**\n * Export a property of an object using a getter function.\n *\n * @param {!Object} object\n * @param {string} name\n * @param {!function(): *} fnGet\n */\nexports.exportPropGetter = function (object, name, fnGet) {\n Object.defineProperty(object, name, { get: fnGet });\n};\n/**\n * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.\n *\n * It is removed with clearTimeout() as normal.\n *\n * @param {Function} fn Function to run.\n * @param {number} time Milliseconds to wait before running.\n * @return {number|Object} The setTimeout() return value.\n */\nexports.setTimeoutNonBlocking = function (fn, time) {\n var timeout = setTimeout(fn, time);\n if (typeof timeout === 'object' && timeout['unref']) {\n timeout['unref']();\n }\n return timeout;\n};\n\n//# sourceMappingURL=util.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/util.js\n// module id = 1\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"./util\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * An immutable object representing a parsed path. It's immutable so that you\n * can pass them around to other functions without worrying about them changing\n * it.\n */\nvar Path = /** @class */ (function () {\n /**\n * @param {string|Array.} pathOrString Path string to parse,\n * or another path, or the raw tokens array\n * @param {number=} pieceNum\n */\n function Path(pathOrString, pieceNum) {\n if (pieceNum === void 0) {\n this.pieces_ = pathOrString.split('/');\n // Remove empty pieces.\n var copyTo = 0;\n for (var i = 0; i < this.pieces_.length; i++) {\n if (this.pieces_[i].length > 0) {\n this.pieces_[copyTo] = this.pieces_[i];\n copyTo++;\n }\n }\n this.pieces_.length = copyTo;\n this.pieceNum_ = 0;\n }\n else {\n this.pieces_ = pathOrString;\n this.pieceNum_ = pieceNum;\n }\n }\n Object.defineProperty(Path, \"Empty\", {\n /**\n * Singleton to represent an empty path\n *\n * @const\n */\n get: function () {\n return new Path('');\n },\n enumerable: true,\n configurable: true\n });\n Path.prototype.getFront = function () {\n if (this.pieceNum_ >= this.pieces_.length)\n return null;\n return this.pieces_[this.pieceNum_];\n };\n /**\n * @return {number} The number of segments in this path\n */\n Path.prototype.getLength = function () {\n return this.pieces_.length - this.pieceNum_;\n };\n /**\n * @return {!Path}\n */\n Path.prototype.popFront = function () {\n var pieceNum = this.pieceNum_;\n if (pieceNum < this.pieces_.length) {\n pieceNum++;\n }\n return new Path(this.pieces_, pieceNum);\n };\n /**\n * @return {?string}\n */\n Path.prototype.getBack = function () {\n if (this.pieceNum_ < this.pieces_.length)\n return this.pieces_[this.pieces_.length - 1];\n return null;\n };\n Path.prototype.toString = function () {\n var pathString = '';\n for (var i = this.pieceNum_; i < this.pieces_.length; i++) {\n if (this.pieces_[i] !== '')\n pathString += '/' + this.pieces_[i];\n }\n return pathString || '/';\n };\n Path.prototype.toUrlEncodedString = function () {\n var pathString = '';\n for (var i = this.pieceNum_; i < this.pieces_.length; i++) {\n if (this.pieces_[i] !== '')\n pathString += '/' + encodeURIComponent(String(this.pieces_[i]));\n }\n return pathString || '/';\n };\n /**\n * Shallow copy of the parts of the path.\n *\n * @param {number=} begin\n * @return {!Array}\n */\n Path.prototype.slice = function (begin) {\n if (begin === void 0) { begin = 0; }\n return this.pieces_.slice(this.pieceNum_ + begin);\n };\n /**\n * @return {?Path}\n */\n Path.prototype.parent = function () {\n if (this.pieceNum_ >= this.pieces_.length)\n return null;\n var pieces = [];\n for (var i = this.pieceNum_; i < this.pieces_.length - 1; i++)\n pieces.push(this.pieces_[i]);\n return new Path(pieces, 0);\n };\n /**\n * @param {string|!Path} childPathObj\n * @return {!Path}\n */\n Path.prototype.child = function (childPathObj) {\n var pieces = [];\n for (var i = this.pieceNum_; i < this.pieces_.length; i++)\n pieces.push(this.pieces_[i]);\n if (childPathObj instanceof Path) {\n for (var i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {\n pieces.push(childPathObj.pieces_[i]);\n }\n }\n else {\n var childPieces = childPathObj.split('/');\n for (var i = 0; i < childPieces.length; i++) {\n if (childPieces[i].length > 0)\n pieces.push(childPieces[i]);\n }\n }\n return new Path(pieces, 0);\n };\n /**\n * @return {boolean} True if there are no segments in this path\n */\n Path.prototype.isEmpty = function () {\n return this.pieceNum_ >= this.pieces_.length;\n };\n /**\n * @param {!Path} outerPath\n * @param {!Path} innerPath\n * @return {!Path} The path from outerPath to innerPath\n */\n Path.relativePath = function (outerPath, innerPath) {\n var outer = outerPath.getFront(), inner = innerPath.getFront();\n if (outer === null) {\n return innerPath;\n }\n else if (outer === inner) {\n return Path.relativePath(outerPath.popFront(), innerPath.popFront());\n }\n else {\n throw new Error('INTERNAL ERROR: innerPath (' +\n innerPath +\n ') is not within ' +\n 'outerPath (' +\n outerPath +\n ')');\n }\n };\n /**\n * @param {!Path} left\n * @param {!Path} right\n * @return {number} -1, 0, 1 if left is less, equal, or greater than the right.\n */\n Path.comparePaths = function (left, right) {\n var leftKeys = left.slice();\n var rightKeys = right.slice();\n for (var i = 0; i < leftKeys.length && i < rightKeys.length; i++) {\n var cmp = util_1.nameCompare(leftKeys[i], rightKeys[i]);\n if (cmp !== 0)\n return cmp;\n }\n if (leftKeys.length === rightKeys.length)\n return 0;\n return leftKeys.length < rightKeys.length ? -1 : 1;\n };\n /**\n *\n * @param {Path} other\n * @return {boolean} true if paths are the same.\n */\n Path.prototype.equals = function (other) {\n if (this.getLength() !== other.getLength()) {\n return false;\n }\n for (var i = this.pieceNum_, j = other.pieceNum_; i <= this.pieces_.length; i++, j++) {\n if (this.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n }\n return true;\n };\n /**\n *\n * @param {!Path} other\n * @return {boolean} True if this path is a parent (or the same as) other\n */\n Path.prototype.contains = function (other) {\n var i = this.pieceNum_;\n var j = other.pieceNum_;\n if (this.getLength() > other.getLength()) {\n return false;\n }\n while (i < this.pieces_.length) {\n if (this.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n ++i;\n ++j;\n }\n return true;\n };\n return Path;\n}()); // end Path\nexports.Path = Path;\n/**\n * Dynamic (mutable) path used to count path lengths.\n *\n * This class is used to efficiently check paths for valid\n * length (in UTF8 bytes) and depth (used in path validation).\n *\n * Throws Error exception if path is ever invalid.\n *\n * The definition of a path always begins with '/'.\n */\nvar ValidationPath = /** @class */ (function () {\n /**\n * @param {!Path} path Initial Path.\n * @param {string} errorPrefix_ Prefix for any error messages.\n */\n function ValidationPath(path, errorPrefix_) {\n this.errorPrefix_ = errorPrefix_;\n /** @type {!Array} */\n this.parts_ = path.slice();\n /** @type {number} Initialize to number of '/' chars needed in path. */\n this.byteLength_ = Math.max(1, this.parts_.length);\n for (var i = 0; i < this.parts_.length; i++) {\n this.byteLength_ += util_2.stringLength(this.parts_[i]);\n }\n this.checkValid_();\n }\n Object.defineProperty(ValidationPath, \"MAX_PATH_DEPTH\", {\n /** @const {number} Maximum key depth. */\n get: function () {\n return 32;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ValidationPath, \"MAX_PATH_LENGTH_BYTES\", {\n /** @const {number} Maximum number of (UTF8) bytes in a Firebase path. */\n get: function () {\n return 768;\n },\n enumerable: true,\n configurable: true\n });\n /** @param {string} child */\n ValidationPath.prototype.push = function (child) {\n // Count the needed '/'\n if (this.parts_.length > 0) {\n this.byteLength_ += 1;\n }\n this.parts_.push(child);\n this.byteLength_ += util_2.stringLength(child);\n this.checkValid_();\n };\n ValidationPath.prototype.pop = function () {\n var last = this.parts_.pop();\n this.byteLength_ -= util_2.stringLength(last);\n // Un-count the previous '/'\n if (this.parts_.length > 0) {\n this.byteLength_ -= 1;\n }\n };\n ValidationPath.prototype.checkValid_ = function () {\n if (this.byteLength_ > ValidationPath.MAX_PATH_LENGTH_BYTES) {\n throw new Error(this.errorPrefix_ +\n 'has a key path longer than ' +\n ValidationPath.MAX_PATH_LENGTH_BYTES +\n ' bytes (' +\n this.byteLength_ +\n ').');\n }\n if (this.parts_.length > ValidationPath.MAX_PATH_DEPTH) {\n throw new Error(this.errorPrefix_ +\n 'path specified exceeds the maximum depth that can be written (' +\n ValidationPath.MAX_PATH_DEPTH +\n ') or object contains a cycle ' +\n this.toErrorString());\n }\n };\n /**\n * String for use in error messages - uses '.' notation for path.\n *\n * @return {string}\n */\n ValidationPath.prototype.toErrorString = function () {\n if (this.parts_.length == 0) {\n return '';\n }\n return \"in property '\" + this.parts_.join('.') + \"'\";\n };\n return ValidationPath;\n}());\nexports.ValidationPath = ValidationPath;\n\n//# sourceMappingURL=Path.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/Path.js\n// module id = 3\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar Index_1 = require(\"./Index\");\nvar util_1 = require(\"../../util/util\");\nvar Node_1 = require(\"../Node\");\nvar LeafNode_1 = require(\"../LeafNode\");\nvar nodeFromJSON;\nvar MAX_NODE;\nfunction setNodeFromJSON(val) {\n nodeFromJSON = val;\n}\nexports.setNodeFromJSON = setNodeFromJSON;\nfunction setMaxNode(val) {\n MAX_NODE = val;\n}\nexports.setMaxNode = setMaxNode;\n/**\n * @constructor\n * @extends {Index}\n * @private\n */\nvar PriorityIndex = /** @class */ (function (_super) {\n tslib_1.__extends(PriorityIndex, _super);\n function PriorityIndex() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.compare = function (a, b) {\n var aPriority = a.node.getPriority();\n var bPriority = b.node.getPriority();\n var indexCmp = aPriority.compareTo(bPriority);\n if (indexCmp === 0) {\n return util_1.nameCompare(a.name, b.name);\n }\n else {\n return indexCmp;\n }\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.isDefinedOn = function (node) {\n return !node.getPriority().isEmpty();\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.indexedValueChanged = function (oldNode, newNode) {\n return !oldNode.getPriority().equals(newNode.getPriority());\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.maxPost = function () {\n return new Node_1.NamedNode(util_1.MAX_NAME, new LeafNode_1.LeafNode('[PRIORITY-POST]', MAX_NODE));\n };\n /**\n * @param {*} indexValue\n * @param {string} name\n * @return {!NamedNode}\n */\n PriorityIndex.prototype.makePost = function (indexValue, name) {\n var priorityNode = nodeFromJSON(indexValue);\n return new Node_1.NamedNode(name, new LeafNode_1.LeafNode('[PRIORITY-POST]', priorityNode));\n };\n /**\n * @return {!string} String representation for inclusion in a query spec\n */\n PriorityIndex.prototype.toString = function () {\n return '.priority';\n };\n return PriorityIndex;\n}(Index_1.Index));\nexports.PriorityIndex = PriorityIndex;\nexports.PRIORITY_INDEX = new PriorityIndex();\n\n//# sourceMappingURL=PriorityIndex.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/indexes/PriorityIndex.js\n// module id = 4\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../util/util\");\nvar SortedMap_1 = require(\"../util/SortedMap\");\nvar Node_1 = require(\"./Node\");\nvar snap_1 = require(\"./snap\");\nvar PriorityIndex_1 = require(\"./indexes/PriorityIndex\");\nvar KeyIndex_1 = require(\"./indexes/KeyIndex\");\nvar IndexMap_1 = require(\"./IndexMap\");\nvar LeafNode_1 = require(\"./LeafNode\");\nvar comparators_1 = require(\"./comparators\");\n// TODO: For memory savings, don't store priorityNode_ if it's empty.\nvar EMPTY_NODE;\n/**\n * ChildrenNode is a class for storing internal nodes in a DataSnapshot\n * (i.e. nodes with children). It implements Node and stores the\n * list of children in the children property, sorted by child name.\n *\n * @constructor\n * @implements {Node}\n */\nvar ChildrenNode = /** @class */ (function () {\n /**\n *\n * @param {!SortedMap.} children_ List of children\n * of this node..\n * @param {?Node} priorityNode_ The priority of this node (as a snapshot node).\n * @param {!IndexMap} indexMap_\n */\n function ChildrenNode(children_, priorityNode_, indexMap_) {\n this.children_ = children_;\n this.priorityNode_ = priorityNode_;\n this.indexMap_ = indexMap_;\n this.lazyHash_ = null;\n /**\n * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use\n * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own\n * class instead of an empty ChildrenNode.\n */\n if (this.priorityNode_) {\n snap_1.validatePriorityNode(this.priorityNode_);\n }\n if (this.children_.isEmpty()) {\n util_1.assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');\n }\n }\n Object.defineProperty(ChildrenNode, \"EMPTY_NODE\", {\n get: function () {\n return (EMPTY_NODE ||\n (EMPTY_NODE = new ChildrenNode(new SortedMap_1.SortedMap(comparators_1.NAME_COMPARATOR), null, IndexMap_1.IndexMap.Default)));\n },\n enumerable: true,\n configurable: true\n });\n /** @inheritDoc */\n ChildrenNode.prototype.isLeafNode = function () {\n return false;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getPriority = function () {\n return this.priorityNode_ || EMPTY_NODE;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.updatePriority = function (newPriorityNode) {\n if (this.children_.isEmpty()) {\n // Don't allow priorities on empty nodes\n return this;\n }\n else {\n return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getImmediateChild = function (childName) {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.getPriority();\n }\n else {\n var child = this.children_.get(childName);\n return child === null ? EMPTY_NODE : child;\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getChild = function (path) {\n var front = path.getFront();\n if (front === null)\n return this;\n return this.getImmediateChild(front).getChild(path.popFront());\n };\n /** @inheritDoc */\n ChildrenNode.prototype.hasChild = function (childName) {\n return this.children_.get(childName) !== null;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.updateImmediateChild = function (childName, newChildNode) {\n util_1.assert(newChildNode, 'We should always be passing snapshot nodes');\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n }\n else {\n var namedNode = new Node_1.NamedNode(childName, newChildNode);\n var newChildren = void 0, newIndexMap = void 0, newPriority = void 0;\n if (newChildNode.isEmpty()) {\n newChildren = this.children_.remove(childName);\n newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);\n }\n else {\n newChildren = this.children_.insert(childName, newChildNode);\n newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);\n }\n newPriority = newChildren.isEmpty() ? EMPTY_NODE : this.priorityNode_;\n return new ChildrenNode(newChildren, newPriority, newIndexMap);\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.updateChild = function (path, newChildNode) {\n var front = path.getFront();\n if (front === null) {\n return newChildNode;\n }\n else {\n util_1.assert(path.getFront() !== '.priority' || path.getLength() === 1, '.priority must be the last token in a path');\n var newImmediateChild = this.getImmediateChild(front).updateChild(path.popFront(), newChildNode);\n return this.updateImmediateChild(front, newImmediateChild);\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.isEmpty = function () {\n return this.children_.isEmpty();\n };\n /** @inheritDoc */\n ChildrenNode.prototype.numChildren = function () {\n return this.children_.count();\n };\n /** @inheritDoc */\n ChildrenNode.prototype.val = function (exportFormat) {\n if (this.isEmpty())\n return null;\n var obj = {};\n var numKeys = 0, maxKey = 0, allIntegerKeys = true;\n this.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n obj[key] = childNode.val(exportFormat);\n numKeys++;\n if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {\n maxKey = Math.max(maxKey, Number(key));\n }\n else {\n allIntegerKeys = false;\n }\n });\n if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {\n // convert to array.\n var array = [];\n for (var key in obj)\n array[key] = obj[key];\n return array;\n }\n else {\n if (exportFormat && !this.getPriority().isEmpty()) {\n obj['.priority'] = this.getPriority().val();\n }\n return obj;\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.hash = function () {\n if (this.lazyHash_ === null) {\n var toHash_1 = '';\n if (!this.getPriority().isEmpty())\n toHash_1 +=\n 'priority:' +\n snap_1.priorityHashText(this.getPriority().val()) +\n ':';\n this.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n var childHash = childNode.hash();\n if (childHash !== '')\n toHash_1 += ':' + key + ':' + childHash;\n });\n this.lazyHash_ = toHash_1 === '' ? '' : util_2.sha1(toHash_1);\n }\n return this.lazyHash_;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getPredecessorChildName = function (childName, childNode, index) {\n var idx = this.resolveIndex_(index);\n if (idx) {\n var predecessor = idx.getPredecessorKey(new Node_1.NamedNode(childName, childNode));\n return predecessor ? predecessor.name : null;\n }\n else {\n return this.children_.getPredecessorKey(childName);\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {?string}\n */\n ChildrenNode.prototype.getFirstChildName = function (indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n var minKey = idx.minKey();\n return minKey && minKey.name;\n }\n else {\n return this.children_.minKey();\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {?NamedNode}\n */\n ChildrenNode.prototype.getFirstChild = function (indexDefinition) {\n var minKey = this.getFirstChildName(indexDefinition);\n if (minKey) {\n return new Node_1.NamedNode(minKey, this.children_.get(minKey));\n }\n else {\n return null;\n }\n };\n /**\n * Given an index, return the key name of the largest value we have, according to that index\n * @param {!Index} indexDefinition\n * @return {?string}\n */\n ChildrenNode.prototype.getLastChildName = function (indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n var maxKey = idx.maxKey();\n return maxKey && maxKey.name;\n }\n else {\n return this.children_.maxKey();\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {?NamedNode}\n */\n ChildrenNode.prototype.getLastChild = function (indexDefinition) {\n var maxKey = this.getLastChildName(indexDefinition);\n if (maxKey) {\n return new Node_1.NamedNode(maxKey, this.children_.get(maxKey));\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.forEachChild = function (index, action) {\n var idx = this.resolveIndex_(index);\n if (idx) {\n return idx.inorderTraversal(function (wrappedNode) {\n return action(wrappedNode.name, wrappedNode.node);\n });\n }\n else {\n return this.children_.inorderTraversal(action);\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {SortedMapIterator}\n */\n ChildrenNode.prototype.getIterator = function (indexDefinition) {\n return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);\n };\n /**\n *\n * @param {!NamedNode} startPost\n * @param {!Index} indexDefinition\n * @return {!SortedMapIterator}\n */\n ChildrenNode.prototype.getIteratorFrom = function (startPost, indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getIteratorFrom(startPost, function (key) { return key; });\n }\n else {\n var iterator = this.children_.getIteratorFrom(startPost.name, Node_1.NamedNode.Wrap);\n var next = iterator.peek();\n while (next != null && indexDefinition.compare(next, startPost) < 0) {\n iterator.getNext();\n next = iterator.peek();\n }\n return iterator;\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {!SortedMapIterator}\n */\n ChildrenNode.prototype.getReverseIterator = function (indexDefinition) {\n return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);\n };\n /**\n * @param {!NamedNode} endPost\n * @param {!Index} indexDefinition\n * @return {!SortedMapIterator}\n */\n ChildrenNode.prototype.getReverseIteratorFrom = function (endPost, indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getReverseIteratorFrom(endPost, function (key) {\n return key;\n });\n }\n else {\n var iterator = this.children_.getReverseIteratorFrom(endPost.name, Node_1.NamedNode.Wrap);\n var next = iterator.peek();\n while (next != null && indexDefinition.compare(next, endPost) > 0) {\n iterator.getNext();\n next = iterator.peek();\n }\n return iterator;\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.compareTo = function (other) {\n if (this.isEmpty()) {\n if (other.isEmpty()) {\n return 0;\n }\n else {\n return -1;\n }\n }\n else if (other.isLeafNode() || other.isEmpty()) {\n return 1;\n }\n else if (other === exports.MAX_NODE) {\n return -1;\n }\n else {\n // Must be another node with children.\n return 0;\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.withIndex = function (indexDefinition) {\n if (indexDefinition === KeyIndex_1.KEY_INDEX ||\n this.indexMap_.hasIndex(indexDefinition)) {\n return this;\n }\n else {\n var newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);\n return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.isIndexed = function (index) {\n return index === KeyIndex_1.KEY_INDEX || this.indexMap_.hasIndex(index);\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.equals = function (other) {\n if (other === this) {\n return true;\n }\n else if (other.isLeafNode()) {\n return false;\n }\n else {\n var otherChildrenNode = other;\n if (!this.getPriority().equals(otherChildrenNode.getPriority())) {\n return false;\n }\n else if (this.children_.count() === otherChildrenNode.children_.count()) {\n var thisIter = this.getIterator(PriorityIndex_1.PRIORITY_INDEX);\n var otherIter = otherChildrenNode.getIterator(PriorityIndex_1.PRIORITY_INDEX);\n var thisCurrent = thisIter.getNext();\n var otherCurrent = otherIter.getNext();\n while (thisCurrent && otherCurrent) {\n if (thisCurrent.name !== otherCurrent.name ||\n !thisCurrent.node.equals(otherCurrent.node)) {\n return false;\n }\n thisCurrent = thisIter.getNext();\n otherCurrent = otherIter.getNext();\n }\n return thisCurrent === null && otherCurrent === null;\n }\n else {\n return false;\n }\n }\n };\n /**\n * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used\n * instead.\n *\n * @private\n * @param {!Index} indexDefinition\n * @return {?SortedMap.}\n */\n ChildrenNode.prototype.resolveIndex_ = function (indexDefinition) {\n if (indexDefinition === KeyIndex_1.KEY_INDEX) {\n return null;\n }\n else {\n return this.indexMap_.get(indexDefinition.toString());\n }\n };\n /**\n * @private\n * @type {RegExp}\n */\n ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\\d*)$/;\n return ChildrenNode;\n}());\nexports.ChildrenNode = ChildrenNode;\n/**\n * @constructor\n * @extends {ChildrenNode}\n * @private\n */\nvar MaxNode = /** @class */ (function (_super) {\n tslib_1.__extends(MaxNode, _super);\n function MaxNode() {\n return _super.call(this, new SortedMap_1.SortedMap(comparators_1.NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap_1.IndexMap.Default) || this;\n }\n MaxNode.prototype.compareTo = function (other) {\n if (other === this) {\n return 0;\n }\n else {\n return 1;\n }\n };\n MaxNode.prototype.equals = function (other) {\n // Not that we every compare it, but MAX_NODE is only ever equal to itself\n return other === this;\n };\n MaxNode.prototype.getPriority = function () {\n return this;\n };\n MaxNode.prototype.getImmediateChild = function (childName) {\n return ChildrenNode.EMPTY_NODE;\n };\n MaxNode.prototype.isEmpty = function () {\n return false;\n };\n return MaxNode;\n}(ChildrenNode));\nexports.MaxNode = MaxNode;\n/**\n * Marker that will sort higher than any other snapshot.\n * @type {!MAX_NODE}\n * @const\n */\nexports.MAX_NODE = new MaxNode();\nObject.defineProperties(Node_1.NamedNode, {\n MIN: {\n value: new Node_1.NamedNode(util_2.MIN_NAME, ChildrenNode.EMPTY_NODE)\n },\n MAX: {\n value: new Node_1.NamedNode(util_2.MAX_NAME, exports.MAX_NODE)\n }\n});\n/**\n * Reference Extensions\n */\nKeyIndex_1.KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;\nLeafNode_1.LeafNode.__childrenNodeConstructor = ChildrenNode;\nsnap_1.setMaxNode(exports.MAX_NODE);\nPriorityIndex_1.setMaxNode(exports.MAX_NODE);\n\n//# sourceMappingURL=ChildrenNode.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/ChildrenNode.js\n// module id = 5\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n *\n * @param {!string} name\n * @param {!Node} node\n * @constructor\n * @struct\n */\nvar NamedNode = /** @class */ (function () {\n function NamedNode(name, node) {\n this.name = name;\n this.node = node;\n }\n /**\n *\n * @param {!string} name\n * @param {!Node} node\n * @return {NamedNode}\n */\n NamedNode.Wrap = function (name, node) {\n return new NamedNode(name, node);\n };\n return NamedNode;\n}());\nexports.NamedNode = NamedNode;\n\n//# sourceMappingURL=Node.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/Node.js\n// module id = 6\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = require(\"./Path\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"./util\");\nvar util_3 = require(\"@firebase/util\");\nvar util_4 = require(\"@firebase/util\");\n/**\n * True for invalid Firebase keys\n * @type {RegExp}\n * @private\n */\nexports.INVALID_KEY_REGEX_ = /[\\[\\].#$\\/\\u0000-\\u001F\\u007F]/;\n/**\n * True for invalid Firebase paths.\n * Allows '/' in paths.\n * @type {RegExp}\n * @private\n */\nexports.INVALID_PATH_REGEX_ = /[\\[\\].#$\\u0000-\\u001F\\u007F]/;\n/**\n * Maximum number of characters to allow in leaf value\n * @type {number}\n * @private\n */\nexports.MAX_LEAF_SIZE_ = 10 * 1024 * 1024;\n/**\n * @param {*} key\n * @return {boolean}\n */\nexports.isValidKey = function (key) {\n return (typeof key === 'string' && key.length !== 0 && !exports.INVALID_KEY_REGEX_.test(key));\n};\n/**\n * @param {string} pathString\n * @return {boolean}\n */\nexports.isValidPathString = function (pathString) {\n return (typeof pathString === 'string' &&\n pathString.length !== 0 &&\n !exports.INVALID_PATH_REGEX_.test(pathString));\n};\n/**\n * @param {string} pathString\n * @return {boolean}\n */\nexports.isValidRootPathString = function (pathString) {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n return exports.isValidPathString(pathString);\n};\n/**\n * @param {*} priority\n * @return {boolean}\n */\nexports.isValidPriority = function (priority) {\n return (priority === null ||\n typeof priority === 'string' ||\n (typeof priority === 'number' && !util_2.isInvalidJSONNumber(priority)) ||\n (priority && typeof priority === 'object' && util_1.contains(priority, '.sv')));\n};\n/**\n * Pre-validate a datum passed as an argument to Firebase function.\n *\n * @param {string} fnName\n * @param {number} argumentNumber\n * @param {*} data\n * @param {!Path} path\n * @param {boolean} optional\n */\nexports.validateFirebaseDataArg = function (fnName, argumentNumber, data, path, optional) {\n if (optional && data === undefined)\n return;\n exports.validateFirebaseData(util_3.errorPrefix(fnName, argumentNumber, optional), data, path);\n};\n/**\n * Validate a data object client-side before sending to server.\n *\n * @param {string} errorPrefix\n * @param {*} data\n * @param {!Path|!ValidationPath} path_\n */\nexports.validateFirebaseData = function (errorPrefix, data, path_) {\n var path = path_ instanceof Path_1.Path ? new Path_1.ValidationPath(path_, errorPrefix) : path_;\n if (data === undefined) {\n throw new Error(errorPrefix + 'contains undefined ' + path.toErrorString());\n }\n if (typeof data === 'function') {\n throw new Error(errorPrefix +\n 'contains a function ' +\n path.toErrorString() +\n ' with contents = ' +\n data.toString());\n }\n if (util_2.isInvalidJSONNumber(data)) {\n throw new Error(errorPrefix + 'contains ' + data.toString() + ' ' + path.toErrorString());\n }\n // Check max leaf size, but try to avoid the utf8 conversion if we can.\n if (typeof data === 'string' &&\n data.length > exports.MAX_LEAF_SIZE_ / 3 &&\n util_4.stringLength(data) > exports.MAX_LEAF_SIZE_) {\n throw new Error(errorPrefix +\n 'contains a string greater than ' +\n exports.MAX_LEAF_SIZE_ +\n ' utf8 bytes ' +\n path.toErrorString() +\n \" ('\" +\n data.substring(0, 50) +\n \"...')\");\n }\n // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON\n // to save extra walking of large objects.\n if (data && typeof data === 'object') {\n var hasDotValue_1 = false, hasActualChild_1 = false;\n util_1.forEach(data, function (key, value) {\n if (key === '.value') {\n hasDotValue_1 = true;\n }\n else if (key !== '.priority' && key !== '.sv') {\n hasActualChild_1 = true;\n if (!exports.isValidKey(key)) {\n throw new Error(errorPrefix +\n ' contains an invalid key (' +\n key +\n ') ' +\n path.toErrorString() +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\n }\n }\n path.push(key);\n exports.validateFirebaseData(errorPrefix, value, path);\n path.pop();\n });\n if (hasDotValue_1 && hasActualChild_1) {\n throw new Error(errorPrefix +\n ' contains \".value\" child ' +\n path.toErrorString() +\n ' in addition to actual children.');\n }\n }\n};\n/**\n * Pre-validate paths passed in the firebase function.\n *\n * @param {string} errorPrefix\n * @param {Array} mergePaths\n */\nexports.validateFirebaseMergePaths = function (errorPrefix, mergePaths) {\n var i, curPath;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n var keys = curPath.slice();\n for (var j = 0; j < keys.length; j++) {\n if (keys[j] === '.priority' && j === keys.length - 1) {\n // .priority is OK\n }\n else if (!exports.isValidKey(keys[j])) {\n throw new Error(errorPrefix +\n 'contains an invalid key (' +\n keys[j] +\n ') in path ' +\n curPath.toString() +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\n }\n }\n }\n // Check that update keys are not descendants of each other.\n // We rely on the property that sorting guarantees that ancestors come\n // right before descendants.\n mergePaths.sort(Path_1.Path.comparePaths);\n var prevPath = null;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n if (prevPath !== null && prevPath.contains(curPath)) {\n throw new Error(errorPrefix +\n 'contains a path ' +\n prevPath.toString() +\n ' that is ancestor of another path ' +\n curPath.toString());\n }\n prevPath = curPath;\n }\n};\n/**\n * pre-validate an object passed as an argument to firebase function (\n * must be an object - e.g. for firebase.update()).\n *\n * @param {string} fnName\n * @param {number} argumentNumber\n * @param {*} data\n * @param {!Path} path\n * @param {boolean} optional\n */\nexports.validateFirebaseMergeDataArg = function (fnName, argumentNumber, data, path, optional) {\n if (optional && data === undefined)\n return;\n var errorPrefix = util_3.errorPrefix(fnName, argumentNumber, optional);\n if (!(data && typeof data === 'object') || Array.isArray(data)) {\n throw new Error(errorPrefix + ' must be an object containing the children to replace.');\n }\n var mergePaths = [];\n util_1.forEach(data, function (key, value) {\n var curPath = new Path_1.Path(key);\n exports.validateFirebaseData(errorPrefix, value, path.child(curPath));\n if (curPath.getBack() === '.priority') {\n if (!exports.isValidPriority(value)) {\n throw new Error(errorPrefix +\n \"contains an invalid value for '\" +\n curPath.toString() +\n \"', which must be a valid \" +\n 'Firebase priority (a string, finite number, server value, or null).');\n }\n }\n mergePaths.push(curPath);\n });\n exports.validateFirebaseMergePaths(errorPrefix, mergePaths);\n};\nexports.validatePriority = function (fnName, argumentNumber, priority, optional) {\n if (optional && priority === undefined)\n return;\n if (util_2.isInvalidJSONNumber(priority))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'is ' +\n priority.toString() +\n ', but must be a valid Firebase priority (a string, finite number, ' +\n 'server value, or null).');\n // Special case to allow importing data with a .sv.\n if (!exports.isValidPriority(priority))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid Firebase priority ' +\n '(a string, finite number, server value, or null).');\n};\nexports.validateEventType = function (fnName, argumentNumber, eventType, optional) {\n if (optional && eventType === undefined)\n return;\n switch (eventType) {\n case 'value':\n case 'child_added':\n case 'child_removed':\n case 'child_changed':\n case 'child_moved':\n break;\n default:\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid event type = \"value\", \"child_added\", \"child_removed\", ' +\n '\"child_changed\", or \"child_moved\".');\n }\n};\nexports.validateKey = function (fnName, argumentNumber, key, optional) {\n if (optional && key === undefined)\n return;\n if (!exports.isValidKey(key))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'was an invalid key = \"' +\n key +\n '\". Firebase keys must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\").');\n};\nexports.validatePathString = function (fnName, argumentNumber, pathString, optional) {\n if (optional && pathString === undefined)\n return;\n if (!exports.isValidPathString(pathString))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'was an invalid path = \"' +\n pathString +\n '\". Paths must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\"');\n};\nexports.validateRootPathString = function (fnName, argumentNumber, pathString, optional) {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n exports.validatePathString(fnName, argumentNumber, pathString, optional);\n};\nexports.validateWritablePath = function (fnName, path) {\n if (path.getFront() === '.info') {\n throw new Error(fnName + \" failed = Can't modify data under /.info/\");\n }\n};\nexports.validateUrl = function (fnName, argumentNumber, parsedUrl) {\n // TODO = Validate server better.\n var pathString = parsedUrl.path.toString();\n if (!(typeof parsedUrl.repoInfo.host === 'string') ||\n parsedUrl.repoInfo.host.length === 0 ||\n (!exports.isValidKey(parsedUrl.repoInfo.namespace) &&\n parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||\n (pathString.length !== 0 && !exports.isValidRootPathString(pathString))) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, false) +\n 'must be a valid firebase URL and ' +\n 'the path can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\".');\n }\n};\nexports.validateCredential = function (fnName, argumentNumber, cred, optional) {\n if (optional && cred === undefined)\n return;\n if (!(typeof cred === 'string'))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid credential (a string).');\n};\nexports.validateBoolean = function (fnName, argumentNumber, bool, optional) {\n if (optional && bool === undefined)\n return;\n if (typeof bool !== 'boolean')\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) + 'must be a boolean.');\n};\nexports.validateString = function (fnName, argumentNumber, string, optional) {\n if (optional && string === undefined)\n return;\n if (!(typeof string === 'string')) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid string.');\n }\n};\nexports.validateObject = function (fnName, argumentNumber, obj, optional) {\n if (optional && obj === undefined)\n return;\n if (!(obj && typeof obj === 'object') || obj === null) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid object.');\n }\n};\nexports.validateObjectContainsKey = function (fnName, argumentNumber, obj, key, optional, opt_type) {\n var objectContainsKey = obj && typeof obj === 'object' && util_1.contains(obj, key);\n if (!objectContainsKey) {\n if (optional) {\n return;\n }\n else {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must contain the key \"' +\n key +\n '\"');\n }\n }\n if (opt_type) {\n var val = util_1.safeGet(obj, key);\n if ((opt_type === 'number' && !(typeof val === 'number')) ||\n (opt_type === 'string' && !(typeof val === 'string')) ||\n (opt_type === 'boolean' && !(typeof val === 'boolean')) ||\n (opt_type === 'function' && !(typeof val === 'function')) ||\n (opt_type === 'object' && !(typeof val === 'object') && val)) {\n if (optional) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'contains invalid value for key \"' +\n key +\n '\" (must be of type \"' +\n opt_type +\n '\")');\n }\n else {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must contain the key \"' +\n key +\n '\" with type \"' +\n opt_type +\n '\"');\n }\n }\n }\n};\n\n//# sourceMappingURL=validation.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/validation.js\n// module id = 8\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n *\n * @enum\n */\nvar OperationType;\n(function (OperationType) {\n OperationType[OperationType[\"OVERWRITE\"] = 0] = \"OVERWRITE\";\n OperationType[OperationType[\"MERGE\"] = 1] = \"MERGE\";\n OperationType[OperationType[\"ACK_USER_WRITE\"] = 2] = \"ACK_USER_WRITE\";\n OperationType[OperationType[\"LISTEN_COMPLETE\"] = 3] = \"LISTEN_COMPLETE\";\n})(OperationType = exports.OperationType || (exports.OperationType = {}));\n/**\n * @param {boolean} fromUser\n * @param {boolean} fromServer\n * @param {?string} queryId\n * @param {boolean} tagged\n * @constructor\n */\nvar OperationSource = /** @class */ (function () {\n function OperationSource(fromUser, fromServer, queryId, tagged) {\n this.fromUser = fromUser;\n this.fromServer = fromServer;\n this.queryId = queryId;\n this.tagged = tagged;\n util_1.assert(!tagged || fromServer, 'Tagged queries must be from server.');\n }\n /**\n * @const\n * @type {!OperationSource}\n */\n OperationSource.User = new OperationSource(\n /*fromUser=*/ true, false, null, \n /*tagged=*/ false);\n /**\n * @const\n * @type {!OperationSource}\n */\n OperationSource.Server = new OperationSource(false, \n /*fromServer=*/ true, null, \n /*tagged=*/ false);\n /**\n * @param {string} queryId\n * @return {!OperationSource}\n */\n OperationSource.forServerTaggedQuery = function (queryId) {\n return new OperationSource(false, \n /*fromServer=*/ true, queryId, \n /*tagged=*/ true);\n };\n return OperationSource;\n}());\nexports.OperationSource = OperationSource;\n\n//# sourceMappingURL=Operation.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/operation/Operation.js\n// module id = 9\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * @constructor\n * @struct\n * @param {!string} type The event type\n * @param {!Node} snapshotNode The data\n * @param {string=} childName The name for this child, if it's a child event\n * @param {Node=} oldSnap Used for intermediate processing of child changed events\n * @param {string=} prevName The name for the previous child, if applicable\n */\nvar Change = /** @class */ (function () {\n function Change(type, snapshotNode, childName, oldSnap, prevName) {\n this.type = type;\n this.snapshotNode = snapshotNode;\n this.childName = childName;\n this.oldSnap = oldSnap;\n this.prevName = prevName;\n }\n /**\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.valueChange = function (snapshot) {\n return new Change(Change.VALUE, snapshot);\n };\n /**\n * @param {string} childKey\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.childAddedChange = function (childKey, snapshot) {\n return new Change(Change.CHILD_ADDED, snapshot, childKey);\n };\n /**\n * @param {string} childKey\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.childRemovedChange = function (childKey, snapshot) {\n return new Change(Change.CHILD_REMOVED, snapshot, childKey);\n };\n /**\n * @param {string} childKey\n * @param {!Node} newSnapshot\n * @param {!Node} oldSnapshot\n * @return {!Change}\n */\n Change.childChangedChange = function (childKey, newSnapshot, oldSnapshot) {\n return new Change(Change.CHILD_CHANGED, newSnapshot, childKey, oldSnapshot);\n };\n /**\n * @param {string} childKey\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.childMovedChange = function (childKey, snapshot) {\n return new Change(Change.CHILD_MOVED, snapshot, childKey);\n };\n //event types\n /** Event type for a child added */\n Change.CHILD_ADDED = 'child_added';\n /** Event type for a child removed */\n Change.CHILD_REMOVED = 'child_removed';\n /** Event type for a child changed */\n Change.CHILD_CHANGED = 'child_changed';\n /** Event type for a child moved */\n Change.CHILD_MOVED = 'child_moved';\n /** Event type for a value change */\n Change.VALUE = 'value';\n return Change;\n}());\nexports.Change = Change;\n\n//# sourceMappingURL=Change.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/Change.js\n// module id = 10\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar Index_1 = require(\"./Index\");\nvar Node_1 = require(\"../Node\");\nvar util_1 = require(\"../../util/util\");\nvar util_2 = require(\"@firebase/util\");\nvar __EMPTY_NODE;\nvar KeyIndex = /** @class */ (function (_super) {\n tslib_1.__extends(KeyIndex, _super);\n function KeyIndex() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n Object.defineProperty(KeyIndex, \"__EMPTY_NODE\", {\n get: function () {\n return __EMPTY_NODE;\n },\n set: function (val) {\n __EMPTY_NODE = val;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.compare = function (a, b) {\n return util_1.nameCompare(a.name, b.name);\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.isDefinedOn = function (node) {\n // We could probably return true here (since every node has a key), but it's never called\n // so just leaving unimplemented for now.\n throw util_2.assertionError('KeyIndex.isDefinedOn not expected to be called.');\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.indexedValueChanged = function (oldNode, newNode) {\n return false; // The key for a node never changes.\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.maxPost = function () {\n // TODO: This should really be created once and cached in a static property, but\n // NamedNode isn't defined yet, so I can't use it in a static. Bleh.\n return new Node_1.NamedNode(util_1.MAX_NAME, __EMPTY_NODE);\n };\n /**\n * @param {*} indexValue\n * @param {string} name\n * @return {!NamedNode}\n */\n KeyIndex.prototype.makePost = function (indexValue, name) {\n util_2.assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');\n // We just use empty node, but it'll never be compared, since our comparator only looks at name.\n return new Node_1.NamedNode(indexValue, __EMPTY_NODE);\n };\n /**\n * @return {!string} String representation for inclusion in a query spec\n */\n KeyIndex.prototype.toString = function () {\n return '.key';\n };\n return KeyIndex;\n}(Index_1.Index));\nexports.KeyIndex = KeyIndex;\nexports.KEY_INDEX = new KeyIndex();\n\n//# sourceMappingURL=KeyIndex.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/indexes/KeyIndex.js\n// module id = 12\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ChildrenNode_1 = require(\"./ChildrenNode\");\nvar LeafNode_1 = require(\"./LeafNode\");\nvar Node_1 = require(\"./Node\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar childSet_1 = require(\"./childSet\");\nvar comparators_1 = require(\"./comparators\");\nvar IndexMap_1 = require(\"./IndexMap\");\nvar PriorityIndex_1 = require(\"./indexes/PriorityIndex\");\nvar USE_HINZE = true;\n/**\n * Constructs a snapshot node representing the passed JSON and returns it.\n * @param {*} json JSON to create a node for.\n * @param {?string|?number=} priority Optional priority to use. This will be ignored if the\n * passed JSON contains a .priority property.\n * @return {!Node}\n */\nfunction nodeFromJSON(json, priority) {\n if (priority === void 0) { priority = null; }\n if (json === null) {\n return ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n if (typeof json === 'object' && '.priority' in json) {\n priority = json['.priority'];\n }\n util_2.assert(priority === null ||\n typeof priority === 'string' ||\n typeof priority === 'number' ||\n (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);\n if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {\n json = json['.value'];\n }\n // Valid leaf nodes include non-objects or server-value wrapper objects\n if (typeof json !== 'object' || '.sv' in json) {\n var jsonLeaf = json;\n return new LeafNode_1.LeafNode(jsonLeaf, nodeFromJSON(priority));\n }\n if (!(json instanceof Array) && USE_HINZE) {\n var children_1 = [];\n var childrenHavePriority_1 = false;\n var hinzeJsonObj_1 = json;\n util_1.forEach(hinzeJsonObj_1, function (key, child) {\n if (typeof key !== 'string' || key.substring(0, 1) !== '.') {\n // Ignore metadata nodes\n var childNode = nodeFromJSON(hinzeJsonObj_1[key]);\n if (!childNode.isEmpty()) {\n childrenHavePriority_1 =\n childrenHavePriority_1 || !childNode.getPriority().isEmpty();\n children_1.push(new Node_1.NamedNode(key, childNode));\n }\n }\n });\n if (children_1.length == 0) {\n return ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n var childSet = childSet_1.buildChildSet(children_1, comparators_1.NAME_ONLY_COMPARATOR, function (namedNode) { return namedNode.name; }, comparators_1.NAME_COMPARATOR);\n if (childrenHavePriority_1) {\n var sortedChildSet = childSet_1.buildChildSet(children_1, PriorityIndex_1.PRIORITY_INDEX.getCompare());\n return new ChildrenNode_1.ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap_1.IndexMap({ '.priority': sortedChildSet }, { '.priority': PriorityIndex_1.PRIORITY_INDEX }));\n }\n else {\n return new ChildrenNode_1.ChildrenNode(childSet, nodeFromJSON(priority), IndexMap_1.IndexMap.Default);\n }\n }\n else {\n var node_1 = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var jsonObj_1 = json;\n util_1.forEach(jsonObj_1, function (key, childData) {\n if (util_1.contains(jsonObj_1, key)) {\n if (key.substring(0, 1) !== '.') {\n // ignore metadata nodes.\n var childNode = nodeFromJSON(childData);\n if (childNode.isLeafNode() || !childNode.isEmpty())\n node_1 = node_1.updateImmediateChild(key, childNode);\n }\n }\n });\n return node_1.updatePriority(nodeFromJSON(priority));\n }\n}\nexports.nodeFromJSON = nodeFromJSON;\nPriorityIndex_1.setNodeFromJSON(nodeFromJSON);\n\n//# sourceMappingURL=nodeFromJSON.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/nodeFromJSON.js\n// module id = 13\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar DOMStorageWrapper_1 = require(\"./DOMStorageWrapper\");\nvar MemoryStorage_1 = require(\"./MemoryStorage\");\n/**\n * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.\n * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change\n * to reflect this type\n *\n * @param {string} domStorageName Name of the underlying storage object\n * (e.g. 'localStorage' or 'sessionStorage').\n * @return {?} Turning off type information until a common interface is defined.\n */\nvar createStoragefor = function (domStorageName) {\n try {\n // NOTE: just accessing \"localStorage\" or \"window['localStorage']\" may throw a security exception,\n // so it must be inside the try/catch.\n if (typeof window !== 'undefined' &&\n typeof window[domStorageName] !== 'undefined') {\n // Need to test cache. Just because it's here doesn't mean it works\n var domStorage = window[domStorageName];\n domStorage.setItem('firebase:sentinel', 'cache');\n domStorage.removeItem('firebase:sentinel');\n return new DOMStorageWrapper_1.DOMStorageWrapper(domStorage);\n }\n }\n catch (e) { }\n // Failed to create wrapper. Just return in-memory storage.\n // TODO: log?\n return new MemoryStorage_1.MemoryStorage();\n};\n/** A storage object that lasts across sessions */\nexports.PersistentStorage = createStoragefor('localStorage');\n/** A storage object that only lasts one session */\nexports.SessionStorage = createStoragefor('sessionStorage');\n\n//# sourceMappingURL=storage.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/storage/storage.js\n// module id = 14\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PROTOCOL_VERSION = '5';\nexports.VERSION_PARAM = 'v';\nexports.TRANSPORT_SESSION_PARAM = 's';\nexports.REFERER_PARAM = 'r';\nexports.FORGE_REF = 'f';\nexports.FORGE_DOMAIN = 'firebaseio.com';\nexports.LAST_SESSION_PARAM = 'ls';\nexports.WEBSOCKET = 'websocket';\nexports.LONG_POLLING = 'long_polling';\n\n//# sourceMappingURL=Constants.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/Constants.js\n// module id = 15\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Node_1 = require(\"../Node\");\nvar util_1 = require(\"../../util/util\");\n/**\n *\n * @constructor\n */\nvar Index = /** @class */ (function () {\n function Index() {\n }\n /**\n * @return {function(!NamedNode, !NamedNode):number} A standalone comparison function for\n * this index\n */\n Index.prototype.getCompare = function () {\n return this.compare.bind(this);\n };\n /**\n * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,\n * it's possible that the changes are isolated to parts of the snapshot that are not indexed.\n *\n * @param {!Node} oldNode\n * @param {!Node} newNode\n * @return {boolean} True if the portion of the snapshot being indexed changed between oldNode and newNode\n */\n Index.prototype.indexedValueChanged = function (oldNode, newNode) {\n var oldWrapped = new Node_1.NamedNode(util_1.MIN_NAME, oldNode);\n var newWrapped = new Node_1.NamedNode(util_1.MIN_NAME, newNode);\n return this.compare(oldWrapped, newWrapped) !== 0;\n };\n /**\n * @return {!NamedNode} a node wrapper that will sort equal to or less than\n * any other node wrapper, using this index\n */\n Index.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n return Index;\n}());\nexports.Index = Index;\n\n//# sourceMappingURL=Index.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/indexes/Index.js\n// module id = 16\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../util/util\");\nvar snap_1 = require(\"./snap\");\nvar __childrenNodeConstructor;\n/**\n * LeafNode is a class for storing leaf nodes in a DataSnapshot. It\n * implements Node and stores the value of the node (a string,\n * number, or boolean) accessible via getValue().\n */\nvar LeafNode = /** @class */ (function () {\n /**\n * @implements {Node}\n * @param {!(string|number|boolean|Object)} value_ The value to store in this leaf node.\n * The object type is possible in the event of a deferred value\n * @param {!Node=} priorityNode_ The priority of this node.\n */\n function LeafNode(value_, priorityNode_) {\n if (priorityNode_ === void 0) { priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE; }\n this.value_ = value_;\n this.priorityNode_ = priorityNode_;\n this.lazyHash_ = null;\n util_1.assert(this.value_ !== undefined && this.value_ !== null, \"LeafNode shouldn't be created with null/undefined value.\");\n snap_1.validatePriorityNode(this.priorityNode_);\n }\n Object.defineProperty(LeafNode, \"__childrenNodeConstructor\", {\n get: function () {\n return __childrenNodeConstructor;\n },\n set: function (val) {\n __childrenNodeConstructor = val;\n },\n enumerable: true,\n configurable: true\n });\n /** @inheritDoc */\n LeafNode.prototype.isLeafNode = function () {\n return true;\n };\n /** @inheritDoc */\n LeafNode.prototype.getPriority = function () {\n return this.priorityNode_;\n };\n /** @inheritDoc */\n LeafNode.prototype.updatePriority = function (newPriorityNode) {\n return new LeafNode(this.value_, newPriorityNode);\n };\n /** @inheritDoc */\n LeafNode.prototype.getImmediateChild = function (childName) {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.priorityNode_;\n }\n else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n };\n /** @inheritDoc */\n LeafNode.prototype.getChild = function (path) {\n if (path.isEmpty()) {\n return this;\n }\n else if (path.getFront() === '.priority') {\n return this.priorityNode_;\n }\n else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.hasChild = function () {\n return false;\n };\n /** @inheritDoc */\n LeafNode.prototype.getPredecessorChildName = function (childName, childNode) {\n return null;\n };\n /** @inheritDoc */\n LeafNode.prototype.updateImmediateChild = function (childName, newChildNode) {\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n }\n else if (newChildNode.isEmpty() && childName !== '.priority') {\n return this;\n }\n else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);\n }\n };\n /** @inheritDoc */\n LeafNode.prototype.updateChild = function (path, newChildNode) {\n var front = path.getFront();\n if (front === null) {\n return newChildNode;\n }\n else if (newChildNode.isEmpty() && front !== '.priority') {\n return this;\n }\n else {\n util_1.assert(front !== '.priority' || path.getLength() === 1, '.priority must be the last token in a path');\n return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(path.popFront(), newChildNode));\n }\n };\n /** @inheritDoc */\n LeafNode.prototype.isEmpty = function () {\n return false;\n };\n /** @inheritDoc */\n LeafNode.prototype.numChildren = function () {\n return 0;\n };\n /** @inheritDoc */\n LeafNode.prototype.forEachChild = function (index, action) {\n return false;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.val = function (exportFormat) {\n if (exportFormat && !this.getPriority().isEmpty())\n return {\n '.value': this.getValue(),\n '.priority': this.getPriority().val()\n };\n else\n return this.getValue();\n };\n /** @inheritDoc */\n LeafNode.prototype.hash = function () {\n if (this.lazyHash_ === null) {\n var toHash = '';\n if (!this.priorityNode_.isEmpty())\n toHash +=\n 'priority:' +\n snap_1.priorityHashText(this.priorityNode_.val()) +\n ':';\n var type = typeof this.value_;\n toHash += type + ':';\n if (type === 'number') {\n toHash += util_2.doubleToIEEE754String(this.value_);\n }\n else {\n toHash += this.value_;\n }\n this.lazyHash_ = util_2.sha1(toHash);\n }\n return this.lazyHash_;\n };\n /**\n * Returns the value of the leaf node.\n * @return {Object|string|number|boolean} The value of the node.\n */\n LeafNode.prototype.getValue = function () {\n return this.value_;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.compareTo = function (other) {\n if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {\n return 1;\n }\n else if (other instanceof LeafNode.__childrenNodeConstructor) {\n return -1;\n }\n else {\n util_1.assert(other.isLeafNode(), 'Unknown node type');\n return this.compareToLeafNode_(other);\n }\n };\n /**\n * Comparison specifically for two leaf nodes\n * @param {!LeafNode} otherLeaf\n * @return {!number}\n * @private\n */\n LeafNode.prototype.compareToLeafNode_ = function (otherLeaf) {\n var otherLeafType = typeof otherLeaf.value_;\n var thisLeafType = typeof this.value_;\n var otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);\n var thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);\n util_1.assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);\n util_1.assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);\n if (otherIndex === thisIndex) {\n // Same type, compare values\n if (thisLeafType === 'object') {\n // Deferred value nodes are all equal, but we should also never get to this point...\n return 0;\n }\n else {\n // Note that this works because true > false, all others are number or string comparisons\n if (this.value_ < otherLeaf.value_) {\n return -1;\n }\n else if (this.value_ === otherLeaf.value_) {\n return 0;\n }\n else {\n return 1;\n }\n }\n }\n else {\n return thisIndex - otherIndex;\n }\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.withIndex = function () {\n return this;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.isIndexed = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.equals = function (other) {\n /**\n * @inheritDoc\n */\n if (other === this) {\n return true;\n }\n else if (other.isLeafNode()) {\n var otherLeaf = other;\n return (this.value_ === otherLeaf.value_ &&\n this.priorityNode_.equals(otherLeaf.priorityNode_));\n }\n else {\n return false;\n }\n };\n /**\n * The sort order for comparing leaf nodes of different types. If two leaf nodes have\n * the same type, the comparison falls back to their value\n * @type {Array.}\n * @const\n */\n LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];\n return LeafNode;\n}());\nexports.LeafNode = LeafNode;\n\n//# sourceMappingURL=LeafNode.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/LeafNode.js\n// module id = 17\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * An iterator over an LLRBNode.\n */\nvar SortedMapIterator = /** @class */ (function () {\n /**\n * @template K, V, T\n * @param {LLRBNode|LLRBEmptyNode} node Node to iterate.\n * @param {?K} startKey\n * @param {function(K, K): number} comparator\n * @param {boolean} isReverse_ Whether or not to iterate in reverse\n * @param {(function(K, V):T)=} resultGenerator_\n */\n function SortedMapIterator(node, startKey, comparator, isReverse_, resultGenerator_) {\n if (resultGenerator_ === void 0) { resultGenerator_ = null; }\n this.isReverse_ = isReverse_;\n this.resultGenerator_ = resultGenerator_;\n /** @private\n * @type {Array.}\n */\n this.nodeStack_ = [];\n var cmp = 1;\n while (!node.isEmpty()) {\n node = node;\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (isReverse_)\n cmp *= -1;\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse_) {\n node = node.left;\n }\n else {\n node = node.right;\n }\n }\n else if (cmp === 0) {\n // This node is exactly equal to our start key. Push it on the stack, but stop iterating;\n this.nodeStack_.push(node);\n break;\n }\n else {\n // This node is greater than our start key, add it to the stack and move to the next one\n this.nodeStack_.push(node);\n if (this.isReverse_) {\n node = node.right;\n }\n else {\n node = node.left;\n }\n }\n }\n }\n SortedMapIterator.prototype.getNext = function () {\n if (this.nodeStack_.length === 0)\n return null;\n var node = this.nodeStack_.pop();\n var result;\n if (this.resultGenerator_)\n result = this.resultGenerator_(node.key, node.value);\n else\n result = { key: node.key, value: node.value };\n if (this.isReverse_) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.right;\n }\n }\n else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.left;\n }\n }\n return result;\n };\n SortedMapIterator.prototype.hasNext = function () {\n return this.nodeStack_.length > 0;\n };\n SortedMapIterator.prototype.peek = function () {\n if (this.nodeStack_.length === 0)\n return null;\n var node = this.nodeStack_[this.nodeStack_.length - 1];\n if (this.resultGenerator_) {\n return this.resultGenerator_(node.key, node.value);\n }\n else {\n return { key: node.key, value: node.value };\n }\n };\n return SortedMapIterator;\n}());\nexports.SortedMapIterator = SortedMapIterator;\n/**\n * Represents a node in a Left-leaning Red-Black tree.\n */\nvar LLRBNode = /** @class */ (function () {\n /**\n * @template K, V\n * @param {!K} key Key associated with this node.\n * @param {!V} value Value associated with this node.\n * @param {?boolean} color Whether this node is red.\n * @param {?(LLRBNode|LLRBEmptyNode)=} left Left child.\n * @param {?(LLRBNode|LLRBEmptyNode)=} right Right child.\n */\n function LLRBNode(key, value, color, left, right) {\n this.key = key;\n this.value = value;\n this.color = color != null ? color : LLRBNode.RED;\n this.left =\n left != null ? left : SortedMap.EMPTY_NODE;\n this.right =\n right != null ? right : SortedMap.EMPTY_NODE;\n }\n /**\n * Returns a copy of the current node, optionally replacing pieces of it.\n *\n * @param {?K} key New key for the node, or null.\n * @param {?V} value New value for the node, or null.\n * @param {?boolean} color New color for the node, or null.\n * @param {?LLRBNode|LLRBEmptyNode} left New left child for the node, or null.\n * @param {?LLRBNode|LLRBEmptyNode} right New right child for the node, or null.\n * @return {!LLRBNode} The node copy.\n */\n LLRBNode.prototype.copy = function (key, value, color, left, right) {\n return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);\n };\n /**\n * @return {number} The total number of nodes in the tree.\n */\n LLRBNode.prototype.count = function () {\n return this.left.count() + 1 + this.right.count();\n };\n /**\n * @return {boolean} True if the tree is empty.\n */\n LLRBNode.prototype.isEmpty = function () {\n return false;\n };\n /**\n * Traverses the tree in key order and calls the specified action function\n * for each node.\n *\n * @param {function(!K, !V):*} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {*} The first truthy value returned by action, or the last falsey\n * value returned by action\n */\n LLRBNode.prototype.inorderTraversal = function (action) {\n return (this.left.inorderTraversal(action) ||\n action(this.key, this.value) ||\n this.right.inorderTraversal(action));\n };\n /**\n * Traverses the tree in reverse key order and calls the specified action function\n * for each node.\n *\n * @param {function(!Object, !Object)} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {*} True if traversal was aborted.\n */\n LLRBNode.prototype.reverseTraversal = function (action) {\n return (this.right.reverseTraversal(action) ||\n action(this.key, this.value) ||\n this.left.reverseTraversal(action));\n };\n /**\n * @return {!Object} The minimum node in the tree.\n * @private\n */\n LLRBNode.prototype.min_ = function () {\n if (this.left.isEmpty()) {\n return this;\n }\n else {\n return this.left.min_();\n }\n };\n /**\n * @return {!K} The maximum key in the tree.\n */\n LLRBNode.prototype.minKey = function () {\n return this.min_().key;\n };\n /**\n * @return {!K} The maximum key in the tree.\n */\n LLRBNode.prototype.maxKey = function () {\n if (this.right.isEmpty()) {\n return this.key;\n }\n else {\n return this.right.maxKey();\n }\n };\n /**\n *\n * @param {!Object} key Key to insert.\n * @param {!Object} value Value to insert.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBNode} New tree, with the key/value added.\n */\n LLRBNode.prototype.insert = function (key, value, comparator) {\n var cmp, n;\n n = this;\n cmp = comparator(key, n.key);\n if (cmp < 0) {\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n }\n else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n }\n else {\n n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));\n }\n return n.fixUp_();\n };\n /**\n * @private\n * @return {!LLRBNode|LLRBEmptyNode} New tree, with the minimum key removed.\n */\n LLRBNode.prototype.removeMin_ = function () {\n if (this.left.isEmpty()) {\n return SortedMap.EMPTY_NODE;\n }\n var n = this;\n if (!n.left.isRed_() && !n.left.left.isRed_())\n n = n.moveRedLeft_();\n n = n.copy(null, null, null, n.left.removeMin_(), null);\n return n.fixUp_();\n };\n /**\n * @param {!Object} key The key of the item to remove.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBNode|LLRBEmptyNode} New tree, with the specified item removed.\n */\n LLRBNode.prototype.remove = function (key, comparator) {\n var n, smallest;\n n = this;\n if (comparator(key, n.key) < 0) {\n if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {\n n = n.moveRedLeft_();\n }\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n }\n else {\n if (n.left.isRed_())\n n = n.rotateRight_();\n if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {\n n = n.moveRedRight_();\n }\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return SortedMap.EMPTY_NODE;\n }\n else {\n smallest = n.right.min_();\n n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp_();\n };\n /**\n * @private\n * @return {boolean} Whether this is a RED node.\n */\n LLRBNode.prototype.isRed_ = function () {\n return this.color;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree after performing any needed rotations.\n */\n LLRBNode.prototype.fixUp_ = function () {\n var n = this;\n if (n.right.isRed_() && !n.left.isRed_())\n n = n.rotateLeft_();\n if (n.left.isRed_() && n.left.left.isRed_())\n n = n.rotateRight_();\n if (n.left.isRed_() && n.right.isRed_())\n n = n.colorFlip_();\n return n;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after moveRedLeft.\n */\n LLRBNode.prototype.moveRedLeft_ = function () {\n var n = this.colorFlip_();\n if (n.right.left.isRed_()) {\n n = n.copy(null, null, null, null, n.right.rotateRight_());\n n = n.rotateLeft_();\n n = n.colorFlip_();\n }\n return n;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after moveRedRight.\n */\n LLRBNode.prototype.moveRedRight_ = function () {\n var n = this.colorFlip_();\n if (n.left.left.isRed_()) {\n n = n.rotateRight_();\n n = n.colorFlip_();\n }\n return n;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after rotateLeft.\n */\n LLRBNode.prototype.rotateLeft_ = function () {\n var nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return this.right.copy(null, null, this.color, nl, null);\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after rotateRight.\n */\n LLRBNode.prototype.rotateRight_ = function () {\n var nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return this.left.copy(null, null, this.color, null, nr);\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after colorFlip.\n */\n LLRBNode.prototype.colorFlip_ = function () {\n var left = this.left.copy(null, null, !this.left.color, null, null);\n var right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n };\n /**\n * For testing.\n *\n * @private\n * @return {boolean} True if all is well.\n */\n LLRBNode.prototype.checkMaxDepth_ = function () {\n var blackDepth = this.check_();\n return Math.pow(2.0, blackDepth) <= this.count() + 1;\n };\n /**\n * @private\n * @return {number} Not sure what this returns exactly. :-).\n */\n LLRBNode.prototype.check_ = function () {\n var blackDepth;\n if (this.isRed_() && this.left.isRed_()) {\n throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');\n }\n if (this.right.isRed_()) {\n throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');\n }\n blackDepth = this.left.check_();\n if (blackDepth !== this.right.check_()) {\n throw new Error('Black depths differ');\n }\n else {\n return blackDepth + (this.isRed_() ? 0 : 1);\n }\n };\n LLRBNode.RED = true;\n LLRBNode.BLACK = false;\n return LLRBNode;\n}());\nexports.LLRBNode = LLRBNode;\n/**\n * Represents an empty node (a leaf node in the Red-Black Tree).\n */\nvar LLRBEmptyNode = /** @class */ (function () {\n function LLRBEmptyNode() {\n }\n /**\n * Returns a copy of the current node.\n *\n * @return {!LLRBEmptyNode} The node copy.\n */\n LLRBEmptyNode.prototype.copy = function (key, value, color, left, right) {\n return this;\n };\n /**\n * Returns a copy of the tree, with the specified key/value added.\n *\n * @param {!K} key Key to be added.\n * @param {!V} value Value to be added.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBNode} New tree, with item added.\n */\n LLRBEmptyNode.prototype.insert = function (key, value, comparator) {\n return new LLRBNode(key, value, null);\n };\n /**\n * Returns a copy of the tree, with the specified key removed.\n *\n * @param {!K} key The key to remove.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBEmptyNode} New tree, with item removed.\n */\n LLRBEmptyNode.prototype.remove = function (key, comparator) {\n return this;\n };\n /**\n * @return {number} The total number of nodes in the tree.\n */\n LLRBEmptyNode.prototype.count = function () {\n return 0;\n };\n /**\n * @return {boolean} True if the tree is empty.\n */\n LLRBEmptyNode.prototype.isEmpty = function () {\n return true;\n };\n /**\n * Traverses the tree in key order and calls the specified action function\n * for each node.\n *\n * @param {function(!K, !V):*} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {boolean} True if traversal was aborted.\n */\n LLRBEmptyNode.prototype.inorderTraversal = function (action) {\n return false;\n };\n /**\n * Traverses the tree in reverse key order and calls the specified action function\n * for each node.\n *\n * @param {function(!K, !V)} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {boolean} True if traversal was aborted.\n */\n LLRBEmptyNode.prototype.reverseTraversal = function (action) {\n return false;\n };\n /**\n * @return {null}\n */\n LLRBEmptyNode.prototype.minKey = function () {\n return null;\n };\n /**\n * @return {null}\n */\n LLRBEmptyNode.prototype.maxKey = function () {\n return null;\n };\n /**\n * @private\n * @return {number} Not sure what this returns exactly. :-).\n */\n LLRBEmptyNode.prototype.check_ = function () {\n return 0;\n };\n /**\n * @private\n * @return {boolean} Whether this node is red.\n */\n LLRBEmptyNode.prototype.isRed_ = function () {\n return false;\n };\n return LLRBEmptyNode;\n}());\nexports.LLRBEmptyNode = LLRBEmptyNode;\n/**\n * An immutable sorted map implementation, based on a Left-leaning Red-Black\n * tree.\n */\nvar SortedMap = /** @class */ (function () {\n /**\n * @template K, V\n * @param {function(K, K):number} comparator_ Key comparator.\n * @param {LLRBNode=} root_ (Optional) Root node for the map.\n */\n function SortedMap(comparator_, root_) {\n if (root_ === void 0) { root_ = SortedMap.EMPTY_NODE; }\n this.comparator_ = comparator_;\n this.root_ = root_;\n }\n /**\n * Returns a copy of the map, with the specified key/value added or replaced.\n * (TODO: We should perhaps rename this method to 'put')\n *\n * @param {!K} key Key to be added.\n * @param {!V} value Value to be added.\n * @return {!SortedMap.} New map, with item added.\n */\n SortedMap.prototype.insert = function (key, value) {\n return new SortedMap(this.comparator_, this.root_\n .insert(key, value, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null));\n };\n /**\n * Returns a copy of the map, with the specified key removed.\n *\n * @param {!K} key The key to remove.\n * @return {!SortedMap.} New map, with item removed.\n */\n SortedMap.prototype.remove = function (key) {\n return new SortedMap(this.comparator_, this.root_\n .remove(key, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null));\n };\n /**\n * Returns the value of the node with the given key, or null.\n *\n * @param {!K} key The key to look up.\n * @return {?V} The value of the node with the given key, or null if the\n * key doesn't exist.\n */\n SortedMap.prototype.get = function (key) {\n var cmp;\n var node = this.root_;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n return node.value;\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else if (cmp > 0) {\n node = node.right;\n }\n }\n return null;\n };\n /**\n * Returns the key of the item *before* the specified key, or null if key is the first item.\n * @param {K} key The key to find the predecessor of\n * @return {?K} The predecessor key.\n */\n SortedMap.prototype.getPredecessorKey = function (key) {\n var cmp, node = this.root_, rightParent = null;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n if (!node.left.isEmpty()) {\n node = node.left;\n while (!node.right.isEmpty())\n node = node.right;\n return node.key;\n }\n else if (rightParent) {\n return rightParent.key;\n }\n else {\n return null; // first item.\n }\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else if (cmp > 0) {\n rightParent = node;\n node = node.right;\n }\n }\n throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');\n };\n /**\n * @return {boolean} True if the map is empty.\n */\n SortedMap.prototype.isEmpty = function () {\n return this.root_.isEmpty();\n };\n /**\n * @return {number} The total number of nodes in the map.\n */\n SortedMap.prototype.count = function () {\n return this.root_.count();\n };\n /**\n * @return {?K} The minimum key in the map.\n */\n SortedMap.prototype.minKey = function () {\n return this.root_.minKey();\n };\n /**\n * @return {?K} The maximum key in the map.\n */\n SortedMap.prototype.maxKey = function () {\n return this.root_.maxKey();\n };\n /**\n * Traverses the map in key order and calls the specified action function\n * for each key/value pair.\n *\n * @param {function(!K, !V):*} action Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @return {*} The first truthy value returned by action, or the last falsey\n * value returned by action\n */\n SortedMap.prototype.inorderTraversal = function (action) {\n return this.root_.inorderTraversal(action);\n };\n /**\n * Traverses the map in reverse key order and calls the specified action function\n * for each key/value pair.\n *\n * @param {function(!Object, !Object)} action Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @return {*} True if the traversal was aborted.\n */\n SortedMap.prototype.reverseTraversal = function (action) {\n return this.root_.reverseTraversal(action);\n };\n /**\n * Returns an iterator over the SortedMap.\n * @template T\n * @param {(function(K, V):T)=} resultGenerator\n * @return {SortedMapIterator.} The iterator.\n */\n SortedMap.prototype.getIterator = function (resultGenerator) {\n return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);\n };\n SortedMap.prototype.getIteratorFrom = function (key, resultGenerator) {\n return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);\n };\n SortedMap.prototype.getReverseIteratorFrom = function (key, resultGenerator) {\n return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);\n };\n SortedMap.prototype.getReverseIterator = function (resultGenerator) {\n return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);\n };\n /**\n * Always use the same empty node, to reduce memory.\n * @const\n */\n SortedMap.EMPTY_NODE = new LLRBEmptyNode();\n return SortedMap;\n}());\nexports.SortedMap = SortedMap;\n\n//# sourceMappingURL=SortedMap.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/SortedMap.js\n// module id = 18\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ServerValues_1 = require(\"./util/ServerValues\");\nvar nodeFromJSON_1 = require(\"./snap/nodeFromJSON\");\nvar Path_1 = require(\"./util/Path\");\nvar SparseSnapshotTree_1 = require(\"./SparseSnapshotTree\");\nvar SyncTree_1 = require(\"./SyncTree\");\nvar SnapshotHolder_1 = require(\"./SnapshotHolder\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"./util/util\");\nvar util_3 = require(\"@firebase/util\");\nvar AuthTokenProvider_1 = require(\"./AuthTokenProvider\");\nvar StatsManager_1 = require(\"./stats/StatsManager\");\nvar StatsReporter_1 = require(\"./stats/StatsReporter\");\nvar StatsListener_1 = require(\"./stats/StatsListener\");\nvar EventQueue_1 = require(\"./view/EventQueue\");\nvar PersistentConnection_1 = require(\"./PersistentConnection\");\nvar ReadonlyRestClient_1 = require(\"./ReadonlyRestClient\");\nvar Database_1 = require(\"../api/Database\");\nvar INTERRUPT_REASON = 'repo_interrupt';\n/**\n * A connection to a single data repository.\n */\nvar Repo = /** @class */ (function () {\n /**\n * @param {!RepoInfo} repoInfo_\n * @param {boolean} forceRestClient\n * @param {!FirebaseApp} app\n */\n function Repo(repoInfo_, forceRestClient, app) {\n var _this = this;\n this.repoInfo_ = repoInfo_;\n this.app = app;\n this.dataUpdateCount = 0;\n this.statsListener_ = null;\n this.eventQueue_ = new EventQueue_1.EventQueue();\n this.nextWriteId_ = 1;\n this.interceptServerDataCallback_ = null;\n // A list of data pieces and paths to be set when this client disconnects.\n this.onDisconnect_ = new SparseSnapshotTree_1.SparseSnapshotTree();\n /**\n * TODO: This should be @private but it's used by test_access.js and internal.js\n * @type {?PersistentConnection}\n */\n this.persistentConnection_ = null;\n /** @type {!AuthTokenProvider} */\n var authTokenProvider = new AuthTokenProvider_1.AuthTokenProvider(app);\n this.stats_ = StatsManager_1.StatsManager.getCollection(repoInfo_);\n if (forceRestClient || util_2.beingCrawled()) {\n this.server_ = new ReadonlyRestClient_1.ReadonlyRestClient(this.repoInfo_, this.onDataUpdate_.bind(this), authTokenProvider);\n // Minor hack: Fire onConnect immediately, since there's no actual connection.\n setTimeout(this.onConnectStatus_.bind(this, true), 0);\n }\n else {\n var authOverride = app.options['databaseAuthVariableOverride'];\n // Validate authOverride\n if (typeof authOverride !== 'undefined' && authOverride !== null) {\n if (typeof authOverride !== 'object') {\n throw new Error('Only objects are supported for option databaseAuthVariableOverride');\n }\n try {\n util_1.stringify(authOverride);\n }\n catch (e) {\n throw new Error('Invalid authOverride provided: ' + e);\n }\n }\n this.persistentConnection_ = new PersistentConnection_1.PersistentConnection(this.repoInfo_, this.onDataUpdate_.bind(this), this.onConnectStatus_.bind(this), this.onServerInfoUpdate_.bind(this), authTokenProvider, authOverride);\n this.server_ = this.persistentConnection_;\n }\n authTokenProvider.addTokenChangeListener(function (token) {\n _this.server_.refreshAuthToken(token);\n });\n // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),\n // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.\n this.statsReporter_ = StatsManager_1.StatsManager.getOrCreateReporter(repoInfo_, function () { return new StatsReporter_1.StatsReporter(_this.stats_, _this.server_); });\n this.transactions_init_();\n // Used for .info.\n this.infoData_ = new SnapshotHolder_1.SnapshotHolder();\n this.infoSyncTree_ = new SyncTree_1.SyncTree({\n startListening: function (query, tag, currentHashFn, onComplete) {\n var infoEvents = [];\n var node = _this.infoData_.getNode(query.path);\n // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events\n // on initial data...\n if (!node.isEmpty()) {\n infoEvents = _this.infoSyncTree_.applyServerOverwrite(query.path, node);\n setTimeout(function () {\n onComplete('ok');\n }, 0);\n }\n return infoEvents;\n },\n stopListening: function () { }\n });\n this.updateInfo_('connected', false);\n this.serverSyncTree_ = new SyncTree_1.SyncTree({\n startListening: function (query, tag, currentHashFn, onComplete) {\n _this.server_.listen(query, currentHashFn, tag, function (status, data) {\n var events = onComplete(status, data);\n _this.eventQueue_.raiseEventsForChangedPath(query.path, events);\n });\n // No synchronous events for network-backed sync trees\n return [];\n },\n stopListening: function (query, tag) {\n _this.server_.unlisten(query, tag);\n }\n });\n }\n /**\n * @return {string} The URL corresponding to the root of this Firebase.\n */\n Repo.prototype.toString = function () {\n return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);\n };\n /**\n * @return {!string} The namespace represented by the repo.\n */\n Repo.prototype.name = function () {\n return this.repoInfo_.namespace;\n };\n /**\n * @return {!number} The time in milliseconds, taking the server offset into account if we have one.\n */\n Repo.prototype.serverTime = function () {\n var offsetNode = this.infoData_.getNode(new Path_1.Path('.info/serverTimeOffset'));\n var offset = offsetNode.val() || 0;\n return new Date().getTime() + offset;\n };\n /**\n * Generate ServerValues using some variables from the repo object.\n * @return {!Object}\n */\n Repo.prototype.generateServerValues = function () {\n return ServerValues_1.generateWithValues({\n timestamp: this.serverTime()\n });\n };\n /**\n * Called by realtime when we get new messages from the server.\n *\n * @private\n * @param {string} pathString\n * @param {*} data\n * @param {boolean} isMerge\n * @param {?number} tag\n */\n Repo.prototype.onDataUpdate_ = function (pathString, data, isMerge, tag) {\n // For testing.\n this.dataUpdateCount++;\n var path = new Path_1.Path(pathString);\n data = this.interceptServerDataCallback_\n ? this.interceptServerDataCallback_(pathString, data)\n : data;\n var events = [];\n if (tag) {\n if (isMerge) {\n var taggedChildren = util_3.map(data, function (raw) {\n return nodeFromJSON_1.nodeFromJSON(raw);\n });\n events = this.serverSyncTree_.applyTaggedQueryMerge(path, taggedChildren, tag);\n }\n else {\n var taggedSnap = nodeFromJSON_1.nodeFromJSON(data);\n events = this.serverSyncTree_.applyTaggedQueryOverwrite(path, taggedSnap, tag);\n }\n }\n else if (isMerge) {\n var changedChildren = util_3.map(data, function (raw) {\n return nodeFromJSON_1.nodeFromJSON(raw);\n });\n events = this.serverSyncTree_.applyServerMerge(path, changedChildren);\n }\n else {\n var snap = nodeFromJSON_1.nodeFromJSON(data);\n events = this.serverSyncTree_.applyServerOverwrite(path, snap);\n }\n var affectedPath = path;\n if (events.length > 0) {\n // Since we have a listener outstanding for each transaction, receiving any events\n // is a proxy for some change having occurred.\n affectedPath = this.rerunTransactions_(path);\n }\n this.eventQueue_.raiseEventsForChangedPath(affectedPath, events);\n };\n /**\n * TODO: This should be @private but it's used by test_access.js and internal.js\n * @param {?function(!string, *):*} callback\n * @private\n */\n Repo.prototype.interceptServerData_ = function (callback) {\n this.interceptServerDataCallback_ = callback;\n };\n /**\n * @param {!boolean} connectStatus\n * @private\n */\n Repo.prototype.onConnectStatus_ = function (connectStatus) {\n this.updateInfo_('connected', connectStatus);\n if (connectStatus === false) {\n this.runOnDisconnectEvents_();\n }\n };\n /**\n * @param {!Object} updates\n * @private\n */\n Repo.prototype.onServerInfoUpdate_ = function (updates) {\n var _this = this;\n util_2.each(updates, function (value, key) {\n _this.updateInfo_(key, value);\n });\n };\n /**\n *\n * @param {!string} pathString\n * @param {*} value\n * @private\n */\n Repo.prototype.updateInfo_ = function (pathString, value) {\n var path = new Path_1.Path('/.info/' + pathString);\n var newNode = nodeFromJSON_1.nodeFromJSON(value);\n this.infoData_.updateSnapshot(path, newNode);\n var events = this.infoSyncTree_.applyServerOverwrite(path, newNode);\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n };\n /**\n * @return {!number}\n * @private\n */\n Repo.prototype.getNextWriteId_ = function () {\n return this.nextWriteId_++;\n };\n /**\n * @param {!Path} path\n * @param {*} newVal\n * @param {number|string|null} newPriority\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.setWithPriority = function (path, newVal, newPriority, onComplete) {\n var _this = this;\n this.log_('set', {\n path: path.toString(),\n value: newVal,\n priority: newPriority\n });\n // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or\n // (b) store unresolved paths on JSON parse\n var serverValues = this.generateServerValues();\n var newNodeUnresolved = nodeFromJSON_1.nodeFromJSON(newVal, newPriority);\n var newNode = ServerValues_1.resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n var writeId = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserOverwrite(path, newNode, writeId, true);\n this.eventQueue_.queueEvents(events);\n this.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), function (status, errorReason) {\n var success = status === 'ok';\n if (!success) {\n util_2.warn('set at ' + path + ' failed: ' + status);\n }\n var clearEvents = _this.serverSyncTree_.ackUserWrite(writeId, !success);\n _this.eventQueue_.raiseEventsForChangedPath(path, clearEvents);\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n var affectedPath = this.abortTransactions_(path);\n this.rerunTransactions_(affectedPath);\n // We queued the events above, so just flush the queue here\n this.eventQueue_.raiseEventsForChangedPath(affectedPath, []);\n };\n /**\n * @param {!Path} path\n * @param {!Object} childrenToMerge\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.update = function (path, childrenToMerge, onComplete) {\n var _this = this;\n this.log_('update', { path: path.toString(), value: childrenToMerge });\n // Start with our existing data and merge each child into it.\n var empty = true;\n var serverValues = this.generateServerValues();\n var changedChildren = {};\n util_3.forEach(childrenToMerge, function (changedKey, changedValue) {\n empty = false;\n var newNodeUnresolved = nodeFromJSON_1.nodeFromJSON(changedValue);\n changedChildren[changedKey] = ServerValues_1.resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n });\n if (!empty) {\n var writeId_1 = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserMerge(path, changedChildren, writeId_1);\n this.eventQueue_.queueEvents(events);\n this.server_.merge(path.toString(), childrenToMerge, function (status, errorReason) {\n var success = status === 'ok';\n if (!success) {\n util_2.warn('update at ' + path + ' failed: ' + status);\n }\n var clearEvents = _this.serverSyncTree_.ackUserWrite(writeId_1, !success);\n var affectedPath = clearEvents.length > 0 ? _this.rerunTransactions_(path) : path;\n _this.eventQueue_.raiseEventsForChangedPath(affectedPath, clearEvents);\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n util_3.forEach(childrenToMerge, function (changedPath) {\n var affectedPath = _this.abortTransactions_(path.child(changedPath));\n _this.rerunTransactions_(affectedPath);\n });\n // We queued the events above, so just flush the queue here\n this.eventQueue_.raiseEventsForChangedPath(path, []);\n }\n else {\n util_2.log(\"update() called with empty data. Don't do anything.\");\n this.callOnCompleteCallback(onComplete, 'ok');\n }\n };\n /**\n * Applies all of the changes stored up in the onDisconnect_ tree.\n * @private\n */\n Repo.prototype.runOnDisconnectEvents_ = function () {\n var _this = this;\n this.log_('onDisconnectEvents');\n var serverValues = this.generateServerValues();\n var resolvedOnDisconnectTree = ServerValues_1.resolveDeferredValueTree(this.onDisconnect_, serverValues);\n var events = [];\n resolvedOnDisconnectTree.forEachTree(Path_1.Path.Empty, function (path, snap) {\n events = events.concat(_this.serverSyncTree_.applyServerOverwrite(path, snap));\n var affectedPath = _this.abortTransactions_(path);\n _this.rerunTransactions_(affectedPath);\n });\n this.onDisconnect_ = new SparseSnapshotTree_1.SparseSnapshotTree();\n this.eventQueue_.raiseEventsForChangedPath(Path_1.Path.Empty, events);\n };\n /**\n * @param {!Path} path\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectCancel = function (path, onComplete) {\n var _this = this;\n this.server_.onDisconnectCancel(path.toString(), function (status, errorReason) {\n if (status === 'ok') {\n _this.onDisconnect_.forget(path);\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Path} path\n * @param {*} value\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectSet = function (path, value, onComplete) {\n var _this = this;\n var newNode = nodeFromJSON_1.nodeFromJSON(value);\n this.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {\n if (status === 'ok') {\n _this.onDisconnect_.remember(path, newNode);\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Path} path\n * @param {*} value\n * @param {*} priority\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectSetWithPriority = function (path, value, priority, onComplete) {\n var _this = this;\n var newNode = nodeFromJSON_1.nodeFromJSON(value, priority);\n this.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {\n if (status === 'ok') {\n _this.onDisconnect_.remember(path, newNode);\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Path} path\n * @param {*} childrenToMerge\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectUpdate = function (path, childrenToMerge, onComplete) {\n var _this = this;\n if (util_3.isEmpty(childrenToMerge)) {\n util_2.log(\"onDisconnect().update() called with empty data. Don't do anything.\");\n this.callOnCompleteCallback(onComplete, 'ok');\n return;\n }\n this.server_.onDisconnectMerge(path.toString(), childrenToMerge, function (status, errorReason) {\n if (status === 'ok') {\n util_3.forEach(childrenToMerge, function (childName, childNode) {\n var newChildNode = nodeFromJSON_1.nodeFromJSON(childNode);\n _this.onDisconnect_.remember(path.child(childName), newChildNode);\n });\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Query} query\n * @param {!EventRegistration} eventRegistration\n */\n Repo.prototype.addEventCallbackForQuery = function (query, eventRegistration) {\n var events;\n if (query.path.getFront() === '.info') {\n events = this.infoSyncTree_.addEventRegistration(query, eventRegistration);\n }\n else {\n events = this.serverSyncTree_.addEventRegistration(query, eventRegistration);\n }\n this.eventQueue_.raiseEventsAtPath(query.path, events);\n };\n /**\n * @param {!Query} query\n * @param {?EventRegistration} eventRegistration\n */\n Repo.prototype.removeEventCallbackForQuery = function (query, eventRegistration) {\n // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof\n // a little bit by handling the return values anyways.\n var events;\n if (query.path.getFront() === '.info') {\n events = this.infoSyncTree_.removeEventRegistration(query, eventRegistration);\n }\n else {\n events = this.serverSyncTree_.removeEventRegistration(query, eventRegistration);\n }\n this.eventQueue_.raiseEventsAtPath(query.path, events);\n };\n Repo.prototype.interrupt = function () {\n if (this.persistentConnection_) {\n this.persistentConnection_.interrupt(INTERRUPT_REASON);\n }\n };\n Repo.prototype.resume = function () {\n if (this.persistentConnection_) {\n this.persistentConnection_.resume(INTERRUPT_REASON);\n }\n };\n Repo.prototype.stats = function (showDelta) {\n if (showDelta === void 0) { showDelta = false; }\n if (typeof console === 'undefined')\n return;\n var stats;\n if (showDelta) {\n if (!this.statsListener_)\n this.statsListener_ = new StatsListener_1.StatsListener(this.stats_);\n stats = this.statsListener_.get();\n }\n else {\n stats = this.stats_.get();\n }\n var longestName = Object.keys(stats).reduce(function (previousValue, currentValue) {\n return Math.max(currentValue.length, previousValue);\n }, 0);\n util_3.forEach(stats, function (stat, value) {\n // pad stat names to be the same length (plus 2 extra spaces).\n for (var i = stat.length; i < longestName + 2; i++)\n stat += ' ';\n console.log(stat + value);\n });\n };\n Repo.prototype.statsIncrementCounter = function (metric) {\n this.stats_.incrementCounter(metric);\n this.statsReporter_.includeStat(metric);\n };\n /**\n * @param {...*} var_args\n * @private\n */\n Repo.prototype.log_ = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var prefix = '';\n if (this.persistentConnection_) {\n prefix = this.persistentConnection_.id + ':';\n }\n util_2.log.apply(void 0, [prefix].concat(var_args));\n };\n /**\n * @param {?function(?Error, *=)} callback\n * @param {!string} status\n * @param {?string=} errorReason\n */\n Repo.prototype.callOnCompleteCallback = function (callback, status, errorReason) {\n if (callback) {\n util_2.exceptionGuard(function () {\n if (status == 'ok') {\n callback(null);\n }\n else {\n var code = (status || 'error').toUpperCase();\n var message = code;\n if (errorReason)\n message += ': ' + errorReason;\n var error = new Error(message);\n error.code = code;\n callback(error);\n }\n });\n }\n };\n Object.defineProperty(Repo.prototype, \"database\", {\n get: function () {\n return this.__database || (this.__database = new Database_1.Database(this));\n },\n enumerable: true,\n configurable: true\n });\n return Repo;\n}());\nexports.Repo = Repo;\n\n//# sourceMappingURL=Repo.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/Repo.js\n// module id = 19\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully\n * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.\n * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks\n * whether a node potentially had children removed due to a filter.\n */\nvar CacheNode = /** @class */ (function () {\n /**\n * @param {!Node} node_\n * @param {boolean} fullyInitialized_\n * @param {boolean} filtered_\n */\n function CacheNode(node_, fullyInitialized_, filtered_) {\n this.node_ = node_;\n this.fullyInitialized_ = fullyInitialized_;\n this.filtered_ = filtered_;\n }\n /**\n * Returns whether this node was fully initialized with either server data or a complete overwrite by the client\n * @return {boolean}\n */\n CacheNode.prototype.isFullyInitialized = function () {\n return this.fullyInitialized_;\n };\n /**\n * Returns whether this node is potentially missing children due to a filter applied to the node\n * @return {boolean}\n */\n CacheNode.prototype.isFiltered = function () {\n return this.filtered_;\n };\n /**\n * @param {!Path} path\n * @return {boolean}\n */\n CacheNode.prototype.isCompleteForPath = function (path) {\n if (path.isEmpty()) {\n return this.isFullyInitialized() && !this.filtered_;\n }\n var childKey = path.getFront();\n return this.isCompleteForChild(childKey);\n };\n /**\n * @param {!string} key\n * @return {boolean}\n */\n CacheNode.prototype.isCompleteForChild = function (key) {\n return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));\n };\n /**\n * @return {!Node}\n */\n CacheNode.prototype.getNode = function () {\n return this.node_;\n };\n return CacheNode;\n}());\nexports.CacheNode = CacheNode;\n\n//# sourceMappingURL=CacheNode.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/CacheNode.js\n// module id = 20\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar onDisconnect_1 = require(\"./onDisconnect\");\nvar TransactionResult_1 = require(\"./TransactionResult\");\nvar util_1 = require(\"../core/util/util\");\nvar NextPushId_1 = require(\"../core/util/NextPushId\");\nvar Query_1 = require(\"./Query\");\nvar Repo_1 = require(\"../core/Repo\");\nvar Path_1 = require(\"../core/util/Path\");\nvar QueryParams_1 = require(\"../core/view/QueryParams\");\nvar validation_1 = require(\"../core/util/validation\");\nvar util_2 = require(\"@firebase/util\");\nvar util_3 = require(\"@firebase/util\");\nvar SyncPoint_1 = require(\"../core/SyncPoint\");\nvar Reference = /** @class */ (function (_super) {\n tslib_1.__extends(Reference, _super);\n /**\n * Call options:\n * new Reference(Repo, Path) or\n * new Reference(url: string, string|RepoManager)\n *\n * Externally - this is the firebase.database.Reference type.\n *\n * @param {!Repo} repo\n * @param {(!Path)} path\n * @extends {Query}\n */\n function Reference(repo, path) {\n var _this = this;\n if (!(repo instanceof Repo_1.Repo)) {\n throw new Error('new Reference() no longer supported - use app.database().');\n }\n // call Query's constructor, passing in the repo and path.\n _this = _super.call(this, repo, path, QueryParams_1.QueryParams.DEFAULT, false) || this;\n return _this;\n }\n /** @return {?string} */\n Reference.prototype.getKey = function () {\n util_2.validateArgCount('Reference.key', 0, 0, arguments.length);\n if (this.path.isEmpty())\n return null;\n else\n return this.path.getBack();\n };\n /**\n * @param {!(string|Path)} pathString\n * @return {!Reference}\n */\n Reference.prototype.child = function (pathString) {\n util_2.validateArgCount('Reference.child', 1, 1, arguments.length);\n if (typeof pathString === 'number') {\n pathString = String(pathString);\n }\n else if (!(pathString instanceof Path_1.Path)) {\n if (this.path.getFront() === null)\n validation_1.validateRootPathString('Reference.child', 1, pathString, false);\n else\n validation_1.validatePathString('Reference.child', 1, pathString, false);\n }\n return new Reference(this.repo, this.path.child(pathString));\n };\n /** @return {?Reference} */\n Reference.prototype.getParent = function () {\n util_2.validateArgCount('Reference.parent', 0, 0, arguments.length);\n var parentPath = this.path.parent();\n return parentPath === null ? null : new Reference(this.repo, parentPath);\n };\n /** @return {!Reference} */\n Reference.prototype.getRoot = function () {\n util_2.validateArgCount('Reference.root', 0, 0, arguments.length);\n var ref = this;\n while (ref.getParent() !== null) {\n ref = ref.getParent();\n }\n return ref;\n };\n /** @return {!Database} */\n Reference.prototype.databaseProp = function () {\n return this.repo.database;\n };\n /**\n * @param {*} newVal\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.set = function (newVal, onComplete) {\n util_2.validateArgCount('Reference.set', 1, 2, arguments.length);\n validation_1.validateWritablePath('Reference.set', this.path);\n validation_1.validateFirebaseDataArg('Reference.set', 1, newVal, this.path, false);\n util_2.validateCallback('Reference.set', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo.setWithPriority(this.path, newVal, \n /*priority=*/ null, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {!Object} objectToMerge\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.update = function (objectToMerge, onComplete) {\n util_2.validateArgCount('Reference.update', 1, 2, arguments.length);\n validation_1.validateWritablePath('Reference.update', this.path);\n if (Array.isArray(objectToMerge)) {\n var newObjectToMerge = {};\n for (var i = 0; i < objectToMerge.length; ++i) {\n newObjectToMerge['' + i] = objectToMerge[i];\n }\n objectToMerge = newObjectToMerge;\n util_1.warn('Passing an Array to Firebase.update() is deprecated. ' +\n 'Use set() if you want to overwrite the existing data, or ' +\n 'an Object with integer keys if you really do want to ' +\n 'only update some of the children.');\n }\n validation_1.validateFirebaseMergeDataArg('Reference.update', 1, objectToMerge, this.path, false);\n util_2.validateCallback('Reference.update', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo.update(this.path, objectToMerge, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*} newVal\n * @param {string|number|null} newPriority\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.setWithPriority = function (newVal, newPriority, onComplete) {\n util_2.validateArgCount('Reference.setWithPriority', 2, 3, arguments.length);\n validation_1.validateWritablePath('Reference.setWithPriority', this.path);\n validation_1.validateFirebaseDataArg('Reference.setWithPriority', 1, newVal, this.path, false);\n validation_1.validatePriority('Reference.setWithPriority', 2, newPriority, false);\n util_2.validateCallback('Reference.setWithPriority', 3, onComplete, true);\n if (this.getKey() === '.length' || this.getKey() === '.keys')\n throw 'Reference.setWithPriority failed: ' +\n this.getKey() +\n ' is a read-only object.';\n var deferred = new util_3.Deferred();\n this.repo.setWithPriority(this.path, newVal, newPriority, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.remove = function (onComplete) {\n util_2.validateArgCount('Reference.remove', 0, 1, arguments.length);\n validation_1.validateWritablePath('Reference.remove', this.path);\n util_2.validateCallback('Reference.remove', 1, onComplete, true);\n return this.set(null, onComplete);\n };\n /**\n * @param {function(*):*} transactionUpdate\n * @param {(function(?Error, boolean, ?DataSnapshot))=} onComplete\n * @param {boolean=} applyLocally\n * @return {!Promise}\n */\n Reference.prototype.transaction = function (transactionUpdate, onComplete, applyLocally) {\n util_2.validateArgCount('Reference.transaction', 1, 3, arguments.length);\n validation_1.validateWritablePath('Reference.transaction', this.path);\n util_2.validateCallback('Reference.transaction', 1, transactionUpdate, false);\n util_2.validateCallback('Reference.transaction', 2, onComplete, true);\n // NOTE: applyLocally is an internal-only option for now. We need to decide if we want to keep it and how\n // to expose it.\n validation_1.validateBoolean('Reference.transaction', 3, applyLocally, true);\n if (this.getKey() === '.length' || this.getKey() === '.keys')\n throw 'Reference.transaction failed: ' +\n this.getKey() +\n ' is a read-only object.';\n if (applyLocally === undefined)\n applyLocally = true;\n var deferred = new util_3.Deferred();\n if (typeof onComplete === 'function') {\n deferred.promise.catch(function () { });\n }\n var promiseComplete = function (error, committed, snapshot) {\n if (error) {\n deferred.reject(error);\n }\n else {\n deferred.resolve(new TransactionResult_1.TransactionResult(committed, snapshot));\n }\n if (typeof onComplete === 'function') {\n onComplete(error, committed, snapshot);\n }\n };\n this.repo.startTransaction(this.path, transactionUpdate, promiseComplete, applyLocally);\n return deferred.promise;\n };\n /**\n * @param {string|number|null} priority\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.setPriority = function (priority, onComplete) {\n util_2.validateArgCount('Reference.setPriority', 1, 2, arguments.length);\n validation_1.validateWritablePath('Reference.setPriority', this.path);\n validation_1.validatePriority('Reference.setPriority', 1, priority, false);\n util_2.validateCallback('Reference.setPriority', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo.setWithPriority(this.path.child('.priority'), priority, null, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*=} value\n * @param {function(?Error)=} onComplete\n * @return {!Reference}\n */\n Reference.prototype.push = function (value, onComplete) {\n util_2.validateArgCount('Reference.push', 0, 2, arguments.length);\n validation_1.validateWritablePath('Reference.push', this.path);\n validation_1.validateFirebaseDataArg('Reference.push', 1, value, this.path, true);\n util_2.validateCallback('Reference.push', 2, onComplete, true);\n var now = this.repo.serverTime();\n var name = NextPushId_1.nextPushId(now);\n // push() returns a ThennableReference whose promise is fulfilled with a regular Reference.\n // We use child() to create handles to two different references. The first is turned into a\n // ThennableReference below by adding then() and catch() methods and is used as the\n // return value of push(). The second remains a regular Reference and is used as the fulfilled\n // value of the first ThennableReference.\n var thennablePushRef = this.child(name);\n var pushRef = this.child(name);\n var promise;\n if (value != null) {\n promise = thennablePushRef.set(value, onComplete).then(function () { return pushRef; });\n }\n else {\n promise = Promise.resolve(pushRef);\n }\n thennablePushRef.then = promise.then.bind(promise);\n thennablePushRef.catch = promise.then.bind(promise, undefined);\n if (typeof onComplete === 'function') {\n promise.catch(function () { });\n }\n return thennablePushRef;\n };\n /**\n * @return {!OnDisconnect}\n */\n Reference.prototype.onDisconnect = function () {\n validation_1.validateWritablePath('Reference.onDisconnect', this.path);\n return new onDisconnect_1.OnDisconnect(this.repo, this.path);\n };\n Object.defineProperty(Reference.prototype, \"database\", {\n get: function () {\n return this.databaseProp();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"key\", {\n get: function () {\n return this.getKey();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"parent\", {\n get: function () {\n return this.getParent();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"root\", {\n get: function () {\n return this.getRoot();\n },\n enumerable: true,\n configurable: true\n });\n return Reference;\n}(Query_1.Query));\nexports.Reference = Reference;\n/**\n * Define reference constructor in various modules\n *\n * We are doing this here to avoid several circular\n * dependency issues\n */\nQuery_1.Query.__referenceConstructor = Reference;\nSyncPoint_1.SyncPoint.__referenceConstructor = Reference;\n\n//# sourceMappingURL=Reference.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/Reference.js\n// module id = 22\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar validation_1 = require(\"../core/util/validation\");\nvar Path_1 = require(\"../core/util/Path\");\nvar PriorityIndex_1 = require(\"../core/snap/indexes/PriorityIndex\");\n/**\n * Class representing a firebase data snapshot. It wraps a SnapshotNode and\n * surfaces the public methods (val, forEach, etc.) we want to expose.\n */\nvar DataSnapshot = /** @class */ (function () {\n /**\n * @param {!Node} node_ A SnapshotNode to wrap.\n * @param {!Reference} ref_ The ref of the location this snapshot came from.\n * @param {!Index} index_ The iteration order for this snapshot\n */\n function DataSnapshot(node_, ref_, index_) {\n this.node_ = node_;\n this.ref_ = ref_;\n this.index_ = index_;\n }\n /**\n * Retrieves the snapshot contents as JSON. Returns null if the snapshot is\n * empty.\n *\n * @return {*} JSON representation of the DataSnapshot contents, or null if empty.\n */\n DataSnapshot.prototype.val = function () {\n util_1.validateArgCount('DataSnapshot.val', 0, 0, arguments.length);\n return this.node_.val();\n };\n /**\n * Returns the snapshot contents as JSON, including priorities of node. Suitable for exporting\n * the entire node contents.\n * @return {*} JSON representation of the DataSnapshot contents, or null if empty.\n */\n DataSnapshot.prototype.exportVal = function () {\n util_1.validateArgCount('DataSnapshot.exportVal', 0, 0, arguments.length);\n return this.node_.val(true);\n };\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n DataSnapshot.prototype.toJSON = function () {\n // Optional spacer argument is unnecessary because we're depending on recursion rather than stringifying the content\n util_1.validateArgCount('DataSnapshot.toJSON', 0, 1, arguments.length);\n return this.exportVal();\n };\n /**\n * Returns whether the snapshot contains a non-null value.\n *\n * @return {boolean} Whether the snapshot contains a non-null value, or is empty.\n */\n DataSnapshot.prototype.exists = function () {\n util_1.validateArgCount('DataSnapshot.exists', 0, 0, arguments.length);\n return !this.node_.isEmpty();\n };\n /**\n * Returns a DataSnapshot of the specified child node's contents.\n *\n * @param {!string} childPathString Path to a child.\n * @return {!DataSnapshot} DataSnapshot for child node.\n */\n DataSnapshot.prototype.child = function (childPathString) {\n util_1.validateArgCount('DataSnapshot.child', 0, 1, arguments.length);\n // Ensure the childPath is a string (can be a number)\n childPathString = String(childPathString);\n validation_1.validatePathString('DataSnapshot.child', 1, childPathString, false);\n var childPath = new Path_1.Path(childPathString);\n var childRef = this.ref_.child(childPath);\n return new DataSnapshot(this.node_.getChild(childPath), childRef, PriorityIndex_1.PRIORITY_INDEX);\n };\n /**\n * Returns whether the snapshot contains a child at the specified path.\n *\n * @param {!string} childPathString Path to a child.\n * @return {boolean} Whether the child exists.\n */\n DataSnapshot.prototype.hasChild = function (childPathString) {\n util_1.validateArgCount('DataSnapshot.hasChild', 1, 1, arguments.length);\n validation_1.validatePathString('DataSnapshot.hasChild', 1, childPathString, false);\n var childPath = new Path_1.Path(childPathString);\n return !this.node_.getChild(childPath).isEmpty();\n };\n /**\n * Returns the priority of the object, or null if no priority was set.\n *\n * @return {string|number|null} The priority.\n */\n DataSnapshot.prototype.getPriority = function () {\n util_1.validateArgCount('DataSnapshot.getPriority', 0, 0, arguments.length);\n // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)\n return this.node_.getPriority().val();\n };\n /**\n * Iterates through child nodes and calls the specified action for each one.\n *\n * @param {function(!DataSnapshot)} action Callback function to be called\n * for each child.\n * @return {boolean} True if forEach was canceled by action returning true for\n * one of the child nodes.\n */\n DataSnapshot.prototype.forEach = function (action) {\n var _this = this;\n util_1.validateArgCount('DataSnapshot.forEach', 1, 1, arguments.length);\n util_1.validateCallback('DataSnapshot.forEach', 1, action, false);\n if (this.node_.isLeafNode())\n return false;\n var childrenNode = this.node_;\n // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...\n return !!childrenNode.forEachChild(this.index_, function (key, node) {\n return action(new DataSnapshot(node, _this.ref_.child(key), PriorityIndex_1.PRIORITY_INDEX));\n });\n };\n /**\n * Returns whether this DataSnapshot has children.\n * @return {boolean} True if the DataSnapshot contains 1 or more child nodes.\n */\n DataSnapshot.prototype.hasChildren = function () {\n util_1.validateArgCount('DataSnapshot.hasChildren', 0, 0, arguments.length);\n if (this.node_.isLeafNode())\n return false;\n else\n return !this.node_.isEmpty();\n };\n Object.defineProperty(DataSnapshot.prototype, \"key\", {\n get: function () {\n return this.ref_.getKey();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the number of children for this DataSnapshot.\n * @return {number} The number of children that this DataSnapshot contains.\n */\n DataSnapshot.prototype.numChildren = function () {\n util_1.validateArgCount('DataSnapshot.numChildren', 0, 0, arguments.length);\n return this.node_.numChildren();\n };\n /**\n * @return {Reference} The Firebase reference for the location this snapshot's data came from.\n */\n DataSnapshot.prototype.getRef = function () {\n util_1.validateArgCount('DataSnapshot.ref', 0, 0, arguments.length);\n return this.ref_;\n };\n Object.defineProperty(DataSnapshot.prototype, \"ref\", {\n get: function () {\n return this.getRef();\n },\n enumerable: true,\n configurable: true\n });\n return DataSnapshot;\n}());\nexports.DataSnapshot = DataSnapshot;\n\n//# sourceMappingURL=DataSnapshot.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/DataSnapshot.js\n// module id = 23\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar SortedMap_1 = require(\"./SortedMap\");\nvar Path_1 = require(\"./Path\");\nvar util_1 = require(\"./util\");\nvar util_2 = require(\"@firebase/util\");\nvar emptyChildrenSingleton;\n/**\n * Singleton empty children collection.\n *\n * @const\n * @type {!SortedMap.>}\n */\nvar EmptyChildren = function () {\n if (!emptyChildrenSingleton) {\n emptyChildrenSingleton = new SortedMap_1.SortedMap(util_1.stringCompare);\n }\n return emptyChildrenSingleton;\n};\n/**\n * A tree with immutable elements.\n */\nvar ImmutableTree = /** @class */ (function () {\n /**\n * @template T\n * @param {?T} value\n * @param {SortedMap.>=} children\n */\n function ImmutableTree(value, children) {\n if (children === void 0) { children = EmptyChildren(); }\n this.value = value;\n this.children = children;\n }\n /**\n * @template T\n * @param {!Object.} obj\n * @return {!ImmutableTree.}\n */\n ImmutableTree.fromObject = function (obj) {\n var tree = ImmutableTree.Empty;\n util_2.forEach(obj, function (childPath, childSnap) {\n tree = tree.set(new Path_1.Path(childPath), childSnap);\n });\n return tree;\n };\n /**\n * True if the value is empty and there are no children\n * @return {boolean}\n */\n ImmutableTree.prototype.isEmpty = function () {\n return this.value === null && this.children.isEmpty();\n };\n /**\n * Given a path and predicate, return the first node and the path to that node\n * where the predicate returns true.\n *\n * TODO Do a perf test -- If we're creating a bunch of {path: value:} objects\n * on the way back out, it may be better to pass down a pathSoFar obj.\n *\n * @param {!Path} relativePath The remainder of the path\n * @param {function(T):boolean} predicate The predicate to satisfy to return a\n * node\n * @return {?{path:!Path, value:!T}}\n */\n ImmutableTree.prototype.findRootMostMatchingPathAndValue = function (relativePath, predicate) {\n if (this.value != null && predicate(this.value)) {\n return { path: Path_1.Path.Empty, value: this.value };\n }\n else {\n if (relativePath.isEmpty()) {\n return null;\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front);\n if (child !== null) {\n var childExistingPathAndValue = child.findRootMostMatchingPathAndValue(relativePath.popFront(), predicate);\n if (childExistingPathAndValue != null) {\n var fullPath = new Path_1.Path(front).child(childExistingPathAndValue.path);\n return { path: fullPath, value: childExistingPathAndValue.value };\n }\n else {\n return null;\n }\n }\n else {\n return null;\n }\n }\n }\n };\n /**\n * Find, if it exists, the shortest subpath of the given path that points a defined\n * value in the tree\n * @param {!Path} relativePath\n * @return {?{path: !Path, value: !T}}\n */\n ImmutableTree.prototype.findRootMostValueAndPath = function (relativePath) {\n return this.findRootMostMatchingPathAndValue(relativePath, function () { return true; });\n };\n /**\n * @param {!Path} relativePath\n * @return {!ImmutableTree.} The subtree at the given path\n */\n ImmutableTree.prototype.subtree = function (relativePath) {\n if (relativePath.isEmpty()) {\n return this;\n }\n else {\n var front = relativePath.getFront();\n var childTree = this.children.get(front);\n if (childTree !== null) {\n return childTree.subtree(relativePath.popFront());\n }\n else {\n return ImmutableTree.Empty;\n }\n }\n };\n /**\n * Sets a value at the specified path.\n *\n * @param {!Path} relativePath Path to set value at.\n * @param {?T} toSet Value to set.\n * @return {!ImmutableTree.} Resulting tree.\n */\n ImmutableTree.prototype.set = function (relativePath, toSet) {\n if (relativePath.isEmpty()) {\n return new ImmutableTree(toSet, this.children);\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front) || ImmutableTree.Empty;\n var newChild = child.set(relativePath.popFront(), toSet);\n var newChildren = this.children.insert(front, newChild);\n return new ImmutableTree(this.value, newChildren);\n }\n };\n /**\n * Removes the value at the specified path.\n *\n * @param {!Path} relativePath Path to value to remove.\n * @return {!ImmutableTree.} Resulting tree.\n */\n ImmutableTree.prototype.remove = function (relativePath) {\n if (relativePath.isEmpty()) {\n if (this.children.isEmpty()) {\n return ImmutableTree.Empty;\n }\n else {\n return new ImmutableTree(null, this.children);\n }\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front);\n if (child) {\n var newChild = child.remove(relativePath.popFront());\n var newChildren = void 0;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n }\n else {\n newChildren = this.children.insert(front, newChild);\n }\n if (this.value === null && newChildren.isEmpty()) {\n return ImmutableTree.Empty;\n }\n else {\n return new ImmutableTree(this.value, newChildren);\n }\n }\n else {\n return this;\n }\n }\n };\n /**\n * Gets a value from the tree.\n *\n * @param {!Path} relativePath Path to get value for.\n * @return {?T} Value at path, or null.\n */\n ImmutableTree.prototype.get = function (relativePath) {\n if (relativePath.isEmpty()) {\n return this.value;\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front);\n if (child) {\n return child.get(relativePath.popFront());\n }\n else {\n return null;\n }\n }\n };\n /**\n * Replace the subtree at the specified path with the given new tree.\n *\n * @param {!Path} relativePath Path to replace subtree for.\n * @param {!ImmutableTree} newTree New tree.\n * @return {!ImmutableTree} Resulting tree.\n */\n ImmutableTree.prototype.setTree = function (relativePath, newTree) {\n if (relativePath.isEmpty()) {\n return newTree;\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front) || ImmutableTree.Empty;\n var newChild = child.setTree(relativePath.popFront(), newTree);\n var newChildren = void 0;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n }\n else {\n newChildren = this.children.insert(front, newChild);\n }\n return new ImmutableTree(this.value, newChildren);\n }\n };\n /**\n * Performs a depth first fold on this tree. Transforms a tree into a single\n * value, given a function that operates on the path to a node, an optional\n * current value, and a map of child names to folded subtrees\n * @template V\n * @param {function(Path, ?T, Object.):V} fn\n * @return {V}\n */\n ImmutableTree.prototype.fold = function (fn) {\n return this.fold_(Path_1.Path.Empty, fn);\n };\n /**\n * Recursive helper for public-facing fold() method\n * @template V\n * @param {!Path} pathSoFar\n * @param {function(Path, ?T, Object.):V} fn\n * @return {V}\n * @private\n */\n ImmutableTree.prototype.fold_ = function (pathSoFar, fn) {\n var accum = {};\n this.children.inorderTraversal(function (childKey, childTree) {\n accum[childKey] = childTree.fold_(pathSoFar.child(childKey), fn);\n });\n return fn(pathSoFar, this.value, accum);\n };\n /**\n * Find the first matching value on the given path. Return the result of applying f to it.\n * @template V\n * @param {!Path} path\n * @param {!function(!Path, !T):?V} f\n * @return {?V}\n */\n ImmutableTree.prototype.findOnPath = function (path, f) {\n return this.findOnPath_(path, Path_1.Path.Empty, f);\n };\n ImmutableTree.prototype.findOnPath_ = function (pathToFollow, pathSoFar, f) {\n var result = this.value ? f(pathSoFar, this.value) : false;\n if (result) {\n return result;\n }\n else {\n if (pathToFollow.isEmpty()) {\n return null;\n }\n else {\n var front = pathToFollow.getFront();\n var nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.findOnPath_(pathToFollow.popFront(), pathSoFar.child(front), f);\n }\n else {\n return null;\n }\n }\n }\n };\n /**\n *\n * @param {!Path} path\n * @param {!function(!Path, !T)} f\n * @returns {!ImmutableTree.}\n */\n ImmutableTree.prototype.foreachOnPath = function (path, f) {\n return this.foreachOnPath_(path, Path_1.Path.Empty, f);\n };\n ImmutableTree.prototype.foreachOnPath_ = function (pathToFollow, currentRelativePath, f) {\n if (pathToFollow.isEmpty()) {\n return this;\n }\n else {\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n var front = pathToFollow.getFront();\n var nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.foreachOnPath_(pathToFollow.popFront(), currentRelativePath.child(front), f);\n }\n else {\n return ImmutableTree.Empty;\n }\n }\n };\n /**\n * Calls the given function for each node in the tree that has a value.\n *\n * @param {function(!Path, !T)} f A function to be called with\n * the path from the root of the tree to a node, and the value at that node.\n * Called in depth-first order.\n */\n ImmutableTree.prototype.foreach = function (f) {\n this.foreach_(Path_1.Path.Empty, f);\n };\n ImmutableTree.prototype.foreach_ = function (currentRelativePath, f) {\n this.children.inorderTraversal(function (childName, childTree) {\n childTree.foreach_(currentRelativePath.child(childName), f);\n });\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n };\n /**\n *\n * @param {function(string, !T)} f\n */\n ImmutableTree.prototype.foreachChild = function (f) {\n this.children.inorderTraversal(function (childName, childTree) {\n if (childTree.value) {\n f(childName, childTree.value);\n }\n });\n };\n ImmutableTree.Empty = new ImmutableTree(null);\n return ImmutableTree;\n}());\nexports.ImmutableTree = ImmutableTree;\n\n//# sourceMappingURL=ImmutableTree.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/ImmutableTree.js\n// module id = 24\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Change_1 = require(\"../Change\");\nvar ChildrenNode_1 = require(\"../../snap/ChildrenNode\");\nvar PriorityIndex_1 = require(\"../../snap/indexes/PriorityIndex\");\n/**\n * Doesn't really filter nodes but applies an index to the node and keeps track of any changes\n *\n * @constructor\n * @implements {NodeFilter}\n * @param {!Index} index\n */\nvar IndexedFilter = /** @class */ (function () {\n function IndexedFilter(index_) {\n this.index_ = index_;\n }\n IndexedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n util_1.assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');\n var oldChild = snap.getImmediateChild(key);\n // Check if anything actually changed.\n if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {\n // There's an edge case where a child can enter or leave the view because affectedPath was set to null.\n // In this case, affectedPath will appear null in both the old and new snapshots. So we need\n // to avoid treating these cases as \"nothing changed.\"\n if (oldChild.isEmpty() == newChild.isEmpty()) {\n // Nothing changed.\n // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.\n //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');\n return snap;\n }\n }\n if (optChangeAccumulator != null) {\n if (newChild.isEmpty()) {\n if (snap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(key, oldChild));\n }\n else {\n util_1.assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');\n }\n }\n else if (oldChild.isEmpty()) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childAddedChange(key, newChild));\n }\n else {\n optChangeAccumulator.trackChildChange(Change_1.Change.childChangedChange(key, newChild, oldChild));\n }\n }\n if (snap.isLeafNode() && newChild.isEmpty()) {\n return snap;\n }\n else {\n // Make sure the node is indexed\n return snap.updateImmediateChild(key, newChild).withIndex(this.index_);\n }\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n if (optChangeAccumulator != null) {\n if (!oldSnap.isLeafNode()) {\n oldSnap.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n if (!newSnap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(key, childNode));\n }\n });\n }\n if (!newSnap.isLeafNode()) {\n newSnap.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n if (oldSnap.hasChild(key)) {\n var oldChild = oldSnap.getImmediateChild(key);\n if (!oldChild.equals(childNode)) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childChangedChange(key, childNode, oldChild));\n }\n }\n else {\n optChangeAccumulator.trackChildChange(Change_1.Change.childAddedChange(key, childNode));\n }\n });\n }\n }\n return newSnap.withIndex(this.index_);\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n if (oldSnap.isEmpty()) {\n return ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n else {\n return oldSnap.updatePriority(newPriority);\n }\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.filtersNodes = function () {\n return false;\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.getIndexedFilter = function () {\n return this;\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n return IndexedFilter;\n}());\nexports.IndexedFilter = IndexedFilter;\n\n//# sourceMappingURL=IndexedFilter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/filter/IndexedFilter.js\n// module id = 25\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar StatsCollection_1 = require(\"./StatsCollection\");\nvar StatsManager = /** @class */ (function () {\n function StatsManager() {\n }\n StatsManager.getCollection = function (repoInfo) {\n var hashString = repoInfo.toString();\n if (!this.collections_[hashString]) {\n this.collections_[hashString] = new StatsCollection_1.StatsCollection();\n }\n return this.collections_[hashString];\n };\n StatsManager.getOrCreateReporter = function (repoInfo, creatorFunction) {\n var hashString = repoInfo.toString();\n if (!this.reporters_[hashString]) {\n this.reporters_[hashString] = creatorFunction();\n }\n return this.reporters_[hashString];\n };\n StatsManager.collections_ = {};\n StatsManager.reporters_ = {};\n return StatsManager;\n}());\nexports.StatsManager = StatsManager;\n\n//# sourceMappingURL=StatsManager.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/stats/StatsManager.js\n// module id = 26\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Repo_1 = require(\"./Repo\");\nvar util_2 = require(\"./util/util\");\nvar parser_1 = require(\"./util/libs/parser\");\nvar validation_1 = require(\"./util/validation\");\nrequire(\"./Repo_transaction\");\n/** @const {string} */\nvar DATABASE_URL_OPTION = 'databaseURL';\nvar _staticInstance;\n/**\n * Creates and caches Repo instances.\n */\nvar RepoManager = /** @class */ (function () {\n function RepoManager() {\n /**\n * @private {!Object.>}\n */\n this.repos_ = {};\n /**\n * If true, new Repos will be created to use ReadonlyRestClient (for testing purposes).\n * @private {boolean}\n */\n this.useRestClient_ = false;\n }\n RepoManager.getInstance = function () {\n if (!_staticInstance) {\n _staticInstance = new RepoManager();\n }\n return _staticInstance;\n };\n // TODO(koss): Remove these functions unless used in tests?\n RepoManager.prototype.interrupt = function () {\n for (var appName in this.repos_) {\n for (var dbUrl in this.repos_[appName]) {\n this.repos_[appName][dbUrl].interrupt();\n }\n }\n };\n RepoManager.prototype.resume = function () {\n for (var appName in this.repos_) {\n for (var dbUrl in this.repos_[appName]) {\n this.repos_[appName][dbUrl].resume();\n }\n }\n };\n /**\n * This function should only ever be called to CREATE a new database instance.\n *\n * @param {!FirebaseApp} app\n * @return {!Database}\n */\n RepoManager.prototype.databaseFromApp = function (app, url) {\n var dbUrl = url || app.options[DATABASE_URL_OPTION];\n if (dbUrl === undefined) {\n util_2.fatal(\"Can't determine Firebase Database URL. Be sure to include \" +\n DATABASE_URL_OPTION +\n ' option when calling firebase.initializeApp().');\n }\n var parsedUrl = parser_1.parseRepoInfo(dbUrl);\n var repoInfo = parsedUrl.repoInfo;\n validation_1.validateUrl('Invalid Firebase Database URL', 1, parsedUrl);\n if (!parsedUrl.path.isEmpty()) {\n util_2.fatal('Database URL must point to the root of a Firebase Database ' +\n '(not including a child path).');\n }\n var repo = this.createRepo(repoInfo, app);\n return repo.database;\n };\n /**\n * Remove the repo and make sure it is disconnected.\n *\n * @param {!Repo} repo\n */\n RepoManager.prototype.deleteRepo = function (repo) {\n var appRepos = util_1.safeGet(this.repos_, repo.app.name);\n // This should never happen...\n if (!appRepos || util_1.safeGet(appRepos, repo.repoInfo_.toURLString()) !== repo) {\n util_2.fatal(\"Database \" + repo.app.name + \"(\" + repo.repoInfo_ + \") has already been deleted.\");\n }\n repo.interrupt();\n delete appRepos[repo.repoInfo_.toURLString()];\n };\n /**\n * Ensures a repo doesn't already exist and then creates one using the\n * provided app.\n *\n * @param {!RepoInfo} repoInfo The metadata about the Repo\n * @param {!FirebaseApp} app\n * @return {!Repo} The Repo object for the specified server / repoName.\n */\n RepoManager.prototype.createRepo = function (repoInfo, app) {\n var appRepos = util_1.safeGet(this.repos_, app.name);\n if (!appRepos) {\n appRepos = {};\n this.repos_[app.name] = appRepos;\n }\n var repo = util_1.safeGet(appRepos, repoInfo.toURLString());\n if (repo) {\n util_2.fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');\n }\n repo = new Repo_1.Repo(repoInfo, this.useRestClient_, app);\n appRepos[repoInfo.toURLString()] = repo;\n return repo;\n };\n /**\n * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.\n * @param {boolean} forceRestClient\n */\n RepoManager.prototype.forceRestClient = function (forceRestClient) {\n this.useRestClient_ = forceRestClient;\n };\n return RepoManager;\n}());\nexports.RepoManager = RepoManager;\n\n//# sourceMappingURL=RepoManager.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/RepoManager.js\n// module id = 27\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar util_1 = require(\"../core/util/util\");\nvar parser_1 = require(\"../core/util/libs/parser\");\nvar Path_1 = require(\"../core/util/Path\");\nvar Reference_1 = require(\"./Reference\");\nvar Repo_1 = require(\"../core/Repo\");\nvar RepoManager_1 = require(\"../core/RepoManager\");\nvar util_2 = require(\"@firebase/util\");\nvar validation_1 = require(\"../core/util/validation\");\n/**\n * Class representing a firebase database.\n * @implements {FirebaseService}\n */\nvar Database = /** @class */ (function () {\n /**\n * The constructor should not be called by users of our public API.\n * @param {!Repo} repo_\n */\n function Database(repo_) {\n this.repo_ = repo_;\n if (!(repo_ instanceof Repo_1.Repo)) {\n util_1.fatal(\"Don't call new Database() directly - please use firebase.database().\");\n }\n /** @type {Reference} */\n this.root_ = new Reference_1.Reference(repo_, Path_1.Path.Empty);\n this.INTERNAL = new DatabaseInternals(this);\n }\n Object.defineProperty(Database.prototype, \"app\", {\n get: function () {\n return this.repo_.app;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns a reference to the root or the path specified in opt_pathString.\n * @param {string=} pathString\n * @return {!Reference} Firebase reference.\n */\n Database.prototype.ref = function (pathString) {\n this.checkDeleted_('ref');\n util_2.validateArgCount('database.ref', 0, 1, arguments.length);\n return pathString !== undefined ? this.root_.child(pathString) : this.root_;\n };\n /**\n * Returns a reference to the root or the path specified in url.\n * We throw a exception if the url is not in the same domain as the\n * current repo.\n * @param {string} url\n * @return {!Reference} Firebase reference.\n */\n Database.prototype.refFromURL = function (url) {\n /** @const {string} */\n var apiName = 'database.refFromURL';\n this.checkDeleted_(apiName);\n util_2.validateArgCount(apiName, 1, 1, arguments.length);\n var parsedURL = parser_1.parseRepoInfo(url);\n validation_1.validateUrl(apiName, 1, parsedURL);\n var repoInfo = parsedURL.repoInfo;\n if (repoInfo.host !== this.repo_.repoInfo_.host) {\n util_1.fatal(apiName +\n ': Host name does not match the current database: ' +\n '(found ' +\n repoInfo.host +\n ' but expected ' +\n this.repo_.repoInfo_.host +\n ')');\n }\n return this.ref(parsedURL.path.toString());\n };\n /**\n * @param {string} apiName\n */\n Database.prototype.checkDeleted_ = function (apiName) {\n if (this.repo_ === null) {\n util_1.fatal('Cannot call ' + apiName + ' on a deleted database.');\n }\n };\n // Make individual repo go offline.\n Database.prototype.goOffline = function () {\n util_2.validateArgCount('database.goOffline', 0, 0, arguments.length);\n this.checkDeleted_('goOffline');\n this.repo_.interrupt();\n };\n Database.prototype.goOnline = function () {\n util_2.validateArgCount('database.goOnline', 0, 0, arguments.length);\n this.checkDeleted_('goOnline');\n this.repo_.resume();\n };\n Database.ServerValue = {\n TIMESTAMP: {\n '.sv': 'timestamp'\n }\n };\n return Database;\n}());\nexports.Database = Database;\nvar DatabaseInternals = /** @class */ (function () {\n /** @param {!Database} database */\n function DatabaseInternals(database) {\n this.database = database;\n }\n /** @return {Promise} */\n DatabaseInternals.prototype.delete = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n this.database.checkDeleted_('delete');\n RepoManager_1.RepoManager.getInstance().deleteRepo(this.database.repo_);\n this.database.repo_ = null;\n this.database.root_ = null;\n this.database.INTERNAL = null;\n this.database = null;\n return [2 /*return*/];\n });\n });\n };\n return DatabaseInternals;\n}());\nexports.DatabaseInternals = DatabaseInternals;\n\n//# sourceMappingURL=Database.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/Database.js\n// module id = 33\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = require(\"../Path\");\nvar RepoInfo_1 = require(\"../../RepoInfo\");\nvar util_1 = require(\"../util\");\n/**\n * @param {!string} pathString\n * @return {string}\n */\nfunction decodePath(pathString) {\n var pathStringDecoded = '';\n var pieces = pathString.split('/');\n for (var i = 0; i < pieces.length; i++) {\n if (pieces[i].length > 0) {\n var piece = pieces[i];\n try {\n piece = decodeURIComponent(piece.replace(/\\+/g, ' '));\n }\n catch (e) { }\n pathStringDecoded += '/' + piece;\n }\n }\n return pathStringDecoded;\n}\n/**\n * @param {!string} queryString\n * @return {!{[key:string]:string}} key value hash\n */\nfunction decodeQuery(queryString) {\n var results = {};\n if (queryString.startsWith('?')) {\n queryString = queryString.substring(1);\n }\n for (var _i = 0, _a = queryString.split('&'); _i < _a.length; _i++) {\n var segment = _a[_i];\n if (segment.length === 0) {\n continue;\n }\n var kv = segment.split('=');\n if (kv.length === 2) {\n results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);\n }\n else {\n util_1.warn(\"Invalid query segment '\" + segment + \"' in query '\" + queryString + \"'\");\n }\n }\n return results;\n}\n/**\n *\n * @param {!string} dataURL\n * @return {{repoInfo: !RepoInfo, path: !Path}}\n */\nexports.parseRepoInfo = function (dataURL) {\n var parsedUrl = exports.parseURL(dataURL), namespace = parsedUrl.subdomain;\n if (parsedUrl.domain === 'firebase') {\n util_1.fatal(parsedUrl.host +\n ' is no longer supported. ' +\n 'Please use .firebaseio.com instead');\n }\n // Catch common error of uninitialized namespace value.\n if ((!namespace || namespace == 'undefined') &&\n parsedUrl.domain !== 'localhost') {\n util_1.fatal('Cannot parse Firebase url. Please use https://.firebaseio.com');\n }\n if (!parsedUrl.secure) {\n util_1.warnIfPageIsSecure();\n }\n var webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';\n return {\n repoInfo: new RepoInfo_1.RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly),\n path: new Path_1.Path(parsedUrl.pathString)\n };\n};\n/**\n *\n * @param {!string} dataURL\n * @return {{host: string, port: number, domain: string, subdomain: string, secure: boolean, scheme: string, pathString: string}}\n */\nexports.parseURL = function (dataURL) {\n // Default to empty strings in the event of a malformed string.\n var host = '', domain = '', subdomain = '', pathString = '';\n // Always default to SSL, unless otherwise specified.\n var secure = true, scheme = 'https', port = 443;\n // Don't do any validation here. The caller is responsible for validating the result of parsing.\n if (typeof dataURL === 'string') {\n // Parse scheme.\n var colonInd = dataURL.indexOf('//');\n if (colonInd >= 0) {\n scheme = dataURL.substring(0, colonInd - 1);\n dataURL = dataURL.substring(colonInd + 2);\n }\n // Parse host, path, and query string.\n var slashInd = dataURL.indexOf('/');\n if (slashInd === -1) {\n slashInd = dataURL.length;\n }\n var questionMarkInd = dataURL.indexOf('?');\n if (questionMarkInd === -1) {\n questionMarkInd = dataURL.length;\n }\n host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));\n if (slashInd < questionMarkInd) {\n // For pathString, questionMarkInd will always come after slashInd\n pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));\n }\n var queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));\n // If we have a port, use scheme for determining if it's secure.\n colonInd = host.indexOf(':');\n if (colonInd >= 0) {\n secure = scheme === 'https' || scheme === 'wss';\n port = parseInt(host.substring(colonInd + 1), 10);\n }\n else {\n colonInd = dataURL.length;\n }\n var parts = host.split('.');\n if (parts.length === 3) {\n // Normalize namespaces to lowercase to share storage / connection.\n domain = parts[1];\n subdomain = parts[0].toLowerCase();\n }\n else if (parts.length === 2) {\n domain = parts[0];\n }\n else if (parts[0].slice(0, colonInd).toLowerCase() === 'localhost') {\n domain = 'localhost';\n }\n // Support `ns` query param if subdomain not already set\n if (subdomain === '' && 'ns' in queryParams) {\n subdomain = queryParams['ns'];\n }\n }\n return {\n host: host,\n port: port,\n domain: domain,\n subdomain: subdomain,\n secure: secure,\n scheme: scheme,\n pathString: pathString\n };\n};\n\n//# sourceMappingURL=parser.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/libs/parser.js\n// module id = 34\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar storage_1 = require(\"./storage/storage\");\nvar Constants_1 = require(\"../realtime/Constants\");\n/**\n * A class that holds metadata about a Repo object\n *\n * @constructor\n */\nvar RepoInfo = /** @class */ (function () {\n /**\n * @param {string} host Hostname portion of the url for the repo\n * @param {boolean} secure Whether or not this repo is accessed over ssl\n * @param {string} namespace The namespace represented by the repo\n * @param {boolean} webSocketOnly Whether to prefer websockets over all other transports (used by Nest).\n * @param {string=} persistenceKey Override the default session persistence storage key\n */\n function RepoInfo(host, secure, namespace, webSocketOnly, persistenceKey) {\n if (persistenceKey === void 0) { persistenceKey = ''; }\n this.secure = secure;\n this.namespace = namespace;\n this.webSocketOnly = webSocketOnly;\n this.persistenceKey = persistenceKey;\n this.host = host.toLowerCase();\n this.domain = this.host.substr(this.host.indexOf('.') + 1);\n this.internalHost = storage_1.PersistentStorage.get('host:' + host) || this.host;\n }\n RepoInfo.prototype.needsQueryParam = function () {\n return this.host !== this.internalHost || this.isCustomHost();\n };\n RepoInfo.prototype.isCacheableHost = function () {\n return this.internalHost.substr(0, 2) === 's-';\n };\n RepoInfo.prototype.isDemoHost = function () {\n return this.domain === 'firebaseio-demo.com';\n };\n RepoInfo.prototype.isCustomHost = function () {\n return (this.domain !== 'firebaseio.com' && this.domain !== 'firebaseio-demo.com');\n };\n RepoInfo.prototype.updateHost = function (newHost) {\n if (newHost !== this.internalHost) {\n this.internalHost = newHost;\n if (this.isCacheableHost()) {\n storage_1.PersistentStorage.set('host:' + this.host, this.internalHost);\n }\n }\n };\n /**\n * Returns the websocket URL for this repo\n * @param {string} type of connection\n * @param {Object} params list\n * @return {string} The URL for this repo\n */\n RepoInfo.prototype.connectionURL = function (type, params) {\n util_1.assert(typeof type === 'string', 'typeof type must == string');\n util_1.assert(typeof params === 'object', 'typeof params must == object');\n var connURL;\n if (type === Constants_1.WEBSOCKET) {\n connURL =\n (this.secure ? 'wss://' : 'ws://') + this.internalHost + '/.ws?';\n }\n else if (type === Constants_1.LONG_POLLING) {\n connURL =\n (this.secure ? 'https://' : 'http://') + this.internalHost + '/.lp?';\n }\n else {\n throw new Error('Unknown connection type: ' + type);\n }\n if (this.needsQueryParam()) {\n params['ns'] = this.namespace;\n }\n var pairs = [];\n util_2.forEach(params, function (key, value) {\n pairs.push(key + '=' + value);\n });\n return connURL + pairs.join('&');\n };\n /** @return {string} */\n RepoInfo.prototype.toString = function () {\n var str = this.toURLString();\n if (this.persistenceKey) {\n str += '<' + this.persistenceKey + '>';\n }\n return str;\n };\n /** @return {string} */\n RepoInfo.prototype.toURLString = function () {\n return (this.secure ? 'https://' : 'http://') + this.host;\n };\n return RepoInfo;\n}());\nexports.RepoInfo = RepoInfo;\n\n//# sourceMappingURL=RepoInfo.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/RepoInfo.js\n// module id = 35\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar validation_1 = require(\"../core/util/validation\");\nvar util_2 = require(\"../core/util/util\");\nvar util_3 = require(\"@firebase/util\");\n/**\n * @constructor\n */\nvar OnDisconnect = /** @class */ (function () {\n /**\n * @param {!Repo} repo_\n * @param {!Path} path_\n */\n function OnDisconnect(repo_, path_) {\n this.repo_ = repo_;\n this.path_ = path_;\n }\n /**\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.cancel = function (onComplete) {\n util_1.validateArgCount('OnDisconnect.cancel', 0, 1, arguments.length);\n util_1.validateCallback('OnDisconnect.cancel', 1, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectCancel(this.path_, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.remove = function (onComplete) {\n util_1.validateArgCount('OnDisconnect.remove', 0, 1, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.remove', this.path_);\n util_1.validateCallback('OnDisconnect.remove', 1, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectSet(this.path_, null, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*} value\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.set = function (value, onComplete) {\n util_1.validateArgCount('OnDisconnect.set', 1, 2, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.set', this.path_);\n validation_1.validateFirebaseDataArg('OnDisconnect.set', 1, value, this.path_, false);\n util_1.validateCallback('OnDisconnect.set', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectSet(this.path_, value, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*} value\n * @param {number|string|null} priority\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.setWithPriority = function (value, priority, onComplete) {\n util_1.validateArgCount('OnDisconnect.setWithPriority', 2, 3, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.setWithPriority', this.path_);\n validation_1.validateFirebaseDataArg('OnDisconnect.setWithPriority', 1, value, this.path_, false);\n validation_1.validatePriority('OnDisconnect.setWithPriority', 2, priority, false);\n util_1.validateCallback('OnDisconnect.setWithPriority', 3, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectSetWithPriority(this.path_, value, priority, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {!Object} objectToMerge\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.update = function (objectToMerge, onComplete) {\n util_1.validateArgCount('OnDisconnect.update', 1, 2, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.update', this.path_);\n if (Array.isArray(objectToMerge)) {\n var newObjectToMerge = {};\n for (var i = 0; i < objectToMerge.length; ++i) {\n newObjectToMerge['' + i] = objectToMerge[i];\n }\n objectToMerge = newObjectToMerge;\n util_2.warn('Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the ' +\n 'existing data, or an Object with integer keys if you really do want to only update some of the children.');\n }\n validation_1.validateFirebaseMergeDataArg('OnDisconnect.update', 1, objectToMerge, this.path_, false);\n util_1.validateCallback('OnDisconnect.update', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectUpdate(this.path_, objectToMerge, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n return OnDisconnect;\n}());\nexports.OnDisconnect = OnDisconnect;\n\n//# sourceMappingURL=onDisconnect.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/onDisconnect.js\n// module id = 36\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar KeyIndex_1 = require(\"../core/snap/indexes/KeyIndex\");\nvar PriorityIndex_1 = require(\"../core/snap/indexes/PriorityIndex\");\nvar ValueIndex_1 = require(\"../core/snap/indexes/ValueIndex\");\nvar PathIndex_1 = require(\"../core/snap/indexes/PathIndex\");\nvar util_2 = require(\"../core/util/util\");\nvar Path_1 = require(\"../core/util/Path\");\nvar validation_1 = require(\"../core/util/validation\");\nvar util_3 = require(\"@firebase/util\");\nvar EventRegistration_1 = require(\"../core/view/EventRegistration\");\nvar util_4 = require(\"@firebase/util\");\nvar __referenceConstructor;\n/**\n * A Query represents a filter to be applied to a firebase location. This object purely represents the\n * query expression (and exposes our public API to build the query). The actual query logic is in ViewBase.js.\n *\n * Since every Firebase reference is a query, Firebase inherits from this object.\n */\nvar Query = /** @class */ (function () {\n function Query(repo, path, queryParams_, orderByCalled_) {\n this.repo = repo;\n this.path = path;\n this.queryParams_ = queryParams_;\n this.orderByCalled_ = orderByCalled_;\n }\n Object.defineProperty(Query, \"__referenceConstructor\", {\n get: function () {\n util_1.assert(__referenceConstructor, 'Reference.ts has not been loaded');\n return __referenceConstructor;\n },\n set: function (val) {\n __referenceConstructor = val;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Validates start/end values for queries.\n * @param {!QueryParams} params\n * @private\n */\n Query.validateQueryEndpoints_ = function (params) {\n var startNode = null;\n var endNode = null;\n if (params.hasStart()) {\n startNode = params.getIndexStartValue();\n }\n if (params.hasEnd()) {\n endNode = params.getIndexEndValue();\n }\n if (params.getIndex() === KeyIndex_1.KEY_INDEX) {\n var tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +\n 'startAt(), endAt(), or equalTo().';\n var wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), endAt(),' +\n 'or equalTo() must be a string.';\n if (params.hasStart()) {\n var startName = params.getIndexStartName();\n if (startName != util_2.MIN_NAME) {\n throw new Error(tooManyArgsError);\n }\n else if (typeof startNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n if (params.hasEnd()) {\n var endName = params.getIndexEndName();\n if (endName != util_2.MAX_NAME) {\n throw new Error(tooManyArgsError);\n }\n else if (typeof endNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n }\n else if (params.getIndex() === PriorityIndex_1.PRIORITY_INDEX) {\n if ((startNode != null && !validation_1.isValidPriority(startNode)) ||\n (endNode != null && !validation_1.isValidPriority(endNode))) {\n throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +\n 'endAt(), or equalTo() must be a valid priority value (null, a number, or a string).');\n }\n }\n else {\n util_1.assert(params.getIndex() instanceof PathIndex_1.PathIndex ||\n params.getIndex() === ValueIndex_1.VALUE_INDEX, 'unknown index type.');\n if ((startNode != null && typeof startNode === 'object') ||\n (endNode != null && typeof endNode === 'object')) {\n throw new Error('Query: First argument passed to startAt(), endAt(), or equalTo() cannot be ' +\n 'an object.');\n }\n }\n };\n /**\n * Validates that limit* has been called with the correct combination of parameters\n * @param {!QueryParams} params\n * @private\n */\n Query.validateLimit_ = function (params) {\n if (params.hasStart() &&\n params.hasEnd() &&\n params.hasLimit() &&\n !params.hasAnchoredLimit()) {\n throw new Error(\"Query: Can't combine startAt(), endAt(), and limit(). Use limitToFirst() or limitToLast() instead.\");\n }\n };\n /**\n * Validates that no other order by call has been made\n * @param {!string} fnName\n * @private\n */\n Query.prototype.validateNoPreviousOrderByCall_ = function (fnName) {\n if (this.orderByCalled_ === true) {\n throw new Error(fnName + \": You can't combine multiple orderBy calls.\");\n }\n };\n /**\n * @return {!QueryParams}\n */\n Query.prototype.getQueryParams = function () {\n return this.queryParams_;\n };\n /**\n * @return {!Reference}\n */\n Query.prototype.getRef = function () {\n util_3.validateArgCount('Query.ref', 0, 0, arguments.length);\n // This is a slight hack. We cannot goog.require('fb.api.Firebase'), since Firebase requires fb.api.Query.\n // However, we will always export 'Firebase' to the global namespace, so it's guaranteed to exist by the time this\n // method gets called.\n return new Query.__referenceConstructor(this.repo, this.path);\n };\n /**\n * @param {!string} eventType\n * @param {!function(DataSnapshot, string=)} callback\n * @param {(function(Error)|Object)=} cancelCallbackOrContext\n * @param {Object=} context\n * @return {!function(DataSnapshot, string=)}\n */\n Query.prototype.on = function (eventType, callback, cancelCallbackOrContext, context) {\n util_3.validateArgCount('Query.on', 2, 4, arguments.length);\n validation_1.validateEventType('Query.on', 1, eventType, false);\n util_3.validateCallback('Query.on', 2, callback, false);\n var ret = Query.getCancelAndContextArgs_('Query.on', cancelCallbackOrContext, context);\n if (eventType === 'value') {\n this.onValueEvent(callback, ret.cancel, ret.context);\n }\n else {\n var callbacks = {};\n callbacks[eventType] = callback;\n this.onChildEvent(callbacks, ret.cancel, ret.context);\n }\n return callback;\n };\n /**\n * @param {!function(!DataSnapshot)} callback\n * @param {?function(Error)} cancelCallback\n * @param {?Object} context\n * @protected\n */\n Query.prototype.onValueEvent = function (callback, cancelCallback, context) {\n var container = new EventRegistration_1.ValueEventRegistration(callback, cancelCallback || null, context || null);\n this.repo.addEventCallbackForQuery(this, container);\n };\n /**\n * @param {!Object.} callbacks\n * @param {?function(Error)} cancelCallback\n * @param {?Object} context\n * @protected\n */\n Query.prototype.onChildEvent = function (callbacks, cancelCallback, context) {\n var container = new EventRegistration_1.ChildEventRegistration(callbacks, cancelCallback, context);\n this.repo.addEventCallbackForQuery(this, container);\n };\n /**\n * @param {string=} eventType\n * @param {(function(!DataSnapshot, ?string=))=} callback\n * @param {Object=} context\n */\n Query.prototype.off = function (eventType, callback, context) {\n util_3.validateArgCount('Query.off', 0, 3, arguments.length);\n validation_1.validateEventType('Query.off', 1, eventType, true);\n util_3.validateCallback('Query.off', 2, callback, true);\n util_3.validateContextObject('Query.off', 3, context, true);\n var container = null;\n var callbacks = null;\n if (eventType === 'value') {\n var valueCallback = callback || null;\n container = new EventRegistration_1.ValueEventRegistration(valueCallback, null, context || null);\n }\n else if (eventType) {\n if (callback) {\n callbacks = {};\n callbacks[eventType] = callback;\n }\n container = new EventRegistration_1.ChildEventRegistration(callbacks, null, context || null);\n }\n this.repo.removeEventCallbackForQuery(this, container);\n };\n /**\n * Attaches a listener, waits for the first event, and then removes the listener\n * @param {!string} eventType\n * @param {!function(!DataSnapshot, string=)} userCallback\n * @param cancelOrContext\n * @param context\n * @return {!firebase.Promise}\n */\n Query.prototype.once = function (eventType, userCallback, cancelOrContext, context) {\n var _this = this;\n util_3.validateArgCount('Query.once', 1, 4, arguments.length);\n validation_1.validateEventType('Query.once', 1, eventType, false);\n util_3.validateCallback('Query.once', 2, userCallback, true);\n var ret = Query.getCancelAndContextArgs_('Query.once', cancelOrContext, context);\n // TODO: Implement this more efficiently (in particular, use 'get' wire protocol for 'value' event)\n // TODO: consider actually wiring the callbacks into the promise. We cannot do this without a breaking change\n // because the API currently expects callbacks will be called synchronously if the data is cached, but this is\n // against the Promise specification.\n var firstCall = true;\n var deferred = new util_4.Deferred();\n // A dummy error handler in case a user wasn't expecting promises\n deferred.promise.catch(function () { });\n var onceCallback = function (snapshot) {\n // NOTE: Even though we unsubscribe, we may get called multiple times if a single action (e.g. set() with JSON)\n // triggers multiple events (e.g. child_added or child_changed).\n if (firstCall) {\n firstCall = false;\n _this.off(eventType, onceCallback);\n if (userCallback) {\n userCallback.bind(ret.context)(snapshot);\n }\n deferred.resolve(snapshot);\n }\n };\n this.on(eventType, onceCallback, \n /*cancel=*/ function (err) {\n _this.off(eventType, onceCallback);\n if (ret.cancel)\n ret.cancel.bind(ret.context)(err);\n deferred.reject(err);\n });\n return deferred.promise;\n };\n /**\n * Set a limit and anchor it to the start of the window.\n * @param {!number} limit\n * @return {!Query}\n */\n Query.prototype.limitToFirst = function (limit) {\n util_3.validateArgCount('Query.limitToFirst', 1, 1, arguments.length);\n if (typeof limit !== 'number' ||\n Math.floor(limit) !== limit ||\n limit <= 0) {\n throw new Error('Query.limitToFirst: First argument must be a positive integer.');\n }\n if (this.queryParams_.hasLimit()) {\n throw new Error('Query.limitToFirst: Limit was already set (by another call to limit, ' +\n 'limitToFirst, or limitToLast).');\n }\n return new Query(this.repo, this.path, this.queryParams_.limitToFirst(limit), this.orderByCalled_);\n };\n /**\n * Set a limit and anchor it to the end of the window.\n * @param {!number} limit\n * @return {!Query}\n */\n Query.prototype.limitToLast = function (limit) {\n util_3.validateArgCount('Query.limitToLast', 1, 1, arguments.length);\n if (typeof limit !== 'number' ||\n Math.floor(limit) !== limit ||\n limit <= 0) {\n throw new Error('Query.limitToLast: First argument must be a positive integer.');\n }\n if (this.queryParams_.hasLimit()) {\n throw new Error('Query.limitToLast: Limit was already set (by another call to limit, ' +\n 'limitToFirst, or limitToLast).');\n }\n return new Query(this.repo, this.path, this.queryParams_.limitToLast(limit), this.orderByCalled_);\n };\n /**\n * Given a child path, return a new query ordered by the specified grandchild path.\n * @param {!string} path\n * @return {!Query}\n */\n Query.prototype.orderByChild = function (path) {\n util_3.validateArgCount('Query.orderByChild', 1, 1, arguments.length);\n if (path === '$key') {\n throw new Error('Query.orderByChild: \"$key\" is invalid. Use Query.orderByKey() instead.');\n }\n else if (path === '$priority') {\n throw new Error('Query.orderByChild: \"$priority\" is invalid. Use Query.orderByPriority() instead.');\n }\n else if (path === '$value') {\n throw new Error('Query.orderByChild: \"$value\" is invalid. Use Query.orderByValue() instead.');\n }\n validation_1.validatePathString('Query.orderByChild', 1, path, false);\n this.validateNoPreviousOrderByCall_('Query.orderByChild');\n var parsedPath = new Path_1.Path(path);\n if (parsedPath.isEmpty()) {\n throw new Error('Query.orderByChild: cannot pass in empty path. Use Query.orderByValue() instead.');\n }\n var index = new PathIndex_1.PathIndex(parsedPath);\n var newParams = this.queryParams_.orderBy(index);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * Return a new query ordered by the KeyIndex\n * @return {!Query}\n */\n Query.prototype.orderByKey = function () {\n util_3.validateArgCount('Query.orderByKey', 0, 0, arguments.length);\n this.validateNoPreviousOrderByCall_('Query.orderByKey');\n var newParams = this.queryParams_.orderBy(KeyIndex_1.KEY_INDEX);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * Return a new query ordered by the PriorityIndex\n * @return {!Query}\n */\n Query.prototype.orderByPriority = function () {\n util_3.validateArgCount('Query.orderByPriority', 0, 0, arguments.length);\n this.validateNoPreviousOrderByCall_('Query.orderByPriority');\n var newParams = this.queryParams_.orderBy(PriorityIndex_1.PRIORITY_INDEX);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * Return a new query ordered by the ValueIndex\n * @return {!Query}\n */\n Query.prototype.orderByValue = function () {\n util_3.validateArgCount('Query.orderByValue', 0, 0, arguments.length);\n this.validateNoPreviousOrderByCall_('Query.orderByValue');\n var newParams = this.queryParams_.orderBy(ValueIndex_1.VALUE_INDEX);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * @param {number|string|boolean|null} value\n * @param {?string=} name\n * @return {!Query}\n */\n Query.prototype.startAt = function (value, name) {\n if (value === void 0) { value = null; }\n util_3.validateArgCount('Query.startAt', 0, 2, arguments.length);\n validation_1.validateFirebaseDataArg('Query.startAt', 1, value, this.path, true);\n validation_1.validateKey('Query.startAt', 2, name, true);\n var newParams = this.queryParams_.startAt(value, name);\n Query.validateLimit_(newParams);\n Query.validateQueryEndpoints_(newParams);\n if (this.queryParams_.hasStart()) {\n throw new Error('Query.startAt: Starting point was already set (by another call to startAt ' +\n 'or equalTo).');\n }\n // Calling with no params tells us to start at the beginning.\n if (value === undefined) {\n value = null;\n name = null;\n }\n return new Query(this.repo, this.path, newParams, this.orderByCalled_);\n };\n /**\n * @param {number|string|boolean|null} value\n * @param {?string=} name\n * @return {!Query}\n */\n Query.prototype.endAt = function (value, name) {\n if (value === void 0) { value = null; }\n util_3.validateArgCount('Query.endAt', 0, 2, arguments.length);\n validation_1.validateFirebaseDataArg('Query.endAt', 1, value, this.path, true);\n validation_1.validateKey('Query.endAt', 2, name, true);\n var newParams = this.queryParams_.endAt(value, name);\n Query.validateLimit_(newParams);\n Query.validateQueryEndpoints_(newParams);\n if (this.queryParams_.hasEnd()) {\n throw new Error('Query.endAt: Ending point was already set (by another call to endAt or ' +\n 'equalTo).');\n }\n return new Query(this.repo, this.path, newParams, this.orderByCalled_);\n };\n /**\n * Load the selection of children with exactly the specified value, and, optionally,\n * the specified name.\n * @param {number|string|boolean|null} value\n * @param {string=} name\n * @return {!Query}\n */\n Query.prototype.equalTo = function (value, name) {\n util_3.validateArgCount('Query.equalTo', 1, 2, arguments.length);\n validation_1.validateFirebaseDataArg('Query.equalTo', 1, value, this.path, false);\n validation_1.validateKey('Query.equalTo', 2, name, true);\n if (this.queryParams_.hasStart()) {\n throw new Error('Query.equalTo: Starting point was already set (by another call to startAt or ' +\n 'equalTo).');\n }\n if (this.queryParams_.hasEnd()) {\n throw new Error('Query.equalTo: Ending point was already set (by another call to endAt or ' +\n 'equalTo).');\n }\n return this.startAt(value, name).endAt(value, name);\n };\n /**\n * @return {!string} URL for this location.\n */\n Query.prototype.toString = function () {\n util_3.validateArgCount('Query.toString', 0, 0, arguments.length);\n return this.repo.toString() + this.path.toUrlEncodedString();\n };\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users.\n Query.prototype.toJSON = function () {\n // An optional spacer argument is unnecessary for a string.\n util_3.validateArgCount('Query.toJSON', 0, 1, arguments.length);\n return this.toString();\n };\n /**\n * An object representation of the query parameters used by this Query.\n * @return {!Object}\n */\n Query.prototype.queryObject = function () {\n return this.queryParams_.getQueryObject();\n };\n /**\n * @return {!string}\n */\n Query.prototype.queryIdentifier = function () {\n var obj = this.queryObject();\n var id = util_2.ObjectToUniqueKey(obj);\n return id === '{}' ? 'default' : id;\n };\n /**\n * Return true if this query and the provided query are equivalent; otherwise, return false.\n * @param {Query} other\n * @return {boolean}\n */\n Query.prototype.isEqual = function (other) {\n util_3.validateArgCount('Query.isEqual', 1, 1, arguments.length);\n if (!(other instanceof Query)) {\n var error = 'Query.isEqual failed: First argument must be an instance of firebase.database.Query.';\n throw new Error(error);\n }\n var sameRepo = this.repo === other.repo;\n var samePath = this.path.equals(other.path);\n var sameQueryIdentifier = this.queryIdentifier() === other.queryIdentifier();\n return sameRepo && samePath && sameQueryIdentifier;\n };\n /**\n * Helper used by .on and .once to extract the context and or cancel arguments.\n * @param {!string} fnName The function name (on or once)\n * @param {(function(Error)|Object)=} cancelOrContext\n * @param {Object=} context\n * @return {{cancel: ?function(Error), context: ?Object}}\n * @private\n */\n Query.getCancelAndContextArgs_ = function (fnName, cancelOrContext, context) {\n var ret = { cancel: null, context: null };\n if (cancelOrContext && context) {\n ret.cancel = cancelOrContext;\n util_3.validateCallback(fnName, 3, ret.cancel, true);\n ret.context = context;\n util_3.validateContextObject(fnName, 4, ret.context, true);\n }\n else if (cancelOrContext) {\n // we have either a cancel callback or a context.\n if (typeof cancelOrContext === 'object' && cancelOrContext !== null) {\n // it's a context!\n ret.context = cancelOrContext;\n }\n else if (typeof cancelOrContext === 'function') {\n ret.cancel = cancelOrContext;\n }\n else {\n throw new Error(util_3.errorPrefix(fnName, 3, true) +\n ' must either be a cancel callback or a context object.');\n }\n }\n return ret;\n };\n Object.defineProperty(Query.prototype, \"ref\", {\n get: function () {\n return this.getRef();\n },\n enumerable: true,\n configurable: true\n });\n return Query;\n}());\nexports.Query = Query;\n\n//# sourceMappingURL=Query.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/Query.js\n// module id = 37\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../util/util\");\nvar util_3 = require(\"@firebase/util\");\nvar MAX_NODE;\nfunction setMaxNode(val) {\n MAX_NODE = val;\n}\nexports.setMaxNode = setMaxNode;\n/**\n * @param {(!string|!number)} priority\n * @return {!string}\n */\nexports.priorityHashText = function (priority) {\n if (typeof priority === 'number')\n return 'number:' + util_2.doubleToIEEE754String(priority);\n else\n return 'string:' + priority;\n};\n/**\n * Validates that a priority snapshot Node is valid.\n *\n * @param {!Node} priorityNode\n */\nexports.validatePriorityNode = function (priorityNode) {\n if (priorityNode.isLeafNode()) {\n var val = priorityNode.val();\n util_1.assert(typeof val === 'string' ||\n typeof val === 'number' ||\n (typeof val === 'object' && util_3.contains(val, '.sv')), 'Priority must be a string or number.');\n }\n else {\n util_1.assert(priorityNode === MAX_NODE || priorityNode.isEmpty(), 'priority of unexpected type.');\n }\n // Don't call getPriority() on MAX_NODE to avoid hitting assertion.\n util_1.assert(priorityNode === MAX_NODE || priorityNode.getPriority().isEmpty(), \"Priority nodes can't have a priority of their own.\");\n};\n\n//# sourceMappingURL=snap.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/snap.js\n// module id = 38\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar Index_1 = require(\"./Index\");\nvar Node_1 = require(\"../Node\");\nvar util_1 = require(\"../../util/util\");\nvar nodeFromJSON_1 = require(\"../nodeFromJSON\");\n/**\n * @constructor\n * @extends {Index}\n * @private\n */\nvar ValueIndex = /** @class */ (function (_super) {\n tslib_1.__extends(ValueIndex, _super);\n function ValueIndex() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.compare = function (a, b) {\n var indexCmp = a.node.compareTo(b.node);\n if (indexCmp === 0) {\n return util_1.nameCompare(a.name, b.name);\n }\n else {\n return indexCmp;\n }\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.isDefinedOn = function (node) {\n return true;\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.indexedValueChanged = function (oldNode, newNode) {\n return !oldNode.equals(newNode);\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.maxPost = function () {\n return Node_1.NamedNode.MAX;\n };\n /**\n * @param {*} indexValue\n * @param {string} name\n * @return {!NamedNode}\n */\n ValueIndex.prototype.makePost = function (indexValue, name) {\n var valueNode = nodeFromJSON_1.nodeFromJSON(indexValue);\n return new Node_1.NamedNode(name, valueNode);\n };\n /**\n * @return {!string} String representation for inclusion in a query spec\n */\n ValueIndex.prototype.toString = function () {\n return '.value';\n };\n return ValueIndex;\n}(Index_1.Index));\nexports.ValueIndex = ValueIndex;\nexports.VALUE_INDEX = new ValueIndex();\n\n//# sourceMappingURL=ValueIndex.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/indexes/ValueIndex.js\n// module id = 39\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar childSet_1 = require(\"./childSet\");\nvar util_2 = require(\"@firebase/util\");\nvar Node_1 = require(\"./Node\");\nvar PriorityIndex_1 = require(\"./indexes/PriorityIndex\");\nvar KeyIndex_1 = require(\"./indexes/KeyIndex\");\nvar _defaultIndexMap;\nvar fallbackObject = {};\n/**\n *\n * @param {Object.>} indexes\n * @param {Object.} indexSet\n * @constructor\n */\nvar IndexMap = /** @class */ (function () {\n function IndexMap(indexes_, indexSet_) {\n this.indexes_ = indexes_;\n this.indexSet_ = indexSet_;\n }\n Object.defineProperty(IndexMap, \"Default\", {\n /**\n * The default IndexMap for nodes without a priority\n * @type {!IndexMap}\n * @const\n */\n get: function () {\n util_1.assert(fallbackObject && PriorityIndex_1.PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');\n _defaultIndexMap =\n _defaultIndexMap ||\n new IndexMap({ '.priority': fallbackObject }, { '.priority': PriorityIndex_1.PRIORITY_INDEX });\n return _defaultIndexMap;\n },\n enumerable: true,\n configurable: true\n });\n /**\n *\n * @param {!string} indexKey\n * @return {?SortedMap.}\n */\n IndexMap.prototype.get = function (indexKey) {\n var sortedMap = util_2.safeGet(this.indexes_, indexKey);\n if (!sortedMap)\n throw new Error('No index defined for ' + indexKey);\n if (sortedMap === fallbackObject) {\n // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the\n // regular child map\n return null;\n }\n else {\n return sortedMap;\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {boolean}\n */\n IndexMap.prototype.hasIndex = function (indexDefinition) {\n return util_2.contains(this.indexSet_, indexDefinition.toString());\n };\n /**\n * @param {!Index} indexDefinition\n * @param {!SortedMap.} existingChildren\n * @return {!IndexMap}\n */\n IndexMap.prototype.addIndex = function (indexDefinition, existingChildren) {\n util_1.assert(indexDefinition !== KeyIndex_1.KEY_INDEX, \"KeyIndex always exists and isn't meant to be added to the IndexMap.\");\n var childList = [];\n var sawIndexedValue = false;\n var iter = existingChildren.getIterator(Node_1.NamedNode.Wrap);\n var next = iter.getNext();\n while (next) {\n sawIndexedValue =\n sawIndexedValue || indexDefinition.isDefinedOn(next.node);\n childList.push(next);\n next = iter.getNext();\n }\n var newIndex;\n if (sawIndexedValue) {\n newIndex = childSet_1.buildChildSet(childList, indexDefinition.getCompare());\n }\n else {\n newIndex = fallbackObject;\n }\n var indexName = indexDefinition.toString();\n var newIndexSet = util_2.clone(this.indexSet_);\n newIndexSet[indexName] = indexDefinition;\n var newIndexes = util_2.clone(this.indexes_);\n newIndexes[indexName] = newIndex;\n return new IndexMap(newIndexes, newIndexSet);\n };\n /**\n * Ensure that this node is properly tracked in any indexes that we're maintaining\n * @param {!NamedNode} namedNode\n * @param {!SortedMap.} existingChildren\n * @return {!IndexMap}\n */\n IndexMap.prototype.addToIndexes = function (namedNode, existingChildren) {\n var _this = this;\n var newIndexes = util_2.map(this.indexes_, function (indexedChildren, indexName) {\n var index = util_2.safeGet(_this.indexSet_, indexName);\n util_1.assert(index, 'Missing index implementation for ' + indexName);\n if (indexedChildren === fallbackObject) {\n // Check to see if we need to index everything\n if (index.isDefinedOn(namedNode.node)) {\n // We need to build this index\n var childList = [];\n var iter = existingChildren.getIterator(Node_1.NamedNode.Wrap);\n var next = iter.getNext();\n while (next) {\n if (next.name != namedNode.name) {\n childList.push(next);\n }\n next = iter.getNext();\n }\n childList.push(namedNode);\n return childSet_1.buildChildSet(childList, index.getCompare());\n }\n else {\n // No change, this remains a fallback\n return fallbackObject;\n }\n }\n else {\n var existingSnap = existingChildren.get(namedNode.name);\n var newChildren = indexedChildren;\n if (existingSnap) {\n newChildren = newChildren.remove(new Node_1.NamedNode(namedNode.name, existingSnap));\n }\n return newChildren.insert(namedNode, namedNode.node);\n }\n });\n return new IndexMap(newIndexes, this.indexSet_);\n };\n /**\n * Create a new IndexMap instance with the given value removed\n * @param {!NamedNode} namedNode\n * @param {!SortedMap.} existingChildren\n * @return {!IndexMap}\n */\n IndexMap.prototype.removeFromIndexes = function (namedNode, existingChildren) {\n var newIndexes = util_2.map(this.indexes_, function (indexedChildren) {\n if (indexedChildren === fallbackObject) {\n // This is the fallback. Just return it, nothing to do in this case\n return indexedChildren;\n }\n else {\n var existingSnap = existingChildren.get(namedNode.name);\n if (existingSnap) {\n return indexedChildren.remove(new Node_1.NamedNode(namedNode.name, existingSnap));\n }\n else {\n // No record of this child\n return indexedChildren;\n }\n }\n });\n return new IndexMap(newIndexes, this.indexSet_);\n };\n return IndexMap;\n}());\nexports.IndexMap = IndexMap;\n\n//# sourceMappingURL=IndexMap.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/IndexMap.js\n// module id = 40\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar SortedMap_1 = require(\"../util/SortedMap\");\nvar SortedMap_2 = require(\"../util/SortedMap\");\nvar LOG_2 = Math.log(2);\n/**\n * @constructor\n */\nvar Base12Num = /** @class */ (function () {\n /**\n * @param {number} length\n */\n function Base12Num(length) {\n var logBase2 = function (num) {\n return parseInt((Math.log(num) / LOG_2), 10);\n };\n var bitMask = function (bits) { return parseInt(Array(bits + 1).join('1'), 2); };\n this.count = logBase2(length + 1);\n this.current_ = this.count - 1;\n var mask = bitMask(this.count);\n this.bits_ = (length + 1) & mask;\n }\n /**\n * @return {boolean}\n */\n Base12Num.prototype.nextBitIsOne = function () {\n //noinspection JSBitwiseOperatorUsage\n var result = !(this.bits_ & (0x1 << this.current_));\n this.current_--;\n return result;\n };\n return Base12Num;\n}());\n/**\n * Takes a list of child nodes and constructs a SortedSet using the given comparison\n * function\n *\n * Uses the algorithm described in the paper linked here:\n * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458\n *\n * @template K, V\n * @param {Array.} childList Unsorted list of children\n * @param {function(!NamedNode, !NamedNode):number} cmp The comparison method to be used\n * @param {(function(NamedNode):K)=} keyFn An optional function to extract K from a node wrapper, if K's\n * type is not NamedNode\n * @param {(function(K, K):number)=} mapSortFn An optional override for comparator used by the generated sorted map\n * @return {SortedMap.}\n */\nexports.buildChildSet = function (childList, cmp, keyFn, mapSortFn) {\n childList.sort(cmp);\n var buildBalancedTree = function (low, high) {\n var length = high - low;\n var namedNode;\n var key;\n if (length == 0) {\n return null;\n }\n else if (length == 1) {\n namedNode = childList[low];\n key = keyFn ? keyFn(namedNode) : namedNode;\n return new SortedMap_1.LLRBNode(key, namedNode.node, SortedMap_1.LLRBNode.BLACK, null, null);\n }\n else {\n var middle = parseInt((length / 2), 10) + low;\n var left = buildBalancedTree(low, middle);\n var right = buildBalancedTree(middle + 1, high);\n namedNode = childList[middle];\n key = keyFn ? keyFn(namedNode) : namedNode;\n return new SortedMap_1.LLRBNode(key, namedNode.node, SortedMap_1.LLRBNode.BLACK, left, right);\n }\n };\n var buildFrom12Array = function (base12) {\n var node = null;\n var root = null;\n var index = childList.length;\n var buildPennant = function (chunkSize, color) {\n var low = index - chunkSize;\n var high = index;\n index -= chunkSize;\n var childTree = buildBalancedTree(low + 1, high);\n var namedNode = childList[low];\n var key = keyFn ? keyFn(namedNode) : namedNode;\n attachPennant(new SortedMap_1.LLRBNode(key, namedNode.node, color, null, childTree));\n };\n var attachPennant = function (pennant) {\n if (node) {\n node.left = pennant;\n node = pennant;\n }\n else {\n root = pennant;\n node = pennant;\n }\n };\n for (var i = 0; i < base12.count; ++i) {\n var isOne = base12.nextBitIsOne();\n // The number of nodes taken in each slice is 2^(arr.length - (i + 1))\n var chunkSize = Math.pow(2, base12.count - (i + 1));\n if (isOne) {\n buildPennant(chunkSize, SortedMap_1.LLRBNode.BLACK);\n }\n else {\n // current == 2\n buildPennant(chunkSize, SortedMap_1.LLRBNode.BLACK);\n buildPennant(chunkSize, SortedMap_1.LLRBNode.RED);\n }\n }\n return root;\n };\n var base12 = new Base12Num(childList.length);\n var root = buildFrom12Array(base12);\n return new SortedMap_2.SortedMap(mapSortFn || cmp, root);\n};\n\n//# sourceMappingURL=childSet.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/childSet.js\n// module id = 41\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../util/util\");\nfunction NAME_ONLY_COMPARATOR(left, right) {\n return util_1.nameCompare(left.name, right.name);\n}\nexports.NAME_ONLY_COMPARATOR = NAME_ONLY_COMPARATOR;\nfunction NAME_COMPARATOR(left, right) {\n return util_1.nameCompare(left, right);\n}\nexports.NAME_COMPARATOR = NAME_COMPARATOR;\n\n//# sourceMappingURL=comparators.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/comparators.js\n// module id = 42\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../../util/util\");\nvar Index_1 = require(\"./Index\");\nvar ChildrenNode_1 = require(\"../ChildrenNode\");\nvar Node_1 = require(\"../Node\");\nvar nodeFromJSON_1 = require(\"../nodeFromJSON\");\n/**\n * @param {!Path} indexPath\n * @constructor\n * @extends {Index}\n */\nvar PathIndex = /** @class */ (function (_super) {\n tslib_1.__extends(PathIndex, _super);\n function PathIndex(indexPath_) {\n var _this = _super.call(this) || this;\n _this.indexPath_ = indexPath_;\n util_1.assert(!indexPath_.isEmpty() && indexPath_.getFront() !== '.priority', \"Can't create PathIndex with empty path or .priority key\");\n return _this;\n }\n /**\n * @param {!Node} snap\n * @return {!Node}\n * @protected\n */\n PathIndex.prototype.extractChild = function (snap) {\n return snap.getChild(this.indexPath_);\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.isDefinedOn = function (node) {\n return !node.getChild(this.indexPath_).isEmpty();\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.compare = function (a, b) {\n var aChild = this.extractChild(a.node);\n var bChild = this.extractChild(b.node);\n var indexCmp = aChild.compareTo(bChild);\n if (indexCmp === 0) {\n return util_2.nameCompare(a.name, b.name);\n }\n else {\n return indexCmp;\n }\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.makePost = function (indexValue, name) {\n var valueNode = nodeFromJSON_1.nodeFromJSON(indexValue);\n var node = ChildrenNode_1.ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);\n return new Node_1.NamedNode(name, node);\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.maxPost = function () {\n var node = ChildrenNode_1.ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, ChildrenNode_1.MAX_NODE);\n return new Node_1.NamedNode(util_2.MAX_NAME, node);\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.toString = function () {\n return this.indexPath_.slice().join('/');\n };\n return PathIndex;\n}(Index_1.Index));\nexports.PathIndex = PathIndex;\n\n//# sourceMappingURL=PathIndex.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/indexes/PathIndex.js\n// module id = 43\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Path_1 = require(\"./Path\");\nvar SparseSnapshotTree_1 = require(\"../SparseSnapshotTree\");\nvar LeafNode_1 = require(\"../snap/LeafNode\");\nvar nodeFromJSON_1 = require(\"../snap/nodeFromJSON\");\nvar PriorityIndex_1 = require(\"../snap/indexes/PriorityIndex\");\n/**\n * Generate placeholders for deferred values.\n * @param {?Object} values\n * @return {!Object}\n */\nexports.generateWithValues = function (values) {\n values = values || {};\n values['timestamp'] = values['timestamp'] || new Date().getTime();\n return values;\n};\n/**\n * Value to use when firing local events. When writing server values, fire\n * local events with an approximate value, otherwise return value as-is.\n * @param {(Object|string|number|boolean)} value\n * @param {!Object} serverValues\n * @return {!(string|number|boolean)}\n */\nexports.resolveDeferredValue = function (value, serverValues) {\n if (!value || typeof value !== 'object') {\n return value;\n }\n else {\n util_1.assert('.sv' in value, 'Unexpected leaf node or priority contents');\n return serverValues[value['.sv']];\n }\n};\n/**\n * Recursively replace all deferred values and priorities in the tree with the\n * specified generated replacement values.\n * @param {!SparseSnapshotTree} tree\n * @param {!Object} serverValues\n * @return {!SparseSnapshotTree}\n */\nexports.resolveDeferredValueTree = function (tree, serverValues) {\n var resolvedTree = new SparseSnapshotTree_1.SparseSnapshotTree();\n tree.forEachTree(new Path_1.Path(''), function (path, node) {\n resolvedTree.remember(path, exports.resolveDeferredValueSnapshot(node, serverValues));\n });\n return resolvedTree;\n};\n/**\n * Recursively replace all deferred values and priorities in the node with the\n * specified generated replacement values. If there are no server values in the node,\n * it'll be returned as-is.\n * @param {!Node} node\n * @param {!Object} serverValues\n * @return {!Node}\n */\nexports.resolveDeferredValueSnapshot = function (node, serverValues) {\n var rawPri = node.getPriority().val();\n var priority = exports.resolveDeferredValue(rawPri, serverValues);\n var newNode;\n if (node.isLeafNode()) {\n var leafNode = node;\n var value = exports.resolveDeferredValue(leafNode.getValue(), serverValues);\n if (value !== leafNode.getValue() ||\n priority !== leafNode.getPriority().val()) {\n return new LeafNode_1.LeafNode(value, nodeFromJSON_1.nodeFromJSON(priority));\n }\n else {\n return node;\n }\n }\n else {\n var childrenNode = node;\n newNode = childrenNode;\n if (priority !== childrenNode.getPriority().val()) {\n newNode = newNode.updatePriority(new LeafNode_1.LeafNode(priority));\n }\n childrenNode.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n var newChildNode = exports.resolveDeferredValueSnapshot(childNode, serverValues);\n if (newChildNode !== childNode) {\n newNode = newNode.updateImmediateChild(childName, newChildNode);\n }\n });\n return newNode;\n }\n};\n\n//# sourceMappingURL=ServerValues.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/ServerValues.js\n// module id = 44\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = require(\"./util/Path\");\nvar PriorityIndex_1 = require(\"./snap/indexes/PriorityIndex\");\nvar CountedSet_1 = require(\"./util/CountedSet\");\n/**\n * Helper class to store a sparse set of snapshots.\n *\n * @constructor\n */\nvar SparseSnapshotTree = /** @class */ (function () {\n function SparseSnapshotTree() {\n /**\n * @private\n * @type {Node}\n */\n this.value_ = null;\n /**\n * @private\n * @type {CountedSet}\n */\n this.children_ = null;\n }\n /**\n * Gets the node stored at the given path if one exists.\n *\n * @param {!Path} path Path to look up snapshot for.\n * @return {?Node} The retrieved node, or null.\n */\n SparseSnapshotTree.prototype.find = function (path) {\n if (this.value_ != null) {\n return this.value_.getChild(path);\n }\n else if (!path.isEmpty() && this.children_ != null) {\n var childKey = path.getFront();\n path = path.popFront();\n if (this.children_.contains(childKey)) {\n var childTree = this.children_.get(childKey);\n return childTree.find(path);\n }\n else {\n return null;\n }\n }\n else {\n return null;\n }\n };\n /**\n * Stores the given node at the specified path. If there is already a node\n * at a shallower path, it merges the new data into that snapshot node.\n *\n * @param {!Path} path Path to look up snapshot for.\n * @param {!Node} data The new data, or null.\n */\n SparseSnapshotTree.prototype.remember = function (path, data) {\n if (path.isEmpty()) {\n this.value_ = data;\n this.children_ = null;\n }\n else if (this.value_ !== null) {\n this.value_ = this.value_.updateChild(path, data);\n }\n else {\n if (this.children_ == null) {\n this.children_ = new CountedSet_1.CountedSet();\n }\n var childKey = path.getFront();\n if (!this.children_.contains(childKey)) {\n this.children_.add(childKey, new SparseSnapshotTree());\n }\n var child = this.children_.get(childKey);\n path = path.popFront();\n child.remember(path, data);\n }\n };\n /**\n * Purge the data at path from the cache.\n *\n * @param {!Path} path Path to look up snapshot for.\n * @return {boolean} True if this node should now be removed.\n */\n SparseSnapshotTree.prototype.forget = function (path) {\n if (path.isEmpty()) {\n this.value_ = null;\n this.children_ = null;\n return true;\n }\n else {\n if (this.value_ !== null) {\n if (this.value_.isLeafNode()) {\n // We're trying to forget a node that doesn't exist\n return false;\n }\n else {\n var value = this.value_;\n this.value_ = null;\n var self_1 = this;\n value.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, tree) {\n self_1.remember(new Path_1.Path(key), tree);\n });\n return this.forget(path);\n }\n }\n else if (this.children_ !== null) {\n var childKey = path.getFront();\n path = path.popFront();\n if (this.children_.contains(childKey)) {\n var safeToRemove = this.children_.get(childKey).forget(path);\n if (safeToRemove) {\n this.children_.remove(childKey);\n }\n }\n if (this.children_.isEmpty()) {\n this.children_ = null;\n return true;\n }\n else {\n return false;\n }\n }\n else {\n return true;\n }\n }\n };\n /**\n * Recursively iterates through all of the stored tree and calls the\n * callback on each one.\n *\n * @param {!Path} prefixPath Path to look up node for.\n * @param {!Function} func The function to invoke for each tree.\n */\n SparseSnapshotTree.prototype.forEachTree = function (prefixPath, func) {\n if (this.value_ !== null) {\n func(prefixPath, this.value_);\n }\n else {\n this.forEachChild(function (key, tree) {\n var path = new Path_1.Path(prefixPath.toString() + '/' + key);\n tree.forEachTree(path, func);\n });\n }\n };\n /**\n * Iterates through each immediate child and triggers the callback.\n *\n * @param {!Function} func The function to invoke for each child.\n */\n SparseSnapshotTree.prototype.forEachChild = function (func) {\n if (this.children_ !== null) {\n this.children_.each(function (key, tree) {\n func(key, tree);\n });\n }\n };\n return SparseSnapshotTree;\n}());\nexports.SparseSnapshotTree = SparseSnapshotTree;\n\n//# sourceMappingURL=SparseSnapshotTree.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/SparseSnapshotTree.js\n// module id = 45\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Implements a set with a count of elements.\n *\n * @template K, V\n */\nvar CountedSet = /** @class */ (function () {\n function CountedSet() {\n this.set = {};\n }\n /**\n * @param {!K} item\n * @param {V} val\n */\n CountedSet.prototype.add = function (item, val) {\n this.set[item] = val !== null ? val : true;\n };\n /**\n * @param {!K} key\n * @return {boolean}\n */\n CountedSet.prototype.contains = function (key) {\n return util_1.contains(this.set, key);\n };\n /**\n * @param {!K} item\n * @return {V}\n */\n CountedSet.prototype.get = function (item) {\n return this.contains(item) ? this.set[item] : undefined;\n };\n /**\n * @param {!K} item\n */\n CountedSet.prototype.remove = function (item) {\n delete this.set[item];\n };\n /**\n * Deletes everything in the set\n */\n CountedSet.prototype.clear = function () {\n this.set = {};\n };\n /**\n * True if there's nothing in the set\n * @return {boolean}\n */\n CountedSet.prototype.isEmpty = function () {\n return util_1.isEmpty(this.set);\n };\n /**\n * @return {number} The number of items in the set\n */\n CountedSet.prototype.count = function () {\n return util_1.getCount(this.set);\n };\n /**\n * Run a function on each k,v pair in the set\n * @param {function(K, V)} fn\n */\n CountedSet.prototype.each = function (fn) {\n util_1.forEach(this.set, function (k, v) { return fn(k, v); });\n };\n /**\n * Mostly for debugging\n * @return {Array.} The keys present in this CountedSet\n */\n CountedSet.prototype.keys = function () {\n var keys = [];\n util_1.forEach(this.set, function (k) {\n keys.push(k);\n });\n return keys;\n };\n return CountedSet;\n}());\nexports.CountedSet = CountedSet;\n\n//# sourceMappingURL=CountedSet.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/CountedSet.js\n// module id = 46\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = require(\"./Operation\");\nvar Path_1 = require(\"../util/Path\");\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @param {!Node} snap\n * @constructor\n * @implements {Operation}\n */\nvar Overwrite = /** @class */ (function () {\n function Overwrite(source, path, snap) {\n this.source = source;\n this.path = path;\n this.snap = snap;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.OVERWRITE;\n }\n Overwrite.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n return new Overwrite(this.source, Path_1.Path.Empty, this.snap.getImmediateChild(childName));\n }\n else {\n return new Overwrite(this.source, this.path.popFront(), this.snap);\n }\n };\n return Overwrite;\n}());\nexports.Overwrite = Overwrite;\n\n//# sourceMappingURL=Overwrite.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/operation/Overwrite.js\n// module id = 47\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar CacheNode_1 = require(\"./view/CacheNode\");\nvar ChildrenNode_1 = require(\"./snap/ChildrenNode\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar ViewCache_1 = require(\"./view/ViewCache\");\nvar View_1 = require(\"./view/View\");\nvar __referenceConstructor;\n/**\n * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to\n * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes\n * and user writes (set, transaction, update).\n *\n * It's responsible for:\n * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).\n * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,\n * applyUserOverwrite, etc.)\n */\nvar SyncPoint = /** @class */ (function () {\n function SyncPoint() {\n /**\n * The Views being tracked at this location in the tree, stored as a map where the key is a\n * queryId and the value is the View for that query.\n *\n * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).\n *\n * @type {!Object.}\n * @private\n */\n this.views_ = {};\n }\n Object.defineProperty(SyncPoint, \"__referenceConstructor\", {\n get: function () {\n util_1.assert(__referenceConstructor, 'Reference.ts has not been loaded');\n return __referenceConstructor;\n },\n set: function (val) {\n util_1.assert(!__referenceConstructor, '__referenceConstructor has already been defined');\n __referenceConstructor = val;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @return {boolean}\n */\n SyncPoint.prototype.isEmpty = function () {\n return util_2.isEmpty(this.views_);\n };\n /**\n *\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} optCompleteServerCache\n * @return {!Array.}\n */\n SyncPoint.prototype.applyOperation = function (operation, writesCache, optCompleteServerCache) {\n var queryId = operation.source.queryId;\n if (queryId !== null) {\n var view = util_2.safeGet(this.views_, queryId);\n util_1.assert(view != null, 'SyncTree gave us an op for an invalid query.');\n return view.applyOperation(operation, writesCache, optCompleteServerCache);\n }\n else {\n var events_1 = [];\n util_2.forEach(this.views_, function (key, view) {\n events_1 = events_1.concat(view.applyOperation(operation, writesCache, optCompleteServerCache));\n });\n return events_1;\n }\n };\n /**\n * Add an event callback for the specified query.\n *\n * @param {!Query} query\n * @param {!EventRegistration} eventRegistration\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache Complete server cache, if we have it.\n * @param {boolean} serverCacheComplete\n * @return {!Array.} Events to raise.\n */\n SyncPoint.prototype.addEventRegistration = function (query, eventRegistration, writesCache, serverCache, serverCacheComplete) {\n var queryId = query.queryIdentifier();\n var view = util_2.safeGet(this.views_, queryId);\n if (!view) {\n // TODO: make writesCache take flag for complete server node\n var eventCache = writesCache.calcCompleteEventCache(serverCacheComplete ? serverCache : null);\n var eventCacheComplete = false;\n if (eventCache) {\n eventCacheComplete = true;\n }\n else if (serverCache instanceof ChildrenNode_1.ChildrenNode) {\n eventCache = writesCache.calcCompleteEventChildren(serverCache);\n eventCacheComplete = false;\n }\n else {\n eventCache = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n eventCacheComplete = false;\n }\n var viewCache = new ViewCache_1.ViewCache(new CacheNode_1.CacheNode(\n /** @type {!Node} */ (eventCache), eventCacheComplete, false), new CacheNode_1.CacheNode(\n /** @type {!Node} */ (serverCache), serverCacheComplete, false));\n view = new View_1.View(query, viewCache);\n this.views_[queryId] = view;\n }\n // This is guaranteed to exist now, we just created anything that was missing\n view.addEventRegistration(eventRegistration);\n return view.getInitialEvents(eventRegistration);\n };\n /**\n * Remove event callback(s). Return cancelEvents if a cancelError is specified.\n *\n * If query is the default query, we'll check all views for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified view(s).\n *\n * @param {!Query} query\n * @param {?EventRegistration} eventRegistration If null, remove all callbacks.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {{removed:!Array., events:!Array.}} removed queries and any cancel events\n */\n SyncPoint.prototype.removeEventRegistration = function (query, eventRegistration, cancelError) {\n var queryId = query.queryIdentifier();\n var removed = [];\n var cancelEvents = [];\n var hadCompleteView = this.hasCompleteView();\n if (queryId === 'default') {\n // When you do ref.off(...), we search all views for the registration to remove.\n var self_1 = this;\n util_2.forEach(this.views_, function (viewQueryId, view) {\n cancelEvents = cancelEvents.concat(view.removeEventRegistration(eventRegistration, cancelError));\n if (view.isEmpty()) {\n delete self_1.views_[viewQueryId];\n // We'll deal with complete views later.\n if (!view\n .getQuery()\n .getQueryParams()\n .loadsAllData()) {\n removed.push(view.getQuery());\n }\n }\n });\n }\n else {\n // remove the callback from the specific view.\n var view = util_2.safeGet(this.views_, queryId);\n if (view) {\n cancelEvents = cancelEvents.concat(view.removeEventRegistration(eventRegistration, cancelError));\n if (view.isEmpty()) {\n delete this.views_[queryId];\n // We'll deal with complete views later.\n if (!view\n .getQuery()\n .getQueryParams()\n .loadsAllData()) {\n removed.push(view.getQuery());\n }\n }\n }\n }\n if (hadCompleteView && !this.hasCompleteView()) {\n // We removed our last complete view.\n removed.push(new SyncPoint.__referenceConstructor(query.repo, query.path));\n }\n return { removed: removed, events: cancelEvents };\n };\n /**\n * @return {!Array.}\n */\n SyncPoint.prototype.getQueryViews = function () {\n var _this = this;\n var values = Object.keys(this.views_).map(function (key) { return _this.views_[key]; });\n return values.filter(function (view) {\n return !view\n .getQuery()\n .getQueryParams()\n .loadsAllData();\n });\n };\n /**\n *\n * @param {!Path} path The path to the desired complete snapshot\n * @return {?Node} A complete cache, if it exists\n */\n SyncPoint.prototype.getCompleteServerCache = function (path) {\n var serverCache = null;\n util_2.forEach(this.views_, function (key, view) {\n serverCache = serverCache || view.getCompleteServerCache(path);\n });\n return serverCache;\n };\n /**\n * @param {!Query} query\n * @return {?View}\n */\n SyncPoint.prototype.viewForQuery = function (query) {\n var params = query.getQueryParams();\n if (params.loadsAllData()) {\n return this.getCompleteView();\n }\n else {\n var queryId = query.queryIdentifier();\n return util_2.safeGet(this.views_, queryId);\n }\n };\n /**\n * @param {!Query} query\n * @return {boolean}\n */\n SyncPoint.prototype.viewExistsForQuery = function (query) {\n return this.viewForQuery(query) != null;\n };\n /**\n * @return {boolean}\n */\n SyncPoint.prototype.hasCompleteView = function () {\n return this.getCompleteView() != null;\n };\n /**\n * @return {?View}\n */\n SyncPoint.prototype.getCompleteView = function () {\n var completeView = util_2.findValue(this.views_, function (view) {\n return view\n .getQuery()\n .getQueryParams()\n .loadsAllData();\n });\n return completeView || null;\n };\n return SyncPoint;\n}());\nexports.SyncPoint = SyncPoint;\n\n//# sourceMappingURL=SyncPoint.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/SyncPoint.js\n// module id = 48\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ChildrenNode_1 = require(\"../snap/ChildrenNode\");\nvar CacheNode_1 = require(\"./CacheNode\");\n/**\n * Stores the data we have cached for a view.\n *\n * serverSnap is the cached server data, eventSnap is the cached event data (server data plus any local writes).\n *\n * @constructor\n */\nvar ViewCache = /** @class */ (function () {\n /**\n *\n * @param {!CacheNode} eventCache_\n * @param {!CacheNode} serverCache_\n */\n function ViewCache(eventCache_, serverCache_) {\n this.eventCache_ = eventCache_;\n this.serverCache_ = serverCache_;\n }\n /**\n * @param {!Node} eventSnap\n * @param {boolean} complete\n * @param {boolean} filtered\n * @return {!ViewCache}\n */\n ViewCache.prototype.updateEventSnap = function (eventSnap, complete, filtered) {\n return new ViewCache(new CacheNode_1.CacheNode(eventSnap, complete, filtered), this.serverCache_);\n };\n /**\n * @param {!Node} serverSnap\n * @param {boolean} complete\n * @param {boolean} filtered\n * @return {!ViewCache}\n */\n ViewCache.prototype.updateServerSnap = function (serverSnap, complete, filtered) {\n return new ViewCache(this.eventCache_, new CacheNode_1.CacheNode(serverSnap, complete, filtered));\n };\n /**\n * @return {!CacheNode}\n */\n ViewCache.prototype.getEventCache = function () {\n return this.eventCache_;\n };\n /**\n * @return {?Node}\n */\n ViewCache.prototype.getCompleteEventSnap = function () {\n return this.eventCache_.isFullyInitialized()\n ? this.eventCache_.getNode()\n : null;\n };\n /**\n * @return {!CacheNode}\n */\n ViewCache.prototype.getServerCache = function () {\n return this.serverCache_;\n };\n /**\n * @return {?Node}\n */\n ViewCache.prototype.getCompleteServerSnap = function () {\n return this.serverCache_.isFullyInitialized()\n ? this.serverCache_.getNode()\n : null;\n };\n /**\n * @const\n * @type {ViewCache}\n */\n ViewCache.Empty = new ViewCache(new CacheNode_1.CacheNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, \n /*fullyInitialized=*/ false, \n /*filtered=*/ false), new CacheNode_1.CacheNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, \n /*fullyInitialized=*/ false, \n /*filtered=*/ false));\n return ViewCache;\n}());\nexports.ViewCache = ViewCache;\n\n//# sourceMappingURL=ViewCache.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/ViewCache.js\n// module id = 49\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Returns the delta from the previous call to get stats.\n *\n * @param collection_ The collection to \"listen\" to.\n * @constructor\n */\nvar StatsListener = /** @class */ (function () {\n function StatsListener(collection_) {\n this.collection_ = collection_;\n this.last_ = null;\n }\n StatsListener.prototype.get = function () {\n var newStats = this.collection_.get();\n var delta = util_1.clone(newStats);\n if (this.last_) {\n util_1.forEach(this.last_, function (stat, value) {\n delta[stat] = delta[stat] - value;\n });\n }\n this.last_ = newStats;\n return delta;\n };\n return StatsListener;\n}());\nexports.StatsListener = StatsListener;\n\n//# sourceMappingURL=StatsListener.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/stats/StatsListener.js\n// module id = 50\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar app_1 = require(\"@firebase/app\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar util_3 = require(\"@firebase/util\");\nvar util_4 = require(\"./util/util\");\nvar Path_1 = require(\"./util/Path\");\nvar VisibilityMonitor_1 = require(\"./util/VisibilityMonitor\");\nvar OnlineMonitor_1 = require(\"./util/OnlineMonitor\");\nvar util_5 = require(\"@firebase/util\");\nvar Connection_1 = require(\"../realtime/Connection\");\nvar util_6 = require(\"@firebase/util\");\nvar util_7 = require(\"@firebase/util\");\nvar ServerActions_1 = require(\"./ServerActions\");\nvar RECONNECT_MIN_DELAY = 1000;\nvar RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)\nvar RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)\nvar RECONNECT_DELAY_MULTIPLIER = 1.3;\nvar RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.\nvar SERVER_KILL_INTERRUPT_REASON = 'server_kill';\n// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.\nvar INVALID_AUTH_TOKEN_THRESHOLD = 3;\n/**\n * Firebase connection. Abstracts wire protocol and handles reconnecting.\n *\n * NOTE: All JSON objects sent to the realtime connection must have property names enclosed\n * in quotes to make sure the closure compiler does not minify them.\n */\nvar PersistentConnection = /** @class */ (function (_super) {\n tslib_1.__extends(PersistentConnection, _super);\n /**\n * @implements {ServerActions}\n * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to\n * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server\n * @param onConnectStatus_\n * @param onServerInfoUpdate_\n * @param authTokenProvider_\n * @param authOverride_\n */\n function PersistentConnection(repoInfo_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, authOverride_) {\n var _this = _super.call(this) || this;\n _this.repoInfo_ = repoInfo_;\n _this.onDataUpdate_ = onDataUpdate_;\n _this.onConnectStatus_ = onConnectStatus_;\n _this.onServerInfoUpdate_ = onServerInfoUpdate_;\n _this.authTokenProvider_ = authTokenProvider_;\n _this.authOverride_ = authOverride_;\n // Used for diagnostic logging.\n _this.id = PersistentConnection.nextPersistentConnectionId_++;\n _this.log_ = util_4.logWrapper('p:' + _this.id + ':');\n /** @private {Object} */\n _this.interruptReasons_ = {};\n _this.listens_ = {};\n _this.outstandingPuts_ = [];\n _this.outstandingPutCount_ = 0;\n _this.onDisconnectRequestQueue_ = [];\n _this.connected_ = false;\n _this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n _this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;\n _this.securityDebugCallback_ = null;\n _this.lastSessionId = null;\n /** @private {number|null} */\n _this.establishConnectionTimer_ = null;\n /** @private {boolean} */\n _this.visible_ = false;\n // Before we get connected, we keep a queue of pending messages to send.\n _this.requestCBHash_ = {};\n _this.requestNumber_ = 0;\n /** @private {?{\n * sendRequest(Object),\n * close()\n * }} */\n _this.realtime_ = null;\n /** @private {string|null} */\n _this.authToken_ = null;\n _this.forceTokenRefresh_ = false;\n _this.invalidAuthTokenCount_ = 0;\n _this.firstConnection_ = true;\n _this.lastConnectionAttemptTime_ = null;\n _this.lastConnectionEstablishedTime_ = null;\n if (authOverride_ && !util_7.isNodeSdk()) {\n throw new Error('Auth override specified in options, but not supported on non Node.js platforms');\n }\n _this.scheduleConnect_(0);\n VisibilityMonitor_1.VisibilityMonitor.getInstance().on('visible', _this.onVisible_, _this);\n if (repoInfo_.host.indexOf('fblocal') === -1) {\n OnlineMonitor_1.OnlineMonitor.getInstance().on('online', _this.onOnline_, _this);\n }\n return _this;\n }\n /**\n * @param {!string} action\n * @param {*} body\n * @param {function(*)=} onResponse\n * @protected\n */\n PersistentConnection.prototype.sendRequest = function (action, body, onResponse) {\n var curReqNum = ++this.requestNumber_;\n var msg = { r: curReqNum, a: action, b: body };\n this.log_(util_2.stringify(msg));\n util_3.assert(this.connected_, \"sendRequest call when we're not connected not allowed.\");\n this.realtime_.sendRequest(msg);\n if (onResponse) {\n this.requestCBHash_[curReqNum] = onResponse;\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.listen = function (query, currentHashFn, tag, onComplete) {\n var queryId = query.queryIdentifier();\n var pathString = query.path.toString();\n this.log_('Listen called for ' + pathString + ' ' + queryId);\n this.listens_[pathString] = this.listens_[pathString] || {};\n util_3.assert(query.getQueryParams().isDefault() ||\n !query.getQueryParams().loadsAllData(), 'listen() called for non-default but complete query');\n util_3.assert(!this.listens_[pathString][queryId], 'listen() called twice for same path/queryId.');\n var listenSpec = {\n onComplete: onComplete,\n hashFn: currentHashFn,\n query: query,\n tag: tag\n };\n this.listens_[pathString][queryId] = listenSpec;\n if (this.connected_) {\n this.sendListen_(listenSpec);\n }\n };\n /**\n * @param {!{onComplete(),\n * hashFn():!string,\n * query: !Query,\n * tag: ?number}} listenSpec\n * @private\n */\n PersistentConnection.prototype.sendListen_ = function (listenSpec) {\n var _this = this;\n var query = listenSpec.query;\n var pathString = query.path.toString();\n var queryId = query.queryIdentifier();\n this.log_('Listen on ' + pathString + ' for ' + queryId);\n var req = { /*path*/ p: pathString };\n var action = 'q';\n // Only bother to send query if it's non-default.\n if (listenSpec.tag) {\n req['q'] = query.queryObject();\n req['t'] = listenSpec.tag;\n }\n req['h'] = listenSpec.hashFn();\n this.sendRequest(action, req, function (message) {\n var payload = message['d'];\n var status = message['s'];\n // print warnings in any case...\n PersistentConnection.warnOnListenWarnings_(payload, query);\n var currentListenSpec = _this.listens_[pathString] && _this.listens_[pathString][queryId];\n // only trigger actions if the listen hasn't been removed and readded\n if (currentListenSpec === listenSpec) {\n _this.log_('listen response', message);\n if (status !== 'ok') {\n _this.removeListen_(pathString, queryId);\n }\n if (listenSpec.onComplete) {\n listenSpec.onComplete(status, payload);\n }\n }\n });\n };\n /**\n * @param {*} payload\n * @param {!Query} query\n * @private\n */\n PersistentConnection.warnOnListenWarnings_ = function (payload, query) {\n if (payload && typeof payload === 'object' && util_1.contains(payload, 'w')) {\n var warnings = util_1.safeGet(payload, 'w');\n if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {\n var indexSpec = '\".indexOn\": \"' +\n query\n .getQueryParams()\n .getIndex()\n .toString() +\n '\"';\n var indexPath = query.path.toString();\n util_4.warn(\"Using an unspecified index. Your data will be downloaded and \" +\n (\"filtered on the client. Consider adding \" + indexSpec + \" at \") +\n (indexPath + \" to your security rules for better performance.\"));\n }\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.refreshAuthToken = function (token) {\n this.authToken_ = token;\n this.log_('Auth token refreshed');\n if (this.authToken_) {\n this.tryAuth();\n }\n else {\n //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete\n //the credential so we dont become authenticated next time we connect.\n if (this.connected_) {\n this.sendRequest('unauth', {}, function () { });\n }\n }\n this.reduceReconnectDelayIfAdminCredential_(token);\n };\n /**\n * @param {!string} credential\n * @private\n */\n PersistentConnection.prototype.reduceReconnectDelayIfAdminCredential_ = function (credential) {\n // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).\n // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.\n var isFirebaseSecret = credential && credential.length === 40;\n if (isFirebaseSecret || util_5.isAdmin(credential)) {\n this.log_('Admin auth credential detected. Reducing max reconnect time.');\n this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n }\n };\n /**\n * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like\n * a auth revoked (the connection is closed).\n */\n PersistentConnection.prototype.tryAuth = function () {\n var _this = this;\n if (this.connected_ && this.authToken_) {\n var token_1 = this.authToken_;\n var authMethod = util_5.isValidFormat(token_1) ? 'auth' : 'gauth';\n var requestData = { cred: token_1 };\n if (this.authOverride_ === null) {\n requestData['noauth'] = true;\n }\n else if (typeof this.authOverride_ === 'object') {\n requestData['authvar'] = this.authOverride_;\n }\n this.sendRequest(authMethod, requestData, function (res) {\n var status = res['s'];\n var data = res['d'] || 'error';\n if (_this.authToken_ === token_1) {\n if (status === 'ok') {\n _this.invalidAuthTokenCount_ = 0;\n }\n else {\n // Triggers reconnect and force refresh for auth token\n _this.onAuthRevoked_(status, data);\n }\n }\n });\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.unlisten = function (query, tag) {\n var pathString = query.path.toString();\n var queryId = query.queryIdentifier();\n this.log_('Unlisten called for ' + pathString + ' ' + queryId);\n util_3.assert(query.getQueryParams().isDefault() ||\n !query.getQueryParams().loadsAllData(), 'unlisten() called for non-default but complete query');\n var listen = this.removeListen_(pathString, queryId);\n if (listen && this.connected_) {\n this.sendUnlisten_(pathString, queryId, query.queryObject(), tag);\n }\n };\n PersistentConnection.prototype.sendUnlisten_ = function (pathString, queryId, queryObj, tag) {\n this.log_('Unlisten on ' + pathString + ' for ' + queryId);\n var req = { /*path*/ p: pathString };\n var action = 'n';\n // Only bother sending queryId if it's non-default.\n if (tag) {\n req['q'] = queryObj;\n req['t'] = tag;\n }\n this.sendRequest(action, req);\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.onDisconnectPut = function (pathString, data, onComplete) {\n if (this.connected_) {\n this.sendOnDisconnect_('o', pathString, data, onComplete);\n }\n else {\n this.onDisconnectRequestQueue_.push({\n pathString: pathString,\n action: 'o',\n data: data,\n onComplete: onComplete\n });\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.onDisconnectMerge = function (pathString, data, onComplete) {\n if (this.connected_) {\n this.sendOnDisconnect_('om', pathString, data, onComplete);\n }\n else {\n this.onDisconnectRequestQueue_.push({\n pathString: pathString,\n action: 'om',\n data: data,\n onComplete: onComplete\n });\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.onDisconnectCancel = function (pathString, onComplete) {\n if (this.connected_) {\n this.sendOnDisconnect_('oc', pathString, null, onComplete);\n }\n else {\n this.onDisconnectRequestQueue_.push({\n pathString: pathString,\n action: 'oc',\n data: null,\n onComplete: onComplete\n });\n }\n };\n PersistentConnection.prototype.sendOnDisconnect_ = function (action, pathString, data, onComplete) {\n var request = { /*path*/ p: pathString, /*data*/ d: data };\n this.log_('onDisconnect ' + action, request);\n this.sendRequest(action, request, function (response) {\n if (onComplete) {\n setTimeout(function () {\n onComplete(response['s'], response['d']);\n }, Math.floor(0));\n }\n });\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {\n this.putInternal('p', pathString, data, onComplete, hash);\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.merge = function (pathString, data, onComplete, hash) {\n this.putInternal('m', pathString, data, onComplete, hash);\n };\n PersistentConnection.prototype.putInternal = function (action, pathString, data, onComplete, hash) {\n var request = {\n /*path*/ p: pathString,\n /*data*/ d: data\n };\n if (hash !== undefined)\n request['h'] = hash;\n // TODO: Only keep track of the most recent put for a given path?\n this.outstandingPuts_.push({\n action: action,\n request: request,\n onComplete: onComplete\n });\n this.outstandingPutCount_++;\n var index = this.outstandingPuts_.length - 1;\n if (this.connected_) {\n this.sendPut_(index);\n }\n else {\n this.log_('Buffering put: ' + pathString);\n }\n };\n PersistentConnection.prototype.sendPut_ = function (index) {\n var _this = this;\n var action = this.outstandingPuts_[index].action;\n var request = this.outstandingPuts_[index].request;\n var onComplete = this.outstandingPuts_[index].onComplete;\n this.outstandingPuts_[index].queued = this.connected_;\n this.sendRequest(action, request, function (message) {\n _this.log_(action + ' response', message);\n delete _this.outstandingPuts_[index];\n _this.outstandingPutCount_--;\n // Clean up array occasionally.\n if (_this.outstandingPutCount_ === 0) {\n _this.outstandingPuts_ = [];\n }\n if (onComplete)\n onComplete(message['s'], message['d']);\n });\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.reportStats = function (stats) {\n var _this = this;\n // If we're not connected, we just drop the stats.\n if (this.connected_) {\n var request = { /*counters*/ c: stats };\n this.log_('reportStats', request);\n this.sendRequest(/*stats*/ 's', request, function (result) {\n var status = result['s'];\n if (status !== 'ok') {\n var errorReason = result['d'];\n _this.log_('reportStats', 'Error sending stats: ' + errorReason);\n }\n });\n }\n };\n /**\n * @param {*} message\n * @private\n */\n PersistentConnection.prototype.onDataMessage_ = function (message) {\n if ('r' in message) {\n // this is a response\n this.log_('from server: ' + util_2.stringify(message));\n var reqNum = message['r'];\n var onResponse = this.requestCBHash_[reqNum];\n if (onResponse) {\n delete this.requestCBHash_[reqNum];\n onResponse(message['b']);\n }\n }\n else if ('error' in message) {\n throw 'A server-side error has occurred: ' + message['error'];\n }\n else if ('a' in message) {\n // a and b are action and body, respectively\n this.onDataPush_(message['a'], message['b']);\n }\n };\n PersistentConnection.prototype.onDataPush_ = function (action, body) {\n this.log_('handleServerMessage', action, body);\n if (action === 'd')\n this.onDataUpdate_(body['p'], body['d'], \n /*isMerge*/ false, body['t']);\n else if (action === 'm')\n this.onDataUpdate_(body['p'], body['d'], \n /*isMerge=*/ true, body['t']);\n else if (action === 'c')\n this.onListenRevoked_(body['p'], body['q']);\n else if (action === 'ac')\n this.onAuthRevoked_(body['s'], body['d']);\n else if (action === 'sd')\n this.onSecurityDebugPacket_(body);\n else\n util_4.error('Unrecognized action received from server: ' +\n util_2.stringify(action) +\n '\\nAre you using the latest client?');\n };\n PersistentConnection.prototype.onReady_ = function (timestamp, sessionId) {\n this.log_('connection ready');\n this.connected_ = true;\n this.lastConnectionEstablishedTime_ = new Date().getTime();\n this.handleTimestamp_(timestamp);\n this.lastSessionId = sessionId;\n if (this.firstConnection_) {\n this.sendConnectStats_();\n }\n this.restoreState_();\n this.firstConnection_ = false;\n this.onConnectStatus_(true);\n };\n PersistentConnection.prototype.scheduleConnect_ = function (timeout) {\n var _this = this;\n util_3.assert(!this.realtime_, \"Scheduling a connect when we're already connected/ing?\");\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n }\n // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating \"Security Error\" in\n // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).\n this.establishConnectionTimer_ = setTimeout(function () {\n _this.establishConnectionTimer_ = null;\n _this.establishConnection_();\n }, Math.floor(timeout));\n };\n /**\n * @param {boolean} visible\n * @private\n */\n PersistentConnection.prototype.onVisible_ = function (visible) {\n // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.\n if (visible &&\n !this.visible_ &&\n this.reconnectDelay_ === this.maxReconnectDelay_) {\n this.log_('Window became visible. Reducing delay.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n this.visible_ = visible;\n };\n PersistentConnection.prototype.onOnline_ = function (online) {\n if (online) {\n this.log_('Browser went online.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n else {\n this.log_('Browser went offline. Killing connection.');\n if (this.realtime_) {\n this.realtime_.close();\n }\n }\n };\n PersistentConnection.prototype.onRealtimeDisconnect_ = function () {\n this.log_('data client disconnected');\n this.connected_ = false;\n this.realtime_ = null;\n // Since we don't know if our sent transactions succeeded or not, we need to cancel them.\n this.cancelSentTransactions_();\n // Clear out the pending requests.\n this.requestCBHash_ = {};\n if (this.shouldReconnect_()) {\n if (!this.visible_) {\n this.log_(\"Window isn't visible. Delaying reconnect.\");\n this.reconnectDelay_ = this.maxReconnectDelay_;\n this.lastConnectionAttemptTime_ = new Date().getTime();\n }\n else if (this.lastConnectionEstablishedTime_) {\n // If we've been connected long enough, reset reconnect delay to minimum.\n var timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;\n if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT)\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n this.lastConnectionEstablishedTime_ = null;\n }\n var timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;\n var reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);\n reconnectDelay = Math.random() * reconnectDelay;\n this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');\n this.scheduleConnect_(reconnectDelay);\n // Adjust reconnect delay for next time.\n this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);\n }\n this.onConnectStatus_(false);\n };\n PersistentConnection.prototype.establishConnection_ = function () {\n if (this.shouldReconnect_()) {\n this.log_('Making a connection attempt');\n this.lastConnectionAttemptTime_ = new Date().getTime();\n this.lastConnectionEstablishedTime_ = null;\n var onDataMessage_1 = this.onDataMessage_.bind(this);\n var onReady_1 = this.onReady_.bind(this);\n var onDisconnect_1 = this.onRealtimeDisconnect_.bind(this);\n var connId_1 = this.id + ':' + PersistentConnection.nextConnectionId_++;\n var self_1 = this;\n var lastSessionId_1 = this.lastSessionId;\n var canceled_1 = false;\n var connection_1 = null;\n var closeFn_1 = function () {\n if (connection_1) {\n connection_1.close();\n }\n else {\n canceled_1 = true;\n onDisconnect_1();\n }\n };\n var sendRequestFn = function (msg) {\n util_3.assert(connection_1, \"sendRequest call when we're not connected not allowed.\");\n connection_1.sendRequest(msg);\n };\n this.realtime_ = {\n close: closeFn_1,\n sendRequest: sendRequestFn\n };\n var forceRefresh = this.forceTokenRefresh_;\n this.forceTokenRefresh_ = false;\n // First fetch auth token, and establish connection after fetching the token was successful\n this.authTokenProvider_\n .getToken(forceRefresh)\n .then(function (result) {\n if (!canceled_1) {\n util_4.log('getToken() completed. Creating connection.');\n self_1.authToken_ = result && result.accessToken;\n connection_1 = new Connection_1.Connection(connId_1, self_1.repoInfo_, onDataMessage_1, onReady_1, onDisconnect_1, \n /* onKill= */ function (reason) {\n util_4.warn(reason + ' (' + self_1.repoInfo_.toString() + ')');\n self_1.interrupt(SERVER_KILL_INTERRUPT_REASON);\n }, lastSessionId_1);\n }\n else {\n util_4.log('getToken() completed but was canceled');\n }\n })\n .then(null, function (error) {\n self_1.log_('Failed to get token: ' + error);\n if (!canceled_1) {\n if (util_6.CONSTANTS.NODE_ADMIN) {\n // This may be a critical error for the Admin Node.js SDK, so log a warning.\n // But getToken() may also just have temporarily failed, so we still want to\n // continue retrying.\n util_4.warn(error);\n }\n closeFn_1();\n }\n });\n }\n };\n /**\n * @param {string} reason\n */\n PersistentConnection.prototype.interrupt = function (reason) {\n util_4.log('Interrupting connection for reason: ' + reason);\n this.interruptReasons_[reason] = true;\n if (this.realtime_) {\n this.realtime_.close();\n }\n else {\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n this.establishConnectionTimer_ = null;\n }\n if (this.connected_) {\n this.onRealtimeDisconnect_();\n }\n }\n };\n /**\n * @param {string} reason\n */\n PersistentConnection.prototype.resume = function (reason) {\n util_4.log('Resuming connection for reason: ' + reason);\n delete this.interruptReasons_[reason];\n if (util_1.isEmpty(this.interruptReasons_)) {\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n };\n PersistentConnection.prototype.handleTimestamp_ = function (timestamp) {\n var delta = timestamp - new Date().getTime();\n this.onServerInfoUpdate_({ serverTimeOffset: delta });\n };\n PersistentConnection.prototype.cancelSentTransactions_ = function () {\n for (var i = 0; i < this.outstandingPuts_.length; i++) {\n var put = this.outstandingPuts_[i];\n if (put && /*hash*/ 'h' in put.request && put.queued) {\n if (put.onComplete)\n put.onComplete('disconnect');\n delete this.outstandingPuts_[i];\n this.outstandingPutCount_--;\n }\n }\n // Clean up array occasionally.\n if (this.outstandingPutCount_ === 0)\n this.outstandingPuts_ = [];\n };\n /**\n * @param {!string} pathString\n * @param {Array.<*>=} query\n * @private\n */\n PersistentConnection.prototype.onListenRevoked_ = function (pathString, query) {\n // Remove the listen and manufacture a \"permission_denied\" error for the failed listen.\n var queryId;\n if (!query) {\n queryId = 'default';\n }\n else {\n queryId = query.map(function (q) { return util_4.ObjectToUniqueKey(q); }).join('$');\n }\n var listen = this.removeListen_(pathString, queryId);\n if (listen && listen.onComplete)\n listen.onComplete('permission_denied');\n };\n /**\n * @param {!string} pathString\n * @param {!string} queryId\n * @return {{queries:Array., onComplete:function(string)}}\n * @private\n */\n PersistentConnection.prototype.removeListen_ = function (pathString, queryId) {\n var normalizedPathString = new Path_1.Path(pathString).toString(); // normalize path.\n var listen;\n if (this.listens_[normalizedPathString] !== undefined) {\n listen = this.listens_[normalizedPathString][queryId];\n delete this.listens_[normalizedPathString][queryId];\n if (util_1.getCount(this.listens_[normalizedPathString]) === 0) {\n delete this.listens_[normalizedPathString];\n }\n }\n else {\n // all listens for this path has already been removed\n listen = undefined;\n }\n return listen;\n };\n PersistentConnection.prototype.onAuthRevoked_ = function (statusCode, explanation) {\n util_4.log('Auth token revoked: ' + statusCode + '/' + explanation);\n this.authToken_ = null;\n this.forceTokenRefresh_ = true;\n this.realtime_.close();\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\n // We'll wait a couple times before logging the warning / increasing the\n // retry period since oauth tokens will report as \"invalid\" if they're\n // just expired. Plus there may be transient issues that resolve themselves.\n this.invalidAuthTokenCount_++;\n if (this.invalidAuthTokenCount_ >= INVALID_AUTH_TOKEN_THRESHOLD) {\n // Set a long reconnect delay because recovery is unlikely\n this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n // Notify the auth token provider that the token is invalid, which will log\n // a warning\n this.authTokenProvider_.notifyForInvalidToken();\n }\n }\n };\n PersistentConnection.prototype.onSecurityDebugPacket_ = function (body) {\n if (this.securityDebugCallback_) {\n this.securityDebugCallback_(body);\n }\n else {\n if ('msg' in body && typeof console !== 'undefined') {\n console.log('FIREBASE: ' + body['msg'].replace('\\n', '\\nFIREBASE: '));\n }\n }\n };\n PersistentConnection.prototype.restoreState_ = function () {\n var _this = this;\n //Re-authenticate ourselves if we have a credential stored.\n this.tryAuth();\n // Puts depend on having received the corresponding data update from the server before they complete, so we must\n // make sure to send listens before puts.\n util_1.forEach(this.listens_, function (pathString, queries) {\n util_1.forEach(queries, function (key, listenSpec) {\n _this.sendListen_(listenSpec);\n });\n });\n for (var i = 0; i < this.outstandingPuts_.length; i++) {\n if (this.outstandingPuts_[i])\n this.sendPut_(i);\n }\n while (this.onDisconnectRequestQueue_.length) {\n var request = this.onDisconnectRequestQueue_.shift();\n this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);\n }\n };\n /**\n * Sends client stats for first connection\n * @private\n */\n PersistentConnection.prototype.sendConnectStats_ = function () {\n var stats = {};\n var clientName = 'js';\n if (util_6.CONSTANTS.NODE_ADMIN) {\n clientName = 'admin_node';\n }\n else if (util_6.CONSTANTS.NODE_CLIENT) {\n clientName = 'node';\n }\n stats['sdk.' + clientName + '.' + app_1.default.SDK_VERSION.replace(/\\./g, '-')] = 1;\n if (util_7.isMobileCordova()) {\n stats['framework.cordova'] = 1;\n }\n else if (util_7.isReactNative()) {\n stats['framework.reactnative'] = 1;\n }\n this.reportStats(stats);\n };\n /**\n * @return {boolean}\n * @private\n */\n PersistentConnection.prototype.shouldReconnect_ = function () {\n var online = OnlineMonitor_1.OnlineMonitor.getInstance().currentlyOnline();\n return util_1.isEmpty(this.interruptReasons_) && online;\n };\n /**\n * @private\n */\n PersistentConnection.nextPersistentConnectionId_ = 0;\n /**\n * Counter for number of connections created. Mainly used for tagging in the logs\n * @type {number}\n * @private\n */\n PersistentConnection.nextConnectionId_ = 0;\n return PersistentConnection;\n}(ServerActions_1.ServerActions));\nexports.PersistentConnection = PersistentConnection;\n\n//# sourceMappingURL=PersistentConnection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/PersistentConnection.js\n// module id = 51\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Base class to be used if you want to emit events. Call the constructor with\n * the set of allowed event names.\n */\nvar EventEmitter = /** @class */ (function () {\n /**\n * @param {!Array.} allowedEvents_\n */\n function EventEmitter(allowedEvents_) {\n this.allowedEvents_ = allowedEvents_;\n this.listeners_ = {};\n util_1.assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');\n }\n /**\n * To be called by derived classes to trigger events.\n * @param {!string} eventType\n * @param {...*} var_args\n */\n EventEmitter.prototype.trigger = function (eventType) {\n var var_args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n var_args[_i - 1] = arguments[_i];\n }\n if (Array.isArray(this.listeners_[eventType])) {\n // Clone the list, since callbacks could add/remove listeners.\n var listeners = this.listeners_[eventType].slice();\n for (var i = 0; i < listeners.length; i++) {\n listeners[i].callback.apply(listeners[i].context, var_args);\n }\n }\n };\n EventEmitter.prototype.on = function (eventType, callback, context) {\n this.validateEventType_(eventType);\n this.listeners_[eventType] = this.listeners_[eventType] || [];\n this.listeners_[eventType].push({ callback: callback, context: context });\n var eventData = this.getInitialEvent(eventType);\n if (eventData) {\n callback.apply(context, eventData);\n }\n };\n EventEmitter.prototype.off = function (eventType, callback, context) {\n this.validateEventType_(eventType);\n var listeners = this.listeners_[eventType] || [];\n for (var i = 0; i < listeners.length; i++) {\n if (listeners[i].callback === callback &&\n (!context || context === listeners[i].context)) {\n listeners.splice(i, 1);\n return;\n }\n }\n };\n EventEmitter.prototype.validateEventType_ = function (eventType) {\n util_1.assert(this.allowedEvents_.find(function (et) {\n return et === eventType;\n }), 'Unknown event: ' + eventType);\n };\n return EventEmitter;\n}());\nexports.EventEmitter = EventEmitter;\n\n//# sourceMappingURL=EventEmitter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/EventEmitter.js\n// module id = 52\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../core/util/util\");\nvar storage_1 = require(\"../core/storage/storage\");\nvar Constants_1 = require(\"./Constants\");\nvar TransportManager_1 = require(\"./TransportManager\");\n// Abort upgrade attempt if it takes longer than 60s.\nvar UPGRADE_TIMEOUT = 60000;\n// For some transports (WebSockets), we need to \"validate\" the transport by exchanging a few requests and responses.\n// If we haven't sent enough requests within 5s, we'll start sending noop ping requests.\nvar DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;\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)\n// then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout\n// but we've sent/received enough bytes, we don't cancel the connection.\nvar BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;\nvar BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;\nvar MESSAGE_TYPE = 't';\nvar MESSAGE_DATA = 'd';\nvar CONTROL_SHUTDOWN = 's';\nvar CONTROL_RESET = 'r';\nvar CONTROL_ERROR = 'e';\nvar CONTROL_PONG = 'o';\nvar SWITCH_ACK = 'a';\nvar END_TRANSMISSION = 'n';\nvar PING = 'p';\nvar SERVER_HELLO = 'h';\n/**\n * Creates a new real-time connection to the server using whichever method works\n * best in the current browser.\n *\n * @constructor\n */\nvar Connection = /** @class */ (function () {\n /**\n * @param {!string} id - an id for this connection\n * @param {!RepoInfo} repoInfo_ - the info for the endpoint to connect to\n * @param {function(Object)} onMessage_ - the callback to be triggered when a server-push message arrives\n * @param {function(number, string)} onReady_ - the callback to be triggered when this connection is ready to send messages.\n * @param {function()} onDisconnect_ - the callback to be triggered when a connection was lost\n * @param {function(string)} onKill_ - the callback to be triggered when this connection has permanently shut down.\n * @param {string=} lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server\n */\n function Connection(id, repoInfo_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {\n this.id = id;\n this.repoInfo_ = repoInfo_;\n this.onMessage_ = onMessage_;\n this.onReady_ = onReady_;\n this.onDisconnect_ = onDisconnect_;\n this.onKill_ = onKill_;\n this.lastSessionId = lastSessionId;\n this.connectionCount = 0;\n this.pendingDataMessages = [];\n this.state_ = 0 /* CONNECTING */;\n this.log_ = util_1.logWrapper('c:' + this.id + ':');\n this.transportManager_ = new TransportManager_1.TransportManager(repoInfo_);\n this.log_('Connection created');\n this.start_();\n }\n /**\n * Starts a connection attempt\n * @private\n */\n Connection.prototype.start_ = function () {\n var _this = this;\n var conn = this.transportManager_.initialTransport();\n this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, undefined, this.lastSessionId);\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;\n var onMessageReceived = this.connReceiver_(this.conn_);\n var onConnectionLost = this.disconnReceiver_(this.conn_);\n this.tx_ = this.conn_;\n this.rx_ = this.conn_;\n this.secondaryConn_ = null;\n this.isHealthy_ = false;\n /*\n * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.\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.\n * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should\n * still have the context of your originating frame.\n */\n setTimeout(function () {\n // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it\n _this.conn_ && _this.conn_.open(onMessageReceived, onConnectionLost);\n }, Math.floor(0));\n var healthyTimeout_ms = conn['healthyTimeout'] || 0;\n if (healthyTimeout_ms > 0) {\n this.healthyTimeout_ = util_1.setTimeoutNonBlocking(function () {\n _this.healthyTimeout_ = null;\n if (!_this.isHealthy_) {\n if (_this.conn_ &&\n _this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {\n _this.log_('Connection exceeded healthy timeout but has received ' +\n _this.conn_.bytesReceived +\n ' bytes. Marking connection healthy.');\n _this.isHealthy_ = true;\n _this.conn_.markConnectionHealthy();\n }\n else if (_this.conn_ &&\n _this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {\n _this.log_('Connection exceeded healthy timeout but has sent ' +\n _this.conn_.bytesSent +\n ' bytes. Leaving connection alive.');\n // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to\n // the server.\n }\n else {\n _this.log_('Closing unhealthy connection after timeout.');\n _this.close();\n }\n }\n }, Math.floor(healthyTimeout_ms));\n }\n };\n /**\n * @return {!string}\n * @private\n */\n Connection.prototype.nextTransportId_ = function () {\n return 'c:' + this.id + ':' + this.connectionCount++;\n };\n Connection.prototype.disconnReceiver_ = function (conn) {\n var _this = this;\n return function (everConnected) {\n if (conn === _this.conn_) {\n _this.onConnectionLost_(everConnected);\n }\n else if (conn === _this.secondaryConn_) {\n _this.log_('Secondary connection lost.');\n _this.onSecondaryConnectionLost_();\n }\n else {\n _this.log_('closing an old connection');\n }\n };\n };\n Connection.prototype.connReceiver_ = function (conn) {\n var _this = this;\n return function (message) {\n if (_this.state_ != 2 /* DISCONNECTED */) {\n if (conn === _this.rx_) {\n _this.onPrimaryMessageReceived_(message);\n }\n else if (conn === _this.secondaryConn_) {\n _this.onSecondaryMessageReceived_(message);\n }\n else {\n _this.log_('message on old connection');\n }\n }\n };\n };\n /**\n *\n * @param {Object} dataMsg An arbitrary data message to be sent to the server\n */\n Connection.prototype.sendRequest = function (dataMsg) {\n // wrap in a data message envelope and send it on\n var msg = { t: 'd', d: dataMsg };\n this.sendData_(msg);\n };\n Connection.prototype.tryCleanupConnection = function () {\n if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {\n this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);\n this.conn_ = this.secondaryConn_;\n this.secondaryConn_ = null;\n // the server will shutdown the old connection\n }\n };\n Connection.prototype.onSecondaryControl_ = function (controlData) {\n if (MESSAGE_TYPE in controlData) {\n var cmd = controlData[MESSAGE_TYPE];\n if (cmd === SWITCH_ACK) {\n this.upgradeIfSecondaryHealthy_();\n }\n else if (cmd === CONTROL_RESET) {\n // Most likely the session wasn't valid. Abandon the switch attempt\n this.log_('Got a reset on secondary, closing it');\n this.secondaryConn_.close();\n // If we were already using this connection for something, than we need to fully close\n if (this.tx_ === this.secondaryConn_ ||\n this.rx_ === this.secondaryConn_) {\n this.close();\n }\n }\n else if (cmd === CONTROL_PONG) {\n this.log_('got pong on secondary.');\n this.secondaryResponsesRequired_--;\n this.upgradeIfSecondaryHealthy_();\n }\n }\n };\n Connection.prototype.onSecondaryMessageReceived_ = function (parsedData) {\n var layer = util_1.requireKey('t', parsedData);\n var data = util_1.requireKey('d', parsedData);\n if (layer == 'c') {\n this.onSecondaryControl_(data);\n }\n else if (layer == 'd') {\n // got a data message, but we're still second connection. Need to buffer it up\n this.pendingDataMessages.push(data);\n }\n else {\n throw new Error('Unknown protocol layer: ' + layer);\n }\n };\n Connection.prototype.upgradeIfSecondaryHealthy_ = function () {\n if (this.secondaryResponsesRequired_ <= 0) {\n this.log_('Secondary connection is healthy.');\n this.isHealthy_ = true;\n this.secondaryConn_.markConnectionHealthy();\n this.proceedWithUpgrade_();\n }\n else {\n // Send a ping to make sure the connection is healthy.\n this.log_('sending ping on secondary.');\n this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });\n }\n };\n Connection.prototype.proceedWithUpgrade_ = function () {\n // tell this connection to consider itself open\n this.secondaryConn_.start();\n // send ack\n this.log_('sending client ack on secondary');\n this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });\n // send end packet on primary transport, switch to sending on this one\n // can receive on this one, buffer responses until end received on primary transport\n this.log_('Ending transmission on primary');\n this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });\n this.tx_ = this.secondaryConn_;\n this.tryCleanupConnection();\n };\n Connection.prototype.onPrimaryMessageReceived_ = function (parsedData) {\n // Must refer to parsedData properties in quotes, so closure doesn't touch them.\n var layer = util_1.requireKey('t', parsedData);\n var data = util_1.requireKey('d', parsedData);\n if (layer == 'c') {\n this.onControl_(data);\n }\n else if (layer == 'd') {\n this.onDataMessage_(data);\n }\n };\n Connection.prototype.onDataMessage_ = function (message) {\n this.onPrimaryResponse_();\n // We don't do anything with data messages, just kick them up a level\n this.onMessage_(message);\n };\n Connection.prototype.onPrimaryResponse_ = function () {\n if (!this.isHealthy_) {\n this.primaryResponsesRequired_--;\n if (this.primaryResponsesRequired_ <= 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n this.conn_.markConnectionHealthy();\n }\n }\n };\n Connection.prototype.onControl_ = function (controlData) {\n var cmd = util_1.requireKey(MESSAGE_TYPE, controlData);\n if (MESSAGE_DATA in controlData) {\n var payload = controlData[MESSAGE_DATA];\n if (cmd === SERVER_HELLO) {\n this.onHandshake_(payload);\n }\n else if (cmd === END_TRANSMISSION) {\n this.log_('recvd end transmission on primary');\n this.rx_ = this.secondaryConn_;\n for (var i = 0; i < this.pendingDataMessages.length; ++i) {\n this.onDataMessage_(this.pendingDataMessages[i]);\n }\n this.pendingDataMessages = [];\n this.tryCleanupConnection();\n }\n else if (cmd === CONTROL_SHUTDOWN) {\n // This was previously the 'onKill' callback passed to the lower-level connection\n // payload in this case is the reason for the shutdown. Generally a human-readable error\n this.onConnectionShutdown_(payload);\n }\n else if (cmd === CONTROL_RESET) {\n // payload in this case is the host we should contact\n this.onReset_(payload);\n }\n else if (cmd === CONTROL_ERROR) {\n util_1.error('Server Error: ' + payload);\n }\n else if (cmd === CONTROL_PONG) {\n this.log_('got pong on primary.');\n this.onPrimaryResponse_();\n this.sendPingOnPrimaryIfNecessary_();\n }\n else {\n util_1.error('Unknown control packet command: ' + cmd);\n }\n }\n };\n /**\n *\n * @param {Object} handshake The handshake data returned from the server\n * @private\n */\n Connection.prototype.onHandshake_ = function (handshake) {\n var timestamp = handshake.ts;\n var version = handshake.v;\n var host = handshake.h;\n this.sessionId = handshake.s;\n this.repoInfo_.updateHost(host);\n // if we've already closed the connection, then don't bother trying to progress further\n if (this.state_ == 0 /* CONNECTING */) {\n this.conn_.start();\n this.onConnectionEstablished_(this.conn_, timestamp);\n if (Constants_1.PROTOCOL_VERSION !== version) {\n util_1.warn('Protocol version mismatch detected');\n }\n // TODO: do we want to upgrade? when? maybe a delay?\n this.tryStartUpgrade_();\n }\n };\n Connection.prototype.tryStartUpgrade_ = function () {\n var conn = this.transportManager_.upgradeTransport();\n if (conn) {\n this.startUpgrade_(conn);\n }\n };\n Connection.prototype.startUpgrade_ = function (conn) {\n var _this = this;\n this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.sessionId);\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n this.secondaryResponsesRequired_ =\n conn['responsesRequiredToBeHealthy'] || 0;\n var onMessage = this.connReceiver_(this.secondaryConn_);\n var onDisconnect = this.disconnReceiver_(this.secondaryConn_);\n this.secondaryConn_.open(onMessage, onDisconnect);\n // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.\n util_1.setTimeoutNonBlocking(function () {\n if (_this.secondaryConn_) {\n _this.log_('Timed out trying to upgrade.');\n _this.secondaryConn_.close();\n }\n }, Math.floor(UPGRADE_TIMEOUT));\n };\n Connection.prototype.onReset_ = function (host) {\n this.log_('Reset packet received. New host: ' + host);\n this.repoInfo_.updateHost(host);\n // TODO: if we're already \"connected\", we need to trigger a disconnect at the next layer up.\n // We don't currently support resets after the connection has already been established\n if (this.state_ === 1 /* CONNECTED */) {\n this.close();\n }\n else {\n // Close whatever connections we have open and start again.\n this.closeConnections_();\n this.start_();\n }\n };\n Connection.prototype.onConnectionEstablished_ = function (conn, timestamp) {\n var _this = this;\n this.log_('Realtime connection established.');\n this.conn_ = conn;\n this.state_ = 1 /* CONNECTED */;\n if (this.onReady_) {\n this.onReady_(timestamp, this.sessionId);\n this.onReady_ = null;\n }\n // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,\n // send some pings.\n if (this.primaryResponsesRequired_ === 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n }\n else {\n util_1.setTimeoutNonBlocking(function () {\n _this.sendPingOnPrimaryIfNecessary_();\n }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));\n }\n };\n Connection.prototype.sendPingOnPrimaryIfNecessary_ = function () {\n // If the connection isn't considered healthy yet, we'll send a noop ping packet request.\n if (!this.isHealthy_ && this.state_ === 1 /* CONNECTED */) {\n this.log_('sending ping on primary.');\n this.sendData_({ t: 'c', d: { t: PING, d: {} } });\n }\n };\n Connection.prototype.onSecondaryConnectionLost_ = function () {\n var conn = this.secondaryConn_;\n this.secondaryConn_ = null;\n if (this.tx_ === conn || this.rx_ === conn) {\n // we are relying on this connection already in some capacity. Therefore, a failure is real\n this.close();\n }\n };\n /**\n *\n * @param {boolean} everConnected Whether or not the connection ever reached a server. Used to determine if\n * we should flush the host cache\n * @private\n */\n Connection.prototype.onConnectionLost_ = function (everConnected) {\n this.conn_ = null;\n // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting\n // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.\n if (!everConnected && this.state_ === 0 /* CONNECTING */) {\n this.log_('Realtime connection failed.');\n // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away\n if (this.repoInfo_.isCacheableHost()) {\n storage_1.PersistentStorage.remove('host:' + this.repoInfo_.host);\n // reset the internal host to what we would show the user, i.e. .firebaseio.com\n this.repoInfo_.internalHost = this.repoInfo_.host;\n }\n }\n else if (this.state_ === 1 /* CONNECTED */) {\n this.log_('Realtime connection lost.');\n }\n this.close();\n };\n /**\n *\n * @param {string} reason\n * @private\n */\n Connection.prototype.onConnectionShutdown_ = function (reason) {\n this.log_('Connection shutdown command received. Shutting down...');\n if (this.onKill_) {\n this.onKill_(reason);\n this.onKill_ = null;\n }\n // We intentionally don't want to fire onDisconnect (kill is a different case),\n // so clear the callback.\n this.onDisconnect_ = null;\n this.close();\n };\n Connection.prototype.sendData_ = function (data) {\n if (this.state_ !== 1 /* CONNECTED */) {\n throw 'Connection is not connected';\n }\n else {\n this.tx_.send(data);\n }\n };\n /**\n * Cleans up this connection, calling the appropriate callbacks\n */\n Connection.prototype.close = function () {\n if (this.state_ !== 2 /* DISCONNECTED */) {\n this.log_('Closing realtime connection.');\n this.state_ = 2 /* DISCONNECTED */;\n this.closeConnections_();\n if (this.onDisconnect_) {\n this.onDisconnect_();\n this.onDisconnect_ = null;\n }\n }\n };\n /**\n *\n * @private\n */\n Connection.prototype.closeConnections_ = function () {\n this.log_('Shutting down all connections');\n if (this.conn_) {\n this.conn_.close();\n this.conn_ = null;\n }\n if (this.secondaryConn_) {\n this.secondaryConn_.close();\n this.secondaryConn_ = null;\n }\n if (this.healthyTimeout_) {\n clearTimeout(this.healthyTimeout_);\n this.healthyTimeout_ = null;\n }\n };\n return Connection;\n}());\nexports.Connection = Connection;\n\n//# sourceMappingURL=Connection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/Connection.js\n// module id = 53\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../core/util/util\");\nvar CountedSet_1 = require(\"../core/util/CountedSet\");\nvar StatsManager_1 = require(\"../core/stats/StatsManager\");\nvar PacketReceiver_1 = require(\"./polling/PacketReceiver\");\nvar Constants_1 = require(\"./Constants\");\nvar util_2 = require(\"@firebase/util\");\nvar util_3 = require(\"@firebase/util\");\n// URL query parameters associated with longpolling\nexports.FIREBASE_LONGPOLL_START_PARAM = 'start';\nexports.FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';\nexports.FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';\nexports.FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';\nexports.FIREBASE_LONGPOLL_ID_PARAM = 'id';\nexports.FIREBASE_LONGPOLL_PW_PARAM = 'pw';\nexports.FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';\nexports.FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';\nexports.FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';\nexports.FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';\nexports.FIREBASE_LONGPOLL_DATA_PARAM = 'd';\nexports.FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM = 'disconn';\nexports.FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';\n//Data size constants.\n//TODO: Perf: the maximum length actually differs from browser to browser.\n// We should check what browser we're on and set accordingly.\nvar MAX_URL_DATA_SIZE = 1870;\nvar SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=\nvar MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;\n/**\n * Keepalive period\n * send a fresh request at minimum every 25 seconds. Opera has a maximum request\n * length of 30 seconds that we can't exceed.\n * @const\n * @type {number}\n */\nvar KEEPALIVE_REQUEST_INTERVAL = 25000;\n/**\n * How long to wait before aborting a long-polling connection attempt.\n * @const\n * @type {number}\n */\nvar LP_CONNECT_TIMEOUT = 30000;\n/**\n * This class manages a single long-polling connection.\n *\n * @constructor\n * @implements {Transport}\n */\nvar BrowserPollConnection = /** @class */ (function () {\n /**\n * @param {string} connId An identifier for this connection, used for logging\n * @param {RepoInfo} repoInfo The info for the endpoint to send data to.\n * @param {string=} transportSessionId Optional transportSessionid if we are reconnecting for an existing\n * transport session\n * @param {string=} lastSessionId Optional lastSessionId if the PersistentConnection has already created a\n * connection previously\n */\n function BrowserPollConnection(connId, repoInfo, transportSessionId, lastSessionId) {\n this.connId = connId;\n this.repoInfo = repoInfo;\n this.transportSessionId = transportSessionId;\n this.lastSessionId = lastSessionId;\n this.bytesSent = 0;\n this.bytesReceived = 0;\n this.everConnected_ = false;\n this.log_ = util_1.logWrapper(connId);\n this.stats_ = StatsManager_1.StatsManager.getCollection(repoInfo);\n this.urlFn = function (params) {\n return repoInfo.connectionURL(Constants_1.LONG_POLLING, params);\n };\n }\n /**\n *\n * @param {function(Object)} onMessage Callback when messages arrive\n * @param {function()} onDisconnect Callback with connection lost.\n */\n BrowserPollConnection.prototype.open = function (onMessage, onDisconnect) {\n var _this = this;\n this.curSegmentNum = 0;\n this.onDisconnect_ = onDisconnect;\n this.myPacketOrderer = new PacketReceiver_1.PacketReceiver(onMessage);\n this.isClosed_ = false;\n this.connectTimeoutTimer_ = setTimeout(function () {\n _this.log_('Timed out trying to connect.');\n // Make sure we clear the host cache\n _this.onClosed_();\n _this.connectTimeoutTimer_ = null;\n }, Math.floor(LP_CONNECT_TIMEOUT));\n // Ensure we delay the creation of the iframe until the DOM is loaded.\n util_1.executeWhenDOMReady(function () {\n if (_this.isClosed_)\n return;\n //Set up a callback that gets triggered once a connection is set up.\n _this.scriptTagHolder = new FirebaseIFrameScriptHolder(function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var command = args[0], arg1 = args[1], arg2 = args[2], arg3 = args[3], arg4 = args[4];\n _this.incrementIncomingBytes_(args);\n if (!_this.scriptTagHolder)\n return; // we closed the connection.\n if (_this.connectTimeoutTimer_) {\n clearTimeout(_this.connectTimeoutTimer_);\n _this.connectTimeoutTimer_ = null;\n }\n _this.everConnected_ = true;\n if (command == exports.FIREBASE_LONGPOLL_START_PARAM) {\n _this.id = arg1;\n _this.password = arg2;\n }\n else if (command === exports.FIREBASE_LONGPOLL_CLOSE_COMMAND) {\n // Don't clear the host cache. We got a response from the server, so we know it's reachable\n if (arg1) {\n // We aren't expecting any more data (other than what the server's already in the process of sending us\n // through our already open polls), so don't send any more.\n _this.scriptTagHolder.sendNewPolls = false;\n // arg1 in this case is the last response number sent by the server. We should try to receive\n // all of the responses up to this one before closing\n _this.myPacketOrderer.closeAfter(arg1, function () {\n _this.onClosed_();\n });\n }\n else {\n _this.onClosed_();\n }\n }\n else {\n throw new Error('Unrecognized command received: ' + command);\n }\n }, function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var pN = args[0], data = args[1];\n _this.incrementIncomingBytes_(args);\n _this.myPacketOrderer.handleResponse(pN, data);\n }, function () {\n _this.onClosed_();\n }, _this.urlFn);\n //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results\n //from cache.\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_START_PARAM] = 't';\n urlParams[exports.FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);\n if (_this.scriptTagHolder.uniqueCallbackIdentifier)\n urlParams[exports.FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] = _this.scriptTagHolder.uniqueCallbackIdentifier;\n urlParams[Constants_1.VERSION_PARAM] = Constants_1.PROTOCOL_VERSION;\n if (_this.transportSessionId) {\n urlParams[Constants_1.TRANSPORT_SESSION_PARAM] = _this.transportSessionId;\n }\n if (_this.lastSessionId) {\n urlParams[Constants_1.LAST_SESSION_PARAM] = _this.lastSessionId;\n }\n if (!util_3.isNodeSdk() &&\n typeof location !== 'undefined' &&\n location.href &&\n location.href.indexOf(Constants_1.FORGE_DOMAIN) !== -1) {\n urlParams[Constants_1.REFERER_PARAM] = Constants_1.FORGE_REF;\n }\n var connectURL = _this.urlFn(urlParams);\n _this.log_('Connecting via long-poll to ' + connectURL);\n _this.scriptTagHolder.addTag(connectURL, function () {\n /* do nothing */\n });\n });\n };\n /**\n * Call this when a handshake has completed successfully and we want to consider the connection established\n */\n BrowserPollConnection.prototype.start = function () {\n this.scriptTagHolder.startLongPoll(this.id, this.password);\n this.addDisconnectPingFrame(this.id, this.password);\n };\n /**\n * Forces long polling to be considered as a potential transport\n */\n BrowserPollConnection.forceAllow = function () {\n BrowserPollConnection.forceAllow_ = true;\n };\n /**\n * Forces longpolling to not be considered as a potential transport\n */\n BrowserPollConnection.forceDisallow = function () {\n BrowserPollConnection.forceDisallow_ = true;\n };\n // Static method, use string literal so it can be accessed in a generic way\n BrowserPollConnection.isAvailable = function () {\n // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in\n // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).\n return (BrowserPollConnection.forceAllow_ ||\n (!BrowserPollConnection.forceDisallow_ &&\n typeof document !== 'undefined' &&\n document.createElement != null &&\n !util_1.isChromeExtensionContentScript() &&\n !util_1.isWindowsStoreApp() &&\n !util_3.isNodeSdk()));\n };\n /**\n * No-op for polling\n */\n BrowserPollConnection.prototype.markConnectionHealthy = function () { };\n /**\n * Stops polling and cleans up the iframe\n * @private\n */\n BrowserPollConnection.prototype.shutdown_ = function () {\n this.isClosed_ = true;\n if (this.scriptTagHolder) {\n this.scriptTagHolder.close();\n this.scriptTagHolder = null;\n }\n //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.\n if (this.myDisconnFrame) {\n document.body.removeChild(this.myDisconnFrame);\n this.myDisconnFrame = null;\n }\n if (this.connectTimeoutTimer_) {\n clearTimeout(this.connectTimeoutTimer_);\n this.connectTimeoutTimer_ = null;\n }\n };\n /**\n * Triggered when this transport is closed\n * @private\n */\n BrowserPollConnection.prototype.onClosed_ = function () {\n if (!this.isClosed_) {\n this.log_('Longpoll is closing itself');\n this.shutdown_();\n if (this.onDisconnect_) {\n this.onDisconnect_(this.everConnected_);\n this.onDisconnect_ = null;\n }\n }\n };\n /**\n * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server\n * that we've left.\n */\n BrowserPollConnection.prototype.close = function () {\n if (!this.isClosed_) {\n this.log_('Longpoll is being closed.');\n this.shutdown_();\n }\n };\n /**\n * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then\n * broken into chunks (since URLs have a small maximum length).\n * @param {!Object} data The JSON data to transmit.\n */\n BrowserPollConnection.prototype.send = function (data) {\n var dataStr = util_2.stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n //first, lets get the base64-encoded data\n var base64data = util_2.base64Encode(dataStr);\n //We can only fit a certain amount in each URL, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n var dataSegs = util_1.splitStringBySize(base64data, MAX_PAYLOAD_SIZE);\n //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number\n //of segments so that we can reassemble the packet on the server.\n for (var i = 0; i < dataSegs.length; i++) {\n this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);\n this.curSegmentNum++;\n }\n };\n /**\n * This is how we notify the server that we're leaving.\n * We aren't able to send requests with DHTML on a window close event, but we can\n * trigger XHR requests in some browsers (everything but Opera basically).\n * @param {!string} id\n * @param {!string} pw\n */\n BrowserPollConnection.prototype.addDisconnectPingFrame = function (id, pw) {\n if (util_3.isNodeSdk())\n return;\n this.myDisconnFrame = document.createElement('iframe');\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = id;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = pw;\n this.myDisconnFrame.src = this.urlFn(urlParams);\n this.myDisconnFrame.style.display = 'none';\n document.body.appendChild(this.myDisconnFrame);\n };\n /**\n * Used to track the bytes received by this client\n * @param {*} args\n * @private\n */\n BrowserPollConnection.prototype.incrementIncomingBytes_ = function (args) {\n // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.\n var bytesReceived = util_2.stringify(args).length;\n this.bytesReceived += bytesReceived;\n this.stats_.incrementCounter('bytes_received', bytesReceived);\n };\n return BrowserPollConnection;\n}());\nexports.BrowserPollConnection = BrowserPollConnection;\n/*********************************************************************************************\n * A wrapper around an iframe that is used as a long-polling script holder.\n * @constructor\n *********************************************************************************************/\nvar FirebaseIFrameScriptHolder = /** @class */ (function () {\n /**\n * @param commandCB - The callback to be called when control commands are recevied from the server.\n * @param onMessageCB - The callback to be triggered when responses arrive from the server.\n * @param onDisconnect - The callback to be triggered when this tag holder is closed\n * @param urlFn - A function that provides the URL of the endpoint to send data to.\n */\n function FirebaseIFrameScriptHolder(commandCB, onMessageCB, onDisconnect, urlFn) {\n this.onDisconnect = onDisconnect;\n this.urlFn = urlFn;\n //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause\n //problems in some browsers.\n /**\n * @type {CountedSet.}\n */\n this.outstandingRequests = new CountedSet_1.CountedSet();\n //A queue of the pending segments waiting for transmission to the server.\n this.pendingSegs = [];\n //A serial number. We use this for two things:\n // 1) A way to ensure the browser doesn't cache responses to polls\n // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The\n // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute\n // JSONP code in the order it was added to the iframe.\n this.currentSerial = Math.floor(Math.random() * 100000000);\n // This gets set to false when we're \"closing down\" the connection (e.g. we're switching transports but there's still\n // incoming data from the server that we're waiting for).\n this.sendNewPolls = true;\n if (!util_3.isNodeSdk()) {\n //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the\n //iframes where we put the long-polling script tags. We have two callbacks:\n // 1) Command Callback - Triggered for control issues, like starting a connection.\n // 2) Message Callback - Triggered when new data arrives.\n this.uniqueCallbackIdentifier = util_1.LUIDGenerator();\n window[exports.FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;\n window[exports.FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] = onMessageCB;\n //Create an iframe for us to add script tags to.\n this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();\n // Set the iframe's contents.\n var script = '';\n // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient\n // for ie9, but ie8 needs to do it again in the document itself.\n if (this.myIFrame.src &&\n this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {\n var currentDomain = document.domain;\n script = '';\n }\n var iframeContents = '' + script + '';\n try {\n this.myIFrame.doc.open();\n this.myIFrame.doc.write(iframeContents);\n this.myIFrame.doc.close();\n }\n catch (e) {\n util_1.log('frame writing exception');\n if (e.stack) {\n util_1.log(e.stack);\n }\n util_1.log(e);\n }\n }\n else {\n this.commandCB = commandCB;\n this.onMessageCB = onMessageCB;\n }\n }\n /**\n * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can\n * actually use.\n * @private\n * @return {Element}\n */\n FirebaseIFrameScriptHolder.createIFrame_ = function () {\n var iframe = document.createElement('iframe');\n iframe.style.display = 'none';\n // This is necessary in order to initialize the document inside the iframe\n if (document.body) {\n document.body.appendChild(iframe);\n try {\n // If document.domain has been modified in IE, this will throw an error, and we need to set the\n // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute\n // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.\n var a = iframe.contentWindow.document;\n if (!a) {\n // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.\n util_1.log('No IE domain setting required');\n }\n }\n catch (e) {\n var domain = document.domain;\n iframe.src =\n \"javascript:void((function(){document.open();document.domain='\" +\n domain +\n \"';document.close();})())\";\n }\n }\n else {\n // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this\n // never gets hit.\n throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';\n }\n // Get the document of the iframe in a browser-specific way.\n if (iframe.contentDocument) {\n iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari\n }\n else if (iframe.contentWindow) {\n iframe.doc = iframe.contentWindow.document; // Internet Explorer\n }\n else if (iframe.document) {\n iframe.doc = iframe.document; //others?\n }\n return iframe;\n };\n /**\n * Cancel all outstanding queries and remove the frame.\n */\n FirebaseIFrameScriptHolder.prototype.close = function () {\n var _this = this;\n //Mark this iframe as dead, so no new requests are sent.\n this.alive = false;\n if (this.myIFrame) {\n //We have to actually remove all of the html inside this iframe before removing it from the\n //window, or IE will continue loading and executing the script tags we've already added, which\n //can lead to some errors being thrown. Setting innerHTML seems to be the easiest way to do this.\n this.myIFrame.doc.body.innerHTML = '';\n setTimeout(function () {\n if (_this.myIFrame !== null) {\n document.body.removeChild(_this.myIFrame);\n _this.myIFrame = null;\n }\n }, Math.floor(0));\n }\n if (util_3.isNodeSdk() && this.myID) {\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM] = 't';\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n var theURL = this.urlFn(urlParams);\n FirebaseIFrameScriptHolder.nodeRestRequest(theURL);\n }\n // Protect from being called recursively.\n var onDisconnect = this.onDisconnect;\n if (onDisconnect) {\n this.onDisconnect = null;\n onDisconnect();\n }\n };\n /**\n * Actually start the long-polling session by adding the first script tag(s) to the iframe.\n * @param {!string} id - The ID of this connection\n * @param {!string} pw - The password for this connection\n */\n FirebaseIFrameScriptHolder.prototype.startLongPoll = function (id, pw) {\n this.myID = id;\n this.myPW = pw;\n this.alive = true;\n //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.\n while (this.newRequest_()) { }\n };\n /**\n * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't\n * too many outstanding requests and we are still alive.\n *\n * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if\n * needed.\n */\n FirebaseIFrameScriptHolder.prototype.newRequest_ = function () {\n // We keep one outstanding request open all the time to receive data, but if we need to send data\n // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically\n // close the old request.\n if (this.alive &&\n this.sendNewPolls &&\n this.outstandingRequests.count() < (this.pendingSegs.length > 0 ? 2 : 1)) {\n //construct our url\n this.currentSerial++;\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n urlParams[exports.FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;\n var theURL = this.urlFn(urlParams);\n //Now add as much data as we can.\n var curDataString = '';\n var i = 0;\n while (this.pendingSegs.length > 0) {\n //first, lets see if the next segment will fit.\n var nextSeg = this.pendingSegs[0];\n if (nextSeg.d.length + SEG_HEADER_SIZE + curDataString.length <=\n MAX_URL_DATA_SIZE) {\n //great, the segment will fit. Lets append it.\n var theSeg = this.pendingSegs.shift();\n curDataString =\n curDataString +\n '&' +\n exports.FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +\n i +\n '=' +\n theSeg.seg +\n '&' +\n exports.FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +\n i +\n '=' +\n theSeg.ts +\n '&' +\n exports.FIREBASE_LONGPOLL_DATA_PARAM +\n i +\n '=' +\n theSeg.d;\n i++;\n }\n else {\n break;\n }\n }\n theURL = theURL + curDataString;\n this.addLongPollTag_(theURL, this.currentSerial);\n return true;\n }\n else {\n return false;\n }\n };\n /**\n * Queue a packet for transmission to the server.\n * @param segnum - A sequential id for this packet segment used for reassembly\n * @param totalsegs - The total number of segments in this packet\n * @param data - The data for this segment.\n */\n FirebaseIFrameScriptHolder.prototype.enqueueSegment = function (segnum, totalsegs, data) {\n //add this to the queue of segments to send.\n this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });\n //send the data immediately if there isn't already data being transmitted, unless\n //startLongPoll hasn't been called yet.\n if (this.alive) {\n this.newRequest_();\n }\n };\n /**\n * Add a script tag for a regular long-poll request.\n * @param {!string} url - The URL of the script tag.\n * @param {!number} serial - The serial number of the request.\n * @private\n */\n FirebaseIFrameScriptHolder.prototype.addLongPollTag_ = function (url, serial) {\n var _this = this;\n //remember that we sent this request.\n this.outstandingRequests.add(serial, 1);\n var doNewRequest = function () {\n _this.outstandingRequests.remove(serial);\n _this.newRequest_();\n };\n // If this request doesn't return on its own accord (by the server sending us some data), we'll\n // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.\n var keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));\n var readyStateCB = function () {\n // Request completed. Cancel the keepalive.\n clearTimeout(keepaliveTimeout);\n // Trigger a new request so we can continue receiving data.\n doNewRequest();\n };\n this.addTag(url, readyStateCB);\n };\n /**\n * Add an arbitrary script tag to the iframe.\n * @param {!string} url - The URL for the script tag source.\n * @param {!function()} loadCB - A callback to be triggered once the script has loaded.\n */\n FirebaseIFrameScriptHolder.prototype.addTag = function (url, loadCB) {\n var _this = this;\n if (util_3.isNodeSdk()) {\n this.doNodeLongPoll(url, loadCB);\n }\n else {\n setTimeout(function () {\n try {\n // if we're already closed, don't add this poll\n if (!_this.sendNewPolls)\n return;\n var newScript_1 = _this.myIFrame.doc.createElement('script');\n newScript_1.type = 'text/javascript';\n newScript_1.async = true;\n newScript_1.src = url;\n newScript_1.onload = newScript_1.onreadystatechange = function () {\n var rstate = newScript_1.readyState;\n if (!rstate || rstate === 'loaded' || rstate === 'complete') {\n newScript_1.onload = newScript_1.onreadystatechange = null;\n if (newScript_1.parentNode) {\n newScript_1.parentNode.removeChild(newScript_1);\n }\n loadCB();\n }\n };\n newScript_1.onerror = function () {\n util_1.log('Long-poll script failed to load: ' + url);\n _this.sendNewPolls = false;\n _this.close();\n };\n _this.myIFrame.doc.body.appendChild(newScript_1);\n }\n catch (e) {\n // TODO: we should make this error visible somehow\n }\n }, Math.floor(1));\n }\n };\n return FirebaseIFrameScriptHolder;\n}());\nexports.FirebaseIFrameScriptHolder = FirebaseIFrameScriptHolder;\n\n//# sourceMappingURL=BrowserPollConnection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/BrowserPollConnection.js\n// module id = 54\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar app_1 = require(\"@firebase/app\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../core/util/util\");\nvar StatsManager_1 = require(\"../core/stats/StatsManager\");\nvar Constants_1 = require(\"./Constants\");\nvar util_3 = require(\"@firebase/util\");\nvar storage_1 = require(\"../core/storage/storage\");\nvar util_4 = require(\"@firebase/util\");\nvar util_5 = require(\"@firebase/util\");\nvar WEBSOCKET_MAX_FRAME_SIZE = 16384;\nvar WEBSOCKET_KEEPALIVE_INTERVAL = 45000;\nvar WebSocketImpl = null;\nif (typeof MozWebSocket !== 'undefined') {\n WebSocketImpl = MozWebSocket;\n}\nelse if (typeof WebSocket !== 'undefined') {\n WebSocketImpl = WebSocket;\n}\nfunction setWebSocketImpl(impl) {\n WebSocketImpl = impl;\n}\nexports.setWebSocketImpl = setWebSocketImpl;\n/**\n * Create a new websocket connection with the given callbacks.\n * @constructor\n * @implements {Transport}\n */\nvar WebSocketConnection = /** @class */ (function () {\n /**\n * @param {string} connId identifier for this transport\n * @param {RepoInfo} repoInfo The info for the websocket endpoint.\n * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport\n * session\n * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection\n */\n function WebSocketConnection(connId, repoInfo, transportSessionId, lastSessionId) {\n this.connId = connId;\n this.keepaliveTimer = null;\n this.frames = null;\n this.totalFrames = 0;\n this.bytesSent = 0;\n this.bytesReceived = 0;\n this.log_ = util_2.logWrapper(this.connId);\n this.stats_ = StatsManager_1.StatsManager.getCollection(repoInfo);\n this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId);\n }\n /**\n * @param {RepoInfo} repoInfo The info for the websocket endpoint.\n * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport\n * session\n * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection\n * @return {string} connection url\n * @private\n */\n WebSocketConnection.connectionURL_ = function (repoInfo, transportSessionId, lastSessionId) {\n var urlParams = {};\n urlParams[Constants_1.VERSION_PARAM] = Constants_1.PROTOCOL_VERSION;\n if (!util_5.isNodeSdk() &&\n typeof location !== 'undefined' &&\n location.href &&\n location.href.indexOf(Constants_1.FORGE_DOMAIN) !== -1) {\n urlParams[Constants_1.REFERER_PARAM] = Constants_1.FORGE_REF;\n }\n if (transportSessionId) {\n urlParams[Constants_1.TRANSPORT_SESSION_PARAM] = transportSessionId;\n }\n if (lastSessionId) {\n urlParams[Constants_1.LAST_SESSION_PARAM] = lastSessionId;\n }\n return repoInfo.connectionURL(Constants_1.WEBSOCKET, urlParams);\n };\n /**\n *\n * @param onMessage Callback when messages arrive\n * @param onDisconnect Callback with connection lost.\n */\n WebSocketConnection.prototype.open = function (onMessage, onDisconnect) {\n var _this = this;\n this.onDisconnect = onDisconnect;\n this.onMessage = onMessage;\n this.log_('Websocket connecting to ' + this.connURL);\n this.everConnected_ = false;\n // Assume failure until proven otherwise.\n storage_1.PersistentStorage.set('previous_websocket_failure', true);\n try {\n if (util_5.isNodeSdk()) {\n var device = util_3.CONSTANTS.NODE_ADMIN ? 'AdminNode' : 'Node';\n // UA Format: Firebase////\n var options = {\n headers: {\n 'User-Agent': \"Firebase/\" + Constants_1.PROTOCOL_VERSION + \"/\" + app_1.default.SDK_VERSION + \"/\" + process.platform + \"/\" + device\n }\n };\n // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.\n var env = process['env'];\n var proxy = this.connURL.indexOf('wss://') == 0\n ? env['HTTPS_PROXY'] || env['https_proxy']\n : env['HTTP_PROXY'] || env['http_proxy'];\n if (proxy) {\n options['proxy'] = { origin: proxy };\n }\n this.mySock = new WebSocketImpl(this.connURL, [], options);\n }\n else {\n this.mySock = new WebSocketImpl(this.connURL);\n }\n }\n catch (e) {\n this.log_('Error instantiating WebSocket.');\n var error = e.message || e.data;\n if (error) {\n this.log_(error);\n }\n this.onClosed_();\n return;\n }\n this.mySock.onopen = function () {\n _this.log_('Websocket connected.');\n _this.everConnected_ = true;\n };\n this.mySock.onclose = function () {\n _this.log_('Websocket connection was disconnected.');\n _this.mySock = null;\n _this.onClosed_();\n };\n this.mySock.onmessage = function (m) {\n _this.handleIncomingFrame(m);\n };\n this.mySock.onerror = function (e) {\n _this.log_('WebSocket error. Closing connection.');\n var error = e.message || e.data;\n if (error) {\n _this.log_(error);\n }\n _this.onClosed_();\n };\n };\n /**\n * No-op for websockets, we don't need to do anything once the connection is confirmed as open\n */\n WebSocketConnection.prototype.start = function () { };\n WebSocketConnection.forceDisallow = function () {\n WebSocketConnection.forceDisallow_ = true;\n };\n WebSocketConnection.isAvailable = function () {\n var isOldAndroid = false;\n if (typeof navigator !== 'undefined' && navigator.userAgent) {\n var oldAndroidRegex = /Android ([0-9]{0,}\\.[0-9]{0,})/;\n var oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);\n if (oldAndroidMatch && oldAndroidMatch.length > 1) {\n if (parseFloat(oldAndroidMatch[1]) < 4.4) {\n isOldAndroid = true;\n }\n }\n }\n return (!isOldAndroid &&\n WebSocketImpl !== null &&\n !WebSocketConnection.forceDisallow_);\n };\n /**\n * Returns true if we previously failed to connect with this transport.\n * @return {boolean}\n */\n WebSocketConnection.previouslyFailed = function () {\n // If our persistent storage is actually only in-memory storage,\n // we default to assuming that it previously failed to be safe.\n return (storage_1.PersistentStorage.isInMemoryStorage ||\n storage_1.PersistentStorage.get('previous_websocket_failure') === true);\n };\n WebSocketConnection.prototype.markConnectionHealthy = function () {\n storage_1.PersistentStorage.remove('previous_websocket_failure');\n };\n WebSocketConnection.prototype.appendFrame_ = function (data) {\n this.frames.push(data);\n if (this.frames.length == this.totalFrames) {\n var fullMess = this.frames.join('');\n this.frames = null;\n var jsonMess = util_4.jsonEval(fullMess);\n //handle the message\n this.onMessage(jsonMess);\n }\n };\n /**\n * @param {number} frameCount The number of frames we are expecting from the server\n * @private\n */\n WebSocketConnection.prototype.handleNewFrameCount_ = function (frameCount) {\n this.totalFrames = frameCount;\n this.frames = [];\n };\n /**\n * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1\n * @param {!String} data\n * @return {?String} Any remaining data to be process, or null if there is none\n * @private\n */\n WebSocketConnection.prototype.extractFrameCount_ = function (data) {\n util_1.assert(this.frames === null, 'We already have a frame buffer');\n // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced\n // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508\n if (data.length <= 6) {\n var frameCount = Number(data);\n if (!isNaN(frameCount)) {\n this.handleNewFrameCount_(frameCount);\n return null;\n }\n }\n this.handleNewFrameCount_(1);\n return data;\n };\n /**\n * Process a websocket frame that has arrived from the server.\n * @param mess The frame data\n */\n WebSocketConnection.prototype.handleIncomingFrame = function (mess) {\n if (this.mySock === null)\n return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.\n var data = mess['data'];\n this.bytesReceived += data.length;\n this.stats_.incrementCounter('bytes_received', data.length);\n this.resetKeepAlive();\n if (this.frames !== null) {\n // we're buffering\n this.appendFrame_(data);\n }\n else {\n // try to parse out a frame count, otherwise, assume 1 and process it\n var remainingData = this.extractFrameCount_(data);\n if (remainingData !== null) {\n this.appendFrame_(remainingData);\n }\n }\n };\n /**\n * Send a message to the server\n * @param {Object} data The JSON object to transmit\n */\n WebSocketConnection.prototype.send = function (data) {\n this.resetKeepAlive();\n var dataStr = util_4.stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n //We can only fit a certain amount in each websocket frame, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n var dataSegs = util_2.splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);\n //Send the length header\n if (dataSegs.length > 1) {\n this.sendString_(String(dataSegs.length));\n }\n //Send the actual data in segments.\n for (var i = 0; i < dataSegs.length; i++) {\n this.sendString_(dataSegs[i]);\n }\n };\n WebSocketConnection.prototype.shutdown_ = function () {\n this.isClosed_ = true;\n if (this.keepaliveTimer) {\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = null;\n }\n if (this.mySock) {\n this.mySock.close();\n this.mySock = null;\n }\n };\n WebSocketConnection.prototype.onClosed_ = function () {\n if (!this.isClosed_) {\n this.log_('WebSocket is closing itself');\n this.shutdown_();\n // since this is an internal close, trigger the close listener\n if (this.onDisconnect) {\n this.onDisconnect(this.everConnected_);\n this.onDisconnect = null;\n }\n }\n };\n /**\n * External-facing close handler.\n * Close the websocket and kill the connection.\n */\n WebSocketConnection.prototype.close = function () {\n if (!this.isClosed_) {\n this.log_('WebSocket is being closed');\n this.shutdown_();\n }\n };\n /**\n * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after\n * the last activity.\n */\n WebSocketConnection.prototype.resetKeepAlive = function () {\n var _this = this;\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = setInterval(function () {\n //If there has been no websocket activity for a while, send a no-op\n if (_this.mySock) {\n _this.sendString_('0');\n }\n _this.resetKeepAlive();\n }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));\n };\n /**\n * Send a string over the websocket.\n *\n * @param {string} str String to send.\n * @private\n */\n WebSocketConnection.prototype.sendString_ = function (str) {\n // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()\n // calls for some unknown reason. We treat these as an error and disconnect.\n // See https://app.asana.com/0/58926111402292/68021340250410\n try {\n this.mySock.send(str);\n }\n catch (e) {\n this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');\n setTimeout(this.onClosed_.bind(this), 0);\n }\n };\n /**\n * Number of response before we consider the connection \"healthy.\"\n * @type {number}\n */\n WebSocketConnection.responsesRequiredToBeHealthy = 2;\n /**\n * Time to wait for the connection te become healthy before giving up.\n * @type {number}\n */\n WebSocketConnection.healthyTimeout = 30000;\n return WebSocketConnection;\n}());\nexports.WebSocketConnection = WebSocketConnection;\n\n//# sourceMappingURL=WebSocketConnection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/WebSocketConnection.js\n// module id = 55\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Interface defining the set of actions that can be performed against the Firebase server\n * (basically corresponds to our wire protocol).\n *\n * @interface\n */\nvar ServerActions = /** @class */ (function () {\n function ServerActions() {\n }\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n * @param {string=} hash\n */\n ServerActions.prototype.put = function (pathString, data, onComplete, hash) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, ?string)} onComplete\n * @param {string=} hash\n */\n ServerActions.prototype.merge = function (pathString, data, onComplete, hash) { };\n /**\n * Refreshes the auth token for the current connection.\n * @param {string} token The authentication token\n */\n ServerActions.prototype.refreshAuthToken = function (token) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectPut = function (pathString, data, onComplete) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectMerge = function (pathString, data, onComplete) { };\n /**\n * @param {string} pathString\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectCancel = function (pathString, onComplete) { };\n /**\n * @param {Object.} stats\n */\n ServerActions.prototype.reportStats = function (stats) { };\n return ServerActions;\n}());\nexports.ServerActions = ServerActions;\n\n//# sourceMappingURL=ServerActions.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/ServerActions.js\n// module id = 56\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar IndexedFilter_1 = require(\"./IndexedFilter\");\nvar PriorityIndex_1 = require(\"../../snap/indexes/PriorityIndex\");\nvar Node_1 = require(\"../../../core/snap/Node\");\nvar ChildrenNode_1 = require(\"../../snap/ChildrenNode\");\n/**\n * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node\n *\n * @constructor\n * @implements {NodeFilter}\n */\nvar RangedFilter = /** @class */ (function () {\n /**\n * @param {!QueryParams} params\n */\n function RangedFilter(params) {\n this.indexedFilter_ = new IndexedFilter_1.IndexedFilter(params.getIndex());\n this.index_ = params.getIndex();\n this.startPost_ = RangedFilter.getStartPost_(params);\n this.endPost_ = RangedFilter.getEndPost_(params);\n }\n /**\n * @return {!NamedNode}\n */\n RangedFilter.prototype.getStartPost = function () {\n return this.startPost_;\n };\n /**\n * @return {!NamedNode}\n */\n RangedFilter.prototype.getEndPost = function () {\n return this.endPost_;\n };\n /**\n * @param {!NamedNode} node\n * @return {boolean}\n */\n RangedFilter.prototype.matches = function (node) {\n return (this.index_.compare(this.getStartPost(), node) <= 0 &&\n this.index_.compare(node, this.getEndPost()) <= 0);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n if (!this.matches(new Node_1.NamedNode(key, newChild))) {\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n if (newSnap.isLeafNode()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n newSnap = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n var filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var self = this;\n newSnap.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n if (!self.matches(new Node_1.NamedNode(key, childNode))) {\n filtered = filtered.updateImmediateChild(key, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n });\n return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n // Don't support priorities on queries\n return oldSnap;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.filtersNodes = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.getIndexedFilter = function () {\n return this.indexedFilter_;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @param {!QueryParams} params\n * @return {!NamedNode}\n * @private\n */\n RangedFilter.getStartPost_ = function (params) {\n if (params.hasStart()) {\n var startName = params.getIndexStartName();\n return params.getIndex().makePost(params.getIndexStartValue(), startName);\n }\n else {\n return params.getIndex().minPost();\n }\n };\n /**\n * @param {!QueryParams} params\n * @return {!NamedNode}\n * @private\n */\n RangedFilter.getEndPost_ = function (params) {\n if (params.hasEnd()) {\n var endName = params.getIndexEndName();\n return params.getIndex().makePost(params.getIndexEndValue(), endName);\n }\n else {\n return params.getIndex().maxPost();\n }\n };\n return RangedFilter;\n}());\nexports.RangedFilter = RangedFilter;\n\n//# sourceMappingURL=RangedFilter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/filter/RangedFilter.js\n// module id = 57\n// module chunks = 0","/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nmodule.exports = require('@firebase/database');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./database/index.js\n// module id = 79\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar app_1 = require(\"@firebase/app\");\nvar Database_1 = require(\"./src/api/Database\");\nexports.Database = Database_1.Database;\nvar Query_1 = require(\"./src/api/Query\");\nexports.Query = Query_1.Query;\nvar Reference_1 = require(\"./src/api/Reference\");\nexports.Reference = Reference_1.Reference;\nvar util_1 = require(\"./src/core/util/util\");\nexports.enableLogging = util_1.enableLogging;\nvar RepoManager_1 = require(\"./src/core/RepoManager\");\nvar INTERNAL = require(\"./src/api/internal\");\nvar TEST_ACCESS = require(\"./src/api/test_access\");\nvar util_2 = require(\"@firebase/util\");\nvar ServerValue = Database_1.Database.ServerValue;\nexports.ServerValue = ServerValue;\nfunction registerDatabase(instance) {\n // Register the Database Service with the 'firebase' namespace.\n var namespace = instance.INTERNAL.registerService('database', function (app, unused, url) { return RepoManager_1.RepoManager.getInstance().databaseFromApp(app, url); }, \n // firebase.database namespace properties\n {\n Reference: Reference_1.Reference,\n Query: Query_1.Query,\n Database: Database_1.Database,\n enableLogging: util_1.enableLogging,\n INTERNAL: INTERNAL,\n ServerValue: ServerValue,\n TEST_ACCESS: TEST_ACCESS\n }, null, true);\n if (util_2.isNodeSdk()) {\n module.exports = namespace;\n }\n}\nexports.registerDatabase = registerDatabase;\nregisterDatabase(app_1.default);\nvar DataSnapshot_1 = require(\"./src/api/DataSnapshot\");\nexports.DataSnapshot = DataSnapshot_1.DataSnapshot;\nvar onDisconnect_1 = require(\"./src/api/onDisconnect\");\nexports.OnDisconnect = onDisconnect_1.OnDisconnect;\n\n//# sourceMappingURL=index.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/index.js\n// module id = 80\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Wraps a DOM Storage object and:\n * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.\n * - prefixes names with \"firebase:\" to avoid collisions with app data.\n *\n * We automatically (see storage.js) create two such wrappers, one for sessionStorage,\n * and one for localStorage.\n *\n * @constructor\n */\nvar DOMStorageWrapper = /** @class */ (function () {\n /**\n * @param {Storage} domStorage_ The underlying storage object (e.g. localStorage or sessionStorage)\n */\n function DOMStorageWrapper(domStorage_) {\n this.domStorage_ = domStorage_;\n // Use a prefix to avoid collisions with other stuff saved by the app.\n this.prefix_ = 'firebase:';\n }\n /**\n * @param {string} key The key to save the value under\n * @param {?Object} value The value being stored, or null to remove the key.\n */\n DOMStorageWrapper.prototype.set = function (key, value) {\n if (value == null) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n }\n else {\n this.domStorage_.setItem(this.prefixedName_(key), util_1.stringify(value));\n }\n };\n /**\n * @param {string} key\n * @return {*} The value that was stored under this key, or null\n */\n DOMStorageWrapper.prototype.get = function (key) {\n var storedVal = this.domStorage_.getItem(this.prefixedName_(key));\n if (storedVal == null) {\n return null;\n }\n else {\n return util_1.jsonEval(storedVal);\n }\n };\n /**\n * @param {string} key\n */\n DOMStorageWrapper.prototype.remove = function (key) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n };\n /**\n * @param {string} name\n * @return {string}\n */\n DOMStorageWrapper.prototype.prefixedName_ = function (name) {\n return this.prefix_ + name;\n };\n DOMStorageWrapper.prototype.toString = function () {\n return this.domStorage_.toString();\n };\n return DOMStorageWrapper;\n}());\nexports.DOMStorageWrapper = DOMStorageWrapper;\n\n//# sourceMappingURL=DOMStorageWrapper.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/storage/DOMStorageWrapper.js\n// module id = 81\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * An in-memory storage implementation that matches the API of DOMStorageWrapper\n * (TODO: create interface for both to implement).\n *\n * @constructor\n */\nvar MemoryStorage = /** @class */ (function () {\n function MemoryStorage() {\n this.cache_ = {};\n this.isInMemoryStorage = true;\n }\n MemoryStorage.prototype.set = function (key, value) {\n if (value == null) {\n delete this.cache_[key];\n }\n else {\n this.cache_[key] = value;\n }\n };\n MemoryStorage.prototype.get = function (key) {\n if (util_1.contains(this.cache_, key)) {\n return this.cache_[key];\n }\n return null;\n };\n MemoryStorage.prototype.remove = function (key) {\n delete this.cache_[key];\n };\n return MemoryStorage;\n}());\nexports.MemoryStorage = MemoryStorage;\n\n//# sourceMappingURL=MemoryStorage.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/storage/MemoryStorage.js\n// module id = 82\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar TransactionResult = /** @class */ (function () {\n /**\n * A type for the resolve value of Firebase.transaction.\n * @constructor\n * @dict\n * @param {boolean} committed\n * @param {DataSnapshot} snapshot\n */\n function TransactionResult(committed, snapshot) {\n this.committed = committed;\n this.snapshot = snapshot;\n }\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n TransactionResult.prototype.toJSON = function () {\n util_1.validateArgCount('TransactionResult.toJSON', 0, 1, arguments.length);\n return { committed: this.committed, snapshot: this.snapshot.toJSON() };\n };\n return TransactionResult;\n}());\nexports.TransactionResult = TransactionResult;\n\n//# sourceMappingURL=TransactionResult.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/TransactionResult.js\n// module id = 83\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Fancy ID generator that creates 20-character string identifiers with the\n * following properties:\n *\n * 1. They're based on timestamp so that they sort *after* any existing ids.\n * 2. They contain 72-bits of random data after the timestamp so that IDs won't\n * collide with other clients' IDs.\n * 3. They sort *lexicographically* (so the timestamp is converted to characters\n * that will sort properly).\n * 4. They're monotonically increasing. Even if you generate more than one in\n * the same timestamp, the latter ones will sort after the former ones. We do\n * this by using the previous random bits but \"incrementing\" them by 1 (only\n * in the case of a timestamp collision).\n */\nexports.nextPushId = (function () {\n // Modeled after base64 web-safe chars, but ordered by ASCII.\n var PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';\n // Timestamp of last push, used to prevent local collisions if you push twice\n // in one ms.\n var lastPushTime = 0;\n // We generate 72-bits of randomness which get turned into 12 characters and\n // appended to the timestamp to prevent collisions with other clients. We\n // store the last characters we generated because in the event of a collision,\n // we'll use those same characters except \"incremented\" by one.\n var lastRandChars = [];\n return function (now) {\n var duplicateTime = now === lastPushTime;\n lastPushTime = now;\n var i;\n var timeStampChars = new Array(8);\n for (i = 7; i >= 0; i--) {\n timeStampChars[i] = PUSH_CHARS.charAt(now % 64);\n // NOTE: Can't use << here because javascript will convert to int and lose\n // the upper bits.\n now = Math.floor(now / 64);\n }\n util_1.assert(now === 0, 'Cannot push at time == 0');\n var id = timeStampChars.join('');\n if (!duplicateTime) {\n for (i = 0; i < 12; i++) {\n lastRandChars[i] = Math.floor(Math.random() * 64);\n }\n }\n else {\n // If the timestamp hasn't changed since last push, use the same random\n // number, except incremented by 1.\n for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {\n lastRandChars[i] = 0;\n }\n lastRandChars[i]++;\n }\n for (i = 0; i < 12; i++) {\n id += PUSH_CHARS.charAt(lastRandChars[i]);\n }\n util_1.assert(id.length === 20, 'nextPushId: Length should be 20.');\n return id;\n };\n})();\n\n//# sourceMappingURL=NextPushId.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/NextPushId.js\n// module id = 84\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar DataSnapshot_1 = require(\"../../api/DataSnapshot\");\nvar Event_1 = require(\"./Event\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * Represents registration for 'value' events.\n */\nvar ValueEventRegistration = /** @class */ (function () {\n /**\n * @param {?function(!DataSnapshot)} callback_\n * @param {?function(Error)} cancelCallback_\n * @param {?Object} context_\n */\n function ValueEventRegistration(callback_, cancelCallback_, context_) {\n this.callback_ = callback_;\n this.cancelCallback_ = cancelCallback_;\n this.context_ = context_;\n }\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.respondsTo = function (eventType) {\n return eventType === 'value';\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.createEvent = function (change, query) {\n var index = query.getQueryParams().getIndex();\n return new Event_1.DataEvent('value', this, new DataSnapshot_1.DataSnapshot(change.snapshotNode, query.getRef(), index));\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.getEventRunner = function (eventData) {\n var ctx = this.context_;\n if (eventData.getEventType() === 'cancel') {\n util_2.assert(this.cancelCallback_, 'Raising a cancel event on a listener with no cancel callback');\n var cancelCB_1 = this.cancelCallback_;\n return function () {\n // We know that error exists, we checked above that this is a cancel event\n cancelCB_1.call(ctx, eventData.error);\n };\n }\n else {\n var cb_1 = this.callback_;\n return function () {\n cb_1.call(ctx, eventData.snapshot);\n };\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.createCancelEvent = function (error, path) {\n if (this.cancelCallback_) {\n return new Event_1.CancelEvent(this, error, path);\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.matches = function (other) {\n if (!(other instanceof ValueEventRegistration)) {\n return false;\n }\n else if (!other.callback_ || !this.callback_) {\n // If no callback specified, we consider it to match any callback.\n return true;\n }\n else {\n return (other.callback_ === this.callback_ && other.context_ === this.context_);\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.hasAnyCallback = function () {\n return this.callback_ !== null;\n };\n return ValueEventRegistration;\n}());\nexports.ValueEventRegistration = ValueEventRegistration;\n/**\n * Represents the registration of 1 or more child_xxx events.\n *\n * Currently, it is always exactly 1 child_xxx event, but the idea is we might let you\n * register a group of callbacks together in the future.\n *\n * @constructor\n * @implements {EventRegistration}\n */\nvar ChildEventRegistration = /** @class */ (function () {\n /**\n * @param {?Object.} callbacks_\n * @param {?function(Error)} cancelCallback_\n * @param {Object=} context_\n */\n function ChildEventRegistration(callbacks_, cancelCallback_, context_) {\n this.callbacks_ = callbacks_;\n this.cancelCallback_ = cancelCallback_;\n this.context_ = context_;\n }\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.respondsTo = function (eventType) {\n var eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;\n eventToCheck =\n eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;\n return util_1.contains(this.callbacks_, eventToCheck);\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.createCancelEvent = function (error, path) {\n if (this.cancelCallback_) {\n return new Event_1.CancelEvent(this, error, path);\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.createEvent = function (change, query) {\n util_2.assert(change.childName != null, 'Child events should have a childName.');\n var ref = query.getRef().child(/** @type {!string} */ (change.childName));\n var index = query.getQueryParams().getIndex();\n return new Event_1.DataEvent(change.type, this, new DataSnapshot_1.DataSnapshot(change.snapshotNode, ref, index), change.prevName);\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.getEventRunner = function (eventData) {\n var ctx = this.context_;\n if (eventData.getEventType() === 'cancel') {\n util_2.assert(this.cancelCallback_, 'Raising a cancel event on a listener with no cancel callback');\n var cancelCB_2 = this.cancelCallback_;\n return function () {\n // We know that error exists, we checked above that this is a cancel event\n cancelCB_2.call(ctx, eventData.error);\n };\n }\n else {\n var cb_2 = this.callbacks_[eventData.eventType];\n return function () {\n cb_2.call(ctx, eventData.snapshot, eventData.prevName);\n };\n }\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.matches = function (other) {\n if (other instanceof ChildEventRegistration) {\n if (!this.callbacks_ || !other.callbacks_) {\n return true;\n }\n else if (this.context_ === other.context_) {\n var otherCount = util_1.getCount(other.callbacks_);\n var thisCount = util_1.getCount(this.callbacks_);\n if (otherCount === thisCount) {\n // If count is 1, do an exact match on eventType, if either is defined but null, it's a match.\n // If event types don't match, not a match\n // If count is not 1, exact match across all\n if (otherCount === 1) {\n var otherKey /** @type {!string} */ = util_1.getAnyKey(other.callbacks_);\n var thisKey /** @type {!string} */ = util_1.getAnyKey(this.callbacks_);\n return (thisKey === otherKey &&\n (!other.callbacks_[otherKey] ||\n !this.callbacks_[thisKey] ||\n other.callbacks_[otherKey] === this.callbacks_[thisKey]));\n }\n else {\n // Exact match on each key.\n return util_1.every(this.callbacks_, function (eventType, cb) { return other.callbacks_[eventType] === cb; });\n }\n }\n }\n }\n return false;\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.hasAnyCallback = function () {\n return this.callbacks_ !== null;\n };\n return ChildEventRegistration;\n}());\nexports.ChildEventRegistration = ChildEventRegistration;\n\n//# sourceMappingURL=EventRegistration.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/EventRegistration.js\n// module id = 85\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Encapsulates the data needed to raise an event\n * @implements {Event}\n */\nvar DataEvent = /** @class */ (function () {\n /**\n * @param {!string} eventType One of: value, child_added, child_changed, child_moved, child_removed\n * @param {!EventRegistration} eventRegistration The function to call to with the event data. User provided\n * @param {!DataSnapshot} snapshot The data backing the event\n * @param {?string=} prevName Optional, the name of the previous child for child_* events.\n */\n function DataEvent(eventType, eventRegistration, snapshot, prevName) {\n this.eventType = eventType;\n this.eventRegistration = eventRegistration;\n this.snapshot = snapshot;\n this.prevName = prevName;\n }\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getPath = function () {\n var ref = this.snapshot.getRef();\n if (this.eventType === 'value') {\n return ref.path;\n }\n else {\n return ref.getParent().path;\n }\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getEventType = function () {\n return this.eventType;\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getEventRunner = function () {\n return this.eventRegistration.getEventRunner(this);\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.toString = function () {\n return (this.getPath().toString() +\n ':' +\n this.eventType +\n ':' +\n util_1.stringify(this.snapshot.exportVal()));\n };\n return DataEvent;\n}());\nexports.DataEvent = DataEvent;\nvar CancelEvent = /** @class */ (function () {\n /**\n * @param {EventRegistration} eventRegistration\n * @param {Error} error\n * @param {!Path} path\n */\n function CancelEvent(eventRegistration, error, path) {\n this.eventRegistration = eventRegistration;\n this.error = error;\n this.path = path;\n }\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getPath = function () {\n return this.path;\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getEventType = function () {\n return 'cancel';\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getEventRunner = function () {\n return this.eventRegistration.getEventRunner(this);\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.toString = function () {\n return this.path.toString() + ':cancel';\n };\n return CancelEvent;\n}());\nexports.CancelEvent = CancelEvent;\n\n//# sourceMappingURL=Event.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/Event.js\n// module id = 86\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"./util/util\");\nvar AckUserWrite_1 = require(\"./operation/AckUserWrite\");\nvar ChildrenNode_1 = require(\"./snap/ChildrenNode\");\nvar util_3 = require(\"@firebase/util\");\nvar ImmutableTree_1 = require(\"./util/ImmutableTree\");\nvar ListenComplete_1 = require(\"./operation/ListenComplete\");\nvar Merge_1 = require(\"./operation/Merge\");\nvar Operation_1 = require(\"./operation/Operation\");\nvar Overwrite_1 = require(\"./operation/Overwrite\");\nvar Path_1 = require(\"./util/Path\");\nvar SyncPoint_1 = require(\"./SyncPoint\");\nvar WriteTree_1 = require(\"./WriteTree\");\n/**\n * SyncTree is the central class for managing event callback registration, data caching, views\n * (query processing), and event generation. There are typically two SyncTree instances for\n * each Repo, one for the normal Firebase data, and one for the .info data.\n *\n * It has a number of responsibilities, including:\n * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).\n * - Applying and caching data changes for user set(), transaction(), and update() calls\n * (applyUserOverwrite(), applyUserMerge()).\n * - Applying and caching data changes for server data changes (applyServerOverwrite(),\n * applyServerMerge()).\n * - Generating user-facing events for server and user changes (all of the apply* methods\n * return the set of events that need to be raised as a result).\n * - Maintaining the appropriate set of server listens to ensure we are always subscribed\n * to the correct set of paths and queries to satisfy the current set of user event\n * callbacks (listens are started/stopped using the provided listenProvider).\n *\n * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual\n * events are returned to the caller rather than raised synchronously.\n *\n * @constructor\n */\nvar SyncTree = /** @class */ (function () {\n /**\n * @param {!ListenProvider} listenProvider_ Used by SyncTree to start / stop listening\n * to server data.\n */\n function SyncTree(listenProvider_) {\n this.listenProvider_ = listenProvider_;\n /**\n * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.\n * @type {!ImmutableTree.}\n * @private\n */\n this.syncPointTree_ = ImmutableTree_1.ImmutableTree.Empty;\n /**\n * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).\n * @type {!WriteTree}\n * @private\n */\n this.pendingWriteTree_ = new WriteTree_1.WriteTree();\n this.tagToQueryMap_ = {};\n this.queryToTagMap_ = {};\n }\n /**\n * Apply the data changes for a user-generated set() or transaction() call.\n *\n * @param {!Path} path\n * @param {!Node} newData\n * @param {number} writeId\n * @param {boolean=} visible\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyUserOverwrite = function (path, newData, writeId, visible) {\n // Record pending write.\n this.pendingWriteTree_.addOverwrite(path, newData, writeId, visible);\n if (!visible) {\n return [];\n }\n else {\n return this.applyOperationToSyncPoints_(new Overwrite_1.Overwrite(Operation_1.OperationSource.User, path, newData));\n }\n };\n /**\n * Apply the data from a user-generated update() call\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} writeId\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyUserMerge = function (path, changedChildren, writeId) {\n // Record pending merge.\n this.pendingWriteTree_.addMerge(path, changedChildren, writeId);\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n return this.applyOperationToSyncPoints_(new Merge_1.Merge(Operation_1.OperationSource.User, path, changeTree));\n };\n /**\n * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().\n *\n * @param {!number} writeId\n * @param {boolean=} revert True if the given write failed and needs to be reverted\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.ackUserWrite = function (writeId, revert) {\n if (revert === void 0) { revert = false; }\n var write = this.pendingWriteTree_.getWrite(writeId);\n var needToReevaluate = this.pendingWriteTree_.removeWrite(writeId);\n if (!needToReevaluate) {\n return [];\n }\n else {\n var affectedTree_1 = ImmutableTree_1.ImmutableTree.Empty;\n if (write.snap != null) {\n // overwrite\n affectedTree_1 = affectedTree_1.set(Path_1.Path.Empty, true);\n }\n else {\n util_3.forEach(write.children, function (pathString, node) {\n affectedTree_1 = affectedTree_1.set(new Path_1.Path(pathString), node);\n });\n }\n return this.applyOperationToSyncPoints_(new AckUserWrite_1.AckUserWrite(write.path, affectedTree_1, revert));\n }\n };\n /**\n * Apply new server data for the specified path..\n *\n * @param {!Path} path\n * @param {!Node} newData\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyServerOverwrite = function (path, newData) {\n return this.applyOperationToSyncPoints_(new Overwrite_1.Overwrite(Operation_1.OperationSource.Server, path, newData));\n };\n /**\n * Apply new server data to be merged in at the specified path.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyServerMerge = function (path, changedChildren) {\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n return this.applyOperationToSyncPoints_(new Merge_1.Merge(Operation_1.OperationSource.Server, path, changeTree));\n };\n /**\n * Apply a listen complete for a query\n *\n * @param {!Path} path\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyListenComplete = function (path) {\n return this.applyOperationToSyncPoints_(new ListenComplete_1.ListenComplete(Operation_1.OperationSource.Server, path));\n };\n /**\n * Apply new server data for the specified tagged query.\n *\n * @param {!Path} path\n * @param {!Node} snap\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedQueryOverwrite = function (path, snap, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey != null) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var op = new Overwrite_1.Overwrite(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath, snap);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // Query must have been removed already\n return [];\n }\n };\n /**\n * Apply server data to be merged in for the specified tagged query.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedQueryMerge = function (path, changedChildren, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n var op = new Merge_1.Merge(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath, changeTree);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n };\n /**\n * Apply a listen complete for a tagged query\n *\n * @param {!Path} path\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedListenComplete = function (path, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var op = new ListenComplete_1.ListenComplete(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n };\n /**\n * Add an event callback for the specified query.\n *\n * @param {!Query} query\n * @param {!EventRegistration} eventRegistration\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.addEventRegistration = function (query, eventRegistration) {\n var path = query.path;\n var serverCache = null;\n var foundAncestorDefaultView = false;\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\n this.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) {\n var relativePath = Path_1.Path.relativePath(pathToSyncPoint, path);\n serverCache = serverCache || sp.getCompleteServerCache(relativePath);\n foundAncestorDefaultView =\n foundAncestorDefaultView || sp.hasCompleteView();\n });\n var syncPoint = this.syncPointTree_.get(path);\n if (!syncPoint) {\n syncPoint = new SyncPoint_1.SyncPoint();\n this.syncPointTree_ = this.syncPointTree_.set(path, syncPoint);\n }\n else {\n foundAncestorDefaultView =\n foundAncestorDefaultView || syncPoint.hasCompleteView();\n serverCache = serverCache || syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var serverCacheComplete;\n if (serverCache != null) {\n serverCacheComplete = true;\n }\n else {\n serverCacheComplete = false;\n serverCache = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var subtree = this.syncPointTree_.subtree(path);\n subtree.foreachChild(function (childName, childSyncPoint) {\n var completeCache = childSyncPoint.getCompleteServerCache(Path_1.Path.Empty);\n if (completeCache) {\n serverCache = serverCache.updateImmediateChild(childName, completeCache);\n }\n });\n }\n var viewAlreadyExists = syncPoint.viewExistsForQuery(query);\n if (!viewAlreadyExists && !query.getQueryParams().loadsAllData()) {\n // We need to track a tag for this query\n var queryKey = SyncTree.makeQueryKey_(query);\n util_1.assert(!(queryKey in this.queryToTagMap_), 'View does not exist, but we have a tag');\n var tag = SyncTree.getNextQueryTag_();\n this.queryToTagMap_[queryKey] = tag;\n // Coerce to string to avoid sparse arrays.\n this.tagToQueryMap_['_' + tag] = queryKey;\n }\n var writesCache = this.pendingWriteTree_.childWrites(path);\n var events = syncPoint.addEventRegistration(query, eventRegistration, writesCache, serverCache, serverCacheComplete);\n if (!viewAlreadyExists && !foundAncestorDefaultView) {\n var view /** @type !View */ = syncPoint.viewForQuery(query);\n events = events.concat(this.setupListener_(query, view));\n }\n return events;\n };\n /**\n * Remove event callback(s).\n *\n * If query is the default query, we'll check all queries for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.\n *\n * @param {!Query} query\n * @param {?EventRegistration} eventRegistration If null, all callbacks are removed.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {!Array.} Cancel events, if cancelError was provided.\n */\n SyncTree.prototype.removeEventRegistration = function (query, eventRegistration, cancelError) {\n var _this = this;\n // Find the syncPoint first. Then deal with whether or not it has matching listeners\n var path = query.path;\n var maybeSyncPoint = this.syncPointTree_.get(path);\n var cancelEvents = [];\n // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without\n // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and\n // not loadsAllData().\n if (maybeSyncPoint &&\n (query.queryIdentifier() === 'default' ||\n maybeSyncPoint.viewExistsForQuery(query))) {\n /**\n * @type {{removed: !Array., events: !Array.}}\n */\n var removedAndEvents = maybeSyncPoint.removeEventRegistration(query, eventRegistration, cancelError);\n if (maybeSyncPoint.isEmpty()) {\n this.syncPointTree_ = this.syncPointTree_.remove(path);\n }\n var removed = removedAndEvents.removed;\n cancelEvents = removedAndEvents.events;\n // We may have just removed one of many listeners and can short-circuit this whole process\n // We may also not have removed a default listener, in which case all of the descendant listeners should already be\n // properly set up.\n //\n // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of\n // queryId === 'default'\n var removingDefault = -1 !==\n removed.findIndex(function (query) {\n return query.getQueryParams().loadsAllData();\n });\n var covered = this.syncPointTree_.findOnPath(path, function (relativePath, parentSyncPoint) {\n return parentSyncPoint.hasCompleteView();\n });\n if (removingDefault && !covered) {\n var subtree = this.syncPointTree_.subtree(path);\n // There are potentially child listeners. Determine what if any listens we need to send before executing the\n // removal\n if (!subtree.isEmpty()) {\n // We need to fold over our subtree and collect the listeners to send\n var newViews = this.collectDistinctViewsForSubTree_(subtree);\n // Ok, we've collected all the listens we need. Set them up.\n for (var i = 0; i < newViews.length; ++i) {\n var view = newViews[i], newQuery = view.getQuery();\n var listener = this.createListenerForView_(view);\n this.listenProvider_.startListening(SyncTree.queryForListening_(newQuery), this.tagForQuery_(newQuery), listener.hashFn, listener.onComplete);\n }\n }\n else {\n // There's nothing below us, so nothing we need to start listening on\n }\n }\n // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query\n // The above block has us covered in terms of making sure we're set up on listens lower in the tree.\n // Also, note that if we have a cancelError, it's already been removed at the provider level.\n if (!covered && removed.length > 0 && !cancelError) {\n // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one\n // default. Otherwise, we need to iterate through and cancel each individual query\n if (removingDefault) {\n // We don't tag default listeners\n var defaultTag = null;\n this.listenProvider_.stopListening(SyncTree.queryForListening_(query), defaultTag);\n }\n else {\n removed.forEach(function (queryToRemove) {\n var tagToRemove = _this.queryToTagMap_[SyncTree.makeQueryKey_(queryToRemove)];\n _this.listenProvider_.stopListening(SyncTree.queryForListening_(queryToRemove), tagToRemove);\n });\n }\n }\n // Now, clear all of the tags we're tracking for the removed listens\n this.removeTags_(removed);\n }\n else {\n // No-op, this listener must've been already removed\n }\n return cancelEvents;\n };\n /**\n * Returns a complete cache, if we have one, of the data at a particular path. The location must have a listener above\n * it, but as this is only used by transaction code, that should always be the case anyways.\n *\n * Note: this method will *include* hidden writes from transaction with applyLocally set to false.\n * @param {!Path} path The path to the data we want\n * @param {Array.=} writeIdsToExclude A specific set to be excluded\n * @return {?Node}\n */\n SyncTree.prototype.calcCompleteEventCache = function (path, writeIdsToExclude) {\n var includeHiddenSets = true;\n var writeTree = this.pendingWriteTree_;\n var serverCache = this.syncPointTree_.findOnPath(path, function (pathSoFar, syncPoint) {\n var relativePath = Path_1.Path.relativePath(pathSoFar, path);\n var serverCache = syncPoint.getCompleteServerCache(relativePath);\n if (serverCache) {\n return serverCache;\n }\n });\n return writeTree.calcCompleteEventCache(path, serverCache, writeIdsToExclude, includeHiddenSets);\n };\n /**\n * This collapses multiple unfiltered views into a single view, since we only need a single\n * listener for them.\n *\n * @param {!ImmutableTree.} subtree\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.collectDistinctViewsForSubTree_ = function (subtree) {\n return subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {\n if (maybeChildSyncPoint && maybeChildSyncPoint.hasCompleteView()) {\n var completeView = maybeChildSyncPoint.getCompleteView();\n return [completeView];\n }\n else {\n // No complete view here, flatten any deeper listens into an array\n var views_1 = [];\n if (maybeChildSyncPoint) {\n views_1 = maybeChildSyncPoint.getQueryViews();\n }\n util_3.forEach(childMap, function (key, childViews) {\n views_1 = views_1.concat(childViews);\n });\n return views_1;\n }\n });\n };\n /**\n * @param {!Array.} queries\n * @private\n */\n SyncTree.prototype.removeTags_ = function (queries) {\n for (var j = 0; j < queries.length; ++j) {\n var removedQuery = queries[j];\n if (!removedQuery.getQueryParams().loadsAllData()) {\n // We should have a tag for this\n var removedQueryKey = SyncTree.makeQueryKey_(removedQuery);\n var removedQueryTag = this.queryToTagMap_[removedQueryKey];\n delete this.queryToTagMap_[removedQueryKey];\n delete this.tagToQueryMap_['_' + removedQueryTag];\n }\n }\n };\n /**\n * Normalizes a query to a query we send the server for listening\n * @param {!Query} query\n * @return {!Query} The normalized query\n * @private\n */\n SyncTree.queryForListening_ = function (query) {\n if (query.getQueryParams().loadsAllData() &&\n !query.getQueryParams().isDefault()) {\n // We treat queries that load all data as default queries\n // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits\n // from Query\n return /** @type {!Query} */ query.getRef();\n }\n else {\n return query;\n }\n };\n /**\n * For a given new listen, manage the de-duplication of outstanding subscriptions.\n *\n * @param {!Query} query\n * @param {!View} view\n * @return {!Array.} This method can return events to support synchronous data sources\n * @private\n */\n SyncTree.prototype.setupListener_ = function (query, view) {\n var path = query.path;\n var tag = this.tagForQuery_(query);\n var listener = this.createListenerForView_(view);\n var events = this.listenProvider_.startListening(SyncTree.queryForListening_(query), tag, listener.hashFn, listener.onComplete);\n var subtree = this.syncPointTree_.subtree(path);\n // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we\n // may need to shadow other listens as well.\n if (tag) {\n util_1.assert(!subtree.value.hasCompleteView(), \"If we're adding a query, it shouldn't be shadowed\");\n }\n else {\n // Shadow everything at or below this location, this is a default listener.\n var queriesToStop = subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {\n if (!relativePath.isEmpty() &&\n maybeChildSyncPoint &&\n maybeChildSyncPoint.hasCompleteView()) {\n return [maybeChildSyncPoint.getCompleteView().getQuery()];\n }\n else {\n // No default listener here, flatten any deeper queries into an array\n var queries_1 = [];\n if (maybeChildSyncPoint) {\n queries_1 = queries_1.concat(maybeChildSyncPoint.getQueryViews().map(function (view) { return view.getQuery(); }));\n }\n util_3.forEach(childMap, function (key, childQueries) {\n queries_1 = queries_1.concat(childQueries);\n });\n return queries_1;\n }\n });\n for (var i = 0; i < queriesToStop.length; ++i) {\n var queryToStop = queriesToStop[i];\n this.listenProvider_.stopListening(SyncTree.queryForListening_(queryToStop), this.tagForQuery_(queryToStop));\n }\n }\n return events;\n };\n /**\n *\n * @param {!View} view\n * @return {{hashFn: function(), onComplete: function(!string, *)}}\n * @private\n */\n SyncTree.prototype.createListenerForView_ = function (view) {\n var _this = this;\n var query = view.getQuery();\n var tag = this.tagForQuery_(query);\n return {\n hashFn: function () {\n var cache = view.getServerCache() || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return cache.hash();\n },\n onComplete: function (status) {\n if (status === 'ok') {\n if (tag) {\n return _this.applyTaggedListenComplete(query.path, tag);\n }\n else {\n return _this.applyListenComplete(query.path);\n }\n }\n else {\n // If a listen failed, kill all of the listeners here, not just the one that triggered the error.\n // Note that this may need to be scoped to just this listener if we change permissions on filtered children\n var error = util_2.errorForServerCode(status, query);\n return _this.removeEventRegistration(query, \n /*eventRegistration*/ null, error);\n }\n }\n };\n };\n /**\n * Given a query, computes a \"queryKey\" suitable for use in our queryToTagMap_.\n * @private\n * @param {!Query} query\n * @return {string}\n */\n SyncTree.makeQueryKey_ = function (query) {\n return query.path.toString() + '$' + query.queryIdentifier();\n };\n /**\n * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.\n * @private\n * @param {!string} queryKey\n * @return {{queryId: !string, path: !Path}}\n */\n SyncTree.parseQueryKey_ = function (queryKey) {\n var splitIndex = queryKey.indexOf('$');\n util_1.assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');\n return {\n queryId: queryKey.substr(splitIndex + 1),\n path: new Path_1.Path(queryKey.substr(0, splitIndex))\n };\n };\n /**\n * Return the query associated with the given tag, if we have one\n * @param {!number} tag\n * @return {?string}\n * @private\n */\n SyncTree.prototype.queryKeyForTag_ = function (tag) {\n return this.tagToQueryMap_['_' + tag];\n };\n /**\n * Return the tag associated with the given query.\n * @param {!Query} query\n * @return {?number}\n * @private\n */\n SyncTree.prototype.tagForQuery_ = function (query) {\n var queryKey = SyncTree.makeQueryKey_(query);\n return util_3.safeGet(this.queryToTagMap_, queryKey);\n };\n /**\n * Static accessor for query tags.\n * @return {number}\n * @private\n */\n SyncTree.getNextQueryTag_ = function () {\n return SyncTree.nextQueryTag_++;\n };\n /**\n * A helper method to apply tagged operations\n *\n * @param {!Path} queryPath\n * @param {!Operation} operation\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.applyTaggedOperation_ = function (queryPath, operation) {\n var syncPoint = this.syncPointTree_.get(queryPath);\n util_1.assert(syncPoint, \"Missing sync point for query tag that we're tracking\");\n var writesCache = this.pendingWriteTree_.childWrites(queryPath);\n return syncPoint.applyOperation(operation, writesCache, \n /*serverCache=*/ null);\n };\n /**\n * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.\n *\n * NOTES:\n * - Descendant SyncPoints will be visited first (since we raise events depth-first).\n \n * - We call applyOperation() on each SyncPoint passing three things:\n * 1. A version of the Operation that has been made relative to the SyncPoint location.\n * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.\n * 3. A snapshot Node with cached server data, if we have it.\n \n * - We concatenate all of the events returned by each SyncPoint and return the result.\n *\n * @param {!Operation} operation\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.applyOperationToSyncPoints_ = function (operation) {\n return this.applyOperationHelper_(operation, this.syncPointTree_, \n /*serverCache=*/ null, this.pendingWriteTree_.childWrites(Path_1.Path.Empty));\n };\n /**\n * Recursive helper for applyOperationToSyncPoints_\n *\n * @private\n * @param {!Operation} operation\n * @param {ImmutableTree.} syncPointTree\n * @param {?Node} serverCache\n * @param {!WriteTreeRef} writesCache\n * @return {!Array.}\n */\n SyncTree.prototype.applyOperationHelper_ = function (operation, syncPointTree, serverCache, writesCache) {\n if (operation.path.isEmpty()) {\n return this.applyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);\n }\n else {\n var syncPoint = syncPointTree.get(Path_1.Path.Empty);\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var events = [];\n var childName = operation.path.getFront();\n var childOperation = operation.operationForChild(childName);\n var childTree = syncPointTree.children.get(childName);\n if (childTree && childOperation) {\n var childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n var childWritesCache = writesCache.child(childName);\n events = events.concat(this.applyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));\n }\n if (syncPoint) {\n events = events.concat(syncPoint.applyOperation(operation, writesCache, serverCache));\n }\n return events;\n }\n };\n /**\n * Recursive helper for applyOperationToSyncPoints_\n *\n * @private\n * @param {!Operation} operation\n * @param {ImmutableTree.} syncPointTree\n * @param {?Node} serverCache\n * @param {!WriteTreeRef} writesCache\n * @return {!Array.}\n */\n SyncTree.prototype.applyOperationDescendantsHelper_ = function (operation, syncPointTree, serverCache, writesCache) {\n var _this = this;\n var syncPoint = syncPointTree.get(Path_1.Path.Empty);\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var events = [];\n syncPointTree.children.inorderTraversal(function (childName, childTree) {\n var childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n var childWritesCache = writesCache.child(childName);\n var childOperation = operation.operationForChild(childName);\n if (childOperation) {\n events = events.concat(_this.applyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));\n }\n });\n if (syncPoint) {\n events = events.concat(syncPoint.applyOperation(operation, writesCache, serverCache));\n }\n return events;\n };\n /**\n * Static tracker for next query tag.\n * @type {number}\n * @private\n */\n SyncTree.nextQueryTag_ = 1;\n return SyncTree;\n}());\nexports.SyncTree = SyncTree;\n\n//# sourceMappingURL=SyncTree.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/SyncTree.js\n// module id = 87\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Path_1 = require(\"../util/Path\");\nvar Operation_1 = require(\"./Operation\");\nvar AckUserWrite = /** @class */ (function () {\n /**\n *\n * @param {!Path} path\n * @param {!ImmutableTree} affectedTree A tree containing true for each affected path. Affected paths can't overlap.\n * @param {!boolean} revert\n */\n function AckUserWrite(\n /**@inheritDoc */ path, \n /**@inheritDoc */ affectedTree, \n /**@inheritDoc */ revert) {\n this.path = path;\n this.affectedTree = affectedTree;\n this.revert = revert;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.ACK_USER_WRITE;\n /** @inheritDoc */\n this.source = Operation_1.OperationSource.User;\n }\n /**\n * @inheritDoc\n */\n AckUserWrite.prototype.operationForChild = function (childName) {\n if (!this.path.isEmpty()) {\n util_1.assert(this.path.getFront() === childName, 'operationForChild called for unrelated child.');\n return new AckUserWrite(this.path.popFront(), this.affectedTree, this.revert);\n }\n else if (this.affectedTree.value != null) {\n util_1.assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');\n // All child locations are affected as well; just return same operation.\n return this;\n }\n else {\n var childTree = this.affectedTree.subtree(new Path_1.Path(childName));\n return new AckUserWrite(Path_1.Path.Empty, childTree, this.revert);\n }\n };\n return AckUserWrite;\n}());\nexports.AckUserWrite = AckUserWrite;\n\n//# sourceMappingURL=AckUserWrite.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/operation/AckUserWrite.js\n// module id = 88\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = require(\"../util/Path\");\nvar Operation_1 = require(\"./Operation\");\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @constructor\n * @implements {Operation}\n */\nvar ListenComplete = /** @class */ (function () {\n function ListenComplete(source, path) {\n this.source = source;\n this.path = path;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.LISTEN_COMPLETE;\n }\n ListenComplete.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n return new ListenComplete(this.source, Path_1.Path.Empty);\n }\n else {\n return new ListenComplete(this.source, this.path.popFront());\n }\n };\n return ListenComplete;\n}());\nexports.ListenComplete = ListenComplete;\n\n//# sourceMappingURL=ListenComplete.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/operation/ListenComplete.js\n// module id = 89\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = require(\"./Operation\");\nvar Overwrite_1 = require(\"./Overwrite\");\nvar Path_1 = require(\"../util/Path\");\nvar util_1 = require(\"@firebase/util\");\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @param {!ImmutableTree.} children\n * @constructor\n * @implements {Operation}\n */\nvar Merge = /** @class */ (function () {\n function Merge(\n /**@inheritDoc */ source, \n /**@inheritDoc */ path, \n /**@inheritDoc */ children) {\n this.source = source;\n this.path = path;\n this.children = children;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.MERGE;\n }\n /**\n * @inheritDoc\n */\n Merge.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n var childTree = this.children.subtree(new Path_1.Path(childName));\n if (childTree.isEmpty()) {\n // This child is unaffected\n return null;\n }\n else if (childTree.value) {\n // We have a snapshot for the child in question. This becomes an overwrite of the child.\n return new Overwrite_1.Overwrite(this.source, Path_1.Path.Empty, childTree.value);\n }\n else {\n // This is a merge at a deeper level\n return new Merge(this.source, Path_1.Path.Empty, childTree);\n }\n }\n else {\n util_1.assert(this.path.getFront() === childName, \"Can't get a merge for a child not on the path of the operation\");\n return new Merge(this.source, this.path.popFront(), this.children);\n }\n };\n /**\n * @inheritDoc\n */\n Merge.prototype.toString = function () {\n return ('Operation(' +\n this.path +\n ': ' +\n this.source.toString() +\n ' merge: ' +\n this.children.toString() +\n ')');\n };\n return Merge;\n}());\nexports.Merge = Merge;\n\n//# sourceMappingURL=Merge.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/operation/Merge.js\n// module id = 90\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar IndexedFilter_1 = require(\"./filter/IndexedFilter\");\nvar ViewProcessor_1 = require(\"./ViewProcessor\");\nvar ChildrenNode_1 = require(\"../snap/ChildrenNode\");\nvar CacheNode_1 = require(\"./CacheNode\");\nvar ViewCache_1 = require(\"./ViewCache\");\nvar EventGenerator_1 = require(\"./EventGenerator\");\nvar util_1 = require(\"@firebase/util\");\nvar Operation_1 = require(\"../operation/Operation\");\nvar Change_1 = require(\"./Change\");\nvar PriorityIndex_1 = require(\"../snap/indexes/PriorityIndex\");\n/**\n * A view represents a specific location and query that has 1 or more event registrations.\n *\n * It does several things:\n * - Maintains the list of event registrations for this location/query.\n * - Maintains a cache of the data visible for this location/query.\n * - Applies new operations (via applyOperation), updates the cache, and based on the event\n * registrations returns the set of events to be raised.\n * @constructor\n */\nvar View = /** @class */ (function () {\n /**\n *\n * @param {!Query} query_\n * @param {!ViewCache} initialViewCache\n */\n function View(query_, initialViewCache) {\n this.query_ = query_;\n this.eventRegistrations_ = [];\n var params = this.query_.getQueryParams();\n var indexFilter = new IndexedFilter_1.IndexedFilter(params.getIndex());\n var filter = params.getNodeFilter();\n /**\n * @type {ViewProcessor}\n * @private\n */\n this.processor_ = new ViewProcessor_1.ViewProcessor(filter);\n var initialServerCache = initialViewCache.getServerCache();\n var initialEventCache = initialViewCache.getEventCache();\n // Don't filter server node with other filter than index, wait for tagged listen\n var serverSnap = indexFilter.updateFullNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);\n var eventSnap = filter.updateFullNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);\n var newServerCache = new CacheNode_1.CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());\n var newEventCache = new CacheNode_1.CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());\n /**\n * @type {!ViewCache}\n * @private\n */\n this.viewCache_ = new ViewCache_1.ViewCache(newEventCache, newServerCache);\n /**\n * @type {!EventGenerator}\n * @private\n */\n this.eventGenerator_ = new EventGenerator_1.EventGenerator(this.query_);\n }\n /**\n * @return {!Query}\n */\n View.prototype.getQuery = function () {\n return this.query_;\n };\n /**\n * @return {?Node}\n */\n View.prototype.getServerCache = function () {\n return this.viewCache_.getServerCache().getNode();\n };\n /**\n * @param {!Path} path\n * @return {?Node}\n */\n View.prototype.getCompleteServerCache = function (path) {\n var cache = this.viewCache_.getCompleteServerSnap();\n if (cache) {\n // If this isn't a \"loadsAllData\" view, then cache isn't actually a complete cache and\n // we need to see if it contains the child we're interested in.\n if (this.query_.getQueryParams().loadsAllData() ||\n (!path.isEmpty() && !cache.getImmediateChild(path.getFront()).isEmpty())) {\n return cache.getChild(path);\n }\n }\n return null;\n };\n /**\n * @return {boolean}\n */\n View.prototype.isEmpty = function () {\n return this.eventRegistrations_.length === 0;\n };\n /**\n * @param {!EventRegistration} eventRegistration\n */\n View.prototype.addEventRegistration = function (eventRegistration) {\n this.eventRegistrations_.push(eventRegistration);\n };\n /**\n * @param {?EventRegistration} eventRegistration If null, remove all callbacks.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {!Array.} Cancel events, if cancelError was provided.\n */\n View.prototype.removeEventRegistration = function (eventRegistration, cancelError) {\n var cancelEvents = [];\n if (cancelError) {\n util_1.assert(eventRegistration == null, 'A cancel should cancel all event registrations.');\n var path_1 = this.query_.path;\n this.eventRegistrations_.forEach(function (registration) {\n cancelError /** @type {!Error} */ = cancelError;\n var maybeEvent = registration.createCancelEvent(cancelError, path_1);\n if (maybeEvent) {\n cancelEvents.push(maybeEvent);\n }\n });\n }\n if (eventRegistration) {\n var remaining = [];\n for (var i = 0; i < this.eventRegistrations_.length; ++i) {\n var existing = this.eventRegistrations_[i];\n if (!existing.matches(eventRegistration)) {\n remaining.push(existing);\n }\n else if (eventRegistration.hasAnyCallback()) {\n // We're removing just this one\n remaining = remaining.concat(this.eventRegistrations_.slice(i + 1));\n break;\n }\n }\n this.eventRegistrations_ = remaining;\n }\n else {\n this.eventRegistrations_ = [];\n }\n return cancelEvents;\n };\n /**\n * Applies the given Operation, updates our cache, and returns the appropriate events.\n *\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeServerCache\n * @return {!Array.}\n */\n View.prototype.applyOperation = function (operation, writesCache, completeServerCache) {\n if (operation.type === Operation_1.OperationType.MERGE &&\n operation.source.queryId !== null) {\n util_1.assert(this.viewCache_.getCompleteServerSnap(), 'We should always have a full cache before handling merges');\n util_1.assert(this.viewCache_.getCompleteEventSnap(), 'Missing event cache, even though we have a server cache');\n }\n var oldViewCache = this.viewCache_;\n var result = this.processor_.applyOperation(oldViewCache, operation, writesCache, completeServerCache);\n this.processor_.assertIndexed(result.viewCache);\n util_1.assert(result.viewCache.getServerCache().isFullyInitialized() ||\n !oldViewCache.getServerCache().isFullyInitialized(), 'Once a server snap is complete, it should never go back');\n this.viewCache_ = result.viewCache;\n return this.generateEventsForChanges_(result.changes, result.viewCache.getEventCache().getNode(), null);\n };\n /**\n * @param {!EventRegistration} registration\n * @return {!Array.}\n */\n View.prototype.getInitialEvents = function (registration) {\n var eventSnap = this.viewCache_.getEventCache();\n var initialChanges = [];\n if (!eventSnap.getNode().isLeafNode()) {\n var eventNode = eventSnap.getNode();\n eventNode.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n initialChanges.push(Change_1.Change.childAddedChange(key, childNode));\n });\n }\n if (eventSnap.isFullyInitialized()) {\n initialChanges.push(Change_1.Change.valueChange(eventSnap.getNode()));\n }\n return this.generateEventsForChanges_(initialChanges, eventSnap.getNode(), registration);\n };\n /**\n * @private\n * @param {!Array.} changes\n * @param {!Node} eventCache\n * @param {EventRegistration=} eventRegistration\n * @return {!Array.}\n */\n View.prototype.generateEventsForChanges_ = function (changes, eventCache, eventRegistration) {\n var registrations = eventRegistration\n ? [eventRegistration]\n : this.eventRegistrations_;\n return this.eventGenerator_.generateEventsForChanges(changes, eventCache, registrations);\n };\n return View;\n}());\nexports.View = View;\n\n//# sourceMappingURL=View.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/View.js\n// module id = 91\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = require(\"../operation/Operation\");\nvar util_1 = require(\"@firebase/util\");\nvar ChildChangeAccumulator_1 = require(\"./ChildChangeAccumulator\");\nvar Change_1 = require(\"./Change\");\nvar ChildrenNode_1 = require(\"../snap/ChildrenNode\");\nvar KeyIndex_1 = require(\"../snap/indexes/KeyIndex\");\nvar ImmutableTree_1 = require(\"../util/ImmutableTree\");\nvar Path_1 = require(\"../util/Path\");\nvar CompleteChildSource_1 = require(\"./CompleteChildSource\");\n/**\n * @constructor\n * @struct\n */\nvar ProcessorResult = /** @class */ (function () {\n /**\n * @param {!ViewCache} viewCache\n * @param {!Array.} changes\n */\n function ProcessorResult(viewCache, changes) {\n this.viewCache = viewCache;\n this.changes = changes;\n }\n return ProcessorResult;\n}());\nexports.ProcessorResult = ProcessorResult;\n/**\n * @constructor\n */\nvar ViewProcessor = /** @class */ (function () {\n /**\n * @param {!NodeFilter} filter_\n */\n function ViewProcessor(filter_) {\n this.filter_ = filter_;\n }\n /**\n * @param {!ViewCache} viewCache\n */\n ViewProcessor.prototype.assertIndexed = function (viewCache) {\n util_1.assert(viewCache\n .getEventCache()\n .getNode()\n .isIndexed(this.filter_.getIndex()), 'Event snap not indexed');\n util_1.assert(viewCache\n .getServerCache()\n .getNode()\n .isIndexed(this.filter_.getIndex()), 'Server snap not indexed');\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @return {!ProcessorResult}\n */\n ViewProcessor.prototype.applyOperation = function (oldViewCache, operation, writesCache, completeCache) {\n var accumulator = new ChildChangeAccumulator_1.ChildChangeAccumulator();\n var newViewCache, filterServerNode;\n if (operation.type === Operation_1.OperationType.OVERWRITE) {\n var overwrite = operation;\n if (overwrite.source.fromUser) {\n newViewCache = this.applyUserOverwrite_(oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);\n }\n else {\n util_1.assert(overwrite.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered and the\n // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered\n // again\n filterServerNode =\n overwrite.source.tagged ||\n (oldViewCache.getServerCache().isFiltered() &&\n !overwrite.path.isEmpty());\n newViewCache = this.applyServerOverwrite_(oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.MERGE) {\n var merge = operation;\n if (merge.source.fromUser) {\n newViewCache = this.applyUserMerge_(oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);\n }\n else {\n util_1.assert(merge.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered\n filterServerNode =\n merge.source.tagged || oldViewCache.getServerCache().isFiltered();\n newViewCache = this.applyServerMerge_(oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.ACK_USER_WRITE) {\n var ackUserWrite = operation;\n if (!ackUserWrite.revert) {\n newViewCache = this.ackUserWrite_(oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);\n }\n else {\n newViewCache = this.revertUserWrite_(oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.LISTEN_COMPLETE) {\n newViewCache = this.listenComplete_(oldViewCache, operation.path, writesCache, accumulator);\n }\n else {\n throw util_1.assertionError('Unknown operation type: ' + operation.type);\n }\n var changes = accumulator.getChanges();\n ViewProcessor.maybeAddValueEvent_(oldViewCache, newViewCache, changes);\n return new ProcessorResult(newViewCache, changes);\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!ViewCache} newViewCache\n * @param {!Array.} accumulator\n * @private\n */\n ViewProcessor.maybeAddValueEvent_ = function (oldViewCache, newViewCache, accumulator) {\n var eventSnap = newViewCache.getEventCache();\n if (eventSnap.isFullyInitialized()) {\n var isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();\n var oldCompleteSnap = oldViewCache.getCompleteEventSnap();\n if (accumulator.length > 0 ||\n !oldViewCache.getEventCache().isFullyInitialized() ||\n (isLeafOrEmpty &&\n !eventSnap\n .getNode()\n .equals(/** @type {!Node} */ (oldCompleteSnap))) ||\n !eventSnap\n .getNode()\n .getPriority()\n .equals(oldCompleteSnap.getPriority())) {\n accumulator.push(Change_1.Change.valueChange(\n /** @type {!Node} */ newViewCache.getCompleteEventSnap()));\n }\n }\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} changePath\n * @param {!WriteTreeRef} writesCache\n * @param {!CompleteChildSource} source\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.generateEventCacheAfterServerEvent_ = function (viewCache, changePath, writesCache, source, accumulator) {\n var oldEventSnap = viewCache.getEventCache();\n if (writesCache.shadowingWrite(changePath) != null) {\n // we have a shadowing write, ignore changes\n return viewCache;\n }\n else {\n var newEventCache = void 0, serverNode = void 0;\n if (changePath.isEmpty()) {\n // TODO: figure out how this plays with \"sliding ack windows\"\n util_1.assert(viewCache.getServerCache().isFullyInitialized(), 'If change path is empty, we must have complete server data');\n if (viewCache.getServerCache().isFiltered()) {\n // We need to special case this, because we need to only apply writes to complete children, or\n // we might end up raising events for incomplete children. If the server data is filtered deep\n // writes cannot be guaranteed to be complete\n var serverCache = viewCache.getCompleteServerSnap();\n var completeChildren = serverCache instanceof ChildrenNode_1.ChildrenNode\n ? serverCache\n : ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var completeEventChildren = writesCache.calcCompleteEventChildren(completeChildren);\n newEventCache = this.filter_.updateFullNode(viewCache.getEventCache().getNode(), completeEventChildren, accumulator);\n }\n else {\n var completeNode = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n newEventCache = this.filter_.updateFullNode(viewCache.getEventCache().getNode(), completeNode, accumulator);\n }\n }\n else {\n var childKey = changePath.getFront();\n if (childKey == '.priority') {\n util_1.assert(changePath.getLength() == 1, \"Can't have a priority with additional path components\");\n var oldEventNode = oldEventSnap.getNode();\n serverNode = viewCache.getServerCache().getNode();\n // we might have overwrites for this priority\n var updatedPriority = writesCache.calcEventCacheAfterServerOverwrite(changePath, oldEventNode, serverNode);\n if (updatedPriority != null) {\n newEventCache = this.filter_.updatePriority(oldEventNode, updatedPriority);\n }\n else {\n // priority didn't change, keep old node\n newEventCache = oldEventSnap.getNode();\n }\n }\n else {\n var childChangePath = changePath.popFront();\n // update child\n var newEventChild = void 0;\n if (oldEventSnap.isCompleteForChild(childKey)) {\n serverNode = viewCache.getServerCache().getNode();\n var eventChildUpdate = writesCache.calcEventCacheAfterServerOverwrite(changePath, oldEventSnap.getNode(), serverNode);\n if (eventChildUpdate != null) {\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey)\n .updateChild(childChangePath, eventChildUpdate);\n }\n else {\n // Nothing changed, just keep the old child\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey);\n }\n }\n else {\n newEventChild = writesCache.calcCompleteChild(childKey, viewCache.getServerCache());\n }\n if (newEventChild != null) {\n newEventCache = this.filter_.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);\n }\n else {\n // no complete child available or no change\n newEventCache = oldEventSnap.getNode();\n }\n }\n }\n return viewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitialized() || changePath.isEmpty(), this.filter_.filtersNodes());\n }\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Path} changePath\n * @param {!Node} changedSnap\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {boolean} filterServerNode\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyServerOverwrite_ = function (oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {\n var oldServerSnap = oldViewCache.getServerCache();\n var newServerCache;\n var serverFilter = filterServerNode\n ? this.filter_\n : this.filter_.getIndexedFilter();\n if (changePath.isEmpty()) {\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);\n }\n else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {\n // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update\n var newServerNode = oldServerSnap\n .getNode()\n .updateChild(changePath, changedSnap);\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);\n }\n else {\n var childKey = changePath.getFront();\n if (!oldServerSnap.isCompleteForPath(changePath) &&\n changePath.getLength() > 1) {\n // We don't update incomplete nodes with updates intended for other listeners\n return oldViewCache;\n }\n var childChangePath = changePath.popFront();\n var childNode = oldServerSnap.getNode().getImmediateChild(childKey);\n var newChildNode = childNode.updateChild(childChangePath, changedSnap);\n if (childKey == '.priority') {\n newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);\n }\n else {\n newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, CompleteChildSource_1.NO_COMPLETE_CHILD_SOURCE, null);\n }\n }\n var newViewCache = oldViewCache.updateServerSnap(newServerCache, oldServerSnap.isFullyInitialized() || changePath.isEmpty(), serverFilter.filtersNodes());\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);\n return this.generateEventCacheAfterServerEvent_(newViewCache, changePath, writesCache, source, accumulator);\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Path} changePath\n * @param {!Node} changedSnap\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyUserOverwrite_ = function (oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {\n var oldEventSnap = oldViewCache.getEventCache();\n var newViewCache, newEventCache;\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);\n if (changePath.isEmpty()) {\n newEventCache = this.filter_.updateFullNode(oldViewCache.getEventCache().getNode(), changedSnap, accumulator);\n newViewCache = oldViewCache.updateEventSnap(newEventCache, true, this.filter_.filtersNodes());\n }\n else {\n var childKey = changePath.getFront();\n if (childKey === '.priority') {\n newEventCache = this.filter_.updatePriority(oldViewCache.getEventCache().getNode(), changedSnap);\n newViewCache = oldViewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());\n }\n else {\n var childChangePath = changePath.popFront();\n var oldChild = oldEventSnap.getNode().getImmediateChild(childKey);\n var newChild = void 0;\n if (childChangePath.isEmpty()) {\n // Child overwrite, we can replace the child\n newChild = changedSnap;\n }\n else {\n var childNode = source.getCompleteChild(childKey);\n if (childNode != null) {\n if (childChangePath.getBack() === '.priority' &&\n childNode.getChild(childChangePath.parent()).isEmpty()) {\n // This is a priority update on an empty node. If this node exists on the server, the\n // server will send down the priority in the update, so ignore for now\n newChild = childNode;\n }\n else {\n newChild = childNode.updateChild(childChangePath, changedSnap);\n }\n }\n else {\n // There is no complete child node available\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n }\n if (!oldChild.equals(newChild)) {\n var newEventSnap = this.filter_.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);\n newViewCache = oldViewCache.updateEventSnap(newEventSnap, oldEventSnap.isFullyInitialized(), this.filter_.filtersNodes());\n }\n else {\n newViewCache = oldViewCache;\n }\n }\n }\n return newViewCache;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {string} childKey\n * @return {boolean}\n * @private\n */\n ViewProcessor.cacheHasChild_ = function (viewCache, childKey) {\n return viewCache.getEventCache().isCompleteForChild(childKey);\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {ImmutableTree.} changedChildren\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyUserMerge_ = function (viewCache, path, changedChildren, writesCache, serverCache, accumulator) {\n var _this = this;\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n var curViewCache = viewCache;\n changedChildren.foreach(function (relativePath, childNode) {\n var writePath = path.child(relativePath);\n if (ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) {\n curViewCache = _this.applyUserOverwrite_(curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\n }\n });\n changedChildren.foreach(function (relativePath, childNode) {\n var writePath = path.child(relativePath);\n if (!ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) {\n curViewCache = _this.applyUserOverwrite_(curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\n }\n });\n return curViewCache;\n };\n /**\n * @param {!Node} node\n * @param {ImmutableTree.} merge\n * @return {!Node}\n * @private\n */\n ViewProcessor.prototype.applyMerge_ = function (node, merge) {\n merge.foreach(function (relativePath, childNode) {\n node = node.updateChild(relativePath, childNode);\n });\n return node;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!ImmutableTree.} changedChildren\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache\n * @param {boolean} filterServerNode\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyServerMerge_ = function (viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {\n var _this = this;\n // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and\n // wait for the complete data update coming soon.\n if (viewCache\n .getServerCache()\n .getNode()\n .isEmpty() &&\n !viewCache.getServerCache().isFullyInitialized()) {\n return viewCache;\n }\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n var curViewCache = viewCache;\n var viewMergeTree;\n if (path.isEmpty()) {\n viewMergeTree = changedChildren;\n }\n else {\n viewMergeTree = ImmutableTree_1.ImmutableTree.Empty.setTree(path, changedChildren);\n }\n var serverNode = viewCache.getServerCache().getNode();\n viewMergeTree.children.inorderTraversal(function (childKey, childTree) {\n if (serverNode.hasChild(childKey)) {\n var serverChild = viewCache\n .getServerCache()\n .getNode()\n .getImmediateChild(childKey);\n var newChild = _this.applyMerge_(serverChild, childTree);\n curViewCache = _this.applyServerOverwrite_(curViewCache, new Path_1.Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\n }\n });\n viewMergeTree.children.inorderTraversal(function (childKey, childMergeTree) {\n var isUnknownDeepMerge = !viewCache.getServerCache().isCompleteForChild(childKey) &&\n childMergeTree.value == null;\n if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {\n var serverChild = viewCache\n .getServerCache()\n .getNode()\n .getImmediateChild(childKey);\n var newChild = _this.applyMerge_(serverChild, childMergeTree);\n curViewCache = _this.applyServerOverwrite_(curViewCache, new Path_1.Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\n }\n });\n return curViewCache;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} ackPath\n * @param {!ImmutableTree} affectedTree\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.ackUserWrite_ = function (viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {\n if (writesCache.shadowingWrite(ackPath) != null) {\n return viewCache;\n }\n // Only filter server node if it is currently filtered\n var filterServerNode = viewCache.getServerCache().isFiltered();\n // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update\n // now that it won't be shadowed.\n var serverCache = viewCache.getServerCache();\n if (affectedTree.value != null) {\n // This is an overwrite.\n if ((ackPath.isEmpty() && serverCache.isFullyInitialized()) ||\n serverCache.isCompleteForPath(ackPath)) {\n return this.applyServerOverwrite_(viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);\n }\n else if (ackPath.isEmpty()) {\n // This is a goofy edge case where we are acking data at this location but don't have full data. We\n // should just re-apply whatever we have in our cache as a merge.\n var changedChildren_1 = ImmutableTree_1.ImmutableTree.Empty;\n serverCache.getNode().forEachChild(KeyIndex_1.KEY_INDEX, function (name, node) {\n changedChildren_1 = changedChildren_1.set(new Path_1.Path(name), node);\n });\n return this.applyServerMerge_(viewCache, ackPath, changedChildren_1, writesCache, completeCache, filterServerNode, accumulator);\n }\n else {\n return viewCache;\n }\n }\n else {\n // This is a merge.\n var changedChildren_2 = ImmutableTree_1.ImmutableTree.Empty;\n affectedTree.foreach(function (mergePath, value) {\n var serverCachePath = ackPath.child(mergePath);\n if (serverCache.isCompleteForPath(serverCachePath)) {\n changedChildren_2 = changedChildren_2.set(mergePath, serverCache.getNode().getChild(serverCachePath));\n }\n });\n return this.applyServerMerge_(viewCache, ackPath, changedChildren_2, writesCache, completeCache, filterServerNode, accumulator);\n }\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!WriteTreeRef} writesCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.listenComplete_ = function (viewCache, path, writesCache, accumulator) {\n var oldServerNode = viewCache.getServerCache();\n var newViewCache = viewCache.updateServerSnap(oldServerNode.getNode(), oldServerNode.isFullyInitialized() || path.isEmpty(), oldServerNode.isFiltered());\n return this.generateEventCacheAfterServerEvent_(newViewCache, path, writesCache, CompleteChildSource_1.NO_COMPLETE_CHILD_SOURCE, accumulator);\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeServerCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.revertUserWrite_ = function (viewCache, path, writesCache, completeServerCache, accumulator) {\n var complete;\n if (writesCache.shadowingWrite(path) != null) {\n return viewCache;\n }\n else {\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);\n var oldEventCache = viewCache.getEventCache().getNode();\n var newEventCache = void 0;\n if (path.isEmpty() || path.getFront() === '.priority') {\n var newNode = void 0;\n if (viewCache.getServerCache().isFullyInitialized()) {\n newNode = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n }\n else {\n var serverChildren = viewCache.getServerCache().getNode();\n util_1.assert(serverChildren instanceof ChildrenNode_1.ChildrenNode, 'serverChildren would be complete if leaf node');\n newNode = writesCache.calcCompleteEventChildren(serverChildren);\n }\n newNode = newNode;\n newEventCache = this.filter_.updateFullNode(oldEventCache, newNode, accumulator);\n }\n else {\n var childKey = path.getFront();\n var newChild = writesCache.calcCompleteChild(childKey, viewCache.getServerCache());\n if (newChild == null &&\n viewCache.getServerCache().isCompleteForChild(childKey)) {\n newChild = oldEventCache.getImmediateChild(childKey);\n }\n if (newChild != null) {\n newEventCache = this.filter_.updateChild(oldEventCache, childKey, newChild, path.popFront(), source, accumulator);\n }\n else if (viewCache\n .getEventCache()\n .getNode()\n .hasChild(childKey)) {\n // No complete child available, delete the existing one, if any\n newEventCache = this.filter_.updateChild(oldEventCache, childKey, ChildrenNode_1.ChildrenNode.EMPTY_NODE, path.popFront(), source, accumulator);\n }\n else {\n newEventCache = oldEventCache;\n }\n if (newEventCache.isEmpty() &&\n viewCache.getServerCache().isFullyInitialized()) {\n // We might have reverted all child writes. Maybe the old event was a leaf node\n complete = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n if (complete.isLeafNode()) {\n newEventCache = this.filter_.updateFullNode(newEventCache, complete, accumulator);\n }\n }\n }\n complete =\n viewCache.getServerCache().isFullyInitialized() ||\n writesCache.shadowingWrite(Path_1.Path.Empty) != null;\n return viewCache.updateEventSnap(newEventCache, complete, this.filter_.filtersNodes());\n }\n };\n return ViewProcessor;\n}());\nexports.ViewProcessor = ViewProcessor;\n\n//# sourceMappingURL=ViewProcessor.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/ViewProcessor.js\n// module id = 92\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Change_1 = require(\"./Change\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * @constructor\n */\nvar ChildChangeAccumulator = /** @class */ (function () {\n function ChildChangeAccumulator() {\n this.changeMap_ = {};\n }\n /**\n * @param {!Change} change\n */\n ChildChangeAccumulator.prototype.trackChildChange = function (change) {\n var type = change.type;\n var childKey /** @type {!string} */ = change.childName;\n util_2.assert(type == Change_1.Change.CHILD_ADDED ||\n type == Change_1.Change.CHILD_CHANGED ||\n type == Change_1.Change.CHILD_REMOVED, 'Only child changes supported for tracking');\n util_2.assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');\n var oldChange = util_1.safeGet(this.changeMap_, childKey);\n if (oldChange) {\n var oldType = oldChange.type;\n if (type == Change_1.Change.CHILD_ADDED && oldType == Change_1.Change.CHILD_REMOVED) {\n this.changeMap_[childKey] = Change_1.Change.childChangedChange(childKey, change.snapshotNode, oldChange.snapshotNode);\n }\n else if (type == Change_1.Change.CHILD_REMOVED &&\n oldType == Change_1.Change.CHILD_ADDED) {\n delete this.changeMap_[childKey];\n }\n else if (type == Change_1.Change.CHILD_REMOVED &&\n oldType == Change_1.Change.CHILD_CHANGED) {\n this.changeMap_[childKey] = Change_1.Change.childRemovedChange(childKey, oldChange.oldSnap);\n }\n else if (type == Change_1.Change.CHILD_CHANGED &&\n oldType == Change_1.Change.CHILD_ADDED) {\n this.changeMap_[childKey] = Change_1.Change.childAddedChange(childKey, change.snapshotNode);\n }\n else if (type == Change_1.Change.CHILD_CHANGED &&\n oldType == Change_1.Change.CHILD_CHANGED) {\n this.changeMap_[childKey] = Change_1.Change.childChangedChange(childKey, change.snapshotNode, oldChange.oldSnap);\n }\n else {\n throw util_2.assertionError('Illegal combination of changes: ' +\n change +\n ' occurred after ' +\n oldChange);\n }\n }\n else {\n this.changeMap_[childKey] = change;\n }\n };\n /**\n * @return {!Array.}\n */\n ChildChangeAccumulator.prototype.getChanges = function () {\n return util_1.getValues(this.changeMap_);\n };\n return ChildChangeAccumulator;\n}());\nexports.ChildChangeAccumulator = ChildChangeAccumulator;\n\n//# sourceMappingURL=ChildChangeAccumulator.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/ChildChangeAccumulator.js\n// module id = 93\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar CacheNode_1 = require(\"./CacheNode\");\n/**\n * An implementation of CompleteChildSource that never returns any additional children\n *\n * @private\n * @constructor\n * @implements CompleteChildSource\n */\nvar NoCompleteChildSource_ = /** @class */ (function () {\n function NoCompleteChildSource_() {\n }\n /**\n * @inheritDoc\n */\n NoCompleteChildSource_.prototype.getCompleteChild = function (childKey) {\n return null;\n };\n /**\n * @inheritDoc\n */\n NoCompleteChildSource_.prototype.getChildAfterChild = function (index, child, reverse) {\n return null;\n };\n return NoCompleteChildSource_;\n}());\nexports.NoCompleteChildSource_ = NoCompleteChildSource_;\n/**\n * Singleton instance.\n * @const\n * @type {!CompleteChildSource}\n */\nexports.NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();\n/**\n * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or\n * old event caches available to calculate complete children.\n *\n *\n * @implements CompleteChildSource\n */\nvar WriteTreeCompleteChildSource = /** @class */ (function () {\n /**\n * @param {!WriteTreeRef} writes_\n * @param {!ViewCache} viewCache_\n * @param {?Node} optCompleteServerCache_\n */\n function WriteTreeCompleteChildSource(writes_, viewCache_, optCompleteServerCache_) {\n if (optCompleteServerCache_ === void 0) { optCompleteServerCache_ = null; }\n this.writes_ = writes_;\n this.viewCache_ = viewCache_;\n this.optCompleteServerCache_ = optCompleteServerCache_;\n }\n /**\n * @inheritDoc\n */\n WriteTreeCompleteChildSource.prototype.getCompleteChild = function (childKey) {\n var node = this.viewCache_.getEventCache();\n if (node.isCompleteForChild(childKey)) {\n return node.getNode().getImmediateChild(childKey);\n }\n else {\n var serverNode = this.optCompleteServerCache_ != null\n ? new CacheNode_1.CacheNode(this.optCompleteServerCache_, true, false)\n : this.viewCache_.getServerCache();\n return this.writes_.calcCompleteChild(childKey, serverNode);\n }\n };\n /**\n * @inheritDoc\n */\n WriteTreeCompleteChildSource.prototype.getChildAfterChild = function (index, child, reverse) {\n var completeServerData = this.optCompleteServerCache_ != null\n ? this.optCompleteServerCache_\n : this.viewCache_.getCompleteServerSnap();\n var nodes = this.writes_.calcIndexedSlice(completeServerData, child, 1, reverse, index);\n if (nodes.length === 0) {\n return null;\n }\n else {\n return nodes[0];\n }\n };\n return WriteTreeCompleteChildSource;\n}());\nexports.WriteTreeCompleteChildSource = WriteTreeCompleteChildSource;\n\n//# sourceMappingURL=CompleteChildSource.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/CompleteChildSource.js\n// module id = 94\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Node_1 = require(\"../snap/Node\");\nvar Change_1 = require(\"./Change\");\nvar util_1 = require(\"@firebase/util\");\n/**\n * An EventGenerator is used to convert \"raw\" changes (Change) as computed by the\n * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()\n * for details.\n *\n * @constructor\n */\nvar EventGenerator = /** @class */ (function () {\n /**\n *\n * @param {!Query} query_\n */\n function EventGenerator(query_) {\n this.query_ = query_;\n /**\n * @private\n * @type {!Index}\n */\n this.index_ = this.query_.getQueryParams().getIndex();\n }\n /**\n * Given a set of raw changes (no moved events and prevName not specified yet), and a set of\n * EventRegistrations that should be notified of these changes, generate the actual events to be raised.\n *\n * Notes:\n * - child_moved events will be synthesized at this time for any child_changed events that affect\n * our index.\n * - prevName will be calculated based on the index ordering.\n *\n * @param {!Array.} changes\n * @param {!Node} eventCache\n * @param {!Array.} eventRegistrations\n * @return {!Array.}\n */\n EventGenerator.prototype.generateEventsForChanges = function (changes, eventCache, eventRegistrations) {\n var _this = this;\n var events = [];\n var moves = [];\n changes.forEach(function (change) {\n if (change.type === Change_1.Change.CHILD_CHANGED &&\n _this.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {\n moves.push(Change_1.Change.childMovedChange(change.childName, change.snapshotNode));\n }\n });\n this.generateEventsForType_(events, Change_1.Change.CHILD_REMOVED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_ADDED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_MOVED, moves, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_CHANGED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.VALUE, changes, eventRegistrations, eventCache);\n return events;\n };\n /**\n * Given changes of a single change type, generate the corresponding events.\n *\n * @param {!Array.} events\n * @param {!string} eventType\n * @param {!Array.} changes\n * @param {!Array.} registrations\n * @param {!Node} eventCache\n * @private\n */\n EventGenerator.prototype.generateEventsForType_ = function (events, eventType, changes, registrations, eventCache) {\n var _this = this;\n var filteredChanges = changes.filter(function (change) { return change.type === eventType; });\n filteredChanges.sort(this.compareChanges_.bind(this));\n filteredChanges.forEach(function (change) {\n var materializedChange = _this.materializeSingleChange_(change, eventCache);\n registrations.forEach(function (registration) {\n if (registration.respondsTo(change.type)) {\n events.push(registration.createEvent(materializedChange, _this.query_));\n }\n });\n });\n };\n /**\n * @param {!Change} change\n * @param {!Node} eventCache\n * @return {!Change}\n * @private\n */\n EventGenerator.prototype.materializeSingleChange_ = function (change, eventCache) {\n if (change.type === 'value' || change.type === 'child_removed') {\n return change;\n }\n else {\n change.prevName = eventCache.getPredecessorChildName(\n /** @type {!string} */\n change.childName, change.snapshotNode, this.index_);\n return change;\n }\n };\n /**\n * @param {!Change} a\n * @param {!Change} b\n * @return {number}\n * @private\n */\n EventGenerator.prototype.compareChanges_ = function (a, b) {\n if (a.childName == null || b.childName == null) {\n throw util_1.assertionError('Should only compare child_ events.');\n }\n var aWrapped = new Node_1.NamedNode(a.childName, a.snapshotNode);\n var bWrapped = new Node_1.NamedNode(b.childName, b.snapshotNode);\n return this.index_.compare(aWrapped, bWrapped);\n };\n return EventGenerator;\n}());\nexports.EventGenerator = EventGenerator;\n\n//# sourceMappingURL=EventGenerator.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/EventGenerator.js\n// module id = 95\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar Path_1 = require(\"./util/Path\");\nvar CompoundWrite_1 = require(\"./CompoundWrite\");\nvar PriorityIndex_1 = require(\"./snap/indexes/PriorityIndex\");\nvar ChildrenNode_1 = require(\"./snap/ChildrenNode\");\n/**\n * WriteTree tracks all pending user-initiated writes and has methods to calculate the result of merging them\n * with underlying server data (to create \"event cache\" data). Pending writes are added with addOverwrite()\n * and addMerge(), and removed with removeWrite().\n *\n * @constructor\n */\nvar WriteTree = /** @class */ (function () {\n function WriteTree() {\n /**\n * A tree tracking the result of applying all visible writes. This does not include transactions with\n * applyLocally=false or writes that are completely shadowed by other writes.\n *\n * @type {!CompoundWrite}\n * @private\n */\n this.visibleWrites_ = CompoundWrite_1.CompoundWrite.Empty;\n /**\n * A list of all pending writes, regardless of visibility and shadowed-ness. Used to calculate arbitrary\n * sets of the changed data, such as hidden writes (from transactions) or changes with certain writes excluded (also\n * used by transactions).\n *\n * @type {!Array.}\n * @private\n */\n this.allWrites_ = [];\n this.lastWriteId_ = -1;\n }\n /**\n * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.\n *\n * @param {!Path} path\n * @return {!WriteTreeRef}\n */\n WriteTree.prototype.childWrites = function (path) {\n return new WriteTreeRef(path, this);\n };\n /**\n * Record a new overwrite from user code.\n *\n * @param {!Path} path\n * @param {!Node} snap\n * @param {!number} writeId\n * @param {boolean=} visible This is set to false by some transactions. It should be excluded from event caches\n */\n WriteTree.prototype.addOverwrite = function (path, snap, writeId, visible) {\n util_2.assert(writeId > this.lastWriteId_, 'Stacking an older write on top of newer ones');\n if (visible === undefined) {\n visible = true;\n }\n this.allWrites_.push({\n path: path,\n snap: snap,\n writeId: writeId,\n visible: visible\n });\n if (visible) {\n this.visibleWrites_ = this.visibleWrites_.addWrite(path, snap);\n }\n this.lastWriteId_ = writeId;\n };\n /**\n * Record a new merge from user code.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} writeId\n */\n WriteTree.prototype.addMerge = function (path, changedChildren, writeId) {\n util_2.assert(writeId > this.lastWriteId_, 'Stacking an older merge on top of newer ones');\n this.allWrites_.push({\n path: path,\n children: changedChildren,\n writeId: writeId,\n visible: true\n });\n this.visibleWrites_ = this.visibleWrites_.addWrites(path, changedChildren);\n this.lastWriteId_ = writeId;\n };\n /**\n * @param {!number} writeId\n * @return {?WriteRecord}\n */\n WriteTree.prototype.getWrite = function (writeId) {\n for (var i = 0; i < this.allWrites_.length; i++) {\n var record = this.allWrites_[i];\n if (record.writeId === writeId) {\n return record;\n }\n }\n return null;\n };\n /**\n * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates\n * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.\n *\n * @param {!number} writeId\n * @return {boolean} true if the write may have been visible (meaning we'll need to reevaluate / raise\n * events as a result).\n */\n WriteTree.prototype.removeWrite = function (writeId) {\n // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied\n // out of order.\n //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;\n //assert(validClear, \"Either we don't have this write, or it's the first one in the queue\");\n var _this = this;\n var idx = this.allWrites_.findIndex(function (s) {\n return s.writeId === writeId;\n });\n util_2.assert(idx >= 0, 'removeWrite called with nonexistent writeId.');\n var writeToRemove = this.allWrites_[idx];\n this.allWrites_.splice(idx, 1);\n var removedWriteWasVisible = writeToRemove.visible;\n var removedWriteOverlapsWithOtherWrites = false;\n var i = this.allWrites_.length - 1;\n while (removedWriteWasVisible && i >= 0) {\n var currentWrite = this.allWrites_[i];\n if (currentWrite.visible) {\n if (i >= idx &&\n this.recordContainsPath_(currentWrite, writeToRemove.path)) {\n // The removed write was completely shadowed by a subsequent write.\n removedWriteWasVisible = false;\n }\n else if (writeToRemove.path.contains(currentWrite.path)) {\n // Either we're covering some writes or they're covering part of us (depending on which came first).\n removedWriteOverlapsWithOtherWrites = true;\n }\n }\n i--;\n }\n if (!removedWriteWasVisible) {\n return false;\n }\n else if (removedWriteOverlapsWithOtherWrites) {\n // There's some shadowing going on. Just rebuild the visible writes from scratch.\n this.resetTree_();\n return true;\n }\n else {\n // There's no shadowing. We can safely just remove the write(s) from visibleWrites.\n if (writeToRemove.snap) {\n this.visibleWrites_ = this.visibleWrites_.removeWrite(writeToRemove.path);\n }\n else {\n var children = writeToRemove.children;\n util_1.forEach(children, function (childName) {\n _this.visibleWrites_ = _this.visibleWrites_.removeWrite(writeToRemove.path.child(childName));\n });\n }\n return true;\n }\n };\n /**\n * Return a complete snapshot for the given path if there's visible write data at that path, else null.\n * No server data is considered.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTree.prototype.getCompleteWriteData = function (path) {\n return this.visibleWrites_.getCompleteNode(path);\n };\n /**\n * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden\n * writes), attempt to calculate a complete snapshot for the given path\n *\n * @param {!Path} treePath\n * @param {?Node} completeServerCache\n * @param {Array.=} writeIdsToExclude An optional set to be excluded\n * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false\n * @return {?Node}\n */\n WriteTree.prototype.calcCompleteEventCache = function (treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {\n if (!writeIdsToExclude && !includeHiddenWrites) {\n var shadowingNode = this.visibleWrites_.getCompleteNode(treePath);\n if (shadowingNode != null) {\n return shadowingNode;\n }\n else {\n var subMerge = this.visibleWrites_.childCompoundWrite(treePath);\n if (subMerge.isEmpty()) {\n return completeServerCache;\n }\n else if (completeServerCache == null &&\n !subMerge.hasCompleteWrite(Path_1.Path.Empty)) {\n // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow\n return null;\n }\n else {\n var layeredCache = completeServerCache || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return subMerge.apply(layeredCache);\n }\n }\n }\n else {\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n if (!includeHiddenWrites && merge.isEmpty()) {\n return completeServerCache;\n }\n else {\n // If the server cache is null, and we don't have a complete cache, we need to return null\n if (!includeHiddenWrites &&\n completeServerCache == null &&\n !merge.hasCompleteWrite(Path_1.Path.Empty)) {\n return null;\n }\n else {\n var filter = function (write) {\n return ((write.visible || includeHiddenWrites) &&\n (!writeIdsToExclude ||\n !~writeIdsToExclude.indexOf(write.writeId)) &&\n (write.path.contains(treePath) || treePath.contains(write.path)));\n };\n var mergeAtPath = WriteTree.layerTree_(this.allWrites_, filter, treePath);\n var layeredCache = completeServerCache || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return mergeAtPath.apply(layeredCache);\n }\n }\n }\n };\n /**\n * With optional, underlying server data, attempt to return a children node of children that we have complete data for.\n * Used when creating new views, to pre-fill their complete event children snapshot.\n *\n * @param {!Path} treePath\n * @param {?ChildrenNode} completeServerChildren\n * @return {!ChildrenNode}\n */\n WriteTree.prototype.calcCompleteEventChildren = function (treePath, completeServerChildren) {\n var completeChildren = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var topLevelSet = this.visibleWrites_.getCompleteNode(treePath);\n if (topLevelSet) {\n if (!topLevelSet.isLeafNode()) {\n // we're shadowing everything. Return the children.\n topLevelSet.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childSnap) {\n completeChildren = completeChildren.updateImmediateChild(childName, childSnap);\n });\n }\n return completeChildren;\n }\n else if (completeServerChildren) {\n // Layer any children we have on top of this\n // We know we don't have a top-level set, so just enumerate existing children\n var merge_1 = this.visibleWrites_.childCompoundWrite(treePath);\n completeServerChildren.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n var node = merge_1\n .childCompoundWrite(new Path_1.Path(childName))\n .apply(childNode);\n completeChildren = completeChildren.updateImmediateChild(childName, node);\n });\n // Add any complete children we have from the set\n merge_1.getCompleteChildren().forEach(function (namedNode) {\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\n });\n return completeChildren;\n }\n else {\n // We don't have anything to layer on top of. Layer on any children we have\n // Note that we can return an empty snap if we have a defined delete\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n merge.getCompleteChildren().forEach(function (namedNode) {\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\n });\n return completeChildren;\n }\n };\n /**\n * Given that the underlying server data has updated, determine what, if anything, needs to be\n * applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events\n *\n * Either existingEventSnap or existingServerSnap must exist\n *\n * @param {!Path} treePath\n * @param {!Path} childPath\n * @param {?Node} existingEventSnap\n * @param {?Node} existingServerSnap\n * @return {?Node}\n */\n WriteTree.prototype.calcEventCacheAfterServerOverwrite = function (treePath, childPath, existingEventSnap, existingServerSnap) {\n util_2.assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');\n var path = treePath.child(childPath);\n if (this.visibleWrites_.hasCompleteWrite(path)) {\n // At this point we can probably guarantee that we're in case 2, meaning no events\n // May need to check visibility while doing the findRootMostValueAndPath call\n return null;\n }\n else {\n // No complete shadowing. We're either partially shadowing or not shadowing at all.\n var childMerge = this.visibleWrites_.childCompoundWrite(path);\n if (childMerge.isEmpty()) {\n // We're not shadowing at all. Case 1\n return existingServerSnap.getChild(childPath);\n }\n else {\n // This could be more efficient if the serverNode + updates doesn't change the eventSnap\n // However this is tricky to find out, since user updates don't necessary change the server\n // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server\n // adds nodes, but doesn't change any existing writes. It is therefore not enough to\n // only check if the updates change the serverNode.\n // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?\n return childMerge.apply(existingServerSnap.getChild(childPath));\n }\n }\n };\n /**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n *\n * @param {!Path} treePath\n * @param {!string} childKey\n * @param {!CacheNode} existingServerSnap\n * @return {?Node}\n */\n WriteTree.prototype.calcCompleteChild = function (treePath, childKey, existingServerSnap) {\n var path = treePath.child(childKey);\n var shadowingNode = this.visibleWrites_.getCompleteNode(path);\n if (shadowingNode != null) {\n return shadowingNode;\n }\n else {\n if (existingServerSnap.isCompleteForChild(childKey)) {\n var childMerge = this.visibleWrites_.childCompoundWrite(path);\n return childMerge.apply(existingServerSnap.getNode().getImmediateChild(childKey));\n }\n else {\n return null;\n }\n }\n };\n /**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTree.prototype.shadowingWrite = function (path) {\n return this.visibleWrites_.getCompleteNode(path);\n };\n /**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window.\n *\n * @param {!Path} treePath\n * @param {?Node} completeServerData\n * @param {!NamedNode} startPost\n * @param {!number} count\n * @param {boolean} reverse\n * @param {!Index} index\n * @return {!Array.}\n */\n WriteTree.prototype.calcIndexedSlice = function (treePath, completeServerData, startPost, count, reverse, index) {\n var toIterate;\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n var shadowingNode = merge.getCompleteNode(Path_1.Path.Empty);\n if (shadowingNode != null) {\n toIterate = shadowingNode;\n }\n else if (completeServerData != null) {\n toIterate = merge.apply(completeServerData);\n }\n else {\n // no children to iterate on\n return [];\n }\n toIterate = toIterate.withIndex(index);\n if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {\n var nodes = [];\n var cmp = index.getCompare();\n var iter = reverse\n ? toIterate.getReverseIteratorFrom(startPost, index)\n : toIterate.getIteratorFrom(startPost, index);\n var next = iter.getNext();\n while (next && nodes.length < count) {\n if (cmp(next, startPost) !== 0) {\n nodes.push(next);\n }\n next = iter.getNext();\n }\n return nodes;\n }\n else {\n return [];\n }\n };\n /**\n * @param {!WriteRecord} writeRecord\n * @param {!Path} path\n * @return {boolean}\n * @private\n */\n WriteTree.prototype.recordContainsPath_ = function (writeRecord, path) {\n if (writeRecord.snap) {\n return writeRecord.path.contains(path);\n }\n else {\n // findKey can return undefined, so use !! to coerce to boolean\n return !!util_1.findKey(writeRecord.children, function (childSnap, childName) {\n return writeRecord.path.child(childName).contains(path);\n });\n }\n };\n /**\n * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots\n * @private\n */\n WriteTree.prototype.resetTree_ = function () {\n this.visibleWrites_ = WriteTree.layerTree_(this.allWrites_, WriteTree.DefaultFilter_, Path_1.Path.Empty);\n if (this.allWrites_.length > 0) {\n this.lastWriteId_ = this.allWrites_[this.allWrites_.length - 1].writeId;\n }\n else {\n this.lastWriteId_ = -1;\n }\n };\n /**\n * The default filter used when constructing the tree. Keep everything that's visible.\n *\n * @param {!WriteRecord} write\n * @return {boolean}\n * @private\n */\n WriteTree.DefaultFilter_ = function (write) {\n return write.visible;\n };\n /**\n * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of\n * event data at that path.\n *\n * @param {!Array.} writes\n * @param {!function(!WriteRecord):boolean} filter\n * @param {!Path} treeRoot\n * @return {!CompoundWrite}\n * @private\n */\n WriteTree.layerTree_ = function (writes, filter, treeRoot) {\n var compoundWrite = CompoundWrite_1.CompoundWrite.Empty;\n for (var i = 0; i < writes.length; ++i) {\n var write = writes[i];\n // Theory, a later set will either:\n // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction\n // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction\n if (filter(write)) {\n var writePath = write.path;\n var relativePath = void 0;\n if (write.snap) {\n if (treeRoot.contains(writePath)) {\n relativePath = Path_1.Path.relativePath(treeRoot, writePath);\n compoundWrite = compoundWrite.addWrite(relativePath, write.snap);\n }\n else if (writePath.contains(treeRoot)) {\n relativePath = Path_1.Path.relativePath(writePath, treeRoot);\n compoundWrite = compoundWrite.addWrite(Path_1.Path.Empty, write.snap.getChild(relativePath));\n }\n else {\n // There is no overlap between root path and write path, ignore write\n }\n }\n else if (write.children) {\n if (treeRoot.contains(writePath)) {\n relativePath = Path_1.Path.relativePath(treeRoot, writePath);\n compoundWrite = compoundWrite.addWrites(relativePath, write.children);\n }\n else if (writePath.contains(treeRoot)) {\n relativePath = Path_1.Path.relativePath(writePath, treeRoot);\n if (relativePath.isEmpty()) {\n compoundWrite = compoundWrite.addWrites(Path_1.Path.Empty, write.children);\n }\n else {\n var child = util_1.safeGet(write.children, relativePath.getFront());\n if (child) {\n // There exists a child in this node that matches the root path\n var deepNode = child.getChild(relativePath.popFront());\n compoundWrite = compoundWrite.addWrite(Path_1.Path.Empty, deepNode);\n }\n }\n }\n else {\n // There is no overlap between root path and write path, ignore write\n }\n }\n else {\n throw util_2.assertionError('WriteRecord should have .snap or .children');\n }\n }\n }\n return compoundWrite;\n };\n return WriteTree;\n}());\nexports.WriteTree = WriteTree;\n/**\n * A WriteTreeRef wraps a WriteTree and a path, for convenient access to a particular subtree. All of the methods\n * just proxy to the underlying WriteTree.\n *\n * @constructor\n */\nvar WriteTreeRef = /** @class */ (function () {\n /**\n * @param {!Path} path\n * @param {!WriteTree} writeTree\n */\n function WriteTreeRef(path, writeTree) {\n this.treePath_ = path;\n this.writeTree_ = writeTree;\n }\n /**\n * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used\n * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node\n * can lead to a more expensive calculation.\n *\n * @param {?Node} completeServerCache\n * @param {Array.=} writeIdsToExclude Optional writes to exclude.\n * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcCompleteEventCache = function (completeServerCache, writeIdsToExclude, includeHiddenWrites) {\n return this.writeTree_.calcCompleteEventCache(this.treePath_, completeServerCache, writeIdsToExclude, includeHiddenWrites);\n };\n /**\n * If possible, returns a children node containing all of the complete children we have data for. The returned data is a\n * mix of the given server data and write data.\n *\n * @param {?ChildrenNode} completeServerChildren\n * @return {!ChildrenNode}\n */\n WriteTreeRef.prototype.calcCompleteEventChildren = function (completeServerChildren) {\n return this.writeTree_.calcCompleteEventChildren(this.treePath_, completeServerChildren);\n };\n /**\n * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,\n * if anything, needs to be applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events should be raised\n *\n * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert\n *\n * @param {!Path} path\n * @param {?Node} existingEventSnap\n * @param {?Node} existingServerSnap\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcEventCacheAfterServerOverwrite = function (path, existingEventSnap, existingServerSnap) {\n return this.writeTree_.calcEventCacheAfterServerOverwrite(this.treePath_, path, existingEventSnap, existingServerSnap);\n };\n /**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTreeRef.prototype.shadowingWrite = function (path) {\n return this.writeTree_.shadowingWrite(this.treePath_.child(path));\n };\n /**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window\n *\n * @param {?Node} completeServerData\n * @param {!NamedNode} startPost\n * @param {!number} count\n * @param {boolean} reverse\n * @param {!Index} index\n * @return {!Array.}\n */\n WriteTreeRef.prototype.calcIndexedSlice = function (completeServerData, startPost, count, reverse, index) {\n return this.writeTree_.calcIndexedSlice(this.treePath_, completeServerData, startPost, count, reverse, index);\n };\n /**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n *\n * @param {!string} childKey\n * @param {!CacheNode} existingServerCache\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcCompleteChild = function (childKey, existingServerCache) {\n return this.writeTree_.calcCompleteChild(this.treePath_, childKey, existingServerCache);\n };\n /**\n * Return a WriteTreeRef for a child.\n *\n * @param {string} childName\n * @return {!WriteTreeRef}\n */\n WriteTreeRef.prototype.child = function (childName) {\n return new WriteTreeRef(this.treePath_.child(childName), this.writeTree_);\n };\n return WriteTreeRef;\n}());\nexports.WriteTreeRef = WriteTreeRef;\n\n//# sourceMappingURL=WriteTree.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/WriteTree.js\n// module id = 96\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ImmutableTree_1 = require(\"./util/ImmutableTree\");\nvar Path_1 = require(\"./util/Path\");\nvar util_1 = require(\"@firebase/util\");\nvar Node_1 = require(\"./snap/Node\");\nvar PriorityIndex_1 = require(\"./snap/indexes/PriorityIndex\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with\n * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write\n * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write\n * to reflect the write added.\n *\n * @constructor\n * @param {!ImmutableTree.} writeTree\n */\nvar CompoundWrite = /** @class */ (function () {\n function CompoundWrite(writeTree_) {\n this.writeTree_ = writeTree_;\n }\n /**\n * @param {!Path} path\n * @param {!Node} node\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.addWrite = function (path, node) {\n if (path.isEmpty()) {\n return new CompoundWrite(new ImmutableTree_1.ImmutableTree(node));\n }\n else {\n var rootmost = this.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n var rootMostPath = rootmost.path;\n var value = rootmost.value;\n var relativePath = Path_1.Path.relativePath(rootMostPath, path);\n value = value.updateChild(relativePath, node);\n return new CompoundWrite(this.writeTree_.set(rootMostPath, value));\n }\n else {\n var subtree = new ImmutableTree_1.ImmutableTree(node);\n var newWriteTree = this.writeTree_.setTree(path, subtree);\n return new CompoundWrite(newWriteTree);\n }\n }\n };\n /**\n * @param {!Path} path\n * @param {!Object.} updates\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.addWrites = function (path, updates) {\n var newWrite = this;\n util_1.forEach(updates, function (childKey, node) {\n newWrite = newWrite.addWrite(path.child(childKey), node);\n });\n return newWrite;\n };\n /**\n * Will remove a write at the given path and deeper paths. This will not modify a write at a higher\n * location, which must be removed by calling this method with that path.\n *\n * @param {!Path} path The path at which a write and all deeper writes should be removed\n * @return {!CompoundWrite} The new CompoundWrite with the removed path\n */\n CompoundWrite.prototype.removeWrite = function (path) {\n if (path.isEmpty()) {\n return CompoundWrite.Empty;\n }\n else {\n var newWriteTree = this.writeTree_.setTree(path, ImmutableTree_1.ImmutableTree.Empty);\n return new CompoundWrite(newWriteTree);\n }\n };\n /**\n * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be\n * considered \"complete\".\n *\n * @param {!Path} path The path to check for\n * @return {boolean} Whether there is a complete write at that path\n */\n CompoundWrite.prototype.hasCompleteWrite = function (path) {\n return this.getCompleteNode(path) != null;\n };\n /**\n * Returns a node for a path if and only if the node is a \"complete\" overwrite at that path. This will not aggregate\n * writes from deeper paths, but will return child nodes from a more shallow path.\n *\n * @param {!Path} path The path to get a complete write\n * @return {?Node} The node if complete at that path, or null otherwise.\n */\n CompoundWrite.prototype.getCompleteNode = function (path) {\n var rootmost = this.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n return this.writeTree_\n .get(rootmost.path)\n .getChild(Path_1.Path.relativePath(rootmost.path, path));\n }\n else {\n return null;\n }\n };\n /**\n * Returns all children that are guaranteed to be a complete overwrite.\n *\n * @return {!Array.} A list of all complete children.\n */\n CompoundWrite.prototype.getCompleteChildren = function () {\n var children = [];\n var node = this.writeTree_.value;\n if (node != null) {\n // If it's a leaf node, it has no children; so nothing to do.\n if (!node.isLeafNode()) {\n node.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n children.push(new Node_1.NamedNode(childName, childNode));\n });\n }\n }\n else {\n this.writeTree_.children.inorderTraversal(function (childName, childTree) {\n if (childTree.value != null) {\n children.push(new Node_1.NamedNode(childName, childTree.value));\n }\n });\n }\n return children;\n };\n /**\n * @param {!Path} path\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.childCompoundWrite = function (path) {\n if (path.isEmpty()) {\n return this;\n }\n else {\n var shadowingNode = this.getCompleteNode(path);\n if (shadowingNode != null) {\n return new CompoundWrite(new ImmutableTree_1.ImmutableTree(shadowingNode));\n }\n else {\n return new CompoundWrite(this.writeTree_.subtree(path));\n }\n }\n };\n /**\n * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.\n * @return {boolean} Whether this CompoundWrite is empty\n */\n CompoundWrite.prototype.isEmpty = function () {\n return this.writeTree_.isEmpty();\n };\n /**\n * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the\n * node\n * @param {!Node} node The node to apply this CompoundWrite to\n * @return {!Node} The node with all writes applied\n */\n CompoundWrite.prototype.apply = function (node) {\n return CompoundWrite.applySubtreeWrite_(Path_1.Path.Empty, this.writeTree_, node);\n };\n /**\n * @type {!CompoundWrite}\n */\n CompoundWrite.Empty = new CompoundWrite(new ImmutableTree_1.ImmutableTree(null));\n /**\n * @param {!Path} relativePath\n * @param {!ImmutableTree.} writeTree\n * @param {!Node} node\n * @return {!Node}\n * @private\n */\n CompoundWrite.applySubtreeWrite_ = function (relativePath, writeTree, node) {\n if (writeTree.value != null) {\n // Since there a write is always a leaf, we're done here\n return node.updateChild(relativePath, writeTree.value);\n }\n else {\n var priorityWrite_1 = null;\n writeTree.children.inorderTraversal(function (childKey, childTree) {\n if (childKey === '.priority') {\n // Apply priorities at the end so we don't update priorities for either empty nodes or forget\n // to apply priorities to empty nodes that are later filled\n util_2.assert(childTree.value !== null, 'Priority writes must always be leaf nodes');\n priorityWrite_1 = childTree.value;\n }\n else {\n node = CompoundWrite.applySubtreeWrite_(relativePath.child(childKey), childTree, node);\n }\n });\n // If there was a priority write, we only apply it if the node is not empty\n if (!node.getChild(relativePath).isEmpty() && priorityWrite_1 !== null) {\n node = node.updateChild(relativePath.child('.priority'), priorityWrite_1);\n }\n return node;\n }\n };\n return CompoundWrite;\n}());\nexports.CompoundWrite = CompoundWrite;\n\n//# sourceMappingURL=CompoundWrite.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/CompoundWrite.js\n// module id = 97\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ChildrenNode_1 = require(\"./snap/ChildrenNode\");\n/**\n * Mutable object which basically just stores a reference to the \"latest\" immutable snapshot.\n *\n * @constructor\n */\nvar SnapshotHolder = /** @class */ (function () {\n function SnapshotHolder() {\n this.rootNode_ = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n SnapshotHolder.prototype.getNode = function (path) {\n return this.rootNode_.getChild(path);\n };\n SnapshotHolder.prototype.updateSnapshot = function (path, newSnapshotNode) {\n this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);\n };\n return SnapshotHolder;\n}());\nexports.SnapshotHolder = SnapshotHolder;\n\n//# sourceMappingURL=SnapshotHolder.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/SnapshotHolder.js\n// module id = 98\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"./util/util\");\n/**\n * Abstraction around FirebaseApp's token fetching capabilities.\n */\nvar AuthTokenProvider = /** @class */ (function () {\n /**\n * @param {!FirebaseApp} app_\n */\n function AuthTokenProvider(app_) {\n this.app_ = app_;\n }\n /**\n * @param {boolean} forceRefresh\n * @return {!Promise}\n */\n AuthTokenProvider.prototype.getToken = function (forceRefresh) {\n return this.app_['INTERNAL']['getToken'](forceRefresh).then(null, \n // .catch\n function (error) {\n // TODO: Need to figure out all the cases this is raised and whether\n // this makes sense.\n if (error && error.code === 'auth/token-not-initialized') {\n util_1.log('Got auth/token-not-initialized error. Treating as null token.');\n return null;\n }\n else {\n return Promise.reject(error);\n }\n });\n };\n AuthTokenProvider.prototype.addTokenChangeListener = function (listener) {\n // TODO: We might want to wrap the listener and call it with no args to\n // avoid a leaky abstraction, but that makes removing the listener harder.\n this.app_['INTERNAL']['addAuthTokenListener'](listener);\n };\n AuthTokenProvider.prototype.removeTokenChangeListener = function (listener) {\n this.app_['INTERNAL']['removeAuthTokenListener'](listener);\n };\n AuthTokenProvider.prototype.notifyForInvalidToken = function () {\n var errorMessage = 'Provided authentication credentials for the app named \"' +\n this.app_.name +\n '\" are invalid. This usually indicates your app was not ' +\n 'initialized correctly. ';\n if ('credential' in this.app_.options) {\n errorMessage +=\n 'Make sure the \"credential\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n }\n else if ('serviceAccount' in this.app_.options) {\n errorMessage +=\n 'Make sure the \"serviceAccount\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n }\n else {\n errorMessage +=\n 'Make sure the \"apiKey\" and \"databaseURL\" properties provided to ' +\n 'initializeApp() match the values provided for your app at ' +\n 'https://console.firebase.google.com/.';\n }\n util_1.warn(errorMessage);\n };\n return AuthTokenProvider;\n}());\nexports.AuthTokenProvider = AuthTokenProvider;\n\n//# sourceMappingURL=AuthTokenProvider.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/AuthTokenProvider.js\n// module id = 99\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * Tracks a collection of stats.\n *\n * @constructor\n */\nvar StatsCollection = /** @class */ (function () {\n function StatsCollection() {\n this.counters_ = {};\n }\n StatsCollection.prototype.incrementCounter = function (name, amount) {\n if (amount === void 0) { amount = 1; }\n if (!util_2.contains(this.counters_, name))\n this.counters_[name] = 0;\n this.counters_[name] += amount;\n };\n StatsCollection.prototype.get = function () {\n return util_1.deepCopy(this.counters_);\n };\n return StatsCollection;\n}());\nexports.StatsCollection = StatsCollection;\n\n//# sourceMappingURL=StatsCollection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/stats/StatsCollection.js\n// module id = 100\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../util/util\");\nvar StatsListener_1 = require(\"./StatsListener\");\n// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably\n// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10\n// seconds to try to ensure the Firebase connection is established / settled.\nvar FIRST_STATS_MIN_TIME = 10 * 1000;\nvar FIRST_STATS_MAX_TIME = 30 * 1000;\n// We'll continue to report stats on average every 5 minutes.\nvar REPORT_STATS_INTERVAL = 5 * 60 * 1000;\n/**\n * @constructor\n */\nvar StatsReporter = /** @class */ (function () {\n /**\n * @param collection\n * @param server_\n */\n function StatsReporter(collection, server_) {\n this.server_ = server_;\n this.statsToReport_ = {};\n this.statsListener_ = new StatsListener_1.StatsListener(collection);\n var timeout = FIRST_STATS_MIN_TIME +\n (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();\n util_2.setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));\n }\n StatsReporter.prototype.includeStat = function (stat) {\n this.statsToReport_[stat] = true;\n };\n StatsReporter.prototype.reportStats_ = function () {\n var _this = this;\n var stats = this.statsListener_.get();\n var reportedStats = {};\n var haveStatsToReport = false;\n util_1.forEach(stats, function (stat, value) {\n if (value > 0 && util_1.contains(_this.statsToReport_, stat)) {\n reportedStats[stat] = value;\n haveStatsToReport = true;\n }\n });\n if (haveStatsToReport) {\n this.server_.reportStats(reportedStats);\n }\n // queue our next run.\n util_2.setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));\n };\n return StatsReporter;\n}());\nexports.StatsReporter = StatsReporter;\n\n//# sourceMappingURL=StatsReporter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/stats/StatsReporter.js\n// module id = 101\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../util/util\");\n/**\n * The event queue serves a few purposes:\n * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more\n * events being queued.\n * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,\n * raiseQueuedEvents() is called again, the \"inner\" call will pick up raising events where the \"outer\" call\n * left off, ensuring that the events are still raised synchronously and in order.\n * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued\n * events are raised synchronously.\n *\n * NOTE: This can all go away if/when we move to async events.\n *\n * @constructor\n */\nvar EventQueue = /** @class */ (function () {\n function EventQueue() {\n /**\n * @private\n * @type {!Array.}\n */\n this.eventLists_ = [];\n /**\n * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.\n * @private\n * @type {!number}\n */\n this.recursionDepth_ = 0;\n }\n /**\n * @param {!Array.} eventDataList The new events to queue.\n */\n EventQueue.prototype.queueEvents = function (eventDataList) {\n // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.\n var currList = null;\n for (var i = 0; i < eventDataList.length; i++) {\n var eventData = eventDataList[i];\n var eventPath = eventData.getPath();\n if (currList !== null && !eventPath.equals(currList.getPath())) {\n this.eventLists_.push(currList);\n currList = null;\n }\n if (currList === null) {\n currList = new EventList(eventPath);\n }\n currList.add(eventData);\n }\n if (currList) {\n this.eventLists_.push(currList);\n }\n };\n /**\n * Queues the specified events and synchronously raises all events (including previously queued ones)\n * for the specified path.\n *\n * It is assumed that the new events are all for the specified path.\n *\n * @param {!Path} path The path to raise events for.\n * @param {!Array.} eventDataList The new events to raise.\n */\n EventQueue.prototype.raiseEventsAtPath = function (path, eventDataList) {\n this.queueEvents(eventDataList);\n this.raiseQueuedEventsMatchingPredicate_(function (eventPath) {\n return eventPath.equals(path);\n });\n };\n /**\n * Queues the specified events and synchronously raises all events (including previously queued ones) for\n * locations related to the specified change path (i.e. all ancestors and descendants).\n *\n * It is assumed that the new events are all related (ancestor or descendant) to the specified path.\n *\n * @param {!Path} changedPath The path to raise events for.\n * @param {!Array.} eventDataList The events to raise\n */\n EventQueue.prototype.raiseEventsForChangedPath = function (changedPath, eventDataList) {\n this.queueEvents(eventDataList);\n this.raiseQueuedEventsMatchingPredicate_(function (eventPath) {\n return eventPath.contains(changedPath) || changedPath.contains(eventPath);\n });\n };\n /**\n * @param {!function(!Path):boolean} predicate\n * @private\n */\n EventQueue.prototype.raiseQueuedEventsMatchingPredicate_ = function (predicate) {\n this.recursionDepth_++;\n var sentAll = true;\n for (var i = 0; i < this.eventLists_.length; i++) {\n var eventList = this.eventLists_[i];\n if (eventList) {\n var eventPath = eventList.getPath();\n if (predicate(eventPath)) {\n this.eventLists_[i].raise();\n this.eventLists_[i] = null;\n }\n else {\n sentAll = false;\n }\n }\n }\n if (sentAll) {\n this.eventLists_ = [];\n }\n this.recursionDepth_--;\n };\n return EventQueue;\n}());\nexports.EventQueue = EventQueue;\n/**\n * @param {!Path} path\n * @constructor\n */\nvar EventList = /** @class */ (function () {\n function EventList(path_) {\n this.path_ = path_;\n /**\n * @type {!Array.}\n * @private\n */\n this.events_ = [];\n }\n /**\n * @param {!Event} eventData\n */\n EventList.prototype.add = function (eventData) {\n this.events_.push(eventData);\n };\n /**\n * Iterates through the list and raises each event\n */\n EventList.prototype.raise = function () {\n for (var i = 0; i < this.events_.length; i++) {\n var eventData = this.events_[i];\n if (eventData !== null) {\n this.events_[i] = null;\n var eventFn = eventData.getEventRunner();\n if (util_1.logger) {\n util_1.log('event: ' + eventData.toString());\n }\n util_1.exceptionGuard(eventFn);\n }\n }\n };\n /**\n * @return {!Path}\n */\n EventList.prototype.getPath = function () {\n return this.path_;\n };\n return EventList;\n}());\nexports.EventList = EventList;\n\n//# sourceMappingURL=EventQueue.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/EventQueue.js\n// module id = 102\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar EventEmitter_1 = require(\"./EventEmitter\");\nvar util_1 = require(\"@firebase/util\");\n/**\n * @extends {EventEmitter}\n */\nvar VisibilityMonitor = /** @class */ (function (_super) {\n tslib_1.__extends(VisibilityMonitor, _super);\n function VisibilityMonitor() {\n var _this = _super.call(this, ['visible']) || this;\n var hidden;\n var visibilityChange;\n if (typeof document !== 'undefined' &&\n typeof document.addEventListener !== 'undefined') {\n if (typeof document['hidden'] !== 'undefined') {\n // Opera 12.10 and Firefox 18 and later support\n visibilityChange = 'visibilitychange';\n hidden = 'hidden';\n }\n else if (typeof document['mozHidden'] !== 'undefined') {\n visibilityChange = 'mozvisibilitychange';\n hidden = 'mozHidden';\n }\n else if (typeof document['msHidden'] !== 'undefined') {\n visibilityChange = 'msvisibilitychange';\n hidden = 'msHidden';\n }\n else if (typeof document['webkitHidden'] !== 'undefined') {\n visibilityChange = 'webkitvisibilitychange';\n hidden = 'webkitHidden';\n }\n }\n // Initially, we always assume we are visible. This ensures that in browsers\n // without page visibility support or in cases where we are never visible\n // (e.g. chrome extension), we act as if we are visible, i.e. don't delay\n // reconnects\n _this.visible_ = true;\n if (visibilityChange) {\n document.addEventListener(visibilityChange, function () {\n var visible = !document[hidden];\n if (visible !== _this.visible_) {\n _this.visible_ = visible;\n _this.trigger('visible', visible);\n }\n }, false);\n }\n return _this;\n }\n VisibilityMonitor.getInstance = function () {\n return new VisibilityMonitor();\n };\n /**\n * @param {!string} eventType\n * @return {Array.}\n */\n VisibilityMonitor.prototype.getInitialEvent = function (eventType) {\n util_1.assert(eventType === 'visible', 'Unknown event type: ' + eventType);\n return [this.visible_];\n };\n return VisibilityMonitor;\n}(EventEmitter_1.EventEmitter));\nexports.VisibilityMonitor = VisibilityMonitor;\n\n//# sourceMappingURL=VisibilityMonitor.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/VisibilityMonitor.js\n// module id = 103\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar util_1 = require(\"@firebase/util\");\nvar EventEmitter_1 = require(\"./EventEmitter\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * Monitors online state (as reported by window.online/offline events).\n *\n * The expectation is that this could have many false positives (thinks we are online\n * when we're not), but no false negatives. So we can safely use it to determine when\n * we definitely cannot reach the internet.\n *\n * @extends {EventEmitter}\n */\nvar OnlineMonitor = /** @class */ (function (_super) {\n tslib_1.__extends(OnlineMonitor, _super);\n function OnlineMonitor() {\n var _this = _super.call(this, ['online']) || this;\n _this.online_ = true;\n // We've had repeated complaints that Cordova apps can get stuck \"offline\", e.g.\n // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810\n // It would seem that the 'online' event does not always fire consistently. So we disable it\n // for Cordova.\n if (typeof window !== 'undefined' &&\n typeof window.addEventListener !== 'undefined' &&\n !util_2.isMobileCordova()) {\n window.addEventListener('online', function () {\n if (!_this.online_) {\n _this.online_ = true;\n _this.trigger('online', true);\n }\n }, false);\n window.addEventListener('offline', function () {\n if (_this.online_) {\n _this.online_ = false;\n _this.trigger('online', false);\n }\n }, false);\n }\n return _this;\n }\n OnlineMonitor.getInstance = function () {\n return new OnlineMonitor();\n };\n /**\n * @param {!string} eventType\n * @return {Array.}\n */\n OnlineMonitor.prototype.getInitialEvent = function (eventType) {\n util_1.assert(eventType === 'online', 'Unknown event type: ' + eventType);\n return [this.online_];\n };\n /**\n * @return {boolean}\n */\n OnlineMonitor.prototype.currentlyOnline = function () {\n return this.online_;\n };\n return OnlineMonitor;\n}(EventEmitter_1.EventEmitter));\nexports.OnlineMonitor = OnlineMonitor;\n\n//# sourceMappingURL=OnlineMonitor.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/OnlineMonitor.js\n// module id = 104\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar BrowserPollConnection_1 = require(\"./BrowserPollConnection\");\nvar WebSocketConnection_1 = require(\"./WebSocketConnection\");\nvar util_1 = require(\"../core/util/util\");\n/**\n * Currently simplistic, this class manages what transport a Connection should use at various stages of its\n * lifecycle.\n *\n * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if\n * they are available.\n * @constructor\n */\nvar TransportManager = /** @class */ (function () {\n /**\n * @param {!RepoInfo} repoInfo Metadata around the namespace we're connecting to\n */\n function TransportManager(repoInfo) {\n this.initTransports_(repoInfo);\n }\n Object.defineProperty(TransportManager, \"ALL_TRANSPORTS\", {\n /**\n * @const\n * @type {!Array.}\n */\n get: function () {\n return [BrowserPollConnection_1.BrowserPollConnection, WebSocketConnection_1.WebSocketConnection];\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @param {!RepoInfo} repoInfo\n * @private\n */\n TransportManager.prototype.initTransports_ = function (repoInfo) {\n var isWebSocketsAvailable = WebSocketConnection_1.WebSocketConnection && WebSocketConnection_1.WebSocketConnection['isAvailable']();\n var isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection_1.WebSocketConnection.previouslyFailed();\n if (repoInfo.webSocketOnly) {\n if (!isWebSocketsAvailable)\n util_1.warn(\"wss:// URL used, but browser isn't known to support websockets. Trying anyway.\");\n isSkipPollConnection = true;\n }\n if (isSkipPollConnection) {\n this.transports_ = [WebSocketConnection_1.WebSocketConnection];\n }\n else {\n var transports_1 = (this.transports_ = []);\n util_1.each(TransportManager.ALL_TRANSPORTS, function (i, transport) {\n if (transport && transport['isAvailable']()) {\n transports_1.push(transport);\n }\n });\n }\n };\n /**\n * @return {function(new:Transport, !string, !RepoInfo, string=, string=)} The constructor for the\n * initial transport to use\n */\n TransportManager.prototype.initialTransport = function () {\n if (this.transports_.length > 0) {\n return this.transports_[0];\n }\n else {\n throw new Error('No transports available');\n }\n };\n /**\n * @return {?function(new:Transport, function(),function(), string=)} The constructor for the next\n * transport, or null\n */\n TransportManager.prototype.upgradeTransport = function () {\n if (this.transports_.length > 1) {\n return this.transports_[1];\n }\n else {\n return null;\n }\n };\n return TransportManager;\n}());\nexports.TransportManager = TransportManager;\n\n//# sourceMappingURL=TransportManager.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/TransportManager.js\n// module id = 105\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../../core/util/util\");\n/**\n * This class ensures the packets from the server arrive in order\n * This class takes data from the server and ensures it gets passed into the callbacks in order.\n * @constructor\n */\nvar PacketReceiver = /** @class */ (function () {\n /**\n * @param onMessage_\n */\n function PacketReceiver(onMessage_) {\n this.onMessage_ = onMessage_;\n this.pendingResponses = [];\n this.currentResponseNum = 0;\n this.closeAfterResponse = -1;\n this.onClose = null;\n }\n PacketReceiver.prototype.closeAfter = function (responseNum, callback) {\n this.closeAfterResponse = responseNum;\n this.onClose = callback;\n if (this.closeAfterResponse < this.currentResponseNum) {\n this.onClose();\n this.onClose = null;\n }\n };\n /**\n * Each message from the server comes with a response number, and an array of data. The responseNumber\n * allows us to ensure that we process them in the right order, since we can't be guaranteed that all\n * browsers will respond in the same order as the requests we sent\n * @param {number} requestNum\n * @param {Array} data\n */\n PacketReceiver.prototype.handleResponse = function (requestNum, data) {\n var _this = this;\n this.pendingResponses[requestNum] = data;\n var _loop_1 = function () {\n var toProcess = this_1.pendingResponses[this_1.currentResponseNum];\n delete this_1.pendingResponses[this_1.currentResponseNum];\n var _loop_2 = function (i) {\n if (toProcess[i]) {\n util_1.exceptionGuard(function () {\n _this.onMessage_(toProcess[i]);\n });\n }\n };\n for (var i = 0; i < toProcess.length; ++i) {\n _loop_2(i);\n }\n if (this_1.currentResponseNum === this_1.closeAfterResponse) {\n if (this_1.onClose) {\n this_1.onClose();\n this_1.onClose = null;\n }\n return \"break\";\n }\n this_1.currentResponseNum++;\n };\n var this_1 = this;\n while (this.pendingResponses[this.currentResponseNum]) {\n var state_1 = _loop_1();\n if (state_1 === \"break\")\n break;\n }\n };\n return PacketReceiver;\n}());\nexports.PacketReceiver = PacketReceiver;\n\n//# sourceMappingURL=PacketReceiver.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/polling/PacketReceiver.js\n// module id = 106\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"./util/util\");\nvar util_3 = require(\"@firebase/util\");\nvar util_4 = require(\"@firebase/util\");\nvar util_5 = require(\"@firebase/util\");\nvar ServerActions_1 = require(\"./ServerActions\");\n/**\n * An implementation of ServerActions that communicates with the server via REST requests.\n * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full\n * persistent connection (using WebSockets or long-polling)\n */\nvar ReadonlyRestClient = /** @class */ (function (_super) {\n tslib_1.__extends(ReadonlyRestClient, _super);\n /**\n * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to\n * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server\n * @param {AuthTokenProvider} authTokenProvider_\n * @implements {ServerActions}\n */\n function ReadonlyRestClient(repoInfo_, onDataUpdate_, authTokenProvider_) {\n var _this = _super.call(this) || this;\n _this.repoInfo_ = repoInfo_;\n _this.onDataUpdate_ = onDataUpdate_;\n _this.authTokenProvider_ = authTokenProvider_;\n /** @private {function(...[*])} */\n _this.log_ = util_2.logWrapper('p:rest:');\n /**\n * We don't actually need to track listens, except to prevent us calling an onComplete for a listen\n * that's been removed. :-/\n *\n * @private {!Object.}\n */\n _this.listens_ = {};\n return _this;\n }\n ReadonlyRestClient.prototype.reportStats = function (stats) {\n throw new Error('Method not implemented.');\n };\n /**\n * @param {!Query} query\n * @param {?number=} tag\n * @return {string}\n * @private\n */\n ReadonlyRestClient.getListenId_ = function (query, tag) {\n if (tag !== undefined) {\n return 'tag$' + tag;\n }\n else {\n util_1.assert(query.getQueryParams().isDefault(), \"should have a tag if it's not a default query.\");\n return query.path.toString();\n }\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.listen = function (query, currentHashFn, tag, onComplete) {\n var _this = this;\n var pathString = query.path.toString();\n this.log_('Listen called for ' + pathString + ' ' + query.queryIdentifier());\n // Mark this listener so we can tell if it's removed.\n var listenId = ReadonlyRestClient.getListenId_(query, tag);\n var thisListen = {};\n this.listens_[listenId] = thisListen;\n var queryStringParamaters = query\n .getQueryParams()\n .toRestQueryStringParameters();\n this.restRequest_(pathString + '.json', queryStringParamaters, function (error, result) {\n var data = result;\n if (error === 404) {\n data = null;\n error = null;\n }\n if (error === null) {\n _this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);\n }\n if (util_4.safeGet(_this.listens_, listenId) === thisListen) {\n var status_1;\n if (!error) {\n status_1 = 'ok';\n }\n else if (error == 401) {\n status_1 = 'permission_denied';\n }\n else {\n status_1 = 'rest_error:' + error;\n }\n onComplete(status_1, null);\n }\n });\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.unlisten = function (query, tag) {\n var listenId = ReadonlyRestClient.getListenId_(query, tag);\n delete this.listens_[listenId];\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.refreshAuthToken = function (token) {\n // no-op since we just always call getToken.\n };\n /**\n * Performs a REST request to the given path, with the provided query string parameters,\n * and any auth credentials we have.\n *\n * @param {!string} pathString\n * @param {!Object.} queryStringParameters\n * @param {?function(?number, *=)} callback\n * @private\n */\n ReadonlyRestClient.prototype.restRequest_ = function (pathString, queryStringParameters, callback) {\n var _this = this;\n if (queryStringParameters === void 0) { queryStringParameters = {}; }\n queryStringParameters['format'] = 'export';\n this.authTokenProvider_\n .getToken(/*forceRefresh=*/ false)\n .then(function (authTokenData) {\n var authToken = authTokenData && authTokenData.accessToken;\n if (authToken) {\n queryStringParameters['auth'] = authToken;\n }\n var url = (_this.repoInfo_.secure ? 'https://' : 'http://') +\n _this.repoInfo_.host +\n pathString +\n '?' +\n util_5.querystring(queryStringParameters);\n _this.log_('Sending REST request for ' + url);\n var xhr = new XMLHttpRequest();\n xhr.onreadystatechange = function () {\n if (callback && xhr.readyState === 4) {\n _this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);\n var res = null;\n if (xhr.status >= 200 && xhr.status < 300) {\n try {\n res = util_3.jsonEval(xhr.responseText);\n }\n catch (e) {\n util_2.warn('Failed to parse JSON response for ' +\n url +\n ': ' +\n xhr.responseText);\n }\n callback(null, res);\n }\n else {\n // 401 and 404 are expected.\n if (xhr.status !== 401 && xhr.status !== 404) {\n util_2.warn('Got unsuccessful REST response for ' +\n url +\n ' Status: ' +\n xhr.status);\n }\n callback(xhr.status);\n }\n callback = null;\n }\n };\n xhr.open('GET', url, /*asynchronous=*/ true);\n xhr.send();\n });\n };\n return ReadonlyRestClient;\n}(ServerActions_1.ServerActions));\nexports.ReadonlyRestClient = ReadonlyRestClient;\n\n//# sourceMappingURL=ReadonlyRestClient.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/ReadonlyRestClient.js\n// module id = 107\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../util/util\");\nvar KeyIndex_1 = require(\"../snap/indexes/KeyIndex\");\nvar PriorityIndex_1 = require(\"../snap/indexes/PriorityIndex\");\nvar ValueIndex_1 = require(\"../snap/indexes/ValueIndex\");\nvar PathIndex_1 = require(\"../snap/indexes/PathIndex\");\nvar IndexedFilter_1 = require(\"./filter/IndexedFilter\");\nvar LimitedFilter_1 = require(\"./filter/LimitedFilter\");\nvar RangedFilter_1 = require(\"./filter/RangedFilter\");\nvar util_3 = require(\"@firebase/util\");\n/**\n * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a\n * range to be returned for a particular location. It is assumed that validation of parameters is done at the\n * user-facing API level, so it is not done here.\n * @constructor\n */\nvar QueryParams = /** @class */ (function () {\n function QueryParams() {\n this.limitSet_ = false;\n this.startSet_ = false;\n this.startNameSet_ = false;\n this.endSet_ = false;\n this.endNameSet_ = false;\n this.limit_ = 0;\n this.viewFrom_ = '';\n this.indexStartValue_ = null;\n this.indexStartName_ = '';\n this.indexEndValue_ = null;\n this.indexEndName_ = '';\n this.index_ = PriorityIndex_1.PRIORITY_INDEX;\n }\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasStart = function () {\n return this.startSet_;\n };\n /**\n * @return {boolean} True if it would return from left.\n */\n QueryParams.prototype.isViewFromLeft = function () {\n if (this.viewFrom_ === '') {\n // limit(), rather than limitToFirst or limitToLast was called.\n // This means that only one of startSet_ and endSet_ is true. Use them\n // to calculate which side of the view to anchor to. If neither is set,\n // anchor to the end.\n return this.startSet_;\n }\n else {\n return (this.viewFrom_ === QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT);\n }\n };\n /**\n * Only valid to call if hasStart() returns true\n * @return {*}\n */\n QueryParams.prototype.getIndexStartValue = function () {\n util_1.assert(this.startSet_, 'Only valid if start has been set');\n return this.indexStartValue_;\n };\n /**\n * Only valid to call if hasStart() returns true.\n * Returns the starting key name for the range defined by these query parameters\n * @return {!string}\n */\n QueryParams.prototype.getIndexStartName = function () {\n util_1.assert(this.startSet_, 'Only valid if start has been set');\n if (this.startNameSet_) {\n return this.indexStartName_;\n }\n else {\n return util_2.MIN_NAME;\n }\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasEnd = function () {\n return this.endSet_;\n };\n /**\n * Only valid to call if hasEnd() returns true.\n * @return {*}\n */\n QueryParams.prototype.getIndexEndValue = function () {\n util_1.assert(this.endSet_, 'Only valid if end has been set');\n return this.indexEndValue_;\n };\n /**\n * Only valid to call if hasEnd() returns true.\n * Returns the end key name for the range defined by these query parameters\n * @return {!string}\n */\n QueryParams.prototype.getIndexEndName = function () {\n util_1.assert(this.endSet_, 'Only valid if end has been set');\n if (this.endNameSet_) {\n return this.indexEndName_;\n }\n else {\n return util_2.MAX_NAME;\n }\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasLimit = function () {\n return this.limitSet_;\n };\n /**\n * @return {boolean} True if a limit has been set and it has been explicitly anchored\n */\n QueryParams.prototype.hasAnchoredLimit = function () {\n return this.limitSet_ && this.viewFrom_ !== '';\n };\n /**\n * Only valid to call if hasLimit() returns true\n * @return {!number}\n */\n QueryParams.prototype.getLimit = function () {\n util_1.assert(this.limitSet_, 'Only valid if limit has been set');\n return this.limit_;\n };\n /**\n * @return {!Index}\n */\n QueryParams.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @return {!QueryParams}\n * @private\n */\n QueryParams.prototype.copy_ = function () {\n var copy = new QueryParams();\n copy.limitSet_ = this.limitSet_;\n copy.limit_ = this.limit_;\n copy.startSet_ = this.startSet_;\n copy.indexStartValue_ = this.indexStartValue_;\n copy.startNameSet_ = this.startNameSet_;\n copy.indexStartName_ = this.indexStartName_;\n copy.endSet_ = this.endSet_;\n copy.indexEndValue_ = this.indexEndValue_;\n copy.endNameSet_ = this.endNameSet_;\n copy.indexEndName_ = this.indexEndName_;\n copy.index_ = this.index_;\n copy.viewFrom_ = this.viewFrom_;\n return copy;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limit = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = '';\n return newParams;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limitToFirst = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT;\n return newParams;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limitToLast = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_RIGHT;\n return newParams;\n };\n /**\n * @param {*} indexValue\n * @param {?string=} key\n * @return {!QueryParams}\n */\n QueryParams.prototype.startAt = function (indexValue, key) {\n var newParams = this.copy_();\n newParams.startSet_ = true;\n if (!(indexValue !== undefined)) {\n indexValue = null;\n }\n newParams.indexStartValue_ = indexValue;\n if (key != null) {\n newParams.startNameSet_ = true;\n newParams.indexStartName_ = key;\n }\n else {\n newParams.startNameSet_ = false;\n newParams.indexStartName_ = '';\n }\n return newParams;\n };\n /**\n * @param {*} indexValue\n * @param {?string=} key\n * @return {!QueryParams}\n */\n QueryParams.prototype.endAt = function (indexValue, key) {\n var newParams = this.copy_();\n newParams.endSet_ = true;\n if (!(indexValue !== undefined)) {\n indexValue = null;\n }\n newParams.indexEndValue_ = indexValue;\n if (key !== undefined) {\n newParams.endNameSet_ = true;\n newParams.indexEndName_ = key;\n }\n else {\n newParams.endNameSet_ = false;\n newParams.indexEndName_ = '';\n }\n return newParams;\n };\n /**\n * @param {!Index} index\n * @return {!QueryParams}\n */\n QueryParams.prototype.orderBy = function (index) {\n var newParams = this.copy_();\n newParams.index_ = index;\n return newParams;\n };\n /**\n * @return {!Object}\n */\n QueryParams.prototype.getQueryObject = function () {\n var WIRE_PROTOCOL_CONSTANTS = QueryParams.WIRE_PROTOCOL_CONSTANTS_;\n var obj = {};\n if (this.startSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE] = this.indexStartValue_;\n if (this.startNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME] = this.indexStartName_;\n }\n }\n if (this.endSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE] = this.indexEndValue_;\n if (this.endNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME] = this.indexEndName_;\n }\n }\n if (this.limitSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.LIMIT] = this.limit_;\n var viewFrom = this.viewFrom_;\n if (viewFrom === '') {\n if (this.isViewFromLeft()) {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n }\n else {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT;\n }\n }\n obj[WIRE_PROTOCOL_CONSTANTS.VIEW_FROM] = viewFrom;\n }\n // For now, priority index is the default, so we only specify if it's some other index\n if (this.index_ !== PriorityIndex_1.PRIORITY_INDEX) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX] = this.index_.toString();\n }\n return obj;\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.loadsAllData = function () {\n return !(this.startSet_ || this.endSet_ || this.limitSet_);\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.isDefault = function () {\n return this.loadsAllData() && this.index_ == PriorityIndex_1.PRIORITY_INDEX;\n };\n /**\n * @return {!NodeFilter}\n */\n QueryParams.prototype.getNodeFilter = function () {\n if (this.loadsAllData()) {\n return new IndexedFilter_1.IndexedFilter(this.getIndex());\n }\n else if (this.hasLimit()) {\n return new LimitedFilter_1.LimitedFilter(this);\n }\n else {\n return new RangedFilter_1.RangedFilter(this);\n }\n };\n /**\n * Returns a set of REST query string parameters representing this query.\n *\n * @return {!Object.} query string parameters\n */\n QueryParams.prototype.toRestQueryStringParameters = function () {\n var REST_CONSTANTS = QueryParams.REST_QUERY_CONSTANTS_;\n var qs = {};\n if (this.isDefault()) {\n return qs;\n }\n var orderBy;\n if (this.index_ === PriorityIndex_1.PRIORITY_INDEX) {\n orderBy = REST_CONSTANTS.PRIORITY_INDEX;\n }\n else if (this.index_ === ValueIndex_1.VALUE_INDEX) {\n orderBy = REST_CONSTANTS.VALUE_INDEX;\n }\n else if (this.index_ === KeyIndex_1.KEY_INDEX) {\n orderBy = REST_CONSTANTS.KEY_INDEX;\n }\n else {\n util_1.assert(this.index_ instanceof PathIndex_1.PathIndex, 'Unrecognized index type!');\n orderBy = this.index_.toString();\n }\n qs[REST_CONSTANTS.ORDER_BY] = util_3.stringify(orderBy);\n if (this.startSet_) {\n qs[REST_CONSTANTS.START_AT] = util_3.stringify(this.indexStartValue_);\n if (this.startNameSet_) {\n qs[REST_CONSTANTS.START_AT] += ',' + util_3.stringify(this.indexStartName_);\n }\n }\n if (this.endSet_) {\n qs[REST_CONSTANTS.END_AT] = util_3.stringify(this.indexEndValue_);\n if (this.endNameSet_) {\n qs[REST_CONSTANTS.END_AT] += ',' + util_3.stringify(this.indexEndName_);\n }\n }\n if (this.limitSet_) {\n if (this.isViewFromLeft()) {\n qs[REST_CONSTANTS.LIMIT_TO_FIRST] = this.limit_;\n }\n else {\n qs[REST_CONSTANTS.LIMIT_TO_LAST] = this.limit_;\n }\n }\n return qs;\n };\n /**\n * Wire Protocol Constants\n * @const\n * @enum {string}\n * @private\n */\n QueryParams.WIRE_PROTOCOL_CONSTANTS_ = {\n INDEX_START_VALUE: 'sp',\n INDEX_START_NAME: 'sn',\n INDEX_END_VALUE: 'ep',\n INDEX_END_NAME: 'en',\n LIMIT: 'l',\n VIEW_FROM: 'vf',\n VIEW_FROM_LEFT: 'l',\n VIEW_FROM_RIGHT: 'r',\n INDEX: 'i'\n };\n /**\n * REST Query Constants\n * @const\n * @enum {string}\n * @private\n */\n QueryParams.REST_QUERY_CONSTANTS_ = {\n ORDER_BY: 'orderBy',\n PRIORITY_INDEX: '$priority',\n VALUE_INDEX: '$value',\n KEY_INDEX: '$key',\n START_AT: 'startAt',\n END_AT: 'endAt',\n LIMIT_TO_FIRST: 'limitToFirst',\n LIMIT_TO_LAST: 'limitToLast'\n };\n /**\n * Default, empty query parameters\n * @type {!QueryParams}\n * @const\n */\n QueryParams.DEFAULT = new QueryParams();\n return QueryParams;\n}());\nexports.QueryParams = QueryParams;\n\n//# sourceMappingURL=QueryParams.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/QueryParams.js\n// module id = 108\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar RangedFilter_1 = require(\"./RangedFilter\");\nvar ChildrenNode_1 = require(\"../../snap/ChildrenNode\");\nvar Node_1 = require(\"../../snap/Node\");\nvar util_1 = require(\"@firebase/util\");\nvar Change_1 = require(\"../Change\");\n/**\n * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible\n *\n * @constructor\n * @implements {NodeFilter}\n */\nvar LimitedFilter = /** @class */ (function () {\n /**\n * @param {!QueryParams} params\n */\n function LimitedFilter(params) {\n this.rangedFilter_ = new RangedFilter_1.RangedFilter(params);\n this.index_ = params.getIndex();\n this.limit_ = params.getLimit();\n this.reverse_ = !params.isViewFromLeft();\n }\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n if (!this.rangedFilter_.matches(new Node_1.NamedNode(key, newChild))) {\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n if (snap.getImmediateChild(key).equals(newChild)) {\n // No change\n return snap;\n }\n else if (snap.numChildren() < this.limit_) {\n return this.rangedFilter_\n .getIndexedFilter()\n .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\n }\n else {\n return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);\n }\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n var filtered;\n if (newSnap.isLeafNode() || newSnap.isEmpty()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n filtered = ChildrenNode_1.ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n }\n else {\n if (this.limit_ * 2 < newSnap.numChildren() &&\n newSnap.isIndexed(this.index_)) {\n // Easier to build up a snapshot, since what we're given has more than twice the elements we want\n filtered = ChildrenNode_1.ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n // anchor to the startPost, endPost, or last element as appropriate\n var iterator = void 0;\n if (this.reverse_) {\n iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);\n }\n else {\n iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);\n }\n var count = 0;\n while (iterator.hasNext() && count < this.limit_) {\n var next = iterator.getNext();\n var inRange = void 0;\n if (this.reverse_) {\n inRange =\n this.index_.compare(this.rangedFilter_.getStartPost(), next) <= 0;\n }\n else {\n inRange =\n this.index_.compare(next, this.rangedFilter_.getEndPost()) <= 0;\n }\n if (inRange) {\n filtered = filtered.updateImmediateChild(next.name, next.node);\n count++;\n }\n else {\n // if we have reached the end post, we cannot keep adding elemments\n break;\n }\n }\n }\n else {\n // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one\n filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var startPost = void 0;\n var endPost = void 0;\n var cmp = void 0;\n var iterator = void 0;\n if (this.reverse_) {\n iterator = filtered.getReverseIterator(this.index_);\n startPost = this.rangedFilter_.getEndPost();\n endPost = this.rangedFilter_.getStartPost();\n var indexCompare_1 = this.index_.getCompare();\n cmp = function (a, b) { return indexCompare_1(b, a); };\n }\n else {\n iterator = filtered.getIterator(this.index_);\n startPost = this.rangedFilter_.getStartPost();\n endPost = this.rangedFilter_.getEndPost();\n cmp = this.index_.getCompare();\n }\n var count = 0;\n var foundStartPost = false;\n while (iterator.hasNext()) {\n var next = iterator.getNext();\n if (!foundStartPost && cmp(startPost, next) <= 0) {\n // start adding\n foundStartPost = true;\n }\n var inRange = foundStartPost && count < this.limit_ && cmp(next, endPost) <= 0;\n if (inRange) {\n count++;\n }\n else {\n filtered = filtered.updateImmediateChild(next.name, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n }\n }\n }\n return this.rangedFilter_\n .getIndexedFilter()\n .updateFullNode(oldSnap, filtered, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n // Don't support priorities on queries\n return oldSnap;\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.filtersNodes = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.getIndexedFilter = function () {\n return this.rangedFilter_.getIndexedFilter();\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @param {!Node} snap\n * @param {string} childKey\n * @param {!Node} childSnap\n * @param {!CompleteChildSource} source\n * @param {?ChildChangeAccumulator} changeAccumulator\n * @return {!Node}\n * @private\n */\n LimitedFilter.prototype.fullLimitUpdateChild_ = function (snap, childKey, childSnap, source, changeAccumulator) {\n // TODO: rename all cache stuff etc to general snap terminology\n var cmp;\n if (this.reverse_) {\n var indexCmp_1 = this.index_.getCompare();\n cmp = function (a, b) { return indexCmp_1(b, a); };\n }\n else {\n cmp = this.index_.getCompare();\n }\n var oldEventCache = snap;\n util_1.assert(oldEventCache.numChildren() == this.limit_, '');\n var newChildNamedNode = new Node_1.NamedNode(childKey, childSnap);\n var windowBoundary = this.reverse_\n ? oldEventCache.getFirstChild(this.index_)\n : oldEventCache.getLastChild(this.index_);\n var inRange = this.rangedFilter_.matches(newChildNamedNode);\n if (oldEventCache.hasChild(childKey)) {\n var oldChildSnap = oldEventCache.getImmediateChild(childKey);\n var nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);\n while (nextChild != null &&\n (nextChild.name == childKey || oldEventCache.hasChild(nextChild.name))) {\n // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't\n // been applied to the limited filter yet. Ignore this next child which will be updated later in\n // the limited filter...\n nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);\n }\n var compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);\n var remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;\n if (remainsInWindow) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childChangedChange(childKey, childSnap, oldChildSnap));\n }\n return oldEventCache.updateImmediateChild(childKey, childSnap);\n }\n else {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(childKey, oldChildSnap));\n }\n var newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);\n if (nextChildInRange) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childAddedChange(nextChild.name, nextChild.node));\n }\n return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);\n }\n else {\n return newEventCache;\n }\n }\n }\n else if (childSnap.isEmpty()) {\n // we're deleting a node, but it was not in the window, so ignore it\n return snap;\n }\n else if (inRange) {\n if (cmp(windowBoundary, newChildNamedNode) >= 0) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(windowBoundary.name, windowBoundary.node));\n changeAccumulator.trackChildChange(Change_1.Change.childAddedChange(childKey, childSnap));\n }\n return oldEventCache\n .updateImmediateChild(childKey, childSnap)\n .updateImmediateChild(windowBoundary.name, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n else {\n return snap;\n }\n }\n else {\n return snap;\n }\n };\n return LimitedFilter;\n}());\nexports.LimitedFilter = LimitedFilter;\n\n//# sourceMappingURL=LimitedFilter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/filter/LimitedFilter.js\n// module id = 109\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Reference_1 = require(\"../api/Reference\");\nvar DataSnapshot_1 = require(\"../api/DataSnapshot\");\nvar Path_1 = require(\"./util/Path\");\nvar Tree_1 = require(\"./util/Tree\");\nvar PriorityIndex_1 = require(\"./snap/indexes/PriorityIndex\");\nvar util_2 = require(\"./util/util\");\nvar ServerValues_1 = require(\"./util/ServerValues\");\nvar validation_1 = require(\"./util/validation\");\nvar util_3 = require(\"@firebase/util\");\nvar nodeFromJSON_1 = require(\"./snap/nodeFromJSON\");\nvar ChildrenNode_1 = require(\"./snap/ChildrenNode\");\nvar Repo_1 = require(\"./Repo\");\n// TODO: This is pretty messy. Ideally, a lot of this would move into FirebaseData, or a transaction-specific\n// component used by FirebaseData, but it has ties to user callbacks (transaction update and onComplete) as well\n// as the realtime connection (to send transactions to the server). So that all needs to be decoupled first.\n// For now it's part of Repo, but in its own file.\n/**\n * @enum {number}\n */\nvar TransactionStatus;\n(function (TransactionStatus) {\n // We've run the transaction and updated transactionResultData_ with the result, but it isn't currently sent to the\n // server. A transaction will go from RUN -> SENT -> RUN if it comes back from the server as rejected due to\n // mismatched hash.\n TransactionStatus[TransactionStatus[\"RUN\"] = 0] = \"RUN\";\n // We've run the transaction and sent it to the server and it's currently outstanding (hasn't come back as accepted\n // or rejected yet).\n TransactionStatus[TransactionStatus[\"SENT\"] = 1] = \"SENT\";\n // Temporary state used to mark completed transactions (whether successful or aborted). The transaction will be\n // removed when we get a chance to prune completed ones.\n TransactionStatus[TransactionStatus[\"COMPLETED\"] = 2] = \"COMPLETED\";\n // Used when an already-sent transaction needs to be aborted (e.g. due to a conflicting set() call that was made).\n // If it comes back as unsuccessful, we'll abort it.\n TransactionStatus[TransactionStatus[\"SENT_NEEDS_ABORT\"] = 3] = \"SENT_NEEDS_ABORT\";\n // Temporary state used to mark transactions that need to be aborted.\n TransactionStatus[TransactionStatus[\"NEEDS_ABORT\"] = 4] = \"NEEDS_ABORT\";\n})(TransactionStatus = exports.TransactionStatus || (exports.TransactionStatus = {}));\n/**\n * If a transaction does not succeed after 25 retries, we abort it. Among other things this ensure that if there's\n * ever a bug causing a mismatch between client / server hashes for some data, we won't retry indefinitely.\n * @type {number}\n * @const\n * @private\n */\nRepo_1.Repo.MAX_TRANSACTION_RETRIES_ = 25;\n/**\n * Setup the transaction data structures\n * @private\n */\nRepo_1.Repo.prototype.transactions_init_ = function () {\n /**\n * Stores queues of outstanding transactions for Firebase locations.\n *\n * @type {!Tree.>}\n * @private\n */\n this.transactionQueueTree_ = new Tree_1.Tree();\n};\n/**\n * Creates a new transaction, adds it to the transactions we're tracking, and sends it to the server if possible.\n *\n * @param {!Path} path Path at which to do transaction.\n * @param {function(*):*} transactionUpdate Update callback.\n * @param {?function(?Error, boolean, ?DataSnapshot)} onComplete Completion callback.\n * @param {boolean} applyLocally Whether or not to make intermediate results visible\n */\nRepo_1.Repo.prototype.startTransaction = function (path, transactionUpdate, onComplete, applyLocally) {\n this.log_('transaction on ' + path);\n // Add a watch to make sure we get server updates.\n var valueCallback = function () { };\n var watchRef = new Reference_1.Reference(this, path);\n watchRef.on('value', valueCallback);\n var unwatcher = function () {\n watchRef.off('value', valueCallback);\n };\n // Initialize transaction.\n var transaction = {\n path: path,\n update: transactionUpdate,\n onComplete: onComplete,\n // One of TransactionStatus enums.\n status: null,\n // Used when combining transactions at different locations to figure out which one goes first.\n order: util_2.LUIDGenerator(),\n // Whether to raise local events for this transaction.\n applyLocally: applyLocally,\n // Count of how many times we've retried the transaction.\n retryCount: 0,\n // Function to call to clean up our .on() listener.\n unwatcher: unwatcher,\n // Stores why a transaction was aborted.\n abortReason: null,\n currentWriteId: null,\n currentInputSnapshot: null,\n currentOutputSnapshotRaw: null,\n currentOutputSnapshotResolved: null\n };\n // Run transaction initially.\n var currentState = this.getLatestState_(path);\n transaction.currentInputSnapshot = currentState;\n var newVal = transaction.update(currentState.val());\n if (newVal === undefined) {\n // Abort transaction.\n transaction.unwatcher();\n transaction.currentOutputSnapshotRaw = null;\n transaction.currentOutputSnapshotResolved = null;\n if (transaction.onComplete) {\n // We just set the input snapshot, so this cast should be safe\n var snapshot = new DataSnapshot_1.DataSnapshot(transaction.currentInputSnapshot, new Reference_1.Reference(this, transaction.path), PriorityIndex_1.PRIORITY_INDEX);\n transaction.onComplete(null, false, snapshot);\n }\n }\n else {\n validation_1.validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);\n // Mark as run and add to our queue.\n transaction.status = TransactionStatus.RUN;\n var queueNode = this.transactionQueueTree_.subTree(path);\n var nodeQueue = queueNode.getValue() || [];\n nodeQueue.push(transaction);\n queueNode.setValue(nodeQueue);\n // Update visibleData and raise events\n // Note: We intentionally raise events after updating all of our transaction state, since the user could\n // start new transactions from the event callbacks.\n var priorityForNode = void 0;\n if (typeof newVal === 'object' &&\n newVal !== null &&\n util_3.contains(newVal, '.priority')) {\n priorityForNode = util_3.safeGet(newVal, '.priority');\n util_1.assert(validation_1.isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +\n 'Priority must be a valid string, finite number, server value, or null.');\n }\n else {\n var currentNode = this.serverSyncTree_.calcCompleteEventCache(path) ||\n ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n priorityForNode = currentNode.getPriority().val();\n }\n priorityForNode /** @type {null|number|string} */ = priorityForNode;\n var serverValues = this.generateServerValues();\n var newNodeUnresolved = nodeFromJSON_1.nodeFromJSON(newVal, priorityForNode);\n var newNode = ServerValues_1.resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n transaction.currentOutputSnapshotRaw = newNodeUnresolved;\n transaction.currentOutputSnapshotResolved = newNode;\n transaction.currentWriteId = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserOverwrite(path, newNode, transaction.currentWriteId, transaction.applyLocally);\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n this.sendReadyTransactions_();\n }\n};\n/**\n * @param {!Path} path\n * @param {Array.=} excludeSets A specific set to exclude\n * @return {Node}\n * @private\n */\nRepo_1.Repo.prototype.getLatestState_ = function (path, excludeSets) {\n return (this.serverSyncTree_.calcCompleteEventCache(path, excludeSets) ||\n ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n};\n/**\n * Sends any already-run transactions that aren't waiting for outstanding transactions to\n * complete.\n *\n * Externally it's called with no arguments, but it calls itself recursively with a particular\n * transactionQueueTree node to recurse through the tree.\n *\n * @param {Tree.>=} node transactionQueueTree node to start at.\n * @private\n */\nRepo_1.Repo.prototype.sendReadyTransactions_ = function (node) {\n var _this = this;\n if (node === void 0) { node = this.transactionQueueTree_; }\n // Before recursing, make sure any completed transactions are removed.\n if (!node) {\n this.pruneCompletedTransactionsBelowNode_(node);\n }\n if (node.getValue() !== null) {\n var queue = this.buildTransactionQueue_(node);\n util_1.assert(queue.length > 0, 'Sending zero length transaction queue');\n var allRun = queue.every(function (transaction) { return transaction.status === TransactionStatus.RUN; });\n // If they're all run (and not sent), we can send them. Else, we must wait.\n if (allRun) {\n this.sendTransactionQueue_(node.path(), queue);\n }\n }\n else if (node.hasChildren()) {\n node.forEachChild(function (childNode) {\n _this.sendReadyTransactions_(childNode);\n });\n }\n};\n/**\n * Given a list of run transactions, send them to the server and then handle the result (success or failure).\n *\n * @param {!Path} path The location of the queue.\n * @param {!Array.} queue Queue of transactions under the specified location.\n * @private\n */\nRepo_1.Repo.prototype.sendTransactionQueue_ = function (path, queue) {\n var _this = this;\n // Mark transactions as sent and increment retry count!\n var setsToIgnore = queue.map(function (txn) {\n return txn.currentWriteId;\n });\n var latestState = this.getLatestState_(path, setsToIgnore);\n var snapToSend = latestState;\n var latestHash = latestState.hash();\n for (var i = 0; i < queue.length; i++) {\n var txn = queue[i];\n util_1.assert(txn.status === TransactionStatus.RUN, 'tryToSendTransactionQueue_: items in queue should all be run.');\n txn.status = TransactionStatus.SENT;\n txn.retryCount++;\n var relativePath = Path_1.Path.relativePath(path, txn.path);\n // If we've gotten to this point, the output snapshot must be defined.\n snapToSend = snapToSend.updateChild(relativePath /**@type {!Node} */, txn.currentOutputSnapshotRaw);\n }\n var dataToSend = snapToSend.val(true);\n var pathToSend = path;\n // Send the put.\n this.server_.put(pathToSend.toString(), dataToSend, function (status) {\n _this.log_('transaction put response', {\n path: pathToSend.toString(),\n status: status\n });\n var events = [];\n if (status === 'ok') {\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n for (var i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.COMPLETED;\n events = events.concat(_this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId));\n if (queue[i].onComplete) {\n // We never unset the output snapshot, and given that this transaction is complete, it should be set\n var node = queue[i].currentOutputSnapshotResolved;\n var ref = new Reference_1.Reference(_this, queue[i].path);\n var snapshot = new DataSnapshot_1.DataSnapshot(node, ref, PriorityIndex_1.PRIORITY_INDEX);\n callbacks.push(queue[i].onComplete.bind(null, null, true, snapshot));\n }\n queue[i].unwatcher();\n }\n // Now remove the completed transactions.\n _this.pruneCompletedTransactionsBelowNode_(_this.transactionQueueTree_.subTree(path));\n // There may be pending transactions that we can now send.\n _this.sendReadyTransactions_();\n _this.eventQueue_.raiseEventsForChangedPath(path, events);\n // Finally, trigger onComplete callbacks.\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n }\n else {\n // transactions are no longer sent. Update their status appropriately.\n if (status === 'datastale') {\n for (var i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT)\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n else\n queue[i].status = TransactionStatus.RUN;\n }\n }\n else {\n util_2.warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);\n for (var i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n queue[i].abortReason = status;\n }\n }\n _this.rerunTransactions_(path);\n }\n }, latestHash);\n};\n/**\n * Finds all transactions dependent on the data at changedPath and reruns them.\n *\n * Should be called any time cached data changes.\n *\n * Return the highest path that was affected by rerunning transactions. This is the path at which events need to\n * be raised for.\n *\n * @param {!Path} changedPath The path in mergedData that changed.\n * @return {!Path} The rootmost path that was affected by rerunning transactions.\n * @private\n */\nRepo_1.Repo.prototype.rerunTransactions_ = function (changedPath) {\n var rootMostTransactionNode = this.getAncestorTransactionNode_(changedPath);\n var path = rootMostTransactionNode.path();\n var queue = this.buildTransactionQueue_(rootMostTransactionNode);\n this.rerunTransactionQueue_(queue, path);\n return path;\n};\n/**\n * Does all the work of rerunning transactions (as well as cleans up aborted transactions and whatnot).\n *\n * @param {Array.} queue The queue of transactions to run.\n * @param {!Path} path The path the queue is for.\n * @private\n */\nRepo_1.Repo.prototype.rerunTransactionQueue_ = function (queue, path) {\n if (queue.length === 0) {\n return; // Nothing to do!\n }\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n var events = [];\n // Ignore all of the sets we're going to re-run.\n var txnsToRerun = queue.filter(function (q) {\n return q.status === TransactionStatus.RUN;\n });\n var setsToIgnore = txnsToRerun.map(function (q) {\n return q.currentWriteId;\n });\n for (var i = 0; i < queue.length; i++) {\n var transaction = queue[i];\n var relativePath = Path_1.Path.relativePath(path, transaction.path);\n var abortTransaction = false, abortReason = void 0;\n util_1.assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');\n if (transaction.status === TransactionStatus.NEEDS_ABORT) {\n abortTransaction = true;\n abortReason = transaction.abortReason;\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n else if (transaction.status === TransactionStatus.RUN) {\n if (transaction.retryCount >= Repo_1.Repo.MAX_TRANSACTION_RETRIES_) {\n abortTransaction = true;\n abortReason = 'maxretry';\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n else {\n // This code reruns a transaction\n var currentNode = this.getLatestState_(transaction.path, setsToIgnore);\n transaction.currentInputSnapshot = currentNode;\n var newData = queue[i].update(currentNode.val());\n if (newData !== undefined) {\n validation_1.validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);\n var newDataNode = nodeFromJSON_1.nodeFromJSON(newData);\n var hasExplicitPriority = typeof newData === 'object' &&\n newData != null &&\n util_3.contains(newData, '.priority');\n if (!hasExplicitPriority) {\n // Keep the old priority if there wasn't a priority explicitly specified.\n newDataNode = newDataNode.updatePriority(currentNode.getPriority());\n }\n var oldWriteId = transaction.currentWriteId;\n var serverValues = this.generateServerValues();\n var newNodeResolved = ServerValues_1.resolveDeferredValueSnapshot(newDataNode, serverValues);\n transaction.currentOutputSnapshotRaw = newDataNode;\n transaction.currentOutputSnapshotResolved = newNodeResolved;\n transaction.currentWriteId = this.getNextWriteId_();\n // Mutates setsToIgnore in place\n setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);\n events = events.concat(this.serverSyncTree_.applyUserOverwrite(transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));\n events = events.concat(this.serverSyncTree_.ackUserWrite(oldWriteId, true));\n }\n else {\n abortTransaction = true;\n abortReason = 'nodata';\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n }\n }\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n events = [];\n if (abortTransaction) {\n // Abort.\n queue[i].status = TransactionStatus.COMPLETED;\n // Removing a listener can trigger pruning which can muck with mergedData/visibleData (as it prunes data).\n // So defer the unwatcher until we're done.\n (function (unwatcher) {\n setTimeout(unwatcher, Math.floor(0));\n })(queue[i].unwatcher);\n if (queue[i].onComplete) {\n if (abortReason === 'nodata') {\n var ref = new Reference_1.Reference(this, queue[i].path);\n // We set this field immediately, so it's safe to cast to an actual snapshot\n var lastInput /** @type {!Node} */ = queue[i].currentInputSnapshot;\n var snapshot = new DataSnapshot_1.DataSnapshot(lastInput, ref, PriorityIndex_1.PRIORITY_INDEX);\n callbacks.push(queue[i].onComplete.bind(null, null, false, snapshot));\n }\n else {\n callbacks.push(queue[i].onComplete.bind(null, new Error(abortReason), false, null));\n }\n }\n }\n }\n // Clean up completed transactions.\n this.pruneCompletedTransactionsBelowNode_(this.transactionQueueTree_);\n // Now fire callbacks, now that we're in a good, known state.\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n // Try to send the transaction result to the server.\n this.sendReadyTransactions_();\n};\n/**\n * Returns the rootmost ancestor node of the specified path that has a pending transaction on it, or just returns\n * the node for the given path if there are no pending transactions on any ancestor.\n *\n * @param {!Path} path The location to start at.\n * @return {!Tree.>} The rootmost node with a transaction.\n * @private\n */\nRepo_1.Repo.prototype.getAncestorTransactionNode_ = function (path) {\n var front;\n // Start at the root and walk deeper into the tree towards path until we find a node with pending transactions.\n var transactionNode = this.transactionQueueTree_;\n while ((front = path.getFront()) !== null &&\n transactionNode.getValue() === null) {\n transactionNode = transactionNode.subTree(front);\n path = path.popFront();\n }\n return transactionNode;\n};\n/**\n * Builds the queue of all transactions at or below the specified transactionNode.\n *\n * @param {!Tree.>} transactionNode\n * @return {Array.} The generated queue.\n * @private\n */\nRepo_1.Repo.prototype.buildTransactionQueue_ = function (transactionNode) {\n // Walk any child transaction queues and aggregate them into a single queue.\n var transactionQueue = [];\n this.aggregateTransactionQueuesForNode_(transactionNode, transactionQueue);\n // Sort them by the order the transactions were created.\n transactionQueue.sort(function (a, b) {\n return a.order - b.order;\n });\n return transactionQueue;\n};\n/**\n * @param {!Tree.>} node\n * @param {Array.} queue\n * @private\n */\nRepo_1.Repo.prototype.aggregateTransactionQueuesForNode_ = function (node, queue) {\n var _this = this;\n var nodeQueue = node.getValue();\n if (nodeQueue !== null) {\n for (var i = 0; i < nodeQueue.length; i++) {\n queue.push(nodeQueue[i]);\n }\n }\n node.forEachChild(function (child) {\n _this.aggregateTransactionQueuesForNode_(child, queue);\n });\n};\n/**\n * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.\n *\n * @param {!Tree.>} node\n * @private\n */\nRepo_1.Repo.prototype.pruneCompletedTransactionsBelowNode_ = function (node) {\n var _this = this;\n var queue = node.getValue();\n if (queue) {\n var to = 0;\n for (var from = 0; from < queue.length; from++) {\n if (queue[from].status !== TransactionStatus.COMPLETED) {\n queue[to] = queue[from];\n to++;\n }\n }\n queue.length = to;\n node.setValue(queue.length > 0 ? queue : null);\n }\n node.forEachChild(function (childNode) {\n _this.pruneCompletedTransactionsBelowNode_(childNode);\n });\n};\n/**\n * Aborts all transactions on ancestors or descendants of the specified path. Called when doing a set() or update()\n * since we consider them incompatible with transactions.\n *\n * @param {!Path} path Path for which we want to abort related transactions.\n * @return {!Path}\n * @private\n */\nRepo_1.Repo.prototype.abortTransactions_ = function (path) {\n var _this = this;\n var affectedPath = this.getAncestorTransactionNode_(path).path();\n var transactionNode = this.transactionQueueTree_.subTree(path);\n transactionNode.forEachAncestor(function (node) {\n _this.abortTransactionsOnNode_(node);\n });\n this.abortTransactionsOnNode_(transactionNode);\n transactionNode.forEachDescendant(function (node) {\n _this.abortTransactionsOnNode_(node);\n });\n return affectedPath;\n};\n/**\n * Abort transactions stored in this transaction queue node.\n *\n * @param {!Tree.>} node Node to abort transactions for.\n * @private\n */\nRepo_1.Repo.prototype.abortTransactionsOnNode_ = function (node) {\n var queue = node.getValue();\n if (queue !== null) {\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n // Go through queue. Any already-sent transactions must be marked for abort, while the unsent ones\n // can be immediately aborted and removed.\n var events = [];\n var lastSent = -1;\n for (var i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) {\n // Already marked. No action needed.\n }\n else if (queue[i].status === TransactionStatus.SENT) {\n util_1.assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');\n lastSent = i;\n // Mark transaction for abort when it comes back.\n queue[i].status = TransactionStatus.SENT_NEEDS_ABORT;\n queue[i].abortReason = 'set';\n }\n else {\n util_1.assert(queue[i].status === TransactionStatus.RUN, 'Unexpected transaction status in abort');\n // We can abort it immediately.\n queue[i].unwatcher();\n events = events.concat(this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId, true));\n if (queue[i].onComplete) {\n var snapshot = null;\n callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, snapshot));\n }\n }\n }\n if (lastSent === -1) {\n // We're not waiting for any sent transactions. We can clear the queue.\n node.setValue(null);\n }\n else {\n // Remove the transactions we aborted.\n queue.length = lastSent + 1;\n }\n // Now fire the callbacks.\n this.eventQueue_.raiseEventsForChangedPath(node.path(), events);\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n }\n};\n\n//# sourceMappingURL=Repo_transaction.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/Repo_transaction.js\n// module id = 110\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Path_1 = require(\"./Path\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * Node in a Tree.\n */\nvar TreeNode = /** @class */ (function () {\n function TreeNode() {\n // TODO: Consider making accessors that create children and value lazily or\n // separate Internal / Leaf 'types'.\n this.children = {};\n this.childCount = 0;\n this.value = null;\n }\n return TreeNode;\n}());\nexports.TreeNode = TreeNode;\n/**\n * A light-weight tree, traversable by path. Nodes can have both values and children.\n * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty\n * children.\n */\nvar Tree = /** @class */ (function () {\n /**\n * @template T\n * @param {string=} name_ Optional name of the node.\n * @param {Tree=} parent_ Optional parent node.\n * @param {TreeNode=} node_ Optional node to wrap.\n */\n function Tree(name_, parent_, node_) {\n if (name_ === void 0) { name_ = ''; }\n if (parent_ === void 0) { parent_ = null; }\n if (node_ === void 0) { node_ = new TreeNode(); }\n this.name_ = name_;\n this.parent_ = parent_;\n this.node_ = node_;\n }\n /**\n * Returns a sub-Tree for the given path.\n *\n * @param {!(string|Path)} pathObj Path to look up.\n * @return {!Tree.} Tree for path.\n */\n Tree.prototype.subTree = function (pathObj) {\n // TODO: Require pathObj to be Path?\n var path = pathObj instanceof Path_1.Path ? pathObj : new Path_1.Path(pathObj);\n var child = this, next;\n while ((next = path.getFront()) !== null) {\n var childNode = util_2.safeGet(child.node_.children, next) || new TreeNode();\n child = new Tree(next, child, childNode);\n path = path.popFront();\n }\n return child;\n };\n /**\n * Returns the data associated with this tree node.\n *\n * @return {?T} The data or null if no data exists.\n */\n Tree.prototype.getValue = function () {\n return this.node_.value;\n };\n /**\n * Sets data to this tree node.\n *\n * @param {!T} value Value to set.\n */\n Tree.prototype.setValue = function (value) {\n util_1.assert(typeof value !== 'undefined', 'Cannot set value to undefined');\n this.node_.value = value;\n this.updateParents_();\n };\n /**\n * Clears the contents of the tree node (its value and all children).\n */\n Tree.prototype.clear = function () {\n this.node_.value = null;\n this.node_.children = {};\n this.node_.childCount = 0;\n this.updateParents_();\n };\n /**\n * @return {boolean} Whether the tree has any children.\n */\n Tree.prototype.hasChildren = function () {\n return this.node_.childCount > 0;\n };\n /**\n * @return {boolean} Whether the tree is empty (no value or children).\n */\n Tree.prototype.isEmpty = function () {\n return this.getValue() === null && !this.hasChildren();\n };\n /**\n * Calls action for each child of this tree node.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n */\n Tree.prototype.forEachChild = function (action) {\n var _this = this;\n util_2.forEach(this.node_.children, function (child, childTree) {\n action(new Tree(child, _this, childTree));\n });\n };\n /**\n * Does a depth-first traversal of this node's descendants, calling action for each one.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n * @param {boolean=} includeSelf Whether to call action on this node as well. Defaults to\n * false.\n * @param {boolean=} childrenFirst Whether to call action on children before calling it on\n * parent.\n */\n Tree.prototype.forEachDescendant = function (action, includeSelf, childrenFirst) {\n if (includeSelf && !childrenFirst)\n action(this);\n this.forEachChild(function (child) {\n child.forEachDescendant(action, /*includeSelf=*/ true, childrenFirst);\n });\n if (includeSelf && childrenFirst)\n action(this);\n };\n /**\n * Calls action on each ancestor node.\n *\n * @param {function(!Tree.)} action Action to be called on each parent; return\n * true to abort.\n * @param {boolean=} includeSelf Whether to call action on this node as well.\n * @return {boolean} true if the action callback returned true.\n */\n Tree.prototype.forEachAncestor = function (action, includeSelf) {\n var node = includeSelf ? this : this.parent();\n while (node !== null) {\n if (action(node)) {\n return true;\n }\n node = node.parent();\n }\n return false;\n };\n /**\n * Does a depth-first traversal of this node's descendants. When a descendant with a value\n * is found, action is called on it and traversal does not continue inside the node.\n * Action is *not* called on this node.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n */\n Tree.prototype.forEachImmediateDescendantWithValue = function (action) {\n this.forEachChild(function (child) {\n if (child.getValue() !== null)\n action(child);\n else\n child.forEachImmediateDescendantWithValue(action);\n });\n };\n /**\n * @return {!Path} The path of this tree node, as a Path.\n */\n Tree.prototype.path = function () {\n return new Path_1.Path(this.parent_ === null\n ? this.name_\n : this.parent_.path() + '/' + this.name_);\n };\n /**\n * @return {string} The name of the tree node.\n */\n Tree.prototype.name = function () {\n return this.name_;\n };\n /**\n * @return {?Tree} The parent tree node, or null if this is the root of the tree.\n */\n Tree.prototype.parent = function () {\n return this.parent_;\n };\n /**\n * Adds or removes this child from its parent based on whether it's empty or not.\n *\n * @private\n */\n Tree.prototype.updateParents_ = function () {\n if (this.parent_ !== null)\n this.parent_.updateChild_(this.name_, this);\n };\n /**\n * Adds or removes the passed child to this tree node, depending on whether it's empty.\n *\n * @param {string} childName The name of the child to update.\n * @param {!Tree.} child The child to update.\n * @private\n */\n Tree.prototype.updateChild_ = function (childName, child) {\n var childEmpty = child.isEmpty();\n var childExists = util_2.contains(this.node_.children, childName);\n if (childEmpty && childExists) {\n delete this.node_.children[childName];\n this.node_.childCount--;\n this.updateParents_();\n }\n else if (!childEmpty && !childExists) {\n this.node_.children[childName] = child.node_;\n this.node_.childCount++;\n this.updateParents_();\n }\n };\n return Tree;\n}());\nexports.Tree = Tree;\n\n//# sourceMappingURL=Tree.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/Tree.js\n// module id = 111\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar WebSocketConnection_1 = require(\"../realtime/WebSocketConnection\");\nvar BrowserPollConnection_1 = require(\"../realtime/BrowserPollConnection\");\n/**\n * INTERNAL methods for internal-use only (tests, etc.).\n *\n * Customers shouldn't use these or else should be aware that they could break at any time.\n *\n * @const\n */\nexports.forceLongPolling = function () {\n WebSocketConnection_1.WebSocketConnection.forceDisallow();\n BrowserPollConnection_1.BrowserPollConnection.forceAllow();\n};\nexports.forceWebSockets = function () {\n BrowserPollConnection_1.BrowserPollConnection.forceDisallow();\n};\n/* Used by App Manager */\nexports.isWebSocketsAvailable = function () {\n return WebSocketConnection_1.WebSocketConnection['isAvailable']();\n};\nexports.setSecurityDebugCallback = function (ref, callback) {\n ref.repo.persistentConnection_.securityDebugCallback_ = callback;\n};\nexports.stats = function (ref, showDelta) {\n ref.repo.stats(showDelta);\n};\nexports.statsIncrementCounter = function (ref, metric) {\n ref.repo.statsIncrementCounter(metric);\n};\nexports.dataUpdateCount = function (ref) {\n return ref.repo.dataUpdateCount;\n};\nexports.interceptServerData = function (ref, callback) {\n return ref.repo.interceptServerData_(callback);\n};\n\n//# sourceMappingURL=internal.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/internal.js\n// module id = 112\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar RepoInfo_1 = require(\"../core/RepoInfo\");\nvar PersistentConnection_1 = require(\"../core/PersistentConnection\");\nvar RepoManager_1 = require(\"../core/RepoManager\");\nvar Connection_1 = require(\"../realtime/Connection\");\nexports.DataConnection = PersistentConnection_1.PersistentConnection;\n/**\n * @param {!string} pathString\n * @param {function(*)} onComplete\n */\nPersistentConnection_1.PersistentConnection.prototype.simpleListen = function (pathString, onComplete) {\n this.sendRequest('q', { p: pathString }, onComplete);\n};\n/**\n * @param {*} data\n * @param {function(*)} onEcho\n */\nPersistentConnection_1.PersistentConnection.prototype.echo = function (data, onEcho) {\n this.sendRequest('echo', { d: data }, onEcho);\n};\n// RealTimeConnection properties that we use in tests.\nexports.RealTimeConnection = Connection_1.Connection;\n/**\n * @param {function(): string} newHash\n * @return {function()}\n */\nexports.hijackHash = function (newHash) {\n var oldPut = PersistentConnection_1.PersistentConnection.prototype.put;\n PersistentConnection_1.PersistentConnection.prototype.put = function (pathString, data, opt_onComplete, opt_hash) {\n if (opt_hash !== undefined) {\n opt_hash = newHash();\n }\n oldPut.call(this, pathString, data, opt_onComplete, opt_hash);\n };\n return function () {\n PersistentConnection_1.PersistentConnection.prototype.put = oldPut;\n };\n};\n/**\n * @type {function(new:RepoInfo, !string, boolean, !string, boolean): undefined}\n */\nexports.ConnectionTarget = RepoInfo_1.RepoInfo;\n/**\n * @param {!Query} query\n * @return {!string}\n */\nexports.queryIdentifier = function (query) {\n return query.queryIdentifier();\n};\n/**\n * @param {!Query} firebaseRef\n * @return {!Object}\n */\nexports.listens = function (firebaseRef) {\n return firebaseRef.repo.persistentConnection_.listens_;\n};\n/**\n * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.\n *\n * @param {boolean} forceRestClient\n */\nexports.forceRestClient = function (forceRestClient) {\n RepoManager_1.RepoManager.getInstance().forceRestClient(forceRestClient);\n};\n\n//# sourceMappingURL=test_access.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/test_access.js\n// module id = 113\n// module chunks = 0"],"sourceRoot":""}