1/*! For license information please see a198fdd9-46f1ff4add8fc319cd97.js.LICENSE.txt */ 2"use strict";(self.webpackChunkweb_autoroot=self.webpackChunkweb_autoroot||[]).push([[505],{65805:function(e,t,n){n.d(t,{$1:function(){return ws},$w:function(){return Xr},AU:function(){return ls},C3:function(){return Ls},Cb:function(){return Qs},D8:function(){return Yr},Di:function(){return Ms},EO:function(){return fs},EZ:function(){return kt},FD:function(){return us},GV:function(){return Vs},H5:function(){return Br},HM:function(){return ms},JK:function(){return Is},Jt:function(){return Zr},KR:function(){return Hr},Kd:function(){return Gi},M4:function(){return ss},Mq:function(){return Us},O5:function(){return Ys},P:function(){return As},SF:function(){return c},TF:function(){return Qr},TS:function(){return Bs},U0:function(){return as},VC:function(){return zr},VJ:function(){return Ws},VR:function(){return Ns},Wm:function(){return Os},X1:function(){return os},YL:function(){return Or},Zy:function(){return is},_O:function(){return rs},c4:function(){return zs},eO:function(){return js},hZ:function(){return Gr},iz:function(){return Rs},j2:function(){return Xi},jf:function(){return Vr},kT:function(){return ks},og:function(){return Ss},pk:function(){return vs},qT:function(){return Ks},qs:function(){return Gs},rf:function(){return _s},t2:function(){return jr},wu:function(){return Mr},wx:function(){return hs},yX:function(){return Kr},yo:function(){return Jr},zm:function(){return $r}});var i=n(22999),r=n(94963),s=n(32090),o=n(84734);const a="@firebase/database",l="0.12.8";let h="";function c(e){h=e}class u{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,s.As)(t))}get(e){const t=this.domStorage_.getItem(this.prefixedName_(e));return null==t?null:(0,s.$L)(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}class d{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){null==t?delete this.cache_[e]:this.cache_[e]=t}get(e){return(0,s.gR)(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}const _=function(e){try{if("undefined"!=typeof window&&void 0!==window[e]){const t=window[e];return t.setItem("firebase:sentinel","cache"),t.removeItem("firebase:sentinel"),new u(t)}}catch(t){}return new d},p=_("localStorage"),f=_("sessionStorage"),g=new o.Vy("@firebase/database"),m=function(){let e=1;return function(){return e++}}(),y=function(e){const t=(0,s.kj)(e),n=new s.gz;n.update(t);const i=n.digest();return s.K3.encodeByteArray(i)},v=function(){let e="";for(let t=0;t<arguments.length;t++){const n=t<0||arguments.length<=t?void 0:arguments[t];Array.isArray(n)||n&&"object"==typeof n&&"number"==typeof n.length?e+=v.apply(null,n):e+="object"==typeof n?(0,s.As)(n):n,e+=" "}return e};let C=null,w=!0;const T=function(e,t){(0,s.vA)(!t||!0===e||!1===e,"Can't turn on custom loggers persistently."),!0===e?(g.logLevel=o.$b.VERBOSE,C=g.log.bind(g),t&&f.set("logging_enabled",!0)):"function"==typeof e?C=e:(C=null,f.remove("logging_enabled"))},k=function(){if(!0===w&&(w=!1,null===C&&!0===f.get("logging_enabled")&&T(!0)),C){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const i=v.apply(null,t);C(i)}},b=function(e){return function(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];k(e,...n)}},I=function(){const e="FIREBASE INTERNAL ERROR: "+v(...arguments);g.error(e)},E=function(){const e="FIREBASE FATAL ERROR: ".concat(v(...arguments));throw g.error(e),new Error(e)},S=function(){const e="FIREBASE WARNING: "+v(...arguments);g.warn(e)},P=function(e){return"number"==typeof e&&(e!=e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY)},N="[MIN_NAME]",x="[MAX_NAME]",R=function(e,t){if(e===t)return 0;if(e===N||t===x)return-1;if(t===N||e===x)return 1;{const 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}},A=function(e,t){return e===t?0:e<t?-1:1},D=function(e,t){if(t&&e in t)return t[e];throw new Error("Missing required key ("+e+") in object: "+(0,s.As)(t))},F=function(e){if("object"!=typeof e||null===e)return(0,s.As)(e);const t=[];for(const i in e)t.push(i);
2t.sort();let n="{";for(let i=0;i<t.length;i++)0!==i&&(n+=","),n+=(0,s.As)(t[i]),n+=":",n+=F(e[t[i]]);return n+="}",n},q=function(e,t){const n=e.length;if(n<=t)return[e];const 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 M(e,t){for(const n in e)e.hasOwnProperty(n)&&t(n,e[n])}const O=function(e){(0,s.vA)(!P(e),"Invalid JSON number");const t=1023;let n,i,r,o,a;0===e?(i=0,r=0,n=1/e==-1/0?1:0):(n=e<0,(e=Math.abs(e))>=Math.pow(2,-1022)?(o=Math.min(Math.floor(Math.log(e)/Math.LN2),t),i=o+t,r=Math.round(e*Math.pow(2,52-o)-Math.pow(2,52))):(i=0,r=Math.round(e/Math.pow(2,-1074))));const l=[];for(a=52;a;a-=1)l.push(r%2?1:0),r=Math.floor(r/2);for(a=11;a;a-=1)l.push(i%2?1:0),i=Math.floor(i/2);l.push(n?1:0),l.reverse();const h=l.join("");let c="";for(a=0;a<64;a+=8){let e=parseInt(h.substr(a,8),2).toString(16);1===e.length&&(e="0"+e),c+=e}return c.toLowerCase()};const L=new RegExp("^-?(0*)\\d{1,10}$"),W=-2147483648,U=2147483647,j=function(e){if(L.test(e)){const t=Number(e);if(t>=W&&t<=U)return t}return null},B=function(e){try{e()}catch(t){setTimeout(()=>{const e=t.stack||"";throw S("Exception was thrown by user callback.",e),t},Math.floor(0))}},H=function(e,t){const n=setTimeout(e,t);return"object"==typeof n&&n.unref&&n.unref(),n};class Y{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(){S('Provided AppCheck credentials for the app named "'.concat(this.appName_,'" ')+"are invalid. This usually indicates your app was not initialized correctly.")}}class V{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?(k("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/.',S(e)}}class K{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}K.OWNER="owner";const z="5",Q=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,G="ac",$="websocket",X="long_polling";class J{constructor(e,t,n,i){let r=arguments.length>4&&void 0!==arguments[4]&&arguments[4],s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:"",o=arguments.length>6&&void 0!==arguments[6]&&arguments[6];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=p.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()&&p.set("host:"+this._host,this.internalHost))}toString(){let e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e}toURLString(){const e=this.secure?"https://":"http://",t=this.includeNamespaceInQueryParams?"?ns=".concat(this.namespace):"";return"".concat(e).concat(this.host,"/").concat(t)}}function Z(e,t,n){let i;if((0,s.vA)("string"==typeof t,"typeof type must == string"),(0,s.vA)("object"==typeof n,"typeof params must == object"),t===$)i=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?";else{if(t!==X)throw new Error("Unknown connection type: "+t);i=(e.secure?"https://":"http://")+e.internalHost+"/.lp?"}(function(e){return e.host!==e.internalHost||e.isCustomHost()||e.includeNamespaceInQueryParams})(e)&&(n.ns=e.namespace);const r=[];return M(n,(e,t)=>{r.push(e+"="+t)}
2),i+r.join("&")}class ee{constructor(){this.counters_={}}incrementCounter(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;(0,s.gR)(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return(0,s.A4)(this.counters_)}}const te={},ne={};function ie(e){const t=e.toString();return te[t]||(te[t]=new ee),te[t]}class re{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];){const e=this.pendingResponses[this.currentResponseNum];delete this.pendingResponses[this.currentResponseNum];for(let t=0;t<e.length;++t)e[t]&&B(()=>{this.onMessage_(e[t])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}const se="start";class oe{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_=b(e),this.stats_=ie(t),this.urlFn=e=>(this.appCheckToken&&(e[G]=this.appCheckToken),Z(t,X,e))}open(e,t){var n=this;this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new re(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null},Math.floor(3e4)),function(e){if((0,s.$g)()||"complete"===document.readyState)e();else{let t=!1;const n=function(){document.body?t||(t=!0,e()):setTimeout(n,Math.floor(10))};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))}}(()=>{if(this.isClosed_)return;this.scriptTagHolder=new ae(function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const[r,s,o,a,l]=t;if(n.incrementIncomingBytes_(t),n.scriptTagHolder)if(n.connectTimeoutTimer_&&(clearTimeout(n.connectTimeoutTimer_),n.connectTimeoutTimer_=null),n.everConnected_=!0,r===se)n.id=s,n.password=o;else{if("close"!==r)throw new Error("Unrecognized command received: "+r);s?(n.scriptTagHolder.sendNewPolls=!1,n.myPacketOrderer.closeAfter(s,()=>{n.onClosed_()})):n.onClosed_()}},function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const[r,s]=t;n.incrementIncomingBytes_(t),n.myPacketOrderer.handleResponse(r,s)},()=>{this.onClosed_()},this.urlFn);const e={};e[se]="t",e.ser=Math.floor(1e8*Math.random()),this.scriptTagHolder.uniqueCallbackIdentifier&&(e.cb=this.scriptTagHolder.uniqueCallbackIdentifier),e.v=z,this.transportSessionId&&(e.s=this.transportSessionId),this.lastSessionId&&(e.ls=this.lastSessionId),this.applicationId&&(e.p=this.applicationId),this.appCheckToken&&(e[G]=this.appCheckToken),"undefined"!=typeof location&&location.hostname&&Q.test(location.hostname)&&(e.r="f");const 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(){oe.forceAllow_=!0}static forceDisallow(){oe.forceDisallow_=!0}static isAvailable(){return!(0,s.$g)()&&(!!oe.forceAllow_||!(oe.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){const t=(0,s.As)(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);const n=(0,s.KA)(t),i=q(n,1840);for(let r=0;r<i.length;r++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,i.length,i[r]),this.curSegmentNum++}addDisconnectPingFrame(e,t){if((0,s.$g)())return;this.myDisconnFrame=document.createElement("iframe");const 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){const t=(0,s.As)(e).length;this.bytesReceived+=t,this.stats_.incrementCounter("bytes_received",t)}}class ae{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,s.$g)())this.commandCB=e,this.onMessageCB=t;else{this.uniqueCallbackIdentifier=m(),window["pLPCommand"+this.uniqueCallbackIdentifier]=e,window["pRTLPCB"+this.uniqueCallbackIdentifier]=t,this.myIFrame=ae.createI
2Frame_();let n="";if(this.myIFrame.src&&"javascript:"===this.myIFrame.src.substr(0,11)){n='<script>document.domain="'+document.domain+'";<\/script>'}const i="<html><body>"+n+"</body></html>";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(i),this.myIFrame.doc.close()}catch(r){k("frame writing exception"),r.stack&&k(r.stack),k(r)}}}static createIFrame_(){const e=document.createElement("iframe");if(e.style.display="none",!document.body)throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";document.body.appendChild(e);try{e.contentWindow.document||k("No IE domain setting required")}catch(t){const n=document.domain;e.src="javascript:void((function(){document.open();document.domain='"+n+"';document.close();})())"}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)));const 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)){this.currentSerial++;const 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;){if(!(this.pendingSegs[0].d.length+30+n.length<=1870))break;{const e=this.pendingSegs.shift();n=n+"&seg"+i+"="+e.seg+"&ts"+i+"="+e.ts+"&d"+i+"="+e.d,i++}}return t+=n,this.addLongPollTag_(t,this.currentSerial),!0}return!1}enqueueSegment(e,t,n){this.pendingSegs.push({seg:e,ts:t,d:n}),this.alive&&this.newRequest_()}addLongPollTag_(e,t){this.outstandingRequests.add(t);const n=()=>{this.outstandingRequests.delete(t),this.newRequest_()},i=setTimeout(n,Math.floor(25e3));this.addTag(e,()=>{clearTimeout(i),n()})}addTag(e,t){(0,s.$g)()?this.doNodeLongPoll(e,t):setTimeout(()=>{try{if(!this.sendNewPolls)return;const n=this.myIFrame.doc.createElement("script");n.type="text/javascript",n.async=!0,n.src=e,n.onload=n.onreadystatechange=function(){const e=n.readyState;e&&"loaded"!==e&&"complete"!==e||(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),t())},n.onerror=()=>{k("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(n)}catch(n){}},Math.floor(1))}}let le=null;"undefined"!=typeof MozWebSocket?le=MozWebSocket:"undefined"!=typeof WebSocket&&(le=WebSocket);class he{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_=b(this.connId),this.stats_=ie(t),this.connURL=he.connectionURL_(t,s,o,i),this.nodeAdmin=t.nodeAdmin}static connectionURL_(e,t,n,i){const r={};return r.v=z,!(0,s.$g)()&&"undefined"!=typeof location&&location.hostname&&Q.test(location.hostname)&&(r.r="f"),t&&(r.s=t),n&&(r.ls=n),i&&(r[G]=i),Z(e,$,r)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,p.set("previous_websocket_failure",!0);try{if((0,s.$g)()){const e=this.nodeAdmin?"AdminNode":"Node",t={headers:{"User-Agent":"Firebase/".concat(z,"/").concat(h,"/").concat(process.platform,"/").concat(e),"X-Firebase-GMPID":this.applicationId||""}};this.authToken&&(t.headers.Authorization="Bearer ".concat(this.authToken)),this.appCheckToken&&(t.headers["X-Firebase-AppCheck"]=this.appCheckToken);const n={},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 le(this.connURL,[],t)}else{const e={headers:{"X-Firebase-GMPID":this.applicationId||"","X-Firebase-AppCheck":this.appCheckToken||""}};this.mySock=new le(this.connURL,[],e)}}catch(n){this.log_("Error instantiating WebSocket.");const e=n.message||n.data;return e&&this.log_(e),void this.onClosed_()}this.mySock.onopen=()=>{this.log_("Websocket connected."),this.everConnected_=!0}
vendor: 6,196 bytes, line 2
2,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.");const t=e.message||e.data;t&&this.log_(t),this.onClosed_()}}start(){}static forceDisallow(){he.forceDisallow_=!0}static isAvailable(){let e=!1;if("undefined"!=typeof navigator&&navigator.userAgent){const t=/Android ([0-9]{0,}\.[0-9]{0,})/,n=navigator.userAgent.match(t);n&&n.length>1&&parseFloat(n[1])<4.4&&(e=!0)}return!e&&null!==le&&!he.forceDisallow_}static previouslyFailed(){return p.isInMemoryStorage||!0===p.get("previous_websocket_failure")}markConnectionHealthy(){p.remove("previous_websocket_failure")}appendFrame_(e){if(this.frames.push(e),this.frames.length===this.totalFrames){const e=this.frames.join("");this.frames=null;const t=(0,s.$L)(e);this.onMessage(t)}}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if((0,s.vA)(null===this.frames,"We already have a frame buffer"),e.length<=6){const t=Number(e);if(!isNaN(t))return this.handleNewFrameCount_(t),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){if(null===this.mySock)return;const t=e.data;if(this.bytesReceived+=t.length,this.stats_.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),null!==this.frames)this.appendFrame_(t);else{const e=this.extractFrameCount_(t);null!==e&&this.appendFrame_(e)}}send(e){this.resetKeepAlive();const t=(0,s.As)(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);const n=q(t,16384);n.length>1&&this.sendString_(String(n.length));for(let i=0;i<n.length;i++)this.sendString_(n[i])}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(t){this.log_("Exception thrown from WebSocket.send():",t.message||t.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}}}he.responsesRequiredToBeHealthy=2,he.healthyTimeout=3e4;class ce{constructor(e){this.initTransports_(e)}static get ALL_TRANSPORTS(){return[oe,he]}initTransports_(e){const t=he&&he.isAvailable();let n=t&&!he.previouslyFailed();if(e.webSocketOnly&&(t||S("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),n=!0),n)this.transports_=[he];else{const e=this.transports_=[];for(const t of ce.ALL_TRANSPORTS)t&&t.isAvailable()&&e.push(t)}}initialTransport(){if(this.transports_.length>0)return this.transports_[0];throw new Error("No transports available")}upgradeTransport(){return this.transports_.length>1?this.transports_[1]:null}}class ue{constructor(e,t,n,i,r,s,o,a,l,h){this.id=e,this.repoInfo_=t,this.applicationId_=n,this.appCheckToken_=i,this.authToken_=r,this.onMessage_=s,this.onReady_=o,this.onDisconnect_=a,this.onKill_=l,this.lastSessionId=h,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=b("c:"+this.id+":"),this.transportManager_=new ce(t),this.log_("Connection created"),this.start_()}start_(){const 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;const 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));const i=e.healthyTimeout||0;i>0&&(this.healthyTimeout_=H(()=>{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){const t={t:"d",d:e};this.sendData_(t)}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){const 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){const t=D("t",e),n=D("d",e);if("c"===t)this.onSecondaryControl_(n);else{if("d"!==t)throw new Error("Unknown protocol layer: "+t);this.pendingDataMessages.push(n)}}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
2:"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){const t=D("t",e),n=D("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){const t=D("t",e);if("d"in e){const 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?I("Server Error: "+n):"o"===t?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):I("Unknown control packet command: "+t)}}onHandshake_(e){const 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),z!==n&&S("Protocol version mismatch detected"),this.tryStartUpgrade_())}tryStartUpgrade_(){const 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;const t=this.connReceiver_(this.secondaryConn_),n=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(t,n),H(()=>{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):H(()=>{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_(){const 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()&&(p.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)}}class de{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){}}class _e{constructor(e){this.allowedEvents_=e,this.listeners_={},(0,s.vA)(Array.isArray(e)&&e.length>0,"Requires a non-empty array")}trigger(e){if(Array.isArray(this.listeners_[e])){const r=[...this.listeners_[e]];for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];for(let e=0;e<r.length;
2e++)r[e].callback.apply(r[e].context,n)}}on(e,t,n){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:n});const i=this.getInitialEvent(e);i&&t.apply(n,i)}off(e,t,n){this.validateEventType_(e);const i=this.listeners_[e]||[];for(let r=0;r<i.length;r++)if(i[r].callback===t&&(!n||n===i[r].context))return void i.splice(r,1)}validateEventType_(e){(0,s.vA)(this.allowedEvents_.find(t=>t===e),"Unknown event: "+e)}}class pe extends _e{constructor(){super(["online"]),this.online_=!0,"undefined"==typeof window||void 0===window.addEventListener||(0,s.jZ)()||(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 pe}getInitialEvent(e){return(0,s.vA)("online"===e,"Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}class fe{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 ge(){return new fe("")}function me(e){return e.pieceNum_>=e.pieces_.length?null:e.pieces_[e.pieceNum_]}function ye(e){return e.pieces_.length-e.pieceNum_}function ve(e){let t=e.pieceNum_;return t<e.pieces_.length&&t++,new fe(e.pieces_,t)}function Ce(e){return e.pieceNum_<e.pieces_.length?e.pieces_[e.pieces_.length-1]:null}function we(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return e.pieces_.slice(e.pieceNum_+t)}function Te(e){if(e.pieceNum_>=e.pieces_.length)return null;const t=[];for(let n=e.pieceNum_;n<e.pieces_.length-1;n++)t.push(e.pieces_[n]);return new fe(t,0)}function ke(e,t){const n=[];for(let i=e.pieceNum_;i<e.pieces_.length;i++)n.push(e.pieces_[i]);if(t instanceof fe)for(let i=t.pieceNum_;i<t.pieces_.length;i++)n.push(t.pieces_[i]);else{const e=t.split("/");for(let t=0;t<e.length;t++)e[t].length>0&&n.push(e[t])}return new fe(n,0)}function be(e){return e.pieceNum_>=e.pieces_.length}function Ie(e,t){const n=me(e),i=me(t);if(null===n)return t;if(n===i)return Ie(ve(e),ve(t));throw new Error("INTERNAL ERROR: innerPath ("+t+") is not within outerPath ("+e+")")}function Ee(e,t){const n=we(e,0),i=we(t,0);for(let r=0;r<n.length&&r<i.length;r++){const e=R(n[r],i[r]);if(0!==e)return e}return n.length===i.length?0:n.length<i.length?-1:1}function Se(e,t){if(ye(e)!==ye(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 Pe(e,t){let n=e.pieceNum_,i=t.pieceNum_;if(ye(e)>ye(t))return!1;for(;n<e.pieces_.length;){if(e.pieces_[n]!==t.pieces_[i])return!1;++n,++i}return!0}class Ne{constructor(e,t){this.errorPrefix_=t,this.parts_=we(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let n=0;n<this.parts_.length;n++)this.byteLength_+=(0,s.OE)(this.parts_[n]);xe(this)}}function xe(e){if(e.byteLength_>768)throw new Error(e.errorPrefix_+"has a key path longer than 768 bytes ("+e.byteLength_+").");if(e.parts_.length>32)throw new Error(e.errorPrefix_+"path specified exceeds the maximum depth that can be written (32) or object contains a cycle "+Re(e))}function Re(e){return 0===e.parts_.length?"":"in property '"+e.parts_.join(".")+"'"}class Ae extends _e{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,()=>{const t=!document[e];t!==this.visible_&&(this.visible_=t,this.trigger("visible",t))},!1)}static getInstance(){return new Ae}getInitialEvent(e){return(0,s.vA)("visible"===e,"Unknown event type: "+e),[this.visible_]}}const De=1e3;class Fe extends de{constructor(e,t,n,i,r,o,a,l){if(super(),this.repoInfo_=e,this.applicationId_=t,this.onDataUpdate_=n,this.onConnectStatus_=i,this.onServerInfoUpdate_=r,this.authTokenProvider_=o,this.appCheckTokenProvider_=a,this.authOverride_=l,this.id=Fe.nextPersistentConnectionId_++,this.log_=b("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_=De,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,s.$g)())throw new Error("Auth override specified in options, but not supported on non Node.js platforms");Ae.getInstance().on("visible",this.onVisible_,this),-1===e.host.indexOf("fblocal")&&pe.getInstance().on("online",this.onOnline_,this)}sendRequest(e,t,n){const i=++this.requestNumber_,r={r:i,a:e,b:t};this.log_((0,s.As)(r)),(0,s.vA)(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(r),n&&(this.requestCBHash_[i]=n)}get(e){this.initConnection_();const t=new s.cY,n={p:e._path.toString(),q:e._queryObject},i={action:"g",request:n,onComplete:e=>{const 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_++;const r=this.outstandingGets_.length-1;return this.connected_||setTimeout(()=>{const 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(new Error("Client is offline.")))},3e3),this.connected_&&this.sendGet_(r),t.promise}listen(e,t,n,i){this.initConnection_();const r=e._queryIdentifier,o=e._path.toString();this.log_("Listen called for "+o+" "+r),this.listens.has(o)||this.listens.set(o,new Map),(0,s.vA)(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),(0,s.vA)(!this.listens.get(o).has(r),"listen() called twice for same path/queryId.");const a={onComplete:i,hashFn:t,query:e,tag:n};this.listens.get(o).set(r,a),this.connected_&&this.sendListen_(a)}sendGet_(e){const 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){const t=e.query,n=t._path.toString(),i=t._queryIdentifier;this.log_("Listen on "+n+" for "+i);const r={p:n};e.tag&&(r.q=t._queryObject,r.t=e.tag),r.h=e.hashFn(),this.sendRequest("q",r,r=>{const s=r.d,o=r.s;Fe.warnOnListenWarnings_(s,t);(this.listens.get(n)&&this.listens.get(n).get(i))===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,s.gR)(e,"w")){const n=(0,s.yw)(e,"w");if(Array.isArray(n)&&~n.indexOf("no_index")){const e='".indexOn": "'+t._queryParams.getIndex().toString()+'"',n=t._path.toString();S("Using an unspecified index. Your data will be downloaded and "+"filtered on the client. Consider adding ".concat(e," at ")+"".concat(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){(e&&40===e.length||(0,s.qc)(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_){const e=this.authToken_,t=(0,s.Cv)(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=>{const 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=>{const t=e.s,n=e.d||"error";"ok"===t?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(t,n)})}unlisten(e,t){const n=e._path.toString(),i=e._queryIdentifier;this.log_("Unlisten called for "+n+" "+i),(0,s.vA)(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query");this.removeListen_(n,i)&&this.connected_&&this.sendUnlisten_(n,i,e._queryObject,t)}sendUnlisten_(e,t,n,i){this.log_("Unlisten on "+e+" for "+t);const 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){const r={p:t,d:n};this.log_("onDisconnect "+e,r),this.sendRequest(e,r,e=>
2{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_();const s={p:t,d:n};void 0!==r&&(s.h=r),this.outstandingPuts_.push({action:e,request:s,onComplete:i}),this.outstandingPutCount_++;const o=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(o):this.log_("Buffering put: "+t)}sendPut_(e){const 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_){const t={c:e};this.log_("reportStats",t),this.sendRequest("s",t,e=>{if("ok"!==e.s){const t=e.d;this.log_("reportStats","Error sending stats: "+t)}})}}onDataMessage_(e){if("r"in e){this.log_("from server: "+(0,s.As)(e));const 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;"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):I("Unrecognized action received from server: "+(0,s.As)(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,s.vA)(!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_=De,this.realtime_||this.scheduleConnect_(0)),this.visible_=e}onOnline_(e){e?(this.log_("Browser went online."),this.reconnectDelay_=De,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_){(new Date).getTime()-this.lastConnectionEstablishedTime_>3e4&&(this.reconnectDelay_=De),this.lastConnectionEstablishedTime_=null}}else this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=(new Date).getTime();const e=(new Date).getTime()-this.lastConnectionAttemptTime_;let 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;const e=this.onDataMessage_.bind(this),t=this.onReady_.bind(this),n=this.onRealtimeDisconnect_.bind(this),i=this.id+":"+Fe.nextConnectionId_++,r=this.lastSessionId;let o=!1,a=null;const l=function(){a?a.close():(o=!0,n())},h=function(e){(0,s.vA)(a,"sendRequest call when we're not connected not allowed."),a.sendRequest(e)};this.realtime_={close:l,sendRequest:h};const c=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{const[s,l]=await Promise.all([this.authTokenProvider_.getToken(c),this.appCheckTokenProvider_.getToken(c)]);o?k("getToken() completed but was canceled"):(k("getToken() completed. Creating connection."),this.authToken_=s&&s.accessToken,this.appCheckToken_=l&&l.token,a=new ue(i,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,e,t,n,e=>{S(e+" ("+this.repoInfo_.toString()+")"),this.interrupt("server_kill")},r))}catch(I){this.log_("Failed to get token: "+I),o||(this.repoInfo_.nodeAdmin&&S(I),l())}}}interrupt(e){k("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){k("Resuming connection for reason: "+e),delete this.interruptReasons_[e],(0,s.Im)(this.interruptReasons_)&&(this.reconnectDelay_=De,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(e){const t=e-(new Date).getTime();this.onServerInfoUpdate_({serverTimeOffset:t})}cancelSentTransactions_(){for(let e=0;e<this.outstandingPuts_.length;e++){const 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=>F(e)).join("$"):"default";const i=this.removeListen_(e,n);i&&i.onComplete&&i.onComplete("permission_denied")}removeListen_(e,t){const n=new fe(e).toString();let i;if(this.listens.has(n)){const e=this.listens.get(n);i=e.get(t),e.delete(t),0===e.size&&this.listens.delete(n)}else i=void 0;return i}onAuthRevoked_(e,t){k("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){k("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_(){this.tryAuth(),this.tryAppCheck();for(const e of this.listens.values())for(const 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;){const 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_(){const e={};let t="js";(0,s.$g)()&&(t=this.repoInfo_.nodeAdmin?"admin_node":"node"),e["sdk."+t+"."+h.replace(/\./g,"-")]=1,(0,s.jZ)()?e["framework.cordova"]=1:(0,s.lV)()&&(e["framework.reactnative"]=1),this.reportStats(e)}shouldReconnect_(){const e=pe.getInstance().currentlyOnline();return(0,s.Im)(this.interruptReasons_)&&e}}Fe.nextPersistentConnectionId_=0,Fe.nextConnectionId_=0;class qe{constructor(e,t){this.name=e,this.node=t}static Wrap(e,t){return new qe(e,t)}}class Me{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,t){const n=new qe(N,e),i=new qe(N,t);return 0!==this.compare(n,i)}
vendor: 4,134 bytes, line 2
2minPost(){return qe.MIN}}let Oe;class Le extends Me{static get __EMPTY_NODE(){return Oe}static set __EMPTY_NODE(e){Oe=e}compare(e,t){return R(e.name,t.name)}isDefinedOn(e){throw(0,s.Hk)("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,t){return!1}minPost(){return qe.MIN}maxPost(){return new qe(x,Oe)}makePost(e,t){return(0,s.vA)("string"==typeof e,"KeyIndex indexValue must always be a string."),new qe(e,Oe)}toString(){return".key"}}const We=new Le;class Ue{constructor(e,t,n,i){let r=arguments.length>4&&void 0!==arguments[4]?arguments[4]: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}this.nodeStack_.push(e),e=this.isReverse_?e.right:e.left}}getNext(){if(0===this.nodeStack_.length)return null;let e,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;const e=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value}}}class je{constructor(e,t,n,i,r){this.key=e,this.value=t,this.color=null!=n?n:je.RED,this.left=null!=i?i:Be.EMPTY_NODE,this.right=null!=r?r:Be.EMPTY_NODE}copy(e,t,n,i,r){return new je(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;const 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)),i.fixUp_()}removeMin_(){if(this.left.isEmpty())return Be.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),e.fixUp_()}remove(e,t){let n,i;if(n=this,t(e,n.key)<0)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 Be.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.copy(null,null,null,null,e.right.rotateRight_()),e=e.rotateLeft_(),e=e.colorFlip_()),e}moveRedRight_(){let e=this.colorFlip_();return e.left.left.isRed_()&&(e=e.rotateRight_(),e=e.colorFlip_()),e}rotateLeft_(){const e=this.copy(null,null,je.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){const e=this.copy(null,null,je.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip_(){const 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_(){const e=this.check_();return Math.pow(2,e)<=this.count()+1}check_(){if(this.isRed_()&&this.left.isRed_())throw new Error("Red node has red child("+this.key+","+this.value+")");
2if(this.right.isRed_())throw new Error("Right child of ("+this.key+","+this.value+") is red");const e=this.left.check_();if(e!==this.right.check_())throw new Error("Black depths differ");return e+(this.isRed_()?0:1)}}je.RED=!0,je.BLACK=!1;class Be{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Be.EMPTY_NODE;this.comparator_=e,this.root_=t}insert(e,t){return new Be(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,je.BLACK,null,null))}remove(e){return new Be(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,je.BLACK,null,null))}get(e){let t,n=this.root_;for(;!n.isEmpty();){if(t=this.comparator_(e,n.key),0===t)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(t=this.comparator_(e,n.key),0===t){if(n.left.isEmpty())return i?i.key: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 new 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 Ue(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new Ue(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new Ue(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new Ue(this.root_,null,this.comparator_,!0,e)}}function He(e,t){return R(e.name,t.name)}function Ye(e,t){return R(e,t)}let Ve;Be.EMPTY_NODE=new class{copy(e,t,n,i,r){return this}insert(e,t,n){return new je(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}};const Ke=function(e){return"number"==typeof e?"number:"+O(e):"string:"+e},ze=function(e){if(e.isLeafNode()){const t=e.val();(0,s.vA)("string"==typeof t||"number"==typeof t||"object"==typeof t&&(0,s.gR)(t,".sv"),"Priority must be a string or number.")}else(0,s.vA)(e===Ve||e.isEmpty(),"priority of unexpected type.");(0,s.vA)(e===Ve||e.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")};let Qe,Ge,$e;class Xe{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Xe.__childrenNodeConstructor.EMPTY_NODE;this.value_=e,this.priorityNode_=t,this.lazyHash_=null,(0,s.vA)(void 0!==this.value_&&null!==this.value_,"LeafNode shouldn't be created with null/undefined value."),ze(this.priorityNode_)}static set __childrenNodeConstructor(e){Qe=e}static get __childrenNodeConstructor(){return Qe}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new Xe(this.value_,e)}getImmediateChild(e){return".priority"===e?this.priorityNode_:Xe.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return be(e)?this:".priority"===me(e)?this.priorityNode_:Xe.__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:Xe.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,t).updatePriority(this.priorityNode_)}updateChild(e,t){const n=me(e);return null===n?t:t.isEmpty()&&".priority"!==n?this:((0,s.vA)(".priority"!==n||1===ye(e),".priority must be the last token in a path"),this.updateImmediateChild(n,Xe.__childrenNodeConstructor.EMPTY_NODE.updateChild(ve(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:"+Ke(this.priorityNode_.val())+":");const t=typeof this.value_;e+=t+":",e+="number"===t?O(this.value_):this.value_,this.lazyHash_=y(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===Xe.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof Xe.__childrenNodeConstructor?-1:((0,s.vA)(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){const t=typeof e.value_,n=typeof this.value_,i=Xe.VALUE_TYPE_ORDER.indexOf(t),r=Xe.VALUE_TYPE_ORDER.indexOf(n);return(0,s.vA)(i>=0,"Unknown leaf type: "+t),(0,s.vA)(r>=0,"Unknown leaf type: "+n),i===r?"object"===n?0:this.value_<e.value_?-1:this.value_===e.value_?0:1:r-i}withIndex(){return this}isIndexed(){return!0}equals(e){if(e===this)return!0;
2if(e.isLeafNode()){const t=e;return this.value_===t.value_&&this.priorityNode_.equals(t.priorityNode_)}return!1}}Xe.VALUE_TYPE_ORDER=["object","boolean","number","string"];const Je=new class extends Me{compare(e,t){const n=e.node.getPriority(),i=t.node.getPriority(),r=n.compareTo(i);return 0===r?R(e.name,t.name):r}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return qe.MIN}maxPost(){return new qe(x,new Xe("[PRIORITY-POST]",$e))}makePost(e,t){const n=Ge(e);return new qe(t,new Xe("[PRIORITY-POST]",n))}toString(){return".priority"}},Ze=Math.log(2);class et{constructor(e){var t;this.count=(t=e+1,parseInt(Math.log(t)/Ze,10)),this.current_=this.count-1;const n=(i=this.count,parseInt(Array(i+1).join("1"),2));var i;this.bits_=e+1&n}nextBitIsOne(){const e=!(this.bits_&1<<this.current_);return this.current_--,e}}const tt=function(e,t,n,i){e.sort(t);const r=function(t,i){const s=i-t;let o,a;if(0===s)return null;if(1===s)return o=e[t],a=n?n(o):o,new je(a,o.node,je.BLACK,null,null);{const l=parseInt(s/2,10)+t,h=r(t,l),c=r(l+1,i);return o=e[l],a=n?n(o):o,new je(a,o.node,je.BLACK,h,c)}},s=function(t){let i=null,s=null,o=e.length;const a=function(t,i){const s=o-t,a=o;o-=t;const h=r(s+1,a),c=e[s],u=n?n(c):c;l(new je(u,c.node,i,null,h))},l=function(e){i?(i.left=e,i=e):(s=e,i=e)};for(let e=0;e<t.count;++e){const n=t.nextBitIsOne(),i=Math.pow(2,t.count-(e+1));n?a(i,je.BLACK):(a(i,je.BLACK),a(i,je.RED))}return s}(new et(e.length));return new Be(i||t,s)};let nt;const it={};class rt{constructor(e,t){this.indexes_=e,this.indexSet_=t}static get Default(){return(0,s.vA)(it&&Je,"ChildrenNode.ts has not been loaded"),nt=nt||new rt({".priority":it},{".priority":Je}),nt}get(e){const t=(0,s.yw)(this.indexes_,e);if(!t)throw new Error("No index defined for "+e);return t instanceof Be?t:null}hasIndex(e){return(0,s.gR)(this.indexSet_,e.toString())}addIndex(e,t){(0,s.vA)(e!==We,"KeyIndex always exists and isn't meant to be added to the IndexMap.");const n=[];let i=!1;const r=t.getIterator(qe.Wrap);let o,a=r.getNext();for(;a;)i=i||e.isDefinedOn(a.node),n.push(a),a=r.getNext();o=i?tt(n,e.getCompare()):it;const l=e.toString(),h=Object.assign({},this.indexSet_);h[l]=e;const c=Object.assign({},this.indexes_);return c[l]=o,new rt(c,h)}addToIndexes(e,t){const n=(0,s.Tj)(this.indexes_,(n,i)=>{const r=(0,s.yw)(this.indexSet_,i);if((0,s.vA)(r,"Missing index implementation for "+i),n===it){if(r.isDefinedOn(e.node)){const n=[],i=t.getIterator(qe.Wrap);let s=i.getNext();for(;s;)s.name!==e.name&&n.push(s),s=i.getNext();return n.push(e),tt(n,r.getCompare())}return it}{const i=t.get(e.name);let r=n;return i&&(r=r.remove(new qe(e.name,i))),r.insert(e,e.node)}});return new rt(n,this.indexSet_)}removeFromIndexes(e,t){const n=(0,s.Tj)(this.indexes_,n=>{if(n===it)return n;{const i=t.get(e.name);return i?n.remove(new qe(e.name,i)):n}});return new rt(n,this.indexSet_)}}let st;
2class ot{constructor(e,t,n){this.children_=e,this.priorityNode_=t,this.indexMap_=n,this.lazyHash_=null,this.priorityNode_&&ze(this.priorityNode_),this.children_.isEmpty()&&(0,s.vA)(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}static get EMPTY_NODE(){return st||(st=new ot(new Be(Ye),null,rt.Default))}isLeafNode(){return!1}getPriority(){return this.priorityNode_||st}updatePriority(e){return this.children_.isEmpty()?this:new ot(this.children_,e,this.indexMap_)}getImmediateChild(e){if(".priority"===e)return this.getPriority();{const t=this.children_.get(e);return null===t?st:t}}getChild(e){const t=me(e);return null===t?this:this.getImmediateChild(t).getChild(ve(e))}hasChild(e){return null!==this.children_.get(e)}updateImmediateChild(e,t){if((0,s.vA)(t,"We should always be passing snapshot nodes"),".priority"===e)return this.updatePriority(t);{const n=new qe(e,t);let i,r;t.isEmpty()?(i=this.children_.remove(e),r=this.indexMap_.removeFromIndexes(n,this.children_)):(i=this.children_.insert(e,t),r=this.indexMap_.addToIndexes(n,this.children_));const s=i.isEmpty()?st:this.priorityNode_;return new ot(i,s,r)}}updateChild(e,t){const n=me(e);if(null===n)return t;{(0,s.vA)(".priority"!==me(e)||1===ye(e),".priority must be the last token in a path");const i=this.getImmediateChild(n).updateChild(ve(e),t);return this.updateImmediateChild(n,i)}}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(e){if(this.isEmpty())return null;const t={};let n=0,i=0,r=!0;if(this.forEachChild(Je,(s,o)=>{t[s]=o.val(e),n++,r&&ot.INTEGER_REGEXP_.test(s)?i=Math.max(i,Number(s)):r=!1}),!e&&r&&i<2*n){const e=[];for(const n in t)e[n]=t[n];return e}return e&&!this.getPriority().isEmpty()&&(t[".priority"]=this.getPriority().val()),t}hash(){if(null===this.lazyHash_){let e="";this.getPriority().isEmpty()||(e+="priority:"+Ke(this.getPriority().val())+":"),this.forEachChild(Je,(t,n)=>{const i=n.hash();""!==i&&(e+=":"+t+":"+i)}),this.lazyHash_=""===e?"":y(e)}return this.lazyHash_}getPredecessorChildName(e,t,n){const i=this.resolveIndex_(n);if(i){const n=i.getPredecessorKey(new qe(e,t));return n?n.name:null}return this.children_.getPredecessorKey(e)}getFirstChildName(e){const t=this.resolveIndex_(e);if(t){const e=t.minKey();return e&&e.name}return this.children_.minKey()}getFirstChild(e){const t=this.getFirstChildName(e);return t?new qe(t,this.children_.get(t)):null}getLastChildName(e){const t=this.resolveIndex_(e);if(t){const e=t.maxKey();return e&&e.name}return this.children_.maxKey()}getLastChild(e){const t=this.getLastChildName(e);return t?new qe(t,this.children_.get(t)):null}forEachChild(e,t){const 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){const n=this.resolveIndex_(t);if(n)return n.getIteratorFrom(e,e=>e);{const n=this.children_.getIteratorFrom(e.name,qe.Wrap);let i=n.peek();for(;null!=i&&t.compare(i,e)<0;)n.getNext(),i=n.peek();return n}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(e,t){const n=this.resolveIndex_(t);if(n)return n.getReverseIteratorFrom(e,e=>e);{const n=this.children_.getReverseIteratorFrom(e.name,qe.Wrap);let 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===at?-1:0}withIndex(e){if(e===We||this.indexMap_.hasIndex(e))return this;{const t=this.indexMap_.addIndex(e,this.children_);return new ot(this.children_,this.priorityNode_,t)}}isIndexed(e){return e===We||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;if(e.isLeafNode())return!1;{const t=e;if(this.getPriority().equals(t.getPriority())){if(this.children_.count()===t.children_.count()){const e=this.getIterator(Je),n=t.getIterator(Je);let i=e.getNext(),r=n.getNext();for(;i&&r;){if(i.name!==r.name||!i.node.equals(r.node))return!1;i=e.getNext(),r=n.getNext()}return null===i&&null===r}return!1}return!1}}resolveIndex_(e){return e===We?null:this.indexMap_.get(e.toString())}}ot.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;const at=new class extends ot{constructor(){super(new Be(Ye),ot.EMPTY_NODE,rt.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return ot.EMPTY_NODE}isEmpty(){return!1}};Object.defineProperties(qe,{MIN:{value:new qe(N,ot.EMPTY_NODE)},MAX:{value:new qe(x,at)}}),Le.__EMPTY_NODE=ot.EMPTY_NODE,Xe.__childrenNodeConstructor=ot,Ve=at,function(e){$e=e}(at);const lt=!0;function ht(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;if(null===e)return ot.EMPTY_NODE;if("object"==typeof e&&".priority"in e&&(t=e[".priority"]),(0,s.vA)(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){return new Xe(e,ht(t))}if(e instanceof Array||!lt){let n=ot.EMPTY_NODE;return M(e,(t,i)=>{if((0,s.gR)(e,t)&&"."!==t.substring(0,1)){const e=ht(i);!e.isLeafNode()&&e.isEmpty()||(n=n.updateImmediateChild(t,e))}}),n.updatePriority(ht(t))}{const n=[];let i=!1;if(M(e,(e,t)=>{if("."!==e.substring(0,1)){const r=ht(t);r.isEmpty()||(i=i||!r.getPriority().isEmpty(),n.push(new qe(e,r)))}}),0===n.length)return ot.EMPTY_NODE;const r=tt(n,He,e=>e.name,Ye);if(i){const e=tt(n,Je.getCompare());return new ot(r,ht(t),new rt({".priority":e},{".priority":Je}))}return new ot(r,ht(t),rt.Default)}}!function(e){Ge=e}(ht);class ct extends Me{constructor(e){super(),this.indexPath_=e,(0,s.vA)(!be(e)&&".priority"!==me(e),"Can't
2create 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){const n=this.extractChild(e.node),i=this.extractChild(t.node),r=n.compareTo(i);return 0===r?R(e.name,t.name):r}makePost(e,t){const n=ht(e),i=ot.EMPTY_NODE.updateChild(this.indexPath_,n);return new qe(t,i)}maxPost(){const e=ot.EMPTY_NODE.updateChild(this.indexPath_,at);return new qe(x,e)}toString(){return we(this.indexPath_,0).join("/")}}const ut=new class extends Me{compare(e,t){const n=e.node.compareTo(t.node);return 0===n?R(e.name,t.name):n}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return qe.MIN}maxPost(){return qe.MAX}makePost(e,t){const n=ht(e);return new qe(t,n)}toString(){return".value"}},dt="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",_t=function(){let e=0;const t=[];return function(n){const i=n===e;let r;e=n;const o=new Array(8);for(r=7;r>=0;r--)o[r]=dt.charAt(n%64),n=Math.floor(n/64);(0,s.vA)(0===n,"Cannot push at time == 0");let a=o.join("");if(i){for(r=11;r>=0&&63===t[r];r--)t[r]=0;t[r]++}else for(r=0;r<12;r++)t[r]=Math.floor(64*Math.random());for(r=0;r<12;r++)a+=dt.charAt(t[r]);return(0,s.vA)(20===a.length,"nextPushId: Length should be 20."),a}}(),pt=function(e){if(e===""+U)return"-";const t=j(e);if(null!=t)return""+(t+1);const n=new Array(e.length);for(let o=0;o<n.length;o++)n[o]=e.charAt(o);if(n.length<786)return n.push("-"),n.join("");let i=n.length-1;for(;i>=0&&"z"===n[i];)i--;if(-1===i)return x;const r=n[i],s=dt.charAt(dt.indexOf(r)+1);return n[i]=s,n.slice(0,i+1).join("")},ft=function(e){if(e===""+W)return N;const t=j(e);if(null!=t)return""+(t-1);const n=new Array(e.length);for(let i=0;i<n.length;i++)n[i]=e.charAt(i);return"-"===n[n.length-1]?1===n.length?""+U:(delete n[n.length-1],n.join("")):(n[n.length-1]=dt.charAt(dt.indexOf(n[n.length-1])-1),n.join("")+"z".repeat(786-n.length))};function gt(e){return{type:"value",snapshotNode:e}}function mt(e,t){return{type:"child_added",snapshotNode:t,childName:e}}function yt(e,t){return{type:"child_removed",snapshotNode:t,childName:e}}function vt(e,t,n){return{type:"child_changed",snapshotNode:t,childName:e,oldSnap:n}}class Ct{constructor(e){this.index_=e}updateChild(e,t,n,i,r,o){(0,s.vA)(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");const a=e.getImmediateChild(t);return a.getChild(i).equals(n.getChild(i))&&a.isEmpty()===n.isEmpty()?e:(null!=o&&(n.isEmpty()?e.hasChild(t)?o.trackChildChange(yt(t,a)):(0,s.vA)(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):a.isEmpty()?o.trackChildChange(mt(t,n)):o.trackChildChange(vt(t,n,a))),e.isLeafNode()&&n.isEmpty()?e:e.updateImmediateChild(t,n).withIndex(this.index_))}updateFullNode(e,t,n){return null!=n&&(e.isLeafNode()||e.forEachChild(Je,(e,i)=>{t.hasChild(e)||n.trackChildChange(yt(e,i))}),t.isLeafNode()||t.forEachChild(Je,(t,i)=>{if(e.hasChild(t)){const r=e.getImmediateChild(t);r.equals(i)||n.trackChildChange(vt(t,i,r))}else n.trackChildChange(mt(t,i))})),t.withIndex(this.index_)}updatePriority(e,t){return e.isEmpty()?ot.EMPTY_NODE:e.updatePriority(t)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}class wt{constructor(e){this.indexedFilter_=new Ct(e.getIndex()),this.index_=e.getIndex(),this.startPost_=wt.getStartPost_(e),this.endPost_=wt.getEndPost_(e)}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){return this.index_.compare(this.getStartPost(),e)<=0&&this.index_.compare(e,this.getEndPost())<=0}updateChild(e,t,n,i,r,s){return this.matches(new qe(t,n))||(n=ot.EMPTY_NODE),this.indexedFilter_.updateChild(e,t,n,i,r,s)}updateFullNode(e,t,n){t.isLeafNode()&&(t=ot.EMPTY_NODE);let i=t.withIndex(this.index_);i=i.updatePriority(ot.EMPTY_NODE);const r=this;return t.forEachChild(Je,(e,t)=>{r.matches(new qe(e,t))||(i=i.updateImmediateChild(e,ot.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()){const t=e.getIndexStartName();return e.getIndex().makePost(e.getIndexStartValue(),t)}return e.getIndex().minPost()}static getEndPost_(e){if(e.hasEnd()){const t=e.getIndexEndName();return e.getIndex().makePost(e.getIndexEndValue(),t)}return e.getIndex().maxPost()}}
2class Tt{constructor(e){this.rangedFilter_=new wt(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 qe(t,n))||(n=ot.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=ot.EMPTY_NODE.withIndex(this.index_);else if(2*this.limit_<t.numChildren()&&t.isIndexed(this.index_)){let e;i=ot.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_;){const t=e.getNext();let r;if(r=this.reverse_?this.index_.compare(this.rangedFilter_.getStartPost(),t)<=0:this.index_.compare(t,this.rangedFilter_.getEndPost())<=0,!r)break;i=i.updateImmediateChild(t.name,t.node),n++}}else{let e,n,r,s;if(i=t.withIndex(this.index_),i=i.updatePriority(ot.EMPTY_NODE),this.reverse_){s=i.getReverseIterator(this.index_),e=this.rangedFilter_.getEndPost(),n=this.rangedFilter_.getStartPost();const 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,a=!1;for(;s.hasNext();){const t=s.getNext();!a&&r(e,t)<=0&&(a=!0);a&&o<this.limit_&&r(t,n)<=0?o++:i=i.updateImmediateChild(t.name,ot.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 o;if(this.reverse_){const e=this.index_.getCompare();o=(t,n)=>e(n,t)}else o=this.index_.getCompare();const a=e;(0,s.vA)(a.numChildren()===this.limit_,"");const l=new qe(t,n),h=this.reverse_?a.getFirstChild(this.index_):a.getLastChild(this.index_),c=this.rangedFilter_.matches(l);if(a.hasChild(t)){const e=a.getImmediateChild(t);let s=i.getChildAfterChild(this.index_,h,this.reverse_);for(;null!=s&&(s.name===t||a.hasChild(s.name));)s=i.getChildAfterChild(this.index_,s,this.reverse_);const u=null==s?1:o(s,l);if(c&&!n.isEmpty()&&u>=0)return null!=r&&r.trackChildChange(vt(t,n,e)),a.updateImmediateChild(t,n);{null!=r&&r.trackChildChange(yt(t,e));const n=a.updateImmediateChild(t,ot.EMPTY_NODE);return null!=s&&this.rangedFilter_.matches(s)?(null!=r&&r.trackChildChange(mt(s.name,s.node)),n.updateImmediateChild(s.name,s.node)):n}}return n.isEmpty()?e:c&&o(h,l)>=0?(null!=r&&(r.trackChildChange(yt(h.name,h.node)),r.trackChildChange(mt(t,n))),a.updateImmediateChild(t,n).updateImmediateChild(h.name,ot.EMPTY_NODE)):e}}class kt{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_=Je}hasStart(){return this.startSet_}hasStartAfter(){return this.startAfterSet_}hasEndBefore(){return this.endBeforeSet_}isViewFromLeft(){return""===this.viewFrom_?this.startSet_:"l"===this.viewFrom_}getIndexStartValue(){return(0,s.vA)(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return(0,s.vA)(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:N}hasEnd(){return this.endSet_}getIndexEndValue(){return(0,s.vA)(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return(0,s.vA)(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:x}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&""!==this.viewFrom_}getLimit(){return(0,s.vA)(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_===Je}copy(){const e=new kt;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 bt(e,t,n){const i=e.copy();return i.startSet_=!0,void 0===t&&(t=null),i.indexStartValue_=t,null!=n?(i.startNameSet_=!0,i.indexStartName_=n):(i.startNameSet_=!1,i.indexStartName_=""),i}function It(e,t,n){const i=e.copy();return i.endSet_=!0,void 0===t&&(t=null),i.indexEndValue_=t,void 0!==n?(i.endNameSet_=!0,i.indexEndName_=n):(i.endNameSet_=!1,i.indexEndName_=""),i}function Et(e,t){const n=e.copy();return n.index_=t,n}function St(e){const t={};if(e.isDefault())return t;let n;
2return e.index_===Je?n="$priority":e.index_===ut?n="$value":e.index_===We?n="$key":((0,s.vA)(e.index_ instanceof ct,"Unrecognized index type!"),n=e.index_.toString()),t.orderBy=(0,s.As)(n),e.startSet_&&(t.startAt=(0,s.As)(e.indexStartValue_),e.startNameSet_&&(t.startAt+=","+(0,s.As)(e.indexStartName_))),e.endSet_&&(t.endAt=(0,s.As)(e.indexEndValue_),e.endNameSet_&&(t.endAt+=","+(0,s.As)(e.indexEndName_))),e.limitSet_&&(e.isViewFromLeft()?t.limitToFirst=e.limit_:t.limitToLast=e.limit_),t}function Pt(e){const 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_!==Je&&(t.i=e.index_.toString()),t}class Nt extends de{constructor(e,t,n,i){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=n,this.appCheckTokenProvider_=i,this.log_=b("p:rest:"),this.listens_={}}reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,t){return void 0!==t?"tag$"+t:((0,s.vA)(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}listen(e,t,n,i){const r=e._path.toString();this.log_("Listen called for "+r+" "+e._queryIdentifier);const o=Nt.getListenId_(e,n),a={};this.listens_[o]=a;const l=St(e._queryParams);this.restRequest_(r+".json",l,(e,t)=>{let l=t;if(404===e&&(l=null,e=null),null===e&&this.onDataUpdate_(r,l,!1,n),(0,s.yw)(this.listens_,o)===a){let t;t=e?401===e?"permission_denied":"rest_error:"+e:"ok",i(t,null)}})}unlisten(e,t){const n=Nt.getListenId_(e,t);delete this.listens_[n]}get(e){const t=St(e._queryParams),n=e._path.toString(),i=new s.cY;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(new Error(r))}),i.promise}refreshAuthToken(e){}restRequest_(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2?arguments[2]:void 0;return t.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then(i=>{let[r,o]=i;r&&r.accessToken&&(t.auth=r.accessToken),o&&o.token&&(t.ac=o.token);const a=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+e+"?ns="+this.repoInfo_.namespace+(0,s.Am)(t);this.log_("Sending REST request for "+a);const l=new XMLHttpRequest;l.onreadystatechange=()=>{if(n&&4===l.readyState){this.log_("REST Response for "+a+" received. status:",l.status,"response:",l.responseText);let t=null;if(l.status>=200&&l.status<300){try{t=(0,s.$L)(l.responseText)}catch(e){S("Failed to parse JSON response for "+a+": "+l.responseText)}n(null,t)}else 401!==l.status&&404!==l.status&&S("Got unsuccessful REST response for "+a+" Status: "+l.status),n(l.status);n=null}},l.open("GET",a,!0),l.send()})}}class xt{constructor(){this.rootNode_=ot.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}function Rt(){return{value:null,children:new Map}}function At(e,t,n){if(be(t))e.value=n,e.children.clear();else if(null!==e.value)e.value=e.value.updateChild(t,n);else{const i=me(t);e.children.has(i)||e.children.set(i,Rt());At(e.children.get(i),t=ve(t),n)}}function Dt(e,t){if(be(t))return e.value=null,e.children.clear(),!0;if(null!==e.value){if(e.value.isLeafNode())return!1;{const n=e.value;return e.value=null,n.forEachChild(Je,(t,n)=>{At(e,new fe(t),n)}),Dt(e,t)}}if(e.children.size>0){const n=me(t);if(t=ve(t),e.children.has(n)){Dt(e.children.get(n),t)&&e.children.delete(n)}return 0===e.children.size}return!0}function Ft(e,t,n){null!==e.value?n(t,e.value):function(e,t){e.children.forEach((e,n)=>{t(n,e)})}(e,(e,i)=>{Ft(i,new fe(t.toString()+"/"+e),n)})}class qt{constructor(e){this.collection_=e,this.last_=null}get(){const e=this.collection_.get(),t=Object.assign({},e);return this.last_&&M(this.last_,(e,n)=>{t[e]=t[e]-n}),this.last_=e,t}}class Mt{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new qt(e);const n=1e4+2e4*Math.random();H(this.reportStats_.bind(this),Math.floor(n))}reportStats_(){const e=this.statsListener_.get(),t={};let n=!1;M(e,(e,i)=>{i>0&&(0,s.gR)(this.statsToReport_,e)&&(t[e]=i,n=!0)}),n&&this.server_.reportStats(t),H(this.reportStats_.bind(this),Math.floor(2*Math.random()*3e5))}}var Ot;function Lt(e){return{fromUser:!1,fromServer:!0,queryId:e,tagged:!0}}!function(e){e[e.OVERWRITE=0]="OVERWRITE",e[e.MERGE=1]="MERGE",e[e.ACK_USER_WRITE=2]="ACK_USER_WRITE",e[e.LISTEN_COMPLETE=3]="LISTEN_COMPLETE"}(Ot||(Ot={}));class Wt{constructor(e,t,n){this.path=e,this.affectedTree=t,this.revert=n,this.type=Ot.ACK_USER_WRITE,this.source={fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}operationForChild(e){if(be(this.path)){if(null!=this.affectedTree.value)return(0,s.vA)(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;{const t=this.affectedTree.subtree(new fe(e));
2return new Wt(ge(),t,this.revert)}}return(0,s.vA)(me(this.path)===e,"operationForChild called for unrelated child."),new Wt(ve(this.path),this.affectedTree,this.revert)}}class Ut{constructor(e,t){this.source=e,this.path=t,this.type=Ot.LISTEN_COMPLETE}operationForChild(e){return be(this.path)?new Ut(this.source,ge()):new Ut(this.source,ve(this.path))}}class jt{constructor(e,t,n){this.source=e,this.path=t,this.snap=n,this.type=Ot.OVERWRITE}operationForChild(e){return be(this.path)?new jt(this.source,ge(),this.snap.getImmediateChild(e)):new jt(this.source,ve(this.path),this.snap)}}class Bt{constructor(e,t,n){this.source=e,this.path=t,this.children=n,this.type=Ot.MERGE}operationForChild(e){if(be(this.path)){const t=this.children.subtree(new fe(e));return t.isEmpty()?null:t.value?new jt(this.source,ge(),t.value):new Bt(this.source,ge(),t)}return(0,s.vA)(me(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new Bt(this.source,ve(this.path),this.children)}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}class Ht{constructor(e,t,n){this.node_=e,this.fullyInitialized_=t,this.filtered_=n}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(be(e))return this.isFullyInitialized()&&!this.filtered_;const t=me(e);return this.isCompleteForChild(t)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}class Yt{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function Vt(e,t,n,i,r,o){const a=i.filter(e=>e.type===n);a.sort((t,n)=>function(e,t,n){if(null==t.childName||null==n.childName)throw(0,s.Hk)("Should only compare child_ events.");const i=new qe(t.childName,t.snapshotNode),r=new qe(n.childName,n.snapshotNode);return e.index_.compare(i,r)}(e,t,n)),a.forEach(n=>{const i=function(e,t,n){return"value"===t.type||"child_removed"===t.type||(t.prevName=n.getPredecessorChildName(t.childName,t.snapshotNode,e.index_)),t}(e,n,o);r.forEach(r=>{r.respondsTo(n.type)&&t.push(r.createEvent(i,e.query_))})})}function Kt(e,t){return{eventCache:e,serverCache:t}}function zt(e,t,n,i){return Kt(new Ht(t,n,i),e.serverCache)}function Qt(e,t,n,i){return Kt(e.eventCache,new Ht(t,n,i))}function Gt(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function $t(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}let Xt;class Jt{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(Xt||(Xt=new Be(A)),Xt);this.value=e,this.children=t}static fromObject(e){let t=new Jt(null);return M(e,(e,n)=>{t=t.set(new fe(e),n)}),t}isEmpty(){return null===this.value&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){if(null!=this.value&&t(this.value))return{path:ge(),value:this.value};if(be(e))return null;{const n=me(e),i=this.children.get(n);if(null!==i){const r=i.findRootMostMatchingPathAndValue(ve(e),t);if(null!=r){return{path:ke(new fe(n),r.path),value:r.value}}return null}return null}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,()=>!0)}subtree(e){if(be(e))return this;{const t=me(e),n=this.children.get(t);return null!==n?n.subtree(ve(e)):new Jt(null)}}set(e,t){if(be(e))return new Jt(t,this.children);{const n=me(e),i=(this.children.get(n)||new Jt(null)).set(ve(e),t),r=this.children.insert(n,i);return new Jt(this.value,r)}}remove(e){if(be(e))return this.children.isEmpty()?new Jt(null):new Jt(null,this.children);{const t=me(e),n=this.children.get(t);if(n){const i=n.remove(ve(e));let r;return r=i.isEmpty()?this.children.remove(t):this.children.insert(t,i),null===this.value&&r.isEmpty()?new Jt(null):new Jt(this.value,r)}return this}}get(e){if(be(e))return this.value;{const t=me(e),n=this.children.get(t);return n?n.get(ve(e)):null}}setTree(e,t){if(be(e))return t;{const n=me(e),i=(this.children.get(n)||new Jt(null)).setTree(ve(e),t);let r;return r=i.isEmpty()?this.children.remove(n):this.children.insert(n,i),new Jt(this.value,r)}}fold(e){return this.fold_(ge(),e)}fold_(e,t){const n={};return this.children.inorderTraversal((i,r)=>{n[i]=r.fold_(ke(e,i),t)}
2),t(e,this.value,n)}findOnPath(e,t){return this.findOnPath_(e,ge(),t)}findOnPath_(e,t,n){const i=!!this.value&&n(t,this.value);if(i)return i;if(be(e))return null;{const i=me(e),r=this.children.get(i);return r?r.findOnPath_(ve(e),ke(t,i),n):null}}foreachOnPath(e,t){return this.foreachOnPath_(e,ge(),t)}foreachOnPath_(e,t,n){if(be(e))return this;{this.value&&n(t,this.value);const i=me(e),r=this.children.get(i);return r?r.foreachOnPath_(ve(e),ke(t,i),n):new Jt(null)}}foreach(e){this.foreach_(ge(),e)}foreach_(e,t){this.children.inorderTraversal((n,i)=>{i.foreach_(ke(e,n),t)}),this.value&&t(e,this.value)}foreachChild(e){this.children.inorderTraversal((t,n)=>{n.value&&e(t,n.value)})}}class Zt{constructor(e){this.writeTree_=e}static empty(){return new Zt(new Jt(null))}}function en(e,t,n){if(be(t))return new Zt(new Jt(n));{const i=e.writeTree_.findRootMostValueAndPath(t);if(null!=i){const r=i.path;let s=i.value;const o=Ie(r,t);return s=s.updateChild(o,n),new Zt(e.writeTree_.set(r,s))}{const i=new Jt(n),r=e.writeTree_.setTree(t,i);return new Zt(r)}}}function tn(e,t,n){let i=e;return M(n,(e,n)=>{i=en(i,ke(t,e),n)}),i}function nn(e,t){if(be(t))return Zt.empty();{const n=e.writeTree_.setTree(t,new Jt(null));return new Zt(n)}}function rn(e,t){return null!=sn(e,t)}function sn(e,t){const n=e.writeTree_.findRootMostValueAndPath(t);return null!=n?e.writeTree_.get(n.path).getChild(Ie(n.path,t)):null}function on(e){const t=[],n=e.writeTree_.value;return null!=n?n.isLeafNode()||n.forEachChild(Je,(e,n)=>{t.push(new qe(e,n))}):e.writeTree_.children.inorderTraversal((e,n)=>{null!=n.value&&t.push(new qe(e,n.value))}),t}function an(e,t){if(be(t))return e;{const n=sn(e,t);return new Zt(null!=n?new Jt(n):e.writeTree_.subtree(t))}}function ln(e){return e.writeTree_.isEmpty()}function hn(e,t){return cn(ge(),e.writeTree_,t)}function cn(e,t,n){if(null!=t.value)return n.updateChild(e,t.value);{let i=null;return t.children.inorderTraversal((t,r)=>{".priority"===t?((0,s.vA)(null!==r.value,"Priority writes must always be leaf nodes"),i=r.value):n=cn(ke(e,t),r,n)}),n.getChild(e).isEmpty()||null===i||(n=n.updateChild(ke(e,".priority"),i)),n}}function un(e,t){return bn(t,e)}function dn(e,t){const n=e.allWrites.findIndex(e=>e.writeId===t);(0,s.vA)(n>=0,"removeWrite called with nonexistent writeId.");const i=e.allWrites[n];e.allWrites.splice(n,1);let r=i.visible,o=!1,a=e.allWrites.length-1;for(;r&&a>=0;){const t=e.allWrites[a];t.visible&&(a>=n&&_n(t,i.path)?r=!1:Pe(i.path,t.path)&&(o=!0)),a--}if(r){if(o)return function(e){e.visibleWrites=fn(e.allWrites,pn,ge()),e.allWrites.length>0?e.lastWriteId=e.allWrites[e.allWrites.length-1].writeId:e.lastWriteId=-1}(e),!0;if(i.snap)e.visibleWrites=nn(e.visibleWrites,i.path);else{M(i.children,t=>{e.visibleWrites=nn(e.visibleWrites,ke(i.path,t))})}return!0}return!1}function _n(e,t){if(e.snap)return Pe(e.path,t);for(const n in e.children)if(e.children.hasOwnProperty(n)&&Pe(ke(e.path,n),t))return!0;return!1}function pn(e){return e.visible}function fn(e,t,n){let i=Zt.empty();for(let r=0;r<e.length;++r){const o=e[r];if(t(o)){const e=o.path;let t;if(o.snap)Pe(n,e)?(t=Ie(n,e),i=en(i,t,o.snap)):Pe(e,n)&&(t=Ie(e,n),i=en(i,ge(),o.snap.getChild(t)));else{if(!o.children)throw(0,s.Hk)("WriteRecord should have .snap or .children");if(Pe(n,e))t=Ie(n,e),i=tn(i,t,o.children);else if(Pe(e,n))if(t=Ie(e,n),be(t))i=tn(i,ge(),o.children);else{const e=(0,s.yw)(o.children,me(t));if(e){const n=e.getChild(ve(t));i=en(i,ge(),n)}}}}}return i}function gn(e,t,n,i,r){if(i||r){const s=an(e.visibleWrites,t);if(!r&&ln(s))return n;if(r||null!=n||rn(s,ge())){const s=function(e){return(e.visible||r)&&(!i||!~i.indexOf(e.writeId))&&(Pe(e.path,t)||Pe(t,e.path))};return hn(fn(e.allWrites,s,t),n||ot.EMPTY_NODE)}return null}{const i=sn(e.visibleWrites,t);if(null!=i)return i;{const i=an(e.visibleWrites,t);if(ln(i))return n;if(null!=n||rn(i,ge())){return hn(i,n||ot.EMPTY_NODE)}return null}}}function mn(e,t,n,i){return gn(e.writeTree,e.treePath,t,n,i)}function yn(e,t){return function(e,t,n){let i=ot.EMPTY_NODE;const r=sn(e.visibleWrites,t);if(r)return r.isLeafNode()||r.forEachChild(Je,(e,t)=>{i=i.updateImmediateChild(e,t)}),i;if(n){const r=an(e.visibleWrites,t);
2return n.forEachChild(Je,(e,t)=>{const n=hn(an(r,new fe(e)),t);i=i.updateImmediateChild(e,n)}),on(r).forEach(e=>{i=i.updateImmediateChild(e.name,e.node)}),i}return on(an(e.visibleWrites,t)).forEach(e=>{i=i.updateImmediateChild(e.name,e.node)}),i}(e.writeTree,e.treePath,t)}function vn(e,t,n,i){return function(e,t,n,i,r){(0,s.vA)(i||r,"Either existingEventSnap or existingServerSnap must exist");const o=ke(t,n);if(rn(e.visibleWrites,o))return null;{const t=an(e.visibleWrites,o);return ln(t)?r.getChild(n):hn(t,r.getChild(n))}}(e.writeTree,e.treePath,t,n,i)}function Cn(e,t){return function(e,t){return sn(e.visibleWrites,t)}(e.writeTree,ke(e.treePath,t))}function wn(e,t,n,i,r,s){return function(e,t,n,i,r,s,o){let a;const l=an(e.visibleWrites,t),h=sn(l,ge());if(null!=h)a=h;else{if(null==n)return[];a=hn(l,n)}if(a=a.withIndex(o),a.isEmpty()||a.isLeafNode())return[];{const e=[],t=o.getCompare(),n=s?a.getReverseIteratorFrom(i,o):a.getIteratorFrom(i,o);let l=n.getNext();for(;l&&e.length<r;)0!==t(l,i)&&e.push(l),l=n.getNext();return e}}(e.writeTree,e.treePath,t,n,i,r,s)}function Tn(e,t,n){return function(e,t,n,i){const r=ke(t,n),s=sn(e.visibleWrites,r);if(null!=s)return s;if(i.isCompleteForChild(n))return hn(an(e.visibleWrites,r),i.getNode().getImmediateChild(n));return null}(e.writeTree,e.treePath,t,n)}function kn(e,t){return bn(ke(e.treePath,t),e.writeTree)}function bn(e,t){return{treePath:e,writeTree:t}}class In{constructor(){this.changeMap=new Map}trackChildChange(e){const t=e.type,n=e.childName;(0,s.vA)("child_added"===t||"child_changed"===t||"child_removed"===t,"Only child changes supported for tracking"),(0,s.vA)(".priority"!==n,"Only non-priority child changes can be tracked.");const i=this.changeMap.get(n);if(i){const r=i.type;if("child_added"===t&&"child_removed"===r)this.changeMap.set(n,vt(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,yt(n,i.oldSnap));else if("child_changed"===t&&"child_added"===r)this.changeMap.set(n,mt(n,e.snapshotNode));else{if("child_changed"!==t||"child_changed"!==r)throw(0,s.Hk)("Illegal combination of changes: "+e+" occurred after "+i);this.changeMap.set(n,vt(n,e.snapshotNode,i.oldSnap))}}else this.changeMap.set(n,e)}getChanges(){return Array.from(this.changeMap.values())}}const En=new class{getCompleteChild(e){return null}getChildAfterChild(e,t,n){return null}};class Sn{constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;this.writes_=e,this.viewCache_=t,this.optCompleteServerCache_=n}getCompleteChild(e){const t=this.viewCache_.eventCache;if(t.isCompleteForChild(e))return t.getNode().getImmediateChild(e);{const t=null!=this.optCompleteServerCache_?new Ht(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache;return Tn(this.writes_,e,t)}}getChildAfterChild(e,t,n){const i=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:$t(this.viewCache_),r=wn(this.writes_,i,t,1,n,e);return 0===r.length?null:r[0]}}function Pn(e,t,n,i,r){const o=new In;let a,l;if(n.type===Ot.OVERWRITE){const h=n;h.source.fromUser?a=Rn(e,t,h.path,h.snap,i,r,o):((0,s.vA)(h.source.fromServer,"Unknown source."),l=h.source.tagged||t.serverCache.isFiltered()&&!be(h.path),a=xn(e,t,h.path,h.snap,i,r,l,o))}else if(n.type===Ot.MERGE){const h=n;h.source.fromUser?a=function(e,t,n,i,r,s,o){let a=t;return i.foreach((i,l)=>{const h=ke(n,i);An(t,me(h))&&(a=Rn(e,a,h,l,r,s,o))}),i.foreach((i,l)=>{const h=ke(n,i);An(t,me(h))||(a=Rn(e,a,h,l,r,s,o))}),a}(e,t,h.path,h.children,i,r,o):((0,s.vA)(h.source.fromServer,"Unknown source."),l=h.source.tagged||t.serverCache.isFiltered(),a=Fn(e,t,h.path,h.children,i,r,l,o))}else if(n.type===Ot.ACK_USER_WRITE){const l=n;a=l.revert?function(e,t,n,i,r,o){let a;if(null!=Cn(i,n))return t;{const l=new Sn(i,t,r),h=t.eventCache.getNode();let c;if(be(n)||".priority"===me(n)){let n;if(t.serverCache.isFullyInitialized())n=mn(i,$t(t));else{const e=t.serverCache.getNode();(0,s.vA)(e instanceof ot,"serverChildren would be complete if leaf node"),n=yn(i,e)}c=e.filter.updateFullNode(h,n,o)}else{const r=me(n);let s=Tn(i,r,t.serverCache);null==s&&t.serverCache.isCompleteForChild(r)&&(s=h.getImmediateChild(r)),c=null!=s?e.filter.updateChild(h,r,s,ve(n),l,o):t.eventCache.getNode().hasChild(r)?e.filter.updateChild(h,r,ot.EMPTY_NODE,ve(n),l,o):h,c.isEmpty()&&t.serverCache.isFullyInitialized()&&(a=mn(i,$t(t)),a.isLeafNode()&&(c=e.filter.updateFullNode(c,a,o)))}return a=t.serverCache.isFullyInitialized()||null!=Cn(i,ge()),zt(t,c,a,e.filter.filtersNodes())}}(e,t,l.path,i,r,o):function(e,t,n,i,r,s,o){if(null!=Cn(r,n))return t;const a=t.serverCache.isFiltered(),l=t.serverCache;if(null!=i.value){if(be(n)&&l.isFullyInitialized()||l.isCompleteForPath(n))return xn(e,t,n,l.getNode().getChild(n),r,s,a,o);if(be(n)){let i=new Jt(null);
vendor: 4,727 bytes, line 2
2return l.getNode().forEachChild(We,(e,t)=>{i=i.set(new fe(e),t)}),Fn(e,t,n,i,r,s,a,o)}return t}{let h=new Jt(null);return i.foreach((e,t)=>{const i=ke(n,e);l.isCompleteForPath(i)&&(h=h.set(e,l.getNode().getChild(i)))}),Fn(e,t,n,h,r,s,a,o)}}(e,t,l.path,l.affectedTree,i,r,o)}else{if(n.type!==Ot.LISTEN_COMPLETE)throw(0,s.Hk)("Unknown operation type: "+n.type);a=function(e,t,n,i,r){const s=t.serverCache,o=Qt(t,s.getNode(),s.isFullyInitialized()||be(n),s.isFiltered());return Nn(e,o,n,i,En,r)}(e,t,n.path,i,o)}const h=o.getChanges();return function(e,t,n){const i=t.eventCache;if(i.isFullyInitialized()){const r=i.getNode().isLeafNode()||i.getNode().isEmpty(),s=Gt(e);(n.length>0||!e.eventCache.isFullyInitialized()||r&&!i.getNode().equals(s)||!i.getNode().getPriority().equals(s.getPriority()))&&n.push(gt(Gt(t)))}}(t,a,h),{viewCache:a,changes:h}}function Nn(e,t,n,i,r,o){const a=t.eventCache;if(null!=Cn(i,n))return t;{let l,h;if(be(n))if((0,s.vA)(t.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),t.serverCache.isFiltered()){const n=$t(t),r=yn(i,n instanceof ot?n:ot.EMPTY_NODE);l=e.filter.updateFullNode(t.eventCache.getNode(),r,o)}else{const n=mn(i,$t(t));l=e.filter.updateFullNode(t.eventCache.getNode(),n,o)}else{const c=me(n);if(".priority"===c){(0,s.vA)(1===ye(n),"Can't have a priority with additional path components");const r=a.getNode();h=t.serverCache.getNode();const o=vn(i,n,r,h);l=null!=o?e.filter.updatePriority(r,o):a.getNode()}else{const s=ve(n);let u;if(a.isCompleteForChild(c)){h=t.serverCache.getNode();const e=vn(i,n,a.getNode(),h);u=null!=e?a.getNode().getImmediateChild(c).updateChild(s,e):a.getNode().getImmediateChild(c)}else u=Tn(i,c,t.serverCache);l=null!=u?e.filter.updateChild(a.getNode(),c,u,s,r,o):a.getNode()}}return zt(t,l,a.isFullyInitialized()||be(n),e.filter.filtersNodes())}}function xn(e,t,n,i,r,s,o,a){const l=t.serverCache;let h;const c=o?e.filter:e.filter.getIndexedFilter();if(be(n))h=c.updateFullNode(l.getNode(),i,null);else if(c.filtersNodes()&&!l.isFiltered()){const e=l.getNode().updateChild(n,i);h=c.updateFullNode(l.getNode(),e,null)}else{const e=me(n);if(!l.isCompleteForPath(n)&&ye(n)>1)return t;const r=ve(n),s=l.getNode().getImmediateChild(e).updateChild(r,i);h=".priority"===e?c.updatePriority(l.getNode(),s):c.updateChild(l.getNode(),e,s,r,En,null)}const u=Qt(t,h,l.isFullyInitialized()||be(n),c.filtersNodes());return Nn(e,u,n,r,new Sn(r,u,s),a)}function Rn(e,t,n,i,r,s,o){const a=t.eventCache;let l,h;const c=new Sn(r,t,s);if(be(n))h=e.filter.updateFullNode(t.eventCache.getNode(),i,o),l=zt(t,h,!0,e.filter.filtersNodes());else{const r=me(n);if(".priority"===r)h=e.filter.updatePriority(t.eventCache.getNode(),i),l=zt(t,h,a.isFullyInitialized(),a.isFiltered());else{const s=ve(n),h=a.getNode().getImmediateChild(r);let u;if(be(s))u=i;else{const e=c.getCompleteChild(r);u=null!=e?".priority"===Ce(s)&&e.getChild(Te(s)).isEmpty()?e:e.updateChild(s,i):ot.EMPTY_NODE}if(h.equals(u))l=t;else{l=zt(t,e.filter.updateChild(a.getNode(),r,u,s,c,o),a.isFullyInitialized(),e.filter.filtersNodes())}}}return l}function An(e,t){return e.eventCache.isCompleteForChild(t)}function Dn(e,t,n){return n.foreach((e,n)=>{t=t.updateChild(e,n)}),t}function Fn(e,t,n,i,r,s,o,a){if(t.serverCache.getNode().isEmpty()&&!t.serverCache.isFullyInitialized())return t;let l,h=t;l=be(n)?i:new Jt(null).setTree(n,i);const c=t.serverCache.getNode();return l.children.inorderTraversal((n,i)=>{if(c.hasChild(n)){const l=Dn(0,t.serverCache.getNode().getImmediateChild(n),i);h=xn(e,h,new fe(n),l,r,s,o,a)}}),l.children.inorderTraversal((n,i)=>{const l=!t.serverCache.isCompleteForChild(n)&&void 0===i.value;if(!c.hasChild(n)&&!l){const l=Dn(0,t.serverCache.getNode().getImmediateChild(n),i);h=xn(e,h,new fe(n),l,r,s,o,a)}}),h}class qn{constructor(e,t){this.query_=e,this.eventRegistrations_=[];const n=this.query_._queryParams,i=new Ct(n.getIndex()),r=(s=n).loadsAllData()?new Ct(s.getIndex()):s.hasLimit()?new Tt(s):new wt(s);var s;this.processor_=function(e){return{filter:e}}(r);const o=t.serverCache,a=t.eventCache,l=i.updateFullNode(ot.EMPTY_NODE,o.getNode(),null),h=r.updateFullNode(ot.EMPTY_NODE,a.getNode(),null),c=new Ht(l,o.isFullyInitialized(),i.filtersNodes()),u=new Ht(h,a.isFullyInitialized(),r.filtersNodes());this.viewCache_=Kt(u,c),this.eventGenerator_=new Yt(this.query_)}get query(){return this.query_}}function Mn(e,t){const n=$t(e.viewCache_);return n&&(e.query._queryParams.loadsAllData()||!be(t)&&!n.getImmediateChild(me(t)).isEmpty())?n.getChild(t):null}function On(e){return 0===e.eventRegistrations_.length}function Ln(e,t,n){const i=[];if(n){(0,s.vA)(null==t,"A cancel should cancel all event registrations.");const r=e.query._path;
2e.eventRegistrations_.forEach(e=>{const t=e.createCancelEvent(n,r);t&&i.push(t)})}if(t){let n=[];for(let i=0;i<e.eventRegistrations_.length;++i){const 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 Wn(e,t,n,i){t.type===Ot.MERGE&&null!==t.source.queryId&&((0,s.vA)($t(e.viewCache_),"We should always have a full cache before handling merges"),(0,s.vA)(Gt(e.viewCache_),"Missing event cache, even though we have a server cache"));const r=e.viewCache_,o=Pn(e.processor_,r,t,n,i);var a,l;return a=e.processor_,l=o.viewCache,(0,s.vA)(l.eventCache.getNode().isIndexed(a.filter.getIndex()),"Event snap not indexed"),(0,s.vA)(l.serverCache.getNode().isIndexed(a.filter.getIndex()),"Server snap not indexed"),(0,s.vA)(o.viewCache.serverCache.isFullyInitialized()||!r.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),e.viewCache_=o.viewCache,Un(e,o.changes,o.viewCache.eventCache.getNode(),null)}function Un(e,t,n,i){const r=i?[i]:e.eventRegistrations_;return function(e,t,n,i){const r=[],s=[];return t.forEach(t=>{var n;"child_changed"===t.type&&e.index_.indexedValueChanged(t.oldSnap,t.snapshotNode)&&s.push((n=t.childName,{type:"child_moved",snapshotNode:t.snapshotNode,childName:n}))}),Vt(e,r,"child_removed",t,i,n),Vt(e,r,"child_added",t,i,n),Vt(e,r,"child_moved",s,i,n),Vt(e,r,"child_changed",t,i,n),Vt(e,r,"value",t,i,n),r}(e.eventGenerator_,t,n,r)}let jn,Bn;class Hn{constructor(){this.views=new Map}}function Yn(e,t,n,i){const r=t.source.queryId;if(null!==r){const o=e.views.get(r);return(0,s.vA)(null!=o,"SyncTree gave us an op for an invalid query."),Wn(o,t,n,i)}{let r=[];
2for(const s of e.views.values())r=r.concat(Wn(s,t,n,i));return r}}function Vn(e,t,n,i,r){const s=t._queryIdentifier,o=e.views.get(s);if(!o){let e=mn(n,r?i:null),s=!1;e?s=!0:i instanceof ot?(e=yn(n,i),s=!1):(e=ot.EMPTY_NODE,s=!1);const o=Kt(new Ht(e,s,!1),new Ht(i,r,!1));return new qn(t,o)}return o}function Kn(e,t,n,i,r,s){const o=Vn(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){const n=e.viewCache_.eventCache,i=[];n.getNode().isLeafNode()||n.getNode().forEachChild(Je,(e,t)=>{i.push(mt(e,t))});return n.isFullyInitialized()&&i.push(gt(n.getNode())),Un(e,i,n.getNode(),t)}(o,n)}function zn(e,t,n,i){const r=t._queryIdentifier,o=[];let a=[];const l=Jn(e);if("default"===r)for(const[s,h]of e.views.entries())a=a.concat(Ln(h,n,i)),On(h)&&(e.views.delete(s),h.query._queryParams.loadsAllData()||o.push(h.query));else{const t=e.views.get(r);t&&(a=a.concat(Ln(t,n,i)),On(t)&&(e.views.delete(r),t.query._queryParams.loadsAllData()||o.push(t.query)))}return l&&!Jn(e)&&o.push(new((0,s.vA)(jn,"Reference.ts has not been loaded"),jn)(t._repo,t._path)),{removed:o,events:a}}function Qn(e){const t=[];for(const n of e.views.values())n.query._queryParams.loadsAllData()||t.push(n);return t}function Gn(e,t){let n=null;for(const i of e.views.values())n=n||Mn(i,t);return n}function $n(e,t){if(t._queryParams.loadsAllData())return Zn(e);{const n=t._queryIdentifier;return e.views.get(n)}}function Xn(e,t){return null!=$n(e,t)}function Jn(e){return null!=Zn(e)}function Zn(e){for(const t of e.views.values())if(t.query._queryParams.loadsAllData())return t;return null}let ei=1;class ti{constructor(e){this.listenProvider_=e,this.syncPointTree_=new Jt(null),this.pendingWriteTree_={visibleWrites:Zt.empty(),allWrites:[],lastWriteId:-1},this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function ni(e,t,n,i,r){return function(e,t,n,i,r){(0,s.vA)(i>e.lastWriteId,"Stacking an older write on top of newer ones"),void 0===r&&(r=!0),e.allWrites.push({path:t,snap:n,writeId:i,visible:r}),r&&(e.visibleWrites=en(e.visibleWrites,t,n)),e.lastWriteId=i}(e.pendingWriteTree_,t,n,i,r),r?ci(e,new jt({fromUser:!0,fromServer:!1,queryId:null,tagged:!1},t,n)):[]}function ii(e,t,n,i){!function(e,t,n,i){(0,s.vA)(i>e.lastWriteId,"Stacking an older merge on top of newer ones"),e.allWrites.push({path:t,children:n,writeId:i,visible:!0}),e.visibleWrites=tn(e.visibleWrites,t,n),e.lastWriteId=i}(e.pendingWriteTree_,t,n,i);const r=Jt.fromObject(n);return ci(e,new Bt({fromUser:!0,fromServer:!1,queryId:null,tagged:!1},t,r))}function ri(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const i=function(e,t){for(let n=0;n<e.allWrites.length;n++){const i=e.allWrites[n];if(i.writeId===t)return i}return null}(e.pendingWriteTree_,t);if(dn(e.pendingWriteTree_,t)){let t=new Jt(null);return null!=i.snap?t=t.set(ge(),!0):M(i.children,e=>{t=t.set(new fe(e),!0)}),ci(e,new Wt(i.path,t,n))}return[]}function si(e,t,n){return ci(e,new jt({fromUser:!1,fromServer:!0,queryId:null,tagged:!1},t,n))}function oi(e,t,n,i){const r=t._path,s=e.syncPointTree_.get(r);let o=[];if(s&&("default"===t._queryIdentifier||Xn(s,t))){const a=zn(s,t,n,i);0===s.views.size&&(e.syncPointTree_=e.syncPointTree_.remove(r));const l=a.removed;o=a.events;const h=-1!==l.findIndex(e=>e._queryParams.loadsAllData()),c=e.syncPointTree_.findOnPath(r,(e,t)=>Jn(t));if(h&&!c){const t=e.syncPointTree_.subtree(r);if(!t.isEmpty()){const n=function(e){return e.fold((e,t,n)=>{if(t&&Jn(t)){return[Zn(t)]}{let e=[];return t&&(e=Qn(t)),M(n,(t,n)=>{e=e.concat(n)}),e}})}(t);for(let t=0;t<n.length;++t){const i=n[t],r=i.query,s=_i(e,i);e.listenProvider_.startListening(vi(r),pi(e,r),s.hashFn,s.onComplete)}}}if(!c&&l.length>0&&!i)if(h){const n=null;e.listenProvider_.stopListening(vi(t),n)}else l.forEach(t=>{const n=e.queryToTagMap.get(fi(t));e.listenProvider_.stopListening(vi(t),n)});!function(e,t){for(let n=0;n<t.length;++n){const i=t[n];if(!i._queryParams.loadsAllData()){const t=fi(i),n=e.queryToTagMap.get(t);e.queryToTagMap.delete(t),e.tagToQueryMap.delete(n)}}}(e,l)}return o}function ai(e,t,n){const i=t._path;let r=null,o=!1;e.syncPointTree_.foreachOnPath(i,(e,t)=>{const n=Ie(e,i);r=r||Gn(t,n),o=o||Jn(t)});let a,l=e.syncPointTree_.get(i);if(l?(o=o||Jn(l),r=r||Gn(l,ge())):(l=new Hn,e.syncPointTree_=e.syncPointTree_.set(i,l)),null!=r)a=!0;else{a=!1,r=ot.EMPTY_NODE;e.syncPointTree_.subtree(i).foreachChild((e,t)=>{const n=Gn(t,ge());n&&(r=r.updateImmediateChild(e,n))})}const h=Xn(l,t);if(!h&&!t._queryParams.loadsAllData()){const n=fi(t);(0,s.vA)(!e.queryToTagMap.has(n),"View does not exist, but we have a tag");const i=ei++;e.queryToTagMap.set(n,i),e.tagToQueryMap.set(i,n)}let c=Kn(l,t,n,un(e.pendingWriteTree_,i),r,a);if(!h&&!o){const n=$n(l,t);c=c.concat(function(e,t,n){const i=t._path,r=pi(e,t),o=_i(e,n),a=e.listenProvi
2der_.startListening(vi(t),r,o.hashFn,o.onComplete),l=e.syncPointTree_.subtree(i);if(r)(0,s.vA)(!Jn(l.value),"If we're adding a query, it shouldn't be shadowed");else{const t=l.fold((e,t,n)=>{if(!be(e)&&t&&Jn(t))return[Zn(t).query];{let e=[];return t&&(e=e.concat(Qn(t).map(e=>e.query))),M(n,(t,n)=>{e=e.concat(n)}),e}});for(let n=0;n<t.length;++n){const i=t[n];e.listenProvider_.stopListening(vi(i),pi(e,i))}}return a}(e,t,n))}return c}function li(e,t,n){const i=e.pendingWriteTree_,r=e.syncPointTree_.findOnPath(t,(e,n)=>{const i=Gn(n,Ie(e,t));if(i)return i});return gn(i,t,r,n,!0)}function hi(e,t){const n=t._path;let i=null;e.syncPointTree_.foreachOnPath(n,(e,t)=>{const r=Ie(e,n);i=i||Gn(t,r)});let r=e.syncPointTree_.get(n);r?i=i||Gn(r,ge()):(r=new Hn,e.syncPointTree_=e.syncPointTree_.set(n,r));const s=null!=i,o=s?new Ht(i,!0,!1):null;return function(e){return Gt(e.viewCache_)}(Vn(r,t,un(e.pendingWriteTree_,t._path),s?o.getNode():ot.EMPTY_NODE,s))}function ci(e,t){return ui(t,e.syncPointTree_,null,un(e.pendingWriteTree_,ge()))}function ui(e,t,n,i){if(be(e.path))return di(e,t,n,i);
2{const r=t.get(ge());null==n&&null!=r&&(n=Gn(r,ge()));let s=[];const o=me(e.path),a=e.operationForChild(o),l=t.children.get(o);if(l&&a){const e=n?n.getImmediateChild(o):null,t=kn(i,o);s=s.concat(ui(a,l,e,t))}return r&&(s=s.concat(Yn(r,e,i,n))),s}}function di(e,t,n,i){const r=t.get(ge());null==n&&null!=r&&(n=Gn(r,ge()));let s=[];return t.children.inorderTraversal((t,r)=>{const o=n?n.getImmediateChild(t):null,a=kn(i,t),l=e.operationForChild(t);l&&(s=s.concat(di(l,r,o,a)))}),r&&(s=s.concat(Yn(r,e,i,n))),s}function _i(e,t){const n=t.query,i=pi(e,n);return{hashFn:()=>{const e=function(e){return e.viewCache_.serverCache.getNode()}(t)||ot.EMPTY_NODE;return e.hash()},onComplete:t=>{if("ok"===t)return i?function(e,t,n){const i=gi(e,n);if(i){const n=mi(i),r=n.path,s=n.queryId,o=Ie(r,t);return yi(e,r,new Ut(Lt(s),o))}return[]}(e,n._path,i):function(e,t){return ci(e,new Ut({fromUser:!1,fromServer:!0,queryId:null,tagged:!1},t))}(e,n._path);{const 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");const i=new Error(e+" at "+t._path.toString()+": "+n);return i.code=e.toUpperCase(),i}(t,n);return oi(e,n,null,i)}}}}function pi(e,t){const n=fi(t);return e.queryToTagMap.get(n)}function fi(e){return e._path.toString()+"$"+e._queryIdentifier}function gi(e,t){return e.tagToQueryMap.get(t)}function mi(e){const t=e.indexOf("$");return(0,s.vA)(-1!==t&&t<e.length-1,"Bad queryKey."),{queryId:e.substr(t+1),path:new fe(e.substr(0,t))}}function yi(e,t,n){const i=e.syncPointTree_.get(t);(0,s.vA)(i,"Missing sync point for query tag that we're tracking");return Yn(i,n,un(e.pendingWriteTree_,t),null)}
2function vi(e){return e._queryParams.loadsAllData()&&!e._queryParams.isDefault()?new((0,s.vA)(Bn,"Reference.ts has not been loaded"),Bn)(e._repo,e._path):e}class Ci{constructor(e){this.node_=e}getImmediateChild(e){const t=this.node_.getImmediateChild(e);return new Ci(t)}node(){return this.node_}}class wi{constructor(e,t){this.syncTree_=e,this.path_=t}getImmediateChild(e){const t=ke(this.path_,e);return new wi(this.syncTree_,t)}node(){return li(this.syncTree_,this.path_)}}const Ti=function(e){return(e=e||{}).timestamp=e.timestamp||(new Date).getTime(),e},ki=function(e,t,n){return e&&"object"==typeof e?((0,s.vA)(".sv"in e,"Unexpected leaf node or priority contents"),"string"==typeof e[".sv"]?bi(e[".sv"],t,n):"object"==typeof e[".sv"]?Ii(e[".sv"],t):void(0,s.vA)(!1,"Unexpected server value: "+JSON.stringify(e,null,2))):e},bi=function(e,t,n){if("timestamp"===e)return n.timestamp;(0,s.vA)(!1,"Unexpected server value: "+e)},Ii=function(e,t,n){e.hasOwnProperty("increment")||(0,s.vA)(!1,"Unexpected server value: "+JSON.stringify(e,null,2));const i=e.increment;"number"!=typeof i&&(0,s.vA)(!1,"Unexpected increment value: "+i);const r=t.node();if((0,s.vA)(null!=r,"Expected ChildrenNode.EMPTY_NODE for nulls"),!r.isLeafNode())return i;const o=r.getValue();return"number"!=typeof o?i:o+i},Ei=function(e,t,n,i){return Pi(t,new wi(n,e),i)},Si=function(e,t,n){return Pi(e,new Ci(t),n)};function Pi(e,t,n){const i=e.getPriority().val(),r=ki(i,t.getImmediateChild(".priority"),n);let s;if(e.isLeafNode()){const i=e,s=ki(i.getValue(),t,n);return s!==i.getValue()||r!==i.getPriority().val()?new Xe(s,ht(r)):e}{const i=e;return s=i,r!==i.getPriority().val()&&(s=s.updatePriority(new Xe(r))),i.forEac
2hChild(Je,(e,i)=>{const r=Pi(i,t.getImmediateChild(e),n);r!==i&&(s=s.updateImmediateChild(e,r))}),s}}class Ni{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{children:{},childCount:0};this.name=e,this.parent=t,this.node=n}}function xi(e,t){let n=t instanceof fe?t:new fe(t),i=e,r=me(n);for(;null!==r;){const e=(0,s.yw)(i.node.children,r)||{children:{},childCount:0};i=new Ni(r,i,e),n=ve(n),r=me(n)}return i}function Ri(e){return e.node.value}function Ai(e,t){e.node.value=t,Oi(e)}function Di(e){return e.node.childCount>0}function Fi(e,t){M(e.node.children,(n,i)=>{t(new Ni(n,e,i))})}function qi(e,t,n,i){n&&!i&&t(e),Fi(e,e=>{qi(e,t,!0,i)}),n&&i&&t(e)}function Mi(e){return new fe(null===e.parent?e.name:Mi(e.parent)+"/"+e.name)}function Oi(e){null!==e.parent&&function(e,t,n){const i=function(e){return void 0===Ri(e)&&!Di(e)}(n),r=(0,s.gR)(e.node.children,t);i&&r?(delete e.node.children[t],e.node.childCount--,Oi(e)):i||r||(e.node.children[t]=n.node,e.node.childCount++,Oi(e))}(e.parent,e.name,e)}const Li=/[\[\].#$\/\u0000-\u001F\u007F]/,Wi=/[\[\].#$\u0000-\u001F\u007F]/,Ui=10485760,ji=function(e){return"string"==typeof e&&0!==e.length&&!Li.test(e)},Bi=function(e){return"string"==typeof e&&0!==e.length&&!Wi.test(e)},Hi=function(e){return null===e||"string"==typeof e||"number"==typeof e&&!P(e)||e&&"object"==typeof e&&(0,s.gR)(e,".sv")},Yi=function(e,t,n,i){i&&void 0===t||Vi((0,s.dI)(e,"value"),t,n)},Vi=function(e,t,n){const i=n instanceof fe?new Ne(n,e):n;if(void 0===t)throw new Error(e+"contains undefined "+Re(i));if("function"==typeof t)throw new Error(e+"contains a function "+Re(i)+" with contents = "+t.toString());if(P(t))throw new Error(e+"contains "+t.toString()+" "+Re(i));if("string"==typeof t&&t.length>Ui/3&&(0,s.OE)(t)>Ui)throw new Error(e+"contains a string greater than "+Ui+" utf8 bytes "+Re(i)+" ('"+t.substring(0,50)+"...')");if(t&&"object"==typeof t){let n=!1,r=!1;if(M(t,(t,o)=>{if(".value"===t)n=!0;else if(".priority"!==t&&".sv"!==t&&(r=!0,!ji(t)))throw new Error(e+" contains an invalid key ("+t+") "+Re(i)+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');!function(e,t){e.parts_.length>0&&(e.byteLength_+=1),e.parts_.push(t),e.byteLength_+=(0,s.OE)(t),xe(e)}(i,t),Vi(e,o,i),function(e){const t=e.parts_.pop();e.byteLength_-=(0,s.OE)(t),e.parts_.length>0&&(e.byteLength_-=1)}(i)}),n&&r)throw new Error(e+' contains ".value" child '+Re(i)+" in addition to actual children.")}},Ki=function(e,t,n,i){if(i&&void 0===t)return;const r=(0,s.dI)(e,"values");if(!t||"object"!=typeof t||Array.isArray(t))throw new Error(r+" must be an object containing the children to replace.");const o=[];M(t,(e,t)=>{const i=new fe(e);
2if(Vi(r,t,ke(n,i)),".priority"===Ce(i)&&!Hi(t))throw new Error(r+"contains an invalid value for '"+i.toString()+"', which must be a valid Firebase priority (a string, finite number, server value, or null).");o.push(i)}),function(e,t){let n,i;for(n=0;n<t.length;n++){i=t[n];const r=we(i);for(let t=0;t<r.length;t++)if(".priority"===r[t]&&t===r.length-1);else if(!ji(r[t]))throw new Error(e+"contains an invalid key ("+r[t]+") in path "+i.toString()+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"')}t.sort(Ee);let r=null;for(n=0;n<t.length;n++){if(i=t[n],null!==r&&Pe(r,i))throw new Error(e+"contains a path "+r.toString()+" that is ancestor of another path "+i.toString());r=i}}(r,o)},zi=function(e,t,n){if(!n||void 0!==t){if(P(t))throw new Error((0,s.dI)(e,"priority")+"is "+t.toString()+", but must be a valid Firebase priority (a string, finite number, server value, or null).");if(!Hi(t))throw new Error((0,s.dI)(e,"priority")+"must be a valid Firebase priority (a string, finite number, server value, or null).")}},Qi=function(e,t,n,i){if(!(i&&void 0===n||ji(n)))throw new Error((0,s.dI)(e,t)+'was an invalid key = "'+n+'". Firebase keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]").')},Gi=function(e,t,n,i){if(!(i&&void 0===n||Bi(n)))throw new Error((0,s.dI)(e,t)+'was an invalid path = "'+n+'". Paths must be non-empty strings and can\'t contain ".", "#", "$", "[", or "]"')},$i=function(e,t,n,i){n&&(n=n.replace(/^\/*\.info(\/|$)/,"/")),Gi(e,t,n,i)},Xi=function(e,t){if(".info"===me(t))throw new Error(e+" failed = Can't modify data under /.info/")},Ji=function(e,t){const n=t.path.toString();if("string"!=typeof t.repoInfo.host||0===t.repoInfo.host.length||!ji(t.repoInfo.namespace)&&"localhost"!==t.repoInfo.host.split(":")[0]||0!==n.length&&!function(e){return e&&(e=e.replace(/^\/*\.info(\/|$)/,"/")),Bi(e)}(n))throw new Error((0,s.dI)(e,"url")+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')};class Zi{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function er(e,t){let n=null;for(let i=0;i<t.length;i++){const r=t[i],s=r.getPath();null===n||Se(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 tr(e,t,n){er(e,n),ir(e,e=>Se(e,t))}function nr(e,t,n){er(e,n),ir(e,e=>Pe(e,t)||Pe(t,e))}function ir(e,t){e.recursionDepth_++;let n=!0;for(let i=0;i<e.eventLists_.length;i++){const r=e.eventLists_[i];if(r){t(r.path)?(rr(e.eventLists_[i]),e.eventLists_[i]=null):n=!1}}n&&(e.eventLists_=[]),e.recursionDepth_--}function rr(e){for(let t=0;t<e.events.length;t++){const n=e.events[t];if(null!==n){e.events[t]=null;const i=n.getEventRunner();C&&k("event: "+n.toString()),B(i)}}}const sr="repo_interrupt",or=25;class ar{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 Zi,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=Rt(),this.transactionQueueTree_=new Ni,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function lr(e,t,n){if(e.stats_=ie(e.repoInfo_),e.forceRestClient_||("object"==typeof window&&window.navigator&&window.navigator.userAgent||"").search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)>=0)e.server_=new Nt(e.repoInfo_,(t,n,i,r)=>{ur(e,t,n,i,r)},e.authTokenProvider_,e.appCheckProvider_),setTimeout(()=>dr(e,!0),0);else{if(null!=n){if("object"!=typeof n)throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{(0,s.As)(n)}catch(i){throw new Error("Invalid authOverride provided: "+i)}}e.persistentConnection_=new Fe(e.repoInfo_,t,(t,n,i,r)=>{ur(e,t,n,i,r)},t=>{dr(e,t)},t=>{!function(e,t){M(t,(t,n)=>{_r(e,t,n)})}(e,t)},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){const n=e.toString();
2return ne[n]||(ne[n]=t()),ne[n]}(e.repoInfo_,()=>new Mt(e.stats_,e.server_)),e.infoData_=new xt,e.infoSyncTree_=new ti({startListening:(t,n,i,r)=>{let s=[];const o=e.infoData_.getNode(t._path);return o.isEmpty()||(s=si(e.infoSyncTree_,t._path,o),setTimeout(()=>{r("ok")},0)),s},stopListening:()=>{}}),_r(e,"connected",!1),e.serverSyncTree_=new ti({startListening:(t,n,i,r)=>(e.server_.listen(t,i,n,(n,i)=>{const s=r(n,i);nr(e.eventQueue_,t._path,s)}),[]),stopListening:(t,n)=>{e.server_.unlisten(t,n)}})}function hr(e){const t=e.infoData_.getNode(new fe(".info/serverTimeOffset")).val()||0;return(new Date).getTime()+t}function cr(e){return Ti({timestamp:hr(e)})}function ur(e,t,n,i,r){e.dataUpdateCount++;const o=new fe(t);n=e.interceptServerDataCallback_?e.interceptServerDataCallback_(t,n):n;let a=[];if(r)if(i){const t=(0,s.Tj)(n,e=>ht(e));a=function(e,t,n,i){const r=gi(e,i);if(r){const i=mi(r),s=i.path,o=i.queryId,a=Ie(s,t),l=Jt.fromObject(n);return yi(e,s,new Bt(Lt(o),a,l))}return[]}(e.serverSyncTree_,o,t,r)}else{const t=ht(n);a=function(e,t,n,i){const r=gi(e,i);if(null!=r){const i=mi(r),s=i.path,o=i.queryId,a=Ie(s,t);return yi(e,s,new jt(Lt(o),a,n))}return[]}(e.serverSyncTree_,o,t,r)}else if(i){const t=(0,s.Tj)(n,e=>ht(e));a=function(e,t,n){const i=Jt.fromObject(n);return ci(e,new Bt({fromUser:!1,fromServer:!0,queryId:null,tagged:!1},t,i))}(e.serverSyncTree_,o,t)}else{const t=ht(n);a=si(e.serverSyncTree_,o,t)}let l=o;a.length>0&&(l=br(e,o)),nr(e.eventQueue_,l,a)}function dr(e,t){_r(e,"connected",t),!1===t&&function(e){Cr(e,"onDisconnectEvents");const t=cr(e),n=Rt();Ft(e.onDisconnect_,ge(),(i,r)=>{const s=Ei(i,r,e.serverSyncTree_,t);At(n,i,s)});let i=[];Ft(n,ge(),(t,n)=>{i=i.concat(si(e.serverSyncTree_,t,n));const r=Nr(e,t);br(e,r)}),e.onDisconnect_=Rt(),nr(e.eventQueue_,ge(),i)}(e)}function _r(e,t,n){const i=new fe("/.info/"+t),r=ht(n);e.infoData_.updateSnapshot(i,r);const s=si(e.infoSyncTree_,i,r);nr(e.eventQueue_,i,s)}function pr(e){return e.nextWriteId_++}function fr(e,t,n,i,r){Cr(e,"set",{path:t.toString(),value:n,priority:i});const s=cr(e),o=ht(n,i),a=li(e.serverSyncTree_,t),l=Si(o,a,s),h=pr(e),c=ni(e.serverSyncTree_,t,l,h,!0);er(e.eventQueue_,c),e.server_.put(t.toString(),o.val(!0),(n,i)=>{const s="ok"===n;s||S("set at "+t+" failed: "+n);const o=ri(e.serverSyncTree_,h,!s);nr(e.eventQueue_,t,o),wr(e,r,n,i)});const u=Nr(e,t);br(e,u),nr(e.eventQueue_,u,[])}function gr(e,t,n){e.server_.onDisconnectCancel(t.toString(),(i,r)=>{"ok"===i&&Dt(e.onDisconnect_,t),wr(e,n,i,r)})}function mr(e,t,n,i){const r=ht(n);e.server_.onDisconnectPut(t.toString(),r.val(!0),(n,s)=>{"ok"===n&&At(e.onDisconnect_,t,r),wr(e,i,n,s)})}function yr(e,t,n){let i;i=".info"===me(t._path)?oi(e.infoSyncTree_,t,n):oi(e.serverSyncTree_,t,n),tr(e.eventQueue_,t._path,i)}function vr(e){e.persistentConnection_&&e.persistentConnection_.interrupt(sr)}function Cr(e){let t="";e.persistentConnection_&&(t=e.persistentConnection_.id+":");for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];k(t,...i)}function wr(e,t,n,i){t&&B(()=>{if("ok"===n)t(null);else{const e=(n||"error").toUpperCase();let r=e;i&&(r+=": "+i);const s=new Error(r);s.code=e,t(s)}})}function Tr(e,t,n){return li(e.serverSyncTree_,t,n)||ot.EMPTY_NODE}function kr(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.transactionQueueTree_;if(t||Pr(e,t),Ri(t)){const n=Er(e,t);(0,s.vA)(n.length>0,"Sending zero length transaction queue");n.every(e=>0===e.status)&&function(e,t,n){const i=n.map(e=>e.currentWriteId),r=Tr(e,t,i);let o=r;const a=r.hash();for(let c=0;c<n.length;c++){const e=n[c];(0,s.vA)(0===e.status,"tryToSendTransactionQueue_: items in queue should all be run."),e.status=1,e.retryCount++;const i=Ie(t,e.path);o=o.updateChild(i,e.currentOutputSnapshotRaw)}const l=o.val(!0),h=t;e.server_.put(h.toString(),l,i=>{Cr(e,"transaction put response",{path:h.toString(),status:i});let r=[];if("ok"===i){const i=[];for(let t=0;t<n.length;t++)n[t].status=2,r=r.concat(ri(e.serverSyncTree_,n[t].currentWriteId)),n[t].onComplete&&i.push(()=>n[t].onComplete(null,!0,n[t].currentOutputSnapshotResolved)),n[t].unwatcher();Pr(e,xi(e.transactionQueueTree_,t)),kr(e,e.transactionQueueTree_),nr(e.eventQueue_,t,r);for(let e=0;e<i.length;e++)B(i[e])}else{if("datastale"===i)for(let e=0;e<n.length;e++)3===n[e].status?n[e].status=4:n[e].status=0;else{S("transaction at "+h.toString()+" failed: "+i);for(let e=0;e<n.length;e++)n[e].status=4,n[e].abortReason=i}br(e,t)}},a)}(e,Mi(t),n)}else Di(t)&&Fi(t,t=>{kr(e,t)})}function br(e,t){const n=Ir(e,t),i=Mi(n);return function(e,t,n){if(0===t.length)return;const i=[];let r=[];const o=t.filter(e=>0===e.status),a=o.map(e=>e.currentWriteId);for(let l=0;l<t.length;l++){const o=t[l],h=Ie(n,o.path);let c,u=!1;if((0,s.vA)(null!==h,"rerunTransactionsUnderNode_: relativePath should not be null."),4===o.status)u=!0,c=o.abortReason,r=r.concat(ri(e.serverSyncTree_,o.currentWriteId,!0));else if(0===o.status)if(o.retryCount>=or)u=!0,c="maxretry",r=r.concat(ri(e.serverSyncTree_,o.currentWriteId,!0));else{const n=Tr(e,o.path,a);o.currentInputSnapshot=n;const i=t[l].update(n.val());if(void 0!==i){Vi("transaction failed: Data returned ",i,o.path);let t=ht(i);"object"==typeof i&&null!=i&&(0,s.gR)(i,".priority")||(t=t.updatePriority(n.getPri
2ority()));const l=o.currentWriteId,h=cr(e),c=Si(t,n,h);o.currentOutputSnapshotRaw=t,o.currentOutputSnapshotResolved=c,o.currentWriteId=pr(e),a.splice(a.indexOf(l),1),r=r.concat(ni(e.serverSyncTree_,o.path,c,o.currentWriteId,o.applyLocally)),r=r.concat(ri(e.serverSyncTree_,l,!0))}else u=!0,c="nodata",r=r.concat(ri(e.serverSyncTree_,o.currentWriteId,!0))}nr(e.eventQueue_,n,r),r=[],u&&(t[l].status=2,function(e){setTimeout(e,Math.floor(0))}(t[l].unwatcher),t[l].onComplete&&("nodata"===c?i.push(()=>t[l].onComplete(null,!1,t[l].currentInputSnapshot)):i.push(()=>t[l].onComplete(new Error(c),!1,null))))}Pr(e,e.transactionQueueTree_);for(let s=0;s<i.length;s++)B(i[s]);kr(e,e.transactionQueueTree_)}(e,Er(e,n),i),i}function Ir(e,t){let n,i=e.transactionQueueTree_;for(n=me(t);null!==n&&void 0===Ri(i);)i=xi(i,n),n=me(t=ve(t));return i}function Er(e,t){const n=[];return Sr(e,t,n),n.sort((e,t)=>e.order-t.order),n}function Sr(e,t,n){const i=Ri(t);if(i)for(let r=0;r<i.length;r++)n.push(i[r]);Fi(t,t=>{Sr(e,t,n)})}function Pr(e,t){const n=Ri(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,Ai(t,n.length>0?n:void 0)}Fi(t,t=>{Pr(e,t)})}function Nr(e,t){const n=Mi(Ir(e,t)),i=xi(e.transactionQueueTree_,t);return function(e,t,n){let i=n?e:e.parent;for(;null!==i;){if(t(i))return!0;i=i.parent}}(i,t=>{xr(e,t)}),xr(e,i),qi(i,t=>{xr(e,t)}),n}function xr(e,t){const n=Ri(t);if(n){const i=[];let r=[],o=-1;for(let t=0;t<n.length;t++)3===n[t].status||(1===n[t].status?((0,s.vA)(o===t-1,"All SENT items should be at beginning of queue."),o=t,n[t].status=3,n[t].abortReason="set"):((0,s.vA)(0===n[t].status,"Unexpected transaction status in abort"),n[t].unwatcher(),r=r.concat(ri(e.serverSyncTree_,n[t].currentWriteId,!0)),n[t].onComplete&&i.push(n[t].onComplete.bind(null,new Error("set"),!1,null))));-1===o?Ai(t,void 0):n.length=o+1,nr(e.eventQueue_,Mi(t),r);for(let e=0;e<i.length;e++)B(i[e])}}const Rr=function(e,t){const n=Ar(e),i=n.namespace;"firebase.com"===n.domain&&E(n.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),i&&"undefined"!==i||"localhost"===n.domain||E("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),n.secure||"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&S("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().");const r="ws"===n.scheme||"wss"===n.scheme;return{repoInfo:new J(n.host,n.secure,i,r,t,"",i!==n.subdomain),path:new fe(n.pathString)}},Ar=function(e){let t="",n="",i="",r="",s="",o=!0,a="https",l=443;if("string"==typeof e){let h=e.indexOf("//");h>=0&&(a=e.substring(0,h-1),e=e.substring(h+2));let c=e.indexOf("/");-1===c&&(c=e.length);let u=e.indexOf("?");-1===u&&(u=e.length),t=e.substring(0,Math.min(c,u)),c<u&&(r=function(e){let t="";const n=e.split("/");for(let r=0;r<n.length;r++)if(n[r].length>0){let e=n[r];try{e=decodeURIComponent(e.replace(/\+/g," "))}catch(i){}t+="/"+e}return t}(e.substring(c,u)));const d=function(e){const t={};"?"===e.charAt(0)&&(e=e.substring(1));for(const n of e.split("&")){if(0===n.length)continue;const i=n.split("=");2===i.length?t[decodeURIComponent(i[0])]=decodeURIComponent(i[1]):S("Invalid query segment '".concat(n,"' in query '").concat(e,"'"))}return t}(e.substring(Math.min(e.length,u)));h=t.indexOf(":"),h>=0?(o="https"===a||"wss"===a,l=parseInt(t.substring(h+1),10)):h=t.length;const _=t.slice(0,h);if("localhost"===_.toLowerCase())n="localhost";else if(_.split(".").length<=2)n=_;else{const 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:l,domain:n,subdomain:i,secure:o,scheme:a,pathString:r,namespace:s}};class Dr{constructor(e,t,n,i){this.eventType=e,this.eventRegistration=t,this.snapshot=n,this.prevName=i}getPath(){const 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,s.As)(this.snapshot.exportVal())}}class Fr{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"}}class qr{constructor(e,t){this.snapshotCallback=e,this.cancelCallback=t}onValue(e,t){this.snapshotCallback.call(null,e,t)}onCancel(e){return(0,s.vA)(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}}class Mr{constructor(e,t){this._repo=e,this._path=t}cancel(){const e=new s.cY;return gr(this._repo,this._path,e.wrapCallback(()=>{})),e.promise}remove(){Xi("OnDisconnect.remove",this._path);const e=new s.cY;return mr(this._repo,this._path,null,e.wrapCallback(()=>{})),e.promise}set(e){Xi("OnDisconnect.set",this._path),Yi("OnDisconnect.set",e,this._path,!1);const t=new s.cY;return mr(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}setWithPriority(e,t){Xi("OnDisconnect.setWithPriority",this._path),Yi("OnDisconnect.setWithPriority",e,this._path,!1),zi("OnDisconnect.setWithPriority",t,!1);const n=new s.cY;return function(e,t,n,i,r){const s=ht(n,i);e.server_.onDisconnectPut(t.toString(),s.val(!0),(n,i)=>{"ok"===n&&At(e.onDisconnect_,t,s),wr(0,r,n,i)})}(this._repo,this._path,e,t,n.wrapCallback(()=>{})),n.promise}update(e){Xi("OnDisconnect.update",this._path),Ki("OnDisconnect.update",e,this._path,!1);const t=new s.cY;return function(e,t,n,i){if((0,s.Im)(n))return k("onDisconnect().update() called with empty data. Don't do anything."),void wr(0,i,"ok",void 0);e.server_.onDisconnectMerge(t.toString(),n,(r,s)=>{"ok"===r&&M(n,(n,i)=>{const r=ht(i);At(e.onDisconnect_,ke(t,n),r)}),wr(0,i,r,s)})}(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}}class Or{constructor(e,t,n,i){this._repo=e,this._path=t,this._queryParams=n,this._orderByCalled=i}get key(){return be(this._path)?null:Ce(this._path)}get ref(){return new jr(this._repo,this._path)}get _queryIdentifier(){const e=Pt(this._queryParams),t=F(e);return"{}"===t?"default":t}get _queryObject(){return Pt(this._queryParams)}isEqual(e){if(!((e=(0,s.Ku)(e))instanceof Or))return!1;const t=this._repo===e._repo,n=Se(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)}}function Lr(e,t){if(!0===e._orderByCalled)throw new Error(t+": You can't combine multiple orderBy calls.")}function Wr(e){let t=null,n=null;if(e.hasStart()&&(t=e.getIndexStartValue()),e.hasEnd()&&(n=e.getIndexEndValue()),e.getIndex()===We){const i="Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().",r="Query: When ordering by key, the argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() must be a string.";if(e.hasStart()){if(e.getIndexStartName()!==N)throw new Error(i);if("string"!=typeof t)throw new Error(r)}if(e.hasEnd()){if(e.getIndexEndName()!==x)throw new Error(i);if("string"!=typeof n)throw new Error(r)}}else if(e.getIndex()===Je){if(null!=t&&!Hi(t)||null!=n&&!Hi(n))throw new Error("Query: When ordering by priority, the first argument passed to startAt(), startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value (null, a number, or a string).")}else if((0,s.vA)(e.getIndex()instanceof ct||e.getIndex()===ut,"unknown index type."),null!=t&&"object"==typeof t||null!=n&&"object"==typeof n)throw new Error("Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() cannot be an object.")}function Ur(e){if(e.hasStart()&&e.hasEnd()&&e.hasLimit()&&!e.hasAnchoredLimit())throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use limitToFirst() or limitToLast() instead.")}class jr extends Or{constructor(e,t){super(e,t,new kt,!1)}get parent(){const e=Te(this._path);return null===e?null:new jr(this._repo,e)}get root(){let e=this;for(;null!==e.parent;)e=e.parent;return e}}class Br{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){const t=new fe(e),n=Vr(this.ref,e);return new Br(this._node.getChild(t),n,Je)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(e){if(this._node.isLeafNode())return!1;return!!this._node.forEachChild(this._index,(t,n)=>e(new Br(n,Vr(this.ref,t),Je)))}hasChild(e){const t=new fe(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 Hr(e,t){return(e=(0,s.Ku)(e))._checkNotDeleted("ref"),void 0!==t?Vr(e._root,t):e._root}function Yr(e,t){(e=(0,s.Ku)(e))._checkNotDeleted("refFromURL");const n=Rr(t,e._repo.repoInfo_.nodeAdmin);Ji("refFromURL",n);const i=n.repoInfo;return e._repo.repoInfo_.isCustomHost()||i.host===e._repo.repoInfo_.host||E("refFromURL: Host name does not match the current database: (found "+i.host+" but expected "+e._repo.repoInfo_.host+")"),Hr(e,n.path.toString())}function Vr(e,t){return null===me((e=(0,s.Ku)(e))._path)?$i("child","path",t,!1):Gi("child","path",t,!1),new jr(e._repo,ke(e._path,t))}function Kr(e){return e=(0,s.Ku)(e),new Mr(e._repo,e._path)}function zr(e,t){e=(0,s.Ku)(e),Xi("push",e._path),Yi("push",t,e._path,!0);const n=hr(e._repo),i=_t(n),r=Vr(e,i),o=Vr(e,i);let a;return a=null!=t?Gr(o,t).then(()=>o):Promise.resolve(o),r.then=a.then.bind(a),r.catch=a.then.bind(a,void 0),r}function Qr(e){return Xi("remove",e._path),Gr(e,null)}function Gr(e,t){e=(0,s.Ku)(e),Xi("set",e._path),Yi("set",t,e._path,!1);const n=new s.cY;return fr(e._repo,e._path,t,null,n.wrapCallback(()=>{})),n.promise}function $r(e,t){e=(0,s.Ku)(e),Xi("setPriority",e._path),zi("setPriority",t,!1);const n=new s.cY;return fr(e._repo,ke(e._path,".priority"),t,null,n.wrapCallback(()=>{})),n.promise}function Xr(e,t,n){if(Xi("setWithPriority",e._path),Yi("setWithPriority",t,e._path,!1),zi("setWithPriority",n,!1),".length"===e.key||".keys"===e.key)throw"setWithPriority failed: "+e.key+" is a read-only object.";const i=new s.cY;return fr(e._repo,e._path,t,n,i.wrapCallback(()=>{})),i.promise}function Jr(e,t){Ki("update",t,e._path,!1);const n=new s.cY;return function(e,t,n,i){Cr(e,"update",{path:t.toString(),value:n});let r=!0;const s=cr(e),o={};if(M(n,(n,i)=>{r=!1,o[n]=Ei(ke(t,n),ht(i),e.serverSyncTree_,s)}),r)k("update() called with empty data. Don't do anything."),wr(0,i,"ok",void 0);else{const r=pr(e),s=ii(e.serverSyncTree_,t,o,r);er(e.eventQueue_,s),e.server_.merge(t.toString(),n,(n,s)=>{const o="ok"===n;o||S("update at "+t+" failed: "+n);const a=ri(e.serverSyncTree_,r,!o),l=a.length>0?br(e,t):t;nr(e.eventQueue_,l,a),wr(0,i,n,s)}),M(n,n=>{const i=Nr(e,ke(t,n));br(e,i)}),nr(e.eventQueue_,t,[])}}(e._repo,e._path,t,n.wrapCallback(()=>{})),n.promise}function Zr(e){return function(e,t){const n=hi(e.serverSyncTree_,t);return null!=n?Promise.resolve(n):e.server_.get(t).then(n=>{const i=ht(n).withIndex(t._queryParams.getIndex()),r=si(e.serverSyncTree_,t._path,i);return tr(e.eventQueue_,t._path,r),Promise.resolve(i)},n=>(Cr(e,"get for query "+(0,s.As)(t)+" failed: "+n),Promise.reject(new Error(n))))}((e=(0,s.Ku)(e))._repo,e).then(t=>new Br(t,new jr(e._repo,e._path),e._queryParams.getIndex()))}class es{constructor(e){this.callbackContext=e}respondsTo(e){return"value"===e}createEvent(e,t){const n=t._queryParams.getIndex();return new Dr("value",this,new Br(e.snapshotNode,new jr(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 Fr(this,e,t):null}matches(e){return e instanceof es&&(!e.callbackContext||!this.callbackContext||e.callbackContext.matches(this.callbackContext))}hasAnyCallback(){return null!==this.callbackContext}}class ts{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 Fr(this,e,t):null}createEvent(e,t){(0,s.vA)(null!=e.childName,"Child events should have a childName.");const n=Vr(new jr(t._repo,t._path),e.childName),i=t._queryParams.getIndex();return new Dr(e.type,this,new Br(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 ts&&(this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext)))}hasAnyCallback(){return!!this.callbackContext}}function ns(e,t,n,i,r){let s;if("object"==typeof i&&(s=void 0,r=i),"function"==typeof i&&(s=i),r&&r.onlyOnce){const t=n,i=(n,i)=>{yr(e._repo,e,a),t(n,i)};i.userCallback=n.userCallback,i.context=n.context,n=i}const o=new qr(n,s||void 0),a="value"===t?new es(o):new ts(t,o);return function(e,t,n){let i;i=".info"===me(t._path)?ai(e.infoSyncTree_,t,n):ai(e.serverSyncTree_,t,n),tr(e.eventQueue_,t._path,i)}(e._repo,e,a),()=>yr(e._repo,e,a)}function is(e,t,n,i){return ns(e,"value",t,n,i)}function rs(e,t,n,i){return ns(e,"child_added",t,n,i)}function ss(e,t,n,i){return ns(e,"child_changed",t,n,i)}function os(e,t,n,i){return ns(e,"child_moved",t,n,i)}function as(e,t,n,i){return ns(e,"child_removed",t,n,i)}
2function ls(e,t,n){let i=null;const r=n?new qr(n):null;"value"===t?i=new es(r):t&&(i=new ts(t,r)),yr(e._repo,e,i)}class hs{}class cs extends hs{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){Yi("endAt",this._value,e._path,!0);const t=It(e._queryParams,this._value,this._key);if(Ur(t),Wr(t),e._queryParams.hasEnd())throw new Error("endAt: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new Or(e._repo,e._path,t,e._orderByCalled)}}function us(e,t){return Qi("endAt","key",t,!0),new cs(e,t)}class ds extends hs{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){Yi("endBefore",this._value,e._path,!1);const t=function(e,t,n){let i,r;return e.index_===We?("string"==typeof t&&(t=ft(t)),r=It(e,t,n)):(i=null==n?N:ft(n),r=It(e,t,i)),r.endBeforeSet_=!0,r}(e._queryParams,this._value,this._key);if(Ur(t),Wr(t),e._queryParams.hasEnd())throw new Error("endBefore: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new Or(e._repo,e._path,t,e._orderByCalled)}}function _s(e,t){return Qi("endBefore","key",t,!0),new ds(e,t)}class ps extends hs{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){Yi("startAt",this._value,e._path,!0);const t=bt(e._queryParams,this._value,this._key);if(Ur(t),Wr(t),e._queryParams.hasStart())throw new Error("startAt: Starting point was already set (by another call to startAt, startBefore or equalTo).");return new Or(e._repo,e._path,t,e._orderByCalled)}}function fs(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1?arguments[1]:void 0;return Qi("startAt","key",t,!0),new ps(e,t)}class gs extends hs{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){Yi("startAfter",this._value,e._path,!1);const t=function(e,t,n){let i;if(e.index_===We)"string"==typeof t&&(t=pt(t)),i=bt(e,t,n);else{let r;r=null==n?x:pt(n),i=bt(e,t,r)}return i.startAfterSet_=!0,i}(e._queryParams,this._value,this._key);if(Ur(t),Wr(t),e._queryParams.hasStart())throw new Error("startAfter: Starting point was already set (by another call to startAt, startAfter, or equalTo).");return new Or(e._repo,e._path,t,e._orderByCalled)}}function ms(e,t){return Qi("startAfter","key",t,!0),new gs(e,t)}class ys extends hs{constructor(e){super(),this._limit=e}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToFirst: Limit was already set (by another call to limitToFirst or limitToLast).");return new Or(e._repo,e._path,function(e,t){const n=e.copy();return n.limitSet_=!0,n.limit_=t,n.viewFrom_="l",n}(e._queryParams,this._limit),e._orderByCalled)}}function vs(e){if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToFirst: First argument must be a positive integer.");return new ys(e)}class Cs extends hs{constructor(e){super(),this._limit=e}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToLast: Limit was already set (by another call to limitToFirst or limitToLast).");return new Or(e._repo,e._path,function(e,t){const n=e.copy();return n.limitSet_=!0,n.limit_=t,n.viewFrom_="r",n}(e._queryParams,this._limit),e._orderByCalled)}}function ws(e){if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToLast: First argument must be a positive integer.");return new Cs(e)}class Ts extends hs{constructor(e){super(),this._path=e}_apply(e){Lr(e,"orderByChild");const t=new fe(this._path);if(be(t))throw new Error("orderByChild: cannot pass in empty path. Use orderByValue() instead.");const n=new ct(t),i=Et(e._queryParams,n);return Wr(i),new Or(e._repo,e._path,i,!0)}}function ks(e){if("$key"===e)throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');if("$priority"===e)throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');if("$value"===e)throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');return Gi("orderByChild","path",e,!1),new Ts(e)}class bs extends hs{_apply(e){Lr(e,"orderByKey");const t=Et(e._queryParams,We);return Wr(t),new Or(e._repo,e._path,t,!0)}}function Is(){return new bs}class Es extends hs{_apply(e){Lr(e,"orderByPriority");const t=Et(e._queryParams,Je);return Wr(t),new Or(e._repo,e._path,t,!0)}}function Ss(){return new Es}class Ps extends hs{_apply(e){Lr(e,"orderByValue");const t=Et(e._queryParams,ut);return Wr(t),new Or(e._repo,e._path,t,!0)}}function Ns(){return new Ps}class xs extends hs{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){if(Yi("equalTo",this._value,e._path,!1),e._queryParams.hasStart())throw new Error("equalTo: Starting point was already set
2(by another call to startAt/startAfter or equalTo).");if(e._queryParams.hasEnd())throw new Error("equalTo: Ending point was already set (by another call to endAt/endBefore or equalTo).");return new cs(this._value,this._key)._apply(new ps(this._value,this._key)._apply(e))}}function Rs(e,t){return Qi("equalTo","key",t,!0),new xs(e,t)}function As(e){let t=(0,s.Ku)(e);for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];for(const s of i)t=s._apply(t);return t}!function(e){(0,s.vA)(!jn,"__referenceConstructor has already been defined"),jn=e}(jr),function(e){(0,s.vA)(!Bn,"__referenceConstructor has already been defined"),Bn=e}(jr);const Ds="FIREBASE_DATABASE_EMULATOR_HOST",Fs={};let qs=!1;function Ms(e,t,n,i,r){let s=i||e.options.databaseURL;void 0===s&&(e.options.projectId||E("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),k("Using default host for project ",e.options.projectId),s="".concat(e.options.projectId,"-default-rtdb.firebaseio.com"));let o,a,l=Rr(s,r),h=l.repoInfo;"undefined"!=typeof process&&(a={}[Ds]),a?(o=!0,s="http://".concat(a,"?ns=").concat(h.namespace),l=Rr(s,r),h=l.repoInfo):o=!l.repoInfo.secure;const c=r&&o?new K(K.OWNER):new V(e.name,e.options,t);Ji("Invalid Firebase Database URL",l),be(l.path)||E("Database URL must point to the root of a Firebase Database (not including a child path).");const u=function(e,t,n,i){let r=Fs[t.name];r||(r={},Fs[t.name]=r);let s=r[e.toURLString()];s&&E("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.");return s=new ar(e,qs,n,i),r[e.toURLString()]=s,s}(h,e,c,new Y(e.name,n));return new Os(u,e)}class Os{constructor(e,t){this._repoInternal=e,this.app=t,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(lr(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new jr(this._repo,ge())),this._rootInternal}_delete(){return null!==this._rootInternal&&(!function(e,t){const n=Fs[t];n&&n[e.key]===e||E("Database ".concat(t,"(").concat(e.repoInfo_,") has already been deleted.")),vr(e),delete n[e.key]}(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){null===this._rootInternal&&E("Cannot call "+e+" on a deleted database.")}}function Ls(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:(0,i.Sx)(),t=arguments.length>1?arguments[1]:void 0;return(0,i.j6)(e,"database").getImmediate({identifier:t})}function Ws(e,t,n){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};(e=(0,s.Ku)(e))._checkNotDeleted("useEmulator"),e._instanceStarted&&E("Cannot call useEmulator() after instance has already been initialized.");const r=e._repoInternal;let o;if(r.repoInfo_.nodeAdmin)i.mockUserToken&&E('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),o=new K(K.OWNER);else if(i.mockUserToken){const t="string"==typeof i.mockUserToken?i.mockUserToken:(0,s.Fy)(i.mockUserToken,e.app.options.projectId);o=new K(t)}!function(e,t,n,i){e.repoInfo_=new J("".concat(t,":").concat(n),!1,e.repoInfo_.namespace,e.repoInfo_.webSocketOnly,e.repoInfo_.nodeAdmin,e.repoInfo_.persistenceKey,e.repoInfo_.includeNamespaceInQueryParams),i&&(e.authTokenProvider_=i)}(r,t,n,o)}function Us(e){(e=(0,s.Ku)(e))._checkNotDeleted("goOffline"),vr(e._repo)}function js(e){var t;(e=(0,s.Ku)(e))._checkNotDeleted("goOnline"),(t=e._repo).persistentConnection_&&t.persistentConnection_.resume(sr)}function Bs(e,t){T(e,t)}const Hs={".sv":"timestamp"};function Ys(){return Hs}function Vs(e){return{".sv":{increment:e}}}class Ks{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}}function zs(e,t,n){var i;if(e=(0,s.Ku)(e),Xi("Reference.transaction",e._path),".length"===e.key||".keys"===e.key)throw"Reference.transaction failed: "+e.key+" is a read-only object.";const r=null===(i=null==n?void 0:n.applyLocally)||void 0===i||i,o=new s.cY,a=is(e,()=>{});return function(e,t,n,i,r,o){Cr(e,"transaction on "+t);const a={path:t,update:n,onComplete:i,status:null,order:m(),applyLocally:o,retryCount:0,unwatcher:r,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},l=Tr(e,t,void 0);a.currentInputSnapshot=l;const h=a.update(l.val());if(void 0===h)a.unwatcher(),a.currentOutputSnapshotRaw=null,a.currentOutputSnapshotResolved=null,a.onComplete&&a.onComplete(null,!1,a.currentInputSnapshot);else{Vi("transaction failed: Data returned ",h,a.path),a.status=0;const n=xi(e.transactionQueueTree_,t),i=Ri(n)||[];let r;i.push(a),Ai(n,i),"object"==typeof h&&null!==h&&(0,s.gR)(h,".priority")?(r=(0,s.yw)(h,".priority"),(0,s.vA)(Hi(r),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.")):r=(li(e.serverSyncTree_,t)||ot.EMPTY_NODE).getPriority().val();const o=cr(e),c=ht(h,r),u=Si(c,l,o);a.currentOutputSnapshotRaw=c,a.currentOutputSnapshotResolved=u,a.currentWriteId=pr(e);const d=ni(e.serverSyncTree_,t,u,a.currentWriteId,a.applyLocally);nr(e.eventQueue_,t,d),kr(e,e.transactionQueueTree_)}}(e._repo,e._path,t,(t,n,i)=>{let r=null;t?o.reject(t):(r=new Br(i,new jr(e._repo,e._path),Je),o.resolve(new Ks(n,r)))},a,r),o.promise}Fe.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)},Fe.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)};const Qs=function(e){const t=Fe.prototype.put;return Fe.prototype.put=function(n,i,r,s){void 0!==s&&(s=e()),t.call(this,n,i,r,s)},function(){Fe.prototype.put=t}},Gs=function(e){!function(e){qs=e}(e)};var $s;c(i.MF),(0,i.om)(new r.uA("database",(e,t)=>{let{instanceIdentifier:n}=t;return Ms(e.getProvider("app").getImmediate(),e.getProvider("auth-internal"),e.getProvider("app-check-internal"),n)},"PUBLIC").setMultipleInstances(!0)),(0,i.KO)(a,l,$s),(0,i.KO)(a,l,"esm2017")}}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.