"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[627],{5276:function(e,t,n){let i,r,s,o,l,a,h,u,c,d,_;n.d(t,{N8:function(){return iD},U2:function(){return iE},VF:function(){return ik},iH:function(){return iT},t8:function(){return ib},yv:function(){return iS}});var p,f,g=n(4258),m=n(909),y=n(4589),v=n(4594),C=n(4155);/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let w="";/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class T{constructor(e){this.domStorage_=e,this.prefix_="firebase:"}set(e,t){null==t?this.domStorage_.removeItem(this.prefixedName_(e)):this.domStorage_.setItem(this.prefixedName_(e),(0,y.Pz)(t))}get(e){let t=this.domStorage_.getItem(this.prefixedName_(e));return null==t?null:(0,y.cI)(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class I{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){null==t?delete this.cache_[e]:this.cache_[e]=t}get(e){return(0,y.r3)(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let k=function(e){try{if("undefined"!=typeof window&&void 0!==window[e]){let t=window[e];return t.setItem("firebase:sentinel","cache"),t.removeItem("firebase:sentinel"),new T(t)}}catch(e){}return new I},b=k("localStorage"),E=k("sessionStorage"),P=new v.Yd("@firebase/database"),N=(_=1,function(){return _++}),S=function(e){let t=(0,y.dS)(e),n=new y.gQ;n.update(t);let i=n.digest();return y.US.encodeByteArray(i)},x=function(...e){let t="";for(let n=0;n<e.length;n++){let i=e[n];Array.isArray(i)||i&&"object"==typeof i&&"number"==typeof i.length?t+=x.apply(null,i):"object"==typeof i?t+=(0,y.Pz)(i):t+=i,t+=" "}return t},R=null,D=!0,M=function(e,t){(0,y.hu)(!t||!0===e||!1===e,"Can't turn on custom loggers persistently."),!0===e?(P.logLevel=v.in.VERBOSE,R=P.log.bind(P),t&&E.set("logging_enabled",!0)):"function"==typeof e?R=e:(R=null,E.remove("logging_enabled"))},F=function(...e){if(!0===D&&(D=!1,null===R&&!0===E.get("logging_enabled")&&M(!0)),R){let t=x.apply(null,e);R(t)}},q=function(e){return function(...t){F(e,...t)}},L=function(...e){let t="FIREBASE INTERNAL ERROR: "+x(...e);P.error(t)},O=function(...e){let t=`FIREBASE FATAL ERROR: ${x(...e)}`;throw P.error(t),Error(t)},A=function(...e){let t="FIREBASE WARNING: "+x(...e);P.warn(t)},W=function(){"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&A("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().")},U=function(e){return"number"==typeof e&&(e!=e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY)},z=function(e){if((0,y.Yr)()||"complete"===document.readyState)e();else{let t=!1,n=function(){if(!document.body){setTimeout(n,Math.floor(10));return}t||(t=!0,e())};document.addEventListener?(document.addEventListener("DOMContentLoaded",n,!1),window.addEventListener("load",n,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",()=>{"complete"===document.readyState&&n()}),window.attachEvent("onload",n))}},H="[MIN_NAME]",Y="[MAX_NAME]",j=function(e,t){if(e===t)return 0;if(e===H||t===Y)return -1;if(t===H||e===Y)return 1;{let n=J(e),i=J(t);return null!==n?null!==i?n-i==0?e.length-t.length:n-i:-1:null!==i?1:e<t?-1:1}},V=function(e,t){return e===t?0:e<t?-1:1},B=function(e,t){if(t&&e in t)return t[e];throw Error("Missing required key ("+e+") in object: "+(0,y.Pz)(t))},K=function(e){if("object"!=typeof e||null===e)return(0,y.Pz)(e);let t=[];for(let n in e)t.push(n);t.sort();let n="{";for(let i=0;i<t.length;i++)0!==i&&(n+=","),n+=(0,y.Pz)(t[i])+":"+K(e[t[i]]);return n+"}"},G=function(e,t){let n=e.length;if(n<=t)return[e];let i=[];for(let r=0;r<n;r+=t)r+t>n?i.push(e.substring(r,n)):i.push(e.substring(r,r+t));return i};function Q(e,t){for(let n in e)e.hasOwnProperty(n)&&t(n,e[n])}let $=function(e){let t,n,i,r,s;(0,y.hu)(!U(e),"Invalid JSON number"),0===e?(n=0,i=0,t=1/e==-1/0?1:0):(t=e<0,(e=Math.abs(e))>=22250738585072014e-324?(n=(r=Math.min(Math.floor(Math.log(e)/Math.LN2),1023))+1023,i=Math.round(e*Math.pow(2,52-r)-4503599627370496)):(n=0,i=Math.round(e/5e-324)));let o=[];for(s=52;s;s-=1)o.push(i%2?1:0),i=Math.floor(i/2);for(s=11;s;s-=1)o.push(n%2?1:0),n=Math.floor(n/2);o.push(t?1:0),o.reverse();let l=o.join(""),a="";for(s=0;s<64;s+=8){let e=parseInt(l.substr(s,8),2).toString(16);1===e.length&&(e="0"+e),a+=e}return a.toLowerCase()},X=RegExp("^-?(0*)\\d{1,10}$"),J=function(e){if(X.test(e)){let t=Number(e);if(t>=-2147483648&&t<=2147483647)return t}return null},Z=function(e){try{e()}catch(e){setTimeout(()=>{let t=e.stack||"";throw A("Exception was thrown by user callback.",t),e},Math.floor(0))}},ee=function(){let e="object"==typeof window&&window.navigator&&window.navigator.userAgent||"";return e.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)>=0},et=function(e,t){let n=setTimeout(e,t);return"object"==typeof n&&n.unref&&n.unref(),n};/**
 * @license
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class en{constructor(e,t){this.appName_=e,this.appCheckProvider=t,this.appCheck=null==t?void 0:t.getImmediate({optional:!0}),this.appCheck||null==t||t.get().then(e=>this.appCheck=e)}getToken(e){return this.appCheck?this.appCheck.getToken(e):new Promise((t,n)=>{setTimeout(()=>{this.appCheck?this.getToken(e).then(t,n):t(null)},0)})}addTokenChangeListener(e){var t;null===(t=this.appCheckProvider)||void 0===t||t.get().then(t=>t.addTokenListener(e))}notifyForInvalidToken(){A(`Provided AppCheck credentials for the app named "${this.appName_}" are invalid. This usually indicates your app was not initialized correctly.`)}}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class ei{constructor(e,t,n){this.appName_=e,this.firebaseOptions_=t,this.authProvider_=n,this.auth_=null,this.auth_=n.getImmediate({optional:!0}),this.auth_||n.onInit(e=>this.auth_=e)}getToken(e){return this.auth_?this.auth_.getToken(e).catch(e=>e&&"auth/token-not-initialized"===e.code?(F("Got auth/token-not-initialized error.  Treating as null token."),null):Promise.reject(e)):new Promise((t,n)=>{setTimeout(()=>{this.auth_?this.getToken(e).then(t,n):t(null)},0)})}addTokenChangeListener(e){this.auth_?this.auth_.addAuthTokenListener(e):this.authProvider_.get().then(t=>t.addAuthTokenListener(e))}removeTokenChangeListener(e){this.authProvider_.get().then(t=>t.removeAuthTokenListener(e))}notifyForInvalidToken(){let e='Provided authentication credentials for the app named "'+this.appName_+'" are invalid. This usually indicates your app was not initialized correctly. ';"credential"in this.firebaseOptions_?e+='Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':"serviceAccount"in this.firebaseOptions_?e+='Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':e+='Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.',A(e)}}class er{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}er.OWNER="owner";let es=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,eo="websocket",el="long_polling";/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class ea{constructor(e,t,n,i,r=!1,s="",o=!1){this.secure=t,this.namespace=n,this.webSocketOnly=i,this.nodeAdmin=r,this.persistenceKey=s,this.includeNamespaceInQueryParams=o,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=b.get("host:"+e)||this._host}isCacheableHost(){return"s-"===this.internalHost.substr(0,2)}isCustomHost(){return"firebaseio.com"!==this._domain&&"firebaseio-demo.com"!==this._domain}get host(){return this._host}set host(e){e!==this.internalHost&&(this.internalHost=e,this.isCacheableHost()&&b.set("host:"+this._host,this.internalHost))}toString(){let e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e}toURLString(){let e=this.secure?"https://":"http://",t=this.includeNamespaceInQueryParams?`?ns=${this.namespace}`:"";return`${e}${this.host}/${t}`}}function eh(e,t,n){let i;if((0,y.hu)("string"==typeof t,"typeof type must == string"),(0,y.hu)("object"==typeof n,"typeof params must == object"),t===eo)i=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?";else if(t===el)i=(e.secure?"https://":"http://")+e.internalHost+"/.lp?";else throw Error("Unknown connection type: "+t);(e.host!==e.internalHost||e.isCustomHost()||e.includeNamespaceInQueryParams)&&(n.ns=e.namespace);let r=[];return Q(n,(e,t)=>{r.push(e+"="+t)}),i+r.join("&")}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class eu{constructor(){this.counters_={}}incrementCounter(e,t=1){(0,y.r3)(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return(0,y.p$)(this.counters_)}}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let ec={},ed={};function e_(e){let t=e.toString();return ec[t]||(ec[t]=new eu),ec[t]}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class ep{constructor(e){this.onMessage_=e,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}closeAfter(e,t){this.closeAfterResponse=e,this.onClose=t,this.closeAfterResponse<this.currentResponseNum&&(this.onClose(),this.onClose=null)}handleResponse(e,t){for(this.pendingResponses[e]=t;this.pendingResponses[this.currentResponseNum];){let e=this.pendingResponses[this.currentResponseNum];delete this.pendingResponses[this.currentResponseNum];for(let t=0;t<e.length;++t)e[t]&&Z(()=>{this.onMessage_(e[t])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let ef="start";class eg{constructor(e,t,n,i,r,s,o){this.connId=e,this.repoInfo=t,this.applicationId=n,this.appCheckToken=i,this.authToken=r,this.transportSessionId=s,this.lastSessionId=o,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=q(e),this.stats_=e_(t),this.urlFn=e=>(this.appCheckToken&&(e.ac=this.appCheckToken),eh(t,el,e))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new ep(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null},Math.floor(3e4)),z(()=>{if(this.isClosed_)return;this.scriptTagHolder=new em((...e)=>{let[t,n,i,r,s]=e;if(this.incrementIncomingBytes_(e),this.scriptTagHolder){if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,t===ef)this.id=n,this.password=i;else if("close"===t)n?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(n,()=>{this.onClosed_()})):this.onClosed_();else throw Error("Unrecognized command received: "+t)}},(...e)=>{let[t,n]=e;this.incrementIncomingBytes_(e),this.myPacketOrderer.handleResponse(t,n)},()=>{this.onClosed_()},this.urlFn);let e={};e[ef]="t",e.ser=Math.floor(1e8*Math.random()),this.scriptTagHolder.uniqueCallbackIdentifier&&(e.cb=this.scriptTagHolder.uniqueCallbackIdentifier),e.v="5",this.transportSessionId&&(e.s=this.transportSessionId),this.lastSessionId&&(e.ls=this.lastSessionId),this.applicationId&&(e.p=this.applicationId),this.appCheckToken&&(e.ac=this.appCheckToken),"undefined"!=typeof location&&location.hostname&&es.test(location.hostname)&&(e.r="f");let t=this.urlFn(e);this.log_("Connecting via long-poll to "+t),this.scriptTagHolder.addTag(t,()=>{})})}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){eg.forceAllow_=!0}static forceDisallow(){eg.forceDisallow_=!0}static isAvailable(){return!(0,y.Yr)()&&(!!eg.forceAllow_||!eg.forceDisallow_&&"undefined"!=typeof document&&null!=document.createElement&&!("object"==typeof window&&window.chrome&&window.chrome.extension&&!/^chrome/.test(window.location.href))&&!("object"==typeof Windows&&"object"==typeof Windows.UI))}markConnectionHealthy(){}shutdown_(){this.isClosed_=!0,this.scriptTagHolder&&(this.scriptTagHolder.close(),this.scriptTagHolder=null),this.myDisconnFrame&&(document.body.removeChild(this.myDisconnFrame),this.myDisconnFrame=null),this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null)}onClosed_(){!this.isClosed_&&(this.log_("Longpoll is closing itself"),this.shutdown_(),this.onDisconnect_&&(this.onDisconnect_(this.everConnected_),this.onDisconnect_=null))}close(){this.isClosed_||(this.log_("Longpoll is being closed."),this.shutdown_())}send(e){let t=(0,y.Pz)(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);let n=(0,y.h$)(t),i=G(n,1840);for(let e=0;e<i.length;e++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,i.length,i[e]),this.curSegmentNum++}addDisconnectPingFrame(e,t){if((0,y.Yr)())return;this.myDisconnFrame=document.createElement("iframe");let n={};n.dframe="t",n.id=e,n.pw=t,this.myDisconnFrame.src=this.urlFn(n),this.myDisconnFrame.style.display="none",document.body.appendChild(this.myDisconnFrame)}incrementIncomingBytes_(e){let t=(0,y.Pz)(e).length;this.bytesReceived+=t,this.stats_.incrementCounter("bytes_received",t)}}class em{constructor(e,t,n,i){if(this.onDisconnect=n,this.urlFn=i,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(1e8*Math.random()),this.sendNewPolls=!0,(0,y.Yr)())this.commandCB=e,this.onMessageCB=t;else{this.uniqueCallbackIdentifier=N(),window["pLPCommand"+this.uniqueCallbackIdentifier]=e,window["pRTLPCB"+this.uniqueCallbackIdentifier]=t,this.myIFrame=em.createIFrame_();let n="";if(this.myIFrame.src&&"javascript:"===this.myIFrame.src.substr(0,11)){let e=document.domain;n='<script>document.domain="'+e+'";</script>'}let i="<html><body>"+n+"</body></html>";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(i),this.myIFrame.doc.close()}catch(e){F("frame writing exception"),e.stack&&F(e.stack),F(e)}}}static createIFrame_(){let e=document.createElement("iframe");if(e.style.display="none",document.body){document.body.appendChild(e);try{let t=e.contentWindow.document;t||F("No IE domain setting required")}catch(n){let t=document.domain;e.src="javascript:void((function(){document.open();document.domain='"+t+"';document.close();})())"}}else throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";return e.contentDocument?e.doc=e.contentDocument:e.contentWindow?e.doc=e.contentWindow.document:e.document&&(e.doc=e.document),e}close(){this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.innerHTML="",setTimeout(()=>{null!==this.myIFrame&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)},Math.floor(0)));let e=this.onDisconnect;e&&(this.onDisconnect=null,e())}startLongPoll(e,t){for(this.myID=e,this.myPW=t,this.alive=!0;this.newRequest_(););}newRequest_(){if(!this.alive||!this.sendNewPolls||!(this.outstandingRequests.size<(this.pendingSegs.length>0?2:1)))return!1;{this.currentSerial++;let e={};e.id=this.myID,e.pw=this.myPW,e.ser=this.currentSerial;let t=this.urlFn(e),n="",i=0;for(;this.pendingSegs.length>0;){let e=this.pendingSegs[0];if(e.d.length+30+n.length<=1870){let e=this.pendingSegs.shift();n=n+"&seg"+i+"="+e.seg+"&ts"+i+"="+e.ts+"&d"+i+"="+e.d,i++}else break}return t+=n,this.addLongPollTag_(t,this.currentSerial),!0}}enqueueSegment(e,t,n){this.pendingSegs.push({seg:e,ts:t,d:n}),this.alive&&this.newRequest_()}addLongPollTag_(e,t){this.outstandingRequests.add(t);let n=()=>{this.outstandingRequests.delete(t),this.newRequest_()},i=setTimeout(n,Math.floor(25e3)),r=()=>{clearTimeout(i),n()};this.addTag(e,r)}addTag(e,t){(0,y.Yr)()?this.doNodeLongPoll(e,t):setTimeout(()=>{try{if(!this.sendNewPolls)return;let n=this.myIFrame.doc.createElement("script");n.type="text/javascript",n.async=!0,n.src=e,n.onload=n.onreadystatechange=function(){let e=n.readyState;e&&"loaded"!==e&&"complete"!==e||(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),t())},n.onerror=()=>{F("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(n)}catch(e){}},Math.floor(1))}}let ey=null;"undefined"!=typeof MozWebSocket?ey=MozWebSocket:"undefined"!=typeof WebSocket&&(ey=WebSocket);class ev{constructor(e,t,n,i,r,s,o){this.connId=e,this.applicationId=n,this.appCheckToken=i,this.authToken=r,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=q(this.connId),this.stats_=e_(t),this.connURL=ev.connectionURL_(t,s,o,i),this.nodeAdmin=t.nodeAdmin}static connectionURL_(e,t,n,i){let r={};return r.v="5",!(0,y.Yr)()&&"undefined"!=typeof location&&location.hostname&&es.test(location.hostname)&&(r.r="f"),t&&(r.s=t),n&&(r.ls=n),i&&(r.ac=i),eh(e,eo,r)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,b.set("previous_websocket_failure",!0);try{if((0,y.Yr)()){let e=this.nodeAdmin?"AdminNode":"Node",t={headers:{"User-Agent":`Firebase/5/${w}/${C.platform}/${e}`,"X-Firebase-GMPID":this.applicationId||""}};this.authToken&&(t.headers.Authorization=`Bearer ${this.authToken}`),this.appCheckToken&&(t.headers["X-Firebase-AppCheck"]=this.appCheckToken);let n=C.env,i=0===this.connURL.indexOf("wss://")?n.HTTPS_PROXY||n.https_proxy:n.HTTP_PROXY||n.http_proxy;i&&(t.proxy={origin:i}),this.mySock=new ey(this.connURL,[],t)}else{let e={headers:{"X-Firebase-GMPID":this.applicationId||"","X-Firebase-AppCheck":this.appCheckToken||""}};this.mySock=new ey(this.connURL,[],e)}}catch(t){this.log_("Error instantiating WebSocket.");let e=t.message||t.data;e&&this.log_(e),this.onClosed_();return}this.mySock.onopen=()=>{this.log_("Websocket connected."),this.everConnected_=!0},this.mySock.onclose=()=>{this.log_("Websocket connection was disconnected."),this.mySock=null,this.onClosed_()},this.mySock.onmessage=e=>{this.handleIncomingFrame(e)},this.mySock.onerror=e=>{this.log_("WebSocket error.  Closing connection.");let t=e.message||e.data;t&&this.log_(t),this.onClosed_()}}start(){}static forceDisallow(){ev.forceDisallow_=!0}static isAvailable(){let e=!1;if("undefined"!=typeof navigator&&navigator.userAgent){let t=navigator.userAgent.match(/Android ([0-9]{0,}\.[0-9]{0,})/);t&&t.length>1&&4.4>parseFloat(t[1])&&(e=!0)}return!e&&null!==ey&&!ev.forceDisallow_}static previouslyFailed(){return b.isInMemoryStorage||!0===b.get("previous_websocket_failure")}markConnectionHealthy(){b.remove("previous_websocket_failure")}appendFrame_(e){if(this.frames.push(e),this.frames.length===this.totalFrames){let e=this.frames.join("");this.frames=null;let t=(0,y.cI)(e);this.onMessage(t)}}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if((0,y.hu)(null===this.frames,"We already have a frame buffer"),e.length<=6){let t=Number(e);if(!isNaN(t))return this.handleNewFrameCount_(t),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){if(null===this.mySock)return;let t=e.data;if(this.bytesReceived+=t.length,this.stats_.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),null!==this.frames)this.appendFrame_(t);else{let e=this.extractFrameCount_(t);null!==e&&this.appendFrame_(e)}}send(e){this.resetKeepAlive();let t=(0,y.Pz)(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);let n=G(t,16384);n.length>1&&this.sendString_(String(n.length));for(let e=0;e<n.length;e++)this.sendString_(n[e])}shutdown_(){this.isClosed_=!0,this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),this.mySock&&(this.mySock.close(),this.mySock=null)}onClosed_(){!this.isClosed_&&(this.log_("WebSocket is closing itself"),this.shutdown_(),this.onDisconnect&&(this.onDisconnect(this.everConnected_),this.onDisconnect=null))}close(){this.isClosed_||(this.log_("WebSocket is being closed"),this.shutdown_())}resetKeepAlive(){clearInterval(this.keepaliveTimer),this.keepaliveTimer=setInterval(()=>{this.mySock&&this.sendString_("0"),this.resetKeepAlive()},Math.floor(45e3))}sendString_(e){try{this.mySock.send(e)}catch(e){this.log_("Exception thrown from WebSocket.send():",e.message||e.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}}}ev.responsesRequiredToBeHealthy=2,ev.healthyTimeout=3e4;/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class eC{constructor(e){this.initTransports_(e)}static get ALL_TRANSPORTS(){return[eg,ev]}initTransports_(e){let t=ev&&ev.isAvailable(),n=t&&!ev.previouslyFailed();if(e.webSocketOnly&&(t||A("wss:// URL used, but browser isn't known to support websockets.  Trying anyway."),n=!0),n)this.transports_=[ev];else{let e=this.transports_=[];for(let t of eC.ALL_TRANSPORTS)t&&t.isAvailable()&&e.push(t)}}initialTransport(){if(this.transports_.length>0)return this.transports_[0];throw Error("No transports available")}upgradeTransport(){return this.transports_.length>1?this.transports_[1]:null}}class ew{constructor(e,t,n,i,r,s,o,l,a,h){this.id=e,this.repoInfo_=t,this.applicationId_=n,this.appCheckToken_=i,this.authToken_=r,this.onMessage_=s,this.onReady_=o,this.onDisconnect_=l,this.onKill_=a,this.lastSessionId=h,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=q("c:"+this.id+":"),this.transportManager_=new eC(t),this.log_("Connection created"),this.start_()}start_(){let e=this.transportManager_.initialTransport();this.conn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,null,this.lastSessionId),this.primaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;let t=this.connReceiver_(this.conn_),n=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout(()=>{this.conn_&&this.conn_.open(t,n)},Math.floor(0));let i=e.healthyTimeout||0;i>0&&(this.healthyTimeout_=et(()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&this.conn_.bytesReceived>102400?(this.log_("Connection exceeded healthy timeout but has received "+this.conn_.bytesReceived+" bytes.  Marking connection healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()):this.conn_&&this.conn_.bytesSent>10240?this.log_("Connection exceeded healthy timeout but has sent "+this.conn_.bytesSent+" bytes.  Leaving connection alive."):(this.log_("Closing unhealthy connection after timeout."),this.close()))},Math.floor(i)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(e){return t=>{e===this.conn_?this.onConnectionLost_(t):e===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(e){return t=>{2!==this.state_&&(e===this.rx_?this.onPrimaryMessageReceived_(t):e===this.secondaryConn_?this.onSecondaryMessageReceived_(t):this.log_("message on old connection"))}}sendRequest(e){this.sendData_({t:"d",d:e})}tryCleanupConnection(){this.tx_===this.secondaryConn_&&this.rx_===this.secondaryConn_&&(this.log_("cleaning up and promoting a connection: "+this.secondaryConn_.connId),this.conn_=this.secondaryConn_,this.secondaryConn_=null)}onSecondaryControl_(e){if("t"in e){let t=e.t;"a"===t?this.upgradeIfSecondaryHealthy_():"r"===t?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),(this.tx_===this.secondaryConn_||this.rx_===this.secondaryConn_)&&this.close()):"o"===t&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_())}}onSecondaryMessageReceived_(e){let t=B("t",e),n=B("d",e);if("c"===t)this.onSecondaryControl_(n);else if("d"===t)this.pendingDataMessages.push(n);else throw Error("Unknown protocol layer: "+t)}upgradeIfSecondaryHealthy_(){this.secondaryResponsesRequired_<=0?(this.log_("Secondary connection is healthy."),this.isHealthy_=!0,this.secondaryConn_.markConnectionHealthy(),this.proceedWithUpgrade_()):(this.log_("sending ping on secondary."),this.secondaryConn_.send({t:"c",d:{t:"p",d:{}}}))}proceedWithUpgrade_(){this.secondaryConn_.start(),this.log_("sending client ack on secondary"),this.secondaryConn_.send({t:"c",d:{t:"a",d:{}}}),this.log_("Ending transmission on primary"),this.conn_.send({t:"c",d:{t:"n",d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()}onPrimaryMessageReceived_(e){let t=B("t",e),n=B("d",e);"c"===t?this.onControl_(n):"d"===t&&this.onDataMessage_(n)}onDataMessage_(e){this.onPrimaryResponse_(),this.onMessage_(e)}onPrimaryResponse_(){!this.isHealthy_&&(this.primaryResponsesRequired_--,this.primaryResponsesRequired_<=0&&(this.log_("Primary connection is healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()))}onControl_(e){let t=B("t",e);if("d"in e){let n=e.d;if("h"===t)this.onHandshake_(n);else if("n"===t){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(let e=0;e<this.pendingDataMessages.length;++e)this.onDataMessage_(this.pendingDataMessages[e]);this.pendingDataMessages=[],this.tryCleanupConnection()}else"s"===t?this.onConnectionShutdown_(n):"r"===t?this.onReset_(n):"e"===t?L("Server Error: "+n):"o"===t?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):L("Unknown control packet command: "+t)}}onHandshake_(e){let t=e.ts,n=e.v,i=e.h;this.sessionId=e.s,this.repoInfo_.host=i,0===this.state_&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,t),"5"!==n&&A("Protocol version mismatch detected"),this.tryStartUpgrade_())}tryStartUpgrade_(){let e=this.transportManager_.upgradeTransport();e&&this.startUpgrade_(e)}startUpgrade_(e){this.secondaryConn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,this.sessionId),this.secondaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;let t=this.connReceiver_(this.secondaryConn_),n=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(t,n),et(()=>{this.secondaryConn_&&(this.log_("Timed out trying to upgrade."),this.secondaryConn_.close())},Math.floor(6e4))}onReset_(e){this.log_("Reset packet received.  New host: "+e),this.repoInfo_.host=e,1===this.state_?this.close():(this.closeConnections_(),this.start_())}onConnectionEstablished_(e,t){this.log_("Realtime connection established."),this.conn_=e,this.state_=1,this.onReady_&&(this.onReady_(t,this.sessionId),this.onReady_=null),0===this.primaryResponsesRequired_?(this.log_("Primary connection is healthy."),this.isHealthy_=!0):et(()=>{this.sendPingOnPrimaryIfNecessary_()},Math.floor(5e3))}sendPingOnPrimaryIfNecessary_(){this.isHealthy_||1!==this.state_||(this.log_("sending ping on primary."),this.sendData_({t:"c",d:{t:"p",d:{}}}))}onSecondaryConnectionLost_(){let e=this.secondaryConn_;this.secondaryConn_=null,(this.tx_===e||this.rx_===e)&&this.close()}onConnectionLost_(e){this.conn_=null,e||0!==this.state_?1===this.state_&&this.log_("Realtime connection lost."):(this.log_("Realtime connection failed."),this.repoInfo_.isCacheableHost()&&(b.remove("host:"+this.repoInfo_.host),this.repoInfo_.internalHost=this.repoInfo_.host)),this.close()}onConnectionShutdown_(e){this.log_("Connection shutdown command received. Shutting down..."),this.onKill_&&(this.onKill_(e),this.onKill_=null),this.onDisconnect_=null,this.close()}sendData_(e){if(1!==this.state_)throw"Connection is not connected";this.tx_.send(e)}close(){2!==this.state_&&(this.log_("Closing realtime connection."),this.state_=2,this.closeConnections_(),this.onDisconnect_&&(this.onDisconnect_(),this.onDisconnect_=null))}closeConnections_(){this.log_("Shutting down all connections"),this.conn_&&(this.conn_.close(),this.conn_=null),this.secondaryConn_&&(this.secondaryConn_.close(),this.secondaryConn_=null),this.healthyTimeout_&&(clearTimeout(this.healthyTimeout_),this.healthyTimeout_=null)}}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class eT{put(e,t,n,i){}merge(e,t,n,i){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,t,n){}onDisconnectMerge(e,t,n){}onDisconnectCancel(e,t){}reportStats(e){}}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class eI{constructor(e){this.allowedEvents_=e,this.listeners_={},(0,y.hu)(Array.isArray(e)&&e.length>0,"Requires a non-empty array")}trigger(e,...t){if(Array.isArray(this.listeners_[e])){let n=[...this.listeners_[e]];for(let e=0;e<n.length;e++)n[e].callback.apply(n[e].context,t)}}on(e,t,n){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:n});let i=this.getInitialEvent(e);i&&t.apply(n,i)}off(e,t,n){this.validateEventType_(e);let i=this.listeners_[e]||[];for(let e=0;e<i.length;e++)if(i[e].callback===t&&(!n||n===i[e].context)){i.splice(e,1);return}}validateEventType_(e){(0,y.hu)(this.allowedEvents_.find(t=>t===e),"Unknown event: "+e)}}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class ek extends eI{constructor(){super(["online"]),this.online_=!0,"undefined"==typeof window||void 0===window.addEventListener||(0,y.uI)()||(window.addEventListener("online",()=>{this.online_||(this.online_=!0,this.trigger("online",!0))},!1),window.addEventListener("offline",()=>{this.online_&&(this.online_=!1,this.trigger("online",!1))},!1))}static getInstance(){return new ek}getInitialEvent(e){return(0,y.hu)("online"===e,"Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}class eb{constructor(e,t){if(void 0===t){this.pieces_=e.split("/");let t=0;for(let e=0;e<this.pieces_.length;e++)this.pieces_[e].length>0&&(this.pieces_[t]=this.pieces_[e],t++);this.pieces_.length=t,this.pieceNum_=0}else this.pieces_=e,this.pieceNum_=t}toString(){let e="";for(let t=this.pieceNum_;t<this.pieces_.length;t++)""!==this.pieces_[t]&&(e+="/"+this.pieces_[t]);return e||"/"}}function eE(){return new eb("")}function eP(e){return e.pieceNum_>=e.pieces_.length?null:e.pieces_[e.pieceNum_]}function eN(e){return e.pieces_.length-e.pieceNum_}function eS(e){let t=e.pieceNum_;return t<e.pieces_.length&&t++,new eb(e.pieces_,t)}function ex(e){return e.pieceNum_<e.pieces_.length?e.pieces_[e.pieces_.length-1]:null}function eR(e,t=0){return e.pieces_.slice(e.pieceNum_+t)}function eD(e){if(e.pieceNum_>=e.pieces_.length)return null;let t=[];for(let n=e.pieceNum_;n<e.pieces_.length-1;n++)t.push(e.pieces_[n]);return new eb(t,0)}function eM(e,t){let n=[];for(let t=e.pieceNum_;t<e.pieces_.length;t++)n.push(e.pieces_[t]);if(t instanceof eb)for(let e=t.pieceNum_;e<t.pieces_.length;e++)n.push(t.pieces_[e]);else{let e=t.split("/");for(let t=0;t<e.length;t++)e[t].length>0&&n.push(e[t])}return new eb(n,0)}function eF(e){return e.pieceNum_>=e.pieces_.length}function eq(e,t){let n=eP(e),i=eP(t);if(null===n)return t;if(n===i)return eq(eS(e),eS(t));throw Error("INTERNAL ERROR: innerPath ("+t+") is not within outerPath ("+e+")")}function eL(e,t){if(eN(e)!==eN(t))return!1;for(let n=e.pieceNum_,i=t.pieceNum_;n<=e.pieces_.length;n++,i++)if(e.pieces_[n]!==t.pieces_[i])return!1;return!0}function eO(e,t){let n=e.pieceNum_,i=t.pieceNum_;if(eN(e)>eN(t))return!1;for(;n<e.pieces_.length;){if(e.pieces_[n]!==t.pieces_[i])return!1;++n,++i}return!0}class eA{constructor(e,t){this.errorPrefix_=t,this.parts_=eR(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let e=0;e<this.parts_.length;e++)this.byteLength_+=(0,y.ug)(this.parts_[e]);eW(this)}}function eW(e){if(e.byteLength_>768)throw Error(e.errorPrefix_+"has a key path longer than 768 bytes ("+e.byteLength_+").");if(e.parts_.length>32)throw Error(e.errorPrefix_+"path specified exceeds the maximum depth that can be written (32) or object contains a cycle "+eU(e))}function eU(e){return 0===e.parts_.length?"":"in property '"+e.parts_.join(".")+"'"}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class ez extends eI{constructor(){let e,t;super(["visible"]),"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(t="visibilitychange",e="hidden"):void 0!==document.mozHidden?(t="mozvisibilitychange",e="mozHidden"):void 0!==document.msHidden?(t="msvisibilitychange",e="msHidden"):void 0!==document.webkitHidden&&(t="webkitvisibilitychange",e="webkitHidden")),this.visible_=!0,t&&document.addEventListener(t,()=>{let t=!document[e];t!==this.visible_&&(this.visible_=t,this.trigger("visible",t))},!1)}static getInstance(){return new ez}getInitialEvent(e){return(0,y.hu)("visible"===e,"Unknown event type: "+e),[this.visible_]}}class eH extends eT{constructor(e,t,n,i,r,s,o,l){if(super(),this.repoInfo_=e,this.applicationId_=t,this.onDataUpdate_=n,this.onConnectStatus_=i,this.onServerInfoUpdate_=r,this.authTokenProvider_=s,this.appCheckTokenProvider_=o,this.authOverride_=l,this.id=eH.nextPersistentConnectionId_++,this.log_=q("p:"+this.id+":"),this.interruptReasons_={},this.listens=new Map,this.outstandingPuts_=[],this.outstandingGets_=[],this.outstandingPutCount_=0,this.outstandingGetCount_=0,this.onDisconnectRequestQueue_=[],this.connected_=!1,this.reconnectDelay_=1e3,this.maxReconnectDelay_=3e5,this.securityDebugCallback_=null,this.lastSessionId=null,this.establishConnectionTimer_=null,this.visible_=!1,this.requestCBHash_={},this.requestNumber_=0,this.realtime_=null,this.authToken_=null,this.appCheckToken_=null,this.forceTokenRefresh_=!1,this.invalidAuthTokenCount_=0,this.invalidAppCheckTokenCount_=0,this.firstConnection_=!0,this.lastConnectionAttemptTime_=null,this.lastConnectionEstablishedTime_=null,l&&!(0,y.Yr)())throw Error("Auth override specified in options, but not supported on non Node.js platforms");ez.getInstance().on("visible",this.onVisible_,this),-1===e.host.indexOf("fblocal")&&ek.getInstance().on("online",this.onOnline_,this)}sendRequest(e,t,n){let i=++this.requestNumber_,r={r:i,a:e,b:t};this.log_((0,y.Pz)(r)),(0,y.hu)(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(r),n&&(this.requestCBHash_[i]=n)}get(e){this.initConnection_();let t=new y.BH,n={p:e._path.toString(),q:e._queryObject},i={action:"g",request:n,onComplete:e=>{let i=e.d;"ok"===e.s?(this.onDataUpdate_(n.p,i,!1,null),t.resolve(i)):t.reject(i)}};this.outstandingGets_.push(i),this.outstandingGetCount_++;let r=this.outstandingGets_.length-1;return this.connected_||setTimeout(()=>{let e=this.outstandingGets_[r];void 0!==e&&i===e&&(delete this.outstandingGets_[r],this.outstandingGetCount_--,0===this.outstandingGetCount_&&(this.outstandingGets_=[]),this.log_("get "+r+" timed out on connection"),t.reject(Error("Client is offline.")))},3e3),this.connected_&&this.sendGet_(r),t.promise}listen(e,t,n,i){this.initConnection_();let r=e._queryIdentifier,s=e._path.toString();this.log_("Listen called for "+s+" "+r),this.listens.has(s)||this.listens.set(s,new Map),(0,y.hu)(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),(0,y.hu)(!this.listens.get(s).has(r),"listen() called twice for same path/queryId.");let o={onComplete:i,hashFn:t,query:e,tag:n};this.listens.get(s).set(r,o),this.connected_&&this.sendListen_(o)}sendGet_(e){let t=this.outstandingGets_[e];this.sendRequest("g",t.request,n=>{delete this.outstandingGets_[e],this.outstandingGetCount_--,0===this.outstandingGetCount_&&(this.outstandingGets_=[]),t.onComplete&&t.onComplete(n)})}sendListen_(e){let t=e.query,n=t._path.toString(),i=t._queryIdentifier;this.log_("Listen on "+n+" for "+i);let r={p:n};e.tag&&(r.q=t._queryObject,r.t=e.tag),r.h=e.hashFn(),this.sendRequest("q",r,r=>{let s=r.d,o=r.s;eH.warnOnListenWarnings_(s,t);let l=this.listens.get(n)&&this.listens.get(n).get(i);l===e&&(this.log_("listen response",r),"ok"!==o&&this.removeListen_(n,i),e.onComplete&&e.onComplete(o,s))})}static warnOnListenWarnings_(e,t){if(e&&"object"==typeof e&&(0,y.r3)(e,"w")){let n=(0,y.DV)(e,"w");if(Array.isArray(n)&&~n.indexOf("no_index")){let e='".indexOn": "'+t._queryParams.getIndex().toString()+'"',n=t._path.toString();A(`Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ${e} at ${n} to your security rules for better performance.`)}}}refreshAuthToken(e){this.authToken_=e,this.log_("Auth token refreshed"),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest("unauth",{},()=>{}),this.reduceReconnectDelayIfAdminCredential_(e)}reduceReconnectDelayIfAdminCredential_(e){let t=e&&40===e.length;(t||(0,y.GJ)(e))&&(this.log_("Admin auth credential detected.  Reducing max reconnect time."),this.maxReconnectDelay_=3e4)}refreshAppCheckToken(e){this.appCheckToken_=e,this.log_("App check token refreshed"),this.appCheckToken_?this.tryAppCheck():this.connected_&&this.sendRequest("unappeck",{},()=>{})}tryAuth(){if(this.connected_&&this.authToken_){let e=this.authToken_,t=(0,y.w9)(e)?"auth":"gauth",n={cred:e};null===this.authOverride_?n.noauth=!0:"object"==typeof this.authOverride_&&(n.authvar=this.authOverride_),this.sendRequest(t,n,t=>{let n=t.s,i=t.d||"error";this.authToken_===e&&("ok"===n?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(n,i))})}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},e=>{let t=e.s,n=e.d||"error";"ok"===t?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(t,n)})}unlisten(e,t){let n=e._path.toString(),i=e._queryIdentifier;this.log_("Unlisten called for "+n+" "+i),(0,y.hu)(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query");let r=this.removeListen_(n,i);r&&this.connected_&&this.sendUnlisten_(n,i,e._queryObject,t)}sendUnlisten_(e,t,n,i){this.log_("Unlisten on "+e+" for "+t);let r={p:e};i&&(r.q=n,r.t=i),this.sendRequest("n",r)}onDisconnectPut(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("o",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"o",data:t,onComplete:n})}onDisconnectMerge(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("om",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"om",data:t,onComplete:n})}onDisconnectCancel(e,t){this.initConnection_(),this.connected_?this.sendOnDisconnect_("oc",e,null,t):this.onDisconnectRequestQueue_.push({pathString:e,action:"oc",data:null,onComplete:t})}sendOnDisconnect_(e,t,n,i){let r={p:t,d:n};this.log_("onDisconnect "+e,r),this.sendRequest(e,r,e=>{i&&setTimeout(()=>{i(e.s,e.d)},Math.floor(0))})}put(e,t,n,i){this.putInternal("p",e,t,n,i)}merge(e,t,n,i){this.putInternal("m",e,t,n,i)}putInternal(e,t,n,i,r){this.initConnection_();let s={p:t,d:n};void 0!==r&&(s.h=r),this.outstandingPuts_.push({action:e,request:s,onComplete:i}),this.outstandingPutCount_++;let o=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(o):this.log_("Buffering put: "+t)}sendPut_(e){let t=this.outstandingPuts_[e].action,n=this.outstandingPuts_[e].request,i=this.outstandingPuts_[e].onComplete;this.outstandingPuts_[e].queued=this.connected_,this.sendRequest(t,n,n=>{this.log_(t+" response",n),delete this.outstandingPuts_[e],this.outstandingPutCount_--,0===this.outstandingPutCount_&&(this.outstandingPuts_=[]),i&&i(n.s,n.d)})}reportStats(e){if(this.connected_){let t={c:e};this.log_("reportStats",t),this.sendRequest("s",t,e=>{let t=e.s;if("ok"!==t){let t=e.d;this.log_("reportStats","Error sending stats: "+t)}})}}onDataMessage_(e){if("r"in e){this.log_("from server: "+(0,y.Pz)(e));let t=e.r,n=this.requestCBHash_[t];n&&(delete this.requestCBHash_[t],n(e.b))}else if("error"in e)throw"A server-side error has occurred: "+e.error;else"a"in e&&this.onDataPush_(e.a,e.b)}onDataPush_(e,t){this.log_("handleServerMessage",e,t),"d"===e?this.onDataUpdate_(t.p,t.d,!1,t.t):"m"===e?this.onDataUpdate_(t.p,t.d,!0,t.t):"c"===e?this.onListenRevoked_(t.p,t.q):"ac"===e?this.onAuthRevoked_(t.s,t.d):"apc"===e?this.onAppCheckRevoked_(t.s,t.d):"sd"===e?this.onSecurityDebugPacket_(t):L("Unrecognized action received from server: "+(0,y.Pz)(e)+"\nAre you using the latest client?")}onReady_(e,t){this.log_("connection ready"),this.connected_=!0,this.lastConnectionEstablishedTime_=new Date().getTime(),this.handleTimestamp_(e),this.lastSessionId=t,this.firstConnection_&&this.sendConnectStats_(),this.restoreState_(),this.firstConnection_=!1,this.onConnectStatus_(!0)}scheduleConnect_(e){(0,y.hu)(!this.realtime_,"Scheduling a connect when we're already connected/ing?"),this.establishConnectionTimer_&&clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=setTimeout(()=>{this.establishConnectionTimer_=null,this.establishConnection_()},Math.floor(e))}initConnection_(){!this.realtime_&&this.firstConnection_&&this.scheduleConnect_(0)}onVisible_(e){!e||this.visible_||this.reconnectDelay_!==this.maxReconnectDelay_||(this.log_("Window became visible.  Reducing delay."),this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0)),this.visible_=e}onOnline_(e){e?(this.log_("Browser went online."),this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0)):(this.log_("Browser went offline.  Killing connection."),this.realtime_&&this.realtime_.close())}onRealtimeDisconnect_(){if(this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()){if(this.visible_){if(this.lastConnectionEstablishedTime_){let e=new Date().getTime()-this.lastConnectionEstablishedTime_;e>3e4&&(this.reconnectDelay_=1e3),this.lastConnectionEstablishedTime_=null}}else this.log_("Window isn't visible.  Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=new Date().getTime();let e=new Date().getTime()-this.lastConnectionAttemptTime_,t=Math.max(0,this.reconnectDelay_-e);t=Math.random()*t,this.log_("Trying to reconnect in "+t+"ms"),this.scheduleConnect_(t),this.reconnectDelay_=Math.min(this.maxReconnectDelay_,1.3*this.reconnectDelay_)}this.onConnectStatus_(!1)}async establishConnection_(){if(this.shouldReconnect_()){this.log_("Making a connection attempt"),this.lastConnectionAttemptTime_=new Date().getTime(),this.lastConnectionEstablishedTime_=null;let e=this.onDataMessage_.bind(this),t=this.onReady_.bind(this),n=this.onRealtimeDisconnect_.bind(this),i=this.id+":"+eH.nextConnectionId_++,r=this.lastSessionId,s=!1,o=null,l=function(){o?o.close():(s=!0,n())};this.realtime_={close:l,sendRequest:function(e){(0,y.hu)(o,"sendRequest call when we're not connected not allowed."),o.sendRequest(e)}};let a=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{let[l,h]=await Promise.all([this.authTokenProvider_.getToken(a),this.appCheckTokenProvider_.getToken(a)]);s?F("getToken() completed but was canceled"):(F("getToken() completed. Creating connection."),this.authToken_=l&&l.accessToken,this.appCheckToken_=h&&h.token,o=new ew(i,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,e,t,n,e=>{A(e+" ("+this.repoInfo_.toString()+")"),this.interrupt("server_kill")},r))}catch(e){this.log_("Failed to get token: "+e),s||(this.repoInfo_.nodeAdmin&&A(e),l())}}}interrupt(e){F("Interrupting connection for reason: "+e),this.interruptReasons_[e]=!0,this.realtime_?this.realtime_.close():(this.establishConnectionTimer_&&(clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=null),this.connected_&&this.onRealtimeDisconnect_())}resume(e){F("Resuming connection for reason: "+e),delete this.interruptReasons_[e],(0,y.xb)(this.interruptReasons_)&&(this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(e){let t=e-new Date().getTime();this.onServerInfoUpdate_({serverTimeOffset:t})}cancelSentTransactions_(){for(let e=0;e<this.outstandingPuts_.length;e++){let t=this.outstandingPuts_[e];t&&"h"in t.request&&t.queued&&(t.onComplete&&t.onComplete("disconnect"),delete this.outstandingPuts_[e],this.outstandingPutCount_--)}0===this.outstandingPutCount_&&(this.outstandingPuts_=[])}onListenRevoked_(e,t){let n;n=t?t.map(e=>K(e)).join("$"):"default";let i=this.removeListen_(e,n);i&&i.onComplete&&i.onComplete("permission_denied")}removeListen_(e,t){let n;let i=new eb(e).toString();if(this.listens.has(i)){let e=this.listens.get(i);n=e.get(t),e.delete(t),0===e.size&&this.listens.delete(i)}else n=void 0;return n}onAuthRevoked_(e,t){F("Auth token revoked: "+e+"/"+t),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),("invalid_token"===e||"permission_denied"===e)&&(this.invalidAuthTokenCount_++,this.invalidAuthTokenCount_>=3&&(this.reconnectDelay_=3e4,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(e,t){F("App check token revoked: "+e+"/"+t),this.appCheckToken_=null,this.forceTokenRefresh_=!0,("invalid_token"===e||"permission_denied"===e)&&(this.invalidAppCheckTokenCount_++,this.invalidAppCheckTokenCount_>=3&&this.appCheckTokenProvider_.notifyForInvalidToken())}onSecurityDebugPacket_(e){this.securityDebugCallback_?this.securityDebugCallback_(e):"msg"in e&&console.log("FIREBASE: "+e.msg.replace("\n","\nFIREBASE: "))}restoreState_(){for(let e of(this.tryAuth(),this.tryAppCheck(),this.listens.values()))for(let t of e.values())this.sendListen_(t);for(let e=0;e<this.outstandingPuts_.length;e++)this.outstandingPuts_[e]&&this.sendPut_(e);for(;this.onDisconnectRequestQueue_.length;){let e=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(e.action,e.pathString,e.data,e.onComplete)}for(let e=0;e<this.outstandingGets_.length;e++)this.outstandingGets_[e]&&this.sendGet_(e)}sendConnectStats_(){let e={},t="js";(0,y.Yr)()&&(t=this.repoInfo_.nodeAdmin?"admin_node":"node"),e["sdk."+t+"."+w.replace(/\./g,"-")]=1,(0,y.uI)()?e["framework.cordova"]=1:(0,y.b$)()&&(e["framework.reactnative"]=1),this.reportStats(e)}shouldReconnect_(){let e=ek.getInstance().currentlyOnline();return(0,y.xb)(this.interruptReasons_)&&e}}eH.nextPersistentConnectionId_=0,eH.nextConnectionId_=0;/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class eY{constructor(e,t){this.name=e,this.node=t}static Wrap(e,t){return new eY(e,t)}}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class ej{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,t){let n=new eY(H,e),i=new eY(H,t);return 0!==this.compare(n,i)}minPost(){return eY.MIN}}class eV extends ej{static get __EMPTY_NODE(){return i}static set __EMPTY_NODE(e){i=e}compare(e,t){return j(e.name,t.name)}isDefinedOn(e){throw(0,y.g5)("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,t){return!1}minPost(){return eY.MIN}maxPost(){return new eY(Y,i)}makePost(e,t){return(0,y.hu)("string"==typeof e,"KeyIndex indexValue must always be a string."),new eY(e,i)}toString(){return".key"}}let eB=new eV;/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class eK{constructor(e,t,n,i,r=null){this.isReverse_=i,this.resultGenerator_=r,this.nodeStack_=[];let s=1;for(;!e.isEmpty();)if(s=t?n(e.key,t):1,i&&(s*=-1),s<0)e=this.isReverse_?e.left:e.right;else if(0===s){this.nodeStack_.push(e);break}else this.nodeStack_.push(e),e=this.isReverse_?e.right:e.left}getNext(){let e;if(0===this.nodeStack_.length)return null;let t=this.nodeStack_.pop();if(e=this.resultGenerator_?this.resultGenerator_(t.key,t.value):{key:t.key,value:t.value},this.isReverse_)for(t=t.left;!t.isEmpty();)this.nodeStack_.push(t),t=t.right;else for(t=t.right;!t.isEmpty();)this.nodeStack_.push(t),t=t.left;return e}hasNext(){return this.nodeStack_.length>0}peek(){if(0===this.nodeStack_.length)return null;let e=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value}}}class eG{constructor(e,t,n,i,r){this.key=e,this.value=t,this.color=null!=n?n:eG.RED,this.left=null!=i?i:eQ.EMPTY_NODE,this.right=null!=r?r:eQ.EMPTY_NODE}copy(e,t,n,i,r){return new eG(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=i?i:this.left,null!=r?r:this.right)}count(){return this.left.count()+1+this.right.count()}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||!!e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min_(){return this.left.isEmpty()?this:this.left.min_()}minKey(){return this.min_().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let i=this,r=n(e,i.key);return(i=r<0?i.copy(null,null,null,i.left.insert(e,t,n),null):0===r?i.copy(null,t,null,null,null):i.copy(null,null,null,null,i.right.insert(e,t,n))).fixUp_()}removeMin_(){if(this.left.isEmpty())return eQ.EMPTY_NODE;let e=this;return e.left.isRed_()||e.left.left.isRed_()||(e=e.moveRedLeft_()),(e=e.copy(null,null,null,e.left.removeMin_(),null)).fixUp_()}remove(e,t){let n,i;if(n=this,0>t(e,n.key))n.left.isEmpty()||n.left.isRed_()||n.left.left.isRed_()||(n=n.moveRedLeft_()),n=n.copy(null,null,null,n.left.remove(e,t),null);else{if(n.left.isRed_()&&(n=n.rotateRight_()),n.right.isEmpty()||n.right.isRed_()||n.right.left.isRed_()||(n=n.moveRedRight_()),0===t(e,n.key)){if(n.right.isEmpty())return eQ.EMPTY_NODE;i=n.right.min_(),n=n.copy(i.key,i.value,null,null,n.right.removeMin_())}n=n.copy(null,null,null,null,n.right.remove(e,t))}return n.fixUp_()}isRed_(){return this.color}fixUp_(){let e=this;return e.right.isRed_()&&!e.left.isRed_()&&(e=e.rotateLeft_()),e.left.isRed_()&&e.left.left.isRed_()&&(e=e.rotateRight_()),e.left.isRed_()&&e.right.isRed_()&&(e=e.colorFlip_()),e}moveRedLeft_(){let e=this.colorFlip_();return e.right.left.isRed_()&&(e=(e=(e=e.copy(null,null,null,null,e.right.rotateRight_())).rotateLeft_()).colorFlip_()),e}moveRedRight_(){let e=this.colorFlip_();return e.left.left.isRed_()&&(e=(e=e.rotateRight_()).colorFlip_()),e}rotateLeft_(){let e=this.copy(null,null,eG.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){let e=this.copy(null,null,eG.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip_(){let e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth_(){let e=this.check_();return Math.pow(2,e)<=this.count()+1}check_(){if(this.isRed_()&&this.left.isRed_())throw Error("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed_())throw Error("Right child of ("+this.key+","+this.value+") is red");let e=this.left.check_();if(e===this.right.check_())return e+(this.isRed_()?0:1);throw Error("Black depths differ")}}eG.RED=!0,eG.BLACK=!1;class eQ{constructor(e,t=eQ.EMPTY_NODE){this.comparator_=e,this.root_=t}insert(e,t){return new eQ(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,eG.BLACK,null,null))}remove(e){return new eQ(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,eG.BLACK,null,null))}get(e){let t;let n=this.root_;for(;!n.isEmpty();){if(0===(t=this.comparator_(e,n.key)))return n.value;t<0?n=n.left:t>0&&(n=n.right)}return null}getPredecessorKey(e){let t,n=this.root_,i=null;for(;!n.isEmpty();){if(0===(t=this.comparator_(e,n.key))){if(n.left.isEmpty()){if(i)return i.key;return null}for(n=n.left;!n.right.isEmpty();)n=n.right;return n.key}t<0?n=n.left:t>0&&(i=n,n=n.right)}throw Error("Attempted to find predecessor key for a nonexistent key.  What gives?")}isEmpty(){return this.root_.isEmpty()}count(){return this.root_.count()}minKey(){return this.root_.minKey()}maxKey(){return this.root_.maxKey()}inorderTraversal(e){return this.root_.inorderTraversal(e)}reverseTraversal(e){return this.root_.reverseTraversal(e)}getIterator(e){return new eK(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new eK(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new eK(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new eK(this.root_,null,this.comparator_,!0,e)}}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function e$(e,t){return j(e.name,t.name)}function eX(e,t){return j(e,t)}eQ.EMPTY_NODE=new class{copy(e,t,n,i,r){return this}insert(e,t,n){return new eG(e,t,null)}remove(e,t){return this}count(){return 0}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}check_(){return 0}isRed_(){return!1}};let eJ=function(e){return"number"==typeof e?"number:"+$(e):"string:"+e},eZ=function(e){if(e.isLeafNode()){let t=e.val();(0,y.hu)("string"==typeof t||"number"==typeof t||"object"==typeof t&&(0,y.r3)(t,".sv"),"Priority must be a string or number.")}else(0,y.hu)(e===r||e.isEmpty(),"priority of unexpected type.");(0,y.hu)(e===r||e.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")};class e0{constructor(e,t=e0.__childrenNodeConstructor.EMPTY_NODE){this.value_=e,this.priorityNode_=t,this.lazyHash_=null,(0,y.hu)(void 0!==this.value_&&null!==this.value_,"LeafNode shouldn't be created with null/undefined value."),eZ(this.priorityNode_)}static set __childrenNodeConstructor(e){s=e}static get __childrenNodeConstructor(){return s}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new e0(this.value_,e)}getImmediateChild(e){return".priority"===e?this.priorityNode_:e0.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return eF(e)?this:".priority"===eP(e)?this.priorityNode_:e0.__childrenNodeConstructor.EMPTY_NODE}hasChild(){return!1}getPredecessorChildName(e,t){return null}updateImmediateChild(e,t){return".priority"===e?this.updatePriority(t):t.isEmpty()&&".priority"!==e?this:e0.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,t).updatePriority(this.priorityNode_)}updateChild(e,t){let n=eP(e);return null===n?t:t.isEmpty()&&".priority"!==n?this:((0,y.hu)(".priority"!==n||1===eN(e),".priority must be the last token in a path"),this.updateImmediateChild(n,e0.__childrenNodeConstructor.EMPTY_NODE.updateChild(eS(e),t)))}isEmpty(){return!1}numChildren(){return 0}forEachChild(e,t){return!1}val(e){return e&&!this.getPriority().isEmpty()?{".value":this.getValue(),".priority":this.getPriority().val()}:this.getValue()}hash(){if(null===this.lazyHash_){let e="";this.priorityNode_.isEmpty()||(e+="priority:"+eJ(this.priorityNode_.val())+":");let t=typeof this.value_;e+=t+":","number"===t?e+=$(this.value_):e+=this.value_,this.lazyHash_=S(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===e0.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof e0.__childrenNodeConstructor?-1:((0,y.hu)(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){let t=typeof e.value_,n=typeof this.value_,i=e0.VALUE_TYPE_ORDER.indexOf(t),r=e0.VALUE_TYPE_ORDER.indexOf(n);return((0,y.hu)(i>=0,"Unknown leaf type: "+t),(0,y.hu)(r>=0,"Unknown leaf type: "+n),i!==r)?r-i:"object"===n?0:this.value_<e.value_?-1:this.value_===e.value_?0:1}withIndex(){return this}isIndexed(){return!0}equals(e){return e===this||!!e.isLeafNode()&&this.value_===e.value_&&this.priorityNode_.equals(e.priorityNode_)}}e0.VALUE_TYPE_ORDER=["object","boolean","number","string"];let e1=new class extends ej{compare(e,t){let n=e.node.getPriority(),i=t.node.getPriority(),r=n.compareTo(i);return 0===r?j(e.name,t.name):r}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return eY.MIN}maxPost(){return new eY(Y,new e0("[PRIORITY-POST]",l))}makePost(e,t){let n=o(e);return new eY(t,new e0("[PRIORITY-POST]",n))}toString(){return".priority"}},e2=Math.log(2);class e3{constructor(e){this.count=parseInt(Math.log(e+1)/e2,10),this.current_=this.count-1;let t=parseInt(Array(this.count+1).join("1"),2);this.bits_=e+1&t}nextBitIsOne(){let e=!(this.bits_&1<<this.current_);return this.current_--,e}}let e4=function(e,t,n,i){e.sort(t);let r=function(t,i){let s,o;let l=i-t;if(0===l)return null;if(1===l)return s=e[t],o=n?n(s):s,new eG(o,s.node,eG.BLACK,null,null);{let a=parseInt(l/2,10)+t,h=r(t,a),u=r(a+1,i);return s=e[a],o=n?n(s):s,new eG(o,s.node,eG.BLACK,h,u)}},s=new e3(e.length),o=function(t){let i=null,s=null,o=e.length,l=function(t,i){let s=o-t,l=o;o-=t;let h=r(s+1,l),u=e[s],c=n?n(u):u;a(new eG(c,u.node,i,null,h))},a=function(e){i?(i.left=e,i=e):(s=e,i=e)};for(let e=0;e<t.count;++e){let n=t.nextBitIsOne(),i=Math.pow(2,t.count-(e+1));n?l(i,eG.BLACK):(l(i,eG.BLACK),l(i,eG.RED))}return s}(s);return new eQ(i||t,o)},e5={};class e8{constructor(e,t){this.indexes_=e,this.indexSet_=t}static get Default(){return(0,y.hu)(e5&&e1,"ChildrenNode.ts has not been loaded"),a=a||new e8({".priority":e5},{".priority":e1})}get(e){let t=(0,y.DV)(this.indexes_,e);if(!t)throw Error("No index defined for "+e);return t instanceof eQ?t:null}hasIndex(e){return(0,y.r3)(this.indexSet_,e.toString())}addIndex(e,t){let n;(0,y.hu)(e!==eB,"KeyIndex always exists and isn't meant to be added to the IndexMap.");let i=[],r=!1,s=t.getIterator(eY.Wrap),o=s.getNext();for(;o;)r=r||e.isDefinedOn(o.node),i.push(o),o=s.getNext();n=r?e4(i,e.getCompare()):e5;let l=e.toString(),a=Object.assign({},this.indexSet_);a[l]=e;let h=Object.assign({},this.indexes_);return h[l]=n,new e8(h,a)}addToIndexes(e,t){let n=(0,y.UI)(this.indexes_,(n,i)=>{let r=(0,y.DV)(this.indexSet_,i);if((0,y.hu)(r,"Missing index implementation for "+i),n===e5){if(!r.isDefinedOn(e.node))return e5;{let n=[],i=t.getIterator(eY.Wrap),s=i.getNext();for(;s;)s.name!==e.name&&n.push(s),s=i.getNext();return n.push(e),e4(n,r.getCompare())}}{let i=t.get(e.name),r=n;return i&&(r=r.remove(new eY(e.name,i))),r.insert(e,e.node)}});return new e8(n,this.indexSet_)}removeFromIndexes(e,t){let n=(0,y.UI)(this.indexes_,n=>{if(n===e5)return n;{let i=t.get(e.name);return i?n.remove(new eY(e.name,i)):n}});return new e8(n,this.indexSet_)}}class e6{constructor(e,t,n){this.children_=e,this.priorityNode_=t,this.indexMap_=n,this.lazyHash_=null,this.priorityNode_&&eZ(this.priorityNode_),this.children_.isEmpty()&&(0,y.hu)(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}static get EMPTY_NODE(){return h||(h=new e6(new eQ(eX),null,e8.Default))}isLeafNode(){return!1}getPriority(){return this.priorityNode_||h}updatePriority(e){return this.children_.isEmpty()?this:new e6(this.children_,e,this.indexMap_)}getImmediateChild(e){if(".priority"===e)return this.getPriority();{let t=this.children_.get(e);return null===t?h:t}}getChild(e){let t=eP(e);return null===t?this:this.getImmediateChild(t).getChild(eS(e))}hasChild(e){return null!==this.children_.get(e)}updateImmediateChild(e,t){if((0,y.hu)(t,"We should always be passing snapshot nodes"),".priority"===e)return this.updatePriority(t);{let n,i;let r=new eY(e,t);t.isEmpty()?(n=this.children_.remove(e),i=this.indexMap_.removeFromIndexes(r,this.children_)):(n=this.children_.insert(e,t),i=this.indexMap_.addToIndexes(r,this.children_));let s=n.isEmpty()?h:this.priorityNode_;return new e6(n,s,i)}}updateChild(e,t){let n=eP(e);if(null===n)return t;{(0,y.hu)(".priority"!==eP(e)||1===eN(e),".priority must be the last token in a path");let i=this.getImmediateChild(n).updateChild(eS(e),t);return this.updateImmediateChild(n,i)}}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(e){if(this.isEmpty())return null;let t={},n=0,i=0,r=!0;if(this.forEachChild(e1,(s,o)=>{t[s]=o.val(e),n++,r&&e6.INTEGER_REGEXP_.test(s)?i=Math.max(i,Number(s)):r=!1}),e||!r||!(i<2*n))return e&&!this.getPriority().isEmpty()&&(t[".priority"]=this.getPriority().val()),t;{let e=[];for(let n in t)e[n]=t[n];return e}}hash(){if(null===this.lazyHash_){let e="";this.getPriority().isEmpty()||(e+="priority:"+eJ(this.getPriority().val())+":"),this.forEachChild(e1,(t,n)=>{let i=n.hash();""!==i&&(e+=":"+t+":"+i)}),this.lazyHash_=""===e?"":S(e)}return this.lazyHash_}getPredecessorChildName(e,t,n){let i=this.resolveIndex_(n);if(!i)return this.children_.getPredecessorKey(e);{let n=i.getPredecessorKey(new eY(e,t));return n?n.name:null}}getFirstChildName(e){let t=this.resolveIndex_(e);if(!t)return this.children_.minKey();{let e=t.minKey();return e&&e.name}}getFirstChild(e){let t=this.getFirstChildName(e);return t?new eY(t,this.children_.get(t)):null}getLastChildName(e){let t=this.resolveIndex_(e);if(!t)return this.children_.maxKey();{let e=t.maxKey();return e&&e.name}}getLastChild(e){let t=this.getLastChildName(e);return t?new eY(t,this.children_.get(t)):null}forEachChild(e,t){let n=this.resolveIndex_(e);return n?n.inorderTraversal(e=>t(e.name,e.node)):this.children_.inorderTraversal(t)}getIterator(e){return this.getIteratorFrom(e.minPost(),e)}getIteratorFrom(e,t){let n=this.resolveIndex_(t);if(n)return n.getIteratorFrom(e,e=>e);{let n=this.children_.getIteratorFrom(e.name,eY.Wrap),i=n.peek();for(;null!=i&&0>t.compare(i,e);)n.getNext(),i=n.peek();return n}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(e,t){let n=this.resolveIndex_(t);if(n)return n.getReverseIteratorFrom(e,e=>e);{let n=this.children_.getReverseIteratorFrom(e.name,eY.Wrap),i=n.peek();for(;null!=i&&t.compare(i,e)>0;)n.getNext(),i=n.peek();return n}}compareTo(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===e9?-1:0}withIndex(e){if(e===eB||this.indexMap_.hasIndex(e))return this;{let t=this.indexMap_.addIndex(e,this.children_);return new e6(this.children_,this.priorityNode_,t)}}isIndexed(e){return e===eB||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;if(e.isLeafNode()||!this.getPriority().equals(e.getPriority())||this.children_.count()!==e.children_.count())return!1;{let t=this.getIterator(e1),n=e.getIterator(e1),i=t.getNext(),r=n.getNext();for(;i&&r;){if(i.name!==r.name||!i.node.equals(r.node))return!1;i=t.getNext(),r=n.getNext()}return null===i&&null===r}}resolveIndex_(e){return e===eB?null:this.indexMap_.get(e.toString())}}e6.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;let e9=new class extends e6{constructor(){super(new eQ(eX),e6.EMPTY_NODE,e8.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return e6.EMPTY_NODE}isEmpty(){return!1}};function e7(e,t=null){if(null===e)return e6.EMPTY_NODE;if("object"==typeof e&&".priority"in e&&(t=e[".priority"]),(0,y.hu)(null===t||"string"==typeof t||"number"==typeof t||"object"==typeof t&&".sv"in t,"Invalid priority type found: "+typeof t),"object"==typeof e&&".value"in e&&null!==e[".value"]&&(e=e[".value"]),"object"!=typeof e||".sv"in e){let n=e;return new e0(n,e7(t))}if(e instanceof Array){let n=e6.EMPTY_NODE;return Q(e,(t,i)=>{if((0,y.r3)(e,t)&&"."!==t.substring(0,1)){let e=e7(i);(e.isLeafNode()||!e.isEmpty())&&(n=n.updateImmediateChild(t,e))}}),n.updatePriority(e7(t))}{let n=[],i=!1,r=e;if(Q(r,(e,t)=>{if("."!==e.substring(0,1)){let r=e7(t);r.isEmpty()||(i=i||!r.getPriority().isEmpty(),n.push(new eY(e,r)))}}),0===n.length)return e6.EMPTY_NODE;let s=e4(n,e$,e=>e.name,eX);if(!i)return new e6(s,e7(t),e8.Default);{let e=e4(n,e1.getCompare());return new e6(s,e7(t),new e8({".priority":e},{".priority":e1}))}}}Object.defineProperties(eY,{MIN:{value:new eY(H,e6.EMPTY_NODE)},MAX:{value:new eY(Y,e9)}}),eV.__EMPTY_NODE=e6.EMPTY_NODE,e0.__childrenNodeConstructor=e6,r=e9,l=e9,o=e7;/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class te extends ej{constructor(e){super(),this.indexPath_=e,(0,y.hu)(!eF(e)&&".priority"!==eP(e),"Can't create PathIndex with empty path or .priority key")}extractChild(e){return e.getChild(this.indexPath_)}isDefinedOn(e){return!e.getChild(this.indexPath_).isEmpty()}compare(e,t){let n=this.extractChild(e.node),i=this.extractChild(t.node),r=n.compareTo(i);return 0===r?j(e.name,t.name):r}makePost(e,t){let n=e7(e),i=e6.EMPTY_NODE.updateChild(this.indexPath_,n);return new eY(t,i)}maxPost(){let e=e6.EMPTY_NODE.updateChild(this.indexPath_,e9);return new eY(Y,e)}toString(){return eR(this.indexPath_,0).join("/")}}let tt=new /**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class extends ej{compare(e,t){let n=e.node.compareTo(t.node);return 0===n?j(e.name,t.name):n}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return eY.MIN}maxPost(){return eY.MAX}makePost(e,t){let n=e7(e);return new eY(t,n)}toString(){return".value"}},tn="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",ti=function(){let e=0,t=[];return function(n){let i;let r=n===e;e=n;let s=Array(8);for(i=7;i>=0;i--)s[i]=tn.charAt(n%64),n=Math.floor(n/64);(0,y.hu)(0===n,"Cannot push at time == 0");let o=s.join("");if(r){for(i=11;i>=0&&63===t[i];i--)t[i]=0;t[i]++}else for(i=0;i<12;i++)t[i]=Math.floor(64*Math.random());for(i=0;i<12;i++)o+=tn.charAt(t[i]);return(0,y.hu)(20===o.length,"nextPushId: Length should be 20."),o}}();/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function tr(e){return{type:"value",snapshotNode:e}}function ts(e,t){return{type:"child_added",snapshotNode:t,childName:e}}function to(e,t){return{type:"child_removed",snapshotNode:t,childName:e}}function tl(e,t,n){return{type:"child_changed",snapshotNode:t,childName:e,oldSnap:n}}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class ta{constructor(e){this.index_=e}updateChild(e,t,n,i,r,s){(0,y.hu)(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");let o=e.getImmediateChild(t);return o.getChild(i).equals(n.getChild(i))&&o.isEmpty()===n.isEmpty()?e:(null!=s&&(n.isEmpty()?e.hasChild(t)?s.trackChildChange(to(t,o)):(0,y.hu)(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):o.isEmpty()?s.trackChildChange(ts(t,n)):s.trackChildChange(tl(t,n,o))),e.isLeafNode()&&n.isEmpty())?e:e.updateImmediateChild(t,n).withIndex(this.index_)}updateFullNode(e,t,n){return null==n||(e.isLeafNode()||e.forEachChild(e1,(e,i)=>{t.hasChild(e)||n.trackChildChange(to(e,i))}),t.isLeafNode()||t.forEachChild(e1,(t,i)=>{if(e.hasChild(t)){let r=e.getImmediateChild(t);r.equals(i)||n.trackChildChange(tl(t,i,r))}else n.trackChildChange(ts(t,i))})),t.withIndex(this.index_)}updatePriority(e,t){return e.isEmpty()?e6.EMPTY_NODE:e.updatePriority(t)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class th{constructor(e){this.indexedFilter_=new ta(e.getIndex()),this.index_=e.getIndex(),this.startPost_=th.getStartPost_(e),this.endPost_=th.getEndPost_(e)}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){return 0>=this.index_.compare(this.getStartPost(),e)&&0>=this.index_.compare(e,this.getEndPost())}updateChild(e,t,n,i,r,s){return this.matches(new eY(t,n))||(n=e6.EMPTY_NODE),this.indexedFilter_.updateChild(e,t,n,i,r,s)}updateFullNode(e,t,n){t.isLeafNode()&&(t=e6.EMPTY_NODE);let i=t.withIndex(this.index_);i=i.updatePriority(e6.EMPTY_NODE);let r=this;return t.forEachChild(e1,(e,t)=>{r.matches(new eY(e,t))||(i=i.updateImmediateChild(e,e6.EMPTY_NODE))}),this.indexedFilter_.updateFullNode(e,i,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){if(!e.hasStart())return e.getIndex().minPost();{let t=e.getIndexStartName();return e.getIndex().makePost(e.getIndexStartValue(),t)}}static getEndPost_(e){if(!e.hasEnd())return e.getIndex().maxPost();{let t=e.getIndexEndName();return e.getIndex().makePost(e.getIndexEndValue(),t)}}}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class tu{constructor(e){this.rangedFilter_=new th(e),this.index_=e.getIndex(),this.limit_=e.getLimit(),this.reverse_=!e.isViewFromLeft()}updateChild(e,t,n,i,r,s){return(this.rangedFilter_.matches(new eY(t,n))||(n=e6.EMPTY_NODE),e.getImmediateChild(t).equals(n))?e:e.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(e,t,n,i,r,s):this.fullLimitUpdateChild_(e,t,n,r,s)}updateFullNode(e,t,n){let i;if(t.isLeafNode()||t.isEmpty())i=e6.EMPTY_NODE.withIndex(this.index_);else if(2*this.limit_<t.numChildren()&&t.isIndexed(this.index_)){let e;i=e6.EMPTY_NODE.withIndex(this.index_),e=this.reverse_?t.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):t.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_);let n=0;for(;e.hasNext()&&n<this.limit_;){let t=e.getNext();if(this.reverse_?0>=this.index_.compare(this.rangedFilter_.getStartPost(),t):0>=this.index_.compare(t,this.rangedFilter_.getEndPost()))i=i.updateImmediateChild(t.name,t.node),n++;else break}}else{let e,n,r,s;if(i=(i=t.withIndex(this.index_)).updatePriority(e6.EMPTY_NODE),this.reverse_){s=i.getReverseIterator(this.index_),e=this.rangedFilter_.getEndPost(),n=this.rangedFilter_.getStartPost();let t=this.index_.getCompare();r=(e,n)=>t(n,e)}else s=i.getIterator(this.index_),e=this.rangedFilter_.getStartPost(),n=this.rangedFilter_.getEndPost(),r=this.index_.getCompare();let o=0,l=!1;for(;s.hasNext();){let t=s.getNext();!l&&0>=r(e,t)&&(l=!0);let a=l&&o<this.limit_&&0>=r(t,n);a?o++:i=i.updateImmediateChild(t.name,e6.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(e,i,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}fullLimitUpdateChild_(e,t,n,i,r){let s;if(this.reverse_){let e=this.index_.getCompare();s=(t,n)=>e(n,t)}else s=this.index_.getCompare();(0,y.hu)(e.numChildren()===this.limit_,"");let o=new eY(t,n),l=this.reverse_?e.getFirstChild(this.index_):e.getLastChild(this.index_),a=this.rangedFilter_.matches(o);if(e.hasChild(t)){let h=e.getImmediateChild(t),u=i.getChildAfterChild(this.index_,l,this.reverse_);for(;null!=u&&(u.name===t||e.hasChild(u.name));)u=i.getChildAfterChild(this.index_,u,this.reverse_);let c=null==u?1:s(u,o),d=a&&!n.isEmpty()&&c>=0;if(d)return null!=r&&r.trackChildChange(tl(t,n,h)),e.updateImmediateChild(t,n);{null!=r&&r.trackChildChange(to(t,h));let n=e.updateImmediateChild(t,e6.EMPTY_NODE),i=null!=u&&this.rangedFilter_.matches(u);return i?(null!=r&&r.trackChildChange(ts(u.name,u.node)),n.updateImmediateChild(u.name,u.node)):n}}return n.isEmpty()?e:a&&s(l,o)>=0?(null!=r&&(r.trackChildChange(to(l.name,l.node)),r.trackChildChange(ts(t,n))),e.updateImmediateChild(t,n).updateImmediateChild(l.name,e6.EMPTY_NODE)):e}}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class tc{constructor(){this.limitSet_=!1,this.startSet_=!1,this.startNameSet_=!1,this.startAfterSet_=!1,this.endSet_=!1,this.endNameSet_=!1,this.endBeforeSet_=!1,this.limit_=0,this.viewFrom_="",this.indexStartValue_=null,this.indexStartName_="",this.indexEndValue_=null,this.indexEndName_="",this.index_=e1}hasStart(){return this.startSet_}hasStartAfter(){return this.startAfterSet_}hasEndBefore(){return this.endBeforeSet_}isViewFromLeft(){return""===this.viewFrom_?this.startSet_:"l"===this.viewFrom_}getIndexStartValue(){return(0,y.hu)(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return((0,y.hu)(this.startSet_,"Only valid if start has been set"),this.startNameSet_)?this.indexStartName_:H}hasEnd(){return this.endSet_}getIndexEndValue(){return(0,y.hu)(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return((0,y.hu)(this.endSet_,"Only valid if end has been set"),this.endNameSet_)?this.indexEndName_:Y}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&""!==this.viewFrom_}getLimit(){return(0,y.hu)(this.limitSet_,"Only valid if limit has been set"),this.limit_}getIndex(){return this.index_}loadsAllData(){return!(this.startSet_||this.endSet_||this.limitSet_)}isDefault(){return this.loadsAllData()&&this.index_===e1}copy(){let e=new tc;return e.limitSet_=this.limitSet_,e.limit_=this.limit_,e.startSet_=this.startSet_,e.indexStartValue_=this.indexStartValue_,e.startNameSet_=this.startNameSet_,e.indexStartName_=this.indexStartName_,e.endSet_=this.endSet_,e.indexEndValue_=this.indexEndValue_,e.endNameSet_=this.endNameSet_,e.indexEndName_=this.indexEndName_,e.index_=this.index_,e.viewFrom_=this.viewFrom_,e}}function td(e){let t;let n={};return e.isDefault()||(e.index_===e1?t="$priority":e.index_===tt?t="$value":e.index_===eB?t="$key":((0,y.hu)(e.index_ instanceof te,"Unrecognized index type!"),t=e.index_.toString()),n.orderBy=(0,y.Pz)(t),e.startSet_&&(n.startAt=(0,y.Pz)(e.indexStartValue_),e.startNameSet_&&(n.startAt+=","+(0,y.Pz)(e.indexStartName_))),e.endSet_&&(n.endAt=(0,y.Pz)(e.indexEndValue_),e.endNameSet_&&(n.endAt+=","+(0,y.Pz)(e.indexEndName_))),e.limitSet_&&(e.isViewFromLeft()?n.limitToFirst=e.limit_:n.limitToLast=e.limit_)),n}function t_(e){let t={};if(e.startSet_&&(t.sp=e.indexStartValue_,e.startNameSet_&&(t.sn=e.indexStartName_)),e.endSet_&&(t.ep=e.indexEndValue_,e.endNameSet_&&(t.en=e.indexEndName_)),e.limitSet_){t.l=e.limit_;let n=e.viewFrom_;""===n&&(n=e.isViewFromLeft()?"l":"r"),t.vf=n}return e.index_!==e1&&(t.i=e.index_.toString()),t}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class tp extends eT{constructor(e,t,n,i){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=n,this.appCheckTokenProvider_=i,this.log_=q("p:rest:"),this.listens_={}}reportStats(e){throw Error("Method not implemented.")}static getListenId_(e,t){return void 0!==t?"tag$"+t:((0,y.hu)(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}listen(e,t,n,i){let r=e._path.toString();this.log_("Listen called for "+r+" "+e._queryIdentifier);let s=tp.getListenId_(e,n),o={};this.listens_[s]=o;let l=td(e._queryParams);this.restRequest_(r+".json",l,(e,t)=>{let l=t;404===e&&(l=null,e=null),null===e&&this.onDataUpdate_(r,l,!1,n),(0,y.DV)(this.listens_,s)===o&&i(e?401===e?"permission_denied":"rest_error:"+e:"ok",null)})}unlisten(e,t){let n=tp.getListenId_(e,t);delete this.listens_[n]}get(e){let t=td(e._queryParams),n=e._path.toString(),i=new y.BH;return this.restRequest_(n+".json",t,(e,t)=>{let r=t;404===e&&(r=null,e=null),null===e?(this.onDataUpdate_(n,r,!1,null),i.resolve(r)):i.reject(Error(r))}),i.promise}refreshAuthToken(e){}restRequest_(e,t={},n){return t.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then(([i,r])=>{i&&i.accessToken&&(t.auth=i.accessToken),r&&r.token&&(t.ac=r.token);let s=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+e+"?ns="+this.repoInfo_.namespace+(0,y.xO)(t);this.log_("Sending REST request for "+s);let o=new XMLHttpRequest;o.onreadystatechange=()=>{if(n&&4===o.readyState){this.log_("REST Response for "+s+" received. status:",o.status,"response:",o.responseText);let e=null;if(o.status>=200&&o.status<300){try{e=(0,y.cI)(o.responseText)}catch(e){A("Failed to parse JSON response for "+s+": "+o.responseText)}n(null,e)}else 401!==o.status&&404!==o.status&&A("Got unsuccessful REST response for "+s+" Status: "+o.status),n(o.status);n=null}},o.open("GET",s,!0),o.send()})}}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class tf{constructor(){this.rootNode_=e6.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function tg(){return{value:null,children:new Map}}function tm(e,t,n){null!==e.value?n(t,e.value):function(e,t){e.children.forEach((e,n)=>{t(n,e)})}(e,(e,i)=>{let r=new eb(t.toString()+"/"+e);tm(i,r,n)})}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class ty{constructor(e){this.collection_=e,this.last_=null}get(){let e=this.collection_.get(),t=Object.assign({},e);return this.last_&&Q(this.last_,(e,n)=>{t[e]=t[e]-n}),this.last_=e,t}}class tv{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new ty(e),et(this.reportStats_.bind(this),Math.floor(1e4+2e4*Math.random()))}reportStats_(){let e=this.statsListener_.get(),t={},n=!1;Q(e,(e,i)=>{i>0&&(0,y.r3)(this.statsToReport_,e)&&(t[e]=i,n=!0)}),n&&this.server_.reportStats(t),et(this.reportStats_.bind(this),Math.floor(2*Math.random()*3e5))}}function tC(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function tw(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function tT(e){return{fromUser:!1,fromServer:!0,queryId:e,tagged:!0}}(p=f||(f={}))[p.OVERWRITE=0]="OVERWRITE",p[p.MERGE=1]="MERGE",p[p.ACK_USER_WRITE=2]="ACK_USER_WRITE",p[p.LISTEN_COMPLETE=3]="LISTEN_COMPLETE";/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class tI{constructor(e,t,n){this.path=e,this.affectedTree=t,this.revert=n,this.type=f.ACK_USER_WRITE,this.source=tC()}operationForChild(e){if(!eF(this.path))return(0,y.hu)(eP(this.path)===e,"operationForChild called for unrelated child."),new tI(eS(this.path),this.affectedTree,this.revert);if(null!=this.affectedTree.value)return(0,y.hu)(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;{let t=this.affectedTree.subtree(new eb(e));return new tI(eE(),t,this.revert)}}}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class tk{constructor(e,t){this.source=e,this.path=t,this.type=f.LISTEN_COMPLETE}operationForChild(e){return eF(this.path)?new tk(this.source,eE()):new tk(this.source,eS(this.path))}}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class tb{constructor(e,t,n){this.source=e,this.path=t,this.snap=n,this.type=f.OVERWRITE}operationForChild(e){return eF(this.path)?new tb(this.source,eE(),this.snap.getImmediateChild(e)):new tb(this.source,eS(this.path),this.snap)}}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class tE{constructor(e,t,n){this.source=e,this.path=t,this.children=n,this.type=f.MERGE}operationForChild(e){if(!eF(this.path))return(0,y.hu)(eP(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new tE(this.source,eS(this.path),this.children);{let t=this.children.subtree(new eb(e));return t.isEmpty()?null:t.value?new tb(this.source,eE(),t.value):new tE(this.source,eE(),t)}}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class tP{constructor(e,t,n){this.node_=e,this.fullyInitialized_=t,this.filtered_=n}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(eF(e))return this.isFullyInitialized()&&!this.filtered_;let t=eP(e);return this.isCompleteForChild(t)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class tN{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function tS(e,t,n,i,r,s){let o=i.filter(e=>e.type===n);o.sort((t,n)=>(function(e,t,n){if(null==t.childName||null==n.childName)throw(0,y.g5)("Should only compare child_ events.");let i=new eY(t.childName,t.snapshotNode),r=new eY(n.childName,n.snapshotNode);return e.index_.compare(i,r)})(e,t,n)),o.forEach(n=>{var i;let o=("value"===(i=n).type||"child_removed"===i.type||(i.prevName=s.getPredecessorChildName(i.childName,i.snapshotNode,e.index_)),i);r.forEach(i=>{i.respondsTo(n.type)&&t.push(i.createEvent(o,e.query_))})})}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function tx(e,t){return{eventCache:e,serverCache:t}}function tR(e,t,n,i){return tx(new tP(t,n,i),e.serverCache)}function tD(e,t,n,i){return tx(e.eventCache,new tP(t,n,i))}function tM(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function tF(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}let tq=()=>(u||(u=new eQ(V)),u);class tL{constructor(e,t=tq()){this.value=e,this.children=t}static fromObject(e){let t=new tL(null);return Q(e,(e,n)=>{t=t.set(new eb(e),n)}),t}isEmpty(){return null===this.value&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){if(null!=this.value&&t(this.value))return{path:eE(),value:this.value};if(eF(e))return null;{let n=eP(e),i=this.children.get(n);if(null===i)return null;{let r=i.findRootMostMatchingPathAndValue(eS(e),t);if(null==r)return null;{let e=eM(new eb(n),r.path);return{path:e,value:r.value}}}}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,()=>!0)}subtree(e){if(eF(e))return this;{let t=eP(e),n=this.children.get(t);return null!==n?n.subtree(eS(e)):new tL(null)}}set(e,t){if(eF(e))return new tL(t,this.children);{let n=eP(e),i=this.children.get(n)||new tL(null),r=i.set(eS(e),t),s=this.children.insert(n,r);return new tL(this.value,s)}}remove(e){if(eF(e))return this.children.isEmpty()?new tL(null):new tL(null,this.children);{let t=eP(e),n=this.children.get(t);if(!n)return this;{let i;let r=n.remove(eS(e));return(i=r.isEmpty()?this.children.remove(t):this.children.insert(t,r),null===this.value&&i.isEmpty())?new tL(null):new tL(this.value,i)}}}get(e){if(eF(e))return this.value;{let t=eP(e),n=this.children.get(t);return n?n.get(eS(e)):null}}setTree(e,t){if(eF(e))return t;{let n;let i=eP(e),r=this.children.get(i)||new tL(null),s=r.setTree(eS(e),t);return n=s.isEmpty()?this.children.remove(i):this.children.insert(i,s),new tL(this.value,n)}}fold(e){return this.fold_(eE(),e)}fold_(e,t){let n={};return this.children.inorderTraversal((i,r)=>{n[i]=r.fold_(eM(e,i),t)}),t(e,this.value,n)}findOnPath(e,t){return this.findOnPath_(e,eE(),t)}findOnPath_(e,t,n){let i=!!this.value&&n(t,this.value);if(i)return i;if(eF(e))return null;{let i=eP(e),r=this.children.get(i);return r?r.findOnPath_(eS(e),eM(t,i),n):null}}foreachOnPath(e,t){return this.foreachOnPath_(e,eE(),t)}foreachOnPath_(e,t,n){if(eF(e))return this;{this.value&&n(t,this.value);let i=eP(e),r=this.children.get(i);return r?r.foreachOnPath_(eS(e),eM(t,i),n):new tL(null)}}foreach(e){this.foreach_(eE(),e)}foreach_(e,t){this.children.inorderTraversal((n,i)=>{i.foreach_(eM(e,n),t)}),this.value&&t(e,this.value)}foreachChild(e){this.children.inorderTraversal((t,n)=>{n.value&&e(t,n.value)})}}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class tO{constructor(e){this.writeTree_=e}static empty(){return new tO(new tL(null))}}function tA(e,t,n){if(eF(t))return new tO(new tL(n));{let i=e.writeTree_.findRootMostValueAndPath(t);if(null!=i){let r=i.path,s=i.value,o=eq(r,t);return s=s.updateChild(o,n),new tO(e.writeTree_.set(r,s))}{let i=new tL(n),r=e.writeTree_.setTree(t,i);return new tO(r)}}}function tW(e,t,n){let i=e;return Q(n,(e,n)=>{i=tA(i,eM(t,e),n)}),i}function tU(e,t){if(eF(t))return tO.empty();{let n=e.writeTree_.setTree(t,new tL(null));return new tO(n)}}function tz(e,t){return null!=tH(e,t)}function tH(e,t){let n=e.writeTree_.findRootMostValueAndPath(t);return null!=n?e.writeTree_.get(n.path).getChild(eq(n.path,t)):null}function tY(e){let t=[],n=e.writeTree_.value;return null!=n?n.isLeafNode()||n.forEachChild(e1,(e,n)=>{t.push(new eY(e,n))}):e.writeTree_.children.inorderTraversal((e,n)=>{null!=n.value&&t.push(new eY(e,n.value))}),t}function tj(e,t){if(eF(t))return e;{let n=tH(e,t);return new tO(null!=n?new tL(n):e.writeTree_.subtree(t))}}function tV(e){return e.writeTree_.isEmpty()}function tB(e,t){return function e(t,n,i){if(null!=n.value)return i.updateChild(t,n.value);{let r=null;return n.children.inorderTraversal((n,s)=>{".priority"===n?((0,y.hu)(null!==s.value,"Priority writes must always be leaf nodes"),r=s.value):i=e(eM(t,n),s,i)}),i.getChild(t).isEmpty()||null===r||(i=i.updateChild(eM(t,".priority"),r)),i}}(eE(),e.writeTree_,t)}function tK(e){return e.visible}function tG(e,t,n){let i=tO.empty();for(let r=0;r<e.length;++r){let s=e[r];if(t(s)){let e;let t=s.path;if(s.snap)eO(n,t)?i=tA(i,e=eq(n,t),s.snap):eO(t,n)&&(e=eq(t,n),i=tA(i,eE(),s.snap.getChild(e)));else if(s.children){if(eO(n,t))i=tW(i,e=eq(n,t),s.children);else if(eO(t,n)){if(eF(e=eq(t,n)))i=tW(i,eE(),s.children);else{let t=(0,y.DV)(s.children,eP(e));if(t){let n=t.getChild(eS(e));i=tA(i,eE(),n)}}}}else throw(0,y.g5)("WriteRecord should have .snap or .children")}}return i}function tQ(e,t,n,i,r){if(i||r){let s=tj(e.visibleWrites,t);if(!r&&tV(s))return n;if(!r&&null==n&&!tz(s,eE()))return null;{let s=tG(e.allWrites,function(e){return(e.visible||r)&&(!i||!~i.indexOf(e.writeId))&&(eO(e.path,t)||eO(t,e.path))},t),o=n||e6.EMPTY_NODE;return tB(s,o)}}{let i=tH(e.visibleWrites,t);if(null!=i)return i;{let i=tj(e.visibleWrites,t);if(tV(i))return n;if(null==n&&!tz(i,eE()))return null;{let e=n||e6.EMPTY_NODE;return tB(i,e)}}}}function t$(e,t,n,i){return tQ(e.writeTree,e.treePath,t,n,i)}function tX(e,t){return function(e,t,n){let i=e6.EMPTY_NODE,r=tH(e.visibleWrites,t);if(r)return r.isLeafNode()||r.forEachChild(e1,(e,t)=>{i=i.updateImmediateChild(e,t)}),i;if(n){let r=tj(e.visibleWrites,t);return n.forEachChild(e1,(e,t)=>{let n=tB(tj(r,new eb(e)),t);i=i.updateImmediateChild(e,n)}),tY(r).forEach(e=>{i=i.updateImmediateChild(e.name,e.node)}),i}{let n=tj(e.visibleWrites,t);return tY(n).forEach(e=>{i=i.updateImmediateChild(e.name,e.node)}),i}}(e.writeTree,e.treePath,t)}function tJ(e,t,n,i){return function(e,t,n,i,r){(0,y.hu)(i||r,"Either existingEventSnap or existingServerSnap must exist");let s=eM(t,n);if(tz(e.visibleWrites,s))return null;{let t=tj(e.visibleWrites,s);return tV(t)?r.getChild(n):tB(t,r.getChild(n))}}(e.writeTree,e.treePath,t,n,i)}function tZ(e,t){var n,i;return n=e.writeTree,i=eM(e.treePath,t),tH(n.visibleWrites,i)}function t0(e,t,n){return function(e,t,n,i){let r=eM(t,n),s=tH(e.visibleWrites,r);if(null!=s)return s;if(!i.isCompleteForChild(n))return null;{let t=tj(e.visibleWrites,r);return tB(t,i.getNode().getImmediateChild(n))}}(e.writeTree,e.treePath,t,n)}function t1(e,t){return t2(eM(e.treePath,t),e.writeTree)}function t2(e,t){return{treePath:e,writeTree:t}}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class t3{constructor(){this.changeMap=new Map}trackChildChange(e){let t=e.type,n=e.childName;(0,y.hu)("child_added"===t||"child_changed"===t||"child_removed"===t,"Only child changes supported for tracking"),(0,y.hu)(".priority"!==n,"Only non-priority child changes can be tracked.");let i=this.changeMap.get(n);if(i){let r=i.type;if("child_added"===t&&"child_removed"===r)this.changeMap.set(n,tl(n,e.snapshotNode,i.snapshotNode));else if("child_removed"===t&&"child_added"===r)this.changeMap.delete(n);else if("child_removed"===t&&"child_changed"===r)this.changeMap.set(n,to(n,i.oldSnap));else if("child_changed"===t&&"child_added"===r)this.changeMap.set(n,ts(n,e.snapshotNode));else if("child_changed"===t&&"child_changed"===r)this.changeMap.set(n,tl(n,e.snapshotNode,i.oldSnap));else throw(0,y.g5)("Illegal combination of changes: "+e+" occurred after "+i)}else this.changeMap.set(n,e)}getChanges(){return Array.from(this.changeMap.values())}}let t4=new /**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class{getCompleteChild(e){return null}getChildAfterChild(e,t,n){return null}};class t5{constructor(e,t,n=null){this.writes_=e,this.viewCache_=t,this.optCompleteServerCache_=n}getCompleteChild(e){let t=this.viewCache_.eventCache;if(t.isCompleteForChild(e))return t.getNode().getImmediateChild(e);{let t=null!=this.optCompleteServerCache_?new tP(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache;return t0(this.writes_,e,t)}}getChildAfterChild(e,t,n){var i;let r=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:tF(this.viewCache_),s=function(e,t,n,i,r,s,o){let l;let a=tj(e.visibleWrites,t),h=tH(a,eE());if(null!=h)l=h;else{if(null==n)return[];l=tB(a,n)}if((l=l.withIndex(o)).isEmpty()||l.isLeafNode())return[];{let e=[],t=o.getCompare(),n=s?l.getReverseIteratorFrom(i,o):l.getIteratorFrom(i,o),r=n.getNext();for(;r&&e.length<1;)0!==t(r,i)&&e.push(r),r=n.getNext();return e}}((i=this.writes_).writeTree,i.treePath,r,t,0,n,e);return 0===s.length?null:s[0]}}function t8(e,t,n,i,r,s){let o=t.eventCache;if(null!=tZ(i,n))return t;{let l,a;if(eF(n)){if((0,y.hu)(t.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),t.serverCache.isFiltered()){let n=tF(t),r=n instanceof e6?n:e6.EMPTY_NODE,o=tX(i,r);l=e.filter.updateFullNode(t.eventCache.getNode(),o,s)}else{let n=t$(i,tF(t));l=e.filter.updateFullNode(t.eventCache.getNode(),n,s)}}else{let h=eP(n);if(".priority"===h){(0,y.hu)(1===eN(n),"Can't have a priority with additional path components");let r=o.getNode();a=t.serverCache.getNode();let s=tJ(i,n,r,a);l=null!=s?e.filter.updatePriority(r,s):o.getNode()}else{let u;let c=eS(n);if(o.isCompleteForChild(h)){a=t.serverCache.getNode();let e=tJ(i,n,o.getNode(),a);u=null!=e?o.getNode().getImmediateChild(h).updateChild(c,e):o.getNode().getImmediateChild(h)}else u=t0(i,h,t.serverCache);l=null!=u?e.filter.updateChild(o.getNode(),h,u,c,r,s):o.getNode()}}return tR(t,l,o.isFullyInitialized()||eF(n),e.filter.filtersNodes())}}function t6(e,t,n,i,r,s,o,l){let a;let h=t.serverCache,u=o?e.filter:e.filter.getIndexedFilter();if(eF(n))a=u.updateFullNode(h.getNode(),i,null);else if(u.filtersNodes()&&!h.isFiltered()){let e=h.getNode().updateChild(n,i);a=u.updateFullNode(h.getNode(),e,null)}else{let e=eP(n);if(!h.isCompleteForPath(n)&&eN(n)>1)return t;let r=eS(n),s=h.getNode().getImmediateChild(e),o=s.updateChild(r,i);a=".priority"===e?u.updatePriority(h.getNode(),o):u.updateChild(h.getNode(),e,o,r,t4,null)}let c=tD(t,a,h.isFullyInitialized()||eF(n),u.filtersNodes()),d=new t5(r,c,s);return t8(e,c,n,r,d,l)}function t9(e,t,n,i,r,s,o){let l,a;let h=t.eventCache,u=new t5(r,t,s);if(eF(n))a=e.filter.updateFullNode(t.eventCache.getNode(),i,o),l=tR(t,a,!0,e.filter.filtersNodes());else{let r=eP(n);if(".priority"===r)a=e.filter.updatePriority(t.eventCache.getNode(),i),l=tR(t,a,h.isFullyInitialized(),h.isFiltered());else{let s;let a=eS(n),c=h.getNode().getImmediateChild(r);if(eF(a))s=i;else{let e=u.getCompleteChild(r);s=null!=e?".priority"===ex(a)&&e.getChild(eD(a)).isEmpty()?e:e.updateChild(a,i):e6.EMPTY_NODE}if(c.equals(s))l=t;else{let n=e.filter.updateChild(h.getNode(),r,s,a,u,o);l=tR(t,n,h.isFullyInitialized(),e.filter.filtersNodes())}}}return l}function t7(e,t){return e.eventCache.isCompleteForChild(t)}function ne(e,t,n){return n.foreach((e,n)=>{t=t.updateChild(e,n)}),t}function nt(e,t,n,i,r,s,o,l){let a;if(t.serverCache.getNode().isEmpty()&&!t.serverCache.isFullyInitialized())return t;let h=t;a=eF(n)?i:new tL(null).setTree(n,i);let u=t.serverCache.getNode();return a.children.inorderTraversal((n,i)=>{if(u.hasChild(n)){let a=t.serverCache.getNode().getImmediateChild(n),u=ne(e,a,i);h=t6(e,h,new eb(n),u,r,s,o,l)}}),a.children.inorderTraversal((n,i)=>{let a=!t.serverCache.isCompleteForChild(n)&&void 0===i.value;if(!u.hasChild(n)&&!a){let a=t.serverCache.getNode().getImmediateChild(n),u=ne(e,a,i);h=t6(e,h,new eb(n),u,r,s,o,l)}}),h}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class nn{constructor(e,t){this.query_=e,this.eventRegistrations_=[];let n=this.query_._queryParams,i=new ta(n.getIndex()),r=n.loadsAllData()?new ta(n.getIndex()):n.hasLimit()?new tu(n):new th(n);this.processor_={filter:r};let s=t.serverCache,o=t.eventCache,l=i.updateFullNode(e6.EMPTY_NODE,s.getNode(),null),a=r.updateFullNode(e6.EMPTY_NODE,o.getNode(),null),h=new tP(l,s.isFullyInitialized(),i.filtersNodes()),u=new tP(a,o.isFullyInitialized(),r.filtersNodes());this.viewCache_=tx(u,h),this.eventGenerator_=new tN(this.query_)}get query(){return this.query_}}function ni(e){return 0===e.eventRegistrations_.length}function nr(e,t,n){let i=[];if(n){(0,y.hu)(null==t,"A cancel should cancel all event registrations.");let r=e.query._path;e.eventRegistrations_.forEach(e=>{let t=e.createCancelEvent(n,r);t&&i.push(t)})}if(t){let n=[];for(let i=0;i<e.eventRegistrations_.length;++i){let r=e.eventRegistrations_[i];if(r.matches(t)){if(t.hasAnyCallback()){n=n.concat(e.eventRegistrations_.slice(i+1));break}}else n.push(r)}e.eventRegistrations_=n}else e.eventRegistrations_=[];return i}function ns(e,t,n,i){var r,s;t.type===f.MERGE&&null!==t.source.queryId&&((0,y.hu)(tF(e.viewCache_),"We should always have a full cache before handling merges"),(0,y.hu)(tM(e.viewCache_),"Missing event cache, even though we have a server cache"));let o=e.viewCache_,l=function(e,t,n,i,r){let s,o;let l=new t3;if(n.type===f.OVERWRITE)n.source.fromUser?s=t9(e,t,n.path,n.snap,i,r,l):((0,y.hu)(n.source.fromServer,"Unknown source."),o=n.source.tagged||t.serverCache.isFiltered()&&!eF(n.path),s=t6(e,t,n.path,n.snap,i,r,o,l));else if(n.type===f.MERGE){var a,h;let u;n.source.fromUser?(a=n.path,h=n.children,u=t,h.foreach((n,s)=>{let o=eM(a,n);t7(t,eP(o))&&(u=t9(e,u,o,s,i,r,l))}),h.foreach((n,s)=>{let o=eM(a,n);t7(t,eP(o))||(u=t9(e,u,o,s,i,r,l))}),s=u):((0,y.hu)(n.source.fromServer,"Unknown source."),o=n.source.tagged||t.serverCache.isFiltered(),s=nt(e,t,n.path,n.children,i,r,o,l))}else if(n.type===f.ACK_USER_WRITE)s=n.revert?function(e,t,n,i,r,s){let o;if(null!=tZ(i,n))return t;{let l;let a=new t5(i,t,r),h=t.eventCache.getNode();if(eF(n)||".priority"===eP(n)){let n;if(t.serverCache.isFullyInitialized())n=t$(i,tF(t));else{let e=t.serverCache.getNode();(0,y.hu)(e instanceof e6,"serverChildren would be complete if leaf node"),n=tX(i,e)}l=e.filter.updateFullNode(h,n,s)}else{let r=eP(n),u=t0(i,r,t.serverCache);null==u&&t.serverCache.isCompleteForChild(r)&&(u=h.getImmediateChild(r)),(l=null!=u?e.filter.updateChild(h,r,u,eS(n),a,s):t.eventCache.getNode().hasChild(r)?e.filter.updateChild(h,r,e6.EMPTY_NODE,eS(n),a,s):h).isEmpty()&&t.serverCache.isFullyInitialized()&&(o=t$(i,tF(t))).isLeafNode()&&(l=e.filter.updateFullNode(l,o,s))}return o=t.serverCache.isFullyInitialized()||null!=tZ(i,eE()),tR(t,l,o,e.filter.filtersNodes())}}(e,t,n.path,i,r,l):function(e,t,n,i,r,s,o){if(null!=tZ(r,n))return t;let l=t.serverCache.isFiltered(),a=t.serverCache;if(null!=i.value){if(eF(n)&&a.isFullyInitialized()||a.isCompleteForPath(n))return t6(e,t,n,a.getNode().getChild(n),r,s,l,o);if(!eF(n))return t;{let i=new tL(null);return a.getNode().forEachChild(eB,(e,t)=>{i=i.set(new eb(e),t)}),nt(e,t,n,i,r,s,l,o)}}{let h=new tL(null);return i.foreach((e,t)=>{let i=eM(n,e);a.isCompleteForPath(i)&&(h=h.set(e,a.getNode().getChild(i)))}),nt(e,t,n,h,r,s,l,o)}}(e,t,n.path,n.affectedTree,i,r,l);else if(n.type===f.LISTEN_COMPLETE)s=function(e,t,n,i,r){let s=t.serverCache,o=tD(t,s.getNode(),s.isFullyInitialized()||eF(n),s.isFiltered());return t8(e,o,n,i,t4,r)}(e,t,n.path,i,l);else throw(0,y.g5)("Unknown operation type: "+n.type);let u=l.getChanges();return function(e,t,n){let i=t.eventCache;if(i.isFullyInitialized()){let r=i.getNode().isLeafNode()||i.getNode().isEmpty(),s=tM(e);!(n.length>0)&&e.eventCache.isFullyInitialized()&&(!r||i.getNode().equals(s))&&i.getNode().getPriority().equals(s.getPriority())||n.push(tr(tM(t)))}}(t,s,u),{viewCache:s,changes:u}}(e.processor_,o,t,n,i);return r=e.processor_,s=l.viewCache,(0,y.hu)(s.eventCache.getNode().isIndexed(r.filter.getIndex()),"Event snap not indexed"),(0,y.hu)(s.serverCache.getNode().isIndexed(r.filter.getIndex()),"Server snap not indexed"),(0,y.hu)(l.viewCache.serverCache.isFullyInitialized()||!o.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),e.viewCache_=l.viewCache,no(e,l.changes,l.viewCache.eventCache.getNode(),null)}function no(e,t,n,i){let r=i?[i]:e.eventRegistrations_;return function(e,t,n,i){let r=[],s=[];return t.forEach(t=>{if("child_changed"===t.type&&e.index_.indexedValueChanged(t.oldSnap,t.snapshotNode)){var n;s.push((n=t.childName,{type:"child_moved",snapshotNode:t.snapshotNode,childName:n}))}}),tS(e,r,"child_removed",t,i,n),tS(e,r,"child_added",t,i,n),tS(e,r,"child_moved",s,i,n),tS(e,r,"child_changed",t,i,n),tS(e,r,"value",t,i,n),r}(e.eventGenerator_,t,n,r)}class nl{constructor(){this.views=new Map}}function na(e,t,n,i){let r=t.source.queryId;if(null!==r){let s=e.views.get(r);return(0,y.hu)(null!=s,"SyncTree gave us an op for an invalid query."),ns(s,t,n,i)}{let r=[];for(let s of e.views.values())r=r.concat(ns(s,t,n,i));return r}}function nh(e,t,n,i,r){let s=t._queryIdentifier,o=e.views.get(s);if(!o){let e=t$(n,r?i:null),s=!1;e?s=!0:i instanceof e6?(e=tX(n,i),s=!1):(e=e6.EMPTY_NODE,s=!1);let o=tx(new tP(e,s,!1),new tP(i,r,!1));return new nn(t,o)}return o}function nu(e){let t=[];for(let n of e.views.values())n.query._queryParams.loadsAllData()||t.push(n);return t}function nc(e,t){let n=null;for(let i of e.views.values())n=n||function(e,t){let n=tF(e.viewCache_);return n&&(e.query._queryParams.loadsAllData()||!eF(t)&&!n.getImmediateChild(eP(t)).isEmpty())?n.getChild(t):null}(i,t);return n}function nd(e,t){let n=t._queryParams;if(n.loadsAllData())return np(e);{let n=t._queryIdentifier;return e.views.get(n)}}function n_(e){return null!=np(e)}function np(e){for(let t of e.views.values())if(t.query._queryParams.loadsAllData())return t;return null}let nf=1;class ng{constructor(e){this.listenProvider_=e,this.syncPointTree_=new tL(null),this.pendingWriteTree_={visibleWrites:tO.empty(),allWrites:[],lastWriteId:-1},this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function nm(e,t,n,i,r){var s,o;return(s=e.pendingWriteTree_,o=r,(0,y.hu)(i>s.lastWriteId,"Stacking an older write on top of newer ones"),void 0===o&&(o=!0),s.allWrites.push({path:t,snap:n,writeId:i,visible:o}),o&&(s.visibleWrites=tA(s.visibleWrites,t,n)),s.lastWriteId=i,r)?nI(e,new tb(tC(),t,n)):[]}function ny(e,t,n=!1){let i=function(e,t){for(let n=0;n<e.allWrites.length;n++){let i=e.allWrites[n];if(i.writeId===t)return i}return null}(e.pendingWriteTree_,t),r=function(e,t){let n=e.allWrites.findIndex(e=>e.writeId===t);(0,y.hu)(n>=0,"removeWrite called with nonexistent writeId.");let i=e.allWrites[n];e.allWrites.splice(n,1);let r=i.visible,s=!1,o=e.allWrites.length-1;for(;r&&o>=0;){let t=e.allWrites[o];t.visible&&(o>=n&&function(e,t){if(e.snap)return eO(e.path,t);for(let n in e.children)if(e.children.hasOwnProperty(n)&&eO(eM(e.path,n),t))return!0;return!1}(t,i.path)?r=!1:eO(i.path,t.path)&&(s=!0)),o--}if(!r)return!1;if(s){var l;return(l=e).visibleWrites=tG(l.allWrites,tK,eE()),l.allWrites.length>0?l.lastWriteId=l.allWrites[l.allWrites.length-1].writeId:l.lastWriteId=-1,!0}if(i.snap)e.visibleWrites=tU(e.visibleWrites,i.path);else{let t=i.children;Q(t,t=>{e.visibleWrites=tU(e.visibleWrites,eM(i.path,t))})}return!0}(e.pendingWriteTree_,t);if(!r)return[];{let t=new tL(null);return null!=i.snap?t=t.set(eE(),!0):Q(i.children,e=>{t=t.set(new eb(e),!0)}),nI(e,new tI(i.path,t,n))}}function nv(e,t,n){return nI(e,new tb(tw(),t,n))}function nC(e,t,n,i){let r=t._path,s=e.syncPointTree_.get(r),o=[];if(s&&("default"===t._queryIdentifier||null!=nd(s,t))){let l=function(e,t,n,i){let r=t._queryIdentifier,s=[],o=[],l=n_(e);if("default"===r)for(let[t,r]of e.views.entries())o=o.concat(nr(r,n,i)),ni(r)&&(e.views.delete(t),r.query._queryParams.loadsAllData()||s.push(r.query));else{let t=e.views.get(r);t&&(o=o.concat(nr(t,n,i)),ni(t)&&(e.views.delete(r),t.query._queryParams.loadsAllData()||s.push(t.query)))}return l&&!n_(e)&&s.push(new((0,y.hu)(c,"Reference.ts has not been loaded"),c)(t._repo,t._path)),{removed:s,events:o}}(s,t,n,i);0===s.views.size&&(e.syncPointTree_=e.syncPointTree_.remove(r));let a=l.removed;o=l.events;let h=-1!==a.findIndex(e=>e._queryParams.loadsAllData()),u=e.syncPointTree_.findOnPath(r,(e,t)=>n_(t));if(h&&!u){let t=e.syncPointTree_.subtree(r);if(!t.isEmpty()){let n=t.fold((e,t,n)=>{if(t&&n_(t)){let e=np(t);return[e]}{let e=[];return t&&(e=nu(t)),Q(n,(t,n)=>{e=e.concat(n)}),e}});for(let t=0;t<n.length;++t){let i=n[t],r=i.query,s=nk(e,i);e.listenProvider_.startListening(nx(r),nb(e,r),s.hashFn,s.onComplete)}}}u||!(a.length>0)||i||(h?e.listenProvider_.stopListening(nx(t),null):a.forEach(t=>{let n=e.queryToTagMap.get(nE(t));e.listenProvider_.stopListening(nx(t),n)})),function(e,t){for(let n=0;n<t.length;++n){let i=t[n];if(!i._queryParams.loadsAllData()){let t=nE(i),n=e.queryToTagMap.get(t);e.queryToTagMap.delete(t),e.tagToQueryMap.delete(n)}}}(e,a)}return o}function nw(e,t,n){var i;let r;let s=t._path,o=null,l=!1;e.syncPointTree_.foreachOnPath(s,(e,t)=>{let n=eq(e,s);o=o||nc(t,n),l=l||n_(t)});let a=e.syncPointTree_.get(s);if(a?(l=l||n_(a),o=o||nc(a,eE())):(a=new nl,e.syncPointTree_=e.syncPointTree_.set(s,a)),null!=o)r=!0;else{r=!1,o=e6.EMPTY_NODE;let t=e.syncPointTree_.subtree(s);t.foreachChild((e,t)=>{let n=nc(t,eE());n&&(o=o.updateImmediateChild(e,n))})}let h=null!=nd(a,t);if(!h&&!t._queryParams.loadsAllData()){let n=nE(t);(0,y.hu)(!e.queryToTagMap.has(n),"View does not exist, but we have a tag");let i=nf++;e.queryToTagMap.set(n,i),e.tagToQueryMap.set(i,n)}let u=(i=e.pendingWriteTree_,t2(s,i)),c=function(e,t,n,i,r,s){let o=nh(e,t,i,r,s);return e.views.has(t._queryIdentifier)||e.views.set(t._queryIdentifier,o),!function(e,t){e.eventRegistrations_.push(t)}(o,n),function(e,t){let n=e.viewCache_.eventCache,i=[];if(!n.getNode().isLeafNode()){let e=n.getNode();e.forEachChild(e1,(e,t)=>{i.push(ts(e,t))})}return n.isFullyInitialized()&&i.push(tr(n.getNode())),no(e,i,n.getNode(),t)}(o,n)}(a,t,n,u,o,r);if(!h&&!l){let n=nd(a,t);c=c.concat(function(e,t,n){let i=t._path,r=nb(e,t),s=nk(e,n),o=e.listenProvider_.startListening(nx(t),r,s.hashFn,s.onComplete),l=e.syncPointTree_.subtree(i);if(r)(0,y.hu)(!n_(l.value),"If we're adding a query, it shouldn't be shadowed");else{let t=l.fold((e,t,n)=>{if(!eF(e)&&t&&n_(t))return[np(t).query];{let e=[];return t&&(e=e.concat(nu(t).map(e=>e.query))),Q(n,(t,n)=>{e=e.concat(n)}),e}});for(let n=0;n<t.length;++n){let i=t[n];e.listenProvider_.stopListening(nx(i),nb(e,i))}}return o}(e,t,n))}return c}function nT(e,t,n){let i=e.pendingWriteTree_,r=e.syncPointTree_.findOnPath(t,(e,n)=>{let i=eq(e,t),r=nc(n,i);if(r)return r});return tQ(i,t,r,n,!0)}function nI(e,t){var n;return function e(t,n,i,r){if(eF(t.path))return function e(t,n,i,r){let s=n.get(eE());null==i&&null!=s&&(i=nc(s,eE()));let o=[];return n.children.inorderTraversal((n,s)=>{let l=i?i.getImmediateChild(n):null,a=t1(r,n),h=t.operationForChild(n);h&&(o=o.concat(e(h,s,l,a)))}),s&&(o=o.concat(na(s,t,r,i))),o}(t,n,i,r);{let s=n.get(eE());null==i&&null!=s&&(i=nc(s,eE()));let o=[],l=eP(t.path),a=t.operationForChild(l),h=n.children.get(l);if(h&&a){let t=i?i.getImmediateChild(l):null,n=t1(r,l);o=o.concat(e(a,h,t,n))}return s&&(o=o.concat(na(s,t,r,i))),o}}(t,e.syncPointTree_,null,(n=e.pendingWriteTree_,t2(eE(),n)))}function nk(e,t){let n=t.query,i=nb(e,n);return{hashFn:()=>{let e=t.viewCache_.serverCache.getNode()||e6.EMPTY_NODE;return e.hash()},onComplete:t=>{if("ok"===t){var r;return i?function(e,t,n){let i=nP(e,n);if(!i)return[];{let n=nN(i),r=n.path,s=n.queryId,o=eq(r,t),l=new tk(tT(s),o);return nS(e,r,l)}}(e,n._path,i):(r=n._path,nI(e,new tk(tw(),r)))}{let i=function(e,t){let n="Unknown Error";"too_big"===e?n="The data requested exceeds the maximum size that can be accessed with a single request.":"permission_denied"===e?n="Client doesn't have permission to access the desired data.":"unavailable"===e&&(n="The service is unavailable");let i=Error(e+" at "+t._path.toString()+": "+n);return i.code=e.toUpperCase(),i}(t,n);return nC(e,n,null,i)}}}}function nb(e,t){let n=nE(t);return e.queryToTagMap.get(n)}function nE(e){return e._path.toString()+"$"+e._queryIdentifier}function nP(e,t){return e.tagToQueryMap.get(t)}function nN(e){let t=e.indexOf("$");return(0,y.hu)(-1!==t&&t<e.length-1,"Bad queryKey."),{queryId:e.substr(t+1),path:new eb(e.substr(0,t))}}function nS(e,t,n){let i=e.syncPointTree_.get(t);(0,y.hu)(i,"Missing sync point for query tag that we're tracking");let r=t2(t,e.pendingWriteTree_);return na(i,n,r,null)}function nx(e){return e._queryParams.loadsAllData()&&!e._queryParams.isDefault()?new((0,y.hu)(d,"Reference.ts has not been loaded"),d)(e._repo,e._path):e}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class nR{constructor(e){this.node_=e}getImmediateChild(e){let t=this.node_.getImmediateChild(e);return new nR(t)}node(){return this.node_}}class nD{constructor(e,t){this.syncTree_=e,this.path_=t}getImmediateChild(e){let t=eM(this.path_,e);return new nD(this.syncTree_,t)}node(){return nT(this.syncTree_,this.path_)}}let nM=function(e,t,n){return e&&"object"==typeof e?((0,y.hu)(".sv"in e,"Unexpected leaf node or priority contents"),"string"==typeof e[".sv"])?nF(e[".sv"],t,n):"object"==typeof e[".sv"]?nq(e[".sv"],t):void(0,y.hu)(!1,"Unexpected server value: "+JSON.stringify(e,null,2)):e},nF=function(e,t,n){if("timestamp"===e)return n.timestamp;(0,y.hu)(!1,"Unexpected server value: "+e)},nq=function(e,t,n){e.hasOwnProperty("increment")||(0,y.hu)(!1,"Unexpected server value: "+JSON.stringify(e,null,2));let i=e.increment;"number"!=typeof i&&(0,y.hu)(!1,"Unexpected increment value: "+i);let r=t.node();if((0,y.hu)(null!=r,"Expected ChildrenNode.EMPTY_NODE for nulls"),!r.isLeafNode())return i;let s=r.getValue();return"number"!=typeof s?i:s+i},nL=function(e,t,n){return nO(e,new nR(t),n)};function nO(e,t,n){let i;let r=e.getPriority().val(),s=nM(r,t.getImmediateChild(".priority"),n);if(!e.isLeafNode())return i=e,s!==e.getPriority().val()&&(i=i.updatePriority(new e0(s))),e.forEachChild(e1,(e,r)=>{let s=nO(r,t.getImmediateChild(e),n);s!==r&&(i=i.updateImmediateChild(e,s))}),i;{let i=nM(e.getValue(),t,n);return i!==e.getValue()||s!==e.getPriority().val()?new e0(i,e7(s)):e}}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class nA{constructor(e="",t=null,n={children:{},childCount:0}){this.name=e,this.parent=t,this.node=n}}function nW(e,t){let n=t instanceof eb?t:new eb(t),i=e,r=eP(n);for(;null!==r;){let e=(0,y.DV)(i.node.children,r)||{children:{},childCount:0};i=new nA(r,i,e),r=eP(n=eS(n))}return i}function nU(e){return e.node.value}function nz(e,t){e.node.value=t,function e(t){null!==t.parent&&function(t,n,i){let r=void 0===nU(i)&&!nH(i),s=(0,y.r3)(t.node.children,n);r&&s?(delete t.node.children[n],t.node.childCount--,e(t)):r||s||(t.node.children[n]=i.node,t.node.childCount++,e(t))}(t.parent,t.name,t)}(e)}function nH(e){return e.node.childCount>0}function nY(e,t){Q(e.node.children,(n,i)=>{t(new nA(n,e,i))})}function nj(e){return new eb(null===e.parent?e.name:nj(e.parent)+"/"+e.name)}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let nV=/[\[\].#$\/\u0000-\u001F\u007F]/,nB=/[\[\].#$\u0000-\u001F\u007F]/,nK=function(e){return"string"==typeof e&&0!==e.length&&!nV.test(e)},nG=function(e){return"string"==typeof e&&0!==e.length&&!nB.test(e)},nQ=function(e,t,n,i){i&&void 0===t||n$((0,y.gK)(e,"value"),t,n)},n$=function(e,t,n){let i=n instanceof eb?new eA(n,e):n;if(void 0===t)throw Error(e+"contains undefined "+eU(i));if("function"==typeof t)throw Error(e+"contains a function "+eU(i)+" with contents = "+t.toString());if(U(t))throw Error(e+"contains "+t.toString()+" "+eU(i));if("string"==typeof t&&t.length>3495253.3333333335&&(0,y.ug)(t)>10485760)throw Error(e+"contains a string greater than 10485760 utf8 bytes "+eU(i)+" ('"+t.substring(0,50)+"...')");if(t&&"object"==typeof t){let n=!1,r=!1;if(Q(t,(t,s)=>{var o;if(".value"===t)n=!0;else if(".priority"!==t&&".sv"!==t&&(r=!0,!nK(t)))throw Error(e+" contains an invalid key ("+t+") "+eU(i)+'.  Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');(o=i).parts_.length>0&&(o.byteLength_+=1),o.parts_.push(t),o.byteLength_+=(0,y.ug)(t),eW(o),n$(e,s,i),function(e){let t=e.parts_.pop();e.byteLength_-=(0,y.ug)(t),e.parts_.length>0&&(e.byteLength_-=1)}(i)}),n&&r)throw Error(e+' contains ".value" child '+eU(i)+" in addition to actual children.")}},nX=function(e,t,n,i){if((!i||void 0!==n)&&!nG(n))throw Error((0,y.gK)(e,t)+'was an invalid path = "'+n+'". Paths must be non-empty strings and can\'t contain ".", "#", "$", "[", or "]"')},nJ=function(e,t,n,i){n&&(n=n.replace(/^\/*\.info(\/|$)/,"/")),nX(e,t,n,i)},nZ=function(e,t){if(".info"===eP(t))throw Error(e+" failed = Can't modify data under /.info/")},n0=function(e,t){var n;let i=t.path.toString();if("string"!=typeof t.repoInfo.host||0===t.repoInfo.host.length||!nK(t.repoInfo.namespace)&&"localhost"!==t.repoInfo.host.split(":")[0]||0!==i.length&&((n=i)&&(n=n.replace(/^\/*\.info(\/|$)/,"/")),!nG(n)))throw Error((0,y.gK)(e,"url")+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class n1{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function n2(e,t){let n=null;for(let i=0;i<t.length;i++){let r=t[i],s=r.getPath();null===n||eL(s,n.path)||(e.eventLists_.push(n),n=null),null===n&&(n={events:[],path:s}),n.events.push(r)}n&&e.eventLists_.push(n)}function n3(e,t,n){n2(e,n),n5(e,e=>eL(e,t))}function n4(e,t,n){n2(e,n),n5(e,e=>eO(e,t)||eO(t,e))}function n5(e,t){e.recursionDepth_++;let n=!0;for(let i=0;i<e.eventLists_.length;i++){let r=e.eventLists_[i];if(r){let s=r.path;t(s)?(function(e){for(let t=0;t<e.events.length;t++){let n=e.events[t];if(null!==n){e.events[t]=null;let i=n.getEventRunner();R&&F("event: "+n.toString()),Z(i)}}}(e.eventLists_[i]),e.eventLists_[i]=null):n=!1}}n&&(e.eventLists_=[]),e.recursionDepth_--}class n8{constructor(e,t,n,i){this.repoInfo_=e,this.forceRestClient_=t,this.authTokenProvider_=n,this.appCheckProvider_=i,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new n1,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=tg(),this.transactionQueueTree_=new nA,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function n6(e){let t=e.infoData_.getNode(new eb(".info/serverTimeOffset")),n=t.val()||0;return new Date().getTime()+n}function n9(e){var t;return(t=t={timestamp:n6(e)}).timestamp=t.timestamp||new Date().getTime(),t}function n7(e,t,n,i,r){e.dataUpdateCount++;let s=new eb(t);n=e.interceptServerDataCallback_?e.interceptServerDataCallback_(t,n):n;let o=[];if(r){if(i){let t=(0,y.UI)(n,e=>e7(e));o=function(e,t,n,i){let r=nP(e,i);if(!r)return[];{let i=nN(r),s=i.path,o=i.queryId,l=eq(s,t),a=tL.fromObject(n),h=new tE(tT(o),l,a);return nS(e,s,h)}}(e.serverSyncTree_,s,t,r)}else{let t=e7(n);o=function(e,t,n,i){let r=nP(e,i);if(null==r)return[];{let i=nN(r),s=i.path,o=i.queryId,l=eq(s,t),a=new tb(tT(o),l,n);return nS(e,s,a)}}(e.serverSyncTree_,s,t,r)}}else if(i){let t=(0,y.UI)(n,e=>e7(e));o=function(e,t,n){let i=tL.fromObject(n);return nI(e,new tE(tw(),t,i))}(e.serverSyncTree_,s,t)}else{let t=e7(n);o=nv(e.serverSyncTree_,s,t)}let l=s;o.length>0&&(l=il(e,s)),n4(e.eventQueue_,l,o)}function ie(e,t){it(e,"connected",t),!1===t&&function(e){is(e,"onDisconnectEvents");let t=n9(e),n=tg();tm(e.onDisconnect_,eE(),(i,r)=>{var s;let o=(s=e.serverSyncTree_,nO(r,new nD(s,i),t));!function e(t,n,i){if(eF(n))t.value=i,t.children.clear();else if(null!==t.value)t.value=t.value.updateChild(n,i);else{let r=eP(n);t.children.has(r)||t.children.set(r,tg());let s=t.children.get(r);e(s,n=eS(n),i)}}(n,i,o)});let i=[];tm(n,eE(),(t,n)=>{i=i.concat(nv(e.serverSyncTree_,t,n));let r=ic(e,t);il(e,r)}),e.onDisconnect_=tg(),n4(e.eventQueue_,eE(),i)}(e)}function it(e,t,n){let i=new eb("/.info/"+t),r=e7(n);e.infoData_.updateSnapshot(i,r);let s=nv(e.infoSyncTree_,i,r);n4(e.eventQueue_,i,s)}function ii(e){return e.nextWriteId_++}function ir(e,t,n){let i;i=".info"===eP(t._path)?nC(e.infoSyncTree_,t,n):nC(e.serverSyncTree_,t,n),n3(e.eventQueue_,t._path,i)}function is(e,...t){let n="";e.persistentConnection_&&(n=e.persistentConnection_.id+":"),F(n,...t)}function io(e,t,n){return nT(e.serverSyncTree_,t,n)||e6.EMPTY_NODE}function il(e,t){let n=ia(e,t),i=nj(n),r=ih(e,n);return function(e,t,n){if(0===t.length)return;let i=[],r=[],s=t.filter(e=>0===e.status),o=s.map(e=>e.currentWriteId);for(let s=0;s<t.length;s++){let l=t[s],a=eq(n,l.path),h=!1,u;if((0,y.hu)(null!==a,"rerunTransactionsUnderNode_: relativePath should not be null."),4===l.status)h=!0,u=l.abortReason,r=r.concat(ny(e.serverSyncTree_,l.currentWriteId,!0));else if(0===l.status){if(l.retryCount>=25)h=!0,u="maxretry",r=r.concat(ny(e.serverSyncTree_,l.currentWriteId,!0));else{let n=io(e,l.path,o);l.currentInputSnapshot=n;let i=t[s].update(n.val());if(void 0!==i){n$("transaction failed: Data returned ",i,l.path);let t=e7(i),s="object"==typeof i&&null!=i&&(0,y.r3)(i,".priority");s||(t=t.updatePriority(n.getPriority()));let a=l.currentWriteId,h=n9(e),u=nL(t,n,h);l.currentOutputSnapshotRaw=t,l.currentOutputSnapshotResolved=u,l.currentWriteId=ii(e),o.splice(o.indexOf(a),1),r=(r=r.concat(nm(e.serverSyncTree_,l.path,u,l.currentWriteId,l.applyLocally))).concat(ny(e.serverSyncTree_,a,!0))}else h=!0,u="nodata",r=r.concat(ny(e.serverSyncTree_,l.currentWriteId,!0))}}n4(e.eventQueue_,n,r),r=[],h&&(t[s].status=2,setTimeout(t[s].unwatcher,Math.floor(0)),t[s].onComplete&&("nodata"===u?i.push(()=>t[s].onComplete(null,!1,t[s].currentInputSnapshot)):i.push(()=>t[s].onComplete(Error(u),!1,null))))}iu(e,e.transactionQueueTree_);for(let e=0;e<i.length;e++)Z(i[e]);(function e(t,n=t.transactionQueueTree_){if(n||iu(t,n),nU(n)){let i=ih(t,n);(0,y.hu)(i.length>0,"Sending zero length transaction queue");let r=i.every(e=>0===e.status);r&&function(t,n,i){let r=i.map(e=>e.currentWriteId),s=io(t,n,r),o=s,l=s.hash();for(let e=0;e<i.length;e++){let t=i[e];(0,y.hu)(0===t.status,"tryToSendTransactionQueue_: items in queue should all be run."),t.status=1,t.retryCount++;let r=eq(n,t.path);o=o.updateChild(r,t.currentOutputSnapshotRaw)}let a=o.val(!0);t.server_.put(n.toString(),a,r=>{is(t,"transaction put response",{path:n.toString(),status:r});let s=[];if("ok"===r){let r=[];for(let e=0;e<i.length;e++)i[e].status=2,s=s.concat(ny(t.serverSyncTree_,i[e].currentWriteId)),i[e].onComplete&&r.push(()=>i[e].onComplete(null,!0,i[e].currentOutputSnapshotResolved)),i[e].unwatcher();iu(t,nW(t.transactionQueueTree_,n)),e(t,t.transactionQueueTree_),n4(t.eventQueue_,n,s);for(let e=0;e<r.length;e++)Z(r[e])}else{if("datastale"===r)for(let e=0;e<i.length;e++)3===i[e].status?i[e].status=4:i[e].status=0;else{A("transaction at "+n.toString()+" failed: "+r);for(let e=0;e<i.length;e++)i[e].status=4,i[e].abortReason=r}il(t,n)}},l)}(t,nj(n),i)}else nH(n)&&nY(n,n=>{e(t,n)})})(e,e.transactionQueueTree_)}(e,r,i),i}function ia(e,t){let n;let i=e.transactionQueueTree_;for(n=eP(t);null!==n&&void 0===nU(i);)i=nW(i,n),n=eP(t=eS(t));return i}function ih(e,t){let n=[];return function e(t,n,i){let r=nU(n);if(r)for(let e=0;e<r.length;e++)i.push(r[e]);nY(n,n=>{e(t,n,i)})}(e,t,n),n.sort((e,t)=>e.order-t.order),n}function iu(e,t){let n=nU(t);if(n){let e=0;for(let t=0;t<n.length;t++)2!==n[t].status&&(n[e]=n[t],e++);n.length=e,nz(t,n.length>0?n:void 0)}nY(t,t=>{iu(e,t)})}function ic(e,t){let n=nj(ia(e,t)),i=nW(e.transactionQueueTree_,t);return!function(e,t,n){let i=e.parent;for(;null!==i;){if(t(i))return!0;i=i.parent}}(i,t=>{id(e,t)}),id(e,i),!function e(t,n,i,r){i&&!r&&n(t),nY(t,t=>{e(t,n,!0,r)}),i&&r&&n(t)}(i,t=>{id(e,t)}),n}function id(e,t){let n=nU(t);if(n){let i=[],r=[],s=-1;for(let t=0;t<n.length;t++)3===n[t].status||(1===n[t].status?((0,y.hu)(s===t-1,"All SENT items should be at beginning of queue."),s=t,n[t].status=3,n[t].abortReason="set"):((0,y.hu)(0===n[t].status,"Unexpected transaction status in abort"),n[t].unwatcher(),r=r.concat(ny(e.serverSyncTree_,n[t].currentWriteId,!0)),n[t].onComplete&&i.push(n[t].onComplete.bind(null,Error("set"),!1,null))));-1===s?nz(t,void 0):n.length=s+1,n4(e.eventQueue_,nj(t),r);for(let e=0;e<i.length;e++)Z(i[e])}}let i_=function(e,t){let n=ip(e),i=n.namespace;"firebase.com"===n.domain&&O(n.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),i&&"undefined"!==i||"localhost"===n.domain||O("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),n.secure||W();let r="ws"===n.scheme||"wss"===n.scheme;return{repoInfo:new ea(n.host,n.secure,i,t,r,"",i!==n.subdomain),path:new eb(n.pathString)}},ip=function(e){let t="",n="",i="",r="",s="",o=!0,l="https",a=443;if("string"==typeof e){let h=e.indexOf("//");h>=0&&(l=e.substring(0,h-1),e=e.substring(h+2));let u=e.indexOf("/");-1===u&&(u=e.length);let c=e.indexOf("?");-1===c&&(c=e.length),t=e.substring(0,Math.min(u,c)),u<c&&(r=/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function(e){let t="",n=e.split("/");for(let e=0;e<n.length;e++)if(n[e].length>0){let i=n[e];try{i=decodeURIComponent(i.replace(/\+/g," "))}catch(e){}t+="/"+i}return t}(e.substring(u,c)));let d=function(e){let t={};for(let n of("?"===e.charAt(0)&&(e=e.substring(1)),e.split("&"))){if(0===n.length)continue;let i=n.split("=");2===i.length?t[decodeURIComponent(i[0])]=decodeURIComponent(i[1]):A(`Invalid query segment '${n}' in query '${e}'`)}return t}(e.substring(Math.min(e.length,c)));(h=t.indexOf(":"))>=0?(o="https"===l||"wss"===l,a=parseInt(t.substring(h+1),10)):h=t.length;let _=t.slice(0,h);if("localhost"===_.toLowerCase())n="localhost";else if(_.split(".").length<=2)n=_;else{let e=t.indexOf(".");i=t.substring(0,e).toLowerCase(),n=t.substring(e+1),s=i}"ns"in d&&(s=d.ns)}return{host:t,port:a,domain:n,subdomain:i,secure:o,scheme:l,pathString:r,namespace:s}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class ig{constructor(e,t,n,i){this.eventType=e,this.eventRegistration=t,this.snapshot=n,this.prevName=i}getPath(){let e=this.snapshot.ref;return"value"===this.eventType?e._path:e.parent._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+(0,y.Pz)(this.snapshot.exportVal())}}class im{constructor(e,t,n){this.eventRegistration=e,this.error=t,this.path=n}getPath(){return this.path}getEventType(){return"cancel"}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.path.toString()+":cancel"}}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class iy{constructor(e,t){this.snapshotCallback=e,this.cancelCallback=t}onValue(e,t){this.snapshotCallback.call(null,e,t)}onCancel(e){return(0,y.hu)(this.hasCancelCallback,"Raising a cancel event on a listener with no cancel callback"),this.cancelCallback.call(null,e)}get hasCancelCallback(){return!!this.cancelCallback}matches(e){return this.snapshotCallback===e.snapshotCallback||void 0!==this.snapshotCallback.userCallback&&this.snapshotCallback.userCallback===e.snapshotCallback.userCallback&&this.snapshotCallback.context===e.snapshotCallback.context}}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class iv{constructor(e,t,n,i){this._repo=e,this._path=t,this._queryParams=n,this._orderByCalled=i}get key(){return eF(this._path)?null:ex(this._path)}get ref(){return new iC(this._repo,this._path)}get _queryIdentifier(){let e=t_(this._queryParams),t=K(e);return"{}"===t?"default":t}get _queryObject(){return t_(this._queryParams)}isEqual(e){if(!((e=(0,y.m9)(e))instanceof iv))return!1;let t=this._repo===e._repo,n=eL(this._path,e._path),i=this._queryIdentifier===e._queryIdentifier;return t&&n&&i}toJSON(){return this.toString()}toString(){return this._repo.toString()+function(e){let t="";for(let n=e.pieceNum_;n<e.pieces_.length;n++)""!==e.pieces_[n]&&(t+="/"+encodeURIComponent(String(e.pieces_[n])));return t||"/"}(this._path)}}class iC extends iv{constructor(e,t){super(e,t,new tc,!1)}get parent(){let e=eD(this._path);return null===e?null:new iC(this._repo,e)}get root(){let e=this;for(;null!==e.parent;)e=e.parent;return e}}class iw{constructor(e,t,n){this._node=e,this.ref=t,this._index=n}get priority(){return this._node.getPriority().val()}get key(){return this.ref.key}get size(){return this._node.numChildren()}child(e){let t=new eb(e),n=iI(this.ref,e);return new iw(this._node.getChild(t),n,e1)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(e){if(this._node.isLeafNode())return!1;let t=this._node;return!!t.forEachChild(this._index,(t,n)=>e(new iw(n,iI(this.ref,t),e1)))}hasChild(e){let t=new eb(e);return!this._node.getChild(t).isEmpty()}hasChildren(){return!this._node.isLeafNode()&&!this._node.isEmpty()}toJSON(){return this.exportVal()}val(){return this._node.val()}}function iT(e,t){return(e=(0,y.m9)(e))._checkNotDeleted("ref"),void 0!==t?iI(e._root,t):e._root}function iI(e,t){return null===eP((e=(0,y.m9)(e))._path)?nJ("child","path",t,!1):nX("child","path",t,!1),new iC(e._repo,eM(e._path,t))}function ik(e,t){let n;nZ("push",(e=(0,y.m9)(e))._path),nQ("push",t,e._path,!0);let i=n6(e._repo),r=ti(i),s=iI(e,r),o=iI(e,r);return n=null!=t?ib(o,t).then(()=>o):Promise.resolve(o),s.then=n.then.bind(n),s.catch=n.then.bind(n,void 0),s}function ib(e,t){nZ("set",(e=(0,y.m9)(e))._path),nQ("set",t,e._path,!1);let n=new y.BH;return!function(e,t,n,i,r){is(e,"set",{path:t.toString(),value:n,priority:i});let s=n9(e),o=e7(n,i),l=nT(e.serverSyncTree_,t),a=nL(o,l,s),h=ii(e),u=nm(e.serverSyncTree_,t,a,h,!0);n2(e.eventQueue_,u),e.server_.put(t.toString(),o.val(!0),(n,i)=>{let s="ok"===n;s||A("set at "+t+" failed: "+n);let o=ny(e.serverSyncTree_,h,!s);n4(e.eventQueue_,t,o),r&&Z(()=>{if("ok"===n)r(null);else{let e=(n||"error").toUpperCase(),t=e;i&&(t+=": "+i);let s=Error(t);s.code=e,r(s)}})});let c=ic(e,t);il(e,c),n4(e.eventQueue_,c,[])}(e._repo,e._path,t,null,n.wrapCallback(()=>{})),n.promise}function iE(e){return(function(e,t){let n=function(e,t){var n;let i=t._path,r=null;e.syncPointTree_.foreachOnPath(i,(e,t)=>{let n=eq(e,i);r=r||nc(t,n)});let s=e.syncPointTree_.get(i);s?r=r||nc(s,eE()):(s=new nl,e.syncPointTree_=e.syncPointTree_.set(i,s));let o=null!=r,l=o?new tP(r,!0,!1):null,a=(n=e.pendingWriteTree_,t2(t._path,n)),h=nh(s,t,a,o?l.getNode():e6.EMPTY_NODE,o);return tM(h.viewCache_)}(e.serverSyncTree_,t);return null!=n?Promise.resolve(n):e.server_.get(t).then(n=>{let i=e7(n).withIndex(t._queryParams.getIndex()),r=nv(e.serverSyncTree_,t._path,i);return n3(e.eventQueue_,t._path,r),Promise.resolve(i)},n=>(is(e,"get for query "+(0,y.Pz)(t)+" failed: "+n),Promise.reject(Error(n))))})((e=(0,y.m9)(e))._repo,e).then(t=>new iw(t,new iC(e._repo,e._path),e._queryParams.getIndex()))}class iP{constructor(e){this.callbackContext=e}respondsTo(e){return"value"===e}createEvent(e,t){let n=t._queryParams.getIndex();return new ig("value",this,new iw(e.snapshotNode,new iC(t._repo,t._path),n))}getEventRunner(e){return"cancel"===e.getEventType()?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,null)}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new im(this,e,t):null}matches(e){return e instanceof iP&&(!e.callbackContext||!this.callbackContext||e.callbackContext.matches(this.callbackContext))}hasAnyCallback(){return null!==this.callbackContext}}class iN{constructor(e,t){this.eventType=e,this.callbackContext=t}respondsTo(e){let t="children_added"===e?"child_added":e;return t="children_removed"===t?"child_removed":t,this.eventType===t}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new im(this,e,t):null}createEvent(e,t){(0,y.hu)(null!=e.childName,"Child events should have a childName.");let n=iI(new iC(t._repo,t._path),e.childName),i=t._queryParams.getIndex();return new ig(e.type,this,new iw(e.snapshotNode,n,i),e.prevName)}getEventRunner(e){return"cancel"===e.getEventType()?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,e.prevName)}matches(e){return e instanceof iN&&this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext))}hasAnyCallback(){return!!this.callbackContext}}function iS(e,t,n,i){return function(e,t,n,i,r){var s;let o,l;if("object"==typeof i&&(o=void 0,r=i),"function"==typeof i&&(o=i),r&&r.onlyOnce){let t=n,i=(n,i)=>{ir(e._repo,e,h),t(n,i)};i.userCallback=n.userCallback,i.context=n.context,n=i}let a=new iy(n,o||void 0),h="value"===t?new iP(a):new iN(t,a);return s=e._repo,l=".info"===eP(e._path)?nw(s.infoSyncTree_,e,h):nw(s.serverSyncTree_,e,h),n3(s.eventQueue_,e._path,l),()=>ir(e._repo,e,h)}(e,"child_added",t,n,i)}(0,y.hu)(!c,"__referenceConstructor has already been defined"),c=iC,(0,y.hu)(!d,"__referenceConstructor has already been defined"),d=iC;let ix={};class iR{constructor(e,t){this._repoInternal=e,this.app=t,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(function(e,t,n){if(e.stats_=e_(e.repoInfo_),e.forceRestClient_||ee())e.server_=new tp(e.repoInfo_,(t,n,i,r)=>{n7(e,t,n,i,r)},e.authTokenProvider_,e.appCheckProvider_),setTimeout(()=>ie(e,!0),0);else{if(null!=n){if("object"!=typeof n)throw Error("Only objects are supported for option databaseAuthVariableOverride");try{(0,y.Pz)(n)}catch(e){throw Error("Invalid authOverride provided: "+e)}}e.persistentConnection_=new eH(e.repoInfo_,t,(t,n,i,r)=>{n7(e,t,n,i,r)},t=>{ie(e,t)},t=>{Q(t,(t,n)=>{it(e,t,n)})},e.authTokenProvider_,e.appCheckProvider_,n),e.server_=e.persistentConnection_}e.authTokenProvider_.addTokenChangeListener(t=>{e.server_.refreshAuthToken(t)}),e.appCheckProvider_.addTokenChangeListener(t=>{e.server_.refreshAppCheckToken(t.token)}),e.statsReporter_=function(e,t){let n=e.toString();return ed[n]||(ed[n]=t()),ed[n]}(e.repoInfo_,()=>new tv(e.stats_,e.server_)),e.infoData_=new tf,e.infoSyncTree_=new ng({startListening:(t,n,i,r)=>{let s=[],o=e.infoData_.getNode(t._path);return o.isEmpty()||(s=nv(e.infoSyncTree_,t._path,o),setTimeout(()=>{r("ok")},0)),s},stopListening:()=>{}}),it(e,"connected",!1),e.serverSyncTree_=new ng({startListening:(t,n,i,r)=>(e.server_.listen(t,i,n,(n,i)=>{let s=r(n,i);n4(e.eventQueue_,t._path,s)}),[]),stopListening:(t,n)=>{e.server_.unlisten(t,n)}})}(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new iC(this._repo,eE())),this._rootInternal}_delete(){return null!==this._rootInternal&&(function(e,t){let n=ix[t];n&&n[e.key]===e||O(`Database ${t}(${e.repoInfo_}) has already been deleted.`),e.persistentConnection_&&e.persistentConnection_.interrupt("repo_interrupt"),delete n[e.key]}(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){null===this._rootInternal&&O("Cannot call "+e+" on a deleted database.")}}function iD(e=(0,g.Mq)(),t){return(0,g.qX)(e,"database").getImmediate({identifier:t})}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */eH.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)},eH.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)},w=g.Jn,(0,g.Xd)(new m.wA("database",(e,{instanceIdentifier:t})=>{let n=e.getProvider("app").getImmediate(),i=e.getProvider("auth-internal"),r=e.getProvider("app-check-internal");return function(e,t,n,i,r){var s,o,l;let a,h,u,c,d=i||e.options.databaseURL;void 0===d&&(e.options.projectId||O("Can't determine Firebase Database URL. Be sure to include  a Project ID when calling firebase.initializeApp()."),F("Using default host for project ",e.options.projectId),d=`${e.options.projectId}-default-rtdb.firebaseio.com`);let _=i_(d,r),p=_.repoInfo;void 0!==C&&(u=C.env.FIREBASE_DATABASE_EMULATOR_HOST),u?(c=!0,p=(_=i_(d=`http://${u}?ns=${p.namespace}`,r)).repoInfo):c=!_.repoInfo.secure;let f=r&&c?new er(er.OWNER):new ei(e.name,e.options,t);n0("Invalid Firebase Database URL",_),eF(_.path)||O("Database URL must point to the root of a Firebase Database (not including a child path).");let g=(s=p,o=e,l=new en(e.name,n),(a=ix[o.name])||(a={},ix[o.name]=a),(h=a[s.toURLString()])&&O("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call."),h=new n8(s,!1,f,l),a[s.toURLString()]=h,h);return new iR(g,e)}(n,i,r,t)},"PUBLIC").setMultipleInstances(!0)),(0,g.KN)("@firebase/database","0.12.0",void 0)}}]);