firebase 13.2.0-eap-sql.a9a137e67 → 13.2.0-eap-sql.b903ef716

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/app/dist/esm/index.esm.js +1 -1
  2. package/app/dist/index.cjs.js +1 -1
  3. package/app/dist/index.mjs +1 -1
  4. package/compat/app/dist/esm/index.esm.js +1 -1
  5. package/compat/app/dist/index.cjs.js +1 -1
  6. package/compat/app/dist/index.mjs +1 -1
  7. package/compat/dist/esm/index.esm.js +2 -2
  8. package/compat/dist/index.node.cjs +2 -2
  9. package/compat/dist/index.rn.cjs.js +2 -2
  10. package/firebase-ai.js +1 -1
  11. package/firebase-analytics-compat.js +1 -1
  12. package/firebase-analytics.js +1 -1
  13. package/firebase-app-check-compat.js +1 -1
  14. package/firebase-app-check.js +1 -1
  15. package/firebase-app-compat.js +2 -2
  16. package/firebase-app.js +5 -5
  17. package/firebase-auth-compat.js +1 -1
  18. package/firebase-auth-cordova.js +1 -1
  19. package/firebase-auth-web-extension.js +1 -1
  20. package/firebase-auth.js +1 -1
  21. package/firebase-compat.js +6 -6
  22. package/firebase-crashlytics.js +1 -1
  23. package/firebase-data-connect.js +1 -1
  24. package/firebase-database-compat.js +1 -1
  25. package/firebase-database.js +1 -1
  26. package/firebase-firestore-compat.js +2 -2
  27. package/firebase-firestore-lite-pipelines.js +1 -1
  28. package/firebase-firestore-lite.js +1 -1
  29. package/firebase-firestore-pipelines.js +1 -1
  30. package/firebase-firestore.js +1 -1
  31. package/firebase-functions-compat.js +1 -1
  32. package/firebase-functions.js +1 -1
  33. package/firebase-installations-compat.js +1 -1
  34. package/firebase-installations.js +1 -1
  35. package/firebase-messaging-compat.js +1 -1
  36. package/firebase-messaging-sw.js +1 -1
  37. package/firebase-messaging.js +1 -1
  38. package/firebase-performance-compat.js +1 -1
  39. package/firebase-performance-standalone-compat.js +7 -7
  40. package/firebase-performance.js +1 -1
  41. package/firebase-remote-config-compat.js +1 -1
  42. package/firebase-remote-config.js +1 -1
  43. package/firebase-sql.js +1 -1
  44. package/firebase-sql.js.map +1 -1
  45. package/firebase-storage-compat.js +1 -1
  46. package/firebase-storage.js +1 -1
  47. package/package.json +31 -31
@@ -1,2 +1,2 @@
1
- ((e,t)=>{"object"==typeof exports&&"undefined"!=typeof module?t(require("@firebase/app-compat"),require("@firebase/app")):"function"==typeof define&&define.amd?define(["@firebase/app-compat","@firebase/app"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).firebase,e.firebase.INTERNAL.modularAPIs)})(this,function(yo,wo){try{!(function(){function r(t){var n=[];let r=0;for(let i=0;i<t.length;i++){let e=t.charCodeAt(i);e<128?n[r++]=e:(e<2048?n[r++]=e>>6|192:(55296==(64512&e)&&i+1<t.length&&56320==(64512&t.charCodeAt(i+1))?(e=65536+((1023&e)<<10)+(1023&t.charCodeAt(++i)),n[r++]=e>>18|240,n[r++]=e>>12&63|128):n[r++]=e>>12|224,n[r++]=e>>6&63|128),n[r++]=63&e|128)}return n}let q={NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"},f=function(e,t){if(!e)throw W(t)},W=function(e){return new Error("Firebase Database ("+q.SDK_VERSION+") INTERNAL ASSERT FAILED: "+e)},B={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(n,e){if(!Array.isArray(n))throw Error("encodeByteArray takes an array as a parameter");this.init_();var r=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,i=[];for(let c=0;c<n.length;c+=3){var s=n[c],o=c+1<n.length,a=o?n[c+1]:0,l=c+2<n.length,h=l?n[c+2]:0;let e=(15&a)<<2|h>>6,t=63&h;l||(t=64,o)||(e=64),i.push(r[s>>2],r[(3&s)<<4|a>>4],r[e],r[t])}return i.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(r(e),t)},decodeString(n,r){if(this.HAS_NATIVE_SUPPORT&&!r)return atob(n);{var i=this.decodeStringToByteArray(n,r);var s=[];let e=0,t=0;for(;e<i.length;){var o,a,l,h=i[e++];h<128?s[t++]=String.fromCharCode(h):191<h&&h<224?(o=i[e++],s[t++]=String.fromCharCode((31&h)<<6|63&o)):239<h&&h<365?(o=((7&h)<<18|(63&i[e++])<<12|(63&i[e++])<<6|63&i[e++])-65536,s[t++]=String.fromCharCode(55296+(o>>10)),s[t++]=String.fromCharCode(56320+(1023&o))):(a=i[e++],l=i[e++],s[t++]=String.fromCharCode((15&h)<<12|(63&a)<<6|63&l))}return s.join("");return}},decodeStringToByteArray(e,t){this.init_();var n=t?this.charToByteMapWebSafe_:this.charToByteMap_,r=[];for(let l=0;l<e.length;){var i=n[e.charAt(l++)],s=l<e.length?n[e.charAt(l)]:0,o=++l<e.length?n[e.charAt(l)]:64,a=++l<e.length?n[e.charAt(l)]:64;if(++l,null==i||null==s||null==o||null==a)throw new U;r.push(i<<2|s>>4),64!==o&&(r.push(s<<4&240|o>>2),64!==a)&&r.push(o<<6&192|a)}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),(this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e)>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class U extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}let j=function(e){var t=r(e);return B.encodeByteArray(t,!0)},V=function(e){return j(e).replace(/\./g,"")},z=function(e){try{return B.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function t(e){return function e(t,n){if(!(n instanceof Object))return n;switch(n.constructor){case Date:let e=n;return new Date(e.getTime());case Object:void 0===t&&(t={});break;case Array:t=[];break;default:return n}for(var r in n)n.hasOwnProperty(r)&&H(r)&&(t[r]=e(t[r],n[r]));return t}(void 0,e)}function H(e){return"__proto__"!==e}class _{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}wrapCallback(n){return(e,t)=>{e?this.reject(e):this.resolve(t),"function"==typeof n&&(this.promise.catch(()=>{}),1===n.length?n(e):n(e,t))}}}function Q(){return"undefined"!=typeof window&&(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test("undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:"")}function Y(e){return JSON.parse(e)}function a(e){return JSON.stringify(e)}function K(e){let t={},n={},r={},i="";try{var s=e.split(".");t=Y(z(s[0])||""),n=Y(z(s[1])||""),i=s[2],r=n.d||{},delete n.d}catch(e){}return{header:t,claims:n,data:r,signature:i}}function p(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function G(e,t){if(Object.prototype.hasOwnProperty.call(e,t))return e[t]}function $(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function J(e,t,n){var r,i={};for(r in e)Object.prototype.hasOwnProperty.call(e,r)&&(i[r]=t.call(n,e[r],r,e));return i}function X(e){return null!==e&&"object"==typeof e}class Z{constructor(){this.chain_=[],this.buf_=[],this.W_=[],this.pad_=[],this.inbuf_=0,this.total_=0,this.blockSize=64,this.pad_[0]=128;for(let e=1;e<this.blockSize;++e)this.pad_[e]=0;this.reset()}reset(){this.chain_[0]=1732584193,this.chain_[1]=4023233417,this.chain_[2]=2562383102,this.chain_[3]=271733878,this.chain_[4]=3285377520,this.inbuf_=0,this.total_=0}compress_(n,r){r=r||0;var i=this.W_;if("string"==typeof n)for(let e=0;e<16;e++)i[e]=n.charCodeAt(r)<<24|n.charCodeAt(r+1)<<16|n.charCodeAt(r+2)<<8|n.charCodeAt(r+3),r+=4;else for(let t=0;t<16;t++)i[t]=n[r]<<24|n[r+1]<<16|n[r+2]<<8|n[r+3],r+=4;for(let d=16;d<80;d++){var e=i[d-3]^i[d-8]^i[d-14]^i[d-16];i[d]=4294967295&(e<<1|e>>>31)}let t=this.chain_[0],s=this.chain_[1],o=this.chain_[2],a=this.chain_[3],l=this.chain_[4],h,c;for(let _=0;_<80;_++){c=_<40?_<20?(h=a^s&(o^a),1518500249):(h=s^o^a,1859775393):_<60?(h=s&o|a&(s|o),2400959708):(h=s^o^a,3395469782);var u=(t<<5|t>>>27)+h+l+c+i[_]&4294967295;l=a,a=o,o=4294967295&(s<<30|s>>>2),s=t,t=u}this.chain_[0]=this.chain_[0]+t&4294967295,this.chain_[1]=this.chain_[1]+s&4294967295,this.chain_[2]=this.chain_[2]+o&4294967295,this.chain_[3]=this.chain_[3]+a&4294967295,this.chain_[4]=this.chain_[4]+l&4294967295}update(n,r){if(null!=n){var i=(r=void 0===r?n.length:r)-this.blockSize;let e=0;var s=this.buf_;let t=this.inbuf_;for(;e<r;){if(0===t)for(;e<=i;)this.compress_(n,e),e+=this.blockSize;if("string"==typeof n){for(;e<r;)if(s[t]=n.charCodeAt(e),++t,++e,t===this.blockSize){this.compress_(s),t=0;break}}else for(;e<r;)if(s[t]=n[e],++t,++e,t===this.blockSize){this.compress_(s),t=0;break}}this.inbuf_=t,this.total_+=r}}digest(){var t=[];let e=8*this.total_;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(let r=this.blockSize-1;56<=r;r--)this.buf_[r]=255&e,e/=256;this.compress_(this.buf_);let n=0;for(let i=0;i<5;i++)for(let e=24;0<=e;e-=8)t[n]=this.chain_[i]>>e&255,++n;return t}}function l(e,t,n,r){let i;var s;if(r<t?i="at least "+t:n<r&&(i=0===n?"none":"no more than "+n),i)throw s=e+" failed: Was called with "+r+(1===r?" argument.":" arguments.")+" Expects "+i+".",new Error(s)}function h(e,t){return e+` failed: ${t} argument `}function c(e,t,n,r){if((!r||n)&&"function"!=typeof n)throw new Error(h(e,t)+"must be a valid function.")}function ee(e,t,n){if(n&&("object"!=typeof n||null===n))throw new Error(h(e,t)+"must be a valid context object.")}let te=function(e){let t=0;for(let r=0;r<e.length;r++){var n=e.charCodeAt(r);n<128?t++:n<2048?t+=2:55296<=n&&n<=56319?(t+=4,r++):t+=3}return t};function g(e){return e&&e._delegate?e._delegate:e}function ne(e){try{return(e.startsWith("http://")||e.startsWith("https://")?new URL(e).hostname:e).endsWith(".cloudworkstations.dev")}catch{return!1}}class re{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}let ie="[DEFAULT]";class se{constructor(e,t){this.name=e,this.container=t,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){var t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){var n=new _;if(this.instancesDeferred.set(t,n),this.isInitialized(t)||this.shouldAutoInitialize())try{var r=this.getOrInitializeService({instanceIdentifier:t});r&&n.resolve(r)}catch(e){}}return this.instancesDeferred.get(t).promise}getImmediate(e){var t=this.normalizeInstanceIdentifier(e?.identifier),n=e?.optional??!1;if(!this.isInitialized(t)&&!this.shouldAutoInitialize()){if(n)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:t})}catch(e){if(n)return null;throw e}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,this.shouldAutoInitialize()){if("EAGER"===e.instantiationMode)try{this.getOrInitializeService({instanceIdentifier:ie})}catch(e){}for(var[t,n]of this.instancesDeferred.entries()){t=this.normalizeInstanceIdentifier(t);try{var r=this.getOrInitializeService({instanceIdentifier:t});n.resolve(r)}catch(e){}}}}clearInstance(e=ie){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){var e=Array.from(this.instances.values());await Promise.all([...e.filter(e=>"INTERNAL"in e).map(e=>e.INTERNAL.delete()),...e.filter(e=>"_delete"in e).map(e=>e._delete())])}isComponentSet(){return null!=this.component}isInitialized(e=ie){return this.instances.has(e)}getOptions(e=ie){return this.instancesOptions.get(e)||{}}initialize(e={}){var{options:t={}}=e,n=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(n))throw Error(this.name+`(${n}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);var r,i,s=this.getOrInitializeService({instanceIdentifier:n,options:t});for([r,i]of this.instancesDeferred.entries())n===this.normalizeInstanceIdentifier(r)&&i.resolve(s);return s}onInit(e,t){var n=this.normalizeInstanceIdentifier(t);let r=this.onInitCallbacks.get(n)??new Set;r.add(e),this.onInitCallbacks.set(n,r);var i=this.instances.get(n);return i&&e(i,n),()=>{r.delete(e)}}invokeOnInitCallbacks(e,t){var n=this.onInitCallbacks.get(t);if(n)for(var r of n)try{r(e,t)}catch{}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let n=this.instances.get(e);if(!n&&this.component&&(n=this.component.instanceFactory(this.container,{instanceIdentifier:(r=e)===ie?void 0:r,options:t}),this.instances.set(e,n),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(n,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,n)}catch{}var r;return n||null}normalizeInstanceIdentifier(e=ie){return!this.component||this.component.multipleInstances?e:ie}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class oe{constructor(e){this.name=e,this.providers=new Map}addComponent(e){var t=this.getProvider(e.name);if(t.isComponentSet())throw new Error(`Component ${e.name} has already been registered with `+this.name);t.setComponent(e)}addOrOverwriteComponent(e){this.getProvider(e.name).isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){var t;return this.providers.has(e)?this.providers.get(e):(t=new se(e,this),this.providers.set(e,t),t)}getProviders(){return Array.from(this.providers.values())}}var n;(e=n=n||{})[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT";let ae={debug:n.DEBUG,verbose:n.VERBOSE,info:n.INFO,warn:n.WARN,error:n.ERROR,silent:n.SILENT},le=n.INFO,he={[n.DEBUG]:"log",[n.VERBOSE]:"log",[n.INFO]:"info",[n.WARN]:"warn",[n.ERROR]:"error"},ce=(e,t,...n)=>{if(!(t<e.logLevel)){var r=(new Date).toISOString(),i=he[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${r}] ${e.name}:`,...n)}};class ue{constructor(e){this.name=e,this._logLevel=le,this._logHandler=ce,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in n))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?ae[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,n.DEBUG,...e),this._logHandler(this,n.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,n.VERBOSE,...e),this._logHandler(this,n.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,n.INFO,...e),this._logHandler(this,n.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,n.WARN,...e),this._logHandler(this,n.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,n.ERROR,...e),this._logHandler(this,n.ERROR,...e)}}let de="@firebase/database",_e="1.1.5-eap-sql.a9a137e67",pe="";function fe(e){pe=e}class ge{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),a(t))}get(e){var t=this.domStorage_.getItem(this.prefixedName_(e));return null==t?null:Y(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}class me{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){null==t?delete this.cache_[e]:this.cache_[e]=t}get(e){return p(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}function ve(e){try{var t;if("undefined"!=typeof window&&void 0!==window[e])return(t=window[e]).setItem("firebase:sentinel","cache"),t.removeItem("firebase:sentinel"),new ge(t)}catch(e){}return new me}var d,ye;function we(e){var t=(t=>{var n,r,i=[];let s=0;for(let o=0;o<t.length;o++){let e=t.charCodeAt(o);55296<=e&&e<=56319&&(n=e-55296,o++,f(o<t.length,"Surrogate pair missing trail surrogate."),r=t.charCodeAt(o)-56320,e=65536+(n<<10)+r),e<128?i[s++]=e:(e<2048?i[s++]=e>>6|192:(e<65536?i[s++]=e>>12|224:(i[s++]=e>>18|240,i[s++]=e>>12&63|128),i[s++]=e>>6&63|128),i[s++]=63&e|128)}return i})(e),n=new Z,t=(n.update(t),n.digest());return B.encodeByteArray(t)}function Ce(t){return function(...e){u(t,...e)}}function be(...e){var t="FIREBASE INTERNAL ERROR: "+xe(...e);Pe.error(t)}function Te(e,t){return e===t?0:e<t?-1:1}function Ie(e,t){if(t&&e in t)return t[e];throw new Error("Missing required key ("+e+") in object: "+a(t))}function Ee(e){if("object"!=typeof e||null===e)return a(e);var t,n=[];for(t in e)n.push(t);n.sort();let r="{";for(let i=0;i<n.length;i++)0!==i&&(r+=","),r=(r=r+a(n[i])+":")+Ee(e[n[i]]);return r+="}"}function Se(e,t){var n=e.length;if(n<=t)return[e];var r=[];for(let i=0;i<n;i+=t)i+t>n?r.push(e.substring(i,n)):r.push(e.substring(i,i+t));return r}let ke=ve("localStorage"),Ne=ve("sessionStorage"),Pe=new ue("@firebase/database"),Re=(()=>{let e=1;return function(){return e++}})(),xe=function(...e){let t="";for(let r=0;r<e.length;r++){var n=e[r];Array.isArray(n)||n&&"object"==typeof n&&"number"==typeof n.length?t+=xe.apply(null,n):t+="object"==typeof n?a(n):n,t+=" "}return t},De=null,Ae=!0,Oe=function(e,t){f(!t||!0===e||!1===e,"Can't turn on custom loggers persistently."),!0===e?(Pe.logLevel=n.VERBOSE,De=Pe.log.bind(Pe),t&&Ne.set("logging_enabled",!0)):"function"==typeof e?De=e:(De=null,Ne.remove("logging_enabled"))},u=function(...e){var t;!0===Ae&&(Ae=!1,null===De)&&!0===Ne.get("logging_enabled")&&Oe(!0),De&&(t=xe.apply(null,e),De(t))},Le=function(...e){var t="FIREBASE FATAL ERROR: "+xe(...e);throw Pe.error(t),new Error(t)},m=function(...e){var t="FIREBASE WARNING: "+xe(...e);Pe.warn(t)},Me=function(){"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&m("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().")},Fe=function(e){return"number"==typeof e&&(e!=e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY)},qe="[MIN_NAME]",We="[MAX_NAME]",Be=function(e,t){var n,r;return e===t?0:e===qe||t===We?-1:t===qe||e===We?1:(n=je(e),r=je(t),null!==n?null!==r?n-r==0?e.length-t.length:n-r:-1:null===r&&e<t?-1:1)};function v(e,t){for(var n in e)e.hasOwnProperty(n)&&t(n,e[n])}function Ue(e){f(!Fe(e),"Invalid JSON number");let t,n,r,i,s;0===e?(n=0,r=0,t=1/e==-1/0?1:0):(t=e<0,e=Math.abs(e),r=e>=Math.pow(2,-1022)?(i=Math.min(Math.floor(Math.log(e)/Math.LN2),1023),n=i+1023,Math.round(e*Math.pow(2,52-i)-Math.pow(2,52))):(n=0,Math.round(e/Math.pow(2,-1074))));var o=[];for(s=52;s;--s)o.push(r%2?1:0),r=Math.floor(r/2);for(s=11;s;--s)o.push(n%2?1:0),n=Math.floor(n/2);o.push(t?1:0),o.reverse();var a=o.join("");let l="";for(s=0;s<64;s+=8){let e=parseInt(a.substr(s,8),2).toString(16);1===e.length&&(e="0"+e),l+=e}return l.toLowerCase()}function je(e){if(ze.test(e)){var t=Number(e);if(t>=He&&t<=Qe)return t}return null}function Ve(e,t){var n=setTimeout(e,t);return"number"==typeof n&&"undefined"!=typeof Deno&&Deno.unrefTimer?Deno.unrefTimer(n):"object"==typeof n&&n.unref&&n.unref(),n}let ze=new RegExp("^-?(0*)\\d{1,10}$"),He=-2147483648,Qe=2147483647,Ye=function(e){try{e()}catch(t){setTimeout(()=>{var e=t.stack||"";throw m("Exception was thrown by user callback.",e),t},Math.floor(0))}};class Ke{constructor(e,t){this.appCheckProvider=t,this.appName=e.name,wo._isFirebaseServerApp(e)&&e.settings.appCheckToken&&(this.serverAppAppCheckToken=e.settings.appCheckToken),this.appCheck=t?.getImmediate({optional:!0}),this.appCheck||t?.get().then(e=>this.appCheck=e)}getToken(n){if(this.serverAppAppCheckToken){if(n)throw new Error("Attempted reuse of `FirebaseServerApp.appCheckToken` after previous usage failed.");return Promise.resolve({token:this.serverAppAppCheckToken})}return this.appCheck?this.appCheck.getToken(n):new Promise((e,t)=>{setTimeout(()=>{this.appCheck?this.getToken(n).then(e,t):e(null)},0)})}addTokenChangeListener(t){this.appCheckProvider?.get().then(e=>e.addTokenListener(t))}notifyForInvalidToken(){m(`Provided AppCheck credentials for the app named "${this.appName}" `+"are invalid. This usually indicates your app was not initialized correctly.")}}class Ge{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(n){return this.auth_?this.auth_.getToken(n).catch(e=>e&&"auth/token-not-initialized"===e.code?(u("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(e)):new Promise((e,t)=>{setTimeout(()=>{this.auth_?this.getToken(n).then(e,t):e(null)},0)})}addTokenChangeListener(t){this.auth_?this.auth_.addAuthTokenListener(t):this.authProvider_.get().then(e=>e.addAuthTokenListener(t))}removeTokenChangeListener(t){this.authProvider_.get().then(e=>e.removeAuthTokenListener(t))}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/.',m(e)}}class $e{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}$e.OWNER="owner";let Je=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,Xe="websocket",Ze="long_polling";class et{constructor(e,t,n,r,i=!1,s="",o=!1,a=!1,l=null){this.secure=t,this.namespace=n,this.webSocketOnly=r,this.nodeAdmin=i,this.persistenceKey=s,this.includeNamespaceInQueryParams=o,this.isUsingEmulator=a,this.emulatorOptions=l,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=ke.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())&&ke.set("host:"+this._host,this.internalHost)}toString(){let e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e}toURLString(){var e=this.secure?"https://":"http://",t=this.includeNamespaceInQueryParams?"?ns="+this.namespace:"";return e+this.host+"/"+t}}function tt(e,t,n){f("string"==typeof t,"typeof type must == string"),f("object"==typeof n,"typeof params must == object");let r;if(t===Xe)r=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?";else{if(t!==Ze)throw new Error("Unknown connection type: "+t);r=(e.secure?"https://":"http://")+e.internalHost+"/.lp?"}((t=e).host!==t.internalHost||t.isCustomHost()||t.includeNamespaceInQueryParams)&&(n.ns=e.namespace);let i=[];return v(n,(e,t)=>{i.push(e+"="+t)}),r+i.join("&")}class nt{constructor(){this.counters_={}}incrementCounter(e,t=1){p(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return t(this.counters_)}}let rt={},it={};function st(e){var t=e.toString();return rt[t]||(rt[t]=new nt),rt[t]}class ot{constructor(e){this.onMessage_=e,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}closeAfter(e,t){this.closeAfterResponse=e,this.onClose=t,this.closeAfterResponse<this.currentResponseNum&&(this.onClose(),this.onClose=null)}handleResponse(e,t){for(this.pendingResponses[e]=t;this.pendingResponses[this.currentResponseNum];){let e=this.pendingResponses[this.currentResponseNum];delete this.pendingResponses[this.currentResponseNum];for(let t=0;t<e.length;++t)e[t]&&Ye(()=>{this.onMessage_(e[t])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}class at{constructor(e,t,n,r,i,s,o){this.connId=e,this.repoInfo=t,this.applicationId=n,this.appCheckToken=r,this.authToken=i,this.transportSessionId=s,this.lastSessionId=o,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=Ce(e),this.stats_=st(t),this.urlFn=e=>(this.appCheckToken&&(e.ac=this.appCheckToken),tt(t,Ze,e))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new ot(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null},Math.floor(3e4));var n=()=>{var e;this.isClosed_||(this.scriptTagHolder=new lt((...e)=>{var[t,n,r,,,]=e;if(this.incrementIncomingBytes_(e),this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,"start"===t)this.id=n,this.password=r;else{if("close"!==t)throw new Error("Unrecognized command received: "+t);n?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(n,()=>{this.onClosed_()})):this.onClosed_()}},(...e)=>{var[t,n]=e;this.incrementIncomingBytes_(e),this.myPacketOrderer.handleResponse(t,n)},()=>{this.onClosed_()},this.urlFn),(e={start:"t"}).ser=Math.floor(1e8*Math.random()),this.scriptTagHolder.uniqueCallbackIdentifier&&(e.cb=this.scriptTagHolder.uniqueCallbackIdentifier),e.v="5",this.transportSessionId&&(e.s=this.transportSessionId),this.lastSessionId&&(e.ls=this.lastSessionId),this.applicationId&&(e.p=this.applicationId),this.appCheckToken&&(e.ac=this.appCheckToken),"undefined"!=typeof location&&location.hostname&&Je.test(location.hostname)&&(e.r="f"),e=this.urlFn(e),this.log_("Connecting via long-poll to "+e),this.scriptTagHolder.addTag(e,()=>{}))};if("complete"===document.readyState)n();else{let e=!1,t=function(){document.body?e||(e=!0,n()):setTimeout(t,Math.floor(10))};document.addEventListener?(document.addEventListener("DOMContentLoaded",t,!1),window.addEventListener("load",t,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",()=>{"complete"===document.readyState&&t()}),window.attachEvent("onload",t))}}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){at.forceAllow_=!0}static forceDisallow(){at.forceDisallow_=!0}static isAvailable(){return!!at.forceAllow_||!(at.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){var t=a(e),t=(this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length),j(t)),n=Se(t,1840);for(let r=0;r<n.length;r++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,n.length,n[r]),this.curSegmentNum++}addDisconnectPingFrame(e,t){this.myDisconnFrame=document.createElement("iframe");var 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){var t=a(e).length;this.bytesReceived+=t,this.stats_.incrementCounter("bytes_received",t)}}class lt{constructor(t,n,e,r){this.onDisconnect=e,this.urlFn=r,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(1e8*Math.random()),this.sendNewPolls=!0;{this.uniqueCallbackIdentifier=Re(),window["pLPCommand"+this.uniqueCallbackIdentifier]=t,window["pRTLPCB"+this.uniqueCallbackIdentifier]=n,this.myIFrame=lt.createIFrame_();let e="";this.myIFrame.src&&"javascript:"===this.myIFrame.src.substr(0,"javascript:".length)&&(i=document.domain,e='<script>document.domain="'+i+'";<\/script>');var i="<html><body>"+e+"</body></html>";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(i),this.myIFrame.doc.close()}catch(e){u("frame writing exception"),e.stack&&u(e.stack),u(e)}}}static createIFrame_(){var t=document.createElement("iframe");if(t.style.display="none",!document.body)throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";document.body.appendChild(t);try{t.contentWindow.document||u("No IE domain setting required")}catch(e){var n=document.domain;t.src="javascript:void((function(){document.open();document.domain='"+n+"';document.close();})())"}return t.contentDocument?t.doc=t.contentDocument:t.contentWindow?t.doc=t.contentWindow.document:t.document&&(t.doc=t.document),t}close(){this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.textContent="",setTimeout(()=>{null!==this.myIFrame&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)},Math.floor(0)));var 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<(0<this.pendingSegs.length?2:1)){this.currentSerial++;var n={},n=(n.id=this.myID,n.pw=this.myPW,n.ser=this.currentSerial,this.urlFn(n));let e="",t=0;for(;0<this.pendingSegs.length;){if(!(this.pendingSegs[0].d.length+30+e.length<=1870))break;var r=this.pendingSegs.shift();e=e+"&seg"+t+"="+r.seg+"&ts"+t+"="+r.ts+"&d"+t+"="+r.d,t++}return n+=e,this.addLongPollTag_(n,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);let n=()=>{this.outstandingRequests.delete(t),this.newRequest_()},r=setTimeout(n,Math.floor(25e3));this.addTag(e,()=>{clearTimeout(r),n()})}addTag(e,n){setTimeout(()=>{try{if(this.sendNewPolls){let t=this.myIFrame.doc.createElement("script");t.type="text/javascript",t.async=!0,t.src=e,t.onload=t.onreadystatechange=function(){var e=t.readyState;e&&"loaded"!==e&&"complete"!==e||(t.onload=t.onreadystatechange=null,t.parentNode&&t.parentNode.removeChild(t),n())},t.onerror=()=>{u("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(t)}}catch(e){}},Math.floor(1))}}let ht=null;"undefined"!=typeof MozWebSocket?ht=MozWebSocket:"undefined"!=typeof WebSocket&&(ht=WebSocket);class y{constructor(e,t,n,r,i,s,o){this.connId=e,this.applicationId=n,this.appCheckToken=r,this.authToken=i,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=Ce(this.connId),this.stats_=st(t),this.connURL=y.connectionURL_(t,s,o,r,n),this.nodeAdmin=t.nodeAdmin}static connectionURL_(e,t,n,r,i){var s={v:"5"};return"undefined"!=typeof location&&location.hostname&&Je.test(location.hostname)&&(s.r="f"),t&&(s.s=t),n&&(s.ls=n),r&&(s.ac=r),i&&(s.p=i),tt(e,Xe,s)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,ke.set("previous_websocket_failure",!0);try{q.NODE_ADMIN,this.mySock=new ht(this.connURL,[],void 0)}catch(e){this.log_("Error instantiating WebSocket.");var n=e.message||e.data;return n&&this.log_(n),void this.onClosed_()}this.mySock.onopen=()=>{this.log_("Websocket connected."),this.everConnected_=!0},this.mySock.onclose=()=>{this.log_("Websocket connection was disconnected."),this.mySock=null,this.onClosed_()},this.mySock.onmessage=e=>{this.handleIncomingFrame(e)},this.mySock.onerror=e=>{this.log_("WebSocket error. Closing connection.");var t=e.message||e.data;t&&this.log_(t),this.onClosed_()}}start(){}static forceDisallow(){y.forceDisallow_=!0}static isAvailable(){let e=!1;var t;return!(e="undefined"!=typeof navigator&&navigator.userAgent&&(t=navigator.userAgent.match(/Android ([0-9]{0,}\.[0-9]{0,})/))&&1<t.length&&parseFloat(t[1])<4.4?!0:e)&&null!==ht&&!y.forceDisallow_}static previouslyFailed(){return ke.isInMemoryStorage||!0===ke.get("previous_websocket_failure")}markConnectionHealthy(){ke.remove("previous_websocket_failure")}appendFrame_(e){var t;this.frames.push(e),this.frames.length===this.totalFrames&&(t=this.frames.join(""),this.frames=null,t=Y(t),this.onMessage(t))}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if(f(null===this.frames,"We already have a frame buffer"),e.length<=6){var t=Number(e);if(!isNaN(t))return this.handleNewFrameCount_(t),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){var t;null!==this.mySock&&(t=e.data,this.bytesReceived+=t.length,this.stats_.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),null!==this.frames?this.appendFrame_(t):null!==(t=this.extractFrameCount_(t))&&this.appendFrame_(t))}send(e){this.resetKeepAlive();var t=a(e),n=(this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length),Se(t,16384));1<n.length&&this.sendString_(String(n.length));for(let r=0;r<n.length;r++)this.sendString_(n[r])}shutdown_(){this.isClosed_=!0,this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),this.mySock&&(this.mySock.close(),this.mySock=null)}onClosed_(){this.isClosed_||(this.log_("WebSocket is closing itself"),this.shutdown_(),this.onDisconnect&&(this.onDisconnect(this.everConnected_),this.onDisconnect=null))}close(){this.isClosed_||(this.log_("WebSocket is being closed"),this.shutdown_())}resetKeepAlive(){clearInterval(this.keepaliveTimer),this.keepaliveTimer=setInterval(()=>{this.mySock&&this.sendString_("0"),this.resetKeepAlive()},Math.floor(45e3))}sendString_(e){try{this.mySock.send(e)}catch(e){this.log_("Exception thrown from WebSocket.send():",e.message||e.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}}}y.responsesRequiredToBeHealthy=2,y.healthyTimeout=3e4;class ct{static get ALL_TRANSPORTS(){return[at,y]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}constructor(e){this.initTransports_(e)}initTransports_(e){var t=y&&y.isAvailable();let n=t&&!y.previouslyFailed();if(e.webSocketOnly&&(t||m("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),n=!0),n)this.transports_=[y];else{var r,i=this.transports_=[];for(r of ct.ALL_TRANSPORTS)r&&r.isAvailable()&&i.push(r);ct.globalTransportInitialized_=!0}}initialTransport(){if(0<this.transports_.length)return this.transports_[0];throw new Error("No transports available")}upgradeTransport(){return 1<this.transports_.length?this.transports_[1]:null}}ct.globalTransportInitialized_=!1;class ut{constructor(e,t,n,r,i,s,o,a,l,h){this.id=e,this.repoInfo_=t,this.applicationId_=n,this.appCheckToken_=r,this.authToken_=i,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_=Ce("c:"+this.id+":"),this.transportManager_=new ct(t),this.log_("Connection created"),this.start_()}start_(){var e=this.transportManager_.initialTransport();this.conn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,null,this.lastSessionId),this.primaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;let t=this.connReceiver_(this.conn_),n=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout(()=>{this.conn_&&this.conn_.open(t,n)},Math.floor(0));e=e.healthyTimeout||0;0<e&&(this.healthyTimeout_=Ve(()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&102400<this.conn_.bytesReceived?(this.log_("Connection exceeded healthy timeout but has received "+this.conn_.bytesReceived+" bytes. Marking connection healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()):this.conn_&&10240<this.conn_.bytesSent?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(e)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(t){return e=>{t===this.conn_?this.onConnectionLost_(e):t===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(t){return e=>{2!==this.state_&&(t===this.rx_?this.onPrimaryMessageReceived_(e):t===this.secondaryConn_?this.onSecondaryMessageReceived_(e):this.log_("message on old connection"))}}sendRequest(e){this.sendData_({t:"d",d:e})}tryCleanupConnection(){this.tx_===this.secondaryConn_&&this.rx_===this.secondaryConn_&&(this.log_("cleaning up and promoting a connection: "+this.secondaryConn_.connId),this.conn_=this.secondaryConn_,this.secondaryConn_=null)}onSecondaryControl_(e){var t;"t"in e&&("a"===(t=e.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){var t=Ie("t",e),n=Ie("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:"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){var t=Ie("t",e),n=Ie("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){var t=Ie("t",e);if("d"in e){var n=e.d;if("h"===t){var r={...n};this.repoInfo_.isUsingEmulator&&(r.h=this.repoInfo_.host),this.onHandshake_(r)}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?be("Server Error: "+n):"o"===t?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):be("Unknown control packet command: "+t)}}onHandshake_(e){var t=e.ts,n=e.v,r=e.h;this.sessionId=e.s,this.repoInfo_.host=r,0===this.state_&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,t),"5"!==n&&m("Protocol version mismatch detected"),this.tryStartUpgrade_())}tryStartUpgrade_(){var 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;var t=this.connReceiver_(this.secondaryConn_),n=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(t,n),Ve(()=>{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):Ve(()=>{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_(){var 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()&&(ke.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 dt{put(e,t,n,r){}merge(e,t,n,r){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,t,n){}onDisconnectMerge(e,t,n){}onDisconnectCancel(e,t){}reportStats(e){}}class _t{constructor(e){this.allowedEvents_=e,this.listeners_={},f(Array.isArray(e)&&0<e.length,"Requires a non-empty array")}trigger(t,...n){if(Array.isArray(this.listeners_[t])){var r=[...this.listeners_[t]];for(let e=0;e<r.length;e++)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});var r=this.getInitialEvent(e);r&&t.apply(n,r)}off(e,t,n){this.validateEventType_(e);var r=this.listeners_[e]||[];for(let i=0;i<r.length;i++)if(r[i].callback===t&&(!n||n===r[i].context))return void r.splice(i,1)}validateEventType_(t){f(this.allowedEvents_.find(e=>e===t),"Unknown event: "+t)}}class pt extends _t{static getInstance(){return new pt}constructor(){super(["online"]),this.online_=!0,"undefined"==typeof window||void 0===window.addEventListener||Q()||(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))}getInitialEvent(e){return f("online"===e,"Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}let ft=32,gt=768;class w{constructor(n,e){if(void 0===e){this.pieces_=n.split("/");let e=0;for(let t=0;t<this.pieces_.length;t++)0<this.pieces_[t].length&&(this.pieces_[e]=this.pieces_[t],e++);this.pieces_.length=e,this.pieceNum_=0}else this.pieces_=n,this.pieceNum_=e}toString(){let e="";for(let t=this.pieceNum_;t<this.pieces_.length;t++)""!==this.pieces_[t]&&(e+="/"+this.pieces_[t]);return e||"/"}}function C(){return new w("")}function b(e){return e.pieceNum_>=e.pieces_.length?null:e.pieces_[e.pieceNum_]}function mt(e){return e.pieces_.length-e.pieceNum_}function T(e){let t=e.pieceNum_;return t<e.pieces_.length&&t++,new w(e.pieces_,t)}function vt(e){return e.pieceNum_<e.pieces_.length?e.pieces_[e.pieces_.length-1]:null}function yt(e,t=0){return e.pieces_.slice(e.pieceNum_+t)}function wt(e){if(e.pieceNum_>=e.pieces_.length)return null;var t=[];for(let n=e.pieceNum_;n<e.pieces_.length-1;n++)t.push(e.pieces_[n]);return new w(t,0)}function I(e,t){var n=[];for(let i=e.pieceNum_;i<e.pieces_.length;i++)n.push(e.pieces_[i]);if(t instanceof w)for(let e=t.pieceNum_;e<t.pieces_.length;e++)n.push(t.pieces_[e]);else{var r=t.split("/");for(let e=0;e<r.length;e++)0<r[e].length&&n.push(r[e])}return new w(n,0)}function E(e){return e.pieceNum_>=e.pieces_.length}function S(e,t){var n=b(e),r=b(t);if(null===n)return t;if(n===r)return S(T(e),T(t));throw new Error("INTERNAL ERROR: innerPath ("+t+") is not within outerPath ("+e+")")}function Ct(e,t){var n=yt(e,0),r=yt(t,0);for(let s=0;s<n.length&&s<r.length;s++){var i=Be(n[s],r[s]);if(0!==i)return i}return n.length===r.length?0:n.length<r.length?-1:1}function bt(e,t){if(mt(e)!==mt(t))return!1;for(let n=e.pieceNum_,r=t.pieceNum_;n<=e.pieces_.length;n++,r++)if(e.pieces_[n]!==t.pieces_[r])return!1;return!0}function k(e,t){let n=e.pieceNum_,r=t.pieceNum_;if(mt(e)>mt(t))return!1;for(;n<e.pieces_.length;){if(e.pieces_[n]!==t.pieces_[r])return!1;++n,++r}return!0}class Tt{constructor(e,t){this.errorPrefix_=t,this.parts_=yt(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let n=0;n<this.parts_.length;n++)this.byteLength_+=te(this.parts_[n]);It(this)}}function It(e){if(e.byteLength_>gt)throw new Error(e.errorPrefix_+"has a key path longer than "+gt+" bytes ("+e.byteLength_+").");if(e.parts_.length>ft)throw new Error(e.errorPrefix_+"path specified exceeds the maximum depth that can be written ("+ft+") or object contains a cycle "+Et(e))}function Et(e){return 0===e.parts_.length?"":"in property '"+e.parts_.join(".")+"'"}class St extends _t{static getInstance(){return new St}constructor(){super(["visible"]);let t,e;"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(e="visibilitychange",t="hidden"):void 0!==document.mozHidden?(e="mozvisibilitychange",t="mozHidden"):void 0!==document.msHidden?(e="msvisibilitychange",t="msHidden"):void 0!==document.webkitHidden&&(e="webkitvisibilitychange",t="webkitHidden")),this.visible_=!0,e&&document.addEventListener(e,()=>{var e=!document[t];e!==this.visible_&&(this.visible_=e,this.trigger("visible",e))},!1)}getInitialEvent(e){return f("visible"===e,"Unknown event type: "+e),[this.visible_]}}class kt extends dt{constructor(e,t,n,r,i,s,o,a){if(super(),this.repoInfo_=e,this.applicationId_=t,this.onDataUpdate_=n,this.onConnectStatus_=r,this.onServerInfoUpdate_=i,this.authTokenProvider_=s,this.appCheckTokenProvider_=o,this.authOverride_=a,this.id=kt.nextPersistentConnectionId_++,this.log_=Ce("p:"+this.id+":"),this.interruptReasons_={},this.listens=new Map,this.outstandingPuts_=[],this.outstandingGets_=[],this.outstandingPutCount_=0,this.outstandingGetCount_=0,this.onDisconnectRequestQueue_=[],this.connected_=!1,this.reconnectDelay_=1e3,this.maxReconnectDelay_=3e5,this.securityDebugCallback_=null,this.lastSessionId=null,this.establishConnectionTimer_=null,this.visible_=!1,this.requestCBHash_={},this.requestNumber_=0,this.realtime_=null,this.authToken_=null,this.appCheckToken_=null,this.forceTokenRefresh_=!1,this.invalidAuthTokenCount_=0,this.invalidAppCheckTokenCount_=0,this.firstConnection_=!0,this.lastConnectionAttemptTime_=null,this.lastConnectionEstablishedTime_=null,a)throw new Error("Auth override specified in options, but not supported on non Node.js platforms");St.getInstance().on("visible",this.onVisible_,this),-1===e.host.indexOf("fblocal")&&pt.getInstance().on("online",this.onOnline_,this)}sendRequest(e,t,n){var r=++this.requestNumber_,i={r:r,a:e,b:t};this.log_(a(i)),f(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(i),n&&(this.requestCBHash_[r]=n)}get(e){this.initConnection_();let n=new _;var t={p:e._path.toString(),q:e._queryObject},t=(this.outstandingGets_.push({action:"g",request:t,onComplete:e=>{var t=e.d;"ok"===e.s?n.resolve(t):n.reject(t)}}),this.outstandingGetCount_++,this.outstandingGets_.length-1);return this.connected_&&this.sendGet_(t),n.promise}listen(e,t,n,r){this.initConnection_();var i=e._queryIdentifier,s=e._path.toString(),o=(this.log_("Listen called for "+s+" "+i),this.listens.has(s)||this.listens.set(s,new Map),f(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),f(!this.listens.get(s).has(i),"listen() called twice for same path/queryId."),{onComplete:r,hashFn:t,query:e,tag:n});this.listens.get(s).set(i,o),this.connected_&&this.sendListen_(o)}sendGet_(t){let n=this.outstandingGets_[t];this.sendRequest("g",n.request,e=>{delete this.outstandingGets_[t],this.outstandingGetCount_--,0===this.outstandingGetCount_&&(this.outstandingGets_=[]),n.onComplete&&n.onComplete(e)})}sendListen_(i){let s=i.query,o=s._path.toString(),a=s._queryIdentifier;this.log_("Listen on "+o+" for "+a);var e={p:o};i.tag&&(e.q=s._queryObject,e.t=i.tag),e.h=i.hashFn(),this.sendRequest("q",e,e=>{var t=e.d,n=e.s,r=(kt.warnOnListenWarnings_(t,s),this.listens.get(o)&&this.listens.get(o).get(a));r===i&&(this.log_("listen response",e),"ok"!==n&&this.removeListen_(o,a),i.onComplete)&&i.onComplete(n,t)})}static warnOnListenWarnings_(e,t){var n,r;e&&"object"==typeof e&&p(e,"w")&&(n=G(e,"w"),Array.isArray(n))&&~n.indexOf("no_index")&&(n='".indexOn": "'+t._queryParams.getIndex().toString()+'"',r=t._path.toString(),m("Using an unspecified index. Your data will be downloaded and "+`filtered on the client. Consider adding ${n} at `+r+" 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){var t;(e&&40===e.length||(e=e,"object"==typeof(t=K(e).claims)&&!0===t.admin))&&(this.log_("Admin auth credential detected. Reducing max reconnect time."),this.maxReconnectDelay_=3e4)}refreshAppCheckToken(e){this.appCheckToken_=e,this.log_("App check token refreshed"),this.appCheckToken_?this.tryAppCheck():this.connected_&&this.sendRequest("unappeck",{},()=>{})}tryAuth(){if(this.connected_&&this.authToken_){let r=this.authToken_;n=r;var e=!!(e=K(n).claims)&&"object"==typeof e&&e.hasOwnProperty("iat")?"auth":"gauth",t={cred:r};null===this.authOverride_?t.noauth=!0:"object"==typeof this.authOverride_&&(t.authvar=this.authOverride_),this.sendRequest(e,t,e=>{var t=e.s,n=e.d||"error";this.authToken_===r&&("ok"===t?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(t,n))})}var n,e}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},e=>{var t=e.s,n=e.d||"error";"ok"===t?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(t,n)})}unlisten(e,t){var n=e._path.toString(),r=e._queryIdentifier,i=(this.log_("Unlisten called for "+n+" "+r),f(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(n,r));i&&this.connected_&&this.sendUnlisten_(n,r,e._queryObject,t)}sendUnlisten_(e,t,n,r){this.log_("Unlisten on "+e+" for "+t);var i={p:e};r&&(i.q=n,i.t=r),this.sendRequest("n",i)}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,r){var i={p:t,d:n};this.log_("onDisconnect "+e,i),this.sendRequest(e,i,e=>{r&&setTimeout(()=>{r(e.s,e.d)},Math.floor(0))})}put(e,t,n,r){this.putInternal("p",e,t,n,r)}merge(e,t,n,r){this.putInternal("m",e,t,n,r)}putInternal(e,t,n,r,i){this.initConnection_();var s={p:t,d:n},s=(void 0!==i&&(s.h=i),this.outstandingPuts_.push({action:e,request:s,onComplete:r}),this.outstandingPutCount_++,this.outstandingPuts_.length-1);this.connected_?this.sendPut_(s):this.log_("Buffering put: "+t)}sendPut_(t){let n=this.outstandingPuts_[t].action;var e=this.outstandingPuts_[t].request;let r=this.outstandingPuts_[t].onComplete;this.outstandingPuts_[t].queued=this.connected_,this.sendRequest(n,e,e=>{this.log_(n+" response",e),delete this.outstandingPuts_[t],this.outstandingPutCount_--,0===this.outstandingPutCount_&&(this.outstandingPuts_=[]),r&&r(e.s,e.d)})}reportStats(e){var t;this.connected_&&(this.log_("reportStats",t={c:e}),this.sendRequest("s",t,e=>{var t;"ok"!==e.s&&(t=e.d,this.log_("reportStats","Error sending stats: "+t))}))}onDataMessage_(e){if("r"in e){this.log_("from server: "+a(e));var 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):be("Unrecognized action received from server: "+a(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){f(!this.realtime_,"Scheduling a connect when we're already connected/ing?"),this.establishConnectionTimer_&&clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=setTimeout(()=>{this.establishConnectionTimer_=null,this.establishConnection_()},Math.floor(e))}initConnection_(){!this.realtime_&&this.firstConnection_&&this.scheduleConnect_(0)}onVisible_(e){e&&!this.visible_&&this.reconnectDelay_===this.maxReconnectDelay_&&(this.log_("Window became visible. Reducing delay."),this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0)),this.visible_=e}onOnline_(e){e?(this.log_("Browser went online."),this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0)):(this.log_("Browser went offline. Killing connection."),this.realtime_&&this.realtime_.close())}onRealtimeDisconnect_(){var e;this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()&&(this.visible_?this.lastConnectionEstablishedTime_&&(3e4<(new Date).getTime()-this.lastConnectionEstablishedTime_&&(this.reconnectDelay_=1e3),this.lastConnectionEstablishedTime_=null):(this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=(new Date).getTime()),e=Math.max(0,(new Date).getTime()-this.lastConnectionAttemptTime_),e=Math.max(0,this.reconnectDelay_-e),e=Math.random()*e,this.log_("Trying to reconnect in "+e+"ms"),this.scheduleConnect_(e),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;var r=this.onDataMessage_.bind(this),i=this.onReady_.bind(this);let e=this.onRealtimeDisconnect_.bind(this);var s=this.id+":"+kt.nextConnectionId_++,o=this.lastSessionId;let t=!1,n=null;var a=function(){n?n.close():(t=!0,e())},l=(this.realtime_={close:a,sendRequest:function(e){f(n,"sendRequest call when we're not connected not allowed."),n.sendRequest(e)}},this.forceTokenRefresh_);this.forceTokenRefresh_=!1;try{var[h,c]=await Promise.all([this.authTokenProvider_.getToken(l),this.appCheckTokenProvider_.getToken(l)]);t?u("getToken() completed but was canceled"):(u("getToken() completed. Creating connection."),this.authToken_=h&&h.accessToken,this.appCheckToken_=c&&c.token,n=new ut(s,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,r,i,e,e=>{m(e+" ("+this.repoInfo_.toString()+")"),this.interrupt("server_kill")},o))}catch(e){this.log_("Failed to get token: "+e),t||(this.repoInfo_.nodeAdmin&&m(e),a())}}}interrupt(e){u("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){u("Resuming connection for reason: "+e),delete this.interruptReasons_[e],$(this.interruptReasons_)&&(this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(e){var t=e-(new Date).getTime();this.onServerInfoUpdate_({serverTimeOffset:t})}cancelSentTransactions_(){for(let t=0;t<this.outstandingPuts_.length;t++){var e=this.outstandingPuts_[t];e&&"h"in e.request&&e.queued&&(e.onComplete&&e.onComplete("disconnect"),delete this.outstandingPuts_[t],this.outstandingPutCount_--)}0===this.outstandingPutCount_&&(this.outstandingPuts_=[])}onListenRevoked_(e,t){let n;n=t?t.map(e=>Ee(e)).join("$"):"default";var r=this.removeListen_(e,n);r&&r.onComplete&&r.onComplete("permission_denied")}removeListen_(e,t){var n,r=new w(e).toString();let i;return this.listens.has(r)?(n=this.listens.get(r),i=n.get(t),n.delete(t),0===n.size&&this.listens.delete(r)):i=void 0,i}onAuthRevoked_(e,t){u("Auth token revoked: "+e+"/"+t),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAuthTokenCount_++,3<=this.invalidAuthTokenCount_&&(this.reconnectDelay_=3e4,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(e,t){u("App check token revoked: "+e+"/"+t),this.appCheckToken_=null,this.forceTokenRefresh_=!0,"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAppCheckTokenCount_++,3<=this.invalidAppCheckTokenCount_&&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(var e of this.listens.values())for(var t of e.values())this.sendListen_(t);for(let r=0;r<this.outstandingPuts_.length;r++)this.outstandingPuts_[r]&&this.sendPut_(r);for(;this.onDisconnectRequestQueue_.length;){var n=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(n.action,n.pathString,n.data,n.onComplete)}for(let i=0;i<this.outstandingGets_.length;i++)this.outstandingGets_[i]&&this.sendGet_(i)}sendConnectStats_(){var e={};e["sdk.js."+pe.replace(/\./g,"-")]=1,Q()?e["framework.cordova"]=1:"object"==typeof navigator&&"ReactNative"===navigator.product&&(e["framework.reactnative"]=1),this.reportStats(e)}shouldReconnect_(){var e=pt.getInstance().currentlyOnline();return $(this.interruptReasons_)&&e}}kt.nextPersistentConnectionId_=0,kt.nextConnectionId_=0;class N{constructor(e,t){this.name=e,this.node=t}static Wrap(e,t){return new N(e,t)}}class Nt{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,t){var n=new N(qe,e),r=new N(qe,t);return 0!==this.compare(n,r)}minPost(){return N.MIN}}let Pt;class Rt extends Nt{static get __EMPTY_NODE(){return Pt}static set __EMPTY_NODE(e){Pt=e}compare(e,t){return Be(e.name,t.name)}isDefinedOn(e){throw W("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,t){return!1}minPost(){return N.MIN}maxPost(){return new N(We,Pt)}makePost(e,t){return f("string"==typeof e,"KeyIndex indexValue must always be a string."),new N(e,Pt)}toString(){return".key"}}let xt=new Rt;class Dt{constructor(e,t,n,r,i=null){this.isReverse_=r,this.resultGenerator_=i,this.nodeStack_=[];let s=1;for(;!e.isEmpty();)if(s=t?n(e.key,t):1,r&&(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=this.nodeStack_.pop(),t;if(t=this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value},this.isReverse_)for(e=e.left;!e.isEmpty();)this.nodeStack_.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack_.push(e),e=e.left;return t}hasNext(){return 0<this.nodeStack_.length}peek(){var e;return 0===this.nodeStack_.length?null:(e=this.nodeStack_[this.nodeStack_.length-1],this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value})}}class P{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:P.RED,this.left=null!=r?r:s.EMPTY_NODE,this.right=null!=i?i:s.EMPTY_NODE}copy(e,t,n,r,i){return new P(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i: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 r=this;var i=n(e,r.key);return(r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n))).fixUp_()}removeMin_(){if(this.left.isEmpty())return s.EMPTY_NODE;let e=this;return(e=(e=e.left.isRed_()||e.left.left.isRed_()?e:e.moveRedLeft_()).copy(null,null,null,e.left.removeMin_(),null)).fixUp_()}remove(e,t){let n,r;if(t(e,(n=this).key)<0)n=(n=n.left.isEmpty()||n.left.isRed_()||n.left.left.isRed_()?n:n.moveRedLeft_()).copy(null,null,null,n.left.remove(e,t),null);else{if(0===t(e,(n=(n=n.left.isRed_()?n.rotateRight_():n).right.isEmpty()||n.right.isRed_()||n.right.left.isRed_()?n:n.moveRedRight_()).key)){if(n.right.isEmpty())return s.EMPTY_NODE;r=n.right.min_(),n=n.copy(r.key,r.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=(e=(e=e.right.isRed_()&&!e.left.isRed_()?e.rotateLeft_():e).left.isRed_()&&e.left.left.isRed_()?e.rotateRight_():e).left.isRed_()&&e.right.isRed_()?e.colorFlip_():e}moveRedLeft_(){let e=this.colorFlip_();return e=e.right.left.isRed_()?(e=(e=e.copy(null,null,null,null,e.right.rotateRight_())).rotateLeft_()).colorFlip_():e}moveRedRight_(){let e=this.colorFlip_();return e=e.left.left.isRed_()?(e=e.rotateRight_()).colorFlip_():e}rotateLeft_(){var e=this.copy(null,null,P.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){var e=this.copy(null,null,P.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip_(){var 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_(){var 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+")");if(this.right.isRed_())throw new Error("Right child of ("+this.key+","+this.value+") is red");var e=this.left.check_();if(e!==this.right.check_())throw new Error("Black depths differ");return e+(this.isRed_()?0:1)}}P.RED=!0,P.BLACK=!1;class s{constructor(e,t=s.EMPTY_NODE){this.comparator_=e,this.root_=t}insert(e,t){return new s(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,P.BLACK,null,null))}remove(e){return new s(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,P.BLACK,null,null))}get(e){var t;let n=this.root_;for(;!n.isEmpty();){if(0===(t=this.comparator_(e,n.key)))return n.value;t<0?n=n.left:0<t&&(n=n.right)}return null}getPredecessorKey(e){let t,n=this.root_,r=null;for(;!n.isEmpty();){if(0===(t=this.comparator_(e,n.key))){if(n.left.isEmpty())return r?r.key:null;for(n=n.left;!n.right.isEmpty();)n=n.right;return n.key}t<0?n=n.left:0<t&&(n=(r=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 Dt(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new Dt(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new Dt(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new Dt(this.root_,null,this.comparator_,!0,e)}}function At(e,t){return Be(e.name,t.name)}function Ot(e,t){return Be(e,t)}s.EMPTY_NODE=new class{copy(e,t,n,r,i){return this}insert(e,t,n){return new P(e,t,null)}remove(e,t){return this}count(){return 0}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}check_(){return 0}isRed_(){return!1}};let Lt;function Mt(e){return"number"==typeof e?"number:"+Ue(e):"string:"+e}function Ft(e){var t;e.isLeafNode()?(t=e.val(),f("string"==typeof t||"number"==typeof t||"object"==typeof t&&p(t,".sv"),"Priority must be a string or number.")):f(e===Lt||e.isEmpty(),"priority of unexpected type."),f(e===Lt||e.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")}let qt;class R{static set __childrenNodeConstructor(e){qt=e}static get __childrenNodeConstructor(){return qt}constructor(e,t=R.__childrenNodeConstructor.EMPTY_NODE){this.value_=e,this.priorityNode_=t,this.lazyHash_=null,f(null!=this.value_,"LeafNode shouldn't be created with null/undefined value."),Ft(this.priorityNode_)}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new R(this.value_,e)}getImmediateChild(e){return".priority"===e?this.priorityNode_:R.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return E(e)?this:".priority"===b(e)?this.priorityNode_:R.__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:R.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,t).updatePriority(this.priorityNode_)}updateChild(e,t){var n=b(e);return null===n?t:t.isEmpty()&&".priority"!==n?this:(f(".priority"!==n||1===mt(e),".priority must be the last token in a path"),this.updateImmediateChild(n,R.__childrenNodeConstructor.EMPTY_NODE.updateChild(T(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:"+Mt(this.priorityNode_.val())+":");var t=typeof this.value_;e=(e+=t+":")+("number"==t?Ue(this.value_):this.value_),this.lazyHash_=we(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===R.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof R.__childrenNodeConstructor?-1:(f(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){var t=typeof e.value_,n=typeof this.value_,r=R.VALUE_TYPE_ORDER.indexOf(t),i=R.VALUE_TYPE_ORDER.indexOf(n);return f(0<=r,"Unknown leaf type: "+t),f(0<=i,"Unknown leaf type: "+n),r===i?"object"==n?0:this.value_<e.value_?-1:this.value_===e.value_?0:1:i-r}withIndex(){return this}isIndexed(){return!0}equals(e){return e===this||!!e.isLeafNode()&&this.value_===e.value_&&this.priorityNode_.equals(e.priorityNode_)}}R.VALUE_TYPE_ORDER=["object","boolean","number","string"];let Wt,Bt;class Ut extends Nt{compare(e,t){var n=e.node.getPriority(),r=t.node.getPriority(),n=n.compareTo(r);return 0===n?Be(e.name,t.name):n}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return N.MIN}maxPost(){return new N(We,new R("[PRIORITY-POST]",Bt))}makePost(e,t){var n=Wt(e);return new N(t,new R("[PRIORITY-POST]",n))}toString(){return".priority"}}let x=new Ut,jt=Math.log(2);class Vt{constructor(e){this.count=(t=e+1,parseInt(Math.log(t)/jt,10)),this.current_=this.count-1,t=this.count;var t,n=parseInt(Array(t+1).join("1"),2);this.bits_=e+1&n}nextBitIsOne(){var e=!(this.bits_&1<<this.current_);return this.current_--,e}}function zt(l,e,h,t){l.sort(e);let c=function(e,t){var n,r,i=t-e;let s,o;return 0==i?null:1==i?(s=l[e],o=h?h(s):s,new P(o,s.node,P.BLACK,null,null)):(i=parseInt(i/2,10)+e,n=c(e,i),r=c(i+1,t),s=l[i],o=h?h(s):s,new P(o,s.node,P.BLACK,n,r))};var n=(e=>{let s=null,o=null,a=l.length;function t(e,t){var n=a-e,r=a,r=(a-=e,c(1+n,r)),n=l[n],i=h?h(n):n,e=new P(i,n.node,t,null,r);s=(s?s.left=e:o=e,e)}for(let i=0;i<e.count;++i){var n=e.nextBitIsOne(),r=Math.pow(2,e.count-(i+1));n?t(r,P.BLACK):(t(r,P.BLACK),t(r,P.RED))}return o})(new Vt(l.length));return new s(t||e,n)}let Ht,Qt={};class Yt{static get Default(){return f((Qt,x),"ChildrenNode.ts has not been loaded"),Ht=Ht||new Yt({".priority":Qt},{".priority":x})}constructor(e,t){this.indexes_=e,this.indexSet_=t}get(e){var t=G(this.indexes_,e);if(t)return t instanceof s?t:null;throw new Error("No index defined for "+e)}hasIndex(e){return p(this.indexSet_,e.toString())}addIndex(e,t){f(e!==xt,"KeyIndex always exists and isn't meant to be added to the IndexMap.");var n=[];let r=!1;var i=t.getIterator(N.Wrap);let s=i.getNext();for(;s;)r=r||e.isDefinedOn(s.node),n.push(s),s=i.getNext();let o;o=r?zt(n,e.getCompare()):Qt;var a=e.toString(),l={...this.indexSet_},h=(l[a]=e,{...this.indexes_});return h[a]=o,new Yt(h,l)}addToIndexes(s,o){var e=J(this.indexes_,(t,e)=>{var n=G(this.indexSet_,e);if(f(n,"Missing index implementation for "+e),t===Qt){if(n.isDefinedOn(s.node)){var r=[],i=o.getIterator(N.Wrap);let e=i.getNext();for(;e;)e.name!==s.name&&r.push(e),e=i.getNext();return r.push(s),zt(r,n.getCompare())}return Qt}{n=o.get(s.name);let e=t;return(e=n?e.remove(new N(s.name,n)):e).insert(s,s.node)}});return new Yt(e,this.indexSet_)}removeFromIndexes(n,r){var e=J(this.indexes_,e=>{var t;return e!==Qt&&(t=r.get(n.name))?e.remove(new N(n.name,t)):e});return new Yt(e,this.indexSet_)}}let Kt;class D{static get EMPTY_NODE(){return Kt=Kt||new D(new s(Ot),null,Yt.Default)}constructor(e,t,n){this.children_=e,this.priorityNode_=t,this.indexMap_=n,this.lazyHash_=null,this.priorityNode_&&Ft(this.priorityNode_),this.children_.isEmpty()&&f(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}isLeafNode(){return!1}getPriority(){return this.priorityNode_||Kt}updatePriority(e){return this.children_.isEmpty()?this:new D(this.children_,e,this.indexMap_)}getImmediateChild(e){var t;return".priority"===e?this.getPriority():null===(t=this.children_.get(e))?Kt:t}getChild(e){var t=b(e);return null===t?this:this.getImmediateChild(t).getChild(T(e))}hasChild(e){return null!==this.children_.get(e)}updateImmediateChild(n,r){if(f(r,"We should always be passing snapshot nodes"),".priority"===n)return this.updatePriority(r);{var i=new N(n,r);let e,t;t=r.isEmpty()?(e=this.children_.remove(n),this.indexMap_.removeFromIndexes(i,this.children_)):(e=this.children_.insert(n,r),this.indexMap_.addToIndexes(i,this.children_));i=e.isEmpty()?Kt:this.priorityNode_;return new D(e,i,t)}}updateChild(e,t){var n,r=b(e);return null===r?t:(f(".priority"!==b(e)||1===mt(e),".priority must be the last token in a path"),n=this.getImmediateChild(r).updateChild(T(e),t),this.updateImmediateChild(r,n))}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(n){if(this.isEmpty())return null;let r={},i=0,s=0,o=!0;if(this.forEachChild(x,(e,t)=>{r[e]=t.val(n),i++,o&&D.INTEGER_REGEXP_.test(e)?s=Math.max(s,Number(e)):o=!1}),!n&&o&&s<2*i){var e,t=[];for(e in r)t[e]=r[e];return t}return n&&!this.getPriority().isEmpty()&&(r[".priority"]=this.getPriority().val()),r}hash(){if(null===this.lazyHash_){let r="";this.getPriority().isEmpty()||(r+="priority:"+Mt(this.getPriority().val())+":"),this.forEachChild(x,(e,t)=>{var n=t.hash();""!==n&&(r+=":"+e+":"+n)}),this.lazyHash_=""===r?"":we(r)}return this.lazyHash_}getPredecessorChildName(e,t,n){var r=this.resolveIndex_(n);return r?(r=r.getPredecessorKey(new N(e,t)))?r.name:null:this.children_.getPredecessorKey(e)}getFirstChildName(e){var t=this.resolveIndex_(e);return t?(t=t.minKey())&&t.name:this.children_.minKey()}getFirstChild(e){var t=this.getFirstChildName(e);return t?new N(t,this.children_.get(t)):null}getLastChildName(e){var t=this.resolveIndex_(e);return t?(t=t.maxKey())&&t.name:this.children_.maxKey()}getLastChild(e){var t=this.getLastChildName(e);return t?new N(t,this.children_.get(t)):null}forEachChild(e,t){var 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(t,n){var e=this.resolveIndex_(n);if(e)return e.getIteratorFrom(t,e=>e);{var r=this.children_.getIteratorFrom(t.name,N.Wrap);let e=r.peek();for(;null!=e&&n.compare(e,t)<0;)r.getNext(),e=r.peek();return r}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(t,n){var e=this.resolveIndex_(n);if(e)return e.getReverseIteratorFrom(t,e=>e);{var r=this.children_.getReverseIteratorFrom(t.name,N.Wrap);let e=r.peek();for(;null!=e&&0<n.compare(e,t);)r.getNext(),e=r.peek();return r}}compareTo(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===$t?-1:0}withIndex(e){var t;return e===xt||this.indexMap_.hasIndex(e)?this:(t=this.indexMap_.addIndex(e,this.children_),new D(this.children_,this.priorityNode_,t))}isIndexed(e){return e===xt||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;if(!e.isLeafNode()){var n=e;if(this.getPriority().equals(n.getPriority())){if(this.children_.count()!==n.children_.count())return!1;{var r=this.getIterator(x),i=n.getIterator(x);let e=r.getNext(),t=i.getNext();for(;e&&t;){if(e.name!==t.name||!e.node.equals(t.node))return!1;e=r.getNext(),t=i.getNext()}return null===e&&null===t}}}return!1}resolveIndex_(e){return e===xt?null:this.indexMap_.get(e.toString())}}D.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;class Gt extends D{constructor(){super(new s(Ot),D.EMPTY_NODE,Yt.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return D.EMPTY_NODE}isEmpty(){return!1}}let $t=new Gt,Jt=(Object.defineProperties(N,{MIN:{value:new N(qe,D.EMPTY_NODE)},MAX:{value:new N(We,$t)}}),Rt.__EMPTY_NODE=D.EMPTY_NODE,R.__childrenNodeConstructor=D,e=$t,Lt=e,e=$t,Bt=e,!0);function A(s,e=null){if(null===s)return D.EMPTY_NODE;var t,n;if("object"==typeof s&&".priority"in s&&(e=s[".priority"]),f(null===e||"string"==typeof e||"number"==typeof e||"object"==typeof e&&".sv"in e,"Invalid priority type found: "+typeof e),"object"!=typeof(s="object"==typeof s&&".value"in s&&null!==s[".value"]?s[".value"]:s)||".sv"in s)return t=s,new R(t,A(e));if(s instanceof Array||!Jt){let r=D.EMPTY_NODE;return v(s,(e,t)=>{var n;!p(s,e)||"."===e.substring(0,1)||!(n=A(t)).isLeafNode()&&n.isEmpty()||(r=r.updateImmediateChild(e,n))}),r.updatePriority(A(e))}{let r=[],i=!1;return v(s,(e,t)=>{var n;"."===e.substring(0,1)||(n=A(t)).isEmpty()||(i=i||!n.getPriority().isEmpty(),r.push(new N(e,n)))}),0===r.length?D.EMPTY_NODE:(t=zt(r,At,e=>e.name,Ot),i?(n=zt(r,x.getCompare()),new D(t,A(e),new Yt({".priority":n},{".priority":x}))):new D(t,A(e),Yt.Default))}}Wt=A;class Xt extends Nt{constructor(e){super(),this.indexPath_=e,f(!E(e)&&".priority"!==b(e),"Can't create PathIndex with empty path or .priority key")}extractChild(e){return e.getChild(this.indexPath_)}isDefinedOn(e){return!e.getChild(this.indexPath_).isEmpty()}compare(e,t){var n=this.extractChild(e.node),r=this.extractChild(t.node),n=n.compareTo(r);return 0===n?Be(e.name,t.name):n}makePost(e,t){var n=A(e),n=D.EMPTY_NODE.updateChild(this.indexPath_,n);return new N(t,n)}maxPost(){var e=D.EMPTY_NODE.updateChild(this.indexPath_,$t);return new N(We,e)}toString(){return yt(this.indexPath_,0).join("/")}}class Zt extends Nt{compare(e,t){var n=e.node.compareTo(t.node);return 0===n?Be(e.name,t.name):n}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return N.MIN}maxPost(){return N.MAX}makePost(e,t){var n=A(e);return new N(t,n)}toString(){return".value"}}let en=new Zt;function tn(e){return{type:"value",snapshotNode:e}}function nn(e,t){return{type:"child_added",snapshotNode:t,childName:e}}function rn(e,t){return{type:"child_removed",snapshotNode:t,childName:e}}function sn(e,t,n){return{type:"child_changed",snapshotNode:t,childName:e,oldSnap:n}}class on{constructor(e){this.index_=e}updateChild(e,t,n,r,i,s){f(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");var o=e.getImmediateChild(t);return o.getChild(r).equals(n.getChild(r))&&o.isEmpty()===n.isEmpty()||(null!=s&&(n.isEmpty()?e.hasChild(t)?s.trackChildChange(rn(t,o)):f(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):o.isEmpty()?s.trackChildChange(nn(t,n)):s.trackChildChange(sn(t,n,o))),e.isLeafNode()&&n.isEmpty())?e:e.updateImmediateChild(t,n).withIndex(this.index_)}updateFullNode(r,n,i){return null!=i&&(r.isLeafNode()||r.forEachChild(x,(e,t)=>{n.hasChild(e)||i.trackChildChange(rn(e,t))}),n.isLeafNode()||n.forEachChild(x,(e,t)=>{var n;r.hasChild(e)?(n=r.getImmediateChild(e)).equals(t)||i.trackChildChange(sn(e,t,n)):i.trackChildChange(nn(e,t))})),n.withIndex(this.index_)}updatePriority(e,t){return e.isEmpty()?D.EMPTY_NODE:e.updatePriority(t)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}class an{constructor(e){this.indexedFilter_=new on(e.getIndex()),this.index_=e.getIndex(),this.startPost_=an.getStartPost_(e),this.endPost_=an.getEndPost_(e),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){var t=this.startIsInclusive_?this.index_.compare(this.getStartPost(),e)<=0:this.index_.compare(this.getStartPost(),e)<0,n=this.endIsInclusive_?this.index_.compare(e,this.getEndPost())<=0:this.index_.compare(e,this.getEndPost())<0;return t&&n}updateChild(e,t,n,r,i,s){return this.matches(new N(t,n))||(n=D.EMPTY_NODE),this.indexedFilter_.updateChild(e,t,n,r,i,s)}updateFullNode(e,t,n){let r=(t=t.isLeafNode()?D.EMPTY_NODE:t).withIndex(this.index_),i=(r=r.updatePriority(D.EMPTY_NODE),this);return t.forEachChild(x,(e,t)=>{i.matches(new N(e,t))||(r=r.updateImmediateChild(e,D.EMPTY_NODE))}),this.indexedFilter_.updateFullNode(e,r,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){var t;return e.hasStart()?(t=e.getIndexStartName(),e.getIndex().makePost(e.getIndexStartValue(),t)):e.getIndex().minPost()}static getEndPost_(e){var t;return e.hasEnd()?(t=e.getIndexEndName(),e.getIndex().makePost(e.getIndexEndValue(),t)):e.getIndex().maxPost()}}class ln{constructor(e){this.withinDirectionalStart=e=>this.reverse_?this.withinEndPost(e):this.withinStartPost(e),this.withinDirectionalEnd=e=>this.reverse_?this.withinStartPost(e):this.withinEndPost(e),this.withinStartPost=e=>{var t=this.index_.compare(this.rangedFilter_.getStartPost(),e);return this.startIsInclusive_?t<=0:t<0},this.withinEndPost=e=>{var t=this.index_.compare(e,this.rangedFilter_.getEndPost());return this.endIsInclusive_?t<=0:t<0},this.rangedFilter_=new an(e),this.index_=e.getIndex(),this.limit_=e.getLimit(),this.reverse_=!e.isViewFromLeft(),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}updateChild(e,t,n,r,i,s){return this.rangedFilter_.matches(new N(t,n))||(n=D.EMPTY_NODE),e.getImmediateChild(t).equals(n)?e:e.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(e,t,n,r,i,s):this.fullLimitUpdateChild_(e,t,n,i,s)}updateFullNode(e,n,t){let r;if(n.isLeafNode()||n.isEmpty())r=D.EMPTY_NODE.withIndex(this.index_);else if(2*this.limit_<n.numChildren()&&n.isIndexed(this.index_)){r=D.EMPTY_NODE.withIndex(this.index_);let e,t=(e=this.reverse_?n.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):n.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_),0);for(;e.hasNext()&&t<this.limit_;){var i=e.getNext();if(this.withinDirectionalStart(i)){if(!this.withinDirectionalEnd(i))break;r=r.updateImmediateChild(i.name,i.node),t++}}}else{r=(r=n.withIndex(this.index_)).updatePriority(D.EMPTY_NODE);let e,t=(e=this.reverse_?r.getReverseIterator(this.index_):r.getIterator(this.index_),0);for(;e.hasNext();){var s=e.getNext();t<this.limit_&&this.withinDirectionalStart(s)&&this.withinDirectionalEnd(s)?t++:r=r.updateImmediateChild(s.name,D.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(e,r,t)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}fullLimitUpdateChild_(e,t,n,r,i){let s;if(this.reverse_){let n=this.index_.getCompare();s=(e,t)=>n(t,e)}else s=this.index_.getCompare();var o=e,a=(f(o.numChildren()===this.limit_,""),new N(t,n)),l=this.reverse_?o.getFirstChild(this.index_):o.getLastChild(this.index_),h=this.rangedFilter_.matches(a);if(o.hasChild(t)){var c=o.getImmediateChild(t);let e=r.getChildAfterChild(this.index_,l,this.reverse_);for(;null!=e&&(e.name===t||o.hasChild(e.name));)e=r.getChildAfterChild(this.index_,e,this.reverse_);var u=null==e?1:s(e,a);return h&&!n.isEmpty()&&0<=u?(null!=i&&i.trackChildChange(sn(t,n,c)),o.updateImmediateChild(t,n)):(null!=i&&i.trackChildChange(rn(t,c)),u=o.updateImmediateChild(t,D.EMPTY_NODE),null!=e&&this.rangedFilter_.matches(e)?(null!=i&&i.trackChildChange(nn(e.name,e.node)),u.updateImmediateChild(e.name,e.node)):u)}return!n.isEmpty()&&h&&0<=s(l,a)?(null!=i&&(i.trackChildChange(rn(l.name,l.node)),i.trackChildChange(nn(t,n))),o.updateImmediateChild(t,n).updateImmediateChild(l.name,D.EMPTY_NODE)):e}}class hn{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_=x}hasStart(){return this.startSet_}isViewFromLeft(){return""===this.viewFrom_?this.startSet_:"l"===this.viewFrom_}getIndexStartValue(){return f(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return f(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:qe}hasEnd(){return this.endSet_}getIndexEndValue(){return f(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return f(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:We}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&""!==this.viewFrom_}getLimit(){return f(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_===x}copy(){var e=new hn;return e.limitSet_=this.limitSet_,e.limit_=this.limit_,e.startSet_=this.startSet_,e.startAfterSet_=this.startAfterSet_,e.indexStartValue_=this.indexStartValue_,e.startNameSet_=this.startNameSet_,e.indexStartName_=this.indexStartName_,e.endSet_=this.endSet_,e.endBeforeSet_=this.endBeforeSet_,e.indexEndValue_=this.indexEndValue_,e.endNameSet_=this.endNameSet_,e.indexEndName_=this.indexEndName_,e.index_=this.index_,e.viewFrom_=this.viewFrom_,e}}function cn(e,t,n){var r=e.copy();return r.startSet_=!0,r.indexStartValue_=t=void 0===t?null:t,null!=n?(r.startNameSet_=!0,r.indexStartName_=n):(r.startNameSet_=!1,r.indexStartName_=""),r}function un(e,t,n){var r=e.copy();return r.endSet_=!0,r.indexEndValue_=t=void 0===t?null:t,void 0!==n?(r.endNameSet_=!0,r.indexEndName_=n):(r.endNameSet_=!1,r.indexEndName_=""),r}function dn(e,t){var n=e.copy();return n.index_=t,n}function _n(t){var n,r={};if(!t.isDefault()){let e;e=t.index_===x?"$priority":t.index_===en?"$value":t.index_===xt?"$key":(f(t.index_ instanceof Xt,"Unrecognized index type!"),t.index_.toString()),r.orderBy=a(e),t.startSet_&&(r[n=t.startAfterSet_?"startAfter":"startAt"]=a(t.indexStartValue_),t.startNameSet_)&&(r[n]+=","+a(t.indexStartName_)),t.endSet_&&(r[n=t.endBeforeSet_?"endBefore":"endAt"]=a(t.indexEndValue_),t.endNameSet_)&&(r[n]+=","+a(t.indexEndName_)),t.limitSet_&&(t.isViewFromLeft()?r.limitToFirst=t.limit_:r.limitToLast=t.limit_)}return r}function pn(t){var n={};if(t.startSet_&&(n.sp=t.indexStartValue_,t.startNameSet_&&(n.sn=t.indexStartName_),n.sin=!t.startAfterSet_),t.endSet_&&(n.ep=t.indexEndValue_,t.endNameSet_&&(n.en=t.indexEndName_),n.ein=!t.endBeforeSet_),t.limitSet_){n.l=t.limit_;let e=t.viewFrom_;""===e&&(e=t.isViewFromLeft()?"l":"r"),n.vf=e}return t.index_!==x&&(n.i=t.index_.toString()),n}class fn extends dt{reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,t){return void 0!==t?"tag$"+t:(f(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}constructor(e,t,n,r){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=n,this.appCheckTokenProvider_=r,this.log_=Ce("p:rest:"),this.listens_={}}listen(e,t,r,i){let s=e._path.toString(),o=(this.log_("Listen called for "+s+" "+e._queryIdentifier),fn.getListenId_(e,r)),a={};this.listens_[o]=a;var n=_n(e._queryParams);this.restRequest_(s+".json",n,(t,e)=>{let n=e;if(null===(t=404===t?n=null:t)&&this.onDataUpdate_(s,n,!1,r),G(this.listens_,o)===a){let e;e=t?401===t?"permission_denied":"rest_error:"+t:"ok",i(e,null)}})}unlisten(e,t){var n=fn.getListenId_(e,t);delete this.listens_[n]}get(e){var t=_n(e._queryParams);let r=e._path.toString(),i=new _;return this.restRequest_(r+".json",t,(e,t)=>{let n=t;null===(e=404===e?n=null:e)?(this.onDataUpdate_(r,n,!1,null),i.resolve(n)):i.reject(new Error(n))}),i.promise}refreshAuthToken(e){}restRequest_(i,s={},o){return s.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then(([e,t])=>{e&&e.accessToken&&(s.auth=e.accessToken),t&&t.token&&(s.ac=t.token);let n=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+i+"?ns="+this.repoInfo_.namespace+(e=>{let t=[];for(let[n,r]of Object.entries(e))Array.isArray(r)?r.forEach(e=>{t.push(encodeURIComponent(n)+"="+encodeURIComponent(e))}):t.push(encodeURIComponent(n)+"="+encodeURIComponent(r));return t.length?"&"+t.join("&"):""})(s),r=(this.log_("Sending REST request for "+n),new XMLHttpRequest);r.onreadystatechange=()=>{if(o&&4===r.readyState){this.log_("REST Response for "+n+" received. status:",r.status,"response:",r.responseText);let e=null;if(200<=r.status&&r.status<300){try{e=Y(r.responseText)}catch(e){m("Failed to parse JSON response for "+n+": "+r.responseText)}o(null,e)}else 401!==r.status&&404!==r.status&&m("Got unsuccessful REST response for "+n+" Status: "+r.status),o(r.status);o=null}},r.open("GET",n,!0),r.send()})}}class gn{constructor(){this.rootNode_=D.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}function mn(){return{value:null,children:new Map}}function vn(e,t,n){var r;E(t)?(e.value=n,e.children.clear()):null!==e.value?e.value=e.value.updateChild(t,n):(r=b(t),e.children.has(r)||e.children.set(r,mn()),vn(e.children.get(r),t=T(t),n))}function yn(e,n,r){var i;null!==e.value?r(n,e.value):(i=(e,t)=>{yn(t,new w(n.toString()+"/"+e),r)},e.children.forEach((e,t)=>{i(t,e)}))}class wn{constructor(e){this.collection_=e,this.last_=null}get(){var e=this.collection_.get();let n={...e};return this.last_&&v(this.last_,(e,t)=>{n[e]=n[e]-t}),this.last_=e,n}}class Cn{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new wn(e);var n=1e4+2e4*Math.random();Ve(this.reportStats_.bind(this),Math.floor(n))}reportStats_(){var e=this.statsListener_.get();let n={},r=!1;v(e,(e,t)=>{0<t&&p(this.statsToReport_,e)&&(n[e]=t,r=!0)}),r&&this.server_.reportStats(n),Ve(this.reportStats_.bind(this),Math.floor(2*Math.random()*3e5))}}function bn(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function Tn(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function In(e){return{fromUser:!1,fromServer:!0,queryId:e,tagged:!0}}(e=d=d||{})[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";class En{constructor(e,t,n){this.path=e,this.affectedTree=t,this.revert=n,this.type=d.ACK_USER_WRITE,this.source=bn()}operationForChild(e){var t;return E(this.path)?null!=this.affectedTree.value?(f(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this):(t=this.affectedTree.subtree(new w(e)),new En(C(),t,this.revert)):(f(b(this.path)===e,"operationForChild called for unrelated child."),new En(T(this.path),this.affectedTree,this.revert))}}class Sn{constructor(e,t){this.source=e,this.path=t,this.type=d.LISTEN_COMPLETE}operationForChild(e){return E(this.path)?new Sn(this.source,C()):new Sn(this.source,T(this.path))}}class kn{constructor(e,t,n){this.source=e,this.path=t,this.snap=n,this.type=d.OVERWRITE}operationForChild(e){return E(this.path)?new kn(this.source,C(),this.snap.getImmediateChild(e)):new kn(this.source,T(this.path),this.snap)}}class Nn{constructor(e,t,n){this.source=e,this.path=t,this.children=n,this.type=d.MERGE}operationForChild(e){var t;return E(this.path)?(t=this.children.subtree(new w(e))).isEmpty()?null:t.value?new kn(this.source,C(),t.value):new Nn(this.source,C(),t):(f(b(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new Nn(this.source,T(this.path),this.children))}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}class Pn{constructor(e,t,n){this.node_=e,this.fullyInitialized_=t,this.filtered_=n}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){var t;return E(e)?this.isFullyInitialized()&&!this.filtered_:(t=b(e),this.isCompleteForChild(t))}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}class Rn{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function xn(n,e,t,r){var i=[];let s=[];return e.forEach(e=>{var t;"child_changed"===e.type&&n.index_.indexedValueChanged(e.oldSnap,e.snapshotNode)&&s.push((t=e.childName,{type:"child_moved",snapshotNode:e.snapshotNode,childName:t}))}),Dn(n,i,"child_removed",e,r,t),Dn(n,i,"child_added",e,r,t),Dn(n,i,"child_moved",s,r,t),Dn(n,i,"child_changed",e,r,t),Dn(n,i,"value",e,r,t),i}function Dn(s,o,t,e,a,l){var n=e.filter(e=>e.type===t);n.sort((e,t)=>{var n=s;if(null==e.childName||null==t.childName)throw W("Should only compare child_ events.");var r=new N(e.childName,e.snapshotNode),i=new N(t.childName,t.snapshotNode);return n.index_.compare(r,i)}),n.forEach(t=>{e=s,i=l,"value"!==(r=t).type&&"child_removed"!==r.type&&(r.prevName=i.getPredecessorChildName(r.childName,r.snapshotNode,e.index_));let n=r;var e,r,i;a.forEach(e=>{e.respondsTo(t.type)&&o.push(e.createEvent(n,s.query_))})})}function An(e,t){return{eventCache:e,serverCache:t}}function On(e,t,n,r){return An(new Pn(t,n,r),e.serverCache)}function Ln(e,t,n,r){return An(e.eventCache,new Pn(t,n,r))}function Mn(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function Fn(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}let qn;class O{static fromObject(e){let n=new O(null);return v(e,(e,t)=>{n=n.set(new w(e),t)}),n}constructor(e,t=qn=qn||new s(Te)){this.value=e,this.children=t}isEmpty(){return null===this.value&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){var n,r;return null!=this.value&&t(this.value)?{path:C(),value:this.value}:!E(e)&&(n=b(e),null!==(r=this.children.get(n)))&&null!=(r=r.findRootMostMatchingPathAndValue(T(e),t))?{path:I(new w(n),r.path),value:r.value}:null}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,()=>!0)}subtree(e){var t;return E(e)?this:(t=b(e),null!==(t=this.children.get(t))?t.subtree(T(e)):new O(null))}set(e,t){var n,r;return E(e)?new O(t,this.children):(r=b(e),n=(this.children.get(r)||new O(null)).set(T(e),t),r=this.children.insert(r,n),new O(this.value,r))}remove(t){if(E(t))return this.children.isEmpty()?new O(null):new O(null,this.children);var n=b(t),r=this.children.get(n);if(r){r=r.remove(T(t));let e;return e=r.isEmpty()?this.children.remove(n):this.children.insert(n,r),null===this.value&&e.isEmpty()?new O(null):new O(this.value,e)}return this}get(e){var t;return E(e)?this.value:(t=b(e),(t=this.children.get(t))?t.get(T(e)):null)}setTree(t,n){if(E(t))return n;{var r=b(t),i=(this.children.get(r)||new O(null)).setTree(T(t),n);let e;return e=i.isEmpty()?this.children.remove(r):this.children.insert(r,i),new O(this.value,e)}}fold(e){return this.fold_(C(),e)}fold_(n,r){let i={};return this.children.inorderTraversal((e,t)=>{i[e]=t.fold_(I(n,e),r)}),r(n,this.value,i)}findOnPath(e,t){return this.findOnPath_(e,C(),t)}findOnPath_(e,t,n){var r,i=!!this.value&&n(t,this.value);return i||(!E(e)&&(i=b(e),r=this.children.get(i))?r.findOnPath_(T(e),I(t,i),n):null)}foreachOnPath(e,t){return this.foreachOnPath_(e,C(),t)}foreachOnPath_(e,t,n){var r,i;return E(e)?this:(this.value&&n(t,this.value),r=b(e),(i=this.children.get(r))?i.foreachOnPath_(T(e),I(t,r),n):new O(null))}foreach(e){this.foreach_(C(),e)}foreach_(n,r){this.children.inorderTraversal((e,t)=>{t.foreach_(I(n,e),r)}),this.value&&r(n,this.value)}foreachChild(n){this.children.inorderTraversal((e,t)=>{t.value&&n(e,t.value)})}}class Wn{constructor(e){this.writeTree_=e}static empty(){return new Wn(new O(null))}}function Bn(t,n,r){if(E(n))return new Wn(new O(r));var i=t.writeTree_.findRootMostValueAndPath(n);if(null==i)return s=new O(r),s=t.writeTree_.setTree(n,s),new Wn(s);{var s=i.path;let e=i.value;i=S(s,n);return e=e.updateChild(i,r),new Wn(t.writeTree_.set(s,e))}}function Un(e,n,t){let r=e;return v(t,(e,t)=>{r=Bn(r,I(n,e),t)}),r}function jn(e,t){var n;return E(t)?Wn.empty():(n=e.writeTree_.setTree(t,new O(null)),new Wn(n))}function Vn(e,t){return null!=zn(e,t)}function zn(e,t){var n=e.writeTree_.findRootMostValueAndPath(t);return null!=n?e.writeTree_.get(n.path).getChild(S(n.path,t)):null}function Hn(e){let n=[];var t=e.writeTree_.value;return null!=t?t.isLeafNode()||t.forEachChild(x,(e,t)=>{n.push(new N(e,t))}):e.writeTree_.children.inorderTraversal((e,t)=>{null!=t.value&&n.push(new N(e,t.value))}),n}function Qn(e,t){var n;return E(t)?e:null!=(n=zn(e,t))?new Wn(new O(n)):new Wn(e.writeTree_.subtree(t))}function Yn(e){return e.writeTree_.isEmpty()}function Kn(e,t){return function r(i,e,s){{if(null!=e.value)return s.updateChild(i,e.value);{let n=null;return e.children.inorderTraversal((e,t)=>{".priority"===e?(f(null!==t.value,"Priority writes must always be leaf nodes"),n=t.value):s=r(I(i,e),t,s)}),s=s.getChild(i).isEmpty()||null===n?s:s.updateChild(I(i,".priority"),n)}}}(C(),e.writeTree_,t)}function Gn(e,t){return ar(t,e)}function $n(t,n){var e,r=t.allWrites.findIndex(e=>e.writeId===n);f(0<=r,"removeWrite called with nonexistent writeId.");let i=t.allWrites[r],s=(t.allWrites.splice(r,1),i.visible),o=!1,a=t.allWrites.length-1;for(;s&&0<=a;){var l=t.allWrites[a];l.visible&&(a>=r&&((e,t)=>{if(e.snap)return k(e.path,t);for(var n in e.children)if(e.children.hasOwnProperty(n)&&k(I(e.path,n),t))return 1})(l,i.path)?s=!1:k(i.path,l.path)&&(o=!0)),a--}return!!s&&(o?((e=t).visibleWrites=Xn(e.allWrites,Jn,C()),0<e.allWrites.length?e.lastWriteId=e.allWrites[e.allWrites.length-1].writeId:e.lastWriteId=-1):i.snap?t.visibleWrites=jn(t.visibleWrites,i.path):v(i.children,e=>{t.visibleWrites=jn(t.visibleWrites,I(i.path,e))}),!0)}function Jn(e){return e.visible}function Xn(e,t,n){let r=Wn.empty();for(let o=0;o<e.length;++o){var i=e[o];if(t(i)){var s=i.path;let e;if(i.snap)k(n,s)?(e=S(n,s),r=Bn(r,e,i.snap)):k(s,n)&&(e=S(s,n),r=Bn(r,C(),i.snap.getChild(e)));else{if(!i.children)throw W("WriteRecord should have .snap or .children");k(n,s)?(e=S(n,s),r=Un(r,e,i.children)):k(s,n)&&(E(e=S(s,n))?r=Un(r,C(),i.children):(s=G(i.children,b(e)))&&(i=s.getChild(T(e)),r=Bn(r,C(),i)))}}}return r}function Zn(e,t,n,r,i){var s;return r||i?(s=Qn(e.visibleWrites,t),!i&&Yn(s)?n:i||null!=n||Vn(s,C())?Kn(Xn(e.allWrites,function(e){return(e.visible||i)&&(!r||!~r.indexOf(e.writeId))&&(k(e.path,t)||k(t,e.path))},t),n||D.EMPTY_NODE):null):null!=(s=zn(e.visibleWrites,t))?s:Yn(s=Qn(e.visibleWrites,t))?n:null!=n||Vn(s,C())?Kn(s,n||D.EMPTY_NODE):null}function er(e,t,n,r){return Zn(e.writeTree,e.treePath,t,n,r)}function tr(e,t){{var n=e.writeTree;e=e.treePath;let i=D.EMPTY_NODE;var r=zn(n.visibleWrites,e);if(r)r.isLeafNode()||r.forEachChild(x,(e,t)=>{i=i.updateImmediateChild(e,t)});else if(t){let r=Qn(n.visibleWrites,e);t.forEachChild(x,(e,t)=>{var n=Kn(Qn(r,new w(e)),t);i=i.updateImmediateChild(e,n)}),Hn(r).forEach(e=>{i=i.updateImmediateChild(e.name,e.node)})}else Hn(Qn(n.visibleWrites,e)).forEach(e=>{i=i.updateImmediateChild(e.name,e.node)});return i}}function nr(e,t,n,r){return i=e.writeTree,e=e.treePath,t=t,n=n,r=r,f(n||r,"Either existingEventSnap or existingServerSnap must exist"),s=I(e,t),Vn(i.visibleWrites,s)?null:Yn(s=Qn(i.visibleWrites,s))?r.getChild(t):Kn(s,r.getChild(t));var i,s}function rr(e,t){return n=e.writeTree,e=I(e.treePath,t),zn(n.visibleWrites,e);var n}function ir(e,n,r,i,s,o){{var a=e.writeTree,l=(e=e.treePath,r),h=i;r=s,i=o;let t;var c=Qn(a.visibleWrites,e),u=zn(c,C());if(null!=u)t=u;else{if(null==n)return[];t=Kn(c,n)}if((t=t.withIndex(i)).isEmpty()||t.isLeafNode())return[];{var d=[],_=i.getCompare(),p=r?t.getReverseIteratorFrom(l,i):t.getIteratorFrom(l,i);let e=p.getNext();for(;e&&d.length<h;)0!==_(e,l)&&d.push(e),e=p.getNext();return d}}}function sr(e,t,n){return r=e.writeTree,n=n,i=I(e.treePath,e=t),null!=(s=zn(r.visibleWrites,i))?s:n.isCompleteForChild(e)?Kn(Qn(r.visibleWrites,i),n.getNode().getImmediateChild(e)):null;var r,i,s}function or(e,t){return ar(I(e.treePath,t),e.writeTree)}function ar(e,t){return{treePath:e,writeTree:t}}class lr{constructor(){this.changeMap=new Map}trackChildChange(e){var t=e.type,n=e.childName,r=(f("child_added"===t||"child_changed"===t||"child_removed"===t,"Only child changes supported for tracking"),f(".priority"!==n,"Only non-priority child changes can be tracked."),this.changeMap.get(n));if(r){var i=r.type;if("child_added"===t&&"child_removed"===i)this.changeMap.set(n,sn(n,e.snapshotNode,r.snapshotNode));else if("child_removed"===t&&"child_added"===i)this.changeMap.delete(n);else if("child_removed"===t&&"child_changed"===i)this.changeMap.set(n,rn(n,r.oldSnap));else if("child_changed"===t&&"child_added"===i)this.changeMap.set(n,nn(n,e.snapshotNode));else{if("child_changed"!==t||"child_changed"!==i)throw W("Illegal combination of changes: "+e+" occurred after "+r);this.changeMap.set(n,sn(n,e.snapshotNode,r.oldSnap))}}else this.changeMap.set(n,e)}getChanges(){return Array.from(this.changeMap.values())}}let hr=new class{getCompleteChild(e){return null}getChildAfterChild(e,t,n){return null}};class cr{constructor(e,t,n=null){this.writes_=e,this.viewCache_=t,this.optCompleteServerCache_=n}getCompleteChild(e){var t=this.viewCache_.eventCache;return t.isCompleteForChild(e)?t.getNode().getImmediateChild(e):(t=null!=this.optCompleteServerCache_?new Pn(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache,sr(this.writes_,e,t))}getChildAfterChild(e,t,n){var r=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:Fn(this.viewCache_),r=ir(this.writes_,r,t,1,n,e);return 0===r.length?null:r[0]}}function ur(e,t,n,r,i){var s=new lr;let o,a;if(n.type===d.OVERWRITE){var l=n;o=l.source.fromUser?pr(e,t,l.path,l.snap,r,i,s):(f(l.source.fromServer,"Unknown source."),a=l.source.tagged||t.serverCache.isFiltered()&&!E(l.path),_r(e,t,l.path,l.snap,r,i,a,s))}else if(n.type===d.MERGE){var l=n;o=l.source.fromUser?((r,i,s,e,o,a,l)=>{let h=i;return e.foreach((e,t)=>{var n=I(s,e);fr(i,b(n))&&(h=pr(r,h,n,t,o,a,l))}),e.foreach((e,t)=>{var n=I(s,e);fr(i,b(n))||(h=pr(r,h,n,t,o,a,l))}),h})(e,t,l.path,l.children,r,i,s):(f(l.source.fromServer,"Unknown source."),a=l.source.tagged||t.serverCache.isFiltered(),mr(e,t,l.path,l.children,r,i,a,s))}else if(n.type===d.ACK_USER_WRITE){l=n;o=l.revert?((n,r,i,s,e,o)=>{let a;if(null!=rr(s,i))return r;{var l=new cr(s,r,e),h=r.eventCache.getNode();let t;if(E(i)||".priority"===b(i)){let e;e=e=r.serverCache.isFullyInitialized()?er(s,Fn(r)):(c=r.serverCache.getNode(),f(c instanceof D,"serverChildren would be complete if leaf node"),tr(s,c)),t=n.filter.updateFullNode(h,e,o)}else{var c=b(i);let e=sr(s,c,r.serverCache);null==e&&r.serverCache.isCompleteForChild(c)&&(e=h.getImmediateChild(c)),(t=null!=e?n.filter.updateChild(h,c,e,T(i),l,o):r.eventCache.getNode().hasChild(c)?n.filter.updateChild(h,c,D.EMPTY_NODE,T(i),l,o):h).isEmpty()&&r.serverCache.isFullyInitialized()&&(a=er(s,Fn(r))).isLeafNode()&&(t=n.filter.updateFullNode(t,a,o))}return a=r.serverCache.isFullyInitialized()||null!=rr(s,C()),On(r,t,a,n.filter.filtersNodes())}})(e,t,l.path,r,i,s):((e,t,i,n,s,o,a)=>{if(null!=rr(s,i))return t;let l=t.serverCache.isFiltered(),h=t.serverCache;if(null!=n.value){if(E(i)&&h.isFullyInitialized()||h.isCompleteForPath(i))return _r(e,t,i,h.getNode().getChild(i),s,o,l,a);if(E(i)){let n=new O(null);return h.getNode().forEachChild(xt,(e,t)=>{n=n.set(new w(e),t)}),mr(e,t,i,n,s,o,l,a)}return t}{let r=new O(null);return n.foreach((e,t)=>{var n=I(i,e);h.isCompleteForPath(n)&&(r=r.set(e,h.getNode().getChild(n)))}),mr(e,t,i,r,s,o,l,a)}})(e,t,l.path,l.affectedTree,r,i,s)}else{if(n.type!==d.LISTEN_COMPLETE)throw W("Unknown operation type: "+n.type);o=(i=e,e=n.path,n=r,r=s,l=t.serverCache,l=Ln(t,l.getNode(),l.isFullyInitialized()||E(e),l.isFiltered()),dr(i,l,e,n,hr,r))}var h,c,s=s.getChanges(),i=t,e=o,n=s,u=e.eventCache;return u.isFullyInitialized()&&(h=u.getNode().isLeafNode()||u.getNode().isEmpty(),c=Mn(i),0<n.length||!i.eventCache.isFullyInitialized()||h&&!u.getNode().equals(c)||!u.getNode().getPriority().equals(c.getPriority()))&&n.push(tn(Mn(e))),{viewCache:o,changes:s}}function dr(r,i,s,o,a,l){var h=i.eventCache;if(null!=rr(o,s))return i;{let t,n;if(E(s))f(i.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),t=i.serverCache.isFiltered()?(c=tr(o,(c=Fn(i))instanceof D?c:D.EMPTY_NODE),r.filter.updateFullNode(i.eventCache.getNode(),c,l)):(c=er(o,Fn(i)),r.filter.updateFullNode(i.eventCache.getNode(),c,l));else{var c=b(s);if(".priority"===c){f(1===mt(s),"Can't have a priority with additional path components");var u=h.getNode(),d=nr(o,s,u,n=i.serverCache.getNode());t=null!=d?r.filter.updatePriority(u,d):h.getNode()}else{u=T(s);let e;e=h.isCompleteForChild(c)?(n=i.serverCache.getNode(),null!=(d=nr(o,s,h.getNode(),n))?h.getNode().getImmediateChild(c).updateChild(u,d):h.getNode().getImmediateChild(c)):sr(o,c,i.serverCache),t=null!=e?r.filter.updateChild(h.getNode(),c,e,u,a,l):h.getNode()}}return On(i,t,h.isFullyInitialized()||E(s),r.filter.filtersNodes())}}function _r(e,t,n,r,i,s,o,a){var l=t.serverCache;let h;var c=o?e.filter:e.filter.getIndexedFilter();if(E(n))h=c.updateFullNode(l.getNode(),r,null);else if(c.filtersNodes()&&!l.isFiltered()){var u=l.getNode().updateChild(n,r);h=c.updateFullNode(l.getNode(),u,null)}else{u=b(n);if(!l.isCompleteForPath(n)&&1<mt(n))return t;var d=T(n),_=l.getNode().getImmediateChild(u).updateChild(d,r);h=".priority"===u?c.updatePriority(l.getNode(),_):c.updateChild(l.getNode(),u,_,d,hr,null)}u=Ln(t,h,l.isFullyInitialized()||E(n),c.filtersNodes());return dr(e,u,n,i,new cr(i,u,s),a)}function pr(t,n,r,i,e,s,o){var a=n.eventCache;let l,h;var c=new cr(e,n,s);if(E(r))h=t.filter.updateFullNode(n.eventCache.getNode(),i,o),l=On(n,h,!0,t.filter.filtersNodes());else{var u=b(r);if(".priority"===u)h=t.filter.updatePriority(n.eventCache.getNode(),i),l=On(n,h,a.isFullyInitialized(),a.isFiltered());else{var d,_=T(r),p=a.getNode().getImmediateChild(u);let e;e=E(_)?i:null!=(d=c.getCompleteChild(u))?".priority"===vt(_)&&d.getChild(wt(_)).isEmpty()?d:d.updateChild(_,i):D.EMPTY_NODE,l=p.equals(e)?n:On(n,t.filter.updateChild(a.getNode(),u,e,_,c,o),a.isFullyInitialized(),t.filter.filtersNodes())}}return l}function fr(e,t){return e.eventCache.isCompleteForChild(t)}function gr(e,n,t){return t.foreach((e,t)=>{n=n.updateChild(e,t)}),n}function mr(r,i,e,t,s,o,a,l){if(i.serverCache.getNode().isEmpty()&&!i.serverCache.isFullyInitialized())return i;let h=i,n,c=(n=E(e)?t:new O(null).setTree(e,t),i.serverCache.getNode());return n.children.inorderTraversal((e,t)=>{var n;c.hasChild(e)&&(n=gr(0,i.serverCache.getNode().getImmediateChild(e),t),h=_r(r,h,new w(e),n,s,o,a,l))}),n.children.inorderTraversal((e,t)=>{var n=!i.serverCache.isCompleteForChild(e)&&null===t.value;c.hasChild(e)||n||(n=gr(0,i.serverCache.getNode().getImmediateChild(e),t),h=_r(r,h,new w(e),n,s,o,a,l))}),h}class vr{constructor(e,t){this.query_=e,this.eventRegistrations_=[];var n=this.query_._queryParams,r=new on(n.getIndex()),n=(e=n).loadsAllData()?new on(e.getIndex()):new(e.hasLimit()?ln:an)(e),i=(this.processor_={filter:n},t.serverCache),s=t.eventCache,o=r.updateFullNode(D.EMPTY_NODE,i.getNode(),null),a=n.updateFullNode(D.EMPTY_NODE,s.getNode(),null),o=new Pn(o,i.isFullyInitialized(),r.filtersNodes()),i=new Pn(a,s.isFullyInitialized(),n.filtersNodes());this.viewCache_=An(i,o),this.eventGenerator_=new Rn(this.query_)}get query(){return this.query_}}function yr(e){return 0===e.eventRegistrations_.length}function wr(r,i,s){let o=[];if(s){f(null==i,"A cancel should cancel all event registrations.");let n=r.query._path;r.eventRegistrations_.forEach(e=>{var t=e.createCancelEvent(s,n);t&&o.push(t)})}if(i){let e=[];for(let t=0;t<r.eventRegistrations_.length;++t){var n=r.eventRegistrations_[t];if(n.matches(i)){if(i.hasAnyCallback()){e=e.concat(r.eventRegistrations_.slice(t+1));break}}else e.push(n)}r.eventRegistrations_=e}else r.eventRegistrations_=[];return o}function Cr(e,t,n,r){t.type===d.MERGE&&null!==t.source.queryId&&(f(Fn(e.viewCache_),"We should always have a full cache before handling merges"),f(Mn(e.viewCache_),"Missing event cache, even though we have a server cache"));var i=e.viewCache_,s=ur(e.processor_,i,t,n,r);return t=e.processor_,n=s.viewCache,f(n.eventCache.getNode().isIndexed(t.filter.getIndex()),"Event snap not indexed"),f(n.serverCache.getNode().isIndexed(t.filter.getIndex()),"Server snap not indexed"),f(s.viewCache.serverCache.isFullyInitialized()||!i.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),e.viewCache_=s.viewCache,br(e,s.changes,s.viewCache.eventCache.getNode(),null)}function br(e,t,n,r){var i=r?[r]:e.eventRegistrations_;return xn(e.eventGenerator_,t,n,i)}let Tr;class Ir{constructor(){this.views=new Map}}function Er(t,n,r,i){var e=n.source.queryId;if(null!==e)return e=t.views.get(e),f(null!=e,"SyncTree gave us an op for an invalid query."),Cr(e,n,r,i);{let e=[];for(var s of t.views.values())e=e.concat(Cr(s,n,r,i));return e}}function Sr(e,n,r,i,s){var o=n._queryIdentifier,o=e.views.get(o);if(o)return o;{let e=er(r,s?i:null),t=!1;t=!!e||(e=i instanceof D?tr(r,i):D.EMPTY_NODE,!1);o=An(new Pn(e,t,!1),new Pn(i,s,!1));return new vr(n,o)}}function kr(e,t,r,i,s,n){var o=Sr(e,t,i,s,n);e.views.has(t._queryIdentifier)||e.views.set(t._queryIdentifier,o),o.eventRegistrations_.push(r);{s=r,o=(i=o).viewCache_.eventCache;let n=[];return o.getNode().isLeafNode()||o.getNode().forEachChild(x,(e,t)=>{n.push(nn(e,t))}),o.isFullyInitialized()&&n.push(tn(o.getNode())),br(i,n,o.getNode(),s)}}function Nr(e,t,n,r){var i=t._queryIdentifier,s=[];let o=[];var a=Ar(e);if("default"===i)for(var[l,h]of e.views.entries())o=o.concat(wr(h,n,r)),yr(h)&&(e.views.delete(l),h.query._queryParams.loadsAllData()||s.push(h.query));else{var c=e.views.get(i);c&&(o=o.concat(wr(c,n,r)),yr(c))&&(e.views.delete(i),c.query._queryParams.loadsAllData()||s.push(c.query))}return a&&!Ar(e)&&s.push((f(Tr,"Reference.ts has not been loaded"),new Tr(t._repo,t._path))),{removed:s,events:o}}function Pr(e){var t,n=[];for(t of e.views.values())t.query._queryParams.loadsAllData()||n.push(t);return n}function Rr(e,t){let n=null;for(var r of e.views.values())n=n||(i=r,s=t,r=void 0,(r=Fn(i.viewCache_))&&(i.query._queryParams.loadsAllData()||!E(s)&&!r.getImmediateChild(b(s)).isEmpty())?r.getChild(s):null);var i,s;return n}function xr(e,t){var n;return t._queryParams.loadsAllData()?Or(e):(n=t._queryIdentifier,e.views.get(n))}function Dr(e,t){return null!=xr(e,t)}function Ar(e){return null!=Or(e)}function Or(e){for(var t of e.views.values())if(t.query._queryParams.loadsAllData())return t;return null}let Lr;let Mr=1;class Fr{constructor(e){this.listenProvider_=e,this.syncPointTree_=new O(null),this.pendingWriteTree_={visibleWrites:Wn.empty(),allWrites:[],lastWriteId:-1},this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function qr(e,t,n,r,i){var s,o,a,l;return s=e.pendingWriteTree_,o=t,a=n,r=r,l=i,f(r>s.lastWriteId,"Stacking an older write on top of newer ones"),s.allWrites.push({path:o,snap:a,writeId:r,visible:l=void 0===l?!0:l}),l&&(s.visibleWrites=Bn(s.visibleWrites,o,a)),s.lastWriteId=r,i?Yr(e,new kn(bn(),t,n)):[]}function Wr(e,t,n,r){i=e.pendingWriteTree_,s=t,o=n,r=r,f(r>i.lastWriteId,"Stacking an older merge on top of newer ones"),i.allWrites.push({path:s,children:o,writeId:r,visible:!0}),i.visibleWrites=Un(i.visibleWrites,s,o),i.lastWriteId=r;var i,s,o,a=O.fromObject(n);return Yr(e,new Nn(bn(),t,a))}function Br(e,t,n=!1){var r=((e,t)=>{for(let r=0;r<e.allWrites.length;r++){var n=e.allWrites[r];if(n.writeId===t)return n}return null})(e.pendingWriteTree_,t);if($n(e.pendingWriteTree_,t)){let t=new O(null);return null!=r.snap?t=t.set(C(),!0):v(r.children,e=>{t=t.set(new w(e),!0)}),Yr(e,new En(r.path,t,n))}return[]}function Ur(e,t,n){return Yr(e,new kn(Tn(),t,n))}function jr(n,t,r,i,s=!1){var o=t._path,a=n.syncPointTree_.get(o);let l=[];if(a&&("default"===t._queryIdentifier||Dr(a,t))){var h=Nr(a,t,r,i),a=(0===a.views.size&&(n.syncPointTree_=n.syncPointTree_.remove(o)),h.removed);if(l=h.events,!s){var h=-1!==a.findIndex(e=>e._queryParams.loadsAllData()),c=n.syncPointTree_.findOnPath(o,(e,t)=>Ar(t));if(h&&!c){o=n.syncPointTree_.subtree(o);if(!o.isEmpty()){var u=o.fold((e,t,r)=>{if(t&&Ar(t))return[Or(t)];{let n=[];return t&&(n=Pr(t)),v(r,(e,t)=>{n=n.concat(t)}),n}});for(let e=0;e<u.length;++e){var d=u[e],_=d.query,d=Gr(n,d);n.listenProvider_.startListening(ti(_),$r(n,_),d.hashFn,d.onComplete)}}}!c&&0<a.length&&!i&&(h?n.listenProvider_.stopListening(ti(t),null):a.forEach(e=>{var t=n.queryToTagMap.get(Jr(e));n.listenProvider_.stopListening(ti(e),t)}))}var p=n,f=a;for(let e=0;e<f.length;++e){var g,m=f[e];m._queryParams.loadsAllData()||(m=Jr(m),g=p.queryToTagMap.get(m),p.queryToTagMap.delete(m),p.tagToQueryMap.delete(g))}}return l}function Vr(e,t,n,r){var i,s,o=Xr(e,r);return null!=o?(i=(o=Zr(o)).path,o=o.queryId,s=S(i,t),ei(e,i,new kn(In(o),s,n))):[]}function zr(e,t,n,r=!1){let i=t._path,s=null,o=!1,a=(e.syncPointTree_.foreachOnPath(i,(e,t)=>{var n=S(e,i);s=s||Rr(t,n),o=o||Ar(t)}),e.syncPointTree_.get(i));a?(o=o||Ar(a),s=s||Rr(a,C())):(a=new Ir,e.syncPointTree_=e.syncPointTree_.set(i,a));let l;null!=s?l=!0:(l=!1,s=D.EMPTY_NODE,e.syncPointTree_.subtree(i).foreachChild((e,t)=>{var n=Rr(t,C());n&&(s=s.updateImmediateChild(e,n))}));var h,c=Dr(a,t),u=(c||t._queryParams.loadsAllData()||(h=Jr(t),f(!e.queryToTagMap.has(h),"View does not exist, but we have a tag"),u=Mr++,e.queryToTagMap.set(h,u),e.tagToQueryMap.set(u,h)),Gn(e.pendingWriteTree_,i));let d=kr(a,t,n,u,s,l);return c||o||r||(h=xr(a,t),d=d.concat(((t,e,n)=>{var r=e._path,i=$r(t,e),s=Gr(t,n),s=t.listenProvider_.startListening(ti(e),i,s.hashFn,s.onComplete),r=t.syncPointTree_.subtree(r);if(i)f(!Ar(r.value),"If we're adding a query, it shouldn't be shadowed");else{var o=r.fold((e,t,r)=>{if(!E(e)&&t&&Ar(t))return[Or(t).query];{let n=[];return t&&(n=n.concat(Pr(t).map(e=>e.query))),v(r,(e,t)=>{n=n.concat(t)}),n}});for(let e=0;e<o.length;++e){var a=o[e];t.listenProvider_.stopListening(ti(a),$r(t,a))}}return s})(e,t,h))),d}function Hr(e,r,t){var n=e.pendingWriteTree_,i=e.syncPointTree_.findOnPath(r,(e,t)=>{var n=Rr(t,S(e,r));if(n)return n});return Zn(n,r,i,t,!0)}function Qr(e,t){let r=t._path,i=null,n=(e.syncPointTree_.foreachOnPath(r,(e,t)=>{var n=S(e,r);i=i||Rr(t,n)}),e.syncPointTree_.get(r));n?i=i||Rr(n,C()):(n=new Ir,e.syncPointTree_=e.syncPointTree_.set(r,n));var s=null!=i,o=s?new Pn(i,!0,!1):null,a=Gn(e.pendingWriteTree_,t._path);return Mn(Sr(n,t,a,s?o.getNode():D.EMPTY_NODE,s).viewCache_)}function Yr(e,t){return function o(t,a,l,h){{if(E(t.path))return Kr(t,a,l,h);{let e=a.get(C()),n=(null==l&&null!=e&&(l=Rr(e,C())),[]),r=b(t.path),i=t.operationForChild(r),s=a.children.get(r);if(s&&i){let e=l?l.getImmediateChild(r):null,t=or(h,r);n=n.concat(o(i,s,e,t))}return n=e?n.concat(Er(e,t,h,l)):n}}}(t,e.syncPointTree_,null,Gn(e.pendingWriteTree_,C()))}function Kr(s,e,o,a){var t=e.get(C());null==o&&null!=t&&(o=Rr(t,C()));let l=[];return e.children.inorderTraversal((e,t)=>{var n=o?o.getImmediateChild(e):null,r=or(a,e),i=s.operationForChild(e);i&&(l=l.concat(Kr(i,t,n,r)))}),l=t?l.concat(Er(t,s,a,o)):l}function Gr(a,e){let l=e.query,h=$r(a,l);return{hashFn:()=>(e.viewCache_.serverCache.getNode()||D.EMPTY_NODE).hash(),onComplete:e=>{var t,n,r,i,s,o;return"ok"===e?h?(t=a,n=l._path,r=h,(o=Xr(t,r))?(i=(o=Zr(o)).path,o=o.queryId,s=S(i,n),ei(t,i,new Sn(In(o),s))):[]):(r=a,n=l._path,Yr(r,new Sn(Tn(),n))):(i=((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");var r=new Error(e+" at "+t._path.toString()+": "+n);return r.code=e.toUpperCase(),r})(e,l),jr(a,l,null,i))}}}function $r(e,t){var n=Jr(t);return e.queryToTagMap.get(n)}function Jr(e){return e._path.toString()+"$"+e._queryIdentifier}function Xr(e,t){return e.tagToQueryMap.get(t)}function Zr(e){var t=e.indexOf("$");return f(-1!==t&&t<e.length-1,"Bad queryKey."),{queryId:e.substr(t+1),path:new w(e.substr(0,t))}}function ei(e,t,n){var r=e.syncPointTree_.get(t),i=(f(r,"Missing sync point for query tag that we're tracking"),Gn(e.pendingWriteTree_,t));return Er(r,n,i,null)}function ti(e){return e._queryParams.loadsAllData()&&!e._queryParams.isDefault()?(f(Lr,"Reference.ts has not been loaded"),new Lr(e._repo,e._path)):e}class ni{constructor(e){this.node_=e}getImmediateChild(e){var t=this.node_.getImmediateChild(e);return new ni(t)}node(){return this.node_}}class ri{constructor(e,t){this.syncTree_=e,this.path_=t}getImmediateChild(e){var t=I(this.path_,e);return new ri(this.syncTree_,t)}node(){return Hr(this.syncTree_,this.path_)}}let ii=function(e){return(e=e||{}).timestamp=e.timestamp||(new Date).getTime(),e},si=function(e,t,n){return e&&"object"==typeof e?(f(".sv"in e,"Unexpected leaf node or priority contents"),"string"==typeof e[".sv"]?oi(e[".sv"],t,n):"object"==typeof e[".sv"]?ai(e[".sv"],t):void f(!1,"Unexpected server value: "+JSON.stringify(e,null,2))):e},oi=function(e,t,n){if("timestamp"===e)return n.timestamp;f(!1,"Unexpected server value: "+e)},ai=function(e,t,n){e.hasOwnProperty("increment")||f(!1,"Unexpected server value: "+JSON.stringify(e,null,2));var r=e.increment,i=("number"!=typeof r&&f(!1,"Unexpected increment value: "+r),t.node());return f(null!=i,"Expected ChildrenNode.EMPTY_NODE for nulls"),!i.isLeafNode()||"number"!=typeof(i=i.getValue())?r:i+r},li=function(e,t,n,r){return ci(t,new ri(n,e),r)},hi=function(e,t,n){return ci(e,new ni(t),n)};function ci(e,r,i){var t,n,s=e.getPriority().val(),s=si(s,r.getImmediateChild(".priority"),i);let o;return e.isLeafNode()?(n=e,(t=si(n.getValue(),r,i))!==n.getValue()||s!==n.getPriority().val()?new R(t,A(s)):e):(n=e,s!==(o=n).getPriority().val()&&(o=o.updatePriority(new R(s))),n.forEachChild(x,(e,t)=>{var n=ci(t,r.getImmediateChild(e),i);n!==t&&(o=o.updateImmediateChild(e,n))}),o)}class ui{constructor(e="",t=null,n={children:{},childCount:0}){this.name=e,this.parent=t,this.node=n}}function di(e,t){let n=t instanceof w?t:new w(t),r=e,i=b(n);for(;null!==i;){var s=G(r.node.children,i)||{children:{},childCount:0};r=new ui(i,r,s),n=T(n),i=b(n)}return r}function _i(e){return e.node.value}function pi(e,t){e.node.value=t,vi(e)}function fi(e){return 0<e.node.childCount}function gi(n,r){v(n.node.children,(e,t)=>{r(new ui(e,n,t))})}function mi(e){return new w(null===e.parent?e.name:mi(e.parent)+"/"+e.name)}function vi(e){var t,n,r,i;null!==e.parent&&(t=e.parent,n=e.name,r=(e=>void 0===_i(e)&&!fi(e))(e=e),i=p(t.node.children,n),r&&i?(delete t.node.children[n],t.node.childCount--,vi(t)):r||i||(t.node.children[n]=e.node,t.node.childCount++,vi(t)))}function yi(e,t,n,r){r&&void 0===t||xi(h(e,"value"),t,n)}function wi(e,t,r,n){let i=h(e,"values");if(!t||"object"!=typeof t||Array.isArray(t))throw new Error(i+" must be an object containing the children to replace.");let s=[];v(t,(e,t)=>{var n=new w(e);if(xi(i,t,I(r,n)),".priority"===vt(n)&&!Ri(t))throw new Error(i+"contains an invalid value for '"+n.toString()+"', which must be a valid Firebase priority (a string, finite number, server value, or null).");s.push(n)});{var o=i,a=s;let t,n;for(t=0;t<a.length;t++){var l=yt(n=a[t]);for(let e=0;e<l.length;e++)if((".priority"!==l[e]||e!==l.length-1)&&!ki(l[e]))throw new Error(o+"contains an invalid key ("+l[e]+") in path "+n.toString()+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"')}a.sort(Ct);let e=null;for(t=0;t<a.length;t++){if(n=a[t],null!==e&&k(e,n))throw new Error(o+"contains a path "+e.toString()+" that is ancestor of another path "+n.toString());e=n}}}function Ci(e,t,n){if(Fe(t))throw new Error(h(e,"priority")+"is "+t.toString()+", but must be a valid Firebase priority (a string, finite number, server value, or null).");if(!Ri(t))throw new Error(h(e,"priority")+"must be a valid Firebase priority (a string, finite number, server value, or null).")}function bi(e,t,n,r){if(void 0!==n&&!ki(n))throw new Error(h(e,t)+'was an invalid key = "'+n+'". Firebase keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]").')}function Ti(e,t,n,r){n=n&&n.replace(/^\/*\.info(\/|$)/,"/"),Di(e,t,n)}function L(e,t){if(".info"===b(t))throw new Error(e+" failed = Can't modify data under /.info/")}let Ii=/[\[\].#$\/\u0000-\u001F\u007F]/,Ei=/[\[\].#$\u0000-\u001F\u007F]/,Si=10485760,ki=function(e){return"string"==typeof e&&0!==e.length&&!Ii.test(e)},Ni=function(e){return"string"==typeof e&&0!==e.length&&!Ei.test(e)},Pi=function(e){return e=e&&e.replace(/^\/*\.info(\/|$)/,"/"),Ni(e)},Ri=function(e){return null===e||"string"==typeof e||"number"==typeof e&&!Fe(e)||e&&"object"==typeof e&&p(e,".sv")},xi=function(o,e,t){let a=t instanceof w?new Tt(t,o):t;if(void 0===e)throw new Error(o+"contains undefined "+Et(a));if("function"==typeof e)throw new Error(o+"contains a function "+Et(a)+" with contents = "+e.toString());if(Fe(e))throw new Error(o+"contains "+e.toString()+" "+Et(a));if("string"==typeof e&&e.length>Si/3&&te(e)>Si)throw new Error(o+"contains a string greater than "+Si+" utf8 bytes "+Et(a)+" ('"+e.substring(0,50)+"...')");if(e&&"object"==typeof e){let i=!1,s=!1;if(v(e,(e,t)=>{if(".value"===e)i=!0;else if(".priority"!==e&&".sv"!==e&&(s=!0,!ki(e)))throw new Error(o+" contains an invalid key ("+e+") "+Et(a)+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');var n,r;n=a,e=e,0<n.parts_.length&&(n.byteLength_+=1),n.parts_.push(e),n.byteLength_+=te(e),It(n),xi(o,t,a),e=a,r=e.parts_.pop(),e.byteLength_-=te(r),0<e.parts_.length&&--e.byteLength_}),i&&s)throw new Error(o+' contains ".value" child '+Et(a)+" in addition to actual children.")}},Di=function(e,t,n,r){if(!Ni(n))throw new Error(h(e,t)+'was an invalid path = "'+n+'". Paths must be non-empty strings and can\'t contain ".", "#", "$", "[", or "]"')},Ai=function(e,t){var n=t.path.toString();if("string"!=typeof t.repoInfo.host||0===t.repoInfo.host.length||!ki(t.repoInfo.namespace)&&"localhost"!==t.repoInfo.host.split(":")[0]||0!==n.length&&!Pi(n))throw new Error(h(e,"url")+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')};class Oi{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function Li(e,t){let n=null;for(let s=0;s<t.length;s++){var r=t[s],i=r.getPath();null===n||bt(i,n.path)||(e.eventLists_.push(n),n=null),(n=null===n?{events:[],path:i}:n).events.push(r)}n&&e.eventLists_.push(n)}function Mi(e,t,n){Li(e,n),Fi(e,e=>bt(e,t))}function M(e,t,n){Li(e,n),Fi(e,e=>k(e,t)||k(t,e))}function Fi(t,e){t.recursionDepth_++;let n=!0;for(let a=0;a<t.eventLists_.length;a++){var r=t.eventLists_[a];if(r)if(e(r.path)){s=o=i=void 0;var i=t.eventLists_[a];for(let e=0;e<i.events.length;e++){var s,o=i.events[e];null!==o&&(i.events[e]=null,s=o.getEventRunner(),De&&u("event: "+o.toString()),Ye(s))}t.eventLists_[a]=null}else n=!1}n&&(t.eventLists_=[]),t.recursionDepth_--}let qi="repo_interrupt",Wi=25;class Bi{constructor(e,t,n,r){this.repoInfo_=e,this.forceRestClient_=t,this.authTokenProvider_=n,this.appCheckProvider_=r,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new Oi,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=mn(),this.transactionQueueTree_=new ui,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function Ui(o,e,t){if(o.stats_=st(o.repoInfo_),o.forceRestClient_||0<=("object"==typeof window&&window.navigator&&window.navigator.userAgent||"").search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i))o.server_=new fn(o.repoInfo_,(e,t,n,r)=>{zi(o,e,t,n,r)},o.authTokenProvider_,o.appCheckProvider_),setTimeout(()=>Hi(o,!0),0);else{if(null!=t){if("object"!=typeof t)throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{a(t)}catch(e){throw new Error("Invalid authOverride provided: "+e)}}o.persistentConnection_=new kt(o.repoInfo_,e,(e,t,n,r)=>{zi(o,e,t,n,r)},e=>{Hi(o,e)},e=>{var n;n=o,v(e,(e,t)=>{Qi(n,e,t)})},o.authTokenProvider_,o.appCheckProvider_,t),o.server_=o.persistentConnection_}var n;o.authTokenProvider_.addTokenChangeListener(e=>{o.server_.refreshAuthToken(e)}),o.appCheckProvider_.addTokenChangeListener(e=>{o.server_.refreshAppCheckToken(e.token)}),o.statsReporter_=(e=()=>new Cn(o.stats_,o.server_),n=o.repoInfo_.toString(),it[n]||(it[n]=e()),it[n]),o.infoData_=new gn,o.infoSyncTree_=new Fr({startListening:(e,t,n,r)=>{let i=[];var s=o.infoData_.getNode(e._path);return s.isEmpty()||(i=Ur(o.infoSyncTree_,e._path,s),setTimeout(()=>{r("ok")},0)),i},stopListening:()=>{}}),Qi(o,"connected",!1),o.serverSyncTree_=new Fr({startListening:(r,e,t,i)=>(o.server_.listen(r,t,e,(e,t)=>{var n=i(e,t);M(o.eventQueue_,r._path,n)}),[]),stopListening:(e,t)=>{o.server_.unlisten(e,t)}})}function ji(e){var t=e.infoData_.getNode(new w(".info/serverTimeOffset")).val()||0;return(new Date).getTime()+t}function Vi(e){return ii({timestamp:ji(e)})}function zi(e,t,n,r,i){e.dataUpdateCount++;var s,o,a,l,h,c,u=new w(t);n=e.interceptServerDataCallback_?e.interceptServerDataCallback_(t,n):n;let d=[],_=u;0<(d=i?r?(c=J(n,e=>A(e)),t=e.serverSyncTree_,s=u,o=c,(c=Xr(t,i))?(a=(c=Zr(c)).path,c=c.queryId,l=S(a,s),h=O.fromObject(o),ei(t,a,new Nn(In(c),l,h))):[]):(a=A(n),Vr(e.serverSyncTree_,u,a,i)):r?(c=J(n,e=>A(e)),s=e.serverSyncTree_,o=u,t=c,l=O.fromObject(t),Yr(s,new Nn(Tn(),o,l))):(h=A(n),Ur(e.serverSyncTree_,u,h))).length&&(_=rs(e,u)),M(e.eventQueue_,_,d)}function Hi(e,t){if(Qi(e,"connected",t),!1===t){var o=e;Zi(o,"onDisconnectEvents");let r=Vi(o),i=mn(),s=(yn(o.onDisconnect_,C(),(e,t)=>{var n=li(e,t,o.serverSyncTree_,r);vn(i,e,n)}),[]);yn(i,C(),(e,t)=>{s=s.concat(Ur(o.serverSyncTree_,e,t));var n=as(o,e);rs(o,n)}),o.onDisconnect_=mn(),M(o.eventQueue_,C(),s)}}function Qi(e,t,n){var r=new w("/.info/"+t),i=A(n),i=(e.infoData_.updateSnapshot(r,i),Ur(e.infoSyncTree_,r,i));M(e.eventQueue_,r,i)}function Yi(e){return e.nextWriteId_++}function Ki(r,i,e,t,s){Zi(r,"set",{path:i.toString(),value:e,priority:t});var n=Vi(r),o=A(e,t),a=Hr(r.serverSyncTree_,i),a=hi(o,a,n);let l=Yi(r);n=qr(r.serverSyncTree_,i,a,l,!0),Li(r.eventQueue_,n),r.server_.put(i.toString(),o.val(!0),(e,t)=>{var n="ok"===e,n=(n||m("set at "+i+" failed: "+e),Br(r.serverSyncTree_,l,!n));M(r.eventQueue_,i,n),es(0,s,e,t)}),a=as(r,i);rs(r,a),M(r.eventQueue_,a,[])}function Gi(n,r,i){n.server_.onDisconnectCancel(r.toString(),(e,t)=>{"ok"===e&&!function e(n,t){var r;return E(t)?(n.value=null,n.children.clear(),!0):null!==n.value?!n.value.isLeafNode()&&(r=n.value,n.value=null,r.forEachChild(x,(e,t)=>{vn(n,new w(e),t)}),e(n,t)):!(0<n.children.size)||(r=b(t),t=T(t),n.children.has(r)&&e(n.children.get(r),t)&&n.children.delete(r),0===n.children.size)}(n.onDisconnect_,r),es(0,i,e,t)})}function $i(n,r,e,i){let s=A(e);n.server_.onDisconnectPut(r.toString(),s.val(!0),(e,t)=>{"ok"===e&&vn(n.onDisconnect_,r,s),es(0,i,e,t)})}function Ji(e,t,n){let r;r=".info"===b(t._path)?jr(e.infoSyncTree_,t,n):jr(e.serverSyncTree_,t,n),Mi(e.eventQueue_,t._path,r)}function Xi(e){e.persistentConnection_&&e.persistentConnection_.interrupt(qi)}function Zi(e,...t){let n="";e.persistentConnection_&&(n=e.persistentConnection_.id+":"),u(n,...t)}function es(e,r,i,s){r&&Ye(()=>{if("ok"===i)r(null);else{var t=(i||"error").toUpperCase();let e=t;s&&(e+=": "+s);var n=new Error(e);n.code=t,r(n)}})}function ts(e,t,n){return Hr(e.serverSyncTree_,t,n)||D.EMPTY_NODE}function ns(a,l=a.transactionQueueTree_){if(l||os(a,l),_i(l)){var h=ss(a,l),e=(f(0<h.length,"Sending zero length transaction queue"),h.every(e=>0===e.status));if(e){var c=a;var u=mi(l);var d=h;let e=d.map(e=>e.currentWriteId),t=ts(c,u,e),n=t,r=t.hash();for(let o=0;o<d.length;o++){var _=d[o],p=(f(0===_.status,"tryToSendTransactionQueue_: items in queue should all be run."),_.status=1,_.retryCount++,S(u,_.path));n=n.updateChild(p,_.currentOutputSnapshotRaw)}let i=n.val(!0),s=u;c.server_.put(s.toString(),i,t=>{Zi(c,"transaction put response",{path:s.toString(),status:t});let n=[];if("ok"===t){var r=[];for(let e=0;e<d.length;e++)d[e].status=2,n=n.concat(Br(c.serverSyncTree_,d[e].currentWriteId)),d[e].onComplete&&r.push(()=>d[e].onComplete(null,!0,d[e].currentOutputSnapshotResolved)),d[e].unwatcher();os(c,di(c.transactionQueueTree_,u)),ns(c,c.transactionQueueTree_),M(c.eventQueue_,u,n);for(let t=0;t<r.length;t++)Ye(r[t])}else{if("datastale"===t)for(let e=0;e<d.length;e++)3===d[e].status?d[e].status=4:d[e].status=0;else{m("transaction at "+s.toString()+" failed: "+t);for(let e=0;e<d.length;e++)d[e].status=4,d[e].abortReason=t}rs(c,u)}},r)}}else fi(l)&&gi(l,e=>{ns(a,e)})}function rs(e,t){var n=is(e,t),r=mi(n),n=ss(e,n),i=e,s=n,o=r;if(0!==s.length){var a=[];let n=[];var l=s.filter(e=>0===e.status).map(e=>e.currentWriteId);for(let r=0;r<s.length;r++){var h=s[r],c=S(o,h.path);let e=!1,t;if(f(null!==c,"rerunTransactionsUnderNode_: relativePath should not be null."),4===h.status)e=!0,t=h.abortReason,n=n.concat(Br(i.serverSyncTree_,h.currentWriteId,!0));else if(0===h.status)if(h.retryCount>=Wi)e=!0,t="maxretry",n=n.concat(Br(i.serverSyncTree_,h.currentWriteId,!0));else{var c=ts(i,h.path,l),u=(h.currentInputSnapshot=c,s[r].update(c.val()));if(void 0!==u){xi("transaction failed: Data returned ",u,h.path);let e=A(u);"object"==typeof u&&null!=u&&p(u,".priority")||(e=e.updatePriority(c.getPriority()));var u=h.currentWriteId,d=Vi(i),c=hi(e,c,d);h.currentOutputSnapshotRaw=e,h.currentOutputSnapshotResolved=c,h.currentWriteId=Yi(i),l.splice(l.indexOf(u),1),n=(n=n.concat(qr(i.serverSyncTree_,h.path,c,h.currentWriteId,h.applyLocally))).concat(Br(i.serverSyncTree_,u,!0))}else e=!0,t="nodata",n=n.concat(Br(i.serverSyncTree_,h.currentWriteId,!0))}M(i.eventQueue_,o,n),n=[],e&&(s[r].status=2,(e=>{setTimeout(e,Math.floor(0))})(s[r].unwatcher),s[r].onComplete)&&("nodata"===t?a.push(()=>s[r].onComplete(null,!1,s[r].currentInputSnapshot)):a.push(()=>s[r].onComplete(new Error(t),!1,null)))}os(i,i.transactionQueueTree_);for(let e=0;e<a.length;e++)Ye(a[e]);ns(i,i.transactionQueueTree_)}return r}function is(e,t){let n,r=e.transactionQueueTree_;for(n=b(t);null!==n&&void 0===_i(r);)r=di(r,n),t=T(t),n=b(t);return r}function ss(e,t){var n=[];return function t(n,e,r){let i=_i(e);if(i)for(let e=0;e<i.length;e++)r.push(i[e]);gi(e,e=>{t(n,e,r)})}(e,t,n),n.sort((e,t)=>e.order-t.order),n}function os(t,n){var r=_i(n);if(r){let e=0;for(let t=0;t<r.length;t++)2!==r[t].status&&(r[e]=r[t],e++);r.length=e,pi(n,0<r.length?r:void 0)}gi(n,e=>{os(t,e)})}function as(t,e){var n=mi(is(t,e)),r=di(t.transactionQueueTree_,e);return((e,t)=>{let n=e.parent;for(;null!==n;){if(t(n))return;n=n.parent}})(r,e=>{ls(t,e)}),ls(t,r),function t(e,n,r){r&&n(e),gi(e,e=>{t(e,n,!0)})}(r,e=>{ls(t,e)}),n}function ls(i,s){var o=_i(s);if(o){var a=[];let e=[],t=-1;for(let n=0;n<o.length;n++)3!==o[n].status&&(1===o[n].status?(f(t===n-1,"All SENT items should be at beginning of queue."),o[t=n].status=3,o[n].abortReason="set"):(f(0===o[n].status,"Unexpected transaction status in abort"),o[n].unwatcher(),e=e.concat(Br(i.serverSyncTree_,o[n].currentWriteId,!0)),o[n].onComplete&&a.push(o[n].onComplete.bind(null,new Error("set"),!1,null))));-1===t?pi(s,void 0):o.length=t+1,M(i.eventQueue_,mi(s),e);for(let r=0;r<a.length;r++)Ye(a[r])}}let hs=function(e,t){var n=cs(e),r=n.namespace,i=("firebase.com"===n.domain&&Le(n.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),r&&"undefined"!==r||"localhost"===n.domain||Le("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),n.secure||Me(),"ws"===n.scheme||"wss"===n.scheme);return{repoInfo:new et(n.host,n.secure,r,i,t,"",r!==n.subdomain),path:new w(n.pathString)}},cs=function(r){let i="",s="",o="",a="",l="",h=!0,c="https",u=443;if("string"==typeof r){let e=r.indexOf("//"),t=(0<=e&&(c=r.substring(0,e-1),r=r.substring(e+2)),r.indexOf("/")),n=(-1===t&&(t=r.length),r.indexOf("?"));-1===n&&(n=r.length),i=r.substring(0,Math.min(t,n)),t<n&&(a=(e=>{let t="";var n=e.split("/");for(let r=0;r<n.length;r++)if(0<n[r].length){let e=n[r];try{e=decodeURIComponent(e.replace(/\+/g," "))}catch(e){}t+="/"+e}return t})(r.substring(t,n)));var d=(e=>{var t,n,r={};for(t of(e="?"===e.charAt(0)?e.substring(1):e).split("&"))0!==t.length&&(2===(n=t.split("=")).length?r[decodeURIComponent(n[0])]=decodeURIComponent(n[1]):m(`Invalid query segment '${t}' in query '${e}'`));return r})(r.substring(Math.min(r.length,n))),_=(0<=(e=i.indexOf(":"))?(h="https"===c||"wss"===c,u=parseInt(i.substring(e+1),10)):e=i.length,i.slice(0,e));"localhost"===_.toLowerCase()?s="localhost":_.split(".").length<=2?s=_:(_=i.indexOf("."),o=i.substring(0,_).toLowerCase(),s=i.substring(_+1),l=o),"ns"in d&&(l=d.ns)}return{host:i,port:u,domain:s,subdomain:o,secure:h,scheme:c,pathString:a,namespace:l}},us="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",ds=(()=>{let s=0,o=[];return function(e){var t=e===s;s=e;let n;var r=new Array(8);for(n=7;0<=n;n--)r[n]=us.charAt(e%64),e=Math.floor(e/64);f(0===e,"Cannot push at time == 0");let i=r.join("");if(t){for(n=11;0<=n&&63===o[n];n--)o[n]=0;o[n]++}else for(n=0;n<12;n++)o[n]=Math.floor(64*Math.random());for(n=0;n<12;n++)i+=us.charAt(o[n]);return f(20===i.length,"nextPushId: Length should be 20."),i}})();class _s{constructor(e,t,n,r){this.eventType=e,this.eventRegistration=t,this.snapshot=n,this.prevName=r}getPath(){var e=this.snapshot.ref;return("value"===this.eventType?e:e.parent)._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+a(this.snapshot.exportVal())}}class ps{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 fs{constructor(e,t){this.snapshotCallback=e,this.cancelCallback=t}onValue(e,t){this.snapshotCallback.call(null,e,t)}onCancel(e){return f(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}}let gs=class{constructor(e,t){this._repo=e,this._path=t}cancel(){var e=new _;return Gi(this._repo,this._path,e.wrapCallback(()=>{})),e.promise}remove(){L("OnDisconnect.remove",this._path);var e=new _;return $i(this._repo,this._path,null,e.wrapCallback(()=>{})),e.promise}set(e){L("OnDisconnect.set",this._path),yi("OnDisconnect.set",e,this._path,!1);var t=new _;return $i(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}setWithPriority(e,t){L("OnDisconnect.setWithPriority",this._path),yi("OnDisconnect.setWithPriority",e,this._path,!1),Ci("OnDisconnect.setWithPriority",t);var r=new _;{var i=this._repo,s=this._path,o=r.wrapCallback(()=>{});let n=A(e,t);i.server_.onDisconnectPut(s.toString(),n.val(!0),(e,t)=>{"ok"===e&&vn(i.onDisconnect_,s,n),es(0,o,e,t)})}return r.promise}update(e){L("OnDisconnect.update",this._path),wi("OnDisconnect.update",e,this._path);var r,i,n,s,t=new _;return r=this._repo,i=this._path,n=e,s=t.wrapCallback(()=>{}),$(n)?(u("onDisconnect().update() called with empty data. Don't do anything."),es(0,s,"ok",void 0)):r.server_.onDisconnectMerge(i.toString(),n,(e,t)=>{"ok"===e&&v(n,(e,t)=>{var n=A(t);vn(r.onDisconnect_,I(i,e),n)}),es(0,s,e,t)}),t.promise}};class i{constructor(e,t,n,r){this._repo=e,this._path=t,this._queryParams=n,this._orderByCalled=r}get key(){return E(this._path)?null:vt(this._path)}get ref(){return new ws(this._repo,this._path)}get _queryIdentifier(){var e=pn(this._queryParams),e=Ee(e);return"{}"===e?"default":e}get _queryObject(){return pn(this._queryParams)}isEqual(e){var t,n,r;return(e=g(e))instanceof i&&(t=this._repo===e._repo,n=bt(this._path,e._path),r=this._queryIdentifier===e._queryIdentifier,t)&&n&&r}toJSON(){return this.toString()}toString(){return this._repo.toString()+(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 ms(e,t){if(!0===e._orderByCalled)throw new Error(t+": You can't combine multiple orderBy calls.")}function vs(e){let t=null,n=null;if(e.hasStart()&&(t=e.getIndexStartValue()),e.hasEnd()&&(n=e.getIndexEndValue()),e.getIndex()===xt){var r="Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().",i="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()!==qe)throw new Error(r);if("string"!=typeof t)throw new Error(i)}if(e.hasEnd()){if(e.getIndexEndName()!==We)throw new Error(r);if("string"!=typeof n)throw new Error(i)}}else if(e.getIndex()===x){if(null!=t&&!Ri(t)||null!=n&&!Ri(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(f(e.getIndex()instanceof Xt||e.getIndex()===en,"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 ys(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 ws extends i{constructor(e,t){super(e,t,new hn,!1)}get parent(){var e=wt(this._path);return null===e?null:new ws(this._repo,e)}get root(){let e=this;for(;null!==e.parent;)e=e.parent;return e}}let Cs=class fo{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){var t=new w(e),n=Is(this.ref,e);return new fo(this._node.getChild(t),n,x)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(n){return!this._node.isLeafNode()&&!!this._node.forEachChild(this._index,(e,t)=>n(new fo(t,Is(this.ref,e),x)))}hasChild(e){var t=new w(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 bs(e,t){return(e=g(e))._checkNotDeleted("ref"),void 0!==t?Is(e._root,t):e._root}function Ts(e,t){(e=g(e))._checkNotDeleted("refFromURL");var n=hs(t,e._repo.repoInfo_.nodeAdmin),r=(Ai("refFromURL",n),n.repoInfo);return e._repo.repoInfo_.isCustomHost()||r.host===e._repo.repoInfo_.host||Le("refFromURL: Host name does not match the current database: (found "+r.host+" but expected "+e._repo.repoInfo_.host+")"),bs(e,n.path.toString())}function Is(e,t){return(null===b((e=g(e))._path)?Ti:Di)("child","path",t),new ws(e._repo,I(e._path,t))}function Es(e,t){e=g(e),L("set",e._path),yi("set",t,e._path,!1);var n=new _;return Ki(e._repo,e._path,t,null,n.wrapCallback(()=>{})),n.promise}function Ss(e,t){wi("update",t,e._path);var i=new _;{var o=e._repo,a=e._path,l=(e=t,i.wrapCallback(()=>{}));Zi(o,"update",{path:a.toString(),value:e});let n=!0,r=Vi(o),s={};if(v(e,(e,t)=>{n=!1,s[e]=li(I(a,e),A(t),o.serverSyncTree_,r)}),n)u("update() called with empty data. Don't do anything."),es(0,l,"ok",void 0);else{let i=Yi(o);var h=Wr(o.serverSyncTree_,a,s,i);Li(o.eventQueue_,h),o.server_.merge(a.toString(),e,(e,t)=>{var n="ok"===e,n=(n||m("update at "+a+" failed: "+e),Br(o.serverSyncTree_,i,!n)),r=0<n.length?rs(o,a):a;M(o.eventQueue_,r,n),es(0,l,e,t)}),v(e,e=>{var t=as(o,I(a,e));rs(o,t)}),M(o.eventQueue_,a,[])}}return i.promise}function ks(t){t=g(t);var i,s,o,e=new fs(()=>{}),e=new Ns(e);return i=t._repo,s=t,o=e,(null!=(e=Qr(i.serverSyncTree_,s))?Promise.resolve(e):i.server_.get(s).then(e=>{var t,n=A(e).withIndex(s._queryParams.getIndex());zr(i.serverSyncTree_,s,o,!0);let r;return r=s._queryParams.loadsAllData()?Ur(i.serverSyncTree_,s._path,n):(t=$r(i.serverSyncTree_,s),Vr(i.serverSyncTree_,s._path,n,t)),M(i.eventQueue_,s._path,r),jr(i.serverSyncTree_,s,o,null,!0),n},e=>(Zi(i,"get for query "+a(s)+" failed: "+e),Promise.reject(new Error(e))))).then(e=>new Cs(e,new ws(t._repo,t._path),t._queryParams.getIndex()))}class Ns{constructor(e){this.callbackContext=e}respondsTo(e){return"value"===e}createEvent(e,t){var n=t._queryParams.getIndex();return new _s("value",this,new Cs(e.snapshotNode,new ws(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 ps(this,e,t):null}matches(e){return e instanceof Ns&&(!e.callbackContext||!this.callbackContext||e.callbackContext.matches(this.callbackContext))}hasAnyCallback(){return null!==this.callbackContext}}class Ps{constructor(e,t){this.eventType=e,this.callbackContext=t}respondsTo(e){var t="children_added"===e?"child_added":e;return this.eventType===("children_removed"===t?"child_removed":t)}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new ps(this,e,t):null}createEvent(e,t){f(null!=e.childName,"Child events should have a childName.");var n=Is(new ws(t._repo,t._path),e.childName),r=t._queryParams.getIndex();return new _s(e.type,this,new Cs(e.snapshotNode,n,r),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 Ps&&this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext))}hasAnyCallback(){return!!this.callbackContext}}function Rs(r,e,t,n,i){let s;if("object"==typeof n&&(s=void 0,i=n),"function"==typeof n&&(s=n),i&&i.onlyOnce){let n=t;var o=(e,t)=>{Ji(r._repo,r,a),n(e,t)};o.userCallback=t.userCallback,o.context=t.context,t=o}o=new fs(t,s||void 0);let a="value"===e?new Ns(o):new Ps(e,o);{n=r._repo,i=r,t=a;let e;e=".info"===b(i._path)?zr(n.infoSyncTree_,i,t):zr(n.serverSyncTree_,i,t),Mi(n.eventQueue_,i._path,e)}return()=>Ji(r._repo,r,a)}function xs(e,t,n,r){return Rs(e,"value",t,n,r)}function Ds(e,t,n,r){Rs(e,"child_added",t,n,r)}function As(e,t,n,r){Rs(e,"child_changed",t,n,r)}function Os(e,t,n,r){Rs(e,"child_moved",t,n,r)}function Ls(e,t,n,r){Rs(e,"child_removed",t,n,r)}function Ms(e,t,n){let r=null;var i=n?new fs(n):null;"value"===t?r=new Ns(i):t&&(r=new Ps(t,i)),Ji(e._repo,e,r)}class Fs{}class qs extends Fs{constructor(e,t){super(),this._value=e,this._key=t,this.type="endAt"}_apply(e){yi("endAt",this._value,e._path,!0);var t=un(e._queryParams,this._value,this._key);if(ys(t),vs(t),e._queryParams.hasEnd())throw new Error("endAt: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new i(e._repo,e._path,t,e._orderByCalled)}}class Ws extends Fs{constructor(e,t){super(),this._value=e,this._key=t,this.type="endBefore"}_apply(e){yi("endBefore",this._value,e._path,!1);var t=((e,t,n)=>{let r;return(r=e.index_===xt||n?un(e,t,n):un(e,t,qe)).endBeforeSet_=!0,r})(e._queryParams,this._value,this._key);if(ys(t),vs(t),e._queryParams.hasEnd())throw new Error("endBefore: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new i(e._repo,e._path,t,e._orderByCalled)}}class Bs extends Fs{constructor(e,t){super(),this._value=e,this._key=t,this.type="startAt"}_apply(e){yi("startAt",this._value,e._path,!0);var t=cn(e._queryParams,this._value,this._key);if(ys(t),vs(t),e._queryParams.hasStart())throw new Error("startAt: Starting point was already set (by another call to startAt, startBefore or equalTo).");return new i(e._repo,e._path,t,e._orderByCalled)}}class Us extends Fs{constructor(e,t){super(),this._value=e,this._key=t,this.type="startAfter"}_apply(e){yi("startAfter",this._value,e._path,!1);var t=((e,t,n)=>{let r;return(r=e.index_===xt||n?cn(e,t,n):cn(e,t,We)).startAfterSet_=!0,r})(e._queryParams,this._value,this._key);if(ys(t),vs(t),e._queryParams.hasStart())throw new Error("startAfter: Starting point was already set (by another call to startAt, startAfter, or equalTo).");return new i(e._repo,e._path,t,e._orderByCalled)}}class js extends Fs{constructor(e){super(),this._limit=e,this.type="limitToFirst"}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToFirst: Limit was already set (by another call to limitToFirst or limitToLast).");return new i(e._repo,e._path,(t=e._queryParams,n=this._limit,(r=t.copy()).limitSet_=!0,r.limit_=n,r.viewFrom_="l",r),e._orderByCalled);var t,n,r}}class Vs extends Fs{constructor(e){super(),this._limit=e,this.type="limitToLast"}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToLast: Limit was already set (by another call to limitToFirst or limitToLast).");return new i(e._repo,e._path,(t=e._queryParams,n=this._limit,(r=t.copy()).limitSet_=!0,r.limit_=n,r.viewFrom_="r",r),e._orderByCalled);var t,n,r}}class zs extends Fs{constructor(e){super(),this._path=e,this.type="orderByChild"}_apply(e){ms(e,"orderByChild");var t=new w(this._path);if(E(t))throw new Error("orderByChild: cannot pass in empty path. Use orderByValue() instead.");t=new Xt(t),t=dn(e._queryParams,t);return vs(t),new i(e._repo,e._path,t,!0)}}class Hs extends Fs{constructor(){super(...arguments),this.type="orderByKey"}_apply(e){ms(e,"orderByKey");var t=dn(e._queryParams,xt);return vs(t),new i(e._repo,e._path,t,!0)}}class Qs extends Fs{constructor(){super(...arguments),this.type="orderByPriority"}_apply(e){ms(e,"orderByPriority");var t=dn(e._queryParams,x);return vs(t),new i(e._repo,e._path,t,!0)}}class Ys extends Fs{constructor(){super(...arguments),this.type="orderByValue"}_apply(e){ms(e,"orderByValue");var t=dn(e._queryParams,en);return vs(t),new i(e._repo,e._path,t,!0)}}class Ks extends Fs{constructor(e,t){super(),this._value=e,this._key=t,this.type="equalTo"}_apply(e){if(yi("equalTo",this._value,e._path,!1),e._queryParams.hasStart())throw new Error("equalTo: Starting point was already set (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 qs(this._value,this._key)._apply(new Bs(this._value,this._key)._apply(e))}}function Gs(e,...t){let n=g(e);for(var r of t)n=r._apply(n);return n}e=ws,f(!Tr,"__referenceConstructor has already been defined"),Tr=e,e=ws,f(!Lr,"__referenceConstructor has already been defined"),Lr=e;let $s="FIREBASE_DATABASE_EMULATOR_HOST",Js={},Xs=!1;function Zs(e,t,n,r,i){let s=r||e.options.databaseURL,o=(void 0===s&&(e.options.projectId||Le("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),u("Using default host for project ",e.options.projectId),s=e.options.projectId+"-default-rtdb.firebaseio.com"),hs(s,i)),a=o.repoInfo,l,h=void 0;(h="undefined"!=typeof process&&process.env?process.env[$s]:h)?(l=!0,s=`http://${h}?ns=`+a.namespace,o=hs(s,i),a=o.repoInfo):l=!o.repoInfo.secure;var c=i&&l?new $e($e.OWNER):new Ge(e.name,e.options,t),c=(Ai("Invalid Firebase Database URL",o),E(o.path)||Le("Database URL must point to the root of a Firebase Database (not including a child path)."),((e,t,n,r)=>{let i=Js[t.name];var s;return i||(i={},Js[t.name]=i),(s=i[e.toURLString()])&&Le("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call."),s=new Bi(e,Xs,n,r),i[e.toURLString()]=s})(a,e,c,new Ke(e,n)));return new eo(c,e)}let eo=class{constructor(e,t){this._repoInternal=e,this.app=t,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(Ui(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new ws(this._repo,C())),this._rootInternal}_delete(){var e,t,n;return null!==this._rootInternal&&(e=this._repo,t=this.app.name,(n=Js[t])&&n[e.key]===e||Le(`Database ${t}(${e.repoInfo_}) has already been deleted.`),Xi(e),delete n[e.key],this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){null===this._rootInternal&&Le("Cannot call "+e+" on a deleted database.")}};function to(){ct.IS_TRANSPORT_INITIALIZED&&m("Transport has already been initialized. Please call this function before calling ref or setting up a listener")}function no(){to(),at.forceDisallow()}function ro(){to(),y.forceDisallow(),at.forceAllow()}function io(e,t,n,r={}){(e=g(e))._checkNotDeleted("useEmulator");var i,s=t+":"+n,o=e._repoInternal;if(e._instanceStarted){if(s===e._repoInternal.repoInfo_.host&&function e(t,n){if(t!==n){var r,i,s=Object.keys(t),o=Object.keys(n);for(r of s){if(!o.includes(r))return;var a=t[r],l=n[r];if(X(a)&&X(l)){if(!e(a,l))return}else if(a!==l)return}for(i of o)if(!s.includes(i))return}return 1}(r,o.repoInfo_.emulatorOptions))return;Le("connectDatabaseEmulator() cannot initialize or alter the emulator configuration after the database instance has started.")}let a=void 0;o.repoInfo_.nodeAdmin?(r.mockUserToken&&Le('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),a=new $e($e.OWNER)):r.mockUserToken&&(i="string"==typeof r.mockUserToken?r.mockUserToken:((e,t)=>{if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');var n=t||"demo-project",r=e.iat||0,i=e.sub||e.user_id;if(i)return n={iss:"https://securetoken.google.com/"+n,aud:n,iat:r,exp:r+3600,auth_time:r,sub:i,user_id:i,firebase:{sign_in_provider:"custom",identities:{}},...e},[V(JSON.stringify({alg:"none",type:"JWT"})),V(JSON.stringify(n)),""].join(".");throw new Error("mockUserToken must contain 'sub' or 'user_id' field!")})(r.mockUserToken,e.app.options.projectId),a=new $e(i)),ne(t)&&(async e=>(await fetch(e,{credentials:"include"})).ok)(t),n=o,e=s,t=r,r=a,i=e.lastIndexOf(":"),i=ne(e.substring(0,i)),n.repoInfo_=new et(e,i,n.repoInfo_.namespace,n.repoInfo_.webSocketOnly,n.repoInfo_.nodeAdmin,n.repoInfo_.persistenceKey,n.repoInfo_.includeNamespaceInQueryParams,!0,t),r&&(n.authTokenProvider_=r)}function so(e){(e=g(e))._checkNotDeleted("goOnline"),(e=e._repo).persistentConnection_&&e.persistentConnection_.resume(qi)}function oo(e,t){Oe(e,t)}let ao={".sv":"timestamp"};let lo=class{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}};function ho(i,e,t){if(i=g(i),L("Reference.transaction",i._path),".length"===i.key||".keys"===i.key)throw"Reference.transaction failed: "+i.key+" is a read-only object.";var n=t?.applyLocally??!0;let s=new _;var r=xs(i,()=>{}),t=i._repo,o=i._path,a=(e,t,n)=>{var r;e?s.reject(e):(r=new Cs(n,new ws(i._repo,i._path),x),s.resolve(new lo(t,r)))},l=r,h=n;Zi(t,"transaction on "+o);var c,r={path:o,update:e,onComplete:a,status:null,order:Re(),applyLocally:h,retryCount:0,unwatcher:l,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},n=ts(t,o,void 0);if(r.currentInputSnapshot=n,void 0===(c=r.update(n.val())))r.unwatcher(),r.currentOutputSnapshotRaw=null,r.currentOutputSnapshotResolved=null,r.onComplete&&r.onComplete(null,!1,r.currentInputSnapshot);else{xi("transaction failed: Data returned ",c,r.path),r.status=0;var u=di(t.transactionQueueTree_,o),d=_i(u)||[];d.push(r),pi(u,d);let e;"object"==typeof c&&null!==c&&p(c,".priority")?(e=G(c,".priority"),f(Ri(e),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.")):(u=Hr(t.serverSyncTree_,o)||D.EMPTY_NODE,e=u.getPriority().val());d=Vi(t),u=A(c,e),c=hi(u,n,d),n=(r.currentOutputSnapshotRaw=u,r.currentOutputSnapshotResolved=c,r.currentWriteId=Yi(t),qr(t.serverSyncTree_,o,c,r.currentWriteId,r.applyLocally));M(t.eventQueue_,o,n),ns(t,t.transactionQueueTree_)}return s.promise}kt.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)},kt.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)},fe(wo.SDK_VERSION),wo._registerComponent(new re("database",(e,{instanceIdentifier:t})=>Zs(e.getProvider("app").getImmediate(),e.getProvider("auth-internal"),e.getProvider("app-check-internal"),t),"PUBLIC").setMultipleInstances(!0)),wo.registerVersion(de,_e,ye),wo.registerVersion(de,_e,"esm2020");function co(e){var t="FIREBASE WARNING: "+e;uo.warn(t)}let uo=new ue("@firebase/database-compat");class _o{constructor(e){this._delegate=e}cancel(t){l("OnDisconnect.cancel",0,1,arguments.length),c("OnDisconnect.cancel","onComplete",t,!0);var e=this._delegate.cancel();return t&&e.then(()=>t(null),e=>t(e)),e}remove(t){l("OnDisconnect.remove",0,1,arguments.length),c("OnDisconnect.remove","onComplete",t,!0);var e=this._delegate.remove();return t&&e.then(()=>t(null),e=>t(e)),e}set(e,t){l("OnDisconnect.set",1,2,arguments.length),c("OnDisconnect.set","onComplete",t,!0);var n=this._delegate.set(e);return t&&n.then(()=>t(null),e=>t(e)),n}setWithPriority(e,t,n){l("OnDisconnect.setWithPriority",2,3,arguments.length),c("OnDisconnect.setWithPriority","onComplete",n,!0);var r=this._delegate.setWithPriority(e,t);return n&&r.then(()=>n(null),e=>n(e)),r}update(t,n){if(l("OnDisconnect.update",1,2,arguments.length),Array.isArray(t)){var r={};for(let e=0;e<t.length;++e)r[""+e]=t[e];t=r,co("Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.")}c("OnDisconnect.update","onComplete",n,!0);var e=this._delegate.update(t);return n&&e.then(()=>n(null),e=>n(e)),e}}class po{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return l("TransactionResult.toJSON",0,1,arguments.length),{committed:this.committed,snapshot:this.snapshot.toJSON()}}}class fo{constructor(e,t){this._database=e,this._delegate=t}val(){return l("DataSnapshot.val",0,0,arguments.length),this._delegate.val()}exportVal(){return l("DataSnapshot.exportVal",0,0,arguments.length),this._delegate.exportVal()}toJSON(){return l("DataSnapshot.toJSON",0,1,arguments.length),this._delegate.toJSON()}exists(){return l("DataSnapshot.exists",0,0,arguments.length),this._delegate.exists()}child(e){return l("DataSnapshot.child",0,1,arguments.length),e=String(e),Di("DataSnapshot.child","path",e),new fo(this._database,this._delegate.child(e))}hasChild(e){return l("DataSnapshot.hasChild",1,1,arguments.length),Di("DataSnapshot.hasChild","path",e),this._delegate.hasChild(e)}getPriority(){return l("DataSnapshot.getPriority",0,0,arguments.length),this._delegate.priority}forEach(t){return l("DataSnapshot.forEach",1,1,arguments.length),c("DataSnapshot.forEach","action",t,!1),this._delegate.forEach(e=>t(new fo(this._database,e)))}hasChildren(){return l("DataSnapshot.hasChildren",0,0,arguments.length),this._delegate.hasChildren()}get key(){return this._delegate.key}numChildren(){return l("DataSnapshot.numChildren",0,0,arguments.length),this._delegate.size}getRef(){return l("DataSnapshot.ref",0,0,arguments.length),new o(this._database,this._delegate.ref)}get ref(){return this.getRef()}}class F{constructor(e,t){this.database=e,this._delegate=t}on(e,n,t,r){l("Query.on",2,4,arguments.length),c("Query.on","callback",n,!1);let i=F.getCancelAndContextArgs_("Query.on",t,r);var s=(e,t)=>{n.call(i.context,new fo(this.database,e),t)},o=(s.userCallback=n,s.context=i.context,i.cancel?.bind(i.context));switch(e){case"value":return xs(this._delegate,s,o),n;case"child_added":return Ds(this._delegate,s,o),n;case"child_removed":return Ls(this._delegate,s,o),n;case"child_changed":return As(this._delegate,s,o),n;case"child_moved":return Os(this._delegate,s,o),n;default:throw new Error(h("Query.on","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}}off(e,t,n){l("Query.off",0,3,arguments.length);var r,i="Query.off",s=e;if(void 0!==s)switch(s){case"value":case"child_added":case"child_removed":case"child_changed":case"child_moved":break;default:throw new Error(h(i,"eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}c("Query.off","callback",t,!0),ee("Query.off","context",n),t?((r=()=>{}).userCallback=t,r.context=n,Ms(this._delegate,e,r)):Ms(this._delegate,e)}get(){return ks(this._delegate).then(e=>new fo(this.database,e))}once(e,r,t,n){l("Query.once",1,4,arguments.length),c("Query.once","callback",r,!0);let i=F.getCancelAndContextArgs_("Query.once",t,n),s=new _;var o=(e,t)=>{var n=new fo(this.database,e);r&&r.call(i.context,n,t),s.resolve(n)},a=(o.userCallback=r,o.context=i.context,e=>{i.cancel&&i.cancel.call(i.context,e),s.reject(e)});switch(e){case"value":xs(this._delegate,o,a,{onlyOnce:!0});break;case"child_added":Ds(this._delegate,o,a,{onlyOnce:!0});break;case"child_removed":Ls(this._delegate,o,a,{onlyOnce:!0});break;case"child_changed":As(this._delegate,o,a,{onlyOnce:!0});break;case"child_moved":Os(this._delegate,o,a,{onlyOnce:!0});break;default:throw new Error(h("Query.once","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}return s.promise}limitToFirst(e){return l("Query.limitToFirst",1,1,arguments.length),new F(this.database,Gs(this._delegate,(e=>{if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToFirst: First argument must be a positive integer.");return new js(e)})(e)))}limitToLast(e){return l("Query.limitToLast",1,1,arguments.length),new F(this.database,Gs(this._delegate,(e=>{if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToLast: First argument must be a positive integer.");return new Vs(e)})(e)))}orderByChild(e){return l("Query.orderByChild",1,1,arguments.length),new F(this.database,Gs(this._delegate,(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 Di("orderByChild","path",e),new zs(e)})(e)))}orderByKey(){return l("Query.orderByKey",0,0,arguments.length),new F(this.database,Gs(this._delegate,new Hs))}orderByPriority(){return l("Query.orderByPriority",0,0,arguments.length),new F(this.database,Gs(this._delegate,new Qs))}orderByValue(){return l("Query.orderByValue",0,0,arguments.length),new F(this.database,Gs(this._delegate,new Ys))}startAt(e=null,t){return l("Query.startAt",0,2,arguments.length),new F(this.database,Gs(this._delegate,([e=null,t]=[e,t],bi("startAt","key",t),new Bs(e,t))))}startAfter(e=null,t){return l("Query.startAfter",0,2,arguments.length),new F(this.database,Gs(this._delegate,(e=e,t=t,bi("startAfter","key",t),new Us(e,t))))}endAt(e=null,t){return l("Query.endAt",0,2,arguments.length),new F(this.database,Gs(this._delegate,(e=e,t=t,bi("endAt","key",t),new qs(e,t))))}endBefore(e=null,t){return l("Query.endBefore",0,2,arguments.length),new F(this.database,Gs(this._delegate,(e=e,t=t,bi("endBefore","key",t),new Ws(e,t))))}equalTo(e,t){return l("Query.equalTo",1,2,arguments.length),new F(this.database,Gs(this._delegate,(e=e,t=t,bi("equalTo","key",t),new Ks(e,t))))}toString(){return l("Query.toString",0,0,arguments.length),this._delegate.toString()}toJSON(){return l("Query.toJSON",0,1,arguments.length),this._delegate.toJSON()}isEqual(e){if(l("Query.isEqual",1,1,arguments.length),e instanceof F)return this._delegate.isEqual(e._delegate);throw new Error("Query.isEqual failed: First argument must be an instance of firebase.database.Query.")}static getCancelAndContextArgs_(e,t,n){var r={cancel:void 0,context:void 0};if(t&&n)r.cancel=t,c(e,"cancel",r.cancel,!0),r.context=n,ee(e,"context",r.context);else if(t)if("object"==typeof t&&null!==t)r.context=t;else{if("function"!=typeof t)throw new Error(h(e,"cancelOrContext")+" must either be a cancel callback or a context object.");r.cancel=t}return r}get ref(){return new o(this.database,new ws(this._delegate._repo,this._delegate._path))}}class o extends F{constructor(e,t){super(e,new i(t._repo,t._path,new hn,!1)),this.database=e,this._delegate=t}getKey(){return l("Reference.key",0,0,arguments.length),this._delegate.key}child(e){return l("Reference.child",1,1,arguments.length),"number"==typeof e&&(e=String(e)),new o(this.database,Is(this._delegate,e))}getParent(){l("Reference.parent",0,0,arguments.length);var e=this._delegate.parent;return e?new o(this.database,e):null}getRoot(){return l("Reference.root",0,0,arguments.length),new o(this.database,this._delegate.root)}set(e,t){l("Reference.set",1,2,arguments.length),c("Reference.set","onComplete",t,!0);var n=Es(this._delegate,e);return t&&n.then(()=>t(null),e=>t(e)),n}update(t,n){if(l("Reference.update",1,2,arguments.length),Array.isArray(t)){var r={};for(let e=0;e<t.length;++e)r[""+e]=t[e];t=r,co("Passing an Array to Firebase.update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.")}L("Reference.update",this._delegate._path),c("Reference.update","onComplete",n,!0);var e=Ss(this._delegate,t);return n&&e.then(()=>n(null),e=>n(e)),e}setWithPriority(e,t,n){l("Reference.setWithPriority",2,3,arguments.length),c("Reference.setWithPriority","onComplete",n,!0);var r=((e,t,n)=>{if(L("setWithPriority",e._path),yi("setWithPriority",t,e._path,!1),Ci("setWithPriority",n),".length"===e.key||".keys"===e.key)throw"setWithPriority failed: "+e.key+" is a read-only object.";var r=new _;return Ki(e._repo,e._path,t,n,r.wrapCallback(()=>{})),r.promise})(this._delegate,e,t);return n&&r.then(()=>n(null),e=>n(e)),r}remove(t){l("Reference.remove",0,1,arguments.length),c("Reference.remove","onComplete",t,!0);e=this._delegate,L("remove",e._path);var e,n=Es(e,null);return t&&n.then(()=>t(null),e=>t(e)),n}transaction(e,t,n){l("Reference.transaction",1,3,arguments.length),c("Reference.transaction","transactionUpdate",e,!1),c("Reference.transaction","onComplete",t,!0);var r="Reference.transaction",i="applyLocally",s=n;if(void 0!==s&&"boolean"!=typeof s)throw new Error(h(r,i)+"must be a boolean.");var o=ho(this._delegate,e,{applyLocally:n}).then(e=>new po(e.committed,new fo(this.database,e.snapshot)));return t&&o.then(e=>t(null,e.committed,e.snapshot),e=>t(e,!1,null)),o}setPriority(e,t){l("Reference.setPriority",1,2,arguments.length),c("Reference.setPriority","onComplete",t,!0);n=this._delegate,e=e,n=g(n),L("setPriority",n._path),Ci("setPriority",e),r=new _,Ki(n._repo,I(n._path,".priority"),e,null,r.wrapCallback(()=>{}));var n,r=r.promise;return t&&r.then(()=>t(null),e=>t(e)),r}push(e,t){l("Reference.push",0,2,arguments.length),c("Reference.push","onComplete",t,!0);var n=((e,t)=>{e=g(e),L("push",e._path),yi("push",t,e._path,!0);var n=ji(e._repo),n=ds(n),r=Is(e,n);let i=Is(e,n),s;return s=null!=t?Es(i,t).then(()=>i):Promise.resolve(i),r.then=s.then.bind(s),r.catch=s.then.bind(s,void 0),r})(this._delegate,e),r=n.then(e=>new o(this.database,e)),n=(t&&r.then(()=>t(null),e=>t(e)),new o(this.database,n));return n.then=r.then.bind(r),n.catch=r.catch.bind(r,void 0),n}onDisconnect(){return L("Reference.onDisconnect",this._delegate._path),new _o(new gs(this._delegate._repo,this._delegate._path))}get key(){return this.getKey()}get parent(){return this.getParent()}get root(){return this.getRoot()}}class go{constructor(e,t){this._delegate=e,this.app=t,this.INTERNAL={delete:()=>this._delegate._delete(),forceWebSockets:no,forceLongPolling:ro}}useEmulator(e,t,n={}){io(this._delegate,e,t,n)}ref(e){var t;return l("database.ref",0,1,arguments.length),e instanceof o?(t=Ts(this._delegate,e.toString()),new o(this,t)):(t=bs(this._delegate,e),new o(this,t))}refFromURL(e){l("database.refFromURL",1,1,arguments.length);var t=Ts(this._delegate,e);return new o(this,t)}goOffline(){var e;l("database.goOffline",0,0,arguments.length),(e=g(e=this._delegate))._checkNotDeleted("goOffline"),Xi(e._repo)}goOnline(){return l("database.goOnline",0,0,arguments.length),so(this._delegate)}}go.ServerValue={TIMESTAMP:ao,increment:e=>({".sv":{increment:e}})};var e,mo=Object.freeze({__proto__:null,initStandalone:function({app:e,url:t,version:n,customAuthImpl:r,customAppCheckImpl:i,namespace:s,nodeAdmin:o=!1}){fe(n);var a=new oe("database-standalone"),l=new se("auth-internal",a);l.setComponent(new re("auth-internal",()=>r,"PRIVATE"));let h=void 0;return i&&(h=new se("app-check-internal",a)).setComponent(new re("app-check-internal",()=>i,"PRIVATE")),{instance:new go(Zs(e,l,h,t,o),e),namespace:s}}});let vo=go.ServerValue;(e=yo).INTERNAL.registerComponent(new re("database-compat",(e,{instanceIdentifier:t})=>{var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("database").getImmediate({identifier:t});return new go(r,n)},"PUBLIC").setServiceProps({Reference:o,Query:F,Database:go,DataSnapshot:fo,enableLogging:oo,INTERNAL:mo,ServerValue:vo}).setMultipleInstances(!0)),e.registerVersion("@firebase/database-compat","2.1.7-eap-sql.a9a137e67")}).apply(this,arguments)}catch(e){throw console.error(e),new Error("Cannot instantiate firebase-database-compat.js - be sure to load firebase-app.js first.")}});
1
+ ((e,t)=>{"object"==typeof exports&&"undefined"!=typeof module?t(require("@firebase/app-compat"),require("@firebase/app")):"function"==typeof define&&define.amd?define(["@firebase/app-compat","@firebase/app"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).firebase,e.firebase.INTERNAL.modularAPIs)})(this,function(yo,wo){try{!(function(){function r(t){var n=[];let r=0;for(let i=0;i<t.length;i++){let e=t.charCodeAt(i);e<128?n[r++]=e:(e<2048?n[r++]=e>>6|192:(55296==(64512&e)&&i+1<t.length&&56320==(64512&t.charCodeAt(i+1))?(e=65536+((1023&e)<<10)+(1023&t.charCodeAt(++i)),n[r++]=e>>18|240,n[r++]=e>>12&63|128):n[r++]=e>>12|224,n[r++]=e>>6&63|128),n[r++]=63&e|128)}return n}let q={NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"},f=function(e,t){if(!e)throw W(t)},W=function(e){return new Error("Firebase Database ("+q.SDK_VERSION+") INTERNAL ASSERT FAILED: "+e)},B={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(n,e){if(!Array.isArray(n))throw Error("encodeByteArray takes an array as a parameter");this.init_();var r=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,i=[];for(let c=0;c<n.length;c+=3){var s=n[c],o=c+1<n.length,a=o?n[c+1]:0,l=c+2<n.length,h=l?n[c+2]:0;let e=(15&a)<<2|h>>6,t=63&h;l||(t=64,o)||(e=64),i.push(r[s>>2],r[(3&s)<<4|a>>4],r[e],r[t])}return i.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(r(e),t)},decodeString(n,r){if(this.HAS_NATIVE_SUPPORT&&!r)return atob(n);{var i=this.decodeStringToByteArray(n,r);var s=[];let e=0,t=0;for(;e<i.length;){var o,a,l,h=i[e++];h<128?s[t++]=String.fromCharCode(h):191<h&&h<224?(o=i[e++],s[t++]=String.fromCharCode((31&h)<<6|63&o)):239<h&&h<365?(o=((7&h)<<18|(63&i[e++])<<12|(63&i[e++])<<6|63&i[e++])-65536,s[t++]=String.fromCharCode(55296+(o>>10)),s[t++]=String.fromCharCode(56320+(1023&o))):(a=i[e++],l=i[e++],s[t++]=String.fromCharCode((15&h)<<12|(63&a)<<6|63&l))}return s.join("");return}},decodeStringToByteArray(e,t){this.init_();var n=t?this.charToByteMapWebSafe_:this.charToByteMap_,r=[];for(let l=0;l<e.length;){var i=n[e.charAt(l++)],s=l<e.length?n[e.charAt(l)]:0,o=++l<e.length?n[e.charAt(l)]:64,a=++l<e.length?n[e.charAt(l)]:64;if(++l,null==i||null==s||null==o||null==a)throw new U;r.push(i<<2|s>>4),64!==o&&(r.push(s<<4&240|o>>2),64!==a)&&r.push(o<<6&192|a)}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),(this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e)>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class U extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}let j=function(e){var t=r(e);return B.encodeByteArray(t,!0)},V=function(e){return j(e).replace(/\./g,"")},z=function(e){try{return B.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function t(e){return function e(t,n){if(!(n instanceof Object))return n;switch(n.constructor){case Date:let e=n;return new Date(e.getTime());case Object:void 0===t&&(t={});break;case Array:t=[];break;default:return n}for(var r in n)n.hasOwnProperty(r)&&H(r)&&(t[r]=e(t[r],n[r]));return t}(void 0,e)}function H(e){return"__proto__"!==e}class _{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}wrapCallback(n){return(e,t)=>{e?this.reject(e):this.resolve(t),"function"==typeof n&&(this.promise.catch(()=>{}),1===n.length?n(e):n(e,t))}}}function Q(){return"undefined"!=typeof window&&(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test("undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:"")}function Y(e){return JSON.parse(e)}function a(e){return JSON.stringify(e)}function K(e){let t={},n={},r={},i="";try{var s=e.split(".");t=Y(z(s[0])||""),n=Y(z(s[1])||""),i=s[2],r=n.d||{},delete n.d}catch(e){}return{header:t,claims:n,data:r,signature:i}}function p(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function G(e,t){if(Object.prototype.hasOwnProperty.call(e,t))return e[t]}function $(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function J(e,t,n){var r,i={};for(r in e)Object.prototype.hasOwnProperty.call(e,r)&&(i[r]=t.call(n,e[r],r,e));return i}function X(e){return null!==e&&"object"==typeof e}class Z{constructor(){this.chain_=[],this.buf_=[],this.W_=[],this.pad_=[],this.inbuf_=0,this.total_=0,this.blockSize=64,this.pad_[0]=128;for(let e=1;e<this.blockSize;++e)this.pad_[e]=0;this.reset()}reset(){this.chain_[0]=1732584193,this.chain_[1]=4023233417,this.chain_[2]=2562383102,this.chain_[3]=271733878,this.chain_[4]=3285377520,this.inbuf_=0,this.total_=0}compress_(n,r){r=r||0;var i=this.W_;if("string"==typeof n)for(let e=0;e<16;e++)i[e]=n.charCodeAt(r)<<24|n.charCodeAt(r+1)<<16|n.charCodeAt(r+2)<<8|n.charCodeAt(r+3),r+=4;else for(let t=0;t<16;t++)i[t]=n[r]<<24|n[r+1]<<16|n[r+2]<<8|n[r+3],r+=4;for(let d=16;d<80;d++){var e=i[d-3]^i[d-8]^i[d-14]^i[d-16];i[d]=4294967295&(e<<1|e>>>31)}let t=this.chain_[0],s=this.chain_[1],o=this.chain_[2],a=this.chain_[3],l=this.chain_[4],h,c;for(let _=0;_<80;_++){c=_<40?_<20?(h=a^s&(o^a),1518500249):(h=s^o^a,1859775393):_<60?(h=s&o|a&(s|o),2400959708):(h=s^o^a,3395469782);var u=(t<<5|t>>>27)+h+l+c+i[_]&4294967295;l=a,a=o,o=4294967295&(s<<30|s>>>2),s=t,t=u}this.chain_[0]=this.chain_[0]+t&4294967295,this.chain_[1]=this.chain_[1]+s&4294967295,this.chain_[2]=this.chain_[2]+o&4294967295,this.chain_[3]=this.chain_[3]+a&4294967295,this.chain_[4]=this.chain_[4]+l&4294967295}update(n,r){if(null!=n){var i=(r=void 0===r?n.length:r)-this.blockSize;let e=0;var s=this.buf_;let t=this.inbuf_;for(;e<r;){if(0===t)for(;e<=i;)this.compress_(n,e),e+=this.blockSize;if("string"==typeof n){for(;e<r;)if(s[t]=n.charCodeAt(e),++t,++e,t===this.blockSize){this.compress_(s),t=0;break}}else for(;e<r;)if(s[t]=n[e],++t,++e,t===this.blockSize){this.compress_(s),t=0;break}}this.inbuf_=t,this.total_+=r}}digest(){var t=[];let e=8*this.total_;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(let r=this.blockSize-1;56<=r;r--)this.buf_[r]=255&e,e/=256;this.compress_(this.buf_);let n=0;for(let i=0;i<5;i++)for(let e=24;0<=e;e-=8)t[n]=this.chain_[i]>>e&255,++n;return t}}function l(e,t,n,r){let i;var s;if(r<t?i="at least "+t:n<r&&(i=0===n?"none":"no more than "+n),i)throw s=e+" failed: Was called with "+r+(1===r?" argument.":" arguments.")+" Expects "+i+".",new Error(s)}function h(e,t){return e+` failed: ${t} argument `}function c(e,t,n,r){if((!r||n)&&"function"!=typeof n)throw new Error(h(e,t)+"must be a valid function.")}function ee(e,t,n){if(n&&("object"!=typeof n||null===n))throw new Error(h(e,t)+"must be a valid context object.")}let te=function(e){let t=0;for(let r=0;r<e.length;r++){var n=e.charCodeAt(r);n<128?t++:n<2048?t+=2:55296<=n&&n<=56319?(t+=4,r++):t+=3}return t};function g(e){return e&&e._delegate?e._delegate:e}function ne(e){try{return(e.startsWith("http://")||e.startsWith("https://")?new URL(e).hostname:e).endsWith(".cloudworkstations.dev")}catch{return!1}}class re{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}let ie="[DEFAULT]";class se{constructor(e,t){this.name=e,this.container=t,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){var t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){var n=new _;if(this.instancesDeferred.set(t,n),this.isInitialized(t)||this.shouldAutoInitialize())try{var r=this.getOrInitializeService({instanceIdentifier:t});r&&n.resolve(r)}catch(e){}}return this.instancesDeferred.get(t).promise}getImmediate(e){var t=this.normalizeInstanceIdentifier(e?.identifier),n=e?.optional??!1;if(!this.isInitialized(t)&&!this.shouldAutoInitialize()){if(n)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:t})}catch(e){if(n)return null;throw e}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,this.shouldAutoInitialize()){if("EAGER"===e.instantiationMode)try{this.getOrInitializeService({instanceIdentifier:ie})}catch(e){}for(var[t,n]of this.instancesDeferred.entries()){t=this.normalizeInstanceIdentifier(t);try{var r=this.getOrInitializeService({instanceIdentifier:t});n.resolve(r)}catch(e){}}}}clearInstance(e=ie){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){var e=Array.from(this.instances.values());await Promise.all([...e.filter(e=>"INTERNAL"in e).map(e=>e.INTERNAL.delete()),...e.filter(e=>"_delete"in e).map(e=>e._delete())])}isComponentSet(){return null!=this.component}isInitialized(e=ie){return this.instances.has(e)}getOptions(e=ie){return this.instancesOptions.get(e)||{}}initialize(e={}){var{options:t={}}=e,n=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(n))throw Error(this.name+`(${n}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);var r,i,s=this.getOrInitializeService({instanceIdentifier:n,options:t});for([r,i]of this.instancesDeferred.entries())n===this.normalizeInstanceIdentifier(r)&&i.resolve(s);return s}onInit(e,t){var n=this.normalizeInstanceIdentifier(t);let r=this.onInitCallbacks.get(n)??new Set;r.add(e),this.onInitCallbacks.set(n,r);var i=this.instances.get(n);return i&&e(i,n),()=>{r.delete(e)}}invokeOnInitCallbacks(e,t){var n=this.onInitCallbacks.get(t);if(n)for(var r of n)try{r(e,t)}catch{}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let n=this.instances.get(e);if(!n&&this.component&&(n=this.component.instanceFactory(this.container,{instanceIdentifier:(r=e)===ie?void 0:r,options:t}),this.instances.set(e,n),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(n,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,n)}catch{}var r;return n||null}normalizeInstanceIdentifier(e=ie){return!this.component||this.component.multipleInstances?e:ie}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class oe{constructor(e){this.name=e,this.providers=new Map}addComponent(e){var t=this.getProvider(e.name);if(t.isComponentSet())throw new Error(`Component ${e.name} has already been registered with `+this.name);t.setComponent(e)}addOrOverwriteComponent(e){this.getProvider(e.name).isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){var t;return this.providers.has(e)?this.providers.get(e):(t=new se(e,this),this.providers.set(e,t),t)}getProviders(){return Array.from(this.providers.values())}}var n;(e=n=n||{})[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT";let ae={debug:n.DEBUG,verbose:n.VERBOSE,info:n.INFO,warn:n.WARN,error:n.ERROR,silent:n.SILENT},le=n.INFO,he={[n.DEBUG]:"log",[n.VERBOSE]:"log",[n.INFO]:"info",[n.WARN]:"warn",[n.ERROR]:"error"},ce=(e,t,...n)=>{if(!(t<e.logLevel)){var r=(new Date).toISOString(),i=he[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${r}] ${e.name}:`,...n)}};class ue{constructor(e){this.name=e,this._logLevel=le,this._logHandler=ce,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in n))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?ae[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,n.DEBUG,...e),this._logHandler(this,n.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,n.VERBOSE,...e),this._logHandler(this,n.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,n.INFO,...e),this._logHandler(this,n.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,n.WARN,...e),this._logHandler(this,n.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,n.ERROR,...e),this._logHandler(this,n.ERROR,...e)}}let de="@firebase/database",_e="1.1.5-eap-sql.b903ef716",pe="";function fe(e){pe=e}class ge{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),a(t))}get(e){var t=this.domStorage_.getItem(this.prefixedName_(e));return null==t?null:Y(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}class me{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){null==t?delete this.cache_[e]:this.cache_[e]=t}get(e){return p(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}function ve(e){try{var t;if("undefined"!=typeof window&&void 0!==window[e])return(t=window[e]).setItem("firebase:sentinel","cache"),t.removeItem("firebase:sentinel"),new ge(t)}catch(e){}return new me}var d,ye;function we(e){var t=(t=>{var n,r,i=[];let s=0;for(let o=0;o<t.length;o++){let e=t.charCodeAt(o);55296<=e&&e<=56319&&(n=e-55296,o++,f(o<t.length,"Surrogate pair missing trail surrogate."),r=t.charCodeAt(o)-56320,e=65536+(n<<10)+r),e<128?i[s++]=e:(e<2048?i[s++]=e>>6|192:(e<65536?i[s++]=e>>12|224:(i[s++]=e>>18|240,i[s++]=e>>12&63|128),i[s++]=e>>6&63|128),i[s++]=63&e|128)}return i})(e),n=new Z,t=(n.update(t),n.digest());return B.encodeByteArray(t)}function Ce(t){return function(...e){u(t,...e)}}function be(...e){var t="FIREBASE INTERNAL ERROR: "+xe(...e);Pe.error(t)}function Te(e,t){return e===t?0:e<t?-1:1}function Ie(e,t){if(t&&e in t)return t[e];throw new Error("Missing required key ("+e+") in object: "+a(t))}function Ee(e){if("object"!=typeof e||null===e)return a(e);var t,n=[];for(t in e)n.push(t);n.sort();let r="{";for(let i=0;i<n.length;i++)0!==i&&(r+=","),r=(r=r+a(n[i])+":")+Ee(e[n[i]]);return r+="}"}function Se(e,t){var n=e.length;if(n<=t)return[e];var r=[];for(let i=0;i<n;i+=t)i+t>n?r.push(e.substring(i,n)):r.push(e.substring(i,i+t));return r}let ke=ve("localStorage"),Ne=ve("sessionStorage"),Pe=new ue("@firebase/database"),Re=(()=>{let e=1;return function(){return e++}})(),xe=function(...e){let t="";for(let r=0;r<e.length;r++){var n=e[r];Array.isArray(n)||n&&"object"==typeof n&&"number"==typeof n.length?t+=xe.apply(null,n):t+="object"==typeof n?a(n):n,t+=" "}return t},De=null,Ae=!0,Oe=function(e,t){f(!t||!0===e||!1===e,"Can't turn on custom loggers persistently."),!0===e?(Pe.logLevel=n.VERBOSE,De=Pe.log.bind(Pe),t&&Ne.set("logging_enabled",!0)):"function"==typeof e?De=e:(De=null,Ne.remove("logging_enabled"))},u=function(...e){var t;!0===Ae&&(Ae=!1,null===De)&&!0===Ne.get("logging_enabled")&&Oe(!0),De&&(t=xe.apply(null,e),De(t))},Le=function(...e){var t="FIREBASE FATAL ERROR: "+xe(...e);throw Pe.error(t),new Error(t)},m=function(...e){var t="FIREBASE WARNING: "+xe(...e);Pe.warn(t)},Me=function(){"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&m("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().")},Fe=function(e){return"number"==typeof e&&(e!=e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY)},qe="[MIN_NAME]",We="[MAX_NAME]",Be=function(e,t){var n,r;return e===t?0:e===qe||t===We?-1:t===qe||e===We?1:(n=je(e),r=je(t),null!==n?null!==r?n-r==0?e.length-t.length:n-r:-1:null===r&&e<t?-1:1)};function v(e,t){for(var n in e)e.hasOwnProperty(n)&&t(n,e[n])}function Ue(e){f(!Fe(e),"Invalid JSON number");let t,n,r,i,s;0===e?(n=0,r=0,t=1/e==-1/0?1:0):(t=e<0,e=Math.abs(e),r=e>=Math.pow(2,-1022)?(i=Math.min(Math.floor(Math.log(e)/Math.LN2),1023),n=i+1023,Math.round(e*Math.pow(2,52-i)-Math.pow(2,52))):(n=0,Math.round(e/Math.pow(2,-1074))));var o=[];for(s=52;s;--s)o.push(r%2?1:0),r=Math.floor(r/2);for(s=11;s;--s)o.push(n%2?1:0),n=Math.floor(n/2);o.push(t?1:0),o.reverse();var a=o.join("");let l="";for(s=0;s<64;s+=8){let e=parseInt(a.substr(s,8),2).toString(16);1===e.length&&(e="0"+e),l+=e}return l.toLowerCase()}function je(e){if(ze.test(e)){var t=Number(e);if(t>=He&&t<=Qe)return t}return null}function Ve(e,t){var n=setTimeout(e,t);return"number"==typeof n&&"undefined"!=typeof Deno&&Deno.unrefTimer?Deno.unrefTimer(n):"object"==typeof n&&n.unref&&n.unref(),n}let ze=new RegExp("^-?(0*)\\d{1,10}$"),He=-2147483648,Qe=2147483647,Ye=function(e){try{e()}catch(t){setTimeout(()=>{var e=t.stack||"";throw m("Exception was thrown by user callback.",e),t},Math.floor(0))}};class Ke{constructor(e,t){this.appCheckProvider=t,this.appName=e.name,wo._isFirebaseServerApp(e)&&e.settings.appCheckToken&&(this.serverAppAppCheckToken=e.settings.appCheckToken),this.appCheck=t?.getImmediate({optional:!0}),this.appCheck||t?.get().then(e=>this.appCheck=e)}getToken(n){if(this.serverAppAppCheckToken){if(n)throw new Error("Attempted reuse of `FirebaseServerApp.appCheckToken` after previous usage failed.");return Promise.resolve({token:this.serverAppAppCheckToken})}return this.appCheck?this.appCheck.getToken(n):new Promise((e,t)=>{setTimeout(()=>{this.appCheck?this.getToken(n).then(e,t):e(null)},0)})}addTokenChangeListener(t){this.appCheckProvider?.get().then(e=>e.addTokenListener(t))}notifyForInvalidToken(){m(`Provided AppCheck credentials for the app named "${this.appName}" `+"are invalid. This usually indicates your app was not initialized correctly.")}}class Ge{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(n){return this.auth_?this.auth_.getToken(n).catch(e=>e&&"auth/token-not-initialized"===e.code?(u("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(e)):new Promise((e,t)=>{setTimeout(()=>{this.auth_?this.getToken(n).then(e,t):e(null)},0)})}addTokenChangeListener(t){this.auth_?this.auth_.addAuthTokenListener(t):this.authProvider_.get().then(e=>e.addAuthTokenListener(t))}removeTokenChangeListener(t){this.authProvider_.get().then(e=>e.removeAuthTokenListener(t))}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/.',m(e)}}class $e{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}$e.OWNER="owner";let Je=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,Xe="websocket",Ze="long_polling";class et{constructor(e,t,n,r,i=!1,s="",o=!1,a=!1,l=null){this.secure=t,this.namespace=n,this.webSocketOnly=r,this.nodeAdmin=i,this.persistenceKey=s,this.includeNamespaceInQueryParams=o,this.isUsingEmulator=a,this.emulatorOptions=l,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=ke.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())&&ke.set("host:"+this._host,this.internalHost)}toString(){let e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e}toURLString(){var e=this.secure?"https://":"http://",t=this.includeNamespaceInQueryParams?"?ns="+this.namespace:"";return e+this.host+"/"+t}}function tt(e,t,n){f("string"==typeof t,"typeof type must == string"),f("object"==typeof n,"typeof params must == object");let r;if(t===Xe)r=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?";else{if(t!==Ze)throw new Error("Unknown connection type: "+t);r=(e.secure?"https://":"http://")+e.internalHost+"/.lp?"}((t=e).host!==t.internalHost||t.isCustomHost()||t.includeNamespaceInQueryParams)&&(n.ns=e.namespace);let i=[];return v(n,(e,t)=>{i.push(e+"="+t)}),r+i.join("&")}class nt{constructor(){this.counters_={}}incrementCounter(e,t=1){p(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return t(this.counters_)}}let rt={},it={};function st(e){var t=e.toString();return rt[t]||(rt[t]=new nt),rt[t]}class ot{constructor(e){this.onMessage_=e,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}closeAfter(e,t){this.closeAfterResponse=e,this.onClose=t,this.closeAfterResponse<this.currentResponseNum&&(this.onClose(),this.onClose=null)}handleResponse(e,t){for(this.pendingResponses[e]=t;this.pendingResponses[this.currentResponseNum];){let e=this.pendingResponses[this.currentResponseNum];delete this.pendingResponses[this.currentResponseNum];for(let t=0;t<e.length;++t)e[t]&&Ye(()=>{this.onMessage_(e[t])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}class at{constructor(e,t,n,r,i,s,o){this.connId=e,this.repoInfo=t,this.applicationId=n,this.appCheckToken=r,this.authToken=i,this.transportSessionId=s,this.lastSessionId=o,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=Ce(e),this.stats_=st(t),this.urlFn=e=>(this.appCheckToken&&(e.ac=this.appCheckToken),tt(t,Ze,e))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new ot(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null},Math.floor(3e4));var n=()=>{var e;this.isClosed_||(this.scriptTagHolder=new lt((...e)=>{var[t,n,r,,,]=e;if(this.incrementIncomingBytes_(e),this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,"start"===t)this.id=n,this.password=r;else{if("close"!==t)throw new Error("Unrecognized command received: "+t);n?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(n,()=>{this.onClosed_()})):this.onClosed_()}},(...e)=>{var[t,n]=e;this.incrementIncomingBytes_(e),this.myPacketOrderer.handleResponse(t,n)},()=>{this.onClosed_()},this.urlFn),(e={start:"t"}).ser=Math.floor(1e8*Math.random()),this.scriptTagHolder.uniqueCallbackIdentifier&&(e.cb=this.scriptTagHolder.uniqueCallbackIdentifier),e.v="5",this.transportSessionId&&(e.s=this.transportSessionId),this.lastSessionId&&(e.ls=this.lastSessionId),this.applicationId&&(e.p=this.applicationId),this.appCheckToken&&(e.ac=this.appCheckToken),"undefined"!=typeof location&&location.hostname&&Je.test(location.hostname)&&(e.r="f"),e=this.urlFn(e),this.log_("Connecting via long-poll to "+e),this.scriptTagHolder.addTag(e,()=>{}))};if("complete"===document.readyState)n();else{let e=!1,t=function(){document.body?e||(e=!0,n()):setTimeout(t,Math.floor(10))};document.addEventListener?(document.addEventListener("DOMContentLoaded",t,!1),window.addEventListener("load",t,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",()=>{"complete"===document.readyState&&t()}),window.attachEvent("onload",t))}}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){at.forceAllow_=!0}static forceDisallow(){at.forceDisallow_=!0}static isAvailable(){return!!at.forceAllow_||!(at.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){var t=a(e),t=(this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length),j(t)),n=Se(t,1840);for(let r=0;r<n.length;r++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,n.length,n[r]),this.curSegmentNum++}addDisconnectPingFrame(e,t){this.myDisconnFrame=document.createElement("iframe");var 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){var t=a(e).length;this.bytesReceived+=t,this.stats_.incrementCounter("bytes_received",t)}}class lt{constructor(t,n,e,r){this.onDisconnect=e,this.urlFn=r,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(1e8*Math.random()),this.sendNewPolls=!0;{this.uniqueCallbackIdentifier=Re(),window["pLPCommand"+this.uniqueCallbackIdentifier]=t,window["pRTLPCB"+this.uniqueCallbackIdentifier]=n,this.myIFrame=lt.createIFrame_();let e="";this.myIFrame.src&&"javascript:"===this.myIFrame.src.substr(0,"javascript:".length)&&(i=document.domain,e='<script>document.domain="'+i+'";<\/script>');var i="<html><body>"+e+"</body></html>";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(i),this.myIFrame.doc.close()}catch(e){u("frame writing exception"),e.stack&&u(e.stack),u(e)}}}static createIFrame_(){var t=document.createElement("iframe");if(t.style.display="none",!document.body)throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";document.body.appendChild(t);try{t.contentWindow.document||u("No IE domain setting required")}catch(e){var n=document.domain;t.src="javascript:void((function(){document.open();document.domain='"+n+"';document.close();})())"}return t.contentDocument?t.doc=t.contentDocument:t.contentWindow?t.doc=t.contentWindow.document:t.document&&(t.doc=t.document),t}close(){this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.textContent="",setTimeout(()=>{null!==this.myIFrame&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)},Math.floor(0)));var 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<(0<this.pendingSegs.length?2:1)){this.currentSerial++;var n={},n=(n.id=this.myID,n.pw=this.myPW,n.ser=this.currentSerial,this.urlFn(n));let e="",t=0;for(;0<this.pendingSegs.length;){if(!(this.pendingSegs[0].d.length+30+e.length<=1870))break;var r=this.pendingSegs.shift();e=e+"&seg"+t+"="+r.seg+"&ts"+t+"="+r.ts+"&d"+t+"="+r.d,t++}return n+=e,this.addLongPollTag_(n,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);let n=()=>{this.outstandingRequests.delete(t),this.newRequest_()},r=setTimeout(n,Math.floor(25e3));this.addTag(e,()=>{clearTimeout(r),n()})}addTag(e,n){setTimeout(()=>{try{if(this.sendNewPolls){let t=this.myIFrame.doc.createElement("script");t.type="text/javascript",t.async=!0,t.src=e,t.onload=t.onreadystatechange=function(){var e=t.readyState;e&&"loaded"!==e&&"complete"!==e||(t.onload=t.onreadystatechange=null,t.parentNode&&t.parentNode.removeChild(t),n())},t.onerror=()=>{u("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(t)}}catch(e){}},Math.floor(1))}}let ht=null;"undefined"!=typeof MozWebSocket?ht=MozWebSocket:"undefined"!=typeof WebSocket&&(ht=WebSocket);class y{constructor(e,t,n,r,i,s,o){this.connId=e,this.applicationId=n,this.appCheckToken=r,this.authToken=i,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=Ce(this.connId),this.stats_=st(t),this.connURL=y.connectionURL_(t,s,o,r,n),this.nodeAdmin=t.nodeAdmin}static connectionURL_(e,t,n,r,i){var s={v:"5"};return"undefined"!=typeof location&&location.hostname&&Je.test(location.hostname)&&(s.r="f"),t&&(s.s=t),n&&(s.ls=n),r&&(s.ac=r),i&&(s.p=i),tt(e,Xe,s)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,ke.set("previous_websocket_failure",!0);try{q.NODE_ADMIN,this.mySock=new ht(this.connURL,[],void 0)}catch(e){this.log_("Error instantiating WebSocket.");var n=e.message||e.data;return n&&this.log_(n),void this.onClosed_()}this.mySock.onopen=()=>{this.log_("Websocket connected."),this.everConnected_=!0},this.mySock.onclose=()=>{this.log_("Websocket connection was disconnected."),this.mySock=null,this.onClosed_()},this.mySock.onmessage=e=>{this.handleIncomingFrame(e)},this.mySock.onerror=e=>{this.log_("WebSocket error. Closing connection.");var t=e.message||e.data;t&&this.log_(t),this.onClosed_()}}start(){}static forceDisallow(){y.forceDisallow_=!0}static isAvailable(){let e=!1;var t;return!(e="undefined"!=typeof navigator&&navigator.userAgent&&(t=navigator.userAgent.match(/Android ([0-9]{0,}\.[0-9]{0,})/))&&1<t.length&&parseFloat(t[1])<4.4?!0:e)&&null!==ht&&!y.forceDisallow_}static previouslyFailed(){return ke.isInMemoryStorage||!0===ke.get("previous_websocket_failure")}markConnectionHealthy(){ke.remove("previous_websocket_failure")}appendFrame_(e){var t;this.frames.push(e),this.frames.length===this.totalFrames&&(t=this.frames.join(""),this.frames=null,t=Y(t),this.onMessage(t))}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if(f(null===this.frames,"We already have a frame buffer"),e.length<=6){var t=Number(e);if(!isNaN(t))return this.handleNewFrameCount_(t),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){var t;null!==this.mySock&&(t=e.data,this.bytesReceived+=t.length,this.stats_.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),null!==this.frames?this.appendFrame_(t):null!==(t=this.extractFrameCount_(t))&&this.appendFrame_(t))}send(e){this.resetKeepAlive();var t=a(e),n=(this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length),Se(t,16384));1<n.length&&this.sendString_(String(n.length));for(let r=0;r<n.length;r++)this.sendString_(n[r])}shutdown_(){this.isClosed_=!0,this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),this.mySock&&(this.mySock.close(),this.mySock=null)}onClosed_(){this.isClosed_||(this.log_("WebSocket is closing itself"),this.shutdown_(),this.onDisconnect&&(this.onDisconnect(this.everConnected_),this.onDisconnect=null))}close(){this.isClosed_||(this.log_("WebSocket is being closed"),this.shutdown_())}resetKeepAlive(){clearInterval(this.keepaliveTimer),this.keepaliveTimer=setInterval(()=>{this.mySock&&this.sendString_("0"),this.resetKeepAlive()},Math.floor(45e3))}sendString_(e){try{this.mySock.send(e)}catch(e){this.log_("Exception thrown from WebSocket.send():",e.message||e.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}}}y.responsesRequiredToBeHealthy=2,y.healthyTimeout=3e4;class ct{static get ALL_TRANSPORTS(){return[at,y]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}constructor(e){this.initTransports_(e)}initTransports_(e){var t=y&&y.isAvailable();let n=t&&!y.previouslyFailed();if(e.webSocketOnly&&(t||m("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),n=!0),n)this.transports_=[y];else{var r,i=this.transports_=[];for(r of ct.ALL_TRANSPORTS)r&&r.isAvailable()&&i.push(r);ct.globalTransportInitialized_=!0}}initialTransport(){if(0<this.transports_.length)return this.transports_[0];throw new Error("No transports available")}upgradeTransport(){return 1<this.transports_.length?this.transports_[1]:null}}ct.globalTransportInitialized_=!1;class ut{constructor(e,t,n,r,i,s,o,a,l,h){this.id=e,this.repoInfo_=t,this.applicationId_=n,this.appCheckToken_=r,this.authToken_=i,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_=Ce("c:"+this.id+":"),this.transportManager_=new ct(t),this.log_("Connection created"),this.start_()}start_(){var e=this.transportManager_.initialTransport();this.conn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,null,this.lastSessionId),this.primaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;let t=this.connReceiver_(this.conn_),n=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout(()=>{this.conn_&&this.conn_.open(t,n)},Math.floor(0));e=e.healthyTimeout||0;0<e&&(this.healthyTimeout_=Ve(()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&102400<this.conn_.bytesReceived?(this.log_("Connection exceeded healthy timeout but has received "+this.conn_.bytesReceived+" bytes. Marking connection healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()):this.conn_&&10240<this.conn_.bytesSent?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(e)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(t){return e=>{t===this.conn_?this.onConnectionLost_(e):t===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(t){return e=>{2!==this.state_&&(t===this.rx_?this.onPrimaryMessageReceived_(e):t===this.secondaryConn_?this.onSecondaryMessageReceived_(e):this.log_("message on old connection"))}}sendRequest(e){this.sendData_({t:"d",d:e})}tryCleanupConnection(){this.tx_===this.secondaryConn_&&this.rx_===this.secondaryConn_&&(this.log_("cleaning up and promoting a connection: "+this.secondaryConn_.connId),this.conn_=this.secondaryConn_,this.secondaryConn_=null)}onSecondaryControl_(e){var t;"t"in e&&("a"===(t=e.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){var t=Ie("t",e),n=Ie("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:"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){var t=Ie("t",e),n=Ie("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){var t=Ie("t",e);if("d"in e){var n=e.d;if("h"===t){var r={...n};this.repoInfo_.isUsingEmulator&&(r.h=this.repoInfo_.host),this.onHandshake_(r)}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?be("Server Error: "+n):"o"===t?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):be("Unknown control packet command: "+t)}}onHandshake_(e){var t=e.ts,n=e.v,r=e.h;this.sessionId=e.s,this.repoInfo_.host=r,0===this.state_&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,t),"5"!==n&&m("Protocol version mismatch detected"),this.tryStartUpgrade_())}tryStartUpgrade_(){var 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;var t=this.connReceiver_(this.secondaryConn_),n=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(t,n),Ve(()=>{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):Ve(()=>{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_(){var 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()&&(ke.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 dt{put(e,t,n,r){}merge(e,t,n,r){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,t,n){}onDisconnectMerge(e,t,n){}onDisconnectCancel(e,t){}reportStats(e){}}class _t{constructor(e){this.allowedEvents_=e,this.listeners_={},f(Array.isArray(e)&&0<e.length,"Requires a non-empty array")}trigger(t,...n){if(Array.isArray(this.listeners_[t])){var r=[...this.listeners_[t]];for(let e=0;e<r.length;e++)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});var r=this.getInitialEvent(e);r&&t.apply(n,r)}off(e,t,n){this.validateEventType_(e);var r=this.listeners_[e]||[];for(let i=0;i<r.length;i++)if(r[i].callback===t&&(!n||n===r[i].context))return void r.splice(i,1)}validateEventType_(t){f(this.allowedEvents_.find(e=>e===t),"Unknown event: "+t)}}class pt extends _t{static getInstance(){return new pt}constructor(){super(["online"]),this.online_=!0,"undefined"==typeof window||void 0===window.addEventListener||Q()||(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))}getInitialEvent(e){return f("online"===e,"Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}let ft=32,gt=768;class w{constructor(n,e){if(void 0===e){this.pieces_=n.split("/");let e=0;for(let t=0;t<this.pieces_.length;t++)0<this.pieces_[t].length&&(this.pieces_[e]=this.pieces_[t],e++);this.pieces_.length=e,this.pieceNum_=0}else this.pieces_=n,this.pieceNum_=e}toString(){let e="";for(let t=this.pieceNum_;t<this.pieces_.length;t++)""!==this.pieces_[t]&&(e+="/"+this.pieces_[t]);return e||"/"}}function C(){return new w("")}function b(e){return e.pieceNum_>=e.pieces_.length?null:e.pieces_[e.pieceNum_]}function mt(e){return e.pieces_.length-e.pieceNum_}function T(e){let t=e.pieceNum_;return t<e.pieces_.length&&t++,new w(e.pieces_,t)}function vt(e){return e.pieceNum_<e.pieces_.length?e.pieces_[e.pieces_.length-1]:null}function yt(e,t=0){return e.pieces_.slice(e.pieceNum_+t)}function wt(e){if(e.pieceNum_>=e.pieces_.length)return null;var t=[];for(let n=e.pieceNum_;n<e.pieces_.length-1;n++)t.push(e.pieces_[n]);return new w(t,0)}function I(e,t){var n=[];for(let i=e.pieceNum_;i<e.pieces_.length;i++)n.push(e.pieces_[i]);if(t instanceof w)for(let e=t.pieceNum_;e<t.pieces_.length;e++)n.push(t.pieces_[e]);else{var r=t.split("/");for(let e=0;e<r.length;e++)0<r[e].length&&n.push(r[e])}return new w(n,0)}function E(e){return e.pieceNum_>=e.pieces_.length}function S(e,t){var n=b(e),r=b(t);if(null===n)return t;if(n===r)return S(T(e),T(t));throw new Error("INTERNAL ERROR: innerPath ("+t+") is not within outerPath ("+e+")")}function Ct(e,t){var n=yt(e,0),r=yt(t,0);for(let s=0;s<n.length&&s<r.length;s++){var i=Be(n[s],r[s]);if(0!==i)return i}return n.length===r.length?0:n.length<r.length?-1:1}function bt(e,t){if(mt(e)!==mt(t))return!1;for(let n=e.pieceNum_,r=t.pieceNum_;n<=e.pieces_.length;n++,r++)if(e.pieces_[n]!==t.pieces_[r])return!1;return!0}function k(e,t){let n=e.pieceNum_,r=t.pieceNum_;if(mt(e)>mt(t))return!1;for(;n<e.pieces_.length;){if(e.pieces_[n]!==t.pieces_[r])return!1;++n,++r}return!0}class Tt{constructor(e,t){this.errorPrefix_=t,this.parts_=yt(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let n=0;n<this.parts_.length;n++)this.byteLength_+=te(this.parts_[n]);It(this)}}function It(e){if(e.byteLength_>gt)throw new Error(e.errorPrefix_+"has a key path longer than "+gt+" bytes ("+e.byteLength_+").");if(e.parts_.length>ft)throw new Error(e.errorPrefix_+"path specified exceeds the maximum depth that can be written ("+ft+") or object contains a cycle "+Et(e))}function Et(e){return 0===e.parts_.length?"":"in property '"+e.parts_.join(".")+"'"}class St extends _t{static getInstance(){return new St}constructor(){super(["visible"]);let t,e;"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(e="visibilitychange",t="hidden"):void 0!==document.mozHidden?(e="mozvisibilitychange",t="mozHidden"):void 0!==document.msHidden?(e="msvisibilitychange",t="msHidden"):void 0!==document.webkitHidden&&(e="webkitvisibilitychange",t="webkitHidden")),this.visible_=!0,e&&document.addEventListener(e,()=>{var e=!document[t];e!==this.visible_&&(this.visible_=e,this.trigger("visible",e))},!1)}getInitialEvent(e){return f("visible"===e,"Unknown event type: "+e),[this.visible_]}}class kt extends dt{constructor(e,t,n,r,i,s,o,a){if(super(),this.repoInfo_=e,this.applicationId_=t,this.onDataUpdate_=n,this.onConnectStatus_=r,this.onServerInfoUpdate_=i,this.authTokenProvider_=s,this.appCheckTokenProvider_=o,this.authOverride_=a,this.id=kt.nextPersistentConnectionId_++,this.log_=Ce("p:"+this.id+":"),this.interruptReasons_={},this.listens=new Map,this.outstandingPuts_=[],this.outstandingGets_=[],this.outstandingPutCount_=0,this.outstandingGetCount_=0,this.onDisconnectRequestQueue_=[],this.connected_=!1,this.reconnectDelay_=1e3,this.maxReconnectDelay_=3e5,this.securityDebugCallback_=null,this.lastSessionId=null,this.establishConnectionTimer_=null,this.visible_=!1,this.requestCBHash_={},this.requestNumber_=0,this.realtime_=null,this.authToken_=null,this.appCheckToken_=null,this.forceTokenRefresh_=!1,this.invalidAuthTokenCount_=0,this.invalidAppCheckTokenCount_=0,this.firstConnection_=!0,this.lastConnectionAttemptTime_=null,this.lastConnectionEstablishedTime_=null,a)throw new Error("Auth override specified in options, but not supported on non Node.js platforms");St.getInstance().on("visible",this.onVisible_,this),-1===e.host.indexOf("fblocal")&&pt.getInstance().on("online",this.onOnline_,this)}sendRequest(e,t,n){var r=++this.requestNumber_,i={r:r,a:e,b:t};this.log_(a(i)),f(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(i),n&&(this.requestCBHash_[r]=n)}get(e){this.initConnection_();let n=new _;var t={p:e._path.toString(),q:e._queryObject},t=(this.outstandingGets_.push({action:"g",request:t,onComplete:e=>{var t=e.d;"ok"===e.s?n.resolve(t):n.reject(t)}}),this.outstandingGetCount_++,this.outstandingGets_.length-1);return this.connected_&&this.sendGet_(t),n.promise}listen(e,t,n,r){this.initConnection_();var i=e._queryIdentifier,s=e._path.toString(),o=(this.log_("Listen called for "+s+" "+i),this.listens.has(s)||this.listens.set(s,new Map),f(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),f(!this.listens.get(s).has(i),"listen() called twice for same path/queryId."),{onComplete:r,hashFn:t,query:e,tag:n});this.listens.get(s).set(i,o),this.connected_&&this.sendListen_(o)}sendGet_(t){let n=this.outstandingGets_[t];this.sendRequest("g",n.request,e=>{delete this.outstandingGets_[t],this.outstandingGetCount_--,0===this.outstandingGetCount_&&(this.outstandingGets_=[]),n.onComplete&&n.onComplete(e)})}sendListen_(i){let s=i.query,o=s._path.toString(),a=s._queryIdentifier;this.log_("Listen on "+o+" for "+a);var e={p:o};i.tag&&(e.q=s._queryObject,e.t=i.tag),e.h=i.hashFn(),this.sendRequest("q",e,e=>{var t=e.d,n=e.s,r=(kt.warnOnListenWarnings_(t,s),this.listens.get(o)&&this.listens.get(o).get(a));r===i&&(this.log_("listen response",e),"ok"!==n&&this.removeListen_(o,a),i.onComplete)&&i.onComplete(n,t)})}static warnOnListenWarnings_(e,t){var n,r;e&&"object"==typeof e&&p(e,"w")&&(n=G(e,"w"),Array.isArray(n))&&~n.indexOf("no_index")&&(n='".indexOn": "'+t._queryParams.getIndex().toString()+'"',r=t._path.toString(),m("Using an unspecified index. Your data will be downloaded and "+`filtered on the client. Consider adding ${n} at `+r+" 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){var t;(e&&40===e.length||(e=e,"object"==typeof(t=K(e).claims)&&!0===t.admin))&&(this.log_("Admin auth credential detected. Reducing max reconnect time."),this.maxReconnectDelay_=3e4)}refreshAppCheckToken(e){this.appCheckToken_=e,this.log_("App check token refreshed"),this.appCheckToken_?this.tryAppCheck():this.connected_&&this.sendRequest("unappeck",{},()=>{})}tryAuth(){if(this.connected_&&this.authToken_){let r=this.authToken_;n=r;var e=!!(e=K(n).claims)&&"object"==typeof e&&e.hasOwnProperty("iat")?"auth":"gauth",t={cred:r};null===this.authOverride_?t.noauth=!0:"object"==typeof this.authOverride_&&(t.authvar=this.authOverride_),this.sendRequest(e,t,e=>{var t=e.s,n=e.d||"error";this.authToken_===r&&("ok"===t?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(t,n))})}var n,e}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},e=>{var t=e.s,n=e.d||"error";"ok"===t?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(t,n)})}unlisten(e,t){var n=e._path.toString(),r=e._queryIdentifier,i=(this.log_("Unlisten called for "+n+" "+r),f(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(n,r));i&&this.connected_&&this.sendUnlisten_(n,r,e._queryObject,t)}sendUnlisten_(e,t,n,r){this.log_("Unlisten on "+e+" for "+t);var i={p:e};r&&(i.q=n,i.t=r),this.sendRequest("n",i)}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,r){var i={p:t,d:n};this.log_("onDisconnect "+e,i),this.sendRequest(e,i,e=>{r&&setTimeout(()=>{r(e.s,e.d)},Math.floor(0))})}put(e,t,n,r){this.putInternal("p",e,t,n,r)}merge(e,t,n,r){this.putInternal("m",e,t,n,r)}putInternal(e,t,n,r,i){this.initConnection_();var s={p:t,d:n},s=(void 0!==i&&(s.h=i),this.outstandingPuts_.push({action:e,request:s,onComplete:r}),this.outstandingPutCount_++,this.outstandingPuts_.length-1);this.connected_?this.sendPut_(s):this.log_("Buffering put: "+t)}sendPut_(t){let n=this.outstandingPuts_[t].action;var e=this.outstandingPuts_[t].request;let r=this.outstandingPuts_[t].onComplete;this.outstandingPuts_[t].queued=this.connected_,this.sendRequest(n,e,e=>{this.log_(n+" response",e),delete this.outstandingPuts_[t],this.outstandingPutCount_--,0===this.outstandingPutCount_&&(this.outstandingPuts_=[]),r&&r(e.s,e.d)})}reportStats(e){var t;this.connected_&&(this.log_("reportStats",t={c:e}),this.sendRequest("s",t,e=>{var t;"ok"!==e.s&&(t=e.d,this.log_("reportStats","Error sending stats: "+t))}))}onDataMessage_(e){if("r"in e){this.log_("from server: "+a(e));var 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):be("Unrecognized action received from server: "+a(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){f(!this.realtime_,"Scheduling a connect when we're already connected/ing?"),this.establishConnectionTimer_&&clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=setTimeout(()=>{this.establishConnectionTimer_=null,this.establishConnection_()},Math.floor(e))}initConnection_(){!this.realtime_&&this.firstConnection_&&this.scheduleConnect_(0)}onVisible_(e){e&&!this.visible_&&this.reconnectDelay_===this.maxReconnectDelay_&&(this.log_("Window became visible. Reducing delay."),this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0)),this.visible_=e}onOnline_(e){e?(this.log_("Browser went online."),this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0)):(this.log_("Browser went offline. Killing connection."),this.realtime_&&this.realtime_.close())}onRealtimeDisconnect_(){var e;this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()&&(this.visible_?this.lastConnectionEstablishedTime_&&(3e4<(new Date).getTime()-this.lastConnectionEstablishedTime_&&(this.reconnectDelay_=1e3),this.lastConnectionEstablishedTime_=null):(this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=(new Date).getTime()),e=Math.max(0,(new Date).getTime()-this.lastConnectionAttemptTime_),e=Math.max(0,this.reconnectDelay_-e),e=Math.random()*e,this.log_("Trying to reconnect in "+e+"ms"),this.scheduleConnect_(e),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;var r=this.onDataMessage_.bind(this),i=this.onReady_.bind(this);let e=this.onRealtimeDisconnect_.bind(this);var s=this.id+":"+kt.nextConnectionId_++,o=this.lastSessionId;let t=!1,n=null;var a=function(){n?n.close():(t=!0,e())},l=(this.realtime_={close:a,sendRequest:function(e){f(n,"sendRequest call when we're not connected not allowed."),n.sendRequest(e)}},this.forceTokenRefresh_);this.forceTokenRefresh_=!1;try{var[h,c]=await Promise.all([this.authTokenProvider_.getToken(l),this.appCheckTokenProvider_.getToken(l)]);t?u("getToken() completed but was canceled"):(u("getToken() completed. Creating connection."),this.authToken_=h&&h.accessToken,this.appCheckToken_=c&&c.token,n=new ut(s,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,r,i,e,e=>{m(e+" ("+this.repoInfo_.toString()+")"),this.interrupt("server_kill")},o))}catch(e){this.log_("Failed to get token: "+e),t||(this.repoInfo_.nodeAdmin&&m(e),a())}}}interrupt(e){u("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){u("Resuming connection for reason: "+e),delete this.interruptReasons_[e],$(this.interruptReasons_)&&(this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(e){var t=e-(new Date).getTime();this.onServerInfoUpdate_({serverTimeOffset:t})}cancelSentTransactions_(){for(let t=0;t<this.outstandingPuts_.length;t++){var e=this.outstandingPuts_[t];e&&"h"in e.request&&e.queued&&(e.onComplete&&e.onComplete("disconnect"),delete this.outstandingPuts_[t],this.outstandingPutCount_--)}0===this.outstandingPutCount_&&(this.outstandingPuts_=[])}onListenRevoked_(e,t){let n;n=t?t.map(e=>Ee(e)).join("$"):"default";var r=this.removeListen_(e,n);r&&r.onComplete&&r.onComplete("permission_denied")}removeListen_(e,t){var n,r=new w(e).toString();let i;return this.listens.has(r)?(n=this.listens.get(r),i=n.get(t),n.delete(t),0===n.size&&this.listens.delete(r)):i=void 0,i}onAuthRevoked_(e,t){u("Auth token revoked: "+e+"/"+t),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAuthTokenCount_++,3<=this.invalidAuthTokenCount_&&(this.reconnectDelay_=3e4,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(e,t){u("App check token revoked: "+e+"/"+t),this.appCheckToken_=null,this.forceTokenRefresh_=!0,"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAppCheckTokenCount_++,3<=this.invalidAppCheckTokenCount_&&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(var e of this.listens.values())for(var t of e.values())this.sendListen_(t);for(let r=0;r<this.outstandingPuts_.length;r++)this.outstandingPuts_[r]&&this.sendPut_(r);for(;this.onDisconnectRequestQueue_.length;){var n=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(n.action,n.pathString,n.data,n.onComplete)}for(let i=0;i<this.outstandingGets_.length;i++)this.outstandingGets_[i]&&this.sendGet_(i)}sendConnectStats_(){var e={};e["sdk.js."+pe.replace(/\./g,"-")]=1,Q()?e["framework.cordova"]=1:"object"==typeof navigator&&"ReactNative"===navigator.product&&(e["framework.reactnative"]=1),this.reportStats(e)}shouldReconnect_(){var e=pt.getInstance().currentlyOnline();return $(this.interruptReasons_)&&e}}kt.nextPersistentConnectionId_=0,kt.nextConnectionId_=0;class N{constructor(e,t){this.name=e,this.node=t}static Wrap(e,t){return new N(e,t)}}class Nt{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,t){var n=new N(qe,e),r=new N(qe,t);return 0!==this.compare(n,r)}minPost(){return N.MIN}}let Pt;class Rt extends Nt{static get __EMPTY_NODE(){return Pt}static set __EMPTY_NODE(e){Pt=e}compare(e,t){return Be(e.name,t.name)}isDefinedOn(e){throw W("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,t){return!1}minPost(){return N.MIN}maxPost(){return new N(We,Pt)}makePost(e,t){return f("string"==typeof e,"KeyIndex indexValue must always be a string."),new N(e,Pt)}toString(){return".key"}}let xt=new Rt;class Dt{constructor(e,t,n,r,i=null){this.isReverse_=r,this.resultGenerator_=i,this.nodeStack_=[];let s=1;for(;!e.isEmpty();)if(s=t?n(e.key,t):1,r&&(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=this.nodeStack_.pop(),t;if(t=this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value},this.isReverse_)for(e=e.left;!e.isEmpty();)this.nodeStack_.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack_.push(e),e=e.left;return t}hasNext(){return 0<this.nodeStack_.length}peek(){var e;return 0===this.nodeStack_.length?null:(e=this.nodeStack_[this.nodeStack_.length-1],this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value})}}class P{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:P.RED,this.left=null!=r?r:s.EMPTY_NODE,this.right=null!=i?i:s.EMPTY_NODE}copy(e,t,n,r,i){return new P(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i: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 r=this;var i=n(e,r.key);return(r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n))).fixUp_()}removeMin_(){if(this.left.isEmpty())return s.EMPTY_NODE;let e=this;return(e=(e=e.left.isRed_()||e.left.left.isRed_()?e:e.moveRedLeft_()).copy(null,null,null,e.left.removeMin_(),null)).fixUp_()}remove(e,t){let n,r;if(t(e,(n=this).key)<0)n=(n=n.left.isEmpty()||n.left.isRed_()||n.left.left.isRed_()?n:n.moveRedLeft_()).copy(null,null,null,n.left.remove(e,t),null);else{if(0===t(e,(n=(n=n.left.isRed_()?n.rotateRight_():n).right.isEmpty()||n.right.isRed_()||n.right.left.isRed_()?n:n.moveRedRight_()).key)){if(n.right.isEmpty())return s.EMPTY_NODE;r=n.right.min_(),n=n.copy(r.key,r.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=(e=(e=e.right.isRed_()&&!e.left.isRed_()?e.rotateLeft_():e).left.isRed_()&&e.left.left.isRed_()?e.rotateRight_():e).left.isRed_()&&e.right.isRed_()?e.colorFlip_():e}moveRedLeft_(){let e=this.colorFlip_();return e=e.right.left.isRed_()?(e=(e=e.copy(null,null,null,null,e.right.rotateRight_())).rotateLeft_()).colorFlip_():e}moveRedRight_(){let e=this.colorFlip_();return e=e.left.left.isRed_()?(e=e.rotateRight_()).colorFlip_():e}rotateLeft_(){var e=this.copy(null,null,P.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){var e=this.copy(null,null,P.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip_(){var 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_(){var 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+")");if(this.right.isRed_())throw new Error("Right child of ("+this.key+","+this.value+") is red");var e=this.left.check_();if(e!==this.right.check_())throw new Error("Black depths differ");return e+(this.isRed_()?0:1)}}P.RED=!0,P.BLACK=!1;class s{constructor(e,t=s.EMPTY_NODE){this.comparator_=e,this.root_=t}insert(e,t){return new s(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,P.BLACK,null,null))}remove(e){return new s(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,P.BLACK,null,null))}get(e){var t;let n=this.root_;for(;!n.isEmpty();){if(0===(t=this.comparator_(e,n.key)))return n.value;t<0?n=n.left:0<t&&(n=n.right)}return null}getPredecessorKey(e){let t,n=this.root_,r=null;for(;!n.isEmpty();){if(0===(t=this.comparator_(e,n.key))){if(n.left.isEmpty())return r?r.key:null;for(n=n.left;!n.right.isEmpty();)n=n.right;return n.key}t<0?n=n.left:0<t&&(n=(r=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 Dt(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new Dt(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new Dt(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new Dt(this.root_,null,this.comparator_,!0,e)}}function At(e,t){return Be(e.name,t.name)}function Ot(e,t){return Be(e,t)}s.EMPTY_NODE=new class{copy(e,t,n,r,i){return this}insert(e,t,n){return new P(e,t,null)}remove(e,t){return this}count(){return 0}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}check_(){return 0}isRed_(){return!1}};let Lt;function Mt(e){return"number"==typeof e?"number:"+Ue(e):"string:"+e}function Ft(e){var t;e.isLeafNode()?(t=e.val(),f("string"==typeof t||"number"==typeof t||"object"==typeof t&&p(t,".sv"),"Priority must be a string or number.")):f(e===Lt||e.isEmpty(),"priority of unexpected type."),f(e===Lt||e.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")}let qt;class R{static set __childrenNodeConstructor(e){qt=e}static get __childrenNodeConstructor(){return qt}constructor(e,t=R.__childrenNodeConstructor.EMPTY_NODE){this.value_=e,this.priorityNode_=t,this.lazyHash_=null,f(null!=this.value_,"LeafNode shouldn't be created with null/undefined value."),Ft(this.priorityNode_)}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new R(this.value_,e)}getImmediateChild(e){return".priority"===e?this.priorityNode_:R.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return E(e)?this:".priority"===b(e)?this.priorityNode_:R.__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:R.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,t).updatePriority(this.priorityNode_)}updateChild(e,t){var n=b(e);return null===n?t:t.isEmpty()&&".priority"!==n?this:(f(".priority"!==n||1===mt(e),".priority must be the last token in a path"),this.updateImmediateChild(n,R.__childrenNodeConstructor.EMPTY_NODE.updateChild(T(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:"+Mt(this.priorityNode_.val())+":");var t=typeof this.value_;e=(e+=t+":")+("number"==t?Ue(this.value_):this.value_),this.lazyHash_=we(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===R.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof R.__childrenNodeConstructor?-1:(f(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){var t=typeof e.value_,n=typeof this.value_,r=R.VALUE_TYPE_ORDER.indexOf(t),i=R.VALUE_TYPE_ORDER.indexOf(n);return f(0<=r,"Unknown leaf type: "+t),f(0<=i,"Unknown leaf type: "+n),r===i?"object"==n?0:this.value_<e.value_?-1:this.value_===e.value_?0:1:i-r}withIndex(){return this}isIndexed(){return!0}equals(e){return e===this||!!e.isLeafNode()&&this.value_===e.value_&&this.priorityNode_.equals(e.priorityNode_)}}R.VALUE_TYPE_ORDER=["object","boolean","number","string"];let Wt,Bt;class Ut extends Nt{compare(e,t){var n=e.node.getPriority(),r=t.node.getPriority(),n=n.compareTo(r);return 0===n?Be(e.name,t.name):n}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return N.MIN}maxPost(){return new N(We,new R("[PRIORITY-POST]",Bt))}makePost(e,t){var n=Wt(e);return new N(t,new R("[PRIORITY-POST]",n))}toString(){return".priority"}}let x=new Ut,jt=Math.log(2);class Vt{constructor(e){this.count=(t=e+1,parseInt(Math.log(t)/jt,10)),this.current_=this.count-1,t=this.count;var t,n=parseInt(Array(t+1).join("1"),2);this.bits_=e+1&n}nextBitIsOne(){var e=!(this.bits_&1<<this.current_);return this.current_--,e}}function zt(l,e,h,t){l.sort(e);let c=function(e,t){var n,r,i=t-e;let s,o;return 0==i?null:1==i?(s=l[e],o=h?h(s):s,new P(o,s.node,P.BLACK,null,null)):(i=parseInt(i/2,10)+e,n=c(e,i),r=c(i+1,t),s=l[i],o=h?h(s):s,new P(o,s.node,P.BLACK,n,r))};var n=(e=>{let s=null,o=null,a=l.length;function t(e,t){var n=a-e,r=a,r=(a-=e,c(1+n,r)),n=l[n],i=h?h(n):n,e=new P(i,n.node,t,null,r);s=(s?s.left=e:o=e,e)}for(let i=0;i<e.count;++i){var n=e.nextBitIsOne(),r=Math.pow(2,e.count-(i+1));n?t(r,P.BLACK):(t(r,P.BLACK),t(r,P.RED))}return o})(new Vt(l.length));return new s(t||e,n)}let Ht,Qt={};class Yt{static get Default(){return f((Qt,x),"ChildrenNode.ts has not been loaded"),Ht=Ht||new Yt({".priority":Qt},{".priority":x})}constructor(e,t){this.indexes_=e,this.indexSet_=t}get(e){var t=G(this.indexes_,e);if(t)return t instanceof s?t:null;throw new Error("No index defined for "+e)}hasIndex(e){return p(this.indexSet_,e.toString())}addIndex(e,t){f(e!==xt,"KeyIndex always exists and isn't meant to be added to the IndexMap.");var n=[];let r=!1;var i=t.getIterator(N.Wrap);let s=i.getNext();for(;s;)r=r||e.isDefinedOn(s.node),n.push(s),s=i.getNext();let o;o=r?zt(n,e.getCompare()):Qt;var a=e.toString(),l={...this.indexSet_},h=(l[a]=e,{...this.indexes_});return h[a]=o,new Yt(h,l)}addToIndexes(s,o){var e=J(this.indexes_,(t,e)=>{var n=G(this.indexSet_,e);if(f(n,"Missing index implementation for "+e),t===Qt){if(n.isDefinedOn(s.node)){var r=[],i=o.getIterator(N.Wrap);let e=i.getNext();for(;e;)e.name!==s.name&&r.push(e),e=i.getNext();return r.push(s),zt(r,n.getCompare())}return Qt}{n=o.get(s.name);let e=t;return(e=n?e.remove(new N(s.name,n)):e).insert(s,s.node)}});return new Yt(e,this.indexSet_)}removeFromIndexes(n,r){var e=J(this.indexes_,e=>{var t;return e!==Qt&&(t=r.get(n.name))?e.remove(new N(n.name,t)):e});return new Yt(e,this.indexSet_)}}let Kt;class D{static get EMPTY_NODE(){return Kt=Kt||new D(new s(Ot),null,Yt.Default)}constructor(e,t,n){this.children_=e,this.priorityNode_=t,this.indexMap_=n,this.lazyHash_=null,this.priorityNode_&&Ft(this.priorityNode_),this.children_.isEmpty()&&f(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}isLeafNode(){return!1}getPriority(){return this.priorityNode_||Kt}updatePriority(e){return this.children_.isEmpty()?this:new D(this.children_,e,this.indexMap_)}getImmediateChild(e){var t;return".priority"===e?this.getPriority():null===(t=this.children_.get(e))?Kt:t}getChild(e){var t=b(e);return null===t?this:this.getImmediateChild(t).getChild(T(e))}hasChild(e){return null!==this.children_.get(e)}updateImmediateChild(n,r){if(f(r,"We should always be passing snapshot nodes"),".priority"===n)return this.updatePriority(r);{var i=new N(n,r);let e,t;t=r.isEmpty()?(e=this.children_.remove(n),this.indexMap_.removeFromIndexes(i,this.children_)):(e=this.children_.insert(n,r),this.indexMap_.addToIndexes(i,this.children_));i=e.isEmpty()?Kt:this.priorityNode_;return new D(e,i,t)}}updateChild(e,t){var n,r=b(e);return null===r?t:(f(".priority"!==b(e)||1===mt(e),".priority must be the last token in a path"),n=this.getImmediateChild(r).updateChild(T(e),t),this.updateImmediateChild(r,n))}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(n){if(this.isEmpty())return null;let r={},i=0,s=0,o=!0;if(this.forEachChild(x,(e,t)=>{r[e]=t.val(n),i++,o&&D.INTEGER_REGEXP_.test(e)?s=Math.max(s,Number(e)):o=!1}),!n&&o&&s<2*i){var e,t=[];for(e in r)t[e]=r[e];return t}return n&&!this.getPriority().isEmpty()&&(r[".priority"]=this.getPriority().val()),r}hash(){if(null===this.lazyHash_){let r="";this.getPriority().isEmpty()||(r+="priority:"+Mt(this.getPriority().val())+":"),this.forEachChild(x,(e,t)=>{var n=t.hash();""!==n&&(r+=":"+e+":"+n)}),this.lazyHash_=""===r?"":we(r)}return this.lazyHash_}getPredecessorChildName(e,t,n){var r=this.resolveIndex_(n);return r?(r=r.getPredecessorKey(new N(e,t)))?r.name:null:this.children_.getPredecessorKey(e)}getFirstChildName(e){var t=this.resolveIndex_(e);return t?(t=t.minKey())&&t.name:this.children_.minKey()}getFirstChild(e){var t=this.getFirstChildName(e);return t?new N(t,this.children_.get(t)):null}getLastChildName(e){var t=this.resolveIndex_(e);return t?(t=t.maxKey())&&t.name:this.children_.maxKey()}getLastChild(e){var t=this.getLastChildName(e);return t?new N(t,this.children_.get(t)):null}forEachChild(e,t){var 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(t,n){var e=this.resolveIndex_(n);if(e)return e.getIteratorFrom(t,e=>e);{var r=this.children_.getIteratorFrom(t.name,N.Wrap);let e=r.peek();for(;null!=e&&n.compare(e,t)<0;)r.getNext(),e=r.peek();return r}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(t,n){var e=this.resolveIndex_(n);if(e)return e.getReverseIteratorFrom(t,e=>e);{var r=this.children_.getReverseIteratorFrom(t.name,N.Wrap);let e=r.peek();for(;null!=e&&0<n.compare(e,t);)r.getNext(),e=r.peek();return r}}compareTo(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===$t?-1:0}withIndex(e){var t;return e===xt||this.indexMap_.hasIndex(e)?this:(t=this.indexMap_.addIndex(e,this.children_),new D(this.children_,this.priorityNode_,t))}isIndexed(e){return e===xt||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;if(!e.isLeafNode()){var n=e;if(this.getPriority().equals(n.getPriority())){if(this.children_.count()!==n.children_.count())return!1;{var r=this.getIterator(x),i=n.getIterator(x);let e=r.getNext(),t=i.getNext();for(;e&&t;){if(e.name!==t.name||!e.node.equals(t.node))return!1;e=r.getNext(),t=i.getNext()}return null===e&&null===t}}}return!1}resolveIndex_(e){return e===xt?null:this.indexMap_.get(e.toString())}}D.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;class Gt extends D{constructor(){super(new s(Ot),D.EMPTY_NODE,Yt.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return D.EMPTY_NODE}isEmpty(){return!1}}let $t=new Gt,Jt=(Object.defineProperties(N,{MIN:{value:new N(qe,D.EMPTY_NODE)},MAX:{value:new N(We,$t)}}),Rt.__EMPTY_NODE=D.EMPTY_NODE,R.__childrenNodeConstructor=D,e=$t,Lt=e,e=$t,Bt=e,!0);function A(s,e=null){if(null===s)return D.EMPTY_NODE;var t,n;if("object"==typeof s&&".priority"in s&&(e=s[".priority"]),f(null===e||"string"==typeof e||"number"==typeof e||"object"==typeof e&&".sv"in e,"Invalid priority type found: "+typeof e),"object"!=typeof(s="object"==typeof s&&".value"in s&&null!==s[".value"]?s[".value"]:s)||".sv"in s)return t=s,new R(t,A(e));if(s instanceof Array||!Jt){let r=D.EMPTY_NODE;return v(s,(e,t)=>{var n;!p(s,e)||"."===e.substring(0,1)||!(n=A(t)).isLeafNode()&&n.isEmpty()||(r=r.updateImmediateChild(e,n))}),r.updatePriority(A(e))}{let r=[],i=!1;return v(s,(e,t)=>{var n;"."===e.substring(0,1)||(n=A(t)).isEmpty()||(i=i||!n.getPriority().isEmpty(),r.push(new N(e,n)))}),0===r.length?D.EMPTY_NODE:(t=zt(r,At,e=>e.name,Ot),i?(n=zt(r,x.getCompare()),new D(t,A(e),new Yt({".priority":n},{".priority":x}))):new D(t,A(e),Yt.Default))}}Wt=A;class Xt extends Nt{constructor(e){super(),this.indexPath_=e,f(!E(e)&&".priority"!==b(e),"Can't create PathIndex with empty path or .priority key")}extractChild(e){return e.getChild(this.indexPath_)}isDefinedOn(e){return!e.getChild(this.indexPath_).isEmpty()}compare(e,t){var n=this.extractChild(e.node),r=this.extractChild(t.node),n=n.compareTo(r);return 0===n?Be(e.name,t.name):n}makePost(e,t){var n=A(e),n=D.EMPTY_NODE.updateChild(this.indexPath_,n);return new N(t,n)}maxPost(){var e=D.EMPTY_NODE.updateChild(this.indexPath_,$t);return new N(We,e)}toString(){return yt(this.indexPath_,0).join("/")}}class Zt extends Nt{compare(e,t){var n=e.node.compareTo(t.node);return 0===n?Be(e.name,t.name):n}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return N.MIN}maxPost(){return N.MAX}makePost(e,t){var n=A(e);return new N(t,n)}toString(){return".value"}}let en=new Zt;function tn(e){return{type:"value",snapshotNode:e}}function nn(e,t){return{type:"child_added",snapshotNode:t,childName:e}}function rn(e,t){return{type:"child_removed",snapshotNode:t,childName:e}}function sn(e,t,n){return{type:"child_changed",snapshotNode:t,childName:e,oldSnap:n}}class on{constructor(e){this.index_=e}updateChild(e,t,n,r,i,s){f(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");var o=e.getImmediateChild(t);return o.getChild(r).equals(n.getChild(r))&&o.isEmpty()===n.isEmpty()||(null!=s&&(n.isEmpty()?e.hasChild(t)?s.trackChildChange(rn(t,o)):f(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):o.isEmpty()?s.trackChildChange(nn(t,n)):s.trackChildChange(sn(t,n,o))),e.isLeafNode()&&n.isEmpty())?e:e.updateImmediateChild(t,n).withIndex(this.index_)}updateFullNode(r,n,i){return null!=i&&(r.isLeafNode()||r.forEachChild(x,(e,t)=>{n.hasChild(e)||i.trackChildChange(rn(e,t))}),n.isLeafNode()||n.forEachChild(x,(e,t)=>{var n;r.hasChild(e)?(n=r.getImmediateChild(e)).equals(t)||i.trackChildChange(sn(e,t,n)):i.trackChildChange(nn(e,t))})),n.withIndex(this.index_)}updatePriority(e,t){return e.isEmpty()?D.EMPTY_NODE:e.updatePriority(t)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}class an{constructor(e){this.indexedFilter_=new on(e.getIndex()),this.index_=e.getIndex(),this.startPost_=an.getStartPost_(e),this.endPost_=an.getEndPost_(e),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){var t=this.startIsInclusive_?this.index_.compare(this.getStartPost(),e)<=0:this.index_.compare(this.getStartPost(),e)<0,n=this.endIsInclusive_?this.index_.compare(e,this.getEndPost())<=0:this.index_.compare(e,this.getEndPost())<0;return t&&n}updateChild(e,t,n,r,i,s){return this.matches(new N(t,n))||(n=D.EMPTY_NODE),this.indexedFilter_.updateChild(e,t,n,r,i,s)}updateFullNode(e,t,n){let r=(t=t.isLeafNode()?D.EMPTY_NODE:t).withIndex(this.index_),i=(r=r.updatePriority(D.EMPTY_NODE),this);return t.forEachChild(x,(e,t)=>{i.matches(new N(e,t))||(r=r.updateImmediateChild(e,D.EMPTY_NODE))}),this.indexedFilter_.updateFullNode(e,r,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){var t;return e.hasStart()?(t=e.getIndexStartName(),e.getIndex().makePost(e.getIndexStartValue(),t)):e.getIndex().minPost()}static getEndPost_(e){var t;return e.hasEnd()?(t=e.getIndexEndName(),e.getIndex().makePost(e.getIndexEndValue(),t)):e.getIndex().maxPost()}}class ln{constructor(e){this.withinDirectionalStart=e=>this.reverse_?this.withinEndPost(e):this.withinStartPost(e),this.withinDirectionalEnd=e=>this.reverse_?this.withinStartPost(e):this.withinEndPost(e),this.withinStartPost=e=>{var t=this.index_.compare(this.rangedFilter_.getStartPost(),e);return this.startIsInclusive_?t<=0:t<0},this.withinEndPost=e=>{var t=this.index_.compare(e,this.rangedFilter_.getEndPost());return this.endIsInclusive_?t<=0:t<0},this.rangedFilter_=new an(e),this.index_=e.getIndex(),this.limit_=e.getLimit(),this.reverse_=!e.isViewFromLeft(),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}updateChild(e,t,n,r,i,s){return this.rangedFilter_.matches(new N(t,n))||(n=D.EMPTY_NODE),e.getImmediateChild(t).equals(n)?e:e.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(e,t,n,r,i,s):this.fullLimitUpdateChild_(e,t,n,i,s)}updateFullNode(e,n,t){let r;if(n.isLeafNode()||n.isEmpty())r=D.EMPTY_NODE.withIndex(this.index_);else if(2*this.limit_<n.numChildren()&&n.isIndexed(this.index_)){r=D.EMPTY_NODE.withIndex(this.index_);let e,t=(e=this.reverse_?n.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):n.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_),0);for(;e.hasNext()&&t<this.limit_;){var i=e.getNext();if(this.withinDirectionalStart(i)){if(!this.withinDirectionalEnd(i))break;r=r.updateImmediateChild(i.name,i.node),t++}}}else{r=(r=n.withIndex(this.index_)).updatePriority(D.EMPTY_NODE);let e,t=(e=this.reverse_?r.getReverseIterator(this.index_):r.getIterator(this.index_),0);for(;e.hasNext();){var s=e.getNext();t<this.limit_&&this.withinDirectionalStart(s)&&this.withinDirectionalEnd(s)?t++:r=r.updateImmediateChild(s.name,D.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(e,r,t)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}fullLimitUpdateChild_(e,t,n,r,i){let s;if(this.reverse_){let n=this.index_.getCompare();s=(e,t)=>n(t,e)}else s=this.index_.getCompare();var o=e,a=(f(o.numChildren()===this.limit_,""),new N(t,n)),l=this.reverse_?o.getFirstChild(this.index_):o.getLastChild(this.index_),h=this.rangedFilter_.matches(a);if(o.hasChild(t)){var c=o.getImmediateChild(t);let e=r.getChildAfterChild(this.index_,l,this.reverse_);for(;null!=e&&(e.name===t||o.hasChild(e.name));)e=r.getChildAfterChild(this.index_,e,this.reverse_);var u=null==e?1:s(e,a);return h&&!n.isEmpty()&&0<=u?(null!=i&&i.trackChildChange(sn(t,n,c)),o.updateImmediateChild(t,n)):(null!=i&&i.trackChildChange(rn(t,c)),u=o.updateImmediateChild(t,D.EMPTY_NODE),null!=e&&this.rangedFilter_.matches(e)?(null!=i&&i.trackChildChange(nn(e.name,e.node)),u.updateImmediateChild(e.name,e.node)):u)}return!n.isEmpty()&&h&&0<=s(l,a)?(null!=i&&(i.trackChildChange(rn(l.name,l.node)),i.trackChildChange(nn(t,n))),o.updateImmediateChild(t,n).updateImmediateChild(l.name,D.EMPTY_NODE)):e}}class hn{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_=x}hasStart(){return this.startSet_}isViewFromLeft(){return""===this.viewFrom_?this.startSet_:"l"===this.viewFrom_}getIndexStartValue(){return f(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return f(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:qe}hasEnd(){return this.endSet_}getIndexEndValue(){return f(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return f(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:We}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&""!==this.viewFrom_}getLimit(){return f(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_===x}copy(){var e=new hn;return e.limitSet_=this.limitSet_,e.limit_=this.limit_,e.startSet_=this.startSet_,e.startAfterSet_=this.startAfterSet_,e.indexStartValue_=this.indexStartValue_,e.startNameSet_=this.startNameSet_,e.indexStartName_=this.indexStartName_,e.endSet_=this.endSet_,e.endBeforeSet_=this.endBeforeSet_,e.indexEndValue_=this.indexEndValue_,e.endNameSet_=this.endNameSet_,e.indexEndName_=this.indexEndName_,e.index_=this.index_,e.viewFrom_=this.viewFrom_,e}}function cn(e,t,n){var r=e.copy();return r.startSet_=!0,r.indexStartValue_=t=void 0===t?null:t,null!=n?(r.startNameSet_=!0,r.indexStartName_=n):(r.startNameSet_=!1,r.indexStartName_=""),r}function un(e,t,n){var r=e.copy();return r.endSet_=!0,r.indexEndValue_=t=void 0===t?null:t,void 0!==n?(r.endNameSet_=!0,r.indexEndName_=n):(r.endNameSet_=!1,r.indexEndName_=""),r}function dn(e,t){var n=e.copy();return n.index_=t,n}function _n(t){var n,r={};if(!t.isDefault()){let e;e=t.index_===x?"$priority":t.index_===en?"$value":t.index_===xt?"$key":(f(t.index_ instanceof Xt,"Unrecognized index type!"),t.index_.toString()),r.orderBy=a(e),t.startSet_&&(r[n=t.startAfterSet_?"startAfter":"startAt"]=a(t.indexStartValue_),t.startNameSet_)&&(r[n]+=","+a(t.indexStartName_)),t.endSet_&&(r[n=t.endBeforeSet_?"endBefore":"endAt"]=a(t.indexEndValue_),t.endNameSet_)&&(r[n]+=","+a(t.indexEndName_)),t.limitSet_&&(t.isViewFromLeft()?r.limitToFirst=t.limit_:r.limitToLast=t.limit_)}return r}function pn(t){var n={};if(t.startSet_&&(n.sp=t.indexStartValue_,t.startNameSet_&&(n.sn=t.indexStartName_),n.sin=!t.startAfterSet_),t.endSet_&&(n.ep=t.indexEndValue_,t.endNameSet_&&(n.en=t.indexEndName_),n.ein=!t.endBeforeSet_),t.limitSet_){n.l=t.limit_;let e=t.viewFrom_;""===e&&(e=t.isViewFromLeft()?"l":"r"),n.vf=e}return t.index_!==x&&(n.i=t.index_.toString()),n}class fn extends dt{reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,t){return void 0!==t?"tag$"+t:(f(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}constructor(e,t,n,r){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=n,this.appCheckTokenProvider_=r,this.log_=Ce("p:rest:"),this.listens_={}}listen(e,t,r,i){let s=e._path.toString(),o=(this.log_("Listen called for "+s+" "+e._queryIdentifier),fn.getListenId_(e,r)),a={};this.listens_[o]=a;var n=_n(e._queryParams);this.restRequest_(s+".json",n,(t,e)=>{let n=e;if(null===(t=404===t?n=null:t)&&this.onDataUpdate_(s,n,!1,r),G(this.listens_,o)===a){let e;e=t?401===t?"permission_denied":"rest_error:"+t:"ok",i(e,null)}})}unlisten(e,t){var n=fn.getListenId_(e,t);delete this.listens_[n]}get(e){var t=_n(e._queryParams);let r=e._path.toString(),i=new _;return this.restRequest_(r+".json",t,(e,t)=>{let n=t;null===(e=404===e?n=null:e)?(this.onDataUpdate_(r,n,!1,null),i.resolve(n)):i.reject(new Error(n))}),i.promise}refreshAuthToken(e){}restRequest_(i,s={},o){return s.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then(([e,t])=>{e&&e.accessToken&&(s.auth=e.accessToken),t&&t.token&&(s.ac=t.token);let n=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+i+"?ns="+this.repoInfo_.namespace+(e=>{let t=[];for(let[n,r]of Object.entries(e))Array.isArray(r)?r.forEach(e=>{t.push(encodeURIComponent(n)+"="+encodeURIComponent(e))}):t.push(encodeURIComponent(n)+"="+encodeURIComponent(r));return t.length?"&"+t.join("&"):""})(s),r=(this.log_("Sending REST request for "+n),new XMLHttpRequest);r.onreadystatechange=()=>{if(o&&4===r.readyState){this.log_("REST Response for "+n+" received. status:",r.status,"response:",r.responseText);let e=null;if(200<=r.status&&r.status<300){try{e=Y(r.responseText)}catch(e){m("Failed to parse JSON response for "+n+": "+r.responseText)}o(null,e)}else 401!==r.status&&404!==r.status&&m("Got unsuccessful REST response for "+n+" Status: "+r.status),o(r.status);o=null}},r.open("GET",n,!0),r.send()})}}class gn{constructor(){this.rootNode_=D.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}function mn(){return{value:null,children:new Map}}function vn(e,t,n){var r;E(t)?(e.value=n,e.children.clear()):null!==e.value?e.value=e.value.updateChild(t,n):(r=b(t),e.children.has(r)||e.children.set(r,mn()),vn(e.children.get(r),t=T(t),n))}function yn(e,n,r){var i;null!==e.value?r(n,e.value):(i=(e,t)=>{yn(t,new w(n.toString()+"/"+e),r)},e.children.forEach((e,t)=>{i(t,e)}))}class wn{constructor(e){this.collection_=e,this.last_=null}get(){var e=this.collection_.get();let n={...e};return this.last_&&v(this.last_,(e,t)=>{n[e]=n[e]-t}),this.last_=e,n}}class Cn{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new wn(e);var n=1e4+2e4*Math.random();Ve(this.reportStats_.bind(this),Math.floor(n))}reportStats_(){var e=this.statsListener_.get();let n={},r=!1;v(e,(e,t)=>{0<t&&p(this.statsToReport_,e)&&(n[e]=t,r=!0)}),r&&this.server_.reportStats(n),Ve(this.reportStats_.bind(this),Math.floor(2*Math.random()*3e5))}}function bn(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function Tn(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function In(e){return{fromUser:!1,fromServer:!0,queryId:e,tagged:!0}}(e=d=d||{})[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";class En{constructor(e,t,n){this.path=e,this.affectedTree=t,this.revert=n,this.type=d.ACK_USER_WRITE,this.source=bn()}operationForChild(e){var t;return E(this.path)?null!=this.affectedTree.value?(f(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this):(t=this.affectedTree.subtree(new w(e)),new En(C(),t,this.revert)):(f(b(this.path)===e,"operationForChild called for unrelated child."),new En(T(this.path),this.affectedTree,this.revert))}}class Sn{constructor(e,t){this.source=e,this.path=t,this.type=d.LISTEN_COMPLETE}operationForChild(e){return E(this.path)?new Sn(this.source,C()):new Sn(this.source,T(this.path))}}class kn{constructor(e,t,n){this.source=e,this.path=t,this.snap=n,this.type=d.OVERWRITE}operationForChild(e){return E(this.path)?new kn(this.source,C(),this.snap.getImmediateChild(e)):new kn(this.source,T(this.path),this.snap)}}class Nn{constructor(e,t,n){this.source=e,this.path=t,this.children=n,this.type=d.MERGE}operationForChild(e){var t;return E(this.path)?(t=this.children.subtree(new w(e))).isEmpty()?null:t.value?new kn(this.source,C(),t.value):new Nn(this.source,C(),t):(f(b(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new Nn(this.source,T(this.path),this.children))}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}class Pn{constructor(e,t,n){this.node_=e,this.fullyInitialized_=t,this.filtered_=n}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){var t;return E(e)?this.isFullyInitialized()&&!this.filtered_:(t=b(e),this.isCompleteForChild(t))}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}class Rn{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function xn(n,e,t,r){var i=[];let s=[];return e.forEach(e=>{var t;"child_changed"===e.type&&n.index_.indexedValueChanged(e.oldSnap,e.snapshotNode)&&s.push((t=e.childName,{type:"child_moved",snapshotNode:e.snapshotNode,childName:t}))}),Dn(n,i,"child_removed",e,r,t),Dn(n,i,"child_added",e,r,t),Dn(n,i,"child_moved",s,r,t),Dn(n,i,"child_changed",e,r,t),Dn(n,i,"value",e,r,t),i}function Dn(s,o,t,e,a,l){var n=e.filter(e=>e.type===t);n.sort((e,t)=>{var n=s;if(null==e.childName||null==t.childName)throw W("Should only compare child_ events.");var r=new N(e.childName,e.snapshotNode),i=new N(t.childName,t.snapshotNode);return n.index_.compare(r,i)}),n.forEach(t=>{e=s,i=l,"value"!==(r=t).type&&"child_removed"!==r.type&&(r.prevName=i.getPredecessorChildName(r.childName,r.snapshotNode,e.index_));let n=r;var e,r,i;a.forEach(e=>{e.respondsTo(t.type)&&o.push(e.createEvent(n,s.query_))})})}function An(e,t){return{eventCache:e,serverCache:t}}function On(e,t,n,r){return An(new Pn(t,n,r),e.serverCache)}function Ln(e,t,n,r){return An(e.eventCache,new Pn(t,n,r))}function Mn(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function Fn(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}let qn;class O{static fromObject(e){let n=new O(null);return v(e,(e,t)=>{n=n.set(new w(e),t)}),n}constructor(e,t=qn=qn||new s(Te)){this.value=e,this.children=t}isEmpty(){return null===this.value&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){var n,r;return null!=this.value&&t(this.value)?{path:C(),value:this.value}:!E(e)&&(n=b(e),null!==(r=this.children.get(n)))&&null!=(r=r.findRootMostMatchingPathAndValue(T(e),t))?{path:I(new w(n),r.path),value:r.value}:null}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,()=>!0)}subtree(e){var t;return E(e)?this:(t=b(e),null!==(t=this.children.get(t))?t.subtree(T(e)):new O(null))}set(e,t){var n,r;return E(e)?new O(t,this.children):(r=b(e),n=(this.children.get(r)||new O(null)).set(T(e),t),r=this.children.insert(r,n),new O(this.value,r))}remove(t){if(E(t))return this.children.isEmpty()?new O(null):new O(null,this.children);var n=b(t),r=this.children.get(n);if(r){r=r.remove(T(t));let e;return e=r.isEmpty()?this.children.remove(n):this.children.insert(n,r),null===this.value&&e.isEmpty()?new O(null):new O(this.value,e)}return this}get(e){var t;return E(e)?this.value:(t=b(e),(t=this.children.get(t))?t.get(T(e)):null)}setTree(t,n){if(E(t))return n;{var r=b(t),i=(this.children.get(r)||new O(null)).setTree(T(t),n);let e;return e=i.isEmpty()?this.children.remove(r):this.children.insert(r,i),new O(this.value,e)}}fold(e){return this.fold_(C(),e)}fold_(n,r){let i={};return this.children.inorderTraversal((e,t)=>{i[e]=t.fold_(I(n,e),r)}),r(n,this.value,i)}findOnPath(e,t){return this.findOnPath_(e,C(),t)}findOnPath_(e,t,n){var r,i=!!this.value&&n(t,this.value);return i||(!E(e)&&(i=b(e),r=this.children.get(i))?r.findOnPath_(T(e),I(t,i),n):null)}foreachOnPath(e,t){return this.foreachOnPath_(e,C(),t)}foreachOnPath_(e,t,n){var r,i;return E(e)?this:(this.value&&n(t,this.value),r=b(e),(i=this.children.get(r))?i.foreachOnPath_(T(e),I(t,r),n):new O(null))}foreach(e){this.foreach_(C(),e)}foreach_(n,r){this.children.inorderTraversal((e,t)=>{t.foreach_(I(n,e),r)}),this.value&&r(n,this.value)}foreachChild(n){this.children.inorderTraversal((e,t)=>{t.value&&n(e,t.value)})}}class Wn{constructor(e){this.writeTree_=e}static empty(){return new Wn(new O(null))}}function Bn(t,n,r){if(E(n))return new Wn(new O(r));var i=t.writeTree_.findRootMostValueAndPath(n);if(null==i)return s=new O(r),s=t.writeTree_.setTree(n,s),new Wn(s);{var s=i.path;let e=i.value;i=S(s,n);return e=e.updateChild(i,r),new Wn(t.writeTree_.set(s,e))}}function Un(e,n,t){let r=e;return v(t,(e,t)=>{r=Bn(r,I(n,e),t)}),r}function jn(e,t){var n;return E(t)?Wn.empty():(n=e.writeTree_.setTree(t,new O(null)),new Wn(n))}function Vn(e,t){return null!=zn(e,t)}function zn(e,t){var n=e.writeTree_.findRootMostValueAndPath(t);return null!=n?e.writeTree_.get(n.path).getChild(S(n.path,t)):null}function Hn(e){let n=[];var t=e.writeTree_.value;return null!=t?t.isLeafNode()||t.forEachChild(x,(e,t)=>{n.push(new N(e,t))}):e.writeTree_.children.inorderTraversal((e,t)=>{null!=t.value&&n.push(new N(e,t.value))}),n}function Qn(e,t){var n;return E(t)?e:null!=(n=zn(e,t))?new Wn(new O(n)):new Wn(e.writeTree_.subtree(t))}function Yn(e){return e.writeTree_.isEmpty()}function Kn(e,t){return function r(i,e,s){{if(null!=e.value)return s.updateChild(i,e.value);{let n=null;return e.children.inorderTraversal((e,t)=>{".priority"===e?(f(null!==t.value,"Priority writes must always be leaf nodes"),n=t.value):s=r(I(i,e),t,s)}),s=s.getChild(i).isEmpty()||null===n?s:s.updateChild(I(i,".priority"),n)}}}(C(),e.writeTree_,t)}function Gn(e,t){return ar(t,e)}function $n(t,n){var e,r=t.allWrites.findIndex(e=>e.writeId===n);f(0<=r,"removeWrite called with nonexistent writeId.");let i=t.allWrites[r],s=(t.allWrites.splice(r,1),i.visible),o=!1,a=t.allWrites.length-1;for(;s&&0<=a;){var l=t.allWrites[a];l.visible&&(a>=r&&((e,t)=>{if(e.snap)return k(e.path,t);for(var n in e.children)if(e.children.hasOwnProperty(n)&&k(I(e.path,n),t))return 1})(l,i.path)?s=!1:k(i.path,l.path)&&(o=!0)),a--}return!!s&&(o?((e=t).visibleWrites=Xn(e.allWrites,Jn,C()),0<e.allWrites.length?e.lastWriteId=e.allWrites[e.allWrites.length-1].writeId:e.lastWriteId=-1):i.snap?t.visibleWrites=jn(t.visibleWrites,i.path):v(i.children,e=>{t.visibleWrites=jn(t.visibleWrites,I(i.path,e))}),!0)}function Jn(e){return e.visible}function Xn(e,t,n){let r=Wn.empty();for(let o=0;o<e.length;++o){var i=e[o];if(t(i)){var s=i.path;let e;if(i.snap)k(n,s)?(e=S(n,s),r=Bn(r,e,i.snap)):k(s,n)&&(e=S(s,n),r=Bn(r,C(),i.snap.getChild(e)));else{if(!i.children)throw W("WriteRecord should have .snap or .children");k(n,s)?(e=S(n,s),r=Un(r,e,i.children)):k(s,n)&&(E(e=S(s,n))?r=Un(r,C(),i.children):(s=G(i.children,b(e)))&&(i=s.getChild(T(e)),r=Bn(r,C(),i)))}}}return r}function Zn(e,t,n,r,i){var s;return r||i?(s=Qn(e.visibleWrites,t),!i&&Yn(s)?n:i||null!=n||Vn(s,C())?Kn(Xn(e.allWrites,function(e){return(e.visible||i)&&(!r||!~r.indexOf(e.writeId))&&(k(e.path,t)||k(t,e.path))},t),n||D.EMPTY_NODE):null):null!=(s=zn(e.visibleWrites,t))?s:Yn(s=Qn(e.visibleWrites,t))?n:null!=n||Vn(s,C())?Kn(s,n||D.EMPTY_NODE):null}function er(e,t,n,r){return Zn(e.writeTree,e.treePath,t,n,r)}function tr(e,t){{var n=e.writeTree;e=e.treePath;let i=D.EMPTY_NODE;var r=zn(n.visibleWrites,e);if(r)r.isLeafNode()||r.forEachChild(x,(e,t)=>{i=i.updateImmediateChild(e,t)});else if(t){let r=Qn(n.visibleWrites,e);t.forEachChild(x,(e,t)=>{var n=Kn(Qn(r,new w(e)),t);i=i.updateImmediateChild(e,n)}),Hn(r).forEach(e=>{i=i.updateImmediateChild(e.name,e.node)})}else Hn(Qn(n.visibleWrites,e)).forEach(e=>{i=i.updateImmediateChild(e.name,e.node)});return i}}function nr(e,t,n,r){return i=e.writeTree,e=e.treePath,t=t,n=n,r=r,f(n||r,"Either existingEventSnap or existingServerSnap must exist"),s=I(e,t),Vn(i.visibleWrites,s)?null:Yn(s=Qn(i.visibleWrites,s))?r.getChild(t):Kn(s,r.getChild(t));var i,s}function rr(e,t){return n=e.writeTree,e=I(e.treePath,t),zn(n.visibleWrites,e);var n}function ir(e,n,r,i,s,o){{var a=e.writeTree,l=(e=e.treePath,r),h=i;r=s,i=o;let t;var c=Qn(a.visibleWrites,e),u=zn(c,C());if(null!=u)t=u;else{if(null==n)return[];t=Kn(c,n)}if((t=t.withIndex(i)).isEmpty()||t.isLeafNode())return[];{var d=[],_=i.getCompare(),p=r?t.getReverseIteratorFrom(l,i):t.getIteratorFrom(l,i);let e=p.getNext();for(;e&&d.length<h;)0!==_(e,l)&&d.push(e),e=p.getNext();return d}}}function sr(e,t,n){return r=e.writeTree,n=n,i=I(e.treePath,e=t),null!=(s=zn(r.visibleWrites,i))?s:n.isCompleteForChild(e)?Kn(Qn(r.visibleWrites,i),n.getNode().getImmediateChild(e)):null;var r,i,s}function or(e,t){return ar(I(e.treePath,t),e.writeTree)}function ar(e,t){return{treePath:e,writeTree:t}}class lr{constructor(){this.changeMap=new Map}trackChildChange(e){var t=e.type,n=e.childName,r=(f("child_added"===t||"child_changed"===t||"child_removed"===t,"Only child changes supported for tracking"),f(".priority"!==n,"Only non-priority child changes can be tracked."),this.changeMap.get(n));if(r){var i=r.type;if("child_added"===t&&"child_removed"===i)this.changeMap.set(n,sn(n,e.snapshotNode,r.snapshotNode));else if("child_removed"===t&&"child_added"===i)this.changeMap.delete(n);else if("child_removed"===t&&"child_changed"===i)this.changeMap.set(n,rn(n,r.oldSnap));else if("child_changed"===t&&"child_added"===i)this.changeMap.set(n,nn(n,e.snapshotNode));else{if("child_changed"!==t||"child_changed"!==i)throw W("Illegal combination of changes: "+e+" occurred after "+r);this.changeMap.set(n,sn(n,e.snapshotNode,r.oldSnap))}}else this.changeMap.set(n,e)}getChanges(){return Array.from(this.changeMap.values())}}let hr=new class{getCompleteChild(e){return null}getChildAfterChild(e,t,n){return null}};class cr{constructor(e,t,n=null){this.writes_=e,this.viewCache_=t,this.optCompleteServerCache_=n}getCompleteChild(e){var t=this.viewCache_.eventCache;return t.isCompleteForChild(e)?t.getNode().getImmediateChild(e):(t=null!=this.optCompleteServerCache_?new Pn(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache,sr(this.writes_,e,t))}getChildAfterChild(e,t,n){var r=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:Fn(this.viewCache_),r=ir(this.writes_,r,t,1,n,e);return 0===r.length?null:r[0]}}function ur(e,t,n,r,i){var s=new lr;let o,a;if(n.type===d.OVERWRITE){var l=n;o=l.source.fromUser?pr(e,t,l.path,l.snap,r,i,s):(f(l.source.fromServer,"Unknown source."),a=l.source.tagged||t.serverCache.isFiltered()&&!E(l.path),_r(e,t,l.path,l.snap,r,i,a,s))}else if(n.type===d.MERGE){var l=n;o=l.source.fromUser?((r,i,s,e,o,a,l)=>{let h=i;return e.foreach((e,t)=>{var n=I(s,e);fr(i,b(n))&&(h=pr(r,h,n,t,o,a,l))}),e.foreach((e,t)=>{var n=I(s,e);fr(i,b(n))||(h=pr(r,h,n,t,o,a,l))}),h})(e,t,l.path,l.children,r,i,s):(f(l.source.fromServer,"Unknown source."),a=l.source.tagged||t.serverCache.isFiltered(),mr(e,t,l.path,l.children,r,i,a,s))}else if(n.type===d.ACK_USER_WRITE){l=n;o=l.revert?((n,r,i,s,e,o)=>{let a;if(null!=rr(s,i))return r;{var l=new cr(s,r,e),h=r.eventCache.getNode();let t;if(E(i)||".priority"===b(i)){let e;e=e=r.serverCache.isFullyInitialized()?er(s,Fn(r)):(c=r.serverCache.getNode(),f(c instanceof D,"serverChildren would be complete if leaf node"),tr(s,c)),t=n.filter.updateFullNode(h,e,o)}else{var c=b(i);let e=sr(s,c,r.serverCache);null==e&&r.serverCache.isCompleteForChild(c)&&(e=h.getImmediateChild(c)),(t=null!=e?n.filter.updateChild(h,c,e,T(i),l,o):r.eventCache.getNode().hasChild(c)?n.filter.updateChild(h,c,D.EMPTY_NODE,T(i),l,o):h).isEmpty()&&r.serverCache.isFullyInitialized()&&(a=er(s,Fn(r))).isLeafNode()&&(t=n.filter.updateFullNode(t,a,o))}return a=r.serverCache.isFullyInitialized()||null!=rr(s,C()),On(r,t,a,n.filter.filtersNodes())}})(e,t,l.path,r,i,s):((e,t,i,n,s,o,a)=>{if(null!=rr(s,i))return t;let l=t.serverCache.isFiltered(),h=t.serverCache;if(null!=n.value){if(E(i)&&h.isFullyInitialized()||h.isCompleteForPath(i))return _r(e,t,i,h.getNode().getChild(i),s,o,l,a);if(E(i)){let n=new O(null);return h.getNode().forEachChild(xt,(e,t)=>{n=n.set(new w(e),t)}),mr(e,t,i,n,s,o,l,a)}return t}{let r=new O(null);return n.foreach((e,t)=>{var n=I(i,e);h.isCompleteForPath(n)&&(r=r.set(e,h.getNode().getChild(n)))}),mr(e,t,i,r,s,o,l,a)}})(e,t,l.path,l.affectedTree,r,i,s)}else{if(n.type!==d.LISTEN_COMPLETE)throw W("Unknown operation type: "+n.type);o=(i=e,e=n.path,n=r,r=s,l=t.serverCache,l=Ln(t,l.getNode(),l.isFullyInitialized()||E(e),l.isFiltered()),dr(i,l,e,n,hr,r))}var h,c,s=s.getChanges(),i=t,e=o,n=s,u=e.eventCache;return u.isFullyInitialized()&&(h=u.getNode().isLeafNode()||u.getNode().isEmpty(),c=Mn(i),0<n.length||!i.eventCache.isFullyInitialized()||h&&!u.getNode().equals(c)||!u.getNode().getPriority().equals(c.getPriority()))&&n.push(tn(Mn(e))),{viewCache:o,changes:s}}function dr(r,i,s,o,a,l){var h=i.eventCache;if(null!=rr(o,s))return i;{let t,n;if(E(s))f(i.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),t=i.serverCache.isFiltered()?(c=tr(o,(c=Fn(i))instanceof D?c:D.EMPTY_NODE),r.filter.updateFullNode(i.eventCache.getNode(),c,l)):(c=er(o,Fn(i)),r.filter.updateFullNode(i.eventCache.getNode(),c,l));else{var c=b(s);if(".priority"===c){f(1===mt(s),"Can't have a priority with additional path components");var u=h.getNode(),d=nr(o,s,u,n=i.serverCache.getNode());t=null!=d?r.filter.updatePriority(u,d):h.getNode()}else{u=T(s);let e;e=h.isCompleteForChild(c)?(n=i.serverCache.getNode(),null!=(d=nr(o,s,h.getNode(),n))?h.getNode().getImmediateChild(c).updateChild(u,d):h.getNode().getImmediateChild(c)):sr(o,c,i.serverCache),t=null!=e?r.filter.updateChild(h.getNode(),c,e,u,a,l):h.getNode()}}return On(i,t,h.isFullyInitialized()||E(s),r.filter.filtersNodes())}}function _r(e,t,n,r,i,s,o,a){var l=t.serverCache;let h;var c=o?e.filter:e.filter.getIndexedFilter();if(E(n))h=c.updateFullNode(l.getNode(),r,null);else if(c.filtersNodes()&&!l.isFiltered()){var u=l.getNode().updateChild(n,r);h=c.updateFullNode(l.getNode(),u,null)}else{u=b(n);if(!l.isCompleteForPath(n)&&1<mt(n))return t;var d=T(n),_=l.getNode().getImmediateChild(u).updateChild(d,r);h=".priority"===u?c.updatePriority(l.getNode(),_):c.updateChild(l.getNode(),u,_,d,hr,null)}u=Ln(t,h,l.isFullyInitialized()||E(n),c.filtersNodes());return dr(e,u,n,i,new cr(i,u,s),a)}function pr(t,n,r,i,e,s,o){var a=n.eventCache;let l,h;var c=new cr(e,n,s);if(E(r))h=t.filter.updateFullNode(n.eventCache.getNode(),i,o),l=On(n,h,!0,t.filter.filtersNodes());else{var u=b(r);if(".priority"===u)h=t.filter.updatePriority(n.eventCache.getNode(),i),l=On(n,h,a.isFullyInitialized(),a.isFiltered());else{var d,_=T(r),p=a.getNode().getImmediateChild(u);let e;e=E(_)?i:null!=(d=c.getCompleteChild(u))?".priority"===vt(_)&&d.getChild(wt(_)).isEmpty()?d:d.updateChild(_,i):D.EMPTY_NODE,l=p.equals(e)?n:On(n,t.filter.updateChild(a.getNode(),u,e,_,c,o),a.isFullyInitialized(),t.filter.filtersNodes())}}return l}function fr(e,t){return e.eventCache.isCompleteForChild(t)}function gr(e,n,t){return t.foreach((e,t)=>{n=n.updateChild(e,t)}),n}function mr(r,i,e,t,s,o,a,l){if(i.serverCache.getNode().isEmpty()&&!i.serverCache.isFullyInitialized())return i;let h=i,n,c=(n=E(e)?t:new O(null).setTree(e,t),i.serverCache.getNode());return n.children.inorderTraversal((e,t)=>{var n;c.hasChild(e)&&(n=gr(0,i.serverCache.getNode().getImmediateChild(e),t),h=_r(r,h,new w(e),n,s,o,a,l))}),n.children.inorderTraversal((e,t)=>{var n=!i.serverCache.isCompleteForChild(e)&&null===t.value;c.hasChild(e)||n||(n=gr(0,i.serverCache.getNode().getImmediateChild(e),t),h=_r(r,h,new w(e),n,s,o,a,l))}),h}class vr{constructor(e,t){this.query_=e,this.eventRegistrations_=[];var n=this.query_._queryParams,r=new on(n.getIndex()),n=(e=n).loadsAllData()?new on(e.getIndex()):new(e.hasLimit()?ln:an)(e),i=(this.processor_={filter:n},t.serverCache),s=t.eventCache,o=r.updateFullNode(D.EMPTY_NODE,i.getNode(),null),a=n.updateFullNode(D.EMPTY_NODE,s.getNode(),null),o=new Pn(o,i.isFullyInitialized(),r.filtersNodes()),i=new Pn(a,s.isFullyInitialized(),n.filtersNodes());this.viewCache_=An(i,o),this.eventGenerator_=new Rn(this.query_)}get query(){return this.query_}}function yr(e){return 0===e.eventRegistrations_.length}function wr(r,i,s){let o=[];if(s){f(null==i,"A cancel should cancel all event registrations.");let n=r.query._path;r.eventRegistrations_.forEach(e=>{var t=e.createCancelEvent(s,n);t&&o.push(t)})}if(i){let e=[];for(let t=0;t<r.eventRegistrations_.length;++t){var n=r.eventRegistrations_[t];if(n.matches(i)){if(i.hasAnyCallback()){e=e.concat(r.eventRegistrations_.slice(t+1));break}}else e.push(n)}r.eventRegistrations_=e}else r.eventRegistrations_=[];return o}function Cr(e,t,n,r){t.type===d.MERGE&&null!==t.source.queryId&&(f(Fn(e.viewCache_),"We should always have a full cache before handling merges"),f(Mn(e.viewCache_),"Missing event cache, even though we have a server cache"));var i=e.viewCache_,s=ur(e.processor_,i,t,n,r);return t=e.processor_,n=s.viewCache,f(n.eventCache.getNode().isIndexed(t.filter.getIndex()),"Event snap not indexed"),f(n.serverCache.getNode().isIndexed(t.filter.getIndex()),"Server snap not indexed"),f(s.viewCache.serverCache.isFullyInitialized()||!i.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),e.viewCache_=s.viewCache,br(e,s.changes,s.viewCache.eventCache.getNode(),null)}function br(e,t,n,r){var i=r?[r]:e.eventRegistrations_;return xn(e.eventGenerator_,t,n,i)}let Tr;class Ir{constructor(){this.views=new Map}}function Er(t,n,r,i){var e=n.source.queryId;if(null!==e)return e=t.views.get(e),f(null!=e,"SyncTree gave us an op for an invalid query."),Cr(e,n,r,i);{let e=[];for(var s of t.views.values())e=e.concat(Cr(s,n,r,i));return e}}function Sr(e,n,r,i,s){var o=n._queryIdentifier,o=e.views.get(o);if(o)return o;{let e=er(r,s?i:null),t=!1;t=!!e||(e=i instanceof D?tr(r,i):D.EMPTY_NODE,!1);o=An(new Pn(e,t,!1),new Pn(i,s,!1));return new vr(n,o)}}function kr(e,t,r,i,s,n){var o=Sr(e,t,i,s,n);e.views.has(t._queryIdentifier)||e.views.set(t._queryIdentifier,o),o.eventRegistrations_.push(r);{s=r,o=(i=o).viewCache_.eventCache;let n=[];return o.getNode().isLeafNode()||o.getNode().forEachChild(x,(e,t)=>{n.push(nn(e,t))}),o.isFullyInitialized()&&n.push(tn(o.getNode())),br(i,n,o.getNode(),s)}}function Nr(e,t,n,r){var i=t._queryIdentifier,s=[];let o=[];var a=Ar(e);if("default"===i)for(var[l,h]of e.views.entries())o=o.concat(wr(h,n,r)),yr(h)&&(e.views.delete(l),h.query._queryParams.loadsAllData()||s.push(h.query));else{var c=e.views.get(i);c&&(o=o.concat(wr(c,n,r)),yr(c))&&(e.views.delete(i),c.query._queryParams.loadsAllData()||s.push(c.query))}return a&&!Ar(e)&&s.push((f(Tr,"Reference.ts has not been loaded"),new Tr(t._repo,t._path))),{removed:s,events:o}}function Pr(e){var t,n=[];for(t of e.views.values())t.query._queryParams.loadsAllData()||n.push(t);return n}function Rr(e,t){let n=null;for(var r of e.views.values())n=n||(i=r,s=t,r=void 0,(r=Fn(i.viewCache_))&&(i.query._queryParams.loadsAllData()||!E(s)&&!r.getImmediateChild(b(s)).isEmpty())?r.getChild(s):null);var i,s;return n}function xr(e,t){var n;return t._queryParams.loadsAllData()?Or(e):(n=t._queryIdentifier,e.views.get(n))}function Dr(e,t){return null!=xr(e,t)}function Ar(e){return null!=Or(e)}function Or(e){for(var t of e.views.values())if(t.query._queryParams.loadsAllData())return t;return null}let Lr;let Mr=1;class Fr{constructor(e){this.listenProvider_=e,this.syncPointTree_=new O(null),this.pendingWriteTree_={visibleWrites:Wn.empty(),allWrites:[],lastWriteId:-1},this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function qr(e,t,n,r,i){var s,o,a,l;return s=e.pendingWriteTree_,o=t,a=n,r=r,l=i,f(r>s.lastWriteId,"Stacking an older write on top of newer ones"),s.allWrites.push({path:o,snap:a,writeId:r,visible:l=void 0===l?!0:l}),l&&(s.visibleWrites=Bn(s.visibleWrites,o,a)),s.lastWriteId=r,i?Yr(e,new kn(bn(),t,n)):[]}function Wr(e,t,n,r){i=e.pendingWriteTree_,s=t,o=n,r=r,f(r>i.lastWriteId,"Stacking an older merge on top of newer ones"),i.allWrites.push({path:s,children:o,writeId:r,visible:!0}),i.visibleWrites=Un(i.visibleWrites,s,o),i.lastWriteId=r;var i,s,o,a=O.fromObject(n);return Yr(e,new Nn(bn(),t,a))}function Br(e,t,n=!1){var r=((e,t)=>{for(let r=0;r<e.allWrites.length;r++){var n=e.allWrites[r];if(n.writeId===t)return n}return null})(e.pendingWriteTree_,t);if($n(e.pendingWriteTree_,t)){let t=new O(null);return null!=r.snap?t=t.set(C(),!0):v(r.children,e=>{t=t.set(new w(e),!0)}),Yr(e,new En(r.path,t,n))}return[]}function Ur(e,t,n){return Yr(e,new kn(Tn(),t,n))}function jr(n,t,r,i,s=!1){var o=t._path,a=n.syncPointTree_.get(o);let l=[];if(a&&("default"===t._queryIdentifier||Dr(a,t))){var h=Nr(a,t,r,i),a=(0===a.views.size&&(n.syncPointTree_=n.syncPointTree_.remove(o)),h.removed);if(l=h.events,!s){var h=-1!==a.findIndex(e=>e._queryParams.loadsAllData()),c=n.syncPointTree_.findOnPath(o,(e,t)=>Ar(t));if(h&&!c){o=n.syncPointTree_.subtree(o);if(!o.isEmpty()){var u=o.fold((e,t,r)=>{if(t&&Ar(t))return[Or(t)];{let n=[];return t&&(n=Pr(t)),v(r,(e,t)=>{n=n.concat(t)}),n}});for(let e=0;e<u.length;++e){var d=u[e],_=d.query,d=Gr(n,d);n.listenProvider_.startListening(ti(_),$r(n,_),d.hashFn,d.onComplete)}}}!c&&0<a.length&&!i&&(h?n.listenProvider_.stopListening(ti(t),null):a.forEach(e=>{var t=n.queryToTagMap.get(Jr(e));n.listenProvider_.stopListening(ti(e),t)}))}var p=n,f=a;for(let e=0;e<f.length;++e){var g,m=f[e];m._queryParams.loadsAllData()||(m=Jr(m),g=p.queryToTagMap.get(m),p.queryToTagMap.delete(m),p.tagToQueryMap.delete(g))}}return l}function Vr(e,t,n,r){var i,s,o=Xr(e,r);return null!=o?(i=(o=Zr(o)).path,o=o.queryId,s=S(i,t),ei(e,i,new kn(In(o),s,n))):[]}function zr(e,t,n,r=!1){let i=t._path,s=null,o=!1,a=(e.syncPointTree_.foreachOnPath(i,(e,t)=>{var n=S(e,i);s=s||Rr(t,n),o=o||Ar(t)}),e.syncPointTree_.get(i));a?(o=o||Ar(a),s=s||Rr(a,C())):(a=new Ir,e.syncPointTree_=e.syncPointTree_.set(i,a));let l;null!=s?l=!0:(l=!1,s=D.EMPTY_NODE,e.syncPointTree_.subtree(i).foreachChild((e,t)=>{var n=Rr(t,C());n&&(s=s.updateImmediateChild(e,n))}));var h,c=Dr(a,t),u=(c||t._queryParams.loadsAllData()||(h=Jr(t),f(!e.queryToTagMap.has(h),"View does not exist, but we have a tag"),u=Mr++,e.queryToTagMap.set(h,u),e.tagToQueryMap.set(u,h)),Gn(e.pendingWriteTree_,i));let d=kr(a,t,n,u,s,l);return c||o||r||(h=xr(a,t),d=d.concat(((t,e,n)=>{var r=e._path,i=$r(t,e),s=Gr(t,n),s=t.listenProvider_.startListening(ti(e),i,s.hashFn,s.onComplete),r=t.syncPointTree_.subtree(r);if(i)f(!Ar(r.value),"If we're adding a query, it shouldn't be shadowed");else{var o=r.fold((e,t,r)=>{if(!E(e)&&t&&Ar(t))return[Or(t).query];{let n=[];return t&&(n=n.concat(Pr(t).map(e=>e.query))),v(r,(e,t)=>{n=n.concat(t)}),n}});for(let e=0;e<o.length;++e){var a=o[e];t.listenProvider_.stopListening(ti(a),$r(t,a))}}return s})(e,t,h))),d}function Hr(e,r,t){var n=e.pendingWriteTree_,i=e.syncPointTree_.findOnPath(r,(e,t)=>{var n=Rr(t,S(e,r));if(n)return n});return Zn(n,r,i,t,!0)}function Qr(e,t){let r=t._path,i=null,n=(e.syncPointTree_.foreachOnPath(r,(e,t)=>{var n=S(e,r);i=i||Rr(t,n)}),e.syncPointTree_.get(r));n?i=i||Rr(n,C()):(n=new Ir,e.syncPointTree_=e.syncPointTree_.set(r,n));var s=null!=i,o=s?new Pn(i,!0,!1):null,a=Gn(e.pendingWriteTree_,t._path);return Mn(Sr(n,t,a,s?o.getNode():D.EMPTY_NODE,s).viewCache_)}function Yr(e,t){return function o(t,a,l,h){{if(E(t.path))return Kr(t,a,l,h);{let e=a.get(C()),n=(null==l&&null!=e&&(l=Rr(e,C())),[]),r=b(t.path),i=t.operationForChild(r),s=a.children.get(r);if(s&&i){let e=l?l.getImmediateChild(r):null,t=or(h,r);n=n.concat(o(i,s,e,t))}return n=e?n.concat(Er(e,t,h,l)):n}}}(t,e.syncPointTree_,null,Gn(e.pendingWriteTree_,C()))}function Kr(s,e,o,a){var t=e.get(C());null==o&&null!=t&&(o=Rr(t,C()));let l=[];return e.children.inorderTraversal((e,t)=>{var n=o?o.getImmediateChild(e):null,r=or(a,e),i=s.operationForChild(e);i&&(l=l.concat(Kr(i,t,n,r)))}),l=t?l.concat(Er(t,s,a,o)):l}function Gr(a,e){let l=e.query,h=$r(a,l);return{hashFn:()=>(e.viewCache_.serverCache.getNode()||D.EMPTY_NODE).hash(),onComplete:e=>{var t,n,r,i,s,o;return"ok"===e?h?(t=a,n=l._path,r=h,(o=Xr(t,r))?(i=(o=Zr(o)).path,o=o.queryId,s=S(i,n),ei(t,i,new Sn(In(o),s))):[]):(r=a,n=l._path,Yr(r,new Sn(Tn(),n))):(i=((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");var r=new Error(e+" at "+t._path.toString()+": "+n);return r.code=e.toUpperCase(),r})(e,l),jr(a,l,null,i))}}}function $r(e,t){var n=Jr(t);return e.queryToTagMap.get(n)}function Jr(e){return e._path.toString()+"$"+e._queryIdentifier}function Xr(e,t){return e.tagToQueryMap.get(t)}function Zr(e){var t=e.indexOf("$");return f(-1!==t&&t<e.length-1,"Bad queryKey."),{queryId:e.substr(t+1),path:new w(e.substr(0,t))}}function ei(e,t,n){var r=e.syncPointTree_.get(t),i=(f(r,"Missing sync point for query tag that we're tracking"),Gn(e.pendingWriteTree_,t));return Er(r,n,i,null)}function ti(e){return e._queryParams.loadsAllData()&&!e._queryParams.isDefault()?(f(Lr,"Reference.ts has not been loaded"),new Lr(e._repo,e._path)):e}class ni{constructor(e){this.node_=e}getImmediateChild(e){var t=this.node_.getImmediateChild(e);return new ni(t)}node(){return this.node_}}class ri{constructor(e,t){this.syncTree_=e,this.path_=t}getImmediateChild(e){var t=I(this.path_,e);return new ri(this.syncTree_,t)}node(){return Hr(this.syncTree_,this.path_)}}let ii=function(e){return(e=e||{}).timestamp=e.timestamp||(new Date).getTime(),e},si=function(e,t,n){return e&&"object"==typeof e?(f(".sv"in e,"Unexpected leaf node or priority contents"),"string"==typeof e[".sv"]?oi(e[".sv"],t,n):"object"==typeof e[".sv"]?ai(e[".sv"],t):void f(!1,"Unexpected server value: "+JSON.stringify(e,null,2))):e},oi=function(e,t,n){if("timestamp"===e)return n.timestamp;f(!1,"Unexpected server value: "+e)},ai=function(e,t,n){e.hasOwnProperty("increment")||f(!1,"Unexpected server value: "+JSON.stringify(e,null,2));var r=e.increment,i=("number"!=typeof r&&f(!1,"Unexpected increment value: "+r),t.node());return f(null!=i,"Expected ChildrenNode.EMPTY_NODE for nulls"),!i.isLeafNode()||"number"!=typeof(i=i.getValue())?r:i+r},li=function(e,t,n,r){return ci(t,new ri(n,e),r)},hi=function(e,t,n){return ci(e,new ni(t),n)};function ci(e,r,i){var t,n,s=e.getPriority().val(),s=si(s,r.getImmediateChild(".priority"),i);let o;return e.isLeafNode()?(n=e,(t=si(n.getValue(),r,i))!==n.getValue()||s!==n.getPriority().val()?new R(t,A(s)):e):(n=e,s!==(o=n).getPriority().val()&&(o=o.updatePriority(new R(s))),n.forEachChild(x,(e,t)=>{var n=ci(t,r.getImmediateChild(e),i);n!==t&&(o=o.updateImmediateChild(e,n))}),o)}class ui{constructor(e="",t=null,n={children:{},childCount:0}){this.name=e,this.parent=t,this.node=n}}function di(e,t){let n=t instanceof w?t:new w(t),r=e,i=b(n);for(;null!==i;){var s=G(r.node.children,i)||{children:{},childCount:0};r=new ui(i,r,s),n=T(n),i=b(n)}return r}function _i(e){return e.node.value}function pi(e,t){e.node.value=t,vi(e)}function fi(e){return 0<e.node.childCount}function gi(n,r){v(n.node.children,(e,t)=>{r(new ui(e,n,t))})}function mi(e){return new w(null===e.parent?e.name:mi(e.parent)+"/"+e.name)}function vi(e){var t,n,r,i;null!==e.parent&&(t=e.parent,n=e.name,r=(e=>void 0===_i(e)&&!fi(e))(e=e),i=p(t.node.children,n),r&&i?(delete t.node.children[n],t.node.childCount--,vi(t)):r||i||(t.node.children[n]=e.node,t.node.childCount++,vi(t)))}function yi(e,t,n,r){r&&void 0===t||xi(h(e,"value"),t,n)}function wi(e,t,r,n){let i=h(e,"values");if(!t||"object"!=typeof t||Array.isArray(t))throw new Error(i+" must be an object containing the children to replace.");let s=[];v(t,(e,t)=>{var n=new w(e);if(xi(i,t,I(r,n)),".priority"===vt(n)&&!Ri(t))throw new Error(i+"contains an invalid value for '"+n.toString()+"', which must be a valid Firebase priority (a string, finite number, server value, or null).");s.push(n)});{var o=i,a=s;let t,n;for(t=0;t<a.length;t++){var l=yt(n=a[t]);for(let e=0;e<l.length;e++)if((".priority"!==l[e]||e!==l.length-1)&&!ki(l[e]))throw new Error(o+"contains an invalid key ("+l[e]+") in path "+n.toString()+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"')}a.sort(Ct);let e=null;for(t=0;t<a.length;t++){if(n=a[t],null!==e&&k(e,n))throw new Error(o+"contains a path "+e.toString()+" that is ancestor of another path "+n.toString());e=n}}}function Ci(e,t,n){if(Fe(t))throw new Error(h(e,"priority")+"is "+t.toString()+", but must be a valid Firebase priority (a string, finite number, server value, or null).");if(!Ri(t))throw new Error(h(e,"priority")+"must be a valid Firebase priority (a string, finite number, server value, or null).")}function bi(e,t,n,r){if(void 0!==n&&!ki(n))throw new Error(h(e,t)+'was an invalid key = "'+n+'". Firebase keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]").')}function Ti(e,t,n,r){n=n&&n.replace(/^\/*\.info(\/|$)/,"/"),Di(e,t,n)}function L(e,t){if(".info"===b(t))throw new Error(e+" failed = Can't modify data under /.info/")}let Ii=/[\[\].#$\/\u0000-\u001F\u007F]/,Ei=/[\[\].#$\u0000-\u001F\u007F]/,Si=10485760,ki=function(e){return"string"==typeof e&&0!==e.length&&!Ii.test(e)},Ni=function(e){return"string"==typeof e&&0!==e.length&&!Ei.test(e)},Pi=function(e){return e=e&&e.replace(/^\/*\.info(\/|$)/,"/"),Ni(e)},Ri=function(e){return null===e||"string"==typeof e||"number"==typeof e&&!Fe(e)||e&&"object"==typeof e&&p(e,".sv")},xi=function(o,e,t){let a=t instanceof w?new Tt(t,o):t;if(void 0===e)throw new Error(o+"contains undefined "+Et(a));if("function"==typeof e)throw new Error(o+"contains a function "+Et(a)+" with contents = "+e.toString());if(Fe(e))throw new Error(o+"contains "+e.toString()+" "+Et(a));if("string"==typeof e&&e.length>Si/3&&te(e)>Si)throw new Error(o+"contains a string greater than "+Si+" utf8 bytes "+Et(a)+" ('"+e.substring(0,50)+"...')");if(e&&"object"==typeof e){let i=!1,s=!1;if(v(e,(e,t)=>{if(".value"===e)i=!0;else if(".priority"!==e&&".sv"!==e&&(s=!0,!ki(e)))throw new Error(o+" contains an invalid key ("+e+") "+Et(a)+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');var n,r;n=a,e=e,0<n.parts_.length&&(n.byteLength_+=1),n.parts_.push(e),n.byteLength_+=te(e),It(n),xi(o,t,a),e=a,r=e.parts_.pop(),e.byteLength_-=te(r),0<e.parts_.length&&--e.byteLength_}),i&&s)throw new Error(o+' contains ".value" child '+Et(a)+" in addition to actual children.")}},Di=function(e,t,n,r){if(!Ni(n))throw new Error(h(e,t)+'was an invalid path = "'+n+'". Paths must be non-empty strings and can\'t contain ".", "#", "$", "[", or "]"')},Ai=function(e,t){var n=t.path.toString();if("string"!=typeof t.repoInfo.host||0===t.repoInfo.host.length||!ki(t.repoInfo.namespace)&&"localhost"!==t.repoInfo.host.split(":")[0]||0!==n.length&&!Pi(n))throw new Error(h(e,"url")+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')};class Oi{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function Li(e,t){let n=null;for(let s=0;s<t.length;s++){var r=t[s],i=r.getPath();null===n||bt(i,n.path)||(e.eventLists_.push(n),n=null),(n=null===n?{events:[],path:i}:n).events.push(r)}n&&e.eventLists_.push(n)}function Mi(e,t,n){Li(e,n),Fi(e,e=>bt(e,t))}function M(e,t,n){Li(e,n),Fi(e,e=>k(e,t)||k(t,e))}function Fi(t,e){t.recursionDepth_++;let n=!0;for(let a=0;a<t.eventLists_.length;a++){var r=t.eventLists_[a];if(r)if(e(r.path)){s=o=i=void 0;var i=t.eventLists_[a];for(let e=0;e<i.events.length;e++){var s,o=i.events[e];null!==o&&(i.events[e]=null,s=o.getEventRunner(),De&&u("event: "+o.toString()),Ye(s))}t.eventLists_[a]=null}else n=!1}n&&(t.eventLists_=[]),t.recursionDepth_--}let qi="repo_interrupt",Wi=25;class Bi{constructor(e,t,n,r){this.repoInfo_=e,this.forceRestClient_=t,this.authTokenProvider_=n,this.appCheckProvider_=r,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new Oi,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=mn(),this.transactionQueueTree_=new ui,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function Ui(o,e,t){if(o.stats_=st(o.repoInfo_),o.forceRestClient_||0<=("object"==typeof window&&window.navigator&&window.navigator.userAgent||"").search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i))o.server_=new fn(o.repoInfo_,(e,t,n,r)=>{zi(o,e,t,n,r)},o.authTokenProvider_,o.appCheckProvider_),setTimeout(()=>Hi(o,!0),0);else{if(null!=t){if("object"!=typeof t)throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{a(t)}catch(e){throw new Error("Invalid authOverride provided: "+e)}}o.persistentConnection_=new kt(o.repoInfo_,e,(e,t,n,r)=>{zi(o,e,t,n,r)},e=>{Hi(o,e)},e=>{var n;n=o,v(e,(e,t)=>{Qi(n,e,t)})},o.authTokenProvider_,o.appCheckProvider_,t),o.server_=o.persistentConnection_}var n;o.authTokenProvider_.addTokenChangeListener(e=>{o.server_.refreshAuthToken(e)}),o.appCheckProvider_.addTokenChangeListener(e=>{o.server_.refreshAppCheckToken(e.token)}),o.statsReporter_=(e=()=>new Cn(o.stats_,o.server_),n=o.repoInfo_.toString(),it[n]||(it[n]=e()),it[n]),o.infoData_=new gn,o.infoSyncTree_=new Fr({startListening:(e,t,n,r)=>{let i=[];var s=o.infoData_.getNode(e._path);return s.isEmpty()||(i=Ur(o.infoSyncTree_,e._path,s),setTimeout(()=>{r("ok")},0)),i},stopListening:()=>{}}),Qi(o,"connected",!1),o.serverSyncTree_=new Fr({startListening:(r,e,t,i)=>(o.server_.listen(r,t,e,(e,t)=>{var n=i(e,t);M(o.eventQueue_,r._path,n)}),[]),stopListening:(e,t)=>{o.server_.unlisten(e,t)}})}function ji(e){var t=e.infoData_.getNode(new w(".info/serverTimeOffset")).val()||0;return(new Date).getTime()+t}function Vi(e){return ii({timestamp:ji(e)})}function zi(e,t,n,r,i){e.dataUpdateCount++;var s,o,a,l,h,c,u=new w(t);n=e.interceptServerDataCallback_?e.interceptServerDataCallback_(t,n):n;let d=[],_=u;0<(d=i?r?(c=J(n,e=>A(e)),t=e.serverSyncTree_,s=u,o=c,(c=Xr(t,i))?(a=(c=Zr(c)).path,c=c.queryId,l=S(a,s),h=O.fromObject(o),ei(t,a,new Nn(In(c),l,h))):[]):(a=A(n),Vr(e.serverSyncTree_,u,a,i)):r?(c=J(n,e=>A(e)),s=e.serverSyncTree_,o=u,t=c,l=O.fromObject(t),Yr(s,new Nn(Tn(),o,l))):(h=A(n),Ur(e.serverSyncTree_,u,h))).length&&(_=rs(e,u)),M(e.eventQueue_,_,d)}function Hi(e,t){if(Qi(e,"connected",t),!1===t){var o=e;Zi(o,"onDisconnectEvents");let r=Vi(o),i=mn(),s=(yn(o.onDisconnect_,C(),(e,t)=>{var n=li(e,t,o.serverSyncTree_,r);vn(i,e,n)}),[]);yn(i,C(),(e,t)=>{s=s.concat(Ur(o.serverSyncTree_,e,t));var n=as(o,e);rs(o,n)}),o.onDisconnect_=mn(),M(o.eventQueue_,C(),s)}}function Qi(e,t,n){var r=new w("/.info/"+t),i=A(n),i=(e.infoData_.updateSnapshot(r,i),Ur(e.infoSyncTree_,r,i));M(e.eventQueue_,r,i)}function Yi(e){return e.nextWriteId_++}function Ki(r,i,e,t,s){Zi(r,"set",{path:i.toString(),value:e,priority:t});var n=Vi(r),o=A(e,t),a=Hr(r.serverSyncTree_,i),a=hi(o,a,n);let l=Yi(r);n=qr(r.serverSyncTree_,i,a,l,!0),Li(r.eventQueue_,n),r.server_.put(i.toString(),o.val(!0),(e,t)=>{var n="ok"===e,n=(n||m("set at "+i+" failed: "+e),Br(r.serverSyncTree_,l,!n));M(r.eventQueue_,i,n),es(0,s,e,t)}),a=as(r,i);rs(r,a),M(r.eventQueue_,a,[])}function Gi(n,r,i){n.server_.onDisconnectCancel(r.toString(),(e,t)=>{"ok"===e&&!function e(n,t){var r;return E(t)?(n.value=null,n.children.clear(),!0):null!==n.value?!n.value.isLeafNode()&&(r=n.value,n.value=null,r.forEachChild(x,(e,t)=>{vn(n,new w(e),t)}),e(n,t)):!(0<n.children.size)||(r=b(t),t=T(t),n.children.has(r)&&e(n.children.get(r),t)&&n.children.delete(r),0===n.children.size)}(n.onDisconnect_,r),es(0,i,e,t)})}function $i(n,r,e,i){let s=A(e);n.server_.onDisconnectPut(r.toString(),s.val(!0),(e,t)=>{"ok"===e&&vn(n.onDisconnect_,r,s),es(0,i,e,t)})}function Ji(e,t,n){let r;r=".info"===b(t._path)?jr(e.infoSyncTree_,t,n):jr(e.serverSyncTree_,t,n),Mi(e.eventQueue_,t._path,r)}function Xi(e){e.persistentConnection_&&e.persistentConnection_.interrupt(qi)}function Zi(e,...t){let n="";e.persistentConnection_&&(n=e.persistentConnection_.id+":"),u(n,...t)}function es(e,r,i,s){r&&Ye(()=>{if("ok"===i)r(null);else{var t=(i||"error").toUpperCase();let e=t;s&&(e+=": "+s);var n=new Error(e);n.code=t,r(n)}})}function ts(e,t,n){return Hr(e.serverSyncTree_,t,n)||D.EMPTY_NODE}function ns(a,l=a.transactionQueueTree_){if(l||os(a,l),_i(l)){var h=ss(a,l),e=(f(0<h.length,"Sending zero length transaction queue"),h.every(e=>0===e.status));if(e){var c=a;var u=mi(l);var d=h;let e=d.map(e=>e.currentWriteId),t=ts(c,u,e),n=t,r=t.hash();for(let o=0;o<d.length;o++){var _=d[o],p=(f(0===_.status,"tryToSendTransactionQueue_: items in queue should all be run."),_.status=1,_.retryCount++,S(u,_.path));n=n.updateChild(p,_.currentOutputSnapshotRaw)}let i=n.val(!0),s=u;c.server_.put(s.toString(),i,t=>{Zi(c,"transaction put response",{path:s.toString(),status:t});let n=[];if("ok"===t){var r=[];for(let e=0;e<d.length;e++)d[e].status=2,n=n.concat(Br(c.serverSyncTree_,d[e].currentWriteId)),d[e].onComplete&&r.push(()=>d[e].onComplete(null,!0,d[e].currentOutputSnapshotResolved)),d[e].unwatcher();os(c,di(c.transactionQueueTree_,u)),ns(c,c.transactionQueueTree_),M(c.eventQueue_,u,n);for(let t=0;t<r.length;t++)Ye(r[t])}else{if("datastale"===t)for(let e=0;e<d.length;e++)3===d[e].status?d[e].status=4:d[e].status=0;else{m("transaction at "+s.toString()+" failed: "+t);for(let e=0;e<d.length;e++)d[e].status=4,d[e].abortReason=t}rs(c,u)}},r)}}else fi(l)&&gi(l,e=>{ns(a,e)})}function rs(e,t){var n=is(e,t),r=mi(n),n=ss(e,n),i=e,s=n,o=r;if(0!==s.length){var a=[];let n=[];var l=s.filter(e=>0===e.status).map(e=>e.currentWriteId);for(let r=0;r<s.length;r++){var h=s[r],c=S(o,h.path);let e=!1,t;if(f(null!==c,"rerunTransactionsUnderNode_: relativePath should not be null."),4===h.status)e=!0,t=h.abortReason,n=n.concat(Br(i.serverSyncTree_,h.currentWriteId,!0));else if(0===h.status)if(h.retryCount>=Wi)e=!0,t="maxretry",n=n.concat(Br(i.serverSyncTree_,h.currentWriteId,!0));else{var c=ts(i,h.path,l),u=(h.currentInputSnapshot=c,s[r].update(c.val()));if(void 0!==u){xi("transaction failed: Data returned ",u,h.path);let e=A(u);"object"==typeof u&&null!=u&&p(u,".priority")||(e=e.updatePriority(c.getPriority()));var u=h.currentWriteId,d=Vi(i),c=hi(e,c,d);h.currentOutputSnapshotRaw=e,h.currentOutputSnapshotResolved=c,h.currentWriteId=Yi(i),l.splice(l.indexOf(u),1),n=(n=n.concat(qr(i.serverSyncTree_,h.path,c,h.currentWriteId,h.applyLocally))).concat(Br(i.serverSyncTree_,u,!0))}else e=!0,t="nodata",n=n.concat(Br(i.serverSyncTree_,h.currentWriteId,!0))}M(i.eventQueue_,o,n),n=[],e&&(s[r].status=2,(e=>{setTimeout(e,Math.floor(0))})(s[r].unwatcher),s[r].onComplete)&&("nodata"===t?a.push(()=>s[r].onComplete(null,!1,s[r].currentInputSnapshot)):a.push(()=>s[r].onComplete(new Error(t),!1,null)))}os(i,i.transactionQueueTree_);for(let e=0;e<a.length;e++)Ye(a[e]);ns(i,i.transactionQueueTree_)}return r}function is(e,t){let n,r=e.transactionQueueTree_;for(n=b(t);null!==n&&void 0===_i(r);)r=di(r,n),t=T(t),n=b(t);return r}function ss(e,t){var n=[];return function t(n,e,r){let i=_i(e);if(i)for(let e=0;e<i.length;e++)r.push(i[e]);gi(e,e=>{t(n,e,r)})}(e,t,n),n.sort((e,t)=>e.order-t.order),n}function os(t,n){var r=_i(n);if(r){let e=0;for(let t=0;t<r.length;t++)2!==r[t].status&&(r[e]=r[t],e++);r.length=e,pi(n,0<r.length?r:void 0)}gi(n,e=>{os(t,e)})}function as(t,e){var n=mi(is(t,e)),r=di(t.transactionQueueTree_,e);return((e,t)=>{let n=e.parent;for(;null!==n;){if(t(n))return;n=n.parent}})(r,e=>{ls(t,e)}),ls(t,r),function t(e,n,r){r&&n(e),gi(e,e=>{t(e,n,!0)})}(r,e=>{ls(t,e)}),n}function ls(i,s){var o=_i(s);if(o){var a=[];let e=[],t=-1;for(let n=0;n<o.length;n++)3!==o[n].status&&(1===o[n].status?(f(t===n-1,"All SENT items should be at beginning of queue."),o[t=n].status=3,o[n].abortReason="set"):(f(0===o[n].status,"Unexpected transaction status in abort"),o[n].unwatcher(),e=e.concat(Br(i.serverSyncTree_,o[n].currentWriteId,!0)),o[n].onComplete&&a.push(o[n].onComplete.bind(null,new Error("set"),!1,null))));-1===t?pi(s,void 0):o.length=t+1,M(i.eventQueue_,mi(s),e);for(let r=0;r<a.length;r++)Ye(a[r])}}let hs=function(e,t){var n=cs(e),r=n.namespace,i=("firebase.com"===n.domain&&Le(n.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),r&&"undefined"!==r||"localhost"===n.domain||Le("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),n.secure||Me(),"ws"===n.scheme||"wss"===n.scheme);return{repoInfo:new et(n.host,n.secure,r,i,t,"",r!==n.subdomain),path:new w(n.pathString)}},cs=function(r){let i="",s="",o="",a="",l="",h=!0,c="https",u=443;if("string"==typeof r){let e=r.indexOf("//"),t=(0<=e&&(c=r.substring(0,e-1),r=r.substring(e+2)),r.indexOf("/")),n=(-1===t&&(t=r.length),r.indexOf("?"));-1===n&&(n=r.length),i=r.substring(0,Math.min(t,n)),t<n&&(a=(e=>{let t="";var n=e.split("/");for(let r=0;r<n.length;r++)if(0<n[r].length){let e=n[r];try{e=decodeURIComponent(e.replace(/\+/g," "))}catch(e){}t+="/"+e}return t})(r.substring(t,n)));var d=(e=>{var t,n,r={};for(t of(e="?"===e.charAt(0)?e.substring(1):e).split("&"))0!==t.length&&(2===(n=t.split("=")).length?r[decodeURIComponent(n[0])]=decodeURIComponent(n[1]):m(`Invalid query segment '${t}' in query '${e}'`));return r})(r.substring(Math.min(r.length,n))),_=(0<=(e=i.indexOf(":"))?(h="https"===c||"wss"===c,u=parseInt(i.substring(e+1),10)):e=i.length,i.slice(0,e));"localhost"===_.toLowerCase()?s="localhost":_.split(".").length<=2?s=_:(_=i.indexOf("."),o=i.substring(0,_).toLowerCase(),s=i.substring(_+1),l=o),"ns"in d&&(l=d.ns)}return{host:i,port:u,domain:s,subdomain:o,secure:h,scheme:c,pathString:a,namespace:l}},us="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",ds=(()=>{let s=0,o=[];return function(e){var t=e===s;s=e;let n;var r=new Array(8);for(n=7;0<=n;n--)r[n]=us.charAt(e%64),e=Math.floor(e/64);f(0===e,"Cannot push at time == 0");let i=r.join("");if(t){for(n=11;0<=n&&63===o[n];n--)o[n]=0;o[n]++}else for(n=0;n<12;n++)o[n]=Math.floor(64*Math.random());for(n=0;n<12;n++)i+=us.charAt(o[n]);return f(20===i.length,"nextPushId: Length should be 20."),i}})();class _s{constructor(e,t,n,r){this.eventType=e,this.eventRegistration=t,this.snapshot=n,this.prevName=r}getPath(){var e=this.snapshot.ref;return("value"===this.eventType?e:e.parent)._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+a(this.snapshot.exportVal())}}class ps{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 fs{constructor(e,t){this.snapshotCallback=e,this.cancelCallback=t}onValue(e,t){this.snapshotCallback.call(null,e,t)}onCancel(e){return f(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}}let gs=class{constructor(e,t){this._repo=e,this._path=t}cancel(){var e=new _;return Gi(this._repo,this._path,e.wrapCallback(()=>{})),e.promise}remove(){L("OnDisconnect.remove",this._path);var e=new _;return $i(this._repo,this._path,null,e.wrapCallback(()=>{})),e.promise}set(e){L("OnDisconnect.set",this._path),yi("OnDisconnect.set",e,this._path,!1);var t=new _;return $i(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}setWithPriority(e,t){L("OnDisconnect.setWithPriority",this._path),yi("OnDisconnect.setWithPriority",e,this._path,!1),Ci("OnDisconnect.setWithPriority",t);var r=new _;{var i=this._repo,s=this._path,o=r.wrapCallback(()=>{});let n=A(e,t);i.server_.onDisconnectPut(s.toString(),n.val(!0),(e,t)=>{"ok"===e&&vn(i.onDisconnect_,s,n),es(0,o,e,t)})}return r.promise}update(e){L("OnDisconnect.update",this._path),wi("OnDisconnect.update",e,this._path);var r,i,n,s,t=new _;return r=this._repo,i=this._path,n=e,s=t.wrapCallback(()=>{}),$(n)?(u("onDisconnect().update() called with empty data. Don't do anything."),es(0,s,"ok",void 0)):r.server_.onDisconnectMerge(i.toString(),n,(e,t)=>{"ok"===e&&v(n,(e,t)=>{var n=A(t);vn(r.onDisconnect_,I(i,e),n)}),es(0,s,e,t)}),t.promise}};class i{constructor(e,t,n,r){this._repo=e,this._path=t,this._queryParams=n,this._orderByCalled=r}get key(){return E(this._path)?null:vt(this._path)}get ref(){return new ws(this._repo,this._path)}get _queryIdentifier(){var e=pn(this._queryParams),e=Ee(e);return"{}"===e?"default":e}get _queryObject(){return pn(this._queryParams)}isEqual(e){var t,n,r;return(e=g(e))instanceof i&&(t=this._repo===e._repo,n=bt(this._path,e._path),r=this._queryIdentifier===e._queryIdentifier,t)&&n&&r}toJSON(){return this.toString()}toString(){return this._repo.toString()+(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 ms(e,t){if(!0===e._orderByCalled)throw new Error(t+": You can't combine multiple orderBy calls.")}function vs(e){let t=null,n=null;if(e.hasStart()&&(t=e.getIndexStartValue()),e.hasEnd()&&(n=e.getIndexEndValue()),e.getIndex()===xt){var r="Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().",i="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()!==qe)throw new Error(r);if("string"!=typeof t)throw new Error(i)}if(e.hasEnd()){if(e.getIndexEndName()!==We)throw new Error(r);if("string"!=typeof n)throw new Error(i)}}else if(e.getIndex()===x){if(null!=t&&!Ri(t)||null!=n&&!Ri(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(f(e.getIndex()instanceof Xt||e.getIndex()===en,"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 ys(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 ws extends i{constructor(e,t){super(e,t,new hn,!1)}get parent(){var e=wt(this._path);return null===e?null:new ws(this._repo,e)}get root(){let e=this;for(;null!==e.parent;)e=e.parent;return e}}let Cs=class fo{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){var t=new w(e),n=Is(this.ref,e);return new fo(this._node.getChild(t),n,x)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(n){return!this._node.isLeafNode()&&!!this._node.forEachChild(this._index,(e,t)=>n(new fo(t,Is(this.ref,e),x)))}hasChild(e){var t=new w(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 bs(e,t){return(e=g(e))._checkNotDeleted("ref"),void 0!==t?Is(e._root,t):e._root}function Ts(e,t){(e=g(e))._checkNotDeleted("refFromURL");var n=hs(t,e._repo.repoInfo_.nodeAdmin),r=(Ai("refFromURL",n),n.repoInfo);return e._repo.repoInfo_.isCustomHost()||r.host===e._repo.repoInfo_.host||Le("refFromURL: Host name does not match the current database: (found "+r.host+" but expected "+e._repo.repoInfo_.host+")"),bs(e,n.path.toString())}function Is(e,t){return(null===b((e=g(e))._path)?Ti:Di)("child","path",t),new ws(e._repo,I(e._path,t))}function Es(e,t){e=g(e),L("set",e._path),yi("set",t,e._path,!1);var n=new _;return Ki(e._repo,e._path,t,null,n.wrapCallback(()=>{})),n.promise}function Ss(e,t){wi("update",t,e._path);var i=new _;{var o=e._repo,a=e._path,l=(e=t,i.wrapCallback(()=>{}));Zi(o,"update",{path:a.toString(),value:e});let n=!0,r=Vi(o),s={};if(v(e,(e,t)=>{n=!1,s[e]=li(I(a,e),A(t),o.serverSyncTree_,r)}),n)u("update() called with empty data. Don't do anything."),es(0,l,"ok",void 0);else{let i=Yi(o);var h=Wr(o.serverSyncTree_,a,s,i);Li(o.eventQueue_,h),o.server_.merge(a.toString(),e,(e,t)=>{var n="ok"===e,n=(n||m("update at "+a+" failed: "+e),Br(o.serverSyncTree_,i,!n)),r=0<n.length?rs(o,a):a;M(o.eventQueue_,r,n),es(0,l,e,t)}),v(e,e=>{var t=as(o,I(a,e));rs(o,t)}),M(o.eventQueue_,a,[])}}return i.promise}function ks(t){t=g(t);var i,s,o,e=new fs(()=>{}),e=new Ns(e);return i=t._repo,s=t,o=e,(null!=(e=Qr(i.serverSyncTree_,s))?Promise.resolve(e):i.server_.get(s).then(e=>{var t,n=A(e).withIndex(s._queryParams.getIndex());zr(i.serverSyncTree_,s,o,!0);let r;return r=s._queryParams.loadsAllData()?Ur(i.serverSyncTree_,s._path,n):(t=$r(i.serverSyncTree_,s),Vr(i.serverSyncTree_,s._path,n,t)),M(i.eventQueue_,s._path,r),jr(i.serverSyncTree_,s,o,null,!0),n},e=>(Zi(i,"get for query "+a(s)+" failed: "+e),Promise.reject(new Error(e))))).then(e=>new Cs(e,new ws(t._repo,t._path),t._queryParams.getIndex()))}class Ns{constructor(e){this.callbackContext=e}respondsTo(e){return"value"===e}createEvent(e,t){var n=t._queryParams.getIndex();return new _s("value",this,new Cs(e.snapshotNode,new ws(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 ps(this,e,t):null}matches(e){return e instanceof Ns&&(!e.callbackContext||!this.callbackContext||e.callbackContext.matches(this.callbackContext))}hasAnyCallback(){return null!==this.callbackContext}}class Ps{constructor(e,t){this.eventType=e,this.callbackContext=t}respondsTo(e){var t="children_added"===e?"child_added":e;return this.eventType===("children_removed"===t?"child_removed":t)}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new ps(this,e,t):null}createEvent(e,t){f(null!=e.childName,"Child events should have a childName.");var n=Is(new ws(t._repo,t._path),e.childName),r=t._queryParams.getIndex();return new _s(e.type,this,new Cs(e.snapshotNode,n,r),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 Ps&&this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext))}hasAnyCallback(){return!!this.callbackContext}}function Rs(r,e,t,n,i){let s;if("object"==typeof n&&(s=void 0,i=n),"function"==typeof n&&(s=n),i&&i.onlyOnce){let n=t;var o=(e,t)=>{Ji(r._repo,r,a),n(e,t)};o.userCallback=t.userCallback,o.context=t.context,t=o}o=new fs(t,s||void 0);let a="value"===e?new Ns(o):new Ps(e,o);{n=r._repo,i=r,t=a;let e;e=".info"===b(i._path)?zr(n.infoSyncTree_,i,t):zr(n.serverSyncTree_,i,t),Mi(n.eventQueue_,i._path,e)}return()=>Ji(r._repo,r,a)}function xs(e,t,n,r){return Rs(e,"value",t,n,r)}function Ds(e,t,n,r){Rs(e,"child_added",t,n,r)}function As(e,t,n,r){Rs(e,"child_changed",t,n,r)}function Os(e,t,n,r){Rs(e,"child_moved",t,n,r)}function Ls(e,t,n,r){Rs(e,"child_removed",t,n,r)}function Ms(e,t,n){let r=null;var i=n?new fs(n):null;"value"===t?r=new Ns(i):t&&(r=new Ps(t,i)),Ji(e._repo,e,r)}class Fs{}class qs extends Fs{constructor(e,t){super(),this._value=e,this._key=t,this.type="endAt"}_apply(e){yi("endAt",this._value,e._path,!0);var t=un(e._queryParams,this._value,this._key);if(ys(t),vs(t),e._queryParams.hasEnd())throw new Error("endAt: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new i(e._repo,e._path,t,e._orderByCalled)}}class Ws extends Fs{constructor(e,t){super(),this._value=e,this._key=t,this.type="endBefore"}_apply(e){yi("endBefore",this._value,e._path,!1);var t=((e,t,n)=>{let r;return(r=e.index_===xt||n?un(e,t,n):un(e,t,qe)).endBeforeSet_=!0,r})(e._queryParams,this._value,this._key);if(ys(t),vs(t),e._queryParams.hasEnd())throw new Error("endBefore: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new i(e._repo,e._path,t,e._orderByCalled)}}class Bs extends Fs{constructor(e,t){super(),this._value=e,this._key=t,this.type="startAt"}_apply(e){yi("startAt",this._value,e._path,!0);var t=cn(e._queryParams,this._value,this._key);if(ys(t),vs(t),e._queryParams.hasStart())throw new Error("startAt: Starting point was already set (by another call to startAt, startBefore or equalTo).");return new i(e._repo,e._path,t,e._orderByCalled)}}class Us extends Fs{constructor(e,t){super(),this._value=e,this._key=t,this.type="startAfter"}_apply(e){yi("startAfter",this._value,e._path,!1);var t=((e,t,n)=>{let r;return(r=e.index_===xt||n?cn(e,t,n):cn(e,t,We)).startAfterSet_=!0,r})(e._queryParams,this._value,this._key);if(ys(t),vs(t),e._queryParams.hasStart())throw new Error("startAfter: Starting point was already set (by another call to startAt, startAfter, or equalTo).");return new i(e._repo,e._path,t,e._orderByCalled)}}class js extends Fs{constructor(e){super(),this._limit=e,this.type="limitToFirst"}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToFirst: Limit was already set (by another call to limitToFirst or limitToLast).");return new i(e._repo,e._path,(t=e._queryParams,n=this._limit,(r=t.copy()).limitSet_=!0,r.limit_=n,r.viewFrom_="l",r),e._orderByCalled);var t,n,r}}class Vs extends Fs{constructor(e){super(),this._limit=e,this.type="limitToLast"}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToLast: Limit was already set (by another call to limitToFirst or limitToLast).");return new i(e._repo,e._path,(t=e._queryParams,n=this._limit,(r=t.copy()).limitSet_=!0,r.limit_=n,r.viewFrom_="r",r),e._orderByCalled);var t,n,r}}class zs extends Fs{constructor(e){super(),this._path=e,this.type="orderByChild"}_apply(e){ms(e,"orderByChild");var t=new w(this._path);if(E(t))throw new Error("orderByChild: cannot pass in empty path. Use orderByValue() instead.");t=new Xt(t),t=dn(e._queryParams,t);return vs(t),new i(e._repo,e._path,t,!0)}}class Hs extends Fs{constructor(){super(...arguments),this.type="orderByKey"}_apply(e){ms(e,"orderByKey");var t=dn(e._queryParams,xt);return vs(t),new i(e._repo,e._path,t,!0)}}class Qs extends Fs{constructor(){super(...arguments),this.type="orderByPriority"}_apply(e){ms(e,"orderByPriority");var t=dn(e._queryParams,x);return vs(t),new i(e._repo,e._path,t,!0)}}class Ys extends Fs{constructor(){super(...arguments),this.type="orderByValue"}_apply(e){ms(e,"orderByValue");var t=dn(e._queryParams,en);return vs(t),new i(e._repo,e._path,t,!0)}}class Ks extends Fs{constructor(e,t){super(),this._value=e,this._key=t,this.type="equalTo"}_apply(e){if(yi("equalTo",this._value,e._path,!1),e._queryParams.hasStart())throw new Error("equalTo: Starting point was already set (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 qs(this._value,this._key)._apply(new Bs(this._value,this._key)._apply(e))}}function Gs(e,...t){let n=g(e);for(var r of t)n=r._apply(n);return n}e=ws,f(!Tr,"__referenceConstructor has already been defined"),Tr=e,e=ws,f(!Lr,"__referenceConstructor has already been defined"),Lr=e;let $s="FIREBASE_DATABASE_EMULATOR_HOST",Js={},Xs=!1;function Zs(e,t,n,r,i){let s=r||e.options.databaseURL,o=(void 0===s&&(e.options.projectId||Le("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),u("Using default host for project ",e.options.projectId),s=e.options.projectId+"-default-rtdb.firebaseio.com"),hs(s,i)),a=o.repoInfo,l,h=void 0;(h="undefined"!=typeof process&&process.env?process.env[$s]:h)?(l=!0,s=`http://${h}?ns=`+a.namespace,o=hs(s,i),a=o.repoInfo):l=!o.repoInfo.secure;var c=i&&l?new $e($e.OWNER):new Ge(e.name,e.options,t),c=(Ai("Invalid Firebase Database URL",o),E(o.path)||Le("Database URL must point to the root of a Firebase Database (not including a child path)."),((e,t,n,r)=>{let i=Js[t.name];var s;return i||(i={},Js[t.name]=i),(s=i[e.toURLString()])&&Le("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call."),s=new Bi(e,Xs,n,r),i[e.toURLString()]=s})(a,e,c,new Ke(e,n)));return new eo(c,e)}let eo=class{constructor(e,t){this._repoInternal=e,this.app=t,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(Ui(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new ws(this._repo,C())),this._rootInternal}_delete(){var e,t,n;return null!==this._rootInternal&&(e=this._repo,t=this.app.name,(n=Js[t])&&n[e.key]===e||Le(`Database ${t}(${e.repoInfo_}) has already been deleted.`),Xi(e),delete n[e.key],this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){null===this._rootInternal&&Le("Cannot call "+e+" on a deleted database.")}};function to(){ct.IS_TRANSPORT_INITIALIZED&&m("Transport has already been initialized. Please call this function before calling ref or setting up a listener")}function no(){to(),at.forceDisallow()}function ro(){to(),y.forceDisallow(),at.forceAllow()}function io(e,t,n,r={}){(e=g(e))._checkNotDeleted("useEmulator");var i,s=t+":"+n,o=e._repoInternal;if(e._instanceStarted){if(s===e._repoInternal.repoInfo_.host&&function e(t,n){if(t!==n){var r,i,s=Object.keys(t),o=Object.keys(n);for(r of s){if(!o.includes(r))return;var a=t[r],l=n[r];if(X(a)&&X(l)){if(!e(a,l))return}else if(a!==l)return}for(i of o)if(!s.includes(i))return}return 1}(r,o.repoInfo_.emulatorOptions))return;Le("connectDatabaseEmulator() cannot initialize or alter the emulator configuration after the database instance has started.")}let a=void 0;o.repoInfo_.nodeAdmin?(r.mockUserToken&&Le('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),a=new $e($e.OWNER)):r.mockUserToken&&(i="string"==typeof r.mockUserToken?r.mockUserToken:((e,t)=>{if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');var n=t||"demo-project",r=e.iat||0,i=e.sub||e.user_id;if(i)return n={iss:"https://securetoken.google.com/"+n,aud:n,iat:r,exp:r+3600,auth_time:r,sub:i,user_id:i,firebase:{sign_in_provider:"custom",identities:{}},...e},[V(JSON.stringify({alg:"none",type:"JWT"})),V(JSON.stringify(n)),""].join(".");throw new Error("mockUserToken must contain 'sub' or 'user_id' field!")})(r.mockUserToken,e.app.options.projectId),a=new $e(i)),ne(t)&&(async e=>(await fetch(e,{credentials:"include"})).ok)(t),n=o,e=s,t=r,r=a,i=e.lastIndexOf(":"),i=ne(e.substring(0,i)),n.repoInfo_=new et(e,i,n.repoInfo_.namespace,n.repoInfo_.webSocketOnly,n.repoInfo_.nodeAdmin,n.repoInfo_.persistenceKey,n.repoInfo_.includeNamespaceInQueryParams,!0,t),r&&(n.authTokenProvider_=r)}function so(e){(e=g(e))._checkNotDeleted("goOnline"),(e=e._repo).persistentConnection_&&e.persistentConnection_.resume(qi)}function oo(e,t){Oe(e,t)}let ao={".sv":"timestamp"};let lo=class{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}};function ho(i,e,t){if(i=g(i),L("Reference.transaction",i._path),".length"===i.key||".keys"===i.key)throw"Reference.transaction failed: "+i.key+" is a read-only object.";var n=t?.applyLocally??!0;let s=new _;var r=xs(i,()=>{}),t=i._repo,o=i._path,a=(e,t,n)=>{var r;e?s.reject(e):(r=new Cs(n,new ws(i._repo,i._path),x),s.resolve(new lo(t,r)))},l=r,h=n;Zi(t,"transaction on "+o);var c,r={path:o,update:e,onComplete:a,status:null,order:Re(),applyLocally:h,retryCount:0,unwatcher:l,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},n=ts(t,o,void 0);if(r.currentInputSnapshot=n,void 0===(c=r.update(n.val())))r.unwatcher(),r.currentOutputSnapshotRaw=null,r.currentOutputSnapshotResolved=null,r.onComplete&&r.onComplete(null,!1,r.currentInputSnapshot);else{xi("transaction failed: Data returned ",c,r.path),r.status=0;var u=di(t.transactionQueueTree_,o),d=_i(u)||[];d.push(r),pi(u,d);let e;"object"==typeof c&&null!==c&&p(c,".priority")?(e=G(c,".priority"),f(Ri(e),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.")):(u=Hr(t.serverSyncTree_,o)||D.EMPTY_NODE,e=u.getPriority().val());d=Vi(t),u=A(c,e),c=hi(u,n,d),n=(r.currentOutputSnapshotRaw=u,r.currentOutputSnapshotResolved=c,r.currentWriteId=Yi(t),qr(t.serverSyncTree_,o,c,r.currentWriteId,r.applyLocally));M(t.eventQueue_,o,n),ns(t,t.transactionQueueTree_)}return s.promise}kt.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)},kt.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)},fe(wo.SDK_VERSION),wo._registerComponent(new re("database",(e,{instanceIdentifier:t})=>Zs(e.getProvider("app").getImmediate(),e.getProvider("auth-internal"),e.getProvider("app-check-internal"),t),"PUBLIC").setMultipleInstances(!0)),wo.registerVersion(de,_e,ye),wo.registerVersion(de,_e,"esm2020");function co(e){var t="FIREBASE WARNING: "+e;uo.warn(t)}let uo=new ue("@firebase/database-compat");class _o{constructor(e){this._delegate=e}cancel(t){l("OnDisconnect.cancel",0,1,arguments.length),c("OnDisconnect.cancel","onComplete",t,!0);var e=this._delegate.cancel();return t&&e.then(()=>t(null),e=>t(e)),e}remove(t){l("OnDisconnect.remove",0,1,arguments.length),c("OnDisconnect.remove","onComplete",t,!0);var e=this._delegate.remove();return t&&e.then(()=>t(null),e=>t(e)),e}set(e,t){l("OnDisconnect.set",1,2,arguments.length),c("OnDisconnect.set","onComplete",t,!0);var n=this._delegate.set(e);return t&&n.then(()=>t(null),e=>t(e)),n}setWithPriority(e,t,n){l("OnDisconnect.setWithPriority",2,3,arguments.length),c("OnDisconnect.setWithPriority","onComplete",n,!0);var r=this._delegate.setWithPriority(e,t);return n&&r.then(()=>n(null),e=>n(e)),r}update(t,n){if(l("OnDisconnect.update",1,2,arguments.length),Array.isArray(t)){var r={};for(let e=0;e<t.length;++e)r[""+e]=t[e];t=r,co("Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.")}c("OnDisconnect.update","onComplete",n,!0);var e=this._delegate.update(t);return n&&e.then(()=>n(null),e=>n(e)),e}}class po{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return l("TransactionResult.toJSON",0,1,arguments.length),{committed:this.committed,snapshot:this.snapshot.toJSON()}}}class fo{constructor(e,t){this._database=e,this._delegate=t}val(){return l("DataSnapshot.val",0,0,arguments.length),this._delegate.val()}exportVal(){return l("DataSnapshot.exportVal",0,0,arguments.length),this._delegate.exportVal()}toJSON(){return l("DataSnapshot.toJSON",0,1,arguments.length),this._delegate.toJSON()}exists(){return l("DataSnapshot.exists",0,0,arguments.length),this._delegate.exists()}child(e){return l("DataSnapshot.child",0,1,arguments.length),e=String(e),Di("DataSnapshot.child","path",e),new fo(this._database,this._delegate.child(e))}hasChild(e){return l("DataSnapshot.hasChild",1,1,arguments.length),Di("DataSnapshot.hasChild","path",e),this._delegate.hasChild(e)}getPriority(){return l("DataSnapshot.getPriority",0,0,arguments.length),this._delegate.priority}forEach(t){return l("DataSnapshot.forEach",1,1,arguments.length),c("DataSnapshot.forEach","action",t,!1),this._delegate.forEach(e=>t(new fo(this._database,e)))}hasChildren(){return l("DataSnapshot.hasChildren",0,0,arguments.length),this._delegate.hasChildren()}get key(){return this._delegate.key}numChildren(){return l("DataSnapshot.numChildren",0,0,arguments.length),this._delegate.size}getRef(){return l("DataSnapshot.ref",0,0,arguments.length),new o(this._database,this._delegate.ref)}get ref(){return this.getRef()}}class F{constructor(e,t){this.database=e,this._delegate=t}on(e,n,t,r){l("Query.on",2,4,arguments.length),c("Query.on","callback",n,!1);let i=F.getCancelAndContextArgs_("Query.on",t,r);var s=(e,t)=>{n.call(i.context,new fo(this.database,e),t)},o=(s.userCallback=n,s.context=i.context,i.cancel?.bind(i.context));switch(e){case"value":return xs(this._delegate,s,o),n;case"child_added":return Ds(this._delegate,s,o),n;case"child_removed":return Ls(this._delegate,s,o),n;case"child_changed":return As(this._delegate,s,o),n;case"child_moved":return Os(this._delegate,s,o),n;default:throw new Error(h("Query.on","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}}off(e,t,n){l("Query.off",0,3,arguments.length);var r,i="Query.off",s=e;if(void 0!==s)switch(s){case"value":case"child_added":case"child_removed":case"child_changed":case"child_moved":break;default:throw new Error(h(i,"eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}c("Query.off","callback",t,!0),ee("Query.off","context",n),t?((r=()=>{}).userCallback=t,r.context=n,Ms(this._delegate,e,r)):Ms(this._delegate,e)}get(){return ks(this._delegate).then(e=>new fo(this.database,e))}once(e,r,t,n){l("Query.once",1,4,arguments.length),c("Query.once","callback",r,!0);let i=F.getCancelAndContextArgs_("Query.once",t,n),s=new _;var o=(e,t)=>{var n=new fo(this.database,e);r&&r.call(i.context,n,t),s.resolve(n)},a=(o.userCallback=r,o.context=i.context,e=>{i.cancel&&i.cancel.call(i.context,e),s.reject(e)});switch(e){case"value":xs(this._delegate,o,a,{onlyOnce:!0});break;case"child_added":Ds(this._delegate,o,a,{onlyOnce:!0});break;case"child_removed":Ls(this._delegate,o,a,{onlyOnce:!0});break;case"child_changed":As(this._delegate,o,a,{onlyOnce:!0});break;case"child_moved":Os(this._delegate,o,a,{onlyOnce:!0});break;default:throw new Error(h("Query.once","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}return s.promise}limitToFirst(e){return l("Query.limitToFirst",1,1,arguments.length),new F(this.database,Gs(this._delegate,(e=>{if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToFirst: First argument must be a positive integer.");return new js(e)})(e)))}limitToLast(e){return l("Query.limitToLast",1,1,arguments.length),new F(this.database,Gs(this._delegate,(e=>{if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToLast: First argument must be a positive integer.");return new Vs(e)})(e)))}orderByChild(e){return l("Query.orderByChild",1,1,arguments.length),new F(this.database,Gs(this._delegate,(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 Di("orderByChild","path",e),new zs(e)})(e)))}orderByKey(){return l("Query.orderByKey",0,0,arguments.length),new F(this.database,Gs(this._delegate,new Hs))}orderByPriority(){return l("Query.orderByPriority",0,0,arguments.length),new F(this.database,Gs(this._delegate,new Qs))}orderByValue(){return l("Query.orderByValue",0,0,arguments.length),new F(this.database,Gs(this._delegate,new Ys))}startAt(e=null,t){return l("Query.startAt",0,2,arguments.length),new F(this.database,Gs(this._delegate,([e=null,t]=[e,t],bi("startAt","key",t),new Bs(e,t))))}startAfter(e=null,t){return l("Query.startAfter",0,2,arguments.length),new F(this.database,Gs(this._delegate,(e=e,t=t,bi("startAfter","key",t),new Us(e,t))))}endAt(e=null,t){return l("Query.endAt",0,2,arguments.length),new F(this.database,Gs(this._delegate,(e=e,t=t,bi("endAt","key",t),new qs(e,t))))}endBefore(e=null,t){return l("Query.endBefore",0,2,arguments.length),new F(this.database,Gs(this._delegate,(e=e,t=t,bi("endBefore","key",t),new Ws(e,t))))}equalTo(e,t){return l("Query.equalTo",1,2,arguments.length),new F(this.database,Gs(this._delegate,(e=e,t=t,bi("equalTo","key",t),new Ks(e,t))))}toString(){return l("Query.toString",0,0,arguments.length),this._delegate.toString()}toJSON(){return l("Query.toJSON",0,1,arguments.length),this._delegate.toJSON()}isEqual(e){if(l("Query.isEqual",1,1,arguments.length),e instanceof F)return this._delegate.isEqual(e._delegate);throw new Error("Query.isEqual failed: First argument must be an instance of firebase.database.Query.")}static getCancelAndContextArgs_(e,t,n){var r={cancel:void 0,context:void 0};if(t&&n)r.cancel=t,c(e,"cancel",r.cancel,!0),r.context=n,ee(e,"context",r.context);else if(t)if("object"==typeof t&&null!==t)r.context=t;else{if("function"!=typeof t)throw new Error(h(e,"cancelOrContext")+" must either be a cancel callback or a context object.");r.cancel=t}return r}get ref(){return new o(this.database,new ws(this._delegate._repo,this._delegate._path))}}class o extends F{constructor(e,t){super(e,new i(t._repo,t._path,new hn,!1)),this.database=e,this._delegate=t}getKey(){return l("Reference.key",0,0,arguments.length),this._delegate.key}child(e){return l("Reference.child",1,1,arguments.length),"number"==typeof e&&(e=String(e)),new o(this.database,Is(this._delegate,e))}getParent(){l("Reference.parent",0,0,arguments.length);var e=this._delegate.parent;return e?new o(this.database,e):null}getRoot(){return l("Reference.root",0,0,arguments.length),new o(this.database,this._delegate.root)}set(e,t){l("Reference.set",1,2,arguments.length),c("Reference.set","onComplete",t,!0);var n=Es(this._delegate,e);return t&&n.then(()=>t(null),e=>t(e)),n}update(t,n){if(l("Reference.update",1,2,arguments.length),Array.isArray(t)){var r={};for(let e=0;e<t.length;++e)r[""+e]=t[e];t=r,co("Passing an Array to Firebase.update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.")}L("Reference.update",this._delegate._path),c("Reference.update","onComplete",n,!0);var e=Ss(this._delegate,t);return n&&e.then(()=>n(null),e=>n(e)),e}setWithPriority(e,t,n){l("Reference.setWithPriority",2,3,arguments.length),c("Reference.setWithPriority","onComplete",n,!0);var r=((e,t,n)=>{if(L("setWithPriority",e._path),yi("setWithPriority",t,e._path,!1),Ci("setWithPriority",n),".length"===e.key||".keys"===e.key)throw"setWithPriority failed: "+e.key+" is a read-only object.";var r=new _;return Ki(e._repo,e._path,t,n,r.wrapCallback(()=>{})),r.promise})(this._delegate,e,t);return n&&r.then(()=>n(null),e=>n(e)),r}remove(t){l("Reference.remove",0,1,arguments.length),c("Reference.remove","onComplete",t,!0);e=this._delegate,L("remove",e._path);var e,n=Es(e,null);return t&&n.then(()=>t(null),e=>t(e)),n}transaction(e,t,n){l("Reference.transaction",1,3,arguments.length),c("Reference.transaction","transactionUpdate",e,!1),c("Reference.transaction","onComplete",t,!0);var r="Reference.transaction",i="applyLocally",s=n;if(void 0!==s&&"boolean"!=typeof s)throw new Error(h(r,i)+"must be a boolean.");var o=ho(this._delegate,e,{applyLocally:n}).then(e=>new po(e.committed,new fo(this.database,e.snapshot)));return t&&o.then(e=>t(null,e.committed,e.snapshot),e=>t(e,!1,null)),o}setPriority(e,t){l("Reference.setPriority",1,2,arguments.length),c("Reference.setPriority","onComplete",t,!0);n=this._delegate,e=e,n=g(n),L("setPriority",n._path),Ci("setPriority",e),r=new _,Ki(n._repo,I(n._path,".priority"),e,null,r.wrapCallback(()=>{}));var n,r=r.promise;return t&&r.then(()=>t(null),e=>t(e)),r}push(e,t){l("Reference.push",0,2,arguments.length),c("Reference.push","onComplete",t,!0);var n=((e,t)=>{e=g(e),L("push",e._path),yi("push",t,e._path,!0);var n=ji(e._repo),n=ds(n),r=Is(e,n);let i=Is(e,n),s;return s=null!=t?Es(i,t).then(()=>i):Promise.resolve(i),r.then=s.then.bind(s),r.catch=s.then.bind(s,void 0),r})(this._delegate,e),r=n.then(e=>new o(this.database,e)),n=(t&&r.then(()=>t(null),e=>t(e)),new o(this.database,n));return n.then=r.then.bind(r),n.catch=r.catch.bind(r,void 0),n}onDisconnect(){return L("Reference.onDisconnect",this._delegate._path),new _o(new gs(this._delegate._repo,this._delegate._path))}get key(){return this.getKey()}get parent(){return this.getParent()}get root(){return this.getRoot()}}class go{constructor(e,t){this._delegate=e,this.app=t,this.INTERNAL={delete:()=>this._delegate._delete(),forceWebSockets:no,forceLongPolling:ro}}useEmulator(e,t,n={}){io(this._delegate,e,t,n)}ref(e){var t;return l("database.ref",0,1,arguments.length),e instanceof o?(t=Ts(this._delegate,e.toString()),new o(this,t)):(t=bs(this._delegate,e),new o(this,t))}refFromURL(e){l("database.refFromURL",1,1,arguments.length);var t=Ts(this._delegate,e);return new o(this,t)}goOffline(){var e;l("database.goOffline",0,0,arguments.length),(e=g(e=this._delegate))._checkNotDeleted("goOffline"),Xi(e._repo)}goOnline(){return l("database.goOnline",0,0,arguments.length),so(this._delegate)}}go.ServerValue={TIMESTAMP:ao,increment:e=>({".sv":{increment:e}})};var e,mo=Object.freeze({__proto__:null,initStandalone:function({app:e,url:t,version:n,customAuthImpl:r,customAppCheckImpl:i,namespace:s,nodeAdmin:o=!1}){fe(n);var a=new oe("database-standalone"),l=new se("auth-internal",a);l.setComponent(new re("auth-internal",()=>r,"PRIVATE"));let h=void 0;return i&&(h=new se("app-check-internal",a)).setComponent(new re("app-check-internal",()=>i,"PRIVATE")),{instance:new go(Zs(e,l,h,t,o),e),namespace:s}}});let vo=go.ServerValue;(e=yo).INTERNAL.registerComponent(new re("database-compat",(e,{instanceIdentifier:t})=>{var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("database").getImmediate({identifier:t});return new go(r,n)},"PUBLIC").setServiceProps({Reference:o,Query:F,Database:go,DataSnapshot:fo,enableLogging:oo,INTERNAL:mo,ServerValue:vo}).setMultipleInstances(!0)),e.registerVersion("@firebase/database-compat","2.1.7-eap-sql.b903ef716")}).apply(this,arguments)}catch(e){throw console.error(e),new Error("Cannot instantiate firebase-database-compat.js - be sure to load firebase-app.js first.")}});
2
2
  //# sourceMappingURL=firebase-database-compat.js.map