1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[5810],{96730:function(e,t,n){let i,r,s,o,a,l,h,c,u,d,p,f,_,m;n.d(t,{F:function(){return aL},G:function(){return o_},a:function(){return ax},b:function(){return oN},c:function(){return rQ},d:function(){return aD},e:function(){return oD},f:function(){return oF},g:function(){return rX},h:function(){return o8},i:function(){return oP},r:function(){return rJ},s:function(){return oA},u:function(){return oO}});var g,v,y,w,I,C=n(20879),b=n(40257);let T=function(e,t){if(!e)throw E(t)},E=function(e){return Error("Firebase Database (${JSCORE_VERSION}) INTERNAL ASSERT FAILED: "+e)},k=function(e){let t=[],n=0;for(let i=0;i<e.length;i++){let r=e.charCodeAt(i);r<128?t[n++]=r:(r<2048?t[n++]=r>>6|192:((64512&r)==55296&&i+1<e.length&&(64512&e.charCodeAt(i+1))==56320?(r=65536+((1023&r)<<10)+(1023&e.charCodeAt(++i)),t[n++]=r>>18|240,t[n++]=r>>12&63|128):t[n++]=r>>12|224,t[n++]=r>>6&63|128),t[n++]=63&r|128)}return t},S=function(e){let t=[],n=0,i=0;for(;n<e.length;){let r=e[n++];if(r<128)t[i++]=String.fromCharCode(r);else if(r>191&&r<224){let s=e[n++];t[i++]=String.fromCharCode((31&r)<<6|63&s)}else if(r>239&&r<365){let s=((7&r)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536;t[i++]=String.fromCharCode(55296+(s>>10)),t[i++]=String.fromCharCode(56320+(1023&s))}else{let s=e[n++],o=e[n++];t[i++]=String.fromCharCode((15&r)<<12|(63&s)<<6|63&o)}}return t.join("")},P={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(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();let n=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,i=[];for(let t=0;t<e.length;t+=3){let r=e[t],s=t+1<e.length,o=s?e[t+1]:0,a=t+2<e.length,l=a?e[t+2]:0,h=r>>2,c=(3&r)<<4|o>>4,u=(15&o)<<2|l>>6,d=63&l;a||(d=64,s||(u=64)),i.push(n[h],n[c],n[u],n[d])}return i.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(k(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):S(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();let n=t?this.charToByteMapWebSafe_:this.charToByteMap_,i=[];for(let t=0;t<e.length;){let r=n[e.charAt(t++)],s=t<e.length?n[e.charAt(t)]:0,o=++t<e.length?n[e.charAt(t)]:64,a=++t<e.length?n[e.charAt(t)]:64;if(++t,null==r||null==s||null==o||null==a)throw new N;let l=r<<2|s>>4;if(i.push(l),64!==o){let e=s<<4&240|o>>2;if(i.push(e),64!==a){let e=o<<6&192|a;i.push(e)}}}return i},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,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class N extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}let R=function(e){let t=k(e);return P.encodeByteArray(t,!0)},O=function(e){return R(e).replace(/\./g,"")},A=function(e){try{return P.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null},D=()=>(function(){if("u">typeof self)return self;if("u">typeof window)return window;if("u">typeof global)return global;throw Error("Unable to locate global object.")})().__FIREBASE_DEFAULTS__,x=()=>{if(typeof b>"u"||typeof b.env>"u")return;let e=b.env.__FIREBASE_DEFAULTS__;if(e)return JSON.parse(e)},L=()=>{let e;if(typeof document>"u")return;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch{return}let t=e&&A(e[1]);return t&&JSON.parse(t)},M=()=>{try{return D()||x()||L()}catch(e){console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);return}},F=e=>{var t,n;return null===(n=null===(t=M())||void 0===t?void 0:t.emulatorHosts)||void 0===n?void 0:n[e]},U=e=>{let t=F(e);if(!t)return;let n=t.lastIndexOf(":");if(n<=0||n+1===t.length)throw Error(`Invalid host ${t} with no separate hostname and port!`);let i=parseInt(t.substring(n+1),10);return"["===t[0]?[t.substring(1,n-1),i]:[t.substring(0,n),i]},q=()=>{var e;return null===(e=M())||void 0===e?void 0:e.config},j=e=>{var t;return null===(t=M())||void 0===t?void 0:t[`_${e}`]};class W{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,t)=>
1{this.resolve=e,this.reject=t})}wrapCallback(e){return(t,n)=>{t?this.reject(t):this.resolve(n),"function"==typeof e&&(this.promise.catch(()=>{}),1===e.length?e(t):e(t,n))}}}function V(){return"u">typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function H(){return"u">typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(V())}function B(){return"object"==typeof navigator&&"ReactNative"===navigator.product}class z extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,z.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,$.prototype.create)}}class ${constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){let n=t[0]||{},i=`${this.service}/${e}`,r=this.errors[e],s=r?r.replace(K,(e,t)=>{let i=n[t];return null!=i?String(i):`<${t}?>`}):"Error",o=`${this.serviceName}: ${s} (${i}).`;return new z(i,o,n)}}let K=/\{\$([^}]+)}/g;function G(e){return JSON.parse(e)}function Y(e){return JSON.stringify(e)}let J=function(e){let t={},n={},i={},r="";try{let s=e.split(".");t=G(A(s[0])||""),n=G(A(s[1])||""),r=s[2],i=n.d||{},delete n.d}catch{}return{header:t,claims:n,data:i,signature:r}},Q=function(e){let t=J(e).claims;return!!t&&"object"==typeof t&&t.hasOwnProperty("iat")},X=function(e){let t=J(e).claims;return"object"==typeof t&&!0===t.admin};function Z(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ee(e,t){if(Object.prototype.hasOwnProperty.call(e,t))return e[t]}function et(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function en(e,t,n){let i={};for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(i[r]=t.call(n,e[r],r,e));return i}function ei(e,t){if(e===t)return!0;let n=Object.keys(e),i=Object.keys(t);for(let r of n){if(!i.includes(r))return!1;let n=e[r],s=t[r];if(er(n)&&er(s)){if(!ei(n,s))return!1}else if(n!==s)return!1}for(let e of i)if(!n.includes(e))return!1;return!0}function er(e){return null!==e&&"object"==typeof e}function es(e){let t=[];for(let[n,i]of Object.entries(e))Array.isArray(i)?i.forEach(e=>{t.push(encodeURIComponent(n)+"="+encodeURIComponent(e))}):t.push(encodeURIComponent(n)+"="+encodeURIComponent(i));return t.length?"&"+t.join("&"):""}function eo(e){let t={};return e.replace(/^\?/,"").split("&").forEach(e=>{if(e){let[n,i]=e.split("=");
1t[decodeURIComponent(n)]=decodeURIComponent(i)}}),t}function ea(e){let t=e.indexOf("?");if(!t)return"";let n=e.indexOf("#",t);return e.substring(t,n>0?n:void 0)}class el{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_(e,t){t||(t=0);let n=this.W_;if("string"==typeof e)for(let i=0;i<16;i++)n[i]=e.charCodeAt(t)<<24|e.charCodeAt(t+1)<<16|e.charCodeAt(t+2)<<8|e.charCodeAt(t+3),t+=4;else for(let i=0;i<16;i++)n[i]=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3],t+=4;for(let e=16;e<80;e++){let t=n[e-3]^n[e-8]^n[e-14]^n[e-16];n[e]=(t<<1|t>>>31)&4294967295}let i=this.chain_[0],r=this.chain_[1],s=this.chain_[2],o=this.chain_[3],a=this.chain_[4],l,h;for(let e=0;e<80;e++){e<40?e<20?(l=o^r&(s^o),h=1518500249):(l=r^s^o,h=1859775393):e<60?(l=r&s|o&(r|s),h=2400959708):(l=r^s^o,h=3395469782);let t=(i<<5|i>>>27)+l+a+h+n[e]&4294967295;a=o,o=s,s=(r<<30|r>>>2)&4294967295,r=i,i=t}this.chain_[0]=this.chain_[0]+i&4294967295,this.chain_[1]=this.chain_[1]+r&4294967295,this.chain_[2]=this.chain_[2]+s&4294967295,this.chain_[3]=this.chain_[3]+o&4294967295,this.chain_[4]=this.chain_[4]+a&4294967295}update(e,t){if(null==e)return;void 0===t&&(t=e.length);let n=t-this.blockSize,i=0,r=this.buf_,s=this.inbuf_;for(;i<t;){if(0===s)for(;i<=n;)this.compress_(e,i),i+=this.blockSize;if("string"==typeof e){for(;i<t;)if(r[s]=e.charCodeAt(i),++s,++i,s===this.blockSize){this.compress_(r),s=0;break}}else for(;i<t;)if(r[s]=e[i],++s,++i,s===this.blockSize){this.compress_(r),s=0;break}}this.inbuf_=s,this.total_+=t}digest(){let e=[],t=8*this.total_;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(let e=this.blockSize-1;e>=56;e--)this.buf_[e]=255&t,t/=256;this.compress_(this.buf_);let n=0;for(let t=0;t<5;t++)for(let i=24;i>=0;i-=8)e[n]=this.chain_[t]>>i&255,++n;return e}}class eh{constructor(e,t){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=t,this.task.then(()=>{e(this)}).catch(e=>{this.error(e)})}next(e){this.forEachObserver(t=>{t.next(e)})}error(e){this.forEachObserver(t=>{t.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,n){let i;if(void 0===e&&void 0===t&&void 0===n)throw Error("Missing Observer.");void 0===(i=!function(e,t){if("object"!=typeof e||null===e)return!1;for(let n of t)if(n in e&&"function"==typeof e[n])return!0;return!1}(e,["next","error","complete"])?{next:e,error:t,complete:n}:e).next&&(i.next=ec),void 0===i.error&&(i.error=ec),void 0===i.complete&&(i.complete=ec);let r=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then(()=>{try{this.finalError?i.error(this.finalError):i.complete()}catch{}}),this.observers.push(i),r}unsubscribeOne(e){void 0===this.observers||void 0===this.observers[e]||(delete this.observers[e],this.observerCount-=1,0===this.observerCount&&void 0!==this.onNoObservers&&this.onNoObservers(this))}forEachObserver(e){if(!this.finalized)for(let t=0;t<this.observers.length;t++)this.sendOne(t,e)}sendOne(e,t){this.task.then(()=>{if(void 0!==this.observers&&void 0!==this.observers[e])try{t(this.observers[e])}catch(e){"u">typeof console&&console.error&&console.error(e)}})}close(e){this.finalized||(this.finalized=!0,void 0!==e&&(this.finalError=e),this.task.then(()=>{this.observers=void 0,this.onNoObservers=void 0}))}}function ec(){}function eu(e,t){return`${e} failed: ${t} argument `}let ed=function(e){let t=[],n=0;for(let i=0;i<e.length;i++){let r=e.charCodeAt(i);if(r>=55296&&r<=56319){let t=r-55296;T(++i<e.length,"Surrogate pair missing trail surrogate."),r=65536+(t<<10)+(e.charCodeAt(i)-56320)}r<128?t[n++]=r:(r<2048?t[n++]=r>>6|192:(r<65536?t[n++]=r>>12|224:(t[n++]=r>>18|240,t[n++]=r>>12&63|128),t[n++]=r>>6&63|128),t[n++]=63&r|128)}return t},ep=function(e){let t=0;for(let n=0;n<e.length;n++){let i=e.charCodeAt(n);i<128?t++:i<2048?t+=2:i>=55296&&i<=56319?(t+=4,n++):t+=3}return t};function ef(e){return e&&e._delegate?e._delegate:e}class e_{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 em="[DEFAULT]";class eg{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){let t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){let e=new W;if(this.instancesDeferred.set(t,e),this.isInitialized(t)||this.shouldAutoInitialize())try{let n=this.getOrInitializeService({instanceIdentifier:t});n&&e.resolve(n)}catch{}}return this.instancesDeferred.get(t).promise}getImmediate(e){var t;let n=this.normalizeInstanceIdentifier(null==e?void 0:e.identifier),i=null!==(t=null==e?void 0:e.optional)&&void 0!==t&&t;if(this.isInitialized(n)||this.shouldAutoInitialize())try{return this.getOrInitializeService({instanceIdentifier:n})}catch(e){if(i)return null;throw e}else{if(i)return null;throw Error(`Service ${this.name} is not available`)}}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:em})}catch{}for(let[e,t]of this.instancesDeferred.entries()){let n=this.normalizeInstanceIdentifier(e);try{let e=this.getOrInitializeService({instanceIdentifier:n});t.resolve(e)}catch{}}}}clearInstance(e=em){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){let 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=em){return this.instances.has(e)}getOptions(e=em){return this.instancesOptions.get(e)||{}}initialize(e={}){let{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`);let i=this.getOrInitializeService({instanceIdentifier:n,options:t});for(let[e,t]of this.instancesDeferred.entries())n===this.normalizeInstanceIdentifier(e)&&t.resolve(i);return i}onInit(e,t){var n;let i=this.normalizeInstanceIdentifier(t),r=null!==(n=this.onInitCallbacks.get(i))&&void 0!==n?n:new Set;r.add(e),this.onInitCallbacks.set(i,r);let s=this.instances.get(i);return s&&e(s,i),()=>{r.delete(e)}}invokeOnInitCallbacks(e,t){let n=this.onInitCallbacks.get(t);if(n)for(let i of n)try{i(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:e===em?void 0:e,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{}return n||null}normalizeInstanceIdentifier(e=em){return this.component?this.component.multipleInstances?e:em:e}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class ev{constructor(e){this.name=e,this.providers=new Map}addComponent(e){let t=this.getProvider(e.name);if(t.isComponentSet())throw 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){if(this.providers.has(e))return this.providers.get(e);let t=new eg(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}}(g=w||(w={}))[g.DEBUG=0]="DEBUG",g[g.VERBOSE=1]="VERBOSE",g[g.INFO=2]="INFO",g[g.WARN=3]="WARN",g[g.ERROR=4]="ERROR",g[g.SILENT=5]="SILENT";let ey={debug:w.DEBUG,verbose:w.VERBOSE,info:w.INFO,warn:w.WARN,error:w.ERROR,silent:w.SILENT},ew=w.INFO,eI={[w.DEBUG]:"log",[w.VERBOSE]:"log",[w.INFO]:"info",[w.WARN]:"warn",[w.ERROR]:"error"},eC=(e,t,...n)=>{if(t<e.logLevel)return;let i=new Date().toISOString(),r=eI[t];if(r)console[r](`[${i}] ${e.name}:`,...n);
1else throw Error(`Attempted to log a message with an invalid logType (value: ${t})`)};class eb{constructor(e){this.name=e,this._logLevel=ew,this._logHandler=eC,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in w))throw TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?ey[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw 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,w.DEBUG,...e),this._logHandler(this,w.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,w.VERBOSE,...e),this._logHandler(this,w.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,w.INFO,...e),this._logHandler(this,w.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,w.WARN,...e),this._logHandler(this,w.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,w.ERROR,...e),this._logHandler(this,w.ERROR,...e)}}let eT=(e,t)=>t.some(t=>e instanceof t),eE=new WeakMap,ek=new WeakMap,eS=new WeakMap,eP=new WeakMap,eN=new WeakMap,eR={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return ek.get(e);if("objectStoreNames"===t)return e.objectStoreNames||eS.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return eO(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function eO(e){if(e instanceof IDBRequest)return function(e){let t=new Promise((t,n)=>{let i=()=>{e.removeEventListener("success",r),e.removeEventListener("error",s)},r=()=>{t(eO(e.result)),i()},s=()=>{n(e.error),i()};e.addEventListener("success",r),e.addEventListener("error",s)});return t.then(t=>{t instanceof IDBCursor&&eE.set(t,e)}).catch(()=>{}),eN.set(t,e),t}(e);if(eP.has(e))return eP.get(e);let t="function"==typeof e?e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(r||(r=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(eA(this),t),eO(eE.get(this))}:function(...t){return eO(e.apply(eA(this),t))}:function(t,...n){let i=e.call(eA(this),t,...n);return eS.set(i,t.sort?t.sort():[t]),eO(i)}:(e instanceof IDBTransaction&&function(e){if(ek.has(e))return;let t=new Promise((t,n)=>{let i=()=>{e.removeEventListener("complete",r),e.removeEventListener("error",s),e.removeEventListener("abort",s)},r=()=>{t(),i()},s=()=>{n(e.error||new DOMException("AbortError","AbortError")),i()};e.addEventListener("complete",r),e.addEventListener("error",s),e.addEventListener("abort",s)});ek.set(e,t)}(e),eT(e,i||(i=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,eR):e);return t!==e&&(eP.set(e,t),eN.set(t,e)),t}let eA=e=>eN.get(e),eD=["get","getKey","getAll","getAllKeys","count"],ex=["put","add","delete","clear"],eL=new Map;function eM(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&"string"==typeof t))return;if(eL.get(t))return eL.get(t);let n=t.replace(/FromIndex$/,""),i=t!==n,r=ex.includes(n);if(!(n in(i?IDBIndex:IDBObjectStore).prototype)||!(r||eD.includes(n)))return;let s=async function(e,...t){let s=this.transaction(e,r?"readwrite":"readonly"),o=s.store;return i&&(o=o.index(t.shift())),(await Promise.all([o[n](...t),r&&s.done]))[0]};return eL.set(t,s),s}eR={...m=eR,get:(e,t,n)=>eM(e,t)||m.get(e,t,n),has:(e,t)=>!!eM(e,t)||m.has(e,t)};class eF{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(e=>{if(!function(e){let t=e.getComponent();return(null==t?void 0:t.type)==="VERSION"}(e))return null;{let t=e.getImmediate();return`${t.library}/${t.version}`}}).filter(e=>e).join(" ")}}let eU="@firebase/app",eq="0.10.13",ej=new eb("@firebase/app"),eW="[DEFAULT]",eV={[eU]:"fire-core","@firebase/app-compat":"fire-core-compat","@firebase/analytics":"fire-analytics","@firebase/analytics-compat":"fire-analytics-compat","@firebase/app-check":"fire-app-check","@firebase/app-check-compat":"fire-app-check-compat","@firebase/auth":"fire-auth","@firebase/auth-compat":"fire-auth-compat","@firebase/database":"fire-rtdb","@firebase/data-connect":"fire-data-connect","@firebase/database-compat":"fire-rtdb-compat","@firebase/functions":"fire-fn","@firebase/functions-compat":"fire-fn-compat","@firebase/installations":"fire-iid","@firebase/installations-compat":"fire-iid-compat","@firebase/messaging":"fire-fcm","@firebase/messaging-compat":"fire-fcm-compat","@firebase/performance":"fire-perf","@firebase/performance-compat":"fire-perf-compat","@firebase/remote-config":"fire-rc","@firebase/remote-config-compat":"fire-rc-compat","@firebase/storage":"fire-gcs","@firebase/storage-compat":"fire-gcs-compat","@firebase/firestore":"fire-fst","@firebase/firestore-compat":"fire-fst-compat","@firebase/vertexai-preview":"fire-vertex","fire-js":"fire-js",firebase:"fire-js-all"},eH=new Map,eB=new Map,ez=new Map;function e$(e,t){try{e.container.addComponent(t)}catch(n){ej.debug(`Component ${t.name} failed to register with FirebaseApp ${e.name}`,n)}}function eK(e){let t=e.name;if(ez.has(t))return ej.debug(`There were multiple attempts to register component ${t}.`),!1;
1for(let n of(ez.set(t,e),eH.values()))e$(n,e);for(let t of eB.values())e$(t,e);return!0}function eG(e,t){let n=e.container.getProvider("heartbeat").getImmediate({optional:!0});return n&&n.triggerHeartbeat(),e.container.getProvider(t)}function eY(e){return void 0!==e.settings}let eJ=new $("app","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call initializeApp() first","bad-app-name":"Illegal App name: '{$appName}'","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","server-app-deleted":"Firebase Server App has been deleted","no-options":"Need to provide options, when not being deployed to hosting via source.","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invalid-log-argument":"First argument to `onLog` must be null or a function.","idb-open":"Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.","idb-get":"Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.","idb-set":"Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.","idb-delete":"Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.","finalization-registry-not-supported":"FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.","invalid-server-app-environment":"FirebaseServerApp is not for use in browser environments."});class eQ{constructor(e,t,n){this._isDeleted=!1,this._options=Object.assign({},e),this._config=Object.assign({},t),this._name=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled,this._container=n,this.container.addComponent(new e_("app",()=>this,"PUBLIC"))}get automaticDataCollectionEnabled(){return this.checkDestroyed(),this._automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this.checkDestroyed(),this._automaticDataCollectionEnabled=e}get name(){return this.checkDestroyed(),this._name}get options(){return this.checkDestroyed(),this._options}get config(){return this.checkDestroyed(),this._config}get container(){return this._container}get isDeleted(){return this._isDeleted}set isDeleted(e){this._isDeleted=e}checkDestroyed(){if(this.isDeleted)throw eJ.create("app-deleted",{appName:this._name})}}let eX="10.14.1";function eZ(e,t={}){let n=e;"object"!=typeof t&&(t={name:t});let i=Object.assign({name:eW,automaticDataCollectionEnabled:!1},t),r=i.name;if("string"!=typeof r||!r)throw eJ.create("bad-app-name",{appName:String(r)});if(n||(n=q()),!n)throw eJ.create("no-options");let s=eH.get(r);if(s){if(ei(n,s.options)&&ei(i,s.config))return s;throw eJ.create("duplicate-app",{appName:r})}let o=new ev(r);for(let e of ez.values())o.addComponent(e);let a=new eQ(n,i,o);return eH.set(r,a),a}function e0(e=eW){let t=eH.get(e);if(!t&&e===eW&&q())return eZ();if(!t)throw eJ.create("no-app",{appName:e});return t}function e1(e,t,n){var i;let r=null!==(i=eV[e])&&void 0!==i?i:e;n&&(r+=`-${n}`);let s=r.match(/\s|\//),o=t.match(/\s|\//);if(s||o){let e=[`Unable to register library "${r}" with version "${t}":`];s&&e.push(`library name "${r}" contains illegal characters (whitespace or "/")`),s&&o&&e.push("and"),o&&e.push(`version name "${t}" contains illegal characters (whitespace or "/")`),ej.warn(e.join(" "));return}eK(new e_(`${r}-version`,()=>({library:r,version:t}),"VERSION"))}let e2="firebase-heartbeat-store",e3=null;function e4(){return e3||(e3=(function(e,t,{blocked:n,upgrade:i,blocking:r,terminated:s}={}){let o=indexedDB.open(e,1),a=eO(o);return i&&o.addEventListener("upgradeneeded",e=>{i(eO(o.result),e.oldVersion,e.newVersion,eO(o.transaction),e)}),n&&o.addEventListener("blocked",e=>n(e.oldVersion,e.newVersion,e)),a.then(e=>{s&&e.addEventListener("close",()=>s()),r&&e.addEventListener("versionchange",e=>r(e.oldVersion,e.newVersion,e))}).catch(()=>{}),a})("firebase-heartbeat-database",0,{upgrade:(e,t)=>{if(0===t)try{e.createObjectStore(e2)}catch(e){console.warn(e)}}}).catch(e=>{throw eJ.create("idb-open",{originalErrorMessage:e.message})})),e3}async function e6(e){try{let t=(await e4()).transaction(e2),n=await t.objectStore(e2).get(e9(e));return await t.done,n}catch(e){if(e instanceof z)ej.warn(e.message);else{let t=eJ.create("idb-get",{originalErrorMessage:null==e?void 0:e.message});ej.warn(t.message)}}}async function e5(e,t){try{let n=(await e4()).transaction(e2,"readwrite");await n.objectStore(e2).put(t,e9(e)),await n.done}catch(e){if(e instanceof z)ej.warn(e.message);else{let t=eJ.create("idb-set",{originalErrorMessage:null==e?void 0:e.message});ej.warn(t.message)}}}function e9(e){return`${e.name}!${e.options.appId}`}class e8{constructor(e){this.container=e,this._heartbeatsCache=null;let t=this.container.getProvider("app").getImmediate();this._storage=new te(t),this._heartbeatsCachePromise=this._storage.read().then(e=>(this._heartbeatsCache=e,e))}async triggerHeartbeat(){var e,t;try{let n=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),i=e7();return(null===(e=this._heartbeatsCache)||void 0===e?void 0:e.heartbeats)==null&&(this._heartbeatsCache=await this._heartbeatsCachePromise,(null===(t=this._heartbeatsCache)||void 0===t?void 0:t.heartbeats)==null)||this._heartbeatsCache.lastSentHeartbeatDate===i||this._heartbeatsCache.heartbeats.some(e=>e.date===i)?void 0:(this._heartbeatsCache.heartbeats.push({date:i,agent:n}),this._heartbeatsCache.heartbeats=this._heartbeatsCache.heartbeats.filter(e=>{let t=new Date(e.date).valueOf();return Date.now()-t<=2592e6}),this._storage.overwrite(this._heartbeatsCache))}catch(e){ej.warn(e)}}async getHeartbeatsHeader(){var e;try{if(null===this._heartbeatsCache&&await this._heartbeatsCachePromise,(null===(e=this._heartbeatsCache)||void 0===e?void 0:e.heartbeats)==null||0===this._heartbeatsCache.heartbeats.length)return"";let t=e7(),{heartbeatsToSend:n,unsentEntries:i}=function(e,t=1024){let n=[],i=e.slice();for(let r of e){let e=n.find(e=>e.agent===r.agent);if(e){if(e.dates.push(r.date),tt(n)>t){e.dates.pop();break}}else if(n.push({agent:r.agent,dates:[r.date]}),tt(n)>t){n.pop();break}i=i.slice(1)}return{heartbeatsToSend:n,unsentEntries:i}}(this._heartbeatsCache.heartbeats),r=O(JSON.stringify({version:2,heartbeats:n}));return this._heartbeatsCache.lastSentHeartbeatDate=t,i.length>0?(this._heartbeatsCache.heartbeats=i,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),r}catch(e){return ej.warn(e),""}}}function e7(){return new Date().toISOString().substring(0,10)}class te{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!function(){try{return"object"==typeof indexedDB}catch{return!1}}()&&new Promise((e,t)=>
1{try{let n=!0,i="validate-browser-context-for-indexeddb-analytics-module",r=self.indexedDB.open(i);r.onsuccess=()=>{r.result.close(),n||self.indexedDB.deleteDatabase(i),e(!0)},r.onupgradeneeded=()=>{n=!1},r.onerror=()=>{var e;t((null===(e=r.error)||void 0===e?void 0:e.message)||"")}}catch(e){t(e)}}).then(()=>!0).catch(()=>!1)}async read(){if(!await this._canUseIndexedDBPromise)return{heartbeats:[]};{let e=await e6(this.app);return null!=e&&e.heartbeats?e:{heartbeats:[]}}}async overwrite(e){var t;if(await this._canUseIndexedDBPromise){let n=await this.read();return e5(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:e.heartbeats})}}async add(e){var t;if(await this._canUseIndexedDBPromise){let n=await this.read();return e5(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:[...n.heartbeats,...e.heartbeats]})}}}function tt(e){return O(JSON.stringify({version:2,heartbeats:e})).length}eK(new e_("platform-logger",e=>new eF(e),"PRIVATE")),eK(new e_("heartbeat",e=>new e8(e),"PRIVATE")),e1(eU,eq,""),e1(eU,eq,"esm2017"),e1("fire-js","");let tn="@firebase/database",ti="1.0.8",tr="";class ts{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),Y(t))}get(e){let t=this.domStorage_.getItem(this.prefixedName_(e));return null==t?null:G(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}class to{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){null==t?delete this.cache_[e]:this.cache_[e]=t}get(e){return Z(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}let ta=function(e){try{if("u">typeof window&&"u">typeof window[e]){let t=window[e];return t.setItem("firebase:sentinel","cache"),t.removeItem("firebase:sentinel"),new ts(t)}}catch{}return new to},tl=ta("localStorage"),th=ta("sessionStorage"),tc=new eb("@firebase/database"),tu=(_=1,function(){return _++}),td=function(e){let t=ed(e),n=new el;n.update(t);let i=n.digest();return P.encodeByteArray(i)},tp=function(...e){let t="";for(let n=0;n<e.length;n++){let i=e[n];Array.isArray(i)||i&&"object"==typeof i&&"number"==typeof i.length?t+=tp.apply(null,i):"object"==typeof i?t+=Y(i):t+=i,t+=" "}return t},tf=null,t_=!0,tm=function(e,t){T(!0,"Can't turn on custom loggers persistently."),tc.logLevel=w.VERBOSE,tf=tc.log.bind(tc)},tg=function(...e){if(!0===t_&&(t_=!1,null===tf&&!0===th.get("logging_enabled")&&tm()),tf){let t=tp.apply(null,e);tf(t)}},tv=function(e){return function(...t){tg(e,...t)}},ty=function(...e){let t="FIREBASE INTERNAL ERROR: "+tp(...e);tc.error(t)},tw=function(...e){let t=`FIREBASE FATAL ERROR: ${tp(...e)}`;throw tc.error(t),Error(t)},tI=function(...e){let t="FIREBASE WARNING: "+tp(...e);tc.warn(t)},tC=function(){"u">typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&tI("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().")},tb=function(e){return"number"==typeof e&&(e!=e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY)},tT=function(e){if("complete"===document.readyState)e();else{let t=!1,n=function(){if(!document.body){setTimeout(n,Math.floor(10));return}t||(t=!0,e())};document.addEventListener?(document.addEventListener("DOMContentLoaded",n,!1),window.addEventListener("load",n,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",()=>{"complete"===document.readyState&&n()}),window.attachEvent("onload",n))}},tE="[MIN_NAME]",tk="[MAX_NAME]",tS=function(e,t){if(e===t)return 0;if(e===tE||t===tk)return -1;if(t===tE||e===tk)return 1;{let n=tL(e),i=tL(t);return null!==n?null!==i?n-i==0?e.length-t.length:n-i:-1:null!==i?1:e<t?-1:1}},tP=function(e,t){return e===t?0:e<t?-1:1},tN=function(e,t){if(t&&e in t)return t[e];throw Error("Missing required key ("+e+") in object: "+Y(t))},tR=function(e){if("object"!=typeof e||null===e)return Y(e);let t=[];for(let n in e)t.push(n);
1t.sort();let n="{";for(let i=0;i<t.length;i++)0!==i&&(n+=","),n+=Y(t[i])+":"+tR(e[t[i]]);return n+"}"},tO=function(e,t){let n=e.length;if(n<=t)return[e];let i=[];for(let r=0;r<n;r+=t)r+t>n?i.push(e.substring(r,n)):i.push(e.substring(r,r+t));return i};function tA(e,t){for(let n in e)e.hasOwnProperty(n)&&t(n,e[n])}let tD=function(e){let t,n,i,r,s;T(!tb(e),"Invalid JSON number"),0===e?(n=0,i=0,t=1/e==-1/0?1:0):(t=e<0,(e=Math.abs(e))>=22250738585072014e-324?(n=(r=Math.min(Math.floor(Math.log(e)/Math.LN2),1023))+1023,i=Math.round(e*Math.pow(2,52-r)-4503599627370496)):(n=0,i=Math.round(e/5e-324)));let o=[];for(s=52;s;s-=1)o.push(i%2?1:0),i=Math.floor(i/2);for(s=11;s;s-=1)o.push(n%2?1:0),n=Math.floor(n/2);o.push(t?1:0),o.reverse();let a=o.join(""),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()},tx=RegExp("^-?(0*)\\d{1,10}$"),tL=function(e){if(tx.test(e)){let t=Number(e);if(t>=-2147483648&&t<=2147483647)return t}return null},tM=function(e){try{e()}catch(e){setTimeout(()=>{throw tI("Exception was thrown by user callback.",e.stack||""),e},Math.floor(0))}},tF=function(e,t){let n=setTimeout(e,t);return"number"==typeof n&&"u">typeof Deno&&Deno.unrefTimer?Deno.unrefTimer(n):"object"==typeof n&&n.unref&&n.unref(),n};class tU{constructor(e,t){this.appName_=e,this.appCheckProvider=t,this.appCheck=null==t?void 0:t.getImmediate({optional:!0}),this.appCheck||null==t||t.get().then(e=>this.appCheck=e)}getToken(e){return this.appCheck?this.appCheck.getToken(e):new Promise((t,n)=>{setTimeout(()=>{this.appCheck?this.getToken(e).then(t,n):t(null)},0)})}addTokenChangeListener(e){var t;null===(t=this.appCheckProvider)||void 0===t||t.get().then(t=>t.addTokenListener(e))}notifyForInvalidToken(){tI(`Provided AppCheck credentials for the app named "${this.appName_}" are invalid. This usually indicates your app was not initialized correctly.`)}}class tq{constructor(e,t,n){this.appName_=e,this.firebaseOptions_=t,this.authProvider_=n,this.auth_=null,this.auth_=n.getImmediate({optional:!0}),this.auth_||n.onInit(e=>this.auth_=e)}getToken(e){return this.auth_?this.auth_.getToken(e).catch(e=>e&&"auth/token-not-initialized"===e.code?(tg("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(e)):new Promise((t,n)=>{setTimeout(()=>{this.auth_?this.getToken(e).then(t,n):t(null)},0)})}addTokenChangeListener(e){this.auth_?this.auth_.addAuthTokenListener(e):this.authProvider_.get().then(t=>t.addAuthTokenListener(e))}removeTokenChangeListener(e){this.authProvider_.get().then(t=>t.removeAuthTokenListener(e))}notifyForInvalidToken(){let e='Provided authentication credentials for the app named "'+this.appName_+'" are invalid. This usually indicates your app was not initialized correctly. ';"credential"in this.firebaseOptions_?e+='Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':"serviceAccount"in this.firebaseOptions_?e+='Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':e+='Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.',tI(e)}}class tj{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}tj.OWNER="owner";let tW=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,tV="websocket",tH="long_polling";class tB{constructor(e,t,n,i,r=!1,s="",o=!1,a=!1){this.secure=t,this.namespace=n,this.webSocketOnly=i,this.nodeAdmin=r,this.persistenceKey=s,this.includeNamespaceInQueryParams=o,this.isUsingEmulator=a,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=tl.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()&&tl.set("host:"+this._host,this.internalHost))}toString(){let e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e}toURLString(){let e=this.secure?"https://":"http://",t=this.includeNamespaceInQueryParams?`?ns=${this.namespace}`:"";return`${e}${this.host}/${t}`}}function tz(e,t,n){let i;if(T("string"==typeof t,"typeof type must == string"),T("object"==typeof n,"typeof params must == object"),t===tV)i=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?";else if(t===tH)i=(e.secure?"https://":"http://")+e.internalHost+"/.lp?";else throw Error("Unknown connection type: "+t);(e.host!==e.internalHost||e.isCustomHost()||e.includeNamespaceInQueryParams)&&
1(n.ns=e.namespace);let r=[];return tA(n,(e,t)=>{r.push(e+"="+t)}),i+r.join("&")}class t${constructor(){this.counters_={}}incrementCounter(e,t=1){Z(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return function e(t,n){if(!(n instanceof Object))return n;switch(n.constructor){case Date:return new Date(n.getTime());case Object:void 0===t&&(t={});break;case Array:t=[];break;default:return n}for(let i in n)n.hasOwnProperty(i)&&"__proto__"!==i&&(t[i]=e(t[i],n[i]));return t}(void 0,this.counters_)}}let tK={},tG={};function tY(e){let t=e.toString();return tK[t]||(tK[t]=new t$),tK[t]}class tJ{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]&&tM(()=>{this.onMessage_(e[t])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}let tQ="start";class tX{constructor(e,t,n,i,r,s,o){this.connId=e,this.repoInfo=t,this.applicationId=n,this.appCheckToken=i,this.authToken=r,this.transportSessionId=s,this.lastSessionId=o,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=tv(e),this.stats_=tY(t),this.urlFn=e=>(this.appCheckToken&&(e.ac=this.appCheckToken),tz(t,tH,e))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new tJ(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null},Math.floor(3e4)),tT(()=>{if(this.isClosed_)return;this.scriptTagHolder=new tZ((...e)=>{let[t,n,i,r,s]=e;if(this.incrementIncomingBytes_(e),this.scriptTagHolder){if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,t===tQ)this.id=n,this.password=i;else if("close"===t)n?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(n,()=>{this.onClosed_()})):this.onClosed_();else throw Error("Unrecognized command received: "+t)}},(...e)=>{let[t,n]=e;this.incrementIncomingBytes_(e),this.myPacketOrderer.handleResponse(t,n)},()=>{this.onClosed_()},this.urlFn);let e={};e[tQ]="t",e.ser=Math.floor(1e8*Math.random()),this.scriptTagHolder.uniqueCallbackIdentifier&&(e.cb=this.scriptTagHolder.uniqueCallbackIdentifier),e.v="5",this.transportSessionId&&(e.s=this.transportSessionId),this.lastSessionId&&(e.ls=this.lastSessionId),this.applicationId&&(e.p=this.applicationId),this.appCheckToken&&(e.ac=this.appCheckToken),"u">typeof location&&location.hostname&&tW.test(location.hostname)&&(e.r="f");let t=this.urlFn(e);this.log_("Connecting via long-poll to "+t),this.scriptTagHolder.addTag(t,()=>{})})}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){tX.forceAllow_=!0}static forceDisallow(){tX.forceDisallow_=!0}static isAvailable(){return!!tX.forceAllow_||!tX.forceDisallow_&&"u">typeof document&&null!=document.createElement&&!("object"==typeof window&&window.chrome&&window.chrome.extension&&!/^chrome/.test(window.location.href))&&!("object"==typeof Windows&&"object"==typeof Windows.UI)}markConnectionHealthy(){}shutdown_(){this.isClosed_=!0,this.scriptTagHolder&&(this.scriptTagHolder.close(),this.scriptTagHolder=null),this.myDisconnFrame&&(document.body.removeChild(this.myDisconnFrame),this.myDisconnFrame=null),this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null)}onClosed_(){this.isClosed_||(this.log_("Longpoll is closing itself"),this.shutdown_(),this.onDisconnect_&&(this.onDisconnect_(this.everConnected_),this.onDisconnect_=null))}close(){this.isClosed_||(this.log_("Longpoll is being closed."),this.shutdown_())}send(e){let t=Y(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);let n=tO(R(t),1840);for(let e=0;e<n.length;e++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,n.length,n[e]),this.curSegmentNum++}addDisconnectPingFrame(e,t){this.myDisconnFrame=document.createElement("iframe");let n={};n.dframe="t",n.id=e,n.pw=t,this.myDisconnFrame.src=this.urlFn(n),this.myDisconnFrame.style.display="none",document.body.appendChild(this.myDisconnFrame)}incrementIncomingBytes_(e){let t=Y(e).length;this.bytesReceived+=t,this.stats_.incrementCounter("bytes_received",t)}}class tZ{constructor(e,t,n,i){this.onDisconnect=n,this.urlFn=i,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(1e8*Math.random()),this.sendNewPolls=!0;{this.uniqueCallbackIdentifier=tu(),window["pLPCommand"+this.uniqueCallbackIdentifier]=e,window["pRTLPCB"+this.uniqueCallbackIdentifier]=t,this.myIFrame=tZ.createIFrame_();let n="";this.myIFrame.src&&"javascript:"===this.myIFrame.src.substr(0,11)&&(n='<script>document.domain="'+document.domain+'";</script>');let i="<html><body>"+n+"</body></html>";
1try{this.myIFrame.doc.open(),this.myIFrame.doc.write(i),this.myIFrame.doc.close()}catch(e){tg("frame writing exception"),e.stack&&tg(e.stack),tg(e)}}}static createIFrame_(){let e=document.createElement("iframe");if(e.style.display="none",document.body){document.body.appendChild(e);try{e.contentWindow.document||tg("No IE domain setting required")}catch{let t=document.domain;e.src="javascript:void((function(){document.open();document.domain='"+t+"';document.close();})())"}}else throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";return e.contentDocument?e.doc=e.contentDocument:e.contentWindow?e.doc=e.contentWindow.document:e.document&&(e.doc=e.document),e}close(){this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.textContent="",setTimeout(()=>{null!==this.myIFrame&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)},Math.floor(0)));let e=this.onDisconnect;e&&(this.onDisconnect=null,e())}startLongPoll(e,t){for(this.myID=e,this.myPW=t,this.alive=!0;this.newRequest_(););}newRequest_(){if(!this.alive||!this.sendNewPolls||!(this.outstandingRequests.size<(this.pendingSegs.length>0?2:1)))return!1;{this.currentSerial++;let e={};e.id=this.myID,e.pw=this.myPW,e.ser=this.currentSerial;let t=this.urlFn(e),n="",i=0;for(;this.pendingSegs.length>0&&this.pendingSegs[0].d.length+30+n.length<=1870;){let e=this.pendingSegs.shift();n=n+"&seg"+i+"="+e.seg+"&ts"+i+"="+e.ts+"&d"+i+"="+e.d,i++}return t+=n,this.addLongPollTag_(t,this.currentSerial),!0}}enqueueSegment(e,t,n){this.pendingSegs.push({seg:e,ts:t,d:n}),this.alive&&this.newRequest_()}addLongPollTag_(e,t){this.outstandingRequests.add(t);let n=()=>{this.outstandingRequests.delete(t),this.newRequest_()},i=setTimeout(n,Math.floor(25e3));this.addTag(e,()=>{clearTimeout(i),n()})}addTag(e,t){setTimeout(()=>{try{if(!this.sendNewPolls)return;let n=this.myIFrame.doc.createElement("script");n.type="text/javascript",n.async=!0,n.src=e,n.onload=n.onreadystatechange=function(){let e=n.readyState;e&&"loaded"!==e&&"complete"!==e||(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),t())},n.onerror=()=>{tg("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(n)}catch{}},Math.floor(1))}}let t0=null;"u">typeof MozWebSocket?t0=MozWebSocket:"u">typeof WebSocket&&(t0=WebSocket);class t1{constructor(e,t,n,i,r,s,o){this.connId=e,this.applicationId=n,this.appCheckToken=i,this.authToken=r,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=tv(this.connId),this.stats_=tY(t),this.connURL=t1.connectionURL_(t,s,o,i,n),this.nodeAdmin=t.nodeAdmin}static connectionURL_(e,t,n,i,r){let s={};return s.v="5","u">typeof location&&location.hostname&&tW.test(location.hostname)&&(s.r="f"),t&&(s.s=t),n&&(s.ls=n),i&&(s.ac=i),r&&(s.p=r),tz(e,tV,s)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,tl.set("previous_websocket_failure",!0);try{let e;this.mySock=new t0(this.connURL,[],e)}catch(t){this.log_("Error instantiating WebSocket.");let e=t.message||t.data;e&&this.log_(e),this.onClosed_();return}this.mySock.onopen=()=>{this.log_("Websocket connected."),this.everConnected_=!0},this.mySock.onclose=()=>{this.log_("Websocket connection was disconnected."),this.mySock=null,this.onClosed_()},this.mySock.onmessage=e=>{this.handleIncomingFrame(e)},this.mySock.onerror=e=>{this.log_("WebSocket error. Closing connection.");let t=e.message||e.data;t&&this.log_(t),this.onClosed_()}}start(){}static forceDisallow(){t1.forceDisallow_=!0}static isAvailable(){let e=!1;if("u">typeof navigator&&navigator.userAgent){let t=navigator.userAgent.match(/Android ([0-9]{0,}\.[0-9]{0,})/);t&&t.length>1&&4.4>parseFloat(t[1])&&(e=!0)}return!e&&null!==t0&&!t1.forceDisallow_}static previouslyFailed(){return tl.isInMemoryStorage||!0===tl.get("previous_websocket_failure")}markConnectionHealthy(){tl.remove("previous_websocket_failure")}appendFrame_(e){if(this.frames.push(e),this.frames.length===this.totalFrames){let e=this.frames.join("");this.frames=null;let t=G(e);this.onMessage(t)}}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if(T(null===this.frames,"We already have a frame buffer"),e.length<=6){let t=Number(e);if(!isNaN(t))return this.handleNewFrameCount_(t),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){if(null===this.mySock)return;let t=e.data;if(this.bytesReceived+=t.length,this.stats_.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),null!==this.frames)this.appendFrame_(t);else{let e=this.extractFrameCount_(t);null!==e&&this.appendFrame_(e)}}send(e){this.resetKeepAlive();let t=Y(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);let n=tO(t,16384);n.length>1&&this.sendString_(String(n.length));for(let e=0;e<n.length;e++)this.sendString_(n[e])}shutdown_(){this.isClosed_=!0,this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),this.mySock&&(this.mySock.close(),this.mySock=null)}onClosed_(){this.isClosed_||(this.log_("WebSocket is closing itself"),this.shutdown_(),this.onDisconnect&&(this.onDisconnect(this.everConnected_),this.onDisconnect=null))}close(){this.isClosed_||(this.log_("WebSocket is being closed"),this.shutdown_())}resetKeepAlive(){clearInterval(this.keepaliveTimer),this.keepaliveTimer=setInterval(()=>{this.mySock&&this.sendString_("0"),this.resetKeepAlive()},Math.floor(45e3))}sendString_(e){try{this.mySock.send(e)}catch(e){this.log_("Exception thrown from WebSocket.send():",e.message||e.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}}}t1.responsesRequiredToBeHealthy=2,t1.healthyTimeout=3e4;class t2{constructor(e){this.initTransports_(e)}static get ALL_TRANSPORTS(){return[tX,t1]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}initTransports_(e){let t=t1&&t1.isAvailable(),n=t&&!t1.previouslyFailed();if(e.webSocketOnly&&(t||tI("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),n=!0),n)this.transports_=[t1];else{let e=this.transports_=[];for(let t of t2.ALL_TRANSPORTS)t&&t.isAvailable()&&e.push(t);t2.globalTransportInitialized_=!0}}initialTransport(){if(this.transports_.length>0)return this.transports_[0];throw Error("No transports available")}upgradeTransport(){return this.transports_.length>1?this.transports_[1]:null}}t2.globalTransportInitialized_=!1;class t3{constructor(e,t,n,i,r,s,o,a,l,h){this.id=e,this.repoInfo_=t,this.applicationId_=n,this.appCheckToken_=i,this.authToken_=r,this.onMessage_=s,this.onReady_=o,this.onDisconnect_=a,this.onKill_=l,this.lastSessionId=h,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=tv("c:"+this.id+":"),this.transportManager_=new t2(t),this.log_("Connection created"),this.start_()}start_(){let e=this.transportManager_.initialTransport();this.conn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,null,this.lastSessionId),this.primaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;let t=this.connReceiver_(this.conn_),n=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout(()=>{this.conn_&&this.conn_.open(t,n)},Math.floor(0));let i=e.healthyTimeout||0;i>0&&(this.healthyTimeout_=tF(()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&this.conn_.bytesReceived>102400?(this.log_("Connection exceeded healthy timeout but has received "+this.conn_.bytesReceived+" bytes. Marking connection healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()):this.conn_&&this.conn_.bytesSent>10240?this.log_("Connection exceeded healthy timeout but has sent "+this.conn_.bytesSent+" bytes. Leaving connection alive."):(this.log_("Closing unhealthy connection after timeout."),this.close()))},Math.floor(i)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(e){return t=>{e===this.conn_?this.onConnectionLost_(t):e===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(e){return t=>{2!==this.state_&&(e===this.rx_?this.onPrimaryMessageReceived_(t):e===this.secondaryConn_?this.onSecondaryMessageReceived_(t):this.log_("message on old connection"))}}sendRequest(e){this.sendData_({t:"d",d:e})}tryCleanupConnection(){this.tx_===this.secondaryConn_&&this.rx_===this.secondaryConn_&&(this.log_("cleaning up and promoting a connection: "+this.secondaryConn_.connId),this.conn_=this.secondaryConn_,this.secondaryConn_=null)}onSecondaryControl_(e){if("t"in e){let t=e.t;"a"===t?this.upgradeIfSecondaryHealthy_():"r"===t?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),(this.tx_===this.secondaryConn_||this.rx_===this.secondaryConn_)&&this.close()):"o"===t&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_())}}onSecondaryMessageReceived_(e){let t=tN("t",e),n=tN("d",e);if("c"===t)this.onSecondaryControl_(n);else if("d"===t)this.pendingDataMessages.push(n);else throw Error("Unknown protocol layer: "+t)}upgradeIfSecondaryHealthy_(){this.secondaryResponsesRequired_<=0?(this.log_("Secondary connection is healthy."),this.isHealthy_=!0,this.secondaryConn_.markConnectionHealthy(),this.proceedWithUpgrade_()):(this.log_("sending ping on secondary."),this.secondaryConn_.send({t
1:"c",d:{t:"p",d:{}}}))}proceedWithUpgrade_(){this.secondaryConn_.start(),this.log_("sending client ack on secondary"),this.secondaryConn_.send({t:"c",d:{t:"a",d:{}}}),this.log_("Ending transmission on primary"),this.conn_.send({t:"c",d:{t:"n",d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()}onPrimaryMessageReceived_(e){let t=tN("t",e),n=tN("d",e);"c"===t?this.onControl_(n):"d"===t&&this.onDataMessage_(n)}onDataMessage_(e){this.onPrimaryResponse_(),this.onMessage_(e)}onPrimaryResponse_(){this.isHealthy_||(this.primaryResponsesRequired_--,this.primaryResponsesRequired_<=0&&(this.log_("Primary connection is healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()))}onControl_(e){let t=tN("t",e);if("d"in e){let n=e.d;if("h"===t){let e=Object.assign({},n);this.repoInfo_.isUsingEmulator&&(e.h=this.repoInfo_.host),this.onHandshake_(e)}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?ty("Server Error: "+n):"o"===t?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):ty("Unknown control packet command: "+t)}}onHandshake_(e){let t=e.ts,n=e.v,i=e.h;this.sessionId=e.s,this.repoInfo_.host=i,0===this.state_&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,t),"5"!==n&&tI("Protocol version mismatch detected"),this.tryStartUpgrade_())}tryStartUpgrade_(){let e=this.transportManager_.upgradeTransport();e&&this.startUpgrade_(e)}startUpgrade_(e){this.secondaryConn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,this.sessionId),this.secondaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;let t=this.connReceiver_(this.secondaryConn_),n=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(t,n),tF(()=>{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):tF(()=>{this.sendPingOnPrimaryIfNecessary_()},Math.floor(5e3))}sendPingOnPrimaryIfNecessary_(){this.isHealthy_||1!==this.state_||(this.log_("sending ping on primary."),this.sendData_({t:"c",d:{t:"p",d:{}}}))}onSecondaryConnectionLost_(){let e=this.secondaryConn_;this.secondaryConn_=null,(this.tx_===e||this.rx_===e)&&this.close()}onConnectionLost_(e){this.conn_=null,e||0!==this.state_?1===this.state_&&this.log_("Realtime connection lost."):(this.log_("Realtime connection failed."),this.repoInfo_.isCacheableHost()&&(tl.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 t4{put(e,t,n,i){}merge(e,t,n,i){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,t,n){}onDisconnectMerge(e,t,n){}onDisconnectCancel(e,t){}reportStats(e){}}class t6{constructor(e){this.allowedEvents_=e,this.listeners_={},T(Array.isArray(e)&&e.length>0,"Requires a non-empty array")}trigger(e,...t){if(Array.isArray(this.listeners_[e])){let n=[...this.listeners_[e]];for(let e=0;e<n.length;e++)n[e].callback.apply(n[e].context,t)}}on(e,t,n){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:n});let i=this.getInitialEvent(e);i&&t.apply(n,i)}off(e,t,n){this.validateEventType_(e);let i=this.listeners_[e]||[];for(let e=0;e<i.length;e++)if(i[e].callback===t&&(!n||n===i[e].context)){i.splice(e,1);return}}validateEventType_(e){T(this.allowedEvents_.find(t=>t===e),"Unknown event: "+e)}}class t5 extends t6{constructor(){super(["online"]),this.online_=!0,"u">typeof window&&"u">typeof window.addEventListener&&!H()&&(window.addEventListener("online",()=>{this.online_||(this.online_=!0,this.trigger("online",!0))},!1),window.addEventListener("offline",()=>{this.online_&&(this.online_=!1,this.trigger("online",!1))},!1))}static getInstance(){return new t5}getInitialEvent(e){return T("online"===e,"Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}class t9{constructor(e,t){if(void 0===t){this.pieces_=e.split("/");let t=0;for(let e=0;e<this.pieces_.length;e++)this.pieces_[e].length>0&&(this.pieces_[t]=this.pieces_[e],t++);this.pieces_.length=t,this.pieceNum_=0}else this.pieces_=e,this.pieceNum_=t}toString(){let e="";for(let t=this.pieceNum_;t<this.pieces_.length;t++)""!==this.pieces_[t]&&(e+="/"+this.pieces_[t]);return e||"/"}}function t8(){return new t9("")}function t7(e){return e.pieceNum_>=e.pieces_.length?null:e.pieces_[e.pieceNum_]}function ne(e){return e.pieces_.length-e.pieceNum_}function nt(e){let t=e.pieceNum_;return t<e.pieces_.length&&t++,new t9(e.pieces_,t)}function nn(e){return e.pieceNum_<e.pieces_.length?e.pieces_[e.pieces_.length-1]:null}function ni(e,t=0){return e.pieces_.slice(e.pieceNum_+t)}function nr(e){if(e.pieceNum_>=e.pieces_.length)return null;let t=[];for(let n=e.pieceNum_;n<e.pieces_.length-1;n++)t.push(e.pieces_[n]);return new t9(t,0)}function ns(e,t){let n=[];for(let t=e.pieceNum_;t<e.pieces_.length;t++)n.push(e.pieces_[t]);if(t instanceof t9)for(let e=t.pieceNum_;e<t.pieces_.length;e++)n.push(t.pieces_[e]);else{let e=t.split("/");for(let t=0;t<e.length;t++)e[t].length>0&&n.push(e[t])}return new t9(n,0)}function no(e){return e.pieceNum_>=e.pieces_.length}function na(e,t){let n=t7(e),i=t7(t);if(null===n)return t;if(n===i)return na(nt(e),nt(t));
1throw Error("INTERNAL ERROR: innerPath ("+t+") is not within outerPath ("+e+")")}function nl(e,t){if(ne(e)!==ne(t))return!1;for(let n=e.pieceNum_,i=t.pieceNum_;n<=e.pieces_.length;n++,i++)if(e.pieces_[n]!==t.pieces_[i])return!1;return!0}function nh(e,t){let n=e.pieceNum_,i=t.pieceNum_;if(ne(e)>ne(t))return!1;for(;n<e.pieces_.length;){if(e.pieces_[n]!==t.pieces_[i])return!1;++n,++i}return!0}class nc{constructor(e,t){this.errorPrefix_=t,this.parts_=ni(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let e=0;e<this.parts_.length;e++)this.byteLength_+=ep(this.parts_[e]);nu(this)}}function nu(e){if(e.byteLength_>768)throw Error(e.errorPrefix_+"has a key path longer than 768 bytes ("+e.byteLength_+").");if(e.parts_.length>32)throw Error(e.errorPrefix_+"path specified exceeds the maximum depth that can be written (32) or object contains a cycle "+nd(e))}function nd(e){return 0===e.parts_.length?"":"in property '"+e.parts_.join(".")+"'"}class np extends t6{constructor(){let e,t;super(["visible"]),"u">typeof document&&"u">typeof document.addEventListener&&("u">typeof document.hidden?(t="visibilitychange",e="hidden"):"u">typeof document.mozHidden?(t="mozvisibilitychange",e="mozHidden"):"u">typeof document.msHidden?(t="msvisibilitychange",e="msHidden"):"u">typeof document.webkitHidden&&(t="webkitvisibilitychange",e="webkitHidden")),this.visible_=!0,t&&document.addEventListener(t,()=>{let t=!document[e];t!==this.visible_&&(this.visible_=t,this.trigger("visible",t))},!1)}static getInstance(){return new np}getInitialEvent(e){return T("visible"===e,"Unknown event type: "+e),[this.visible_]}}class nf extends t4{constructor(e,t,n,i,r,s,o,a){if(super(),this.repoInfo_=e,this.applicationId_=t,this.onDataUpdate_=n,this.onConnectStatus_=i,this.onServerInfoUpdate_=r,this.authTokenProvider_=s,this.appCheckTokenProvider_=o,this.authOverride_=a,this.id=nf.nextPersistentConnectionId_++,this.log_=tv("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 Error("Auth override specified in options, but not supported on non Node.js platforms");np.getInstance().on("visible",this.onVisible_,this),-1===e.host.indexOf("fblocal")&&t5.getInstance().on("online",this.onOnline_,this)}sendRequest(e,t,n){let i=++this.requestNumber_,r={r:i,a:e,b:t};this.log_(Y(r)),T(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(r),n&&(this.requestCBHash_[i]=n)}get(e){this.initConnection_();let t=new W,n={action:"g",request:{p:e._path.toString(),q:e._queryObject},onComplete:e=>{let n=e.d;"ok"===e.s?t.resolve(n):t.reject(n)}};this.outstandingGets_.push(n),this.outstandingGetCount_++;let i=this.outstandingGets_.length-1;return this.connected_&&this.sendGet_(i),t.promise}listen(e,t,n,i){this.initConnection_();let r=e._queryIdentifier,s=e._path.toString();this.log_("Listen called for "+s+" "+r),this.listens.has(s)||this.listens.set(s,new Map),T(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),T(!this.listens.get(s).has(r),"listen() called twice for same path/queryId.");let o={onComplete:i,hashFn:t,query:e,tag:n};this.listens.get(s).set(r,o),this.connected_&&this.sendListen_(o)}sendGet_(e){let t=this.outstandingGets_[e];this.sendRequest("g",t.request,n=>{delete this.outstandingGets_[e],this.outstandingGetCount_--,0===this.outstandingGetCount_&&(this.outstandingGets_=[]),t.onComplete&&t.onComplete(n)})}sendListen_(e){let t=e.query,n=t._path.toString(),i=t._queryIdentifier;this.log_("Listen on "+n+" for "+i);let r={p:n};e.tag&&(r.q=t._queryObject,r.t=e.tag),r.h=e.hashFn(),this.sendRequest("q",r,r=>{let s=r.d,o=r.s;nf.warnOnListenWarnings_(s,t),(this.listens.get(n)&&this.listens.get(n).get(i))===e&&(this.log_("listen response",r),"ok"!==o&&this.removeListen_(n,i),e.onComplete&&e.onComplete(o,s))})}static warnOnListenWarnings_(e,t){if(e&&"object"==typeof e&&Z(e,"w")){let n=ee(e,"w");if(Array.isArray(n)&&~n.indexOf("no_index")){let e='".indexOn": "'+t._queryParams.getIndex().toString()+'"',n=t._path.toString();tI(`Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ${e} at ${n} to your security rules for better performance.`)}}}refreshAuthToken(e){this.authToken_=e,this.log_("Auth token refreshed"),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest("unauth",{},()=>{}),this.reduceReconnectDelayIfAdminCredential_(e)}reduceReconnectDelayIfAdminCredential_(e){(e&&40===e.length||X(e))&&(this.log_("Admin auth credential detected. Reducing max reconnect time."),this.maxReconnectDelay_=3e4)}refreshAppCheckToken(e){this.appCheckToken_=e,this.log_("App check token refreshed"),this.appCheckToken_?this.tryAppCheck():this.connected_&&this.sendRequest("unappeck",{},()=>{})}tryAuth(){if(this.connected_&&this.authToken_){let e=this.authToken_,t=Q(e)?"auth":"gauth",n={cred:e};null===this.authOverride_?n.noauth=!0:"object"==typeof this.authOverride_&&(n.authvar=this.authOverride_),this.sendRequest(t,n,t=>{let n=t.s,i=t.d||"error";this.authToken_===e&&("ok"===n?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(n,i))})}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},e=>{let t=e.s,n=e.d||"error";"ok"===t?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(t,n)})}unlisten(e,t){let n=e._path.toString(),i=e._queryIdentifier;this.log_("Unlisten called for "+n+" "+i),T(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(n,i)&&this.connected_&&this.sendUnlisten_(n,i,e._queryObject,t)}sendUnlisten_(e,t,n,i){this.log_("Unlisten on "+e+" for "+t);let r={p:e};i&&(r.q=n,r.t=i),this.sendRequest("n",r)}onDisconnectPut(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("o",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"o",data:t,onComplete:n})}onDisconnectMerge(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("om",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"om",data:t,onComplete:n})}onDisconnectCancel(e,t){this.initConnection_(),this.connected_?this.sendOnDisconnect_("oc",e,null,t):this.onDisconnectRequestQueue_.push({pathString:e,action:"oc",data:null,onComplete:t})}sendOnDisconnect_(e,t,n,i){let r={p:t,d:n};this.log_("onDisconnect "+e,r),this.sendRequest(e,r,e=>
1{i&&setTimeout(()=>{i(e.s,e.d)},Math.floor(0))})}put(e,t,n,i){this.putInternal("p",e,t,n,i)}merge(e,t,n,i){this.putInternal("m",e,t,n,i)}putInternal(e,t,n,i,r){this.initConnection_();let s={p:t,d:n};void 0!==r&&(s.h=r),this.outstandingPuts_.push({action:e,request:s,onComplete:i}),this.outstandingPutCount_++;let o=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(o):this.log_("Buffering put: "+t)}sendPut_(e){let t=this.outstandingPuts_[e].action,n=this.outstandingPuts_[e].request,i=this.outstandingPuts_[e].onComplete;this.outstandingPuts_[e].queued=this.connected_,this.sendRequest(t,n,n=>{this.log_(t+" response",n),delete this.outstandingPuts_[e],this.outstandingPutCount_--,0===this.outstandingPutCount_&&(this.outstandingPuts_=[]),i&&i(n.s,n.d)})}reportStats(e){if(this.connected_){let t={c:e};this.log_("reportStats",t),this.sendRequest("s",t,e=>{if("ok"!==e.s){let t=e.d;this.log_("reportStats","Error sending stats: "+t)}})}}onDataMessage_(e){if("r"in e){this.log_("from server: "+Y(e));let t=e.r,n=this.requestCBHash_[t];n&&(delete this.requestCBHash_[t],n(e.b))}else{if("error"in e)throw"A server-side error has occurred: "+e.error;"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):ty("Unrecognized action received from server: "+Y(e)+` 2Are 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){T(!this.realtime_,"Scheduling a connect when we're already connected/ing?"),this.establishConnectionTimer_&&clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=setTimeout(()=>{this.establishConnectionTimer_=null,this.establishConnection_()},Math.floor(e))}initConnection_(){!this.realtime_&&this.firstConnection_&&this.scheduleConnect_(0)}onVisible_(e){e&&!this.visible_&&this.reconnectDelay_===this.maxReconnectDelay_&&(this.log_("Window became visible. Reducing delay."),this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0)),this.visible_=e}onOnline_(e){e?(this.log_("Browser went online."),this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0)):(this.log_("Browser went offline. Killing connection."),this.realtime_&&this.realtime_.close())}onRealtimeDisconnect_(){if(this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()){this.visible_?this.lastConnectionEstablishedTime_&&(new Date().getTime()-this.lastConnectionEstablishedTime_>3e4&&(this.reconnectDelay_=1e3),this.lastConnectionEstablishedTime_=null):(this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=new Date().getTime());let e=new Date().getTime()-this.lastConnectionAttemptTime_,t=Math.max(0,this.reconnectDelay_-e);t=Math.random()*t,this.log_("Trying to reconnect in "+t+"ms"),this.scheduleConnect_(t),this.reconnectDelay_=Math.min(this.maxReconnectDelay_,1.3*this.reconnectDelay_)}this.onConnectStatus_(!1)}async establishConnection_(){if(this.shouldReconnect_()){this.log_("Making a connection attempt"),this.lastConnectionAttemptTime_=new Date().getTime(),this.lastConnectionEstablishedTime_=null;let e=this.onDataMessage_.bind(this),t=this.onReady_.bind(this),n=this.onRealtimeDisconnect_.bind(this),i=this.id+":"+nf.nextConnectionId_++,r=this.lastSessionId,s=!1,o=null,a=function(){o?o.close():(s=!0,n())};this.realtime_={close:a,sendRequest:function(e){T(o,"sendRequest call when we're not connected not allowed."),o.send
2Request(e)}};let l=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{let[a,h]=await Promise.all([this.authTokenProvider_.getToken(l),this.appCheckTokenProvider_.getToken(l)]);s?tg("getToken() completed but was canceled"):(tg("getToken() completed. Creating connection."),this.authToken_=a&&a.accessToken,this.appCheckToken_=h&&h.token,o=new t3(i,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,e,t,n,e=>{tI(e+" ("+this.repoInfo_.toString()+")"),this.interrupt("server_kill")},r))}catch(e){this.log_("Failed to get token: "+e),s||(this.repoInfo_.nodeAdmin&&tI(e),a())}}}interrupt(e){tg("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){tg("Resuming connection for reason: "+e),delete this.interruptReasons_[e],et(this.interruptReasons_)&&(this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(e){let t=e-new Date().getTime();this.onServerInfoUpdate_({serverTimeOffset:t})}cancelSentTransactions_(){for(let e=0;e<this.outstandingPuts_.length;e++){let t=this.outstandingPuts_[e];t&&"h"in t.request&&t.queued&&(t.onComplete&&t.onComplete("disconnect"),delete this.outstandingPuts_[e],this.outstandingPutCount_--)}0===this.outstandingPutCount_&&(this.outstandingPuts_=[])}onListenRevoked_(e,t){let n;n=t?t.map(e=>tR(e)).join("$"):"default";let i=this.removeListen_(e,n);i&&i.onComplete&&i.onComplete("permission_denied")}removeListen_(e,t){let n;let i=new t9(e).toString();if(this.listens.has(i)){let e=this.listens.get(i);n=e.get(t),e.delete(t),0===e.size&&this.listens.delete(i)}else n=void 0;return n}onAuthRevoked_(e,t){tg("Auth token revoked: "+e+"/"+t),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),("invalid_token"===e||"permission_denied"===e)&&(this.invalidAuthTokenCount_++,this.invalidAuthTokenCount_>=3&&(this.reconnectDelay_=3e4,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(e,t){tg("App check token revoked: "+e+"/"+t),this.appCheckToken_=null,this.forceTokenRefresh_=!0,("invalid_token"===e||"permission_denied"===e)&&(this.invalidAppCheckTokenCount_++,this.invalidAppCheckTokenCount_>=3&&this.appCheckTokenProvider_.notifyForInvalidToken())}onSecurityDebugPacket_(e){this.securityDebugCallback_?this.securityDebugCallback_(e):"msg"in e&&console.log("FIREBASE: "+e.msg.replace(` 3`,` 4FIREBASE: `))}restoreState_(){for(let e of(this.tryAuth(),this.tryAppCheck(),this.listens.values()))for(let t of e.values())this.sendListen_(t);for(let e=0;e<this.outstandingPuts_.length;e++)this.outstandingPuts_[e]&&this.sendPut_(e);for(;this.onDisconnectRequestQueue_.length;){let e=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(e.action,e.pathString,e.data,e.onComplete)}for(let e=0;e<this.outstandingGets_.length;e++)this.outstandingGets_[e]&&this.sendGet_(e)}sendConnectStats_(){let e={};e["sdk.js."+tr.replace(/\./g,"-")]=1,H()?e["framework.cordova"]=1:B()&&(e["framework.reactnative"]=1),this.reportStats(e)}shouldReconnect_(){let e=t5.getInstance().currentlyOnline();return et(this.interruptReasons_)&&e}}nf.nextPersistentConnectionId_=0,nf.nextConnectionId_=0;class n_{constructor(e,t){this.name=e,this.node=t}static Wrap(e,t){return new n_(e,t)}}class nm{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,t){let n=new n_(tE,e),i=new n_(tE,t);return 0!==this.compare(n,i)}minPost(){return n_.MIN}}class ng extends nm{static get __EMPTY_NODE(){return s}static set __EMPTY_NODE(e){s=e}compare(e,t){return tS(e.name,t.name)}isDefinedOn(e){throw E("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,t){return!1}minPost(){return n_.MIN}maxPost(){return new n_(tk,s)}makePost(e,t){return T("string"==typeof e,"KeyIndex indexValue must always be a string."),new n_(e,s)}toString(){return".key"}}let nv=new ng;class ny{constructor(e,t,n,i,r=null){this.isReverse_=i,this.resultGenerator_=r,this.nodeStack_=[];let s=1;for(;!e.isEmpty();)if(s=t?n(e.key,t):1,i&&(s*=-1),s<0)e=this.isReverse_?e.left:e.right;else if(0===s){this.nodeStack_.push(e);break}else this.nodeStack_.push(e),e=this.isReverse_?e.right:e.left}getNext(){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 this.nodeStack_.length>0}peek(){if(0===this.nodeStack_.length)return null;let e=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value}}}class nw{constructor(e,t,n,i,r){this.key=e,this.value=t,this.color=n??nw.RED,this.left=i??nC.EMPTY_NODE,this.right=r??nC.EMPTY_NODE}
4copy(e,t,n,i,r){return new nw(e??this.key,t??this.value,n??this.color,i??this.left,r??this.right)}count(){return this.left.count()+1+this.right.count()}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||!!e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min_(){return this.left.isEmpty()?this:this.left.min_()}minKey(){return this.min_().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let i=this,r=n(e,i.key);return(i=r<0?i.copy(null,null,null,i.left.insert(e,t,n),null):0===r?i.copy(null,t,null,null,null):i.copy(null,null,null,null,i.right.insert(e,t,n))).fixUp_()}removeMin_(){if(this.left.isEmpty())return nC.EMPTY_NODE;let e=this;return e.left.isRed_()||e.left.left.isRed_()||(e=e.moveRedLeft_()),(e=e.copy(null,null,null,e.left.removeMin_(),null)).fixUp_()}remove(e,t){let n,i;if(n=this,0>t(e,n.key))n.left.isEmpty()||n.left.isRed_()||n.left.left.isRed_()||(n=n.moveRedLeft_()),n=n.copy(null,null,null,n.left.remove(e,t),null);else{if(n.left.isRed_()&&(n=n.rotateRight_()),n.right.isEmpty()||n.right.isRed_()||n.right.left.isRed_()||(n=n.moveRedRight_()),0===t(e,n.key)){if(n.right.isEmpty())return nC.EMPTY_NODE;i=n.right.min_(),n=n.copy(i.key,i.value,null,null,n.right.removeMin_())}n=n.copy(null,null,null,null,n.right.remove(e,t))}return n.fixUp_()}isRed_(){return this.color}fixUp_(){let e=this;return e.right.isRed_()&&!e.left.isRed_()&&(e=e.rotateLeft_()),e.left.isRed_()&&e.left.left.isRed_()&&(e=e.rotateRight_()),e.left.isRed_()&&e.right.isRed_()&&(e=e.colorFlip_()),e}moveRedLeft_(){let e=this.colorFlip_();return e.right.left.isRed_()&&(e=(e=(e=e.copy(null,null,null,null,e.right.rotateRight_())).rotateLeft_()).colorFlip_()),e}moveRedRight_(){let e=this.colorFlip_();return e.left.left.isRed_()&&(e=(e=e.rotateRight_()).colorFlip_()),e}rotateLeft_(){let e=this.copy(null,null,nw.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){let e=this.copy(null,null,nw.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip_(){let e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth_(){return Math.pow(2,this.check_())<=this.count()+1}check_(){if(this.isRed_()&&this.left.isRed_())throw Error("Red node has red child("+this.key+","+this.value+")");
4if(this.right.isRed_())throw Error("Right child of ("+this.key+","+this.value+") is red");let e=this.left.check_();if(e!==this.right.check_())throw Error("Black depths differ");return e+(this.isRed_()?0:1)}}nw.RED=!0,nw.BLACK=!1;class nI{copy(e,t,n,i,r){return this}insert(e,t,n){return new nw(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}}class nC{constructor(e,t=nC.EMPTY_NODE){this.comparator_=e,this.root_=t}insert(e,t){return new nC(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,nw.BLACK,null,null))}remove(e){return new nC(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,nw.BLACK,null,null))}get(e){let t,n=this.root_;for(;!n.isEmpty();){if(0===(t=this.comparator_(e,n.key)))return n.value;t<0?n=n.left:t>0&&(n=n.right)}return null}getPredecessorKey(e){let t,n=this.root_,i=null;for(;!n.isEmpty();)if(0===(t=this.comparator_(e,n.key))){if(n.left.isEmpty())return i?i.key:null;for(n=n.left;!n.right.isEmpty();)n=n.right;return n.key}else t<0?n=n.left:t>0&&(i=n,n=n.right);throw Error("Attempted to find predecessor key for a nonexistent key. What gives?")}isEmpty(){return this.root_.isEmpty()}count(){return this.root_.count()}minKey(){return this.root_.minKey()}maxKey(){return this.root_.maxKey()}inorderTraversal(e){return this.root_.inorderTraversal(e)}reverseTraversal(e){return this.root_.reverseTraversal(e)}getIterator(e){return new ny(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new ny(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new ny(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new ny(this.root_,null,this.comparator_,!0,e)}}function nb(e,t){return tS(e.name,t.name)}function nT(e,t){return tS(e,t)}nC.EMPTY_NODE=new nI;let nE=function(e){return"number"==typeof e?"number:"+tD(e):"string:"+e},nk=function(e){if(e.isLeafNode()){let t=e.val();T("string"==typeof t||"number"==typeof t||"object"==typeof t&&Z(t,".sv"),"Priority must be a string or number.")}else T(e===o||e.isEmpty(),"priority of unexpected type.");T(e===o||e.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")};
4class nS{constructor(e,t=nS.__childrenNodeConstructor.EMPTY_NODE){this.value_=e,this.priorityNode_=t,this.lazyHash_=null,T(void 0!==this.value_&&null!==this.value_,"LeafNode shouldn't be created with null/undefined value."),nk(this.priorityNode_)}static set __childrenNodeConstructor(e){a=e}static get __childrenNodeConstructor(){return a}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new nS(this.value_,e)}getImmediateChild(e){return".priority"===e?this.priorityNode_:nS.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return no(e)?this:".priority"===t7(e)?this.priorityNode_:nS.__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:nS.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,t).updatePriority(this.priorityNode_)}updateChild(e,t){let n=t7(e);return null===n?t:t.isEmpty()&&".priority"!==n?this:(T(".priority"!==n||1===ne(e),".priority must be the last token in a path"),this.updateImmediateChild(n,nS.__childrenNodeConstructor.EMPTY_NODE.updateChild(nt(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:"+nE(this.priorityNode_.val())+":");let t=typeof this.value_;e+=t+":","number"===t?e+=tD(this.value_):e+=this.value_,this.lazyHash_=td(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===nS.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof nS.__childrenNodeConstructor?-1:(T(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){let t=typeof e.value_,n=typeof this.value_,i=nS.VALUE_TYPE_ORDER.indexOf(t),r=nS.VALUE_TYPE_ORDER.indexOf(n);return T(i>=0,"Unknown leaf type: "+t),T(r>=0,"Unknown leaf type: "+n),i===r?"object"===n?0:this.value_<e.value_?-1:this.value_===e.value_?0:1:r-i}withIndex(){return this}isIndexed(){return!0}equals(e){return e===this||!!e.isLeafNode()&&this.value_===e.value_&&this.priorityNode_.equals(e.priorityNode_)}}nS.VALUE_TYPE_ORDER=["object","boolean","number","string"];class nP extends nm{compare(e,t){let n=e.node.getPriority(),i=t.node.getPriority(),r=n.compareTo(i);return 0===r?tS(e.name,t.name):r}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return n_.MIN}maxPost(){return new n_(tk,new nS("[PRIORITY-POST]",h))}makePost(e,t){return new n_(t,new nS("[PRIORITY-POST]",l(e)))}toString(){return".priority"}}let nN=new nP,nR=Math.log(2);class nO{constructor(e){this.count=parseInt(Math.log(e+1)/nR,10),this.current_=this.count-1;let t=parseInt(Array(this.count+1).join("1"),2);this.bits_=e+1&t}nextBitIsOne(){let e=!(this.bits_&1<<this.current_);return this.current_--,e}}let nA=function(e,t,n,i){e.sort(t);let r=function(t,i){let s;let o=i-t;if(0===o)return null;if(1===o)return s=e[t],new nw(n?n(s):s,s.node,nw.BLACK,null,null);{let a=parseInt(o/2,10)+t,l=r(t,a),h=r(a+1,i);return s=e[a],new nw(n?n(s):s,s.node,nw.BLACK,l,h)}};return new nC(i||t,function(t){let i=null,s=null,o=e.length,a=function(t,i){let s=o-t,a=o;o-=t;let h=r(s+1,a),c=e[s];l(new nw(n?n(c):c,c.node,i,null,h))},l=function(e){i?i.left=e:s=e,i=e};for(let e=0;e<t.count;++e){let n=t.nextBitIsOne(),i=Math.pow(2,t.count-(e+1));n?a(i,nw.BLACK):(a(i,nw.BLACK),a(i,nw.RED))}return s}(new nO(e.length)))},nD={};class nx{constructor(e,t){this.indexes_=e,this.indexSet_=t}static get Default(){return T(nD&&nN,"ChildrenNode.ts has not been loaded"),c=c||new nx({".priority":nD},{".priority":nN})}get(e){let t=ee(this.indexes_,e);if(!t)throw Error("No index defined for "+e);return t instanceof nC?t:null}hasIndex(e){return Z(this.indexSet_,e.toString())}addIndex(e,t){let n;T(e!==nv,"KeyIndex always exists and isn't meant to be added to the IndexMap.");let i=[],r=!1,s=t.getIterator(n_.Wrap),o=s.getNext();for(;o;)r=r||e.isDefinedOn(o.node),i.push(o),o=s.getNext();n=r?nA(i,e.getCompare()):nD;let a=e.toString(),l=Object.assign({},this.indexSet_);l[a]=e;let h=Object.assign({},this.indexes_);return h[a]=n,new nx(h,l)}addToIndexes(e,t){return new nx(en(this.indexes_,(n,i)=>{let r=ee(this.indexSet_,i);
4if(T(r,"Missing index implementation for "+i),n===nD){if(!r.isDefinedOn(e.node))return nD;{let n=[],i=t.getIterator(n_.Wrap),s=i.getNext();for(;s;)s.name!==e.name&&n.push(s),s=i.getNext();return n.push(e),nA(n,r.getCompare())}}{let i=t.get(e.name),r=n;return i&&(r=r.remove(new n_(e.name,i))),r.insert(e,e.node)}}),this.indexSet_)}removeFromIndexes(e,t){return new nx(en(this.indexes_,n=>{if(n===nD)return n;{let i=t.get(e.name);return i?n.remove(new n_(e.name,i)):n}}),this.indexSet_)}}class nL{constructor(e,t,n){this.children_=e,this.priorityNode_=t,this.indexMap_=n,this.lazyHash_=null,this.priorityNode_&&nk(this.priorityNode_),this.children_.isEmpty()&&T(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}static get EMPTY_NODE(){return u||(u=new nL(new nC(nT),null,nx.Default))}isLeafNode(){return!1}getPriority(){return this.priorityNode_||u}updatePriority(e){return this.children_.isEmpty()?this:new nL(this.children_,e,this.indexMap_)}getImmediateChild(e){if(".priority"===e)return this.getPriority();{let t=this.children_.get(e);return null===t?u:t}}getChild(e){let t=t7(e);return null===t?this:this.getImmediateChild(t).getChild(nt(e))}hasChild(e){return null!==this.children_.get(e)}updateImmediateChild(e,t){if(T(t,"We should always be passing snapshot nodes"),".priority"===e)return this.updatePriority(t);{let n,i;let r=new n_(e,t);t.isEmpty()?(n=this.children_.remove(e),i=this.indexMap_.removeFromIndexes(r,this.children_)):(n=this.children_.insert(e,t),i=this.indexMap_.addToIndexes(r,this.children_));let s=n.isEmpty()?u:this.priorityNode_;return new nL(n,s,i)}}updateChild(e,t){let n=t7(e);if(null===n)return t;{T(".priority"!==t7(e)||1===ne(e),".priority must be the last token in a path");let i=this.getImmediateChild(n).updateChild(nt(e),t);return this.updateImmediateChild(n,i)}}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(e){if(this.isEmpty())return null;let t={},n=0,i=0,r=!0;if(this.forEachChild(nN,(s,o)=>{t[s]=o.val(e),n++,r&&nL.INTEGER_REGEXP_.test(s)?i=Math.max(i,Number(s)):r=!1}),e||!r||!(i<2*n))return e&&!this.getPriority().isEmpty()&&(t[".priority"]=this.getPriority().val()),t;{let e=[];for(let n in t)e[n]=t[n];return e}}hash(){if(null===this.lazyHash_){let e="";this.getPriority().isEmpty()||(e+="priority:"+nE(this.getPriority().val())+":"),this.forEachChild(nN,(t,n)=>{let i=n.hash();""!==i&&(e+=":"+t+":"+i)}),this.lazyHash_=""===e?"":td(e)}return this.lazyHash_}getPredecessorChildName(e,t,n){let i=this.resolveIndex_(n);if(!i)return this.children_.getPredecessorKey(e);{let n=i.getPredecessorKey(new n_(e,t));return n?n.name:null}}getFirstChildName(e){let t=this.resolveIndex_(e);if(!t)return this.children_.minKey();{let e=t.minKey();return e&&e.name}}getFirstChild(e){let t=this.getFirstChildName(e);return t?new n_(t,this.children_.get(t)):null}getLastChildName(e){let t=this.resolveIndex_(e);if(!t)return this.children_.maxKey();{let e=t.maxKey();return e&&e.name}}getLastChild(e){let t=this.getLastChildName(e);return t?new n_(t,this.children_.get(t)):null}forEachChild(e,t){let n=this.resolveIndex_(e);return n?n.inorderTraversal(e=>t(e.name,e.node)):this.children_.inorderTraversal(t)}getIterator(e){return this.getIteratorFrom(e.minPost(),e)}getIteratorFrom(e,t){let n=this.resolveIndex_(t);if(n)return n.getIteratorFrom(e,e=>e);{let n=this.children_.getIteratorFrom(e.name,n_.Wrap),i=n.peek();for(;null!=i&&0>t.compare(i,e);)n.getNext(),i=n.peek();return n}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(e,t){let n=this.resolveIndex_(t);if(n)return n.getReverseIteratorFrom(e,e=>e);{let n=this.children_.getReverseIteratorFrom(e.name,n_.Wrap),i=n.peek();for(;null!=i&&t.compare(i,e)>0;)n.getNext(),i=n.peek();return n}}compareTo(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===nF?-1:0}withIndex(e){if(e===nv||this.indexMap_.hasIndex(e))return this;{let t=this.indexMap_.addIndex(e,this.children_);return new nL(this.children_,this.priorityNode_,t)}}isIndexed(e){return e===nv||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;
4if(e.isLeafNode()||!this.getPriority().equals(e.getPriority())||this.children_.count()!==e.children_.count())return!1;{let t=this.getIterator(nN),n=e.getIterator(nN),i=t.getNext(),r=n.getNext();for(;i&&r;){if(i.name!==r.name||!i.node.equals(r.node))return!1;i=t.getNext(),r=n.getNext()}return null===i&&null===r}}resolveIndex_(e){return e===nv?null:this.indexMap_.get(e.toString())}}nL.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;class nM extends nL{constructor(){super(new nC(nT),nL.EMPTY_NODE,nx.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return nL.EMPTY_NODE}isEmpty(){return!1}}let nF=new nM;function nU(e,t=null){if(null===e)return nL.EMPTY_NODE;if("object"==typeof e&&".priority"in e&&(t=e[".priority"]),T(null===t||"string"==typeof t||"number"==typeof t||"object"==typeof t&&".sv"in t,"Invalid priority type found: "+typeof t),"object"==typeof e&&".value"in e&&null!==e[".value"]&&(e=e[".value"]),"object"!=typeof e||".sv"in e)return new nS(e,nU(t));if(e instanceof Array){let n=nL.EMPTY_NODE;return tA(e,(t,i)=>{if(Z(e,t)&&"."!==t.substring(0,1)){let e=nU(i);(e.isLeafNode()||!e.isEmpty())&&(n=n.updateImmediateChild(t,e))}}),n.updatePriority(nU(t))}{let n=[],i=!1;if(tA(e,(e,t)=>{if("."!==e.substring(0,1)){let r=nU(t);r.isEmpty()||(i=i||!r.getPriority().isEmpty(),n.push(new n_(e,r)))}}),0===n.length)return nL.EMPTY_NODE;let r=nA(n,nb,e=>e.name,nT);if(!i)return new nL(r,nU(t),nx.Default);{let e=nA(n,nN.getCompare());return new nL(r,nU(t),new nx({".priority":e},{".priority":nN}))}}}Object.defineProperties(n_,{MIN:{value:new n_(tE,nL.EMPTY_NODE)},MAX:{value:new n_(tk,nF)}}),ng.__EMPTY_NODE=nL.EMPTY_NODE,nS.__childrenNodeConstructor=nL,o=nF,h=nF,l=nU;class nq extends nm{constructor(e){super(),this.indexPath_=e,T(!no(e)&&".priority"!==t7(e),"Can't create PathIndex with empty path or .priority key")}extractChild(e){return e.getChild(this.indexPath_)}isDefinedOn(e){return!e.getChild(this.indexPath_).isEmpty()}compare(e,t){let n=this.extractChild(e.node),i=this.extractChild(t.node),r=n.compareTo(i);return 0===r?tS(e.name,t.name):r}makePost(e,t){let n=nU(e);return new n_(t,nL.EMPTY_NODE.updateChild(this.indexPath_,n))}maxPost(){return new n_(tk,nL.EMPTY_NODE.updateChild(this.indexPath_,nF))}toString(){return ni(this.indexPath_,0).join("/")}}class nj extends nm{compare(e,t){let n=e.node.compareTo(t.node);return 0===n?tS(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){return new n_(t,nU(e))}toString(){return".value"}}let nW=new nj;function nV(e){return{type:"value",snapshotNode:e}}function nH(e,t){return{type:"child_added",snapshotNode:t,childName:e}}function nB(e,t){return{type:"child_removed",snapshotNode:t,childName:e}}function nz(e,t,n){return{type:"child_changed",snapshotNode:t,childName:e,oldSnap:n}}class n${constructor(e){this.index_=e}updateChild(e,t,n,i,r,s){T(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");let o=e.getImmediateChild(t);return o.getChild(i).equals(n.getChild(i))&&o.isEmpty()===n.isEmpty()||(null!=s&&(n.isEmpty()?e.hasChild(t)?s.trackChildChange(nB(t,o)):T(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):o.isEmpty()?s.trackChildChange(nH(t,n)):s.trackChildChange(nz(t,n,o))),e.isLeafNode()&&n.isEmpty())?e:e.updateImmediateChild(t,n).withIndex(this.index_)}updateFullNode(e,t,n){return null!=n&&(e.isLeafNode()||e.forEachChild(nN,(e,i)=>{t.hasChild(e)||n.trackChildChange(nB(e,i))}),t.isLeafNode()||t.forEachChild(nN,(t,i)=>{if(e.hasChild(t)){let r=e.getImmediateChild(t);r.equals(i)||n.trackChildChange(nz(t,i,r))}else n.trackChildChange(nH(t,i))})),t.withIndex(this.index_)}updatePriority(e,t){return e.isEmpty()?nL.EMPTY_NODE:e.updatePriority(t)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}class nK{constructor(e){this.indexedFilter_=new n$(e.getIndex()),this.index_=e.getIndex(),this.startPost_=nK.getStartPost_(e),this.endPost_=nK.getEndPost_(e),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){let t=this.startIsInclusive_?0>=this.index_.compare(this.getStartPost(),e):0>this.index_.compare(this.getStartPost(),e),n=this.endIsInclusive_?0>=this.index_.compare(e,this.getEndPost()):0>this.index_.compare(e,this.getEndPost());return t&&n}updateChild(e,t,n,i,r,s){return this.matches(new n_(t,n))||(n=nL.EMPTY_NODE),this.indexedFilter_.updateChild(e,t,n,i,r,s)}updateFullNode(e,t,n){t.isLeafNode()&&(t=nL.EMPTY_NODE);let i=t.withIndex(this.index_);i=i.updatePriority(nL.EMPTY_NODE);let r=this;return t.forEachChild(nN,(e,t)=>{r.matches(new n_(e,t))||(i=i.updateImmediateChild(e,nL.EMPTY_NODE))}),this.indexedFilter_.updateFullNode(e,i,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){if(!e.hasStart())return e.getIndex().minPost();{let t=e.getIndexStartName();return e.getIndex().makePost(e.getIndexStartValue(),t)}}static getEndPost_(e){if(!e.hasEnd())return e.getIndex().maxPost();{let t=e.getIndexEndName();return e.getIndex().makePost(e.getIndexEndValue(),t)}}}class nG{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=>{let t=this.index_.compare(this.rangedFilter_.getStartPost(),e);return this.startIsInclusive_?t<=0:t<0},this.withinEndPost=e=>{let t=this.index_.compare(e,this.rangedFilter_.getEndPost());return this.endIsInclusive_?t<=0:t<0}
4,this.rangedFilter_=new nK(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,i,r,s){return this.rangedFilter_.matches(new n_(t,n))||(n=nL.EMPTY_NODE),e.getImmediateChild(t).equals(n)?e:e.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(e,t,n,i,r,s):this.fullLimitUpdateChild_(e,t,n,r,s)}updateFullNode(e,t,n){let i;if(t.isLeafNode()||t.isEmpty())i=nL.EMPTY_NODE.withIndex(this.index_);else if(2*this.limit_<t.numChildren()&&t.isIndexed(this.index_)){let e;i=nL.EMPTY_NODE.withIndex(this.index_),e=this.reverse_?t.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):t.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_);let n=0;for(;e.hasNext()&&n<this.limit_;){let t=e.getNext();if(this.withinDirectionalStart(t)){if(this.withinDirectionalEnd(t))i=i.updateImmediateChild(t.name,t.node),n++;else break}}}else{let e;i=(i=t.withIndex(this.index_)).updatePriority(nL.EMPTY_NODE),e=this.reverse_?i.getReverseIterator(this.index_):i.getIterator(this.index_);let n=0;for(;e.hasNext();){let t=e.getNext();n<this.limit_&&this.withinDirectionalStart(t)&&this.withinDirectionalEnd(t)?n++:i=i.updateImmediateChild(t.name,nL.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(e,i,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}fullLimitUpdateChild_(e,t,n,i,r){let s;if(this.reverse_){let e=this.index_.getCompare();s=(t,n)=>e(n,t)}else s=this.index_.getCompare();T(e.numChildren()===this.limit_,"");let o=new n_(t,n),a=this.reverse_?e.getFirstChild(this.index_):e.getLastChild(this.index_),l=this.rangedFilter_.matches(o);if(!e.hasChild(t))return n.isEmpty()?e:l&&s(a,o)>=0?(null!=r&&(r.trackChildChange(nB(a.name,a.node)),r.trackChildChange(nH(t,n))),e.updateImmediateChild(t,n).updateImmediateChild(a.name,nL.EMPTY_NODE)):e;{let h=e.getImmediateChild(t),c=i.getChildAfterChild(this.index_,a,this.reverse_);for(;null!=c&&(c.name===t||e.hasChild(c.name));)c=i.getChildAfterChild(this.index_,c,this.reverse_);let u=null==c?1:s(c,o);if(l&&!n.isEmpty()&&u>=0)return null!=r&&r.trackChildChange(nz(t,n,h)),e.updateImmediateChild(t,n);{null!=r&&r.trackChildChange(nB(t,h));let n=e.updateImmediateChild(t,nL.EMPTY_NODE);return null!=c&&this.rangedFilter_.matches(c)?(null!=r&&r.trackChildChange(nH(c.name,c.node)),n.updateImmediateChild(c.name,c.node)):n}}}}class nY{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_=nN}hasStart(){return this.startSet_}isViewFromLeft(){return""===this.viewFrom_?this.startSet_:"l"===this.viewFrom_}getIndexStartValue(){return T(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return T(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:tE}hasEnd(){return this.endSet_}getIndexEndValue(){return T(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return T(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:tk}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&""!==this.viewFrom_}getLimit(){return T(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_===nN}copy(){let e=new nY;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 nJ(e){let t;let n={};if(e.isDefault())return n;
4if(e.index_===nN?t="$priority":e.index_===nW?t="$value":e.index_===nv?t="$key":(T(e.index_ instanceof nq,"Unrecognized index type!"),t=e.index_.toString()),n.orderBy=Y(t),e.startSet_){let t=e.startAfterSet_?"startAfter":"startAt";n[t]=Y(e.indexStartValue_),e.startNameSet_&&(n[t]+=","+Y(e.indexStartName_))}if(e.endSet_){let t=e.endBeforeSet_?"endBefore":"endAt";n[t]=Y(e.indexEndValue_),e.endNameSet_&&(n[t]+=","+Y(e.indexEndName_))}return e.limitSet_&&(e.isViewFromLeft()?n.limitToFirst=e.limit_:n.limitToLast=e.limit_),n}function nQ(e){let t={};if(e.startSet_&&(t.sp=e.indexStartValue_,e.startNameSet_&&(t.sn=e.indexStartName_),t.sin=!e.startAfterSet_),e.endSet_&&(t.ep=e.indexEndValue_,e.endNameSet_&&(t.en=e.indexEndName_),t.ein=!e.endBeforeSet_),e.limitSet_){t.l=e.limit_;let n=e.viewFrom_;""===n&&(n=e.isViewFromLeft()?"l":"r"),t.vf=n}return e.index_!==nN&&(t.i=e.index_.toString()),t}class nX extends t4{constructor(e,t,n,i){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=n,this.appCheckTokenProvider_=i,this.log_=tv("p:rest:"),this.listens_={}}reportStats(e){throw Error("Method not implemented.")}static getListenId_(e,t){return void 0!==t?"tag$"+t:(T(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}listen(e,t,n,i){let r=e._path.toString();this.log_("Listen called for "+r+" "+e._queryIdentifier);let s=nX.getListenId_(e,n),o={};this.listens_[s]=o;let a=nJ(e._queryParams);this.restRequest_(r+".json",a,(e,t)=>{let a=t;404===e&&(a=null,e=null),null===e&&this.onDataUpdate_(r,a,!1,n),ee(this.listens_,s)===o&&i(e?401===e?"permission_denied":"rest_error:"+e:"ok",null)})}unlisten(e,t){let n=nX.getListenId_(e,t);delete this.listens_[n]}get(e){let t=nJ(e._queryParams),n=e._path.toString(),i=new W;return this.restRequest_(n+".json",t,(e,t)=>{let r=t;404===e&&(r=null,e=null),null===e?(this.onDataUpdate_(n,r,!1,null),i.resolve(r)):i.reject(Error(r))}),i.promise}refreshAuthToken(e){}restRequest_(e,t={},n){return t.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then(([i,r])=>{i&&i.accessToken&&(t.auth=i.accessToken),r&&r.token&&(t.ac=r.token);let s=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+e+"?ns="+this.repoInfo_.namespace+es(t);this.log_("Sending REST request for "+s);let o=new XMLHttpRequest;o.onreadystatechange=()=>{if(n&&4===o.readyState){this.log_("REST Response for "+s+" received. status:",o.status,"response:",o.responseText);let e=null;if(o.status>=200&&o.status<300){try{e=G(o.responseText)}catch{tI("Failed to parse JSON response for "+s+": "+o.responseText)}n(null,e)}else 401!==o.status&&404!==o.status&&tI("Got unsuccessful REST response for "+s+" Status: "+o.status),n(o.status);n=null}},o.open("GET",s,!0),o.send()})}}class nZ{constructor(){this.rootNode_=nL.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}function n0(){return{value:null,children:new Map}}function n1(e,t,n){null!==e.value?n(t,e.value):function(e,t){e.children.forEach((e,n)=>{t(n,e)})}(e,(e,i)=>{n1(i,new t9(t.toString()+"/"+e),n)})}class n2{constructor(e){this.collection_=e,this.last_=null}get(){let e=this.collection_.get(),t=Object.assign({},e);return this.last_&&tA(this.last_,(e,n)=>{t[e]=t[e]-n}),this.last_=e,t}}class n3{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new n2(e),tF(this.reportStats_.bind(this),Math.floor(1e4+2e4*Math.random()))}reportStats_(){let e=this.statsListener_.get(),t={},n=!1;tA(e,(e,i)=>{i>0&&Z(this.statsToReport_,e)&&(t[e]=i,n=!0)}),n&&this.server_.reportStats(t),tF(this.reportStats_.bind(this),Math.floor(2*Math.random()*3e5))}}function n4(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function n6(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function n5(e){return{fromUser:!1,fromServer:!0,queryId:e,tagged:!0}}(v=I||(I={}))[v.OVERWRITE=0]="OVERWRITE",v[v.MERGE=1]="MERGE",v[v.ACK_USER_WRITE=2]="ACK_USER_WRITE",v[v.LISTEN_COMPLETE=3]="LISTEN_COMPLETE";class n9{constructor(e,t,n){this.path=e,this.affectedTree=t,this.revert=n,this.type=I.ACK_USER_WRITE,this.source=n4()}operationForChild(e){if(!no(this.path))return T(t7(this.path)===e,"operationForChild called for unrelated child."),new n9(nt(this.path),this.affectedTree,this.revert);if(null!=this.affectedTree.value)return T(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;{let t=this.affectedTree.subtree(new t9(e));return new n9(t8(),t,this.revert)}}}class n8{constructor(e,t){this.source=e,this.path=t,this.type=I.LISTEN_COMPLETE}operationForChild(e){return no(this.path)?new n8(this.source,t8()):new n8(this.source,nt(this.path))}}class n7{constructor(e,t,n){this.source=e,this.path=t,this.snap=n,this.type=I.OVERWRITE}operationForChild(e){return no(this.path)?new n7(this.source,t8(),this.snap.getImmediateChild(e)):new n7(this.source,nt(this.path),this.snap)}}class ie{constructor(e,t,n){this.source=e,this.path=t,this.children=n,this.type=I.MERGE}operationForChild(e){if(!no(this.path))return T(t7(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new ie(this.source,nt(this.path),this.children);{let t=this.children.subtree(new t9(e));return t.isEmpty()?null:t.value?new n7(this.source,t8(),t.value):new ie(this.source,t8(),t)}}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}class it{constructor(e,t,n){this.node_=e,this.fullyInitialized_=t,this.filtered_=n}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(no(e))return this.isFullyInitialized()&&!this.filtered_;let t=t7(e);return this.isCompleteForChild(t)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}class ii{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function ir(e,t,n,i,r,s){let o=i.filter(e=>e.type===n);o.sort((t,n)=>(function(e,t,n){if(null==t.childName||null==n.childName)throw E("Should only compare child_ events.");let i=new n_(t.childName,t.snapshotNode),r=new n_(n.childName,n.snapshotNode);return e.index_.compare(i,r)})(e,t,n)),o.forEach(n=>{let i=("value"===n.type||"child_removed"===n.type||(n.prevName=s.getPredecessorChildName(n.childName,n.snapshotNode,e.index_)),n);r.forEach(r=>{r.respondsTo(n.type)&&t.push(r.createEvent(i,e.query_))})})}function is(e,t){return{eventCache:e,serverCache:t}}function io(e,t,n,i){return is(new it(t,n,i),e.serverCache)}function ia(e,t,n,i){return is(e.eventCache,new it(t,n,i))}function il(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function ih(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}let ic=()=>(d||(d=new nC(tP)),d);class iu{constructor(e,t=ic()){this.value=e,this.children=t}static fromObject(e){let t=new iu(null);return tA(e,(e,n)=>{t=t.set(new t9(e),n)}),t}isEmpty(){return null===this.value&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){if(null!=this.value&&t(this.value))return{path:t8(),value:this.value};if(no(e))return null;{let n=t7(e),i=this.children.get(n);if(null===i)return null;{let r=i.findRootMostMatchingPathAndValue(nt(e),t);return null!=r?{path:ns(new t9(n),r.path),value:r.value}:null}}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,()=>!0)}subtree(e){if(no(e))return this;{let t=t7(e),n=this.children.get(t);return null!==n?n.subtree(nt(e)):new iu(null)}}set(e,t){if(no(e))return new iu(t,this.children);{let n=t7(e),i=(this.children.get(n)||new iu(null)).set(nt(e),t),r=this.children.insert(n,i);return new iu(this.value,r)}}remove(e){if(no(e))return this.children.isEmpty()?new iu(null):new iu(null,this.children);{let t=t7(e),n=this.children.get(t);if(!n)return this;{let i;let r=n.remove(nt(e));return i=r.isEmpty()?this.children.remove(t):this.children.insert(t,r),null===this.value&&i.isEmpty()?new iu(null):new iu(this.value,i)}}}get(e){if(no(e))return this.value;{let t=t7(e),n=this.children.get(t);return n?n.get(nt(e)):null}}setTree(e,t){if(no(e))return t;{let n;let i=t7(e),r=(this.children.get(i)||new iu(null)).setTree(nt(e),t);return n=r.isEmpty()?this.children.remove(i):this.children.insert(i,r),new iu(this.value,
4n)}}fold(e){return this.fold_(t8(),e)}fold_(e,t){let n={};return this.children.inorderTraversal((i,r)=>{n[i]=r.fold_(ns(e,i),t)}),t(e,this.value,n)}findOnPath(e,t){return this.findOnPath_(e,t8(),t)}findOnPath_(e,t,n){let i=!!this.value&&n(t,this.value);if(i)return i;if(no(e))return null;{let i=t7(e),r=this.children.get(i);return r?r.findOnPath_(nt(e),ns(t,i),n):null}}foreachOnPath(e,t){return this.foreachOnPath_(e,t8(),t)}foreachOnPath_(e,t,n){if(no(e))return this;{this.value&&n(t,this.value);let i=t7(e),r=this.children.get(i);return r?r.foreachOnPath_(nt(e),ns(t,i),n):new iu(null)}}foreach(e){this.foreach_(t8(),e)}foreach_(e,t){this.children.inorderTraversal((n,i)=>{i.foreach_(ns(e,n),t)}),this.value&&t(e,this.value)}foreachChild(e){this.children.inorderTraversal((t,n)=>{n.value&&e(t,n.value)})}}class id{constructor(e){this.writeTree_=e}static empty(){return new id(new iu(null))}}function ip(e,t,n){if(no(t))return new id(new iu(n));{let i=e.writeTree_.findRootMostValueAndPath(t);if(null!=i){let r=i.path,s=i.value,o=na(r,t);return s=s.updateChild(o,n),new id(e.writeTree_.set(r,s))}{let i=new iu(n);return new id(e.writeTree_.setTree(t,i))}}}function i_(e,t,n){let i=e;return tA(n,(e,n)=>{i=ip(i,ns(t,e),n)}),i}function im(e,t){return no(t)?id.empty():new id(e.writeTree_.setTree(t,new iu(null)))}function ig(e,t){return null!=iv(e,t)}function iv(e,t){let n=e.writeTree_.findRootMostValueAndPath(t);return null!=n?e.writeTree_.get(n.path).getChild(na(n.path,t)):null}function iy(e){let t=[],n=e.writeTree_.value;return null!=n?n.isLeafNode()||n.forEachChild(nN,(e,n)=>{t.push(new n_(e,n))}):e.writeTree_.children.inorderTraversal((e,n)=>{null!=n.value&&t.push(new n_(e,n.value))}),t}function iw(e,t){if(no(t))return e;{let n=iv(e,t);return new id(null!=n?new iu(n):e.writeTree_.subtree(t))}}function iI(e){return e.writeTree_.isEmpty()}function iC(e,t){return function e(t,n,i){if(null!=n.value)return i.updateChild(t,n.value);{let r=null;return n.children.inorderTraversal((n,s)=>{".priority"===n?(T(null!==s.value,"Priority writes must always be leaf nodes"),r=s.value):i=e(ns(t,n),s,i)}),i.getChild(t).isEmpty()||null===r||(i=i.updateChild(ns(t,".priority"),r)),i}}(t8(),e.writeTree_,t)}function ib(e){return e.visible}function iT(e,t,n){let i=id.empty();for(let r=0;r<e.length;++r){let s=e[r];if(t(s)){let e;let t=s.path;if(s.snap)nh(n,t)?i=ip(i,e=na(n,t),s.snap):nh(t,n)&&(e=na(t,n),i=ip(i,t8(),s.snap.getChild(e)));else if(s.children){if(nh(n,t))i=i_(i,e=na(n,t),s.children);else if(nh(t,n)){if(no(e=na(t,n)))i=i_(i,t8(),s.children);else{let t=ee(s.children,t7(e));if(t){let n=t.getChild(nt(e));i=ip(i,t8(),n)}}}}else throw E("WriteRecord should have .snap or .children")}}return i}function iE(e,t,n,i,r){if(i||r){let s=iw(e.visibleWrites,t);return!r&&iI(s)?n:r||null!=n||ig(s,t8())?iC(iT(e.allWrites,function(e){return(e.visible||r)&&(!i||!~i.indexOf(e.writeId))&&(nh(e.path,t)||nh(t,e.path))},t),n||nL.EMPTY_NODE):null}{let i=iv(e.visibleWrites,t);if(null!=i)return i;{let i=iw(e.visibleWrites,t);return iI(i)?n:null!=n||ig(i,t8())?iC(i,n||nL.EMPTY_NODE):null}}}function ik(e,t,n,i){return iE(e.writeTree,e.treePath,t,n,i)}function iS(e,t){return function(e,t,n){let i=nL.EMPTY_NODE,r=iv(e.visibleWrites,t);if(r)return r.isLeafNode()||r.forEachChild(nN,(e,t)=>{i=i.updateImmediateChild(e,t)}),i;
4if(!n)return iy(iw(e.visibleWrites,t)).forEach(e=>{i=i.updateImmediateChild(e.name,e.node)}),i;{let r=iw(e.visibleWrites,t);return n.forEachChild(nN,(e,t)=>{let n=iC(iw(r,new t9(e)),t);i=i.updateImmediateChild(e,n)}),iy(r).forEach(e=>{i=i.updateImmediateChild(e.name,e.node)}),i}}(e.writeTree,e.treePath,t)}function iP(e,t,n,i){return function(e,t,n,i,r){T(i||r,"Either existingEventSnap or existingServerSnap must exist");let s=ns(t,n);if(ig(e.visibleWrites,s))return null;{let t=iw(e.visibleWrites,s);return iI(t)?r.getChild(n):iC(t,r.getChild(n))}}(e.writeTree,e.treePath,t,n,i)}function iN(e,t){var n,i;return n=e.writeTree,i=ns(e.treePath,t),iv(n.visibleWrites,i)}function iR(e,t,n){return function(e,t,n,i){let r=ns(t,n),s=iv(e.visibleWrites,r);return null!=s?s:i.isCompleteForChild(n)?iC(iw(e.visibleWrites,r),i.getNode().getImmediateChild(n)):null}(e.writeTree,e.treePath,t,n)}function iO(e,t){return iA(ns(e.treePath,t),e.writeTree)}function iA(e,t){return{treePath:e,writeTree:t}}class iD{constructor(){this.changeMap=new Map}trackChildChange(e){let t=e.type,n=e.childName;T("child_added"===t||"child_changed"===t||"child_removed"===t,"Only child changes supported for tracking"),T(".priority"!==n,"Only non-priority child changes can be tracked.");let i=this.changeMap.get(n);if(i){let r=i.type;if("child_added"===t&&"child_removed"===r)this.changeMap.set(n,nz(n,e.snapshotNode,i.snapshotNode));else if("child_removed"===t&&"child_added"===r)this.changeMap.delete(n);else if("child_removed"===t&&"child_changed"===r)this.changeMap.set(n,nB(n,i.oldSnap));else if("child_changed"===t&&"child_added"===r)this.changeMap.set(n,nH(n,e.snapshotNode));else if("child_changed"===t&&"child_changed"===r)this.changeMap.set(n,nz(n,e.snapshotNode,i.oldSnap));else throw E("Illegal combination of changes: "+e+" occurred after "+i)}else this.changeMap.set(n,e)}getChanges(){return Array.from(this.changeMap.values())}}class ix{getCompleteChild(e){return null}getChildAfterChild(e,t,n){return null}}let iL=new ix;class iM{constructor(e,t,n=null){this.writes_=e,this.viewCache_=t,this.optCompleteServerCache_=n}getCompleteChild(e){let t=this.viewCache_.eventCache;if(t.isCompleteForChild(e))return t.getNode().getImmediateChild(e);{let t=null!=this.optCompleteServerCache_?new it(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache;return iR(this.writes_,e,t)}}getChildAfterChild(e,t,n){var i;let r=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:ih(this.viewCache_),s=function(e,t,n,i,r,s,o){let a;let l=iw(e.visibleWrites,t),h=iv(l,t8());if(null!=h)a=h;else{if(null==n)return[];a=iC(l,n)}if((a=a.withIndex(o)).isEmpty()||a.isLeafNode())return[];{let e=[],t=o.getCompare(),n=s?a.getReverseIteratorFrom(i,o):a.getIteratorFrom(i,o),r=n.getNext();for(;r&&e.length<1;)0!==t(r,i)&&e.push(r),r=n.getNext();return e}}((i=this.writes_).writeTree,i.treePath,r,t,0,n,e);return 0===s.length?null:s[0]}}function iF(e,t,n,i,r,s){let o=t.eventCache;if(null!=iN(i,n))return t;{let a,l;if(no(n)){if(T(t.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),t.serverCache.isFiltered()){let n=ih(t),r=iS(i,n instanceof nL?n:nL.EMPTY_NODE);a=e.filter.updateFullNode(t.eventCache.getNode(),r,s)}else{let n=ik(i,ih(t));a=e.filter.updateFullNode(t.eventCache.getNode(),n,s)}}else{let h=t7(n);if(".priority"===h){T(1===ne(n),"Can't have a priority with additional path components");let r=o.getNode(),s=iP(i,n,r,l=t.serverCache.getNode());a=null!=s?e.filter.updatePriority(r,s):o.getNode()}else{let c;let u=nt(n);if(o.isCompleteForChild(h)){l=t.serverCache.getNode();let e=iP(i,n,o.getNode(),l);c=null!=e?o.getNode().getImmediateChild(h).updateChild(u,e):o.getNode().getImmediateChild(h)}else c=iR(i,h,t.serverCache);a=null!=c?e.filter.updateChild(o.getNode(),h,c,u,r,s):o.getNode()}}return io(t,a,o.isFullyInitialized()||no(n),e.filter.filtersNodes())}}function iU(e,t,n,i,r,s,o,a){let l;let h=t.serverCache,c=o?e.filter:e.filter.getIndexedFilter();if(no(n))l=c.updateFullNode(h.getNode(),i,null);else if(c.filtersNodes()&&!h.isFiltered()){let e=h.getNode().updateChild(n,i);l=c.updateFullNode(h.getNode(),e,null)}else{let e=t7(n);if(!h.isCompleteForPath(n)&&ne(n)>1)return t;let r=nt(n),s=h.getNode().getImmediateChild(e).updateChild(r,i);l=".priority"===e?c.updatePriority(h.getNode(),s):c.updateChild(h.getNode(),e,s,r,iL,null)}let u=ia(t,l,h.isFullyInitialized()||no(n),c.filtersNodes()),d=new iM(r,u,s);return iF(e,u,n,r,d,a)}function iq(e,t,n,i,r,s,o){let a,l;let h=t.eventCache,c=new iM(r,t,s);if(no(n))l=e.filter.updateFullNode(t.eventCache.getNode(),i,o),a=io(t,l,!0,e.filter.filtersNodes());else{let r=t7(n);if(".priority"===r)l=e.filter.updatePriority(t.eventCache.getNode(),i),a=io(t,l,h.isFullyInitialized(),h.isFiltered());else{let s;let l=nt(n),u=h.getNode().getImmediateChild(r);if(no(l))s=i;else{let e=c.getCompleteChild(r);s=null!=e?".priority"===nn(l)&&e.getChild(nr(l)).isEmpty()?e:e.updateChild(l,i):nL.EMPTY_NODE}a=u.equals(s)?t:io(t,e.filter.updateChild(h.getNode(),r,s,l,c,o),h.isFullyInitialized(),e.filter.filtersNodes())}}return a}function ij(e,t){return e.eventCache.isCompleteForChild(t)}function iW(e,t,n){return n.foreach((e,n)=>{t=t.updateChild(e,n)}),t}function iV(e,t,n,i,r,s,o,a){if(t.serverCache.getNode().isEmpty()&&!t.serverCache.isFullyInitialized())return t;let l=t,h;h=no(n)?i:new iu(null).setTree(n,i);let c=t.serverCache.getNode();return h.children.inorderTraversal((n,i)=>{if(c.hasChild(n)){let h=iW(e,t.serverCache.getNode().getImmediateChild(n),i);l=iU(e,l,new t9(n),h,r,s,o,a)}}),h.children.inorderTraversal((n,i)=>{let h=!t.serverCache.isCompleteForChild(n)&&null===i.value;if(!c.hasChild(n)&&!h){let h=iW(e,t.serverCache.getNode().getImmediateChild(n),i);l=iU(e,l,new t9(n),h,r,s,o,a)}}),l}class iH{constructor(e,t){this.query_=e,this.eventRegistrations_=[];let n=this.query_._queryParams,i=new n$(n.getIndex()),r=n.loadsAllData()?new n$(n.getIndex()):n.hasLimit()?new nG(n):new nK(n);this.processor_={filter:r};let s=t.serverCache,o=t.eventCache,a=i.updateFullNode(nL.EMPTY_NODE,s.getNode(),null),l=r.updateFullNode(nL.EMPTY_NODE,o.getNode(),null),h=new it(a,s.isFullyInitialized(),i.filtersNodes()),c=new it(l,o.isFullyInitialized(),r.filtersNodes());this.viewCache_=is(c,h),this.eventGenerator_=new ii(this.query_)}get query(){return this.query_}}function iB(e){return 0===e.eventRegistrations_.length}function iz(e,t,n){let i=[];if(n){T(null==t,"A cancel should cancel all event registrations.");let r=e.query._path;
4e.eventRegistrations_.forEach(e=>{let t=e.createCancelEvent(n,r);t&&i.push(t)})}if(t){let n=[];for(let i=0;i<e.eventRegistrations_.length;++i){let r=e.eventRegistrations_[i];if(r.matches(t)){if(t.hasAnyCallback()){n=n.concat(e.eventRegistrations_.slice(i+1));break}}else n.push(r)}e.eventRegistrations_=n}else e.eventRegistrations_=[];return i}function i$(e,t,n,i){var r,s;t.type===I.MERGE&&null!==t.source.queryId&&(T(ih(e.viewCache_),"We should always have a full cache before handling merges"),T(il(e.viewCache_),"Missing event cache, even though we have a server cache"));let o=e.viewCache_,a=function(e,t,n,i,r){let s,o;let a=new iD;if(n.type===I.OVERWRITE)n.source.fromUser?s=iq(e,t,n.path,n.snap,i,r,a):(T(n.source.fromServer,"Unknown source."),o=n.source.tagged||t.serverCache.isFiltered()&&!no(n.path),s=iU(e,t,n.path,n.snap,i,r,o,a));else if(n.type===I.MERGE){var l,h;let c;n.source.fromUser?(l=n.path,h=n.children,c=t,h.foreach((n,s)=>{let o=ns(l,n);ij(t,t7(o))&&(c=iq(e,c,o,s,i,r,a))}),h.foreach((n,s)=>{let o=ns(l,n);ij(t,t7(o))||(c=iq(e,c,o,s,i,r,a))}),s=c):(T(n.source.fromServer,"Unknown source."),o=n.source.tagged||t.serverCache.isFiltered(),s=iV(e,t,n.path,n.children,i,r,o,a))}else if(n.type===I.ACK_USER_WRITE)s=n.revert?function(e,t,n,i,r,s){let o;if(null!=iN(i,n))return t;{let a;let l=new iM(i,t,r),h=t.eventCache.getNode();if(no(n)||".priority"===t7(n)){let n;if(t.serverCache.isFullyInitialized())n=ik(i,ih(t));else{let e=t.serverCache.getNode();T(e instanceof nL,"serverChildren would be complete if leaf node"),n=iS(i,e)}a=e.filter.updateFullNode(h,n,s)}else{let r=t7(n),c=iR(i,r,t.serverCache);null==c&&t.serverCache.isCompleteForChild(r)&&(c=h.getImmediateChild(r)),(a=null!=c?e.filter.updateChild(h,r,c,nt(n),l,s):t.eventCache.getNode().hasChild(r)?e.filter.updateChild(h,r,nL.EMPTY_NODE,nt(n),l,s):h).isEmpty()&&t.serverCache.isFullyInitialized()&&(o=ik(i,ih(t))).isLeafNode()&&(a=e.filter.updateFullNode(a,o,s))}return o=t.serverCache.isFullyInitialized()||null!=iN(i,t8()),io(t,a,o,e.filter.filtersNodes())}}(e,t,n.path,i,r,a):function(e,t,n,i,r,s,o){if(null!=iN(r,n))return t;let a=t.serverCache.isFiltered(),l=t.serverCache;if(null!=i.value){if(no(n)&&l.isFullyInitialized()||l.isCompleteForPath(n))return iU(e,t,n,l.getNode().getChild(n),r,s,a,o);if(!no(n))return t;{let i=new iu(null);return l.getNode().forEachChild(nv,(e,t)=>{i=i.set(new t9(e),t)}),iV(e,t,n,i,r,s,a,o)}}{let h=new iu(null);return i.foreach((e,t)=>{let i=ns(n,e);l.isCompleteForPath(i)&&(h=h.set(e,l.getNode().getChild(i)))}),iV(e,t,n,h,r,s,a,o)}}(e,t,n.path,n.affectedTree,i,r,a);else if(n.type===I.LISTEN_COMPLETE)s=function(e,t,n,i,r){let s=t.serverCache;return iF(e,ia(t,s.getNode(),s.isFullyInitialized()||no(n),s.isFiltered()),n,i,iL,r)}(e,t,n.path,i,a);else throw E("Unknown operation type: "+n.type);let c=a.getChanges();return function(e,t,n){let i=t.eventCache;if(i.isFullyInitialized()){let r=i.getNode().isLeafNode()||i.getNode().isEmpty(),s=il(e);!(n.length>0)&&e.eventCache.isFullyInitialized()&&(!r||i.getNode().equals(s))&&i.getNode().getPriority().equals(s.getPriority())||n.push(nV(il(t)))}}(t,s,c),{viewCache:s,changes:c}}(e.processor_,o,t,n,i);return r=e.processor_,T((s=a.viewCache).eventCache.getNode().isIndexed(r.filter.getIndex()),"Event snap not indexed"),T(s.serverCache.getNode().isIndexed(r.filter.getIndex()),"Server snap not indexed"),T(a.viewCache.serverCache.isFullyInitialized()||!o.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),e.viewCache_=a.viewCache,iK(e,a.changes,a.viewCache.eventCache.getNode(),null)}function iK(e,t,n,i){let r=i?[i]:e.eventRegistrations_;return function(e,t,n,i){let r=[],s=[];return t.forEach(t=>{var n;"child_changed"===t.type&&e.index_.indexedValueChanged(t.oldSnap,t.snapshotNode)&&s.push((n=t.childName,{type:"child_moved",snapshotNode:t.snapshotNode,childName:n}))}),ir(e,r,"child_removed",t,i,n),ir(e,r,"child_added",t,i,n),ir(e,r,"child_moved",s,i,n),ir(e,r,"child_changed",t,i,n),ir(e,r,"value",t,i,n),r}(e.eventGenerator_,t,n,r)}class iG{constructor(){this.views=new Map}}function iY(e,t,n,i){let r=t.source.queryId;if(null!==r){let s=e.views.get(r);
4return T(null!=s,"SyncTree gave us an op for an invalid query."),i$(s,t,n,i)}{let r=[];for(let s of e.views.values())r=r.concat(i$(s,t,n,i));return r}}function iJ(e,t,n,i,r){let s=t._queryIdentifier,o=e.views.get(s);if(!o){let e=ik(n,r?i:null),s=!1;return e?s=!0:(e=i instanceof nL?iS(n,i):nL.EMPTY_NODE,s=!1),new iH(t,is(new it(e,s,!1),new it(i,r,!1)))}return o}function iQ(e){let t=[];for(let n of e.views.values())n.query._queryParams.loadsAllData()||t.push(n);return t}function iX(e,t){let n=null;for(let i of e.views.values())n=n||function(e,t){let n=ih(e.viewCache_);return n&&(e.query._queryParams.loadsAllData()||!no(t)&&!n.getImmediateChild(t7(t)).isEmpty())?n.getChild(t):null}(i,t);return n}function iZ(e,t){if(t._queryParams.loadsAllData())return i1(e);{let n=t._queryIdentifier;return e.views.get(n)}}function i0(e){return null!=i1(e)}function i1(e){for(let t of e.views.values())if(t.query._queryParams.loadsAllData())return t;return null}let i2=1;class i3{constructor(e){this.listenProvider_=e,this.syncPointTree_=new iu(null),this.pendingWriteTree_={visibleWrites:id.empty(),allWrites:[],lastWriteId:-1},this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function i4(e,t,n=!1){let i=function(e,t){for(let n=0;n<e.allWrites.length;n++){let i=e.allWrites[n];if(i.writeId===t)return i}return null}(e.pendingWriteTree_,t);if(!function(e,t){let n=e.allWrites.findIndex(e=>e.writeId===t);T(n>=0,"removeWrite called with nonexistent writeId.");let i=e.allWrites[n];e.allWrites.splice(n,1);let r=i.visible,s=!1,o=e.allWrites.length-1;for(;r&&o>=0;){let t=e.allWrites[o];t.visible&&(o>=n&&function(e,t){if(e.snap)return nh(e.path,t);for(let n in e.children)if(e.children.hasOwnProperty(n)&&nh(ns(e.path,n),t))return!0;return!1}(t,i.path)?r=!1:nh(i.path,t.path)&&(s=!0)),o--}return!!r&&(s?(e.visibleWrites=iT(e.allWrites,ib,t8()),e.allWrites.length>0?e.lastWriteId=e.allWrites[e.allWrites.length-1].writeId:e.lastWriteId=-1):i.snap?e.visibleWrites=im(e.visibleWrites,i.path):tA(i.children,t=>{e.visibleWrites=im(e.visibleWrites,ns(i.path,t))}),!0)}(e.pendingWriteTree_,t))return[];{let t=new iu(null);return null!=i.snap?t=t.set(t8(),!0):tA(i.children,e=>{t=t.set(new t9(e),!0)}),i7(e,new n9(i.path,t,n))}}function i6(e,t,n){return i7(e,new n7(n6(),t,n))}function i5(e,t,n,i,r=!1){let s=t._path,o=e.syncPointTree_.get(s),a=[];if(o&&("default"===t._queryIdentifier||null!=iZ(o,t))){let l=function(e,t,n,i){let r=t._queryIdentifier,s=[],o=[],a=i0(e);if("default"===r)for(let[t,r]of e.views.entries())o=o.concat(iz(r,n,i)),iB(r)&&(e.views.delete(t),r.query._queryParams.loadsAllData()||s.push(r.query));else{let t=e.views.get(r);t&&(o=o.concat(iz(t,n,i)),iB(t)&&(e.views.delete(r),t.query._queryParams.loadsAllData()||s.push(t.query)))}return a&&!i0(e)&&s.push(new(T(p,"Reference.ts has not been loaded"),p)(t._repo,t._path)),{removed:s,events:o}}(o,t,n,i);0===o.views.size&&(e.syncPointTree_=e.syncPointTree_.remove(s));let h=l.removed;if(a=l.events,!r){let n=-1!==h.findIndex(e=>e._queryParams.loadsAllData()),r=e.syncPointTree_.findOnPath(s,(e,t)=>i0(t));if(n&&!r){let t=e.syncPointTree_.subtree(s);if(!t.isEmpty()){let n=t.fold((e,t,n)=>{if(t&&i0(t))return[i1(t)];{let e=[];return t&&(e=iQ(t)),tA(n,(t,n)=>{e=e.concat(n)}),e}});for(let t=0;t<n.length;++t){let i=n[t],r=i.query,s=re(e,i);e.listenProvider_.startListening(ro(r),rt(e,r),s.hashFn,s.onComplete)}}}r||!(h.length>0)||i||(n?e.listenProvider_.stopListening(ro(t),null):h.forEach(t=>{let n=e.queryToTagMap.get(rn(t));e.listenProvider_.stopListening(ro(t),n)}))}!function(e,t){for(let n=0;n<t.length;++n){let i=t[n];if(!i._queryParams.loadsAllData()){let t=rn(i),n=e.queryToTagMap.get(t);e.queryToTagMap.delete(t),e.tagToQueryMap.delete(n)}}}(e,h)}return a}function i9(e,t,n,i){let r=ri(e,i);if(null==r)return[];{let i=rr(r),s=i.path,o=i.queryId,a=na(s,t);return rs(e,s,new n7(n5(o),a,n))}}function i8(e,t,n){let i=e.pendingWriteTree_,r=e.syncPointTree_.findOnPath(t,(e,n)=>{let i=iX(n,na(e,t));if(i)return i});return iE(i,t,r,n,!0)}function i7(e,t){var n;return function e(t,n,i,r){if(no(t.path))return function e(t,n,i,r){let s=n.get(t8());null==i&&null!=s&&(i=iX(s,t8()));let o=[];return n.children.inorderTraversal((n,s)=>{let a=i?i.getImmediateChild(n):null,l=iO(r,n),h=t.operationForChild(n);
4h&&(o=o.concat(e(h,s,a,l)))}),s&&(o=o.concat(iY(s,t,r,i))),o}(t,n,i,r);{let s=n.get(t8());null==i&&null!=s&&(i=iX(s,t8()));let o=[],a=t7(t.path),l=t.operationForChild(a),h=n.children.get(a);if(h&&l){let t=i?i.getImmediateChild(a):null,n=iO(r,a);o=o.concat(e(l,h,t,n))}return s&&(o=o.concat(iY(s,t,r,i))),o}}(t,e.syncPointTree_,null,(n=e.pendingWriteTree_,iA(t8(),n)))}function re(e,t){let n=t.query,i=rt(e,n);return{hashFn:()=>(t.viewCache_.serverCache.getNode()||nL.EMPTY_NODE).hash(),onComplete:t=>{if("ok"===t){var r;return i?function(e,t,n){let i=ri(e,n);if(!i)return[];{let n=rr(i),r=n.path,s=n.queryId,o=na(r,t);return rs(e,r,new n8(n5(s),o))}}(e,n._path,i):(r=n._path,i7(e,new n8(n6(),r)))}{let i=function(e,t){let n="Unknown Error";"too_big"===e?n="The data requested exceeds the maximum size that can be accessed with a single request.":"permission_denied"===e?n="Client doesn't have permission to access the desired data.":"unavailable"===e&&(n="The service is unavailable");let i=Error(e+" at "+t._path.toString()+": "+n);return i.code=e.toUpperCase(),i}(t,n);return i5(e,n,null,i)}}}}function rt(e,t){let n=rn(t);return e.queryToTagMap.get(n)}function rn(e){return e._path.toString()+"$"+e._queryIdentifier}function ri(e,t){return e.tagToQueryMap.get(t)}function rr(e){let t=e.indexOf("$");return T(-1!==t&&t<e.length-1,"Bad queryKey."),{queryId:e.substr(t+1),path:new t9(e.substr(0,t))}}function rs(e,t,n){let i=e.syncPointTree_.get(t);return T(i,"Missing sync point for query tag that we're tracking"),iY(i,n,iA(t,e.pendingWriteTree_),null)}
4function ro(e){return e._queryParams.loadsAllData()&&!e._queryParams.isDefault()?new(T(f,"Reference.ts has not been loaded"),f)(e._repo,e._path):e}class ra{constructor(e){this.node_=e}getImmediateChild(e){return new ra(this.node_.getImmediateChild(e))}node(){return this.node_}}class rl{constructor(e,t){this.syncTree_=e,this.path_=t}getImmediateChild(e){let t=ns(this.path_,e);return new rl(this.syncTree_,t)}node(){return i8(this.syncTree_,this.path_)}}let rh=function(e,t,n){return e&&"object"==typeof e?(T(".sv"in e,"Unexpected leaf node or priority contents"),"string"==typeof e[".sv"])?rc(e[".sv"],t,n):"object"==typeof e[".sv"]?ru(e[".sv"],t):void T(!1,"Unexpected server value: "+JSON.stringify(e,null,2)):e},rc=function(e,t,n){if("timestamp"===e)return n.timestamp;T(!1,"Unexpected server value: "+e)},ru=function(e,t,n){e.hasOwnProperty("increment")||T(!1,"Unexpected server value: "+JSON.stringify(e,null,2));let i=e.increment;"number"!=typeof i&&T(!1,"Unexpected increment value: "+i);let r=t.node();if(T(null!==r&&"u">typeof r,"Expected ChildrenNode.EMPTY_NODE for nulls"),!r.isLeafNode())return i;let s=r.getValue();return"number"!=typeof s?i:s+i};function rd(e,t,n){let i;let r=rh(e.getPriority().val(),t.getImmediateChild(".priority"),n);if(!e.isLeafNode())return i=e,r!==e.getPriority().val()&&(i=i.updatePriority(new nS(r))),e.forEachChild(nN,(e,r)=>{let s=rd(r,t.getImmediateChild(e),n);s!==r&&(i=i.updateImmediateChild(e,s))}),i;{let i=rh(e.getValue(),t,n);return i!==e.getValue()||r!==e.getPriority().val()?new nS(i,nU(r)):e}}class rp{constructor(e="",t=null,n={children:{},childCount:0}){this.name=e,this.parent=t,this.node=n}}function rf(e,t){let n=t instanceof t9?t:new t9(t),i=e,r=t7(n);for(;null!==r;){let e=ee(i.node.children,r)||{children:{},childCount:0};i=new rp(r,i,e),r=t7(n=nt(n))}return i}function r_(e){return e.node.value}function rm(e,t){e.node.value=t,function e(t){null!==t.parent&&function(t,n,i){let r=void 0===r_(i)&&!rg(i),s=Z(t.node.children,n);r&&s?(delete t.node.children[n],t.node.childCount--,e(t)):r||s||(t.node.children[n]=i.node,t.node.childCount++,e(t))}(t.parent,t.name,t)}(e)}function rg(e){return e.node.childCount>0}function rv(e,t){tA(e.node.children,(n,i)=>{t(new rp(n,e,i))})}function ry(e){return new t9(null===e.parent?e.name:ry(e.parent)+"/"+e.name)}let rw=/[\[\].#$\/\u0000-\u001F\u007F]/,rI=/[\[\].#$\u0000-\u001F\u007F]/,rC=function(e){return"string"==typeof e&&0!==e.length&&!rw.test(e)},rb=function(e){return"string"==typeof e&&0!==e.length&&!rI.test(e)},rT=function(e,t,n){let i=n instanceof t9?new nc(n,e):n;if(void 0===t)throw Error(e+"contains undefined "+nd(i));if("function"==typeof t)throw Error(e+"contains a function "+nd(i)+" with contents = "+t.toString());if(tb(t))throw Error(e+"contains "+t.toString()+" "+nd(i));if("string"==typeof t&&t.length>3495253.3333333335&&ep(t)>10485760)throw Error(e+"contains a string greater than 10485760 utf8 bytes "+nd(i)+" ('"+t.substring(0,50)+"...')");if(t&&"object"==typeof t){let n=!1,r=!1;if(tA(t,(t,s)=>{if(".value"===t)n=!0;else if(".priority"!==t&&".sv"!==t&&(r=!0,!rC(t)))throw Error(e+" contains an invalid key ("+t+") "+nd(i)+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');i.parts_.length>0&&(i.byteLength_+=1),i.parts_.push(t),i.byteLength_+=ep(t),nu(i),rT(e,s,i),function(e){let t=e.parts_.pop();e.byteLength_-=ep(t),e.parts_.length>0&&(e.byteLength_-=1)}(i)}),n&&r)throw Error(e+' contains ".value" child '+nd(i)+" in addition to actual children.")}},rE=function(e,t,n,i){if(!rb(n))throw Error(eu(e,t)+'was an invalid path = "'+n+'". Paths must be non-empty strings and can\'t contain ".", "#", "$", "[", or "]"')},rk=function(e,t,n,i){n&&(n=n.replace(/^\/*\.info(\/|$)/,"/")),rE(e,t,n)},rS=function(e,t){var n;let i=t.path.toString();if("string"!=typeof t.repoInfo.host||0===t.repoInfo.host.length||!rC(t.repoInfo.namespace)&&"localhost"!==t.repoInfo.host.split(":")[0]||0!==i.length&&((n=i)&&(n=n.replace(/^\/*\.info(\/|$)/,"/")),!rb(n)))throw Error(eu(e,"url")+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')};class rP{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function rN(e,t,n){(function(e,t){let n=null;for(let i=0;i<t.length;i++){let r=t[i],s=r.getPath();null===n||nl(s,n.path)||(e.eventLists_.push(n),n=null),null===n&&(n={events:[],path:s}),n.events.push(r)}n&&e.eventLists_.push(n)})(e,n),function(e,t){e.recursionDepth_++;let n=!0;for(let i=0;i<e.eventLists_.length;i++){let r=e.eventLists_[i];r&&(t(r.path)?(function(e){for(let t=0;t<e.events.length;t++){let n=e.events[t];if(null!==n){e.events[t]=null;let i=n.getEventRunner();tf&&tg("event: "+n.toString()),tM(i)}}}(e.eventLists_[i]),e.eventLists_[i]=null):n=!1)}n&&(e.eventLists_=[]),e.recursionDepth_--}(e,e=>nh(e,t)||nh(t,e))}class rR{constructor(e,t,n,i){this.repoInfo_=e,this.forceRestClient_=t,this.authTokenProvider_=n,this.appCheckProvider_=i,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new rP,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=n0(),this.transactionQueueTree_=new rp,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function rO(e){var t;return(t=t={timestamp:function(e){let t=e.infoData_.getNode(new t9(".info/serverTimeOffset")).val()||0;return new Date().getTime()+t}(e)}).timestamp=t.timestamp||new Date().getTime(),t}function rA(e,t,n,i,r){e.dataUpdateCount++;let s=new t9(t);n=e.interceptServerDataCallback_?e.interceptServerDataCallback_(t,n):n;let o=[];if(r){if(i){let t=en(n,e=>nU(e));o=function(e,t,n,i){let r=ri(e,i);if(!r)return[];{let i=rr(r),s=i.path,o=i.queryId,a=na(s,t),l=iu.fromObject(n);return rs(e,s,new ie(n5(o),a,l))}}(e.serverSyncTree_,s,t,r)}else{let t=nU(n);o=i9(e.serverSyncTree_,s,t,r)}}else if(i){let t=en(n,e=>nU(e));o=function(e,t,n){let i=iu.fromObject(n);return i7(e,new ie(n6(),t,i))}(e.serverSyncTree_,s,t)}else{let t=nU(n);o=i6(e.serverSyncTree_,s,t)}let a=s;o.length>0&&(a=rF(e,s)),rN(e.eventQueue_,a,o)}function rD(e,t){rx(e,"connected",t),!1===t&&function(e){rL(e,"onDisconnectEvents");let t=rO(e),n=n0();n1(e.onDisconnect_,t8(),(i,r)=>{let s=rd(r,new rl(e.serverSyncTree_,i),t);!function e(t,n,i){if(no(n))t.value=i,t.children.clear();else if(null!==t.value)t.value=t.value.updateChild(n,i);else{let r=t7(n);t.children.has(r)||t.children.set(r,n0()),e(t.children.get(r),n=nt(n),i)}}(n,i,s)});let i=[];n1(n,t8(),(t,n)=>{i=i.concat(i6(e.serverSyncTree_,t,n));let r=function(e,t){let n=ry(rU(e,t)),i=rf(e.transactionQueueTree_,t);return function(e,t,n){let i=e.parent;for(;null!==i;){if(t(i))return!0;
4i=i.parent}}(i,t=>{rW(e,t)}),rW(e,i),function e(t,n,i,r){i&&n(t),rv(t,t=>{e(t,n,!0)})}(i,t=>{rW(e,t)}),n}(e,t);rF(e,r)}),e.onDisconnect_=n0(),rN(e.eventQueue_,t8(),i)}(e)}function rx(e,t,n){let i=new t9("/.info/"+t),r=nU(n);e.infoData_.updateSnapshot(i,r);let s=i6(e.infoSyncTree_,i,r);rN(e.eventQueue_,i,s)}function rL(e,...t){let n="";e.persistentConnection_&&(n=e.persistentConnection_.id+":"),tg(n,...t)}function rM(e,t,n){return i8(e.serverSyncTree_,t,n)||nL.EMPTY_NODE}function rF(e,t){let n=rU(e,t),i=ry(n),r=rq(e,n);return function(e,t,n){if(0===t.length)return;let i=[],r=[],s=t.filter(e=>0===e.status).map(e=>e.currentWriteId);for(let o=0;o<t.length;o++){let a=t[o],l=na(n,a.path),h=!1,c;if(T(null!==l,"rerunTransactionsUnderNode_: relativePath should not be null."),4===a.status)h=!0,c=a.abortReason,r=r.concat(i4(e.serverSyncTree_,a.currentWriteId,!0));else if(0===a.status){if(a.retryCount>=25)h=!0,c="maxretry",r=r.concat(i4(e.serverSyncTree_,a.currentWriteId,!0));else{let n=rM(e,a.path,s);a.currentInputSnapshot=n;let i=t[o].update(n.val());if(void 0!==i){rT("transaction failed: Data returned ",i,a.path);let t=nU(i);"object"==typeof i&&null!=i&&Z(i,".priority")||(t=t.updatePriority(n.getPriority()));let o=a.currentWriteId,l=rO(e),h=rd(t,new ra(n),l);a.currentOutputSnapshotRaw=t,a.currentOutputSnapshotResolved=h,a.currentWriteId=e.nextWriteId_++,s.splice(s.indexOf(o),1),r=(r=r.concat(function(e,t,n,i,r){var s,o;return s=e.pendingWriteTree_,o=r,T(i>s.lastWriteId,"Stacking an older write on top of newer ones"),void 0===o&&(o=!0),s.allWrites.push({path:t,snap:n,writeId:i,visible:o}),o&&(s.visibleWrites=ip(s.visibleWrites,t,n)),s.lastWriteId=i,r?i7(e,new n7(n4(),t,n)):[]}(e.serverSyncTree_,a.path,h,a.currentWriteId,a.applyLocally))).concat(i4(e.serverSyncTree_,o,!0))}else h=!0,c="nodata",r=r.concat(i4(e.serverSyncTree_,a.currentWriteId,!0))}}rN(e.eventQueue_,n,r),r=[],h&&(t[o].status=2,setTimeout(t[o].unwatcher,Math.floor(0)),t[o].onComplete&&("nodata"===c?i.push(()=>t[o].onComplete(null,!1,t[o].currentInputSnapshot)):i.push(()=>t[o].onComplete(Error(c),!1,null))))}rj(e,e.transactionQueueTree_);for(let e=0;e<i.length;e++)tM(i[e]);(function e(t,n=t.transactionQueueTree_){if(n||rj(t,n),r_(n)){let i=rq(t,n);T(i.length>0,"Sending zero length transaction queue"),i.every(e=>0===e.status)&&function(t,n,i){let r=rM(t,n,i.map(e=>e.currentWriteId)),s=r,o=r.hash();for(let e=0;e<i.length;e++){let t=i[e];T(0===t.status,"tryToSendTransactionQueue_: items in queue should all be run."),t.status=1,t.retryCount++;let r=na(n,t.path);s=s.updateChild(r,t.currentOutputSnapshotRaw)}let a=s.val(!0);t.server_.put(n.toString(),a,r=>{rL(t,"transaction put response",{path:n.toString(),status:r});let s=[];if("ok"===r){let r=[];for(let e=0;e<i.length;e++)i[e].status=2,s=s.concat(i4(t.serverSyncTree_,i[e].currentWriteId)),i[e].onComplete&&r.push(()=>i[e].onComplete(null,!0,i[e].currentOutputSnapshotResolved)),i[e].unwatcher();rj(t,rf(t.transactionQueueTree_,n)),e(t,t.transactionQueueTree_),rN(t.eventQueue_,n,s);for(let e=0;e<r.length;e++)tM(r[e])}else{if("datastale"===r)for(let e=0;e<i.length;e++)3===i[e].status?i[e].status=4:i[e].status=0;else{tI("transaction at "+n.toString()+" failed: "+r);for(let e=0;e<i.length;e++)i[e].status=4,i[e].abortReason=r}rF(t,n)}},o)}(t,ry(n),i)}else rg(n)&&rv(n,n=>{e(t,n)})})(e,e.transactionQueueTree_)}(e,r,i),i}function rU(e,t){let n,i=e.transactionQueueTree_;for(n=t7(t);null!==n&&void 0===r_(i);)i=rf(i,n),n=t7(t=nt(t));return i}function rq(e,t){let n=[];return function e(t,n,i){let r=r_(n);if(r)for(let e=0;e<r.length;e++)i.push(r[e]);rv(n,n=>{e(t,n,i)})}(e,t,n),n.sort((e,t)=>e.order-t.order),n}function rj(e,t){let n=r_(t);if(n){let e=0;for(let t=0;t<n.length;t++)2!==n[t].status&&(n[e]=n[t],e++);n.length=e,rm(t,n.length>0?n:void 0)}rv(t,t=>{rj(e,t)})}function rW(e,t){let n=r_(t);if(n){let i=[],r=[],s=-1;for(let t=0;t<n.length;t++)3===n[t].status||(1===n[t].status?(T(s===t-1,"All SENT items should be at beginning of queue."),s=t,n[t].status=3,n[t].abortReason="set"):(T(0===n[t].status,"Unexpected transaction status in abort"),n[t].unwatcher(),r
4=r.concat(i4(e.serverSyncTree_,n[t].currentWriteId,!0)),n[t].onComplete&&i.push(n[t].onComplete.bind(null,Error("set"),!1,null))));-1===s?rm(t,void 0):n.length=s+1,rN(e.eventQueue_,ry(t),r);for(let e=0;e<i.length;e++)tM(i[e])}}let rV=function(e,t){let n=rH(e),i=n.namespace;"firebase.com"===n.domain&&tw(n.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),i&&"undefined"!==i||"localhost"===n.domain||tw("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),n.secure||tC();let r="ws"===n.scheme||"wss"===n.scheme;return{repoInfo:new tB(n.host,n.secure,i,r,t,"",i!==n.subdomain),path:new t9(n.pathString)}},rH=function(e){let t="",n="",i="",r="",s="",o=!0,a="https",l=443;if("string"==typeof e){let h=e.indexOf("//");h>=0&&(a=e.substring(0,h-1),e=e.substring(h+2));let c=e.indexOf("/");-1===c&&(c=e.length);let u=e.indexOf("?");-1===u&&(u=e.length),t=e.substring(0,Math.min(c,u)),c<u&&(r=function(e){let t="",n=e.split("/");for(let e=0;e<n.length;e++)if(n[e].length>0){let i=n[e];try{i=decodeURIComponent(i.replace(/\+/g," "))}catch{}t+="/"+i}return t}(e.substring(c,u)));let d=function(e){let t={};for(let n of("?"===e.charAt(0)&&(e=e.substring(1)),e.split("&"))){if(0===n.length)continue;let i=n.split("=");2===i.length?t[decodeURIComponent(i[0])]=decodeURIComponent(i[1]):tI(`Invalid query segment '${n}' in query '${e}'`)}return t}(e.substring(Math.min(e.length,u)));(h=t.indexOf(":"))>=0?(o="https"===a||"wss"===a,l=parseInt(t.substring(h+1),10)):h=t.length;let p=t.slice(0,h);if("localhost"===p.toLowerCase())n="localhost";else if(p.split(".").length<=2)n=p;else{let e=t.indexOf(".");i=t.substring(0,e).toLowerCase(),n=t.substring(e+1),s=i}"ns"in d&&(s=d.ns)}return{host:t,port:l,domain:n,subdomain:i,secure:o,scheme:a,pathString:r,namespace:s}};class rB{constructor(e,t,n,i){this.eventType=e,this.eventRegistration=t,this.snapshot=n,this.prevName=i}getPath(){let e=this.snapshot.ref;return"value"===this.eventType?e._path:e.parent._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+Y(this.snapshot.exportVal())}}class rz{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 r${constructor(e,t){this.snapshotCallback=e,this.cancelCallback=t}onValue(e,t){this.snapshotCallback.call(null,e,t)}onCancel(e){return T(this.hasCancelCallback,"Raising a cancel event on a listener with no cancel callback"),this.cancelCallback.call(null,e)}get hasCancelCallback(){return!!this.cancelCallback}matches(e){return this.snapshotCallback===e.snapshotCallback||void 0!==this.snapshotCallback.userCallback&&this.snapshotCallback.userCallback===e.snapshotCallback.userCallback&&this.snapshotCallback.context===e.snapshotCallback.context}}class rK{constructor(e,t,n,i){this._repo=e,this._path=t,this._queryParams=n,this._orderByCalled=i}get key(){return no(this._path)?null:nn(this._path)}get ref(){return new rG(this._repo,this._path)}get _queryIdentifier(){let e=tR(nQ(this._queryParams));return"{}"===e?"default":e}get _queryObject(){return nQ(this._queryParams)}isEqual(e){if(!((e=ef(e))instanceof rK))return!1;let t=this._repo===e._repo,n=nl(this._path,e._path),i=this._queryIdentifier===e._queryIdentifier;return t&&n&&i}toJSON(){return this.toString()}toString(){return this._repo.toString()+function(e){let t="";for(let n=e.pieceNum_;n<e.pieces_.length;n++)""!==e.pieces_[n]&&(t+="/"+encodeURIComponent(String(e.pieces_[n])));return t||"/"}(this._path)}}class rG extends rK{constructor(e,t){super(e,t,new nY,!1)}get parent(){let e=nr(this._path);return null===e?null:new rG(this._repo,e)}get root(){let e=this;for(;null!==e.parent;)e=e.parent;return e}}class rY{constructor(e,t,n){this._node=e,this.ref=t,this._index=n}get priority(){return this._node.getPriority().val()}get key(){return this.ref.key}get size(){return this._node.numChildren()}child(e){let t=new t9(e),n=rQ(this.ref,e);return new rY(this._node.getChild(t),n,nN)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(e){return!this._node.isLeafNode()&&!!this._node.forEachChild(this._index,(t,n)=>e(new rY(n,rQ(this.ref,t),nN)))}hasChild(e){let t=new t9(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 rJ(e,t){return(e=ef(e))._checkNotDeleted("ref"),void 0!==t?rQ(e._root,t):e._root}function rQ(e,t){return null===t7((e=ef(e))._path)?rk("child","path",t):rE("child","path",t),new rG(e._repo,ns(e._path,t))}function rX(e){e=ef(e);let t=new rZ(new r$(()=>{}));return(function(e,t,n){let i=function(e,t){var n;let i=t._path,r=null;e.syncPointTree_.foreachOnPath(i,(e,t)=>{let n=na(e,i);r=r||iX(t,n)});let s=e.syncPointTree_.get(i);s?r=r||iX(s,t8()):(s=new iG,e.syncPointTree_=e.syncPointTree_.set(i,s));let o=null!=r,a=o?new it(r,!0,!1):null,l=(n=e.pendingWriteTree_,iA(t._path,n));return il(iJ(s,t,l,o?a.getNode():nL.EMPTY_NODE,o).viewCache_)}(e.serverSyncTree_,t);return null!=i?Promise.resolve(i):e.server_.get(t).then(i=>{let r;let s=nU(i).withIndex(t._queryParams.getIndex());if(!function(e,t,n,i=!1){let r;let s=t._path,o=null,a=!1;e.syncPointTree_.foreachOnPath(s,(e,t)=>{let n=na(e,s);o=o||iX(t,n),a=a||i0(t)});let l=e.syncPointTree_.get(s);l?(a=a||i0(l),o=o||iX(l,t8())):(l=new iG,e.syncPointTree_=e.syncPointTree_.set(s,l)),null!=o?r=!0:(r=!1,o=nL.EMPTY_NODE,e.syncPointTree_.subtree(s).foreachChild((e,t)=>{let n=iX(t,t8());n&&(o=o.updateImmediateChild(e,n))}));let h=null!=iZ(l,t);if(!h&&!t._queryParams.loadsAllData()){let n=rn(t);T(!e.queryToTagMap.has(n),"View does not exist, but we have a tag");let i=i2++;e.queryToTagMap.set(n,i),e.tagToQueryMap.set(i,n)}let c=function(e,t,n,i,r,s){let o=iJ(e,t,i,r,s);return e.views.has(t._queryIdentifier)||e.views.set(t._queryIdentifier,o),function(e,t){e.eventRegistrations_.push(t)}(o,n),function(e,t){let n=e.viewCache_.eventCache,i=[];
4return n.getNode().isLeafNode()||n.getNode().forEachChild(nN,(e,t)=>{i.push(nH(e,t))}),n.isFullyInitialized()&&i.push(nV(n.getNode())),iK(e,i,n.getNode(),t)}(o,n)}(l,t,n,iA(s,e.pendingWriteTree_),o,r);if(!h&&!a&&!i){let n=iZ(l,t);c=c.concat(function(e,t,n){let i=t._path,r=rt(e,t),s=re(e,n),o=e.listenProvider_.startListening(ro(t),r,s.hashFn,s.onComplete),a=e.syncPointTree_.subtree(i);if(r)T(!i0(a.value),"If we're adding a query, it shouldn't be shadowed");else{let t=a.fold((e,t,n)=>{if(!no(e)&&t&&i0(t))return[i1(t).query];{let e=[];return t&&(e=e.concat(iQ(t).map(e=>e.query))),tA(n,(t,n)=>{e=e.concat(n)}),e}});for(let n=0;n<t.length;++n){let i=t[n];e.listenProvider_.stopListening(ro(i),rt(e,i))}}return o}(e,t,n))}}(e.serverSyncTree_,t,n,!0),t._queryParams.loadsAllData())r=i6(e.serverSyncTree_,t._path,s);else{let n=rt(e.serverSyncTree_,t);r=i9(e.serverSyncTree_,t._path,s,n)}return rN(e.eventQueue_,t._path,r),i5(e.serverSyncTree_,t,n,null,!0),s},n=>(rL(e,"get for query "+Y(t)+" failed: "+n),Promise.reject(Error(n))))})(e._repo,e,t).then(t=>new rY(t,new rG(e._repo,e._path),e._queryParams.getIndex()))}class rZ{constructor(e){this.callbackContext=e}respondsTo(e){return"value"===e}createEvent(e,t){let n=t._queryParams.getIndex();return new rB("value",this,new rY(e.snapshotNode,new rG(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 rz(this,e,t):null}matches(e){return e instanceof rZ&&(!e.callbackContext||!this.callbackContext||e.callbackContext.matches(this.callbackContext))}hasAnyCallback(){return null!==this.callbackContext}}T(!p,"__referenceConstructor has already been defined"),p=rG,T(!f,"__referenceConstructor has already been defined"),f=rG;let r0={};class r1{constructor(e,t){this._repoInternal=e,this.app=t,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(function(e,t,n){if(e.stats_=tY(e.repoInfo_),e.forceRestClient_||("object"==typeof window&&window.navigator&&window.navigator.userAgent||"").search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)>=0)e.server_=new nX(e.repoInfo_,(t,n,i,r)=>{rA(e,t,n,i,r)},e.authTokenProvider_,e.appCheckProvider_),setTimeout(()=>rD(e,!0),0);else{if("u">typeof n&&null!==n){if("object"!=typeof n)throw Error("Only objects are supported for option databaseAuthVariableOverride");try{Y(n)}catch(e){throw Error("Invalid authOverride provided: "+e)}}e.persistentConnection_=new nf(e.repoInfo_,t,(t,n,i,r)=>{rA(e,t,n,i,r)},t=>{rD(e,t)},t=>{tA(t,(t,n)=>{rx(e,t,n)})},e.authTokenProvider_,e.appCheckProvider_,n),e.server_=e.persistentConnection_}e.authTokenProvider_.addTokenChangeListener(t=>{e.server_.refreshAuthToken(t)}),e.appCheckProvider_.addTokenChangeListener(t=>{e.server_.refreshAppCheckToken(t.token)}),e.statsReporter_=function(e,t){let n=e.toString();return tG[n]||(tG[n]=t()),tG[n]}(e.repoInfo_,()=>new n3(e.stats_,e.server_)),e.infoData_=new nZ,e.infoSyncTree_=new i3({startListening:(t,n,i,r)=>{let s=[],o=e.infoData_.getNode(t._path);return o.isEmpty()||(s=i6(e.infoSyncTree_,t._path,o),setTimeout(()=>{r("ok")},0)),s},stopListening:()=>{}}),rx(e,"connected",!1),e.serverSyncTree_=new i3({startListening:(t,n,i,r)=>(e.server_.listen(t,i,n,(n,i)=>{let s=r(n,i);rN(e.eventQueue_,t._path,s)}),[]),stopListening:(t,n)=>{e.server_.unlisten(t,n)}})}(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new rG(this._repo,t8())),this._rootInternal}_delete(){return null!==this._rootInternal&&(function(e,t){let n=r0[t];n&&n[e.key]===e||tw(`Database ${t}(${e.repoInfo_}) has already been deleted.`),e.persistentConnection_&&e.persistentConnection_.interrupt("repo_interrupt"),delete n[e.key]}(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){null===this._rootInternal&&tw("Cannot call "+e+" on a deleted database.")}}function r2(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&0>t.indexOf(i)&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,i=Object.getOwnPropertySymbols(e);r<i.length;r++)0>t.indexOf(i[r])&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]]);return n}function r3(){return{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}}nf.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)},nf.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)},tr=eX,eK(new e_("database",(e,{instanceIdentifier:t})=>(function(e,t,n,i,r){var s,o;let a,l,h=i||e.options.databaseURL;void 0===h&&(e.options.projectId||tw("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),tg("Using default host for project ",e.options.projectId),h=`${e.options.projectId}-default-rtdb.firebaseio.com`);
4let c=rV(h,void 0),u=c.repoInfo,d;"u">typeof b&&b.env&&(d=b.env.FIREBASE_DATABASE_EMULATOR_HOST),d?u=(c=rV(h=`http://${d}?ns=${u.namespace}`,void 0)).repoInfo:c.repoInfo.secure;let p=new tq(e.name,e.options,t);return rS("Invalid Firebase Database URL",c),no(c.path)||tw("Database URL must point to the root of a Firebase Database (not including a child path)."),new r1((s=u,o=new tU(e.name,n),(a=r0[e.name])||(a={},r0[e.name]=a),(l=a[s.toURLString()])&&tw("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call."),l=new rR(s,!1,p,o),a[s.toURLString()]=l,l),e)})(e.getProvider("app").getImmediate(),e.getProvider("auth-internal"),e.getProvider("app-check-internal"),t),"PUBLIC").setMultipleInstances(!0)),e1(tn,ti,void 0),e1(tn,ti,"esm2017"),e1("firebase","10.14.1","app");let r4=new $("auth","Firebase",r3()),r6=new eb("@firebase/auth");function r5(e,...t){r6.logLevel<=w.ERROR&&r6.error(`Auth (${eX}): ${e}`,...t)}function r9(e,...t){throw st(e,...t)}function r8(e,...t){return st(e,...t)}function r7(e,t,n){return new $("auth","Firebase",Object.assign(Object.assign({},r3()),{[t]:n})).create(t,{appName:e.name})}function se(e){return r7(e,"operation-not-supported-in-this-environment","Operations that alter the current user are not supported in conjunction with FirebaseServerApp")}function st(e,...t){if("string"!=typeof e){let n=t[0],i=[...t.slice(1)];return i[0]&&(i[0].appName=e.name),e._errorFactory.create(n,...i)}return r4.create(e,...t)}function sn(e,t,...n){if(!e)throw st(t,...n)}function si(e){let t="INTERNAL ASSERTION FAILED: "+e;throw r5(t),Error(t)}function sr(){var e;return"u">typeof self&&(null===(e=self.location)||void 0===e?void 0:e.href)||""}function ss(){var e;return"u">typeof self&&(null===(e=self.location)||void 0===e?void 0:e.protocol)||null}class so{constructor(e,t){var n;this.shortDelay=e,this.longDelay=t,n="Short delay should be less than long delay!",t>e||si(n),this.isMobile=H()||B()}get(){return!("u">typeof navigator&&navigator&&"onLine"in navigator&&"boolean"==typeof navigator.onLine&&("http:"===ss()||"https:"===ss()||function(){let e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}()||"connection"in navigator))||navigator.onLine?this.isMobile?this.longDelay:this.shortDelay:Math.min(5e3,this.shortDelay)}}function sa(e,t){var n,i;n=e.emulator,i="Emulator should always be set here",n||si(i);let{url:r}=e.emulator;return t?`${r}${t.startsWith("/")?t.slice(1):t}`:r}class sl{static initialize(e,t,n){this.fetchImpl=e,t&&(this.headersImpl=t),n&&(this.responseImpl=n)}static fetch(){return this.fetchImpl?this.fetchImpl:"u">typeof self&&"fetch"in self?self.fetch:"u">typeof globalThis&&globalThis.fetch?globalThis.fetch:"u">typeof fetch?fetch:void si("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static headers(){return this.headersImpl?this.headersImpl:"u">typeof self&&"Headers"in self?self.Headers:"u">typeof globalThis&&globalThis.Headers?globalThis.Headers:"u">typeof Headers?Headers:void si("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static response(){return this.responseImpl?this.responseImpl:"u">typeof self&&"Response"in self?self.Response:"u">typeof globalThis&&globalThis.Response?globalThis.Response:"u">typeof Response?Response:void si("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}}let sh={CREDENTIAL_MISMATCH:"custom-token-mismatch",MISSING_CUSTOM_TOKEN:"internal-error",INVALID_IDENTIFIER:"invalid-email",MISSING_CONTINUE_URI:"internal-error",INVALID_PASSWORD:"wrong-password",MISSING_PASSWORD:"missing-password",INVALID_LOGIN_CREDENTIALS:"invalid-credential",EMAIL_EXISTS:"email-already-in-use",PASSWORD_LOGIN_DISABLED:"operation-not-allowed",INVALID_IDP_RESPONSE:"invalid-credential",INVALID_PENDING_TOKEN:"invalid-credential",FEDERATED_USER_ID_ALREADY_LINKED:"credential-already-in-use",MISSING_REQ_TYPE:"internal-error",EMAIL_NOT_FOUND:"user-not-found",RESET_PASSWORD_EXCEED_LIMIT:"too-many-requests",EXPIRED_OOB_CODE:"expired-action-code",INVALID_OOB_CODE:"invalid-action-code",MISSING_OOB_CODE:"internal-error",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"requires-recent-login",INVALID_ID_TOKEN:"invalid-user-token",TOKEN_EXPIRED:"user-token-expired",USER_NOT_FOUND:"user-token-expired",TOO_MANY_ATTEMPTS_TRY_LATER:"too-many-requests",PASSWORD_DOES_NOT_MEET_REQUIREMENTS:"password-does-not-meet-requirements",INVALID_CODE:"invalid-verification-code",INVALID_SESSION_INFO:"invalid-verification-id",INVALID_TEMPORARY_PROOF:"invalid-credential",MISSING_SESSION_INFO:"missing-verification-id",SESSION_EXPIRED:"code-expired",MISSING_ANDROID_PACKAGE_NAME:"missing-android-pkg-name",UNAUTHORIZED_DOMAIN:"unauthorized-continue-uri",INVALID_OAUTH_CLIENT_ID:"invalid-oauth-client-id",ADMIN_ONLY_OPERATION:"admin-restricted-operation",INVALID_MFA_PENDING_CREDENTIAL:"invalid-multi-factor-session",MFA_ENROLLMENT_NOT_FOUND:"multi-factor-info-not-found",MISSING_MFA_ENROLLMENT_ID:"missing-multi-factor-info",MISSING_MFA_PENDING_CREDENTIAL:"missing-multi-factor-session",SECOND_FACTOR_EXISTS:"second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"maximum-second-factor-count-exceeded",BLOCKING_FUNCTION_ERROR_RESPONSE:"internal-error",RECAPTCHA_NOT_ENABLED:"recaptcha-not-enabled",MISSING_RECAPTCHA_TOKEN:"missing-rec
4aptcha-token",INVALID_RECAPTCHA_TOKEN:"invalid-recaptcha-token",INVALID_RECAPTCHA_ACTION:"invalid-recaptcha-action",MISSING_CLIENT_TYPE:"missing-client-type",MISSING_RECAPTCHA_VERSION:"missing-recaptcha-version",INVALID_RECAPTCHA_VERSION:"invalid-recaptcha-version",INVALID_REQ_TYPE:"invalid-req-type"},sc=new so(3e4,6e4);function su(e,t){return e.tenantId&&!t.tenantId?Object.assign(Object.assign({},t),{tenantId:e.tenantId}):t}async function sd(e,t,n,i,r={}){return sp(e,r,async()=>{let r={},s={};i&&("GET"===t?s=i:r={body:JSON.stringify(i)});let o=es(Object.assign({key:e.config.apiKey},s)).slice(1),a=await e._getAdditionalHeaders();a["Content-Type"]="application/json",e.languageCode&&(a["X-Firebase-Locale"]=e.languageCode);let l=Object.assign({method:t,headers:a},r);return"u">typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||(l.referrerPolicy="no-referrer"),sl.fetch()(s_(e,e.config.apiHost,n,o),l)})}async function sp(e,t,n){e._canInitEmulator=!1;let i=Object.assign(Object.assign({},sh),t);try{let t=new sm(e),r=await Promise.race([n(),t.promise]);t.clearNetworkTimeout();let s=await r.json();if("needConfirmation"in s)throw sg(e,"account-exists-with-different-credential",s);if(r.ok&&!("errorMessage"in s))return s;{let[t,n]=(r.ok?s.errorMessage:s.error.message).split(" : ");if("FEDERATED_USER_ID_ALREADY_LINKED"===t)throw sg(e,"credential-already-in-use",s);if("EMAIL_EXISTS"===t)throw sg(e,"email-already-in-use",s);if("USER_DISABLED"===t)throw sg(e,"user-disabled",s);let o=i[t]||t.toLowerCase().replace(/[_\s]+/g,"-");if(n)throw r7(e,o,n);r9(e,o)}}catch(t){if(t instanceof z)throw t;r9(e,"network-request-failed",{message:String(t)})}}async function sf(e,t,n,i,r={}){let s=await sd(e,t,n,i,r);return"mfaPendingCredential"in s&&r9(e,"multi-factor-auth-required",{_serverResponse:s}),s}function s_(e,t,n,i){let r=`${t}${n}?${i}`;return e.config.emulator?sa(e.config,r):`${e.config.apiScheme}://${r}`}class sm{constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((e,t)=>{this.timer=setTimeout(()=>t(r8(this.auth,"network-request-failed")),sc.get())})}clearNetworkTimeout(){clearTimeout(this.timer)}}function sg(e,t,n){let i={appName:e.name};n.email&&(i.email=n.email),n.phoneNumber&&(i.phoneNumber=n.phoneNumber);let r=r8(e,t,i);return r.customData._tokenResponse=n,r}function sv(e){return void 0!==e&&void 0!==e.enterprise}class sy{constructor(e){if(this.siteKey="",this.recaptchaEnforcementState=[],void 0===e.recaptchaKey)throw Error("recaptchaKey undefined");this.siteKey=e.recaptchaKey.split("/")[3],this.recaptchaEnforcementState=e.recaptchaEnforcementState}getProviderEnforcementState(e){if(!this.recaptchaEnforcementState||0===this.recaptchaEnforcementState.length)return null;for(let t of this.recaptchaEnforcementState)if(t.provider&&t.provider===e)return function(e){switch(e){case"ENFORCE":return"ENFORCE";case"AUDIT":return"AUDIT";case"OFF":return"OFF";default:return"ENFORCEMENT_STATE_UNSPECIFIED"}}(t.enforcementState);return null}isProviderEnabled(e){return"ENFORCE"===this.getProviderEnforcementState(e)||"AUDIT"===this.getProviderEnforcementState(e)}}async function sw(e,t){return sd(e,"GET","/v2/recaptchaConfig",su(e,t))}async function sI(e,t){return sd(e,"POST","/v1/accounts:delete",t)}async function sC(e,t){return sd(e,"POST","/v1/accounts:lookup",t)}function sb(e){if(e)try{let t=new Date(Number(e));if(!isNaN(t.getTime()))return t.toUTCString()}catch{}}async function sT(e,t=!1){let n=ef(e),i=await n.getIdToken(t),r=sk(i);sn(r&&r.exp&&r.auth_time&&r.iat,n.auth,"internal-error");let s="object"==typeof r.firebase?r.firebase:void 0,o=null==s?void 0:s.sign_in_provider;return{claims:r,token:i,authTime:sb(sE(r.auth_time)),issuedAtTime:sb(sE(r.iat)),expirationTime:sb(sE(r.exp)),signInProvider:o||null,signInSecondFactor:(null==s?void 0:s.sign_in_second_factor)||null}}function sE(e){return 1e3*Number(e)}function sk(e){let[t,n,i]=e.split(".");if(void 0===t||void 0===n||void 0===i)return r5("JWT malformed, contained fewer than 3 sections"),null;try{let e=A(n);return e?JSON.parse(e):(r5("Failed to decode base64 JWT payload"),null)}catch(e){return r5("Caught error parsing JWT payload as JSON",null==e?void 0:e.toString()),null}}function sS(e){let t=sk(e);return sn(t,"internal-error"),sn("u">typeof t.exp,"internal-error"),sn("u">typeof t.iat,"internal-error"),Number(t.exp)-Number(t.iat)}async function sP(e,t,n=!1){if(n)return t;try{return await t}catch(t){throw t instanceof z&&function({code:e}){return"auth/user-disabled"===e||"auth/user-token-expired"===e}(t)&&e.auth.currentUser===e&&await e.auth.signOut(),t}}class sN{constructor(e){this.user=e,this.isRunning=!1,this.timerId=null,this.errorBackoff=3e4}_start(){this.isRunning||(this.isRunning=!0,this.schedule())}_stop(){this.isRunning&&(this.isRunning=!1,null!==this.timerId&&clearTimeout(this.timerId))}getInterval(e){var t;if(!e)return this.errorBackoff=3e4,Math.max(0,(null!==(t=this.user.stsTokenManager.expirationTime)&&void 0!==t?t:0)-Date.now()-3e5);{let e=this.errorBackoff;return this.errorBackoff=Math.min(2*this.errorBackoff,96e4),e}}schedule(e=!1){if(!this.isRunning)return;let t=this.getInterval(e);this.timerId=setTimeout(async()=>{await this.iteration()},t)}async iteration(){try{await this.user.getIdToken(!0)}catch(e){(null==e?void 0:e.code)==="auth/network-request-failed"&&this.schedule(!0);return}this.schedule()}}class sR{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=sb(this.lastLoginAt),this.creationTime=sb(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function sO(e){var t;let n=e.auth,i=await e.getIdToken(),r=await sP(e,sC(n,{idToken:i}));sn(null==r?void 0:r.users.length,n,"internal-error");let s=r.users[0];e._notifyReloadListener(s);let o=!(null===(t=s.providerUserInfo)||void 0===t)&&t.length?sD(s.providerUserInfo):[],a=[...e.providerData.filter(e=>!o.some(t=>t.providerId===e.providerId)),...o],l=e.isAnonymous,h=!(e.email&&s.passwordHash)&&!(null!=a&&a.length);Object.assign(e,{uid:s.localId,displayName:s.displayName||null,photoURL:s.photoUrl||null,email:s.email||null,emailVerified:s.emailVerified||!1,phoneNumber:s.phoneNumber||null,tenantId:s.tenantId||null,providerData:a,metadata:new sR(s.createdAt,s.lastLoginAt),isAnonymous:!!l&&h})}async function sA(e){let t=ef(e);await sO(t),await t.auth._persistUserIfCurrent(t),t.auth._notifyListenersIfCurrent(t)}function sD(e){return e.map(e=>{var{providerId:t}=e,n=r2(e,["providerId"]);
4return{providerId:t,uid:n.rawId||"",displayName:n.displayName||null,email:n.email||null,phoneNumber:n.phoneNumber||null,photoURL:n.photoUrl||null}})}async function sx(e,t){let n=await sp(e,{},async()=>{let n=es({grant_type:"refresh_token",refresh_token:t}).slice(1),{tokenApiHost:i,apiKey:r}=e.config,s=s_(e,i,"/v1/token",`key=${r}`),o=await e._getAdditionalHeaders();return o["Content-Type"]="application/x-www-form-urlencoded",sl.fetch()(s,{method:"POST",headers:o,body:n})});return{accessToken:n.access_token,expiresIn:n.expires_in,refreshToken:n.refresh_token}}async function sL(e,t){return sd(e,"POST","/v2/accounts:revokeToken",su(e,t))}class sM{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){sn(e.idToken,"internal-error"),sn("u">typeof e.idToken,"internal-error"),sn("u">typeof e.refreshToken,"internal-error");let t="expiresIn"in e&&"u">typeof e.expiresIn?Number(e.expiresIn):sS(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,t)}updateFromIdToken(e){sn(0!==e.length,"internal-error");let t=sS(e);this.updateTokensAndExpiration(e,null,t)}async getToken(e,t=!1){return t||!this.accessToken||this.isExpired?(sn(this.refreshToken,e,"user-token-expired"),this.refreshToken?(await this.refresh(e,this.refreshToken),this.accessToken):null):this.accessToken}clearRefreshToken(){this.refreshToken=null}async refresh(e,t){let{accessToken:n,refreshToken:i,expiresIn:r}=await sx(e,t);this.updateTokensAndExpiration(n,i,Number(r))}updateTokensAndExpiration(e,t,n){this.refreshToken=t||null,this.accessToken=e||null,this.expirationTime=Date.now()+1e3*n}static fromJSON(e,t){let{refreshToken:n,accessToken:i,expirationTime:r}=t,s=new sM;return n&&(sn("string"==typeof n,"internal-error",{appName:e}),s.refreshToken=n),i&&(sn("string"==typeof i,"internal-error",{appName:e}),s.accessToken=i),r&&(sn("number"==typeof r,"internal-error",{appName:e}),s.expirationTime=r),s}toJSON(){return{refreshToken:this.refreshToken,accessToken:this.accessToken,expirationTime:this.expirationTime}}_assign(e){this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expirationTime=e.expirationTime}_clone(){return Object.assign(new sM,this.toJSON())}_performRefresh(){return si("not implemented")}}function sF(e,t){sn("string"==typeof e||typeof e>"u","internal-error",{appName:t})}class sU{constructor(e){var{uid:t,auth:n,stsTokenManager:i}=e,r=r2(e,["uid","auth","stsTokenManager"]);this.providerId="firebase",this.proactiveRefresh=new sN(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=t,this.auth=n,this.stsTokenManager=i,this.accessToken=i.accessToken,this.displayName=r.displayName||null,this.email=r.email||null,this.emailVerified=r.emailVerified||!1,this.phoneNumber=r.phoneNumber||null,this.photoURL=r.photoURL||null,this.isAnonymous=r.isAnonymous||!1,this.tenantId=r.tenantId||null,this.providerData=r.providerData?[...r.providerData]:[],this.metadata=new sR(r.createdAt||void 0,r.lastLoginAt||void 0)}async getIdToken(e){let t=await sP(this,this.stsTokenManager.getToken(this.auth,e));return sn(t,this.auth,"internal-error"),this.accessToken!==t&&(this.accessToken=t,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),t}getIdTokenResult(e){return sT(this,e)}reload(){return sA(this)}_assign(e){this!==e&&(sn(this.uid===e.uid,this.auth,"internal-error"),this.displayName=e.displayName,this.photoURL=e.photoURL,this.email=e.email,this.emailVerified=e.emailVerified,this.phoneNumber=e.phoneNumber,this.isAnonymous=e.isAnonymous,this.tenantId=e.tenantId,this.providerData=e.providerData.map(e=>Object.assign({},e)),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){let t=new sU(Object.assign(Object.assign({},this),{auth:e,stsTokenManager:this.stsTokenManager._clone()}));return t.metadata._copy(this.metadata),t}_onReload(e){sn(!this.reloadListener,this.auth,"internal-error"),this.reloadListener=e,this.reloadUserInfo&&(this._notifyReloadListener(this.reloadUserInfo),this.reloadUserInfo=null)}_notifyReloadListener(e){this.reloadListener?this.reloadListener(e):this.reloadUserInfo=e}_startProactiveRefresh(){this.proactiveRefresh._start()}_stopProactiveRefresh(){this.proactiveRefresh._stop()}async _updateTokensIfNecessary(e,t=!1){let n=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),n=!0),t&&await sO(this),await this.auth._persistUserIfCurrent(this),n&&this.auth._notifyListenersIfCurrent(this)}async delete(){if(eY(this.auth.app))return Promise.reject(se(this.auth));let e=await this.getIdToken();return await sP(this,sI(this.auth,{idToken:e})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut()}toJSON(){return Object.assign(Object.assign({uid:this.uid,email:this.email||void 0,emailVerified:this.emailVerified,displayName:this.displayName||void 0,isA
4nonymous:this.isAnonymous,photoURL:this.photoURL||void 0,phoneNumber:this.phoneNumber||void 0,tenantId:this.tenantId||void 0,providerData:this.providerData.map(e=>Object.assign({},e)),stsTokenManager:this.stsTokenManager.toJSON(),_redirectEventId:this._redirectEventId},this.metadata.toJSON()),{apiKey:this.auth.config.apiKey,appName:this.auth.name})}get refreshToken(){return this.stsTokenManager.refreshToken||""}static _fromJSON(e,t){var n,i,r,s,o,a,l,h;let c=null!==(n=t.displayName)&&void 0!==n?n:void 0,u=null!==(i=t.email)&&void 0!==i?i:void 0,d=null!==(r=t.phoneNumber)&&void 0!==r?r:void 0,p=null!==(s=t.photoURL)&&void 0!==s?s:void 0,f=null!==(o=t.tenantId)&&void 0!==o?o:void 0,_=null!==(a=t._redirectEventId)&&void 0!==a?a:void 0,m=null!==(l=t.createdAt)&&void 0!==l?l:void 0,g=null!==(h=t.lastLoginAt)&&void 0!==h?h:void 0,{uid:v,emailVerified:y,isAnonymous:w,providerData:I,stsTokenManager:C}=t;sn(v&&C,e,"internal-error");let b=sM.fromJSON(this.name,C);sn("string"==typeof v,e,"internal-error"),sF(c,e.name),sF(u,e.name),sn("boolean"==typeof y,e,"internal-error"),sn("boolean"==typeof w,e,"internal-error"),sF(d,e.name),sF(p,e.name),sF(f,e.name),sF(_,e.name),sF(m,e.name),sF(g,e.name);let T=new sU({uid:v,auth:e,email:u,emailVerified:y,displayName:c,isAnonymous:w,photoURL:p,phoneNumber:d,tenantId:f,stsTokenManager:b,createdAt:m,lastLoginAt:g});return I&&Array.isArray(I)&&(T.providerData=I.map(e=>Object.assign({},e))),_&&(T._redirectEventId=_),T}static async _fromIdTokenResponse(e,t,n=!1){let i=new sM;i.updateFromServerResponse(t);let r=new sU({uid:t.localId,auth:e,stsTokenManager:i,isAnonymous:n});return await sO(r),r}static async _fromGetAccountInfoResponse(e,t,n){let i=t.users[0];sn(void 0!==i.localId,"internal-error");let r=void 0!==i.providerUserInfo?sD(i.providerUserInfo):[],s=!(i.email&&i.passwordHash)&&!(null!=r&&r.length),o=new sM;o.updateFromIdToken(n);let a=new sU({uid:i.localId,auth:e,stsTokenManager:o,isAnonymous:s});return Object.assign(a,{uid:i.localId,displayName:i.displayName||null,photoURL:i.photoUrl||null,email:i.email||null,emailVerified:i.emailVerified||!1,phoneNumber:i.phoneNumber||null,tenantId:i.tenantId||null,providerData:r,metadata:new sR(i.createdAt,i.lastLoginAt),isAnonymous:!(i.email&&i.passwordHash)&&!(null!=r&&r.length)}),a}}let sq=new Map;function sj(e){var t,n;t="Expected a class definition",e instanceof Function||si(t);let i=sq.get(e);return i?(n="Instance stored in cache mismatched with class",i instanceof e||si(n)):(i=new e,sq.set(e,i)),i}class sW{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,t){this.storage[e]=t}async _get(e){let t=this.storage[e];return void 0===t?null:t}async _remove(e){delete this.storage[e]}_addListener(e,t){}_removeListener(e,t){}}function sV(e,t,n){return`firebase:${e}:${t}:${n}`}sW.type="NONE";class sH{constructor(e,t,n){this.persistence=e,this.auth=t,this.userKey=n;let{config:i,name:r}=this.auth;this.fullUserKey=sV(this.userKey,i.apiKey,r),this.fullPersistenceKey=sV("persistence",i.apiKey,r),this.boundEventHandler=t._onStorageEvent.bind(t),this.persistence._addListener(this.fullUserKey,this.boundEventHandler)}setCurrentUser(e){return this.persistence._set(this.fullUserKey,e.toJSON())}async getCurrentUser(){let e=await this.persistence._get(this.fullUserKey);return e?sU._fromJSON(this.auth,e):null}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(e){if(this.persistence===e)return;let t=await this.getCurrentUser();if(await this.removeCurrentUser(),this.persistence=e,t)return this.setCurrentUser(t)}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(e,t,n="authUser"){if(!t.length)return new sH(sj(sW),e,n);let i=(await Promise.all(t.map(async e=>{if(await e._isAvailable())return e}))).filter(e=>e),r=i[0]||sj(sW),s=sV(n,e.config.apiKey,e.name),o=null;for(let n of t)try{let t=await n._get(s);if(t){let i=sU._fromJSON(e,t);n!==r&&(o=i),r=n;break}}catch{}let a=i.filter(e=>e._shouldAllowMigration);return r._shouldAllowMigration&&a.length&&(r=a[0],o&&await r._set(s,o.toJSON()),await Promise.all(t.map(async e=>{if(e!==r)try{await e._remove(s)}catch{}}))),new sH(r,e,n)}}function sB(e){let t=e.toLowerCase();if(t.includes("opera/")||t.includes("opr/")||t.includes("opios/"))return"Opera";if(sG(t))return"IEMobile";if(t.includes("msie")||t.includes("trident/"))return"IE";if(t.includes("edge/"))return"Edge";if(sz(t))return"Firefox";if(t.includes("silk/"))return"Silk";if(sJ(t))return"Blackberry";if(sQ(t))return"Webos";if(s$(t))return"Safari";if((t.includes("chrome/")||sK(t))&&!t.includes("edge/"))return"Chrome";if(sY(t))return"Android";{let t=e.match(/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/);if((null==t?void 0:t.length)===2)return t[1]}return"Other"}function sz(e=V()){return/firefox\//i.test(e)}function s$(e=V()){let t=e.toLowerCase();return t.includes("safari/")&&!t.includes("chrome/")&&!t.includes("crios/")&&!t.includes("android")}function sK(e=V()){return/crios\//i.test(e)}function sG(e=V()){return/iemobile/i.test(e)}function sY(e=V()){return/android/i.test(e)}function sJ(e=V()){return/blackberry/i.test(e)}function sQ(e=V()){return/webos/i.test(e)}function sX(e=V()){return/iphone|ipad|ipod/i.test(e)||/macintosh/i.test(e)&&/mobile/i.test(e)}function sZ(e=V()){return sX(e)||sY(e)||sQ(e)||sJ(e)||/windows phone/i.test(e)||sG(e)}function s0(e,t=[]){let n;switch(e){case"Browser":n=sB(V());break;case"Worker":n=`${sB(V())}-${e}`;break;default:n=e}let i=t.length?t.join(","):"FirebaseCore-web";return`${n}/JsCore/${eX}/${i}`}class s1{constructor(e){this.auth=e,this.queue=[]}pushCallback(e,t){let n=t=>new Promise((n,i)=>{try{let i=e(t);n(i)}catch(e){i(e)}});n.onAbort=t,this.queue.push(n);let i=this.queue.length-1;return()=>{this.queue[i]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser===e)return;let t=[];try{for(let n of this.queue)await n(e),n.onAbort&&t.push(n.onAbort)}catch(e){for(let e of(t.reverse(),t))try{e()}catch{}throw this.auth._errorFactory.create("login-blocked",{originalMessage:null==e?void 0:e.message})}}}async function s2(e,t={}){return sd(e,"GET","/v2/passwordPolicy",su(e,t))}class s3{constructor(e){var t,n,i,r;let s=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=null!==(t=s.minPasswordLength)&&void 0!==t?t:6,s.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=s.maxPasswordLength),void 0!==s.containsLowercaseCharacter&&(this.customStrengthOptions.containsLowercaseLetter=s.containsLowercaseCharacter),void 0!==s.containsUppercaseCharacter&&(this.customStrengthOptions.containsUppercaseLetter=s.containsUppercaseCharacter),void 0!==s.containsNumericCharacter&&(this.customStrengthOptions.containsNumericCharacter=s.containsNumericCharacter),void 0!==s.containsNonAlphanumericCharacter&&(this.customStrengthOptions.containsNonAlphanumericCharacter=s.containsNonAlphanumericCharacter),this.enforcementState=e.enforcementState,"ENFORCEMENT_STATE_UNSPECIFIED"===this.enforcementState&&(this.enforcementState="OFF"),this.allowedNonAlphanumericCharacters=null!==(i=null===(n=e.allowedNonAlphanumericCharacters)||void 0===n?void 0:n.join(""))&&void 0!==i?i:"",this.forceUpgradeOnSignin=null!==(r=e.forceUpgradeOnSignin)&&void 0!==r&&r,this.schemaVersion=e.schemaVersion}validatePassword(e){var t,n,i,r,s,o;let a={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,a),this.validatePasswordCharacterOptions(e,a),a.isValid&&
4(a.isValid=null===(t=a.meetsMinPasswordLength)||void 0===t||t),a.isValid&&(a.isValid=null===(n=a.meetsMaxPasswordLength)||void 0===n||n),a.isValid&&(a.isValid=null===(i=a.containsLowercaseLetter)||void 0===i||i),a.isValid&&(a.isValid=null===(r=a.containsUppercaseLetter)||void 0===r||r),a.isValid&&(a.isValid=null===(s=a.containsNumericCharacter)||void 0===s||s),a.isValid&&(a.isValid=null===(o=a.containsNonAlphanumericCharacter)||void 0===o||o),a}validatePasswordLengthOptions(e,t){let n=this.customStrengthOptions.minPasswordLength,i=this.customStrengthOptions.maxPasswordLength;n&&(t.meetsMinPasswordLength=e.length>=n),i&&(t.meetsMaxPasswordLength=e.length<=i)}validatePasswordCharacterOptions(e,t){let n;this.updatePasswordCharacterOptionsStatuses(t,!1,!1,!1,!1);for(let i=0;i<e.length;i++)n=e.charAt(i),this.updatePasswordCharacterOptionsStatuses(t,n>="a"&&n<="z",n>="A"&&n<="Z",n>="0"&&n<="9",this.allowedNonAlphanumericCharacters.includes(n))}updatePasswordCharacterOptionsStatuses(e,t,n,i,r){this.customStrengthOptions.containsLowercaseLetter&&(e.containsLowercaseLetter||(e.containsLowercaseLetter=t)),this.customStrengthOptions.containsUppercaseLetter&&(e.containsUppercaseLetter||(e.containsUppercaseLetter=n)),this.customStrengthOptions.containsNumericCharacter&&(e.containsNumericCharacter||(e.containsNumericCharacter=i)),this.customStrengthOptions.containsNonAlphanumericCharacter&&(e.containsNonAlphanumericCharacter||(e.containsNonAlphanumericCharacter=r))}}class s4{constructor(e,t,n,i){this.app=e,this.heartbeatServiceProvider=t,this.appCheckServiceProvider=n,this.config=i,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new s6(this),this.idTokenSubscription=new s6(this),this.beforeStateQueue=new s1(this),this.redirectUser=null,this.isProactiveRefreshEnabled=!1,this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION=1,this._canInitEmulator=!0,this._isInitialized=!1,this._deleted=!1,this._initializationPromise=null,this._popupRedirectResolver=null,this._errorFactory=r4,this._agentRecaptchaConfig=null,this._tenantRecaptchaConfigs={},this._projectPasswordPolicy=null,this._tenantPasswordPolicies={},this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=i.sdkClientVersion}_initializeWithPersistence(e,t){return t&&(this._popupRedirectResolver=sj(t)),this._initializationPromise=this.queue(async()=>{var n,i;if(!this._deleted&&(this.persistenceManager=await sH.create(this,e),!this._deleted)){if(!(null===(n=this._popupRedirectResolver)||void 0===n)&&n._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch{}await this.initializeCurrentUser(t),this.lastNotifiedUid=(null===(i=this.currentUser)||void 0===i?void 0:i.uid)||null,this._deleted||(this._isInitialized=!0)}}),this._initializationPromise}async _onStorageEvent(){if(this._deleted)return;let e=await this.assertedPersistence.getCurrentUser();if(!(!this.currentUser&&!e)){if(this.currentUser&&e&&this.currentUser.uid===e.uid){this._currentUser._assign(e),await this.currentUser.getIdToken();return}await this._updateCurrentUser(e,!0)}}async initializeCurrentUserFromIdToken(e){try{let t=await sC(this,{idToken:e}),n=await sU._fromGetAccountInfoResponse(this,t,e);await this.directlySetCurrentUser(n)}catch(e){console.warn("FirebaseServerApp could not login user with provided authIdToken: ",e),await this.directlySetCurrentUser(null)}}async initializeCurrentUser(e){var t;if(eY(this.app)){let e=this.app.settings.authIdToken;return e?new Promise(t=>{setTimeout(()=>this.initializeCurrentUserFromIdToken(e).then(t,t))}):this.directlySetCurrentUser(null)}let n=await this.assertedPersistence.getCurrentUser(),i=n,r=!1;if(e&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();let n=null===(t=this.redirectUser)||void 0===t?void 0:t._redirectEventId,s=null==i?void 0:i._redirectEventId,o=await this.tryRedirectSignIn(e);(!n||n===s)&&null!=o&&o.user&&(i=o.user,r=!0)}if(!i)return this.directlySetCurrentUser(null);
4if(!i._redirectEventId){if(r)try{await this.beforeStateQueue.runMiddleware(i)}catch(e){i=n,this._popupRedirectResolver._overrideRedirectResult(this,()=>Promise.reject(e))}return i?this.reloadAndSetCurrentUserOrClear(i):this.directlySetCurrentUser(null)}return sn(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===i._redirectEventId?this.directlySetCurrentUser(i):this.reloadAndSetCurrentUserOrClear(i)}async tryRedirectSignIn(e){let t=null;try{t=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch{await this._setRedirectUser(null)}return t}async reloadAndSetCurrentUserOrClear(e){try{await sO(e)}catch(e){if((null==e?void 0:e.code)!=="auth/network-request-failed")return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=function(){if(typeof navigator>"u")return null;let e=navigator;return e.languages&&e.languages[0]||e.language||null}()}async _delete(){this._deleted=!0}async updateCurrentUser(e){if(eY(this.app))return Promise.reject(se(this));let t=e?ef(e):null;return t&&sn(t.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(t&&t._clone(this))}async _updateCurrentUser(e,t=!1){if(!this._deleted)return e&&sn(this.tenantId===e.tenantId,this,"tenant-id-mismatch"),t||await this.beforeStateQueue.runMiddleware(e),this.queue(async()=>{await this.directlySetCurrentUser(e),this.notifyAuthListeners()})}async signOut(){return eY(this.app)?Promise.reject(se(this)):(await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0))}setPersistence(e){return eY(this.app)?Promise.reject(se(this)):this.queue(async()=>{await this.assertedPersistence.setPersistence(sj(e))})}_getRecaptchaConfig(){return null==this.tenantId?this._agentRecaptchaConfig:this._tenantRecaptchaConfigs[this.tenantId]}async validatePassword(e){this._getPasswordPolicyInternal()||await this._updatePasswordPolicy();let t=this._getPasswordPolicyInternal();return t.schemaVersion!==this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION?Promise.reject(this._errorFactory.create("unsupported-password-policy-schema-version",{})):t.validatePassword(e)}_getPasswordPolicyInternal(){return null===this.tenantId?this._projectPasswordPolicy:this._tenantPasswordPolicies[this.tenantId]}async _updatePasswordPolicy(){let e=new s3(await s2(this));null===this.tenantId?this._projectPasswordPolicy=e:this._tenantPasswordPolicies[this.tenantId]=e}_getPersistence(){return this.assertedPersistence.persistence.type}_updateErrorMap(e){this._errorFactory=new $("auth","Firebase",e())}onAuthStateChanged(e,t,n){return this.registerStateListener(this.authStateSubscription,e,t,n)}beforeAuthStateChanged(e,t){return this.beforeStateQueue.pushCallback(e,t)}onIdTokenChanged(e,t,n){return this.registerStateListener(this.idTokenSubscription,e,t,n)}authStateReady(){return new Promise((e,t)=>{if(this.currentUser)e();else{let n=this.onAuthStateChanged(()=>{n(),e()},t)}})}async revokeAccessToken(e){if(this.currentUser){let t={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:e,idToken:await this.currentUser.getIdToken()};null!=this.tenantId&&(t.tenantId=this.tenantId),await sL(this,t)}}toJSON(){var e;return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:null===(e=this._currentUser)||void 0===e?void 0:e.toJSON()}}async _setRedirectUser(e,t){let n=await this.getOrInitRedirectPersistenceManager(t);return null===e?n.removeCurrentUser():n.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){let t=e&&sj(e)||this._popupRedirectResolver;sn(t,this,"argument-error"),this.redirectPersistenceManager=await sH.create(this,[sj(t._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()}return this.redirectPersistenceManager}async _redirectUserForId(e){var t,n;return this._isInitialized&&await this.queue(async()=>{}),(null===(t=this._currentUser)||void 0===t?void 0:t._redirectEventId)===e?this._currentUser:(null===(n=this.redirectUser)||void 0===n?void 0:n._redirectEventId)===e?this.redirectUser:null}async _persistUserIfCurrent(e){if(e===this.currentUser)return this.queue(async()=>this.directlySetCurrentUser(e))}_notifyListenersIfCurrent(e){e===this.currentUser&&this.notifyAuthListeners()}_key(){return`${this.config.authDomain}:${this.config.apiKey}:${this.name}`}_startProactiveRefresh(){this.isProactiveRefreshEnabled=!0,this.currentUser&&this._currentUser._startProactiveRefresh()}_stopProactiveRefresh(){this.isProactiveRefreshEnabled=!1,this.currentUser&&this._currentUser._stopProactiveRefresh()}get _currentUser(){return this.currentUser}notifyAuthListeners(){var e,t;if(!this._isInitialized)return;this.idTokenSubscription.next(this.currentUser);let n=null!==(t=null===(e=this.currentUser)||void 0===e?void 0:e.uid)&&void 0!==t?t:null;this.lastNotifiedUid!==n&&(this.lastNotifiedUid=n,this.authStateSubscription.next(this.currentUser))}registerStateListener(e,t,n,i){if(this._deleted)return()=>{};let r="function"==typeof t?t:t.next.bind(t),s=!1,o=this._isInitialized?Promise.resolve():this._initializationPromise;if(sn(o,this,"internal-error"),o.then(()=>{s||r(this.currentUser)}),"function"==typeof t){let r=e.addObserver(t,n,i);return()=>{s=!0,r()}}{let n=e.addObserver(t);return()=>{s=!0,n()}}}async directlySetCurrentUser(e){this.currentUser&&this.currentUser!==e&&this._currentUser._stopProactiveRefresh(),e&&this.isProactiveRefreshEnabled&&e._startProactiveRefresh(),this.currentUser=e,e?await this.assertedPersistence.setCurrentUser(e):await this.assertedPersistence.removeCurrentUser()}queue(e){return this.operations=this.operations.then(e,e),this.operations}get assertedPersistence(){return sn(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){!e||this.frameworks.includes(e)||(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=s0(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){var e;let t={"X-Client-Version":this.clientVersion};this.app.options.appId&&(t["X-Firebase-gmpid"]=this.app.options.appId);let n=await (null===(e=this.heartbeatServiceProvider.getImmediate({optional:!0}))||void 0===e?void 0:e.getHeartbeatsHeader());n&&(t["X-Firebase-Client"]=n);let i=await this._getAppCheckToken();return i&&(t["X-Firebase-AppCheck"]=i),t}async _getAppCheckToken(){var e;let t=await (null===(e=this.appCheckServiceProvider.getImmediate({optional:!0}))||void 0===e?void 0:e.getToken());return null!=t&&t.error&&function(e,...t){r6.logLevel<=w.WARN&&r6.warn(`Auth (${eX}): ${e}`,...t)}(`Error while retrieving App Check token: ${t.error}`),null==t?void 0:t.token}}class s6{constructor(e){this.auth=e,this.observer=null,this.addObserver=function(e,t){let n=new eh(e,void 0);return n.subscribe.bind(n)}(e=>this.observer=e)}get next(){return sn(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}let s5={async loadJS(){throw Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};class s9{constructor(e){this.type="recaptcha-enterprise",this.auth=ef(e)}async verify(e="verify",t=!1){async function n(e){if(!t){if(null==e.tenantId&&null!=e._agentRecaptchaConfig)return e._agentRecaptchaConfig.siteKey;if(null!=e.tenantId&&void 0!==e._tenantRecaptchaConfigs[e.tenantId])return e._tenantRecaptchaConfigs[e.tenantId].siteKey}return new Promise(async(t,n)=>
4{sw(e,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then(i=>{if(void 0===i.recaptchaKey)n(Error("recaptcha Enterprise site key undefined"));else{let n=new sy(i);return null==e.tenantId?e._agentRecaptchaConfig=n:e._tenantRecaptchaConfigs[e.tenantId]=n,t(n.siteKey)}}).catch(e=>{n(e)})})}function i(t,n,i){let r=window.grecaptcha;sv(r)?r.enterprise.ready(()=>{r.enterprise.execute(t,{action:e}).then(e=>{n(e)}).catch(()=>{n("NO_RECAPTCHA")})}):i(Error("No reCAPTCHA enterprise script loaded."))}return new Promise((e,r)=>{n(this.auth).then(n=>{if(!t&&sv(window.grecaptcha))i(n,e,r);else{var s;if(typeof window>"u"){r(Error("RecaptchaVerifier is only supported in browser"));return}let t=s5.recaptchaEnterpriseScript;0!==t.length&&(t+=n),(s=t,s5.loadJS(s)).then(()=>{i(n,e,r)}).catch(e=>{r(e)})}}).catch(e=>{r(e)})})}}async function s8(e,t,n,i=!1){let r;let s=new s9(e);try{r=await s.verify(n)}catch{r=await s.verify(n,!0)}let o=Object.assign({},t);return i?Object.assign(o,{captchaResp:r}):Object.assign(o,{captchaResponse:r}),Object.assign(o,{clientType:"CLIENT_TYPE_WEB"}),Object.assign(o,{recaptchaVersion:"RECAPTCHA_ENTERPRISE"}),o}async function s7(e,t,n,i){var r;if(!(!(null===(r=e._getRecaptchaConfig())||void 0===r)&&r.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")))return i(e,t).catch(async r=>{if("auth/missing-recaptcha-token"!==r.code)return Promise.reject(r);{console.log(`${n} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`);let r=await s8(e,t,n,"getOobCode"===n);return i(e,r)}});{let r=await s8(e,t,n,"getOobCode"===n);return i(e,r)}}function oe(e){let t=e.indexOf(":");return t<0?"":e.substr(0,t+1)}function ot(e){if(!e)return null;let t=Number(e);return isNaN(t)?null:t}class on{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return si("not implemented")}_getIdTokenResponse(e){return si("not implemented")}_linkToIdToken(e,t){return si("not implemented")}_getReauthenticationResolver(e){return si("not implemented")}}async function oi(e,t){return sd(e,"POST","/v1/accounts:signUp",t)}async function or(e,t){return sf(e,"POST","/v1/accounts:signInWithPassword",su(e,t))}async function os(e,t){return sf(e,"POST","/v1/accounts:signInWithEmailLink",su(e,t))}async function oo(e,t){return sf(e,"POST","/v1/accounts:signInWithEmailLink",su(e,t))}class oa extends on{constructor(e,t,n,i=null){super("password",n),this._email=e,this._password=t,this._tenantId=i}static _fromEmailAndPassword(e,t){return new oa(e,t,"password")}static _fromEmailAndCode(e,t,n=null){return new oa(e,t,"emailLink",n)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){let t="string"==typeof e?JSON.parse(e):e;if(null!=t&&t.email&&null!=t&&t.password){if("password"===t.signInMethod)return this._fromEmailAndPassword(t.email,t.password);if("emailLink"===t.signInMethod)return this._fromEmailAndCode(t.email,t.password,t.tenantId)}return null}async _getIdTokenResponse(e){switch(this.signInMethod){case"password":return s7(e,{returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signInWithPassword",or);case"emailLink":return os(e,{email:this._email,oobCode:this._password});default:r9(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":return s7(e,{idToken:t,returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",oi);case"emailLink":return oo(e,{idToken:t,email:this._email,oobCode:this._password});default:r9(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function ol(e,t){return sf(e,"POST","/v1/accounts:signInWithIdp",su(e,t))}class oh extends on{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){let t=new oh(e.providerId,e.signInMethod);return e.idToken||e.accessToken?(e.idToken&&(t.idToken=e.idToken),e.accessToken&&(t.accessToken=e.accessToken),e.nonce&&!e.pendingToken&&(t.nonce=e.nonce),e.pendingToken&&
4(t.pendingToken=e.pendingToken)):e.oauthToken&&e.oauthTokenSecret?(t.accessToken=e.oauthToken,t.secret=e.oauthTokenSecret):r9("argument-error"),t}toJSON(){return{idToken:this.idToken,accessToken:this.accessToken,secret:this.secret,nonce:this.nonce,pendingToken:this.pendingToken,providerId:this.providerId,signInMethod:this.signInMethod}}static fromJSON(e){let t="string"==typeof e?JSON.parse(e):e,{providerId:n,signInMethod:i}=t,r=r2(t,["providerId","signInMethod"]);if(!n||!i)return null;let s=new oh(n,i);return s.idToken=r.idToken||void 0,s.accessToken=r.accessToken||void 0,s.secret=r.secret,s.nonce=r.nonce,s.pendingToken=r.pendingToken||null,s}_getIdTokenResponse(e){return ol(e,this.buildRequest())}_linkToIdToken(e,t){let n=this.buildRequest();return n.idToken=t,ol(e,n)}_getReauthenticationResolver(e){let t=this.buildRequest();return t.autoCreate=!1,ol(e,t)}buildRequest(){let e={requestUri:"http://localhost",returnSecureToken:!0};if(this.pendingToken)e.pendingToken=this.pendingToken;else{let t={};this.idToken&&(t.id_token=this.idToken),this.accessToken&&(t.access_token=this.accessToken),this.secret&&(t.oauth_token_secret=this.secret),t.providerId=this.providerId,this.nonce&&!this.pendingToken&&(t.nonce=this.nonce),e.postBody=es(t)}return e}}class oc{constructor(e){var t,n,i,r,s,o;let a=eo(ea(e)),l=null!==(t=a.apiKey)&&void 0!==t?t:null,h=null!==(n=a.oobCode)&&void 0!==n?n:null,c=function(e){switch(e){case"recoverEmail":return"RECOVER_EMAIL";case"resetPassword":return"PASSWORD_RESET";case"signIn":return"EMAIL_SIGNIN";case"verifyEmail":return"VERIFY_EMAIL";case"verifyAndChangeEmail":return"VERIFY_AND_CHANGE_EMAIL";case"revertSecondFactorAddition":return"REVERT_SECOND_FACTOR_ADDITION";default:return null}}(null!==(i=a.mode)&&void 0!==i?i:null);sn(l&&h&&c,"argument-error"),this.apiKey=l,this.operation=c,this.code=h,this.continueUrl=null!==(r=a.continueUrl)&&void 0!==r?r:null,this.languageCode=null!==(s=a.languageCode)&&void 0!==s?s:null,this.tenantId=null!==(o=a.tenantId)&&void 0!==o?o:null}static parseLink(e){let t=function(e){let t=eo(ea(e)).link,n=t?eo(ea(t)).deep_link_id:null,i=eo(ea(e)).deep_link_id;return(i?eo(ea(i)).link:null)||i||n||t||e}(e);try{return new oc(t)}catch{return null}}}class ou{constructor(){this.providerId=ou.PROVIDER_ID}static credential(e,t){return oa._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){let n=oc.parseLink(t);return sn(n,"argument-error"),oa._fromEmailAndCode(e,n.code,n.tenantId)}}ou.PROVIDER_ID="password",ou.EMAIL_PASSWORD_SIGN_IN_METHOD="password",ou.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class od{constructor(e){this.providerId=e,this.defaultLanguageCode=null,this.customParameters={}}setDefaultLanguage(e){this.defaultLanguageCode=e}setCustomParameters(e){return this.customParameters=e,this}getCustomParameters(){return this.customParameters}}class op extends od{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class of extends op{constructor(){super("facebook.com")}static credential(e){return oh._fromParams({providerId:of.PROVIDER_ID,signInMethod:of.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return of.credentialFromTaggedObject(e)}static credentialFromError(e){return of.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)||!e.oauthAccessToken)return null;try{return of.credential(e.oauthAccessToken)}catch{return null}}}of.FACEBOOK_SIGN_IN_METHOD="facebook.com",of.PROVIDER_ID="facebook.com";class o_ extends op{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return oh._fromParams({providerId:o_.PROVIDER_ID,signInMethod:o_.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return o_.credentialFromTaggedObject(e)}static credentialFromError(e){return o_.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;let{oauthIdToken:t,oauthAccessToken:n}=e;if(!t&&!n)return null;try{return o_.credential(t,n)}catch{return null}}}o_.GOOGLE_SIGN_IN_METHOD="google.com",o_.PROVIDER_ID="google.com";class om extends op{constructor(){super("github.com")}static credential(e){return oh._fromParams({providerId:om.PROVIDER_ID,signInMethod:om.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return om.credentialFromTaggedObject(e)}static credentialFromError(e){return om.credentialFromTaggedObject(e.customData||{})}
4static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)||!e.oauthAccessToken)return null;try{return om.credential(e.oauthAccessToken)}catch{return null}}}om.GITHUB_SIGN_IN_METHOD="github.com",om.PROVIDER_ID="github.com";class og extends op{constructor(){super("twitter.com")}static credential(e,t){return oh._fromParams({providerId:og.PROVIDER_ID,signInMethod:og.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return og.credentialFromTaggedObject(e)}static credentialFromError(e){return og.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;let{oauthAccessToken:t,oauthTokenSecret:n}=e;if(!t||!n)return null;try{return og.credential(t,n)}catch{return null}}}async function ov(e,t){return sf(e,"POST","/v1/accounts:signUp",su(e,t))}og.TWITTER_SIGN_IN_METHOD="twitter.com",og.PROVIDER_ID="twitter.com";class oy{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,n,i=!1){return new oy({user:await sU._fromIdTokenResponse(e,n,i),providerId:ow(n),_tokenResponse:n,operationType:t})}static async _forOperation(e,t,n){return await e._updateTokensIfNecessary(n,!0),new oy({user:e,providerId:ow(n),_tokenResponse:n,operationType:t})}}function ow(e){return e.providerId?e.providerId:"phoneNumber"in e?"phone":null}class oI extends z{constructor(e,t,n,i){var r;super(t.code,t.message),this.operationType=n,this.user=i,Object.setPrototypeOf(this,oI.prototype),this.customData={appName:e.name,tenantId:null!==(r=e.tenantId)&&void 0!==r?r:void 0,_serverResponse:t.customData._serverResponse,operationType:n}}static _fromErrorAndOperation(e,t,n,i){return new oI(e,t,n,i)}}function oC(e,t,n,i){return("reauthenticate"===t?n._getReauthenticationResolver(e):n._getIdTokenResponse(e)).catch(n=>{throw"auth/multi-factor-auth-required"===n.code?oI._fromErrorAndOperation(e,n,t,i):n})}async function ob(e,t,n=!1){let i=await sP(e,t._linkToIdToken(e.auth,await e.getIdToken()),n);return oy._forOperation(e,"link",i)}async function oT(e,t,n=!1){let{auth:i}=e;if(eY(i.app))return Promise.reject(se(i));let r="reauthenticate";try{let s=await sP(e,oC(i,r,t,e),n);sn(s.idToken,i,"internal-error");let o=sk(s.idToken);sn(o,i,"internal-error");let{sub:a}=o;return sn(e.uid===a,i,"user-mismatch"),oy._forOperation(e,r,s)}catch(e){throw(null==e?void 0:e.code)==="auth/user-not-found"&&r9(i,"user-mismatch"),e}}async function oE(e,t,n=!1){if(eY(e.app))return Promise.reject(se(e));let i="signIn",r=await oC(e,i,t),s=await oy._fromIdTokenResponse(e,i,r);return n||await e._updateCurrentUser(s.user),s}async function ok(e,t){return oE(ef(e),t)}async function oS(e){let t=ef(e);t._getPasswordPolicyInternal()&&await t._updatePasswordPolicy()}async function oP(e,t,n){if(eY(e.app))return Promise.reject(se(e));let i=ef(e),r=await s7(i,{returnSecureToken:!0,email:t,password:n,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",ov).catch(t=>{throw"auth/password-does-not-meet-requirements"===t.code&&oS(e),t}),s=await oy._fromIdTokenResponse(i,"signIn",r);return await i._updateCurrentUser(s.user),s}function oN(e,t,n){return eY(e.app)?Promise.reject(se(e)):ok(ef(e),ou.credential(t,n)).catch(async t=>{throw"auth/password-does-not-meet-requirements"===t.code&&oS(e),t})}async function oR(e,t){return sd(e,"POST","/v1/accounts:update",t)}async function oO(e,{displayName:t,photoURL:n}){if(void 0===t&&void 0===n)return;let i=ef(e),r={idToken:await i.getIdToken(),displayName:t,photoUrl:n,returnSecureToken:!0},s=await sP(i,oR(i.auth,r));i.displayName=s.displayName||null,i.photoURL=s.photoUrl||null;let o=i.providerData.find(({providerId:e})=>"password"===e);o&&(o.displayName=i.displayName,o.photoURL=i.photoURL),await i._updateTokensIfNecessary(s)}function oA(e,t){return ef(e).setPersistence(t)}function oD(e){return ef(e).signOut()}let ox="__sak";class oL{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(ox,"1"),this.storage.removeItem(ox),Promise.resolve(!0)):Promise.resolve(!1)}catch{return Promise.resolve(!1)}}_set(e,t){return this.storage.setItem(e,JSON.stringify(t)),Promise.resolve()}_get(e){let t=this.storage.getItem(e);return Promise.resolve(t?JSON.parse(t):null)}_remove(e){return this.storage.removeItem(e),Promise.resolve()}get storage(){return this.storageRetriever()}}class oM extends oL{constructor(){super(()=>window.localStorage,"LOCAL"),this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t),this.listeners={},this.localCache={},this.pollTimer=null,this.fallbackToPolling=sZ(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(let t of Object.keys(this.listeners)){let n=this.storage.getItem(t),i=this.localCache[t];n!==i&&e(t,i,n)}}
4onStorageEvent(e,t=!1){if(!e.key){this.forAllChangedKeys((e,t,n)=>{this.notifyListeners(e,n)});return}let n=e.key;t?this.detachListener():this.stopPolling();let i=()=>{let e=this.storage.getItem(n);(t||this.localCache[n]!==e)&&this.notifyListeners(n,e)},r=this.storage.getItem(n);(function(){let e=V();return e.indexOf("MSIE ")>=0||e.indexOf("Trident/")>=0})()&&10===document.documentMode&&r!==e.newValue&&e.newValue!==e.oldValue?setTimeout(i,10):i()}notifyListeners(e,t){this.localCache[e]=t;let n=this.listeners[e];if(n)for(let e of Array.from(n))e(t&&JSON.parse(t))}startPolling(){this.stopPolling(),this.pollTimer=setInterval(()=>{this.forAllChangedKeys((e,t,n)=>{this.onStorageEvent(new StorageEvent("storage",{key:e,oldValue:t,newValue:n}),!0)})},1e3)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}attachListener(){window.addEventListener("storage",this.boundEventHandler)}detachListener(){window.removeEventListener("storage",this.boundEventHandler)}_addListener(e,t){0===Object.keys(this.listeners).length&&(this.fallbackToPolling?this.startPolling():this.attachListener()),this.listeners[e]||(this.listeners[e]=new Set,this.localCache[e]=this.storage.getItem(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),0===this.listeners[e].size&&delete this.listeners[e]),0===Object.keys(this.listeners).length&&(this.detachListener(),this.stopPolling())}async _set(e,t){await super._set(e,t),this.localCache[e]=JSON.stringify(t)}async _get(e){let t=await super._get(e);return this.localCache[e]=JSON.stringify(t),t}async _remove(e){await super._remove(e),delete this.localCache[e]}}oM.type="LOCAL";let oF=oM;class oU extends oL{constructor(){super(()=>window.sessionStorage,"SESSION")}_addListener(e,t){}_removeListener(e,t){}}oU.type="SESSION";class oq{constructor(e){this.eventTarget=e,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(e){let t=this.receivers.find(t=>t.isListeningto(e));if(t)return t;let n=new oq(e);return this.receivers.push(n),n}isListeningto(e){return this.eventTarget===e}async handleEvent(e){let{eventId:t,eventType:n,data:i}=e.data,r=this.handlersMap[n];if(!(null!=r&&r.size))return;e.ports[0].postMessage({status:"ack",eventId:t,eventType:n});let s=Array.from(r).map(async t=>t(e.origin,i)),o=await Promise.all(s.map(async e=>{try{return{fulfilled:!0,value:await e}}catch(e){return{fulfilled:!1,reason:e}}}));e.ports[0].postMessage({status:"done",eventId:t,eventType:n,response:o})}_subscribe(e,t){0===Object.keys(this.handlersMap).length&&this.eventTarget.addEventListener("message",this.boundEventHandler),this.handlersMap[e]||(this.handlersMap[e]=new Set),this.handlersMap[e].add(t)}_unsubscribe(e,t){this.handlersMap[e]&&t&&this.handlersMap[e].delete(t),t&&0!==this.handlersMap[e].size||delete this.handlersMap[e],0===Object.keys(this.handlersMap).length&&this.eventTarget.removeEventListener("message",this.boundEventHandler)}}function oj(e="",t=10){let n="";for(let e=0;e<t;e++)n+=Math.floor(10*Math.random());return e+n}oq.receivers=[];class oW{constructor(e){this.target=e,this.handlers=new Set}removeMessageHandler(e){e.messageChannel&&(e.messageChannel.port1.removeEventListener("message",e.onMessage),e.messageChannel.port1.close()),this.handlers.delete(e)}async _send(e,t,n=50){let i,r;let s="u">typeof MessageChannel?new MessageChannel:null;if(!s)throw Error("connection_unavailable");return new Promise((o,a)=>{let l=oj("",20);s.port1.start();let h=setTimeout(()=>{a(Error("unsupported_event"))},n);r={messageChannel:s,onMessage(e){if(e.data.eventId===l)switch(e.data.status){case"ack":clearTimeout(h),i=setTimeout(()=>{a(Error("timeout"))},3e3);break;case"done":clearTimeout(i),o(e.data.response);break;default:clearTimeout(h),clearTimeout(i),a(Error("invalid_response"))}}},this.handlers.add(r),s.port1.addEventListener("message",r.onMessage),this.target.postMessage({eventType:e,eventId:l,data:t},[s.port2])}).finally(()=>{r&&this.removeMessageHandler(r)})}}function oV(){return window}function oH(){return"u">typeof oV().WorkerGlobalScope&&"function"==typeof oV().importScripts}async function oB(){if(!(null!=navigator&&navigator.serviceWorker))return null;try{return(await navigator.serviceWorker.ready).active}catch{return null}}let oz="firebaseLocalStorageDb",o$="firebaseLocalStorage",oK="fbase_key";class oG{constructor(e){this.request=e}toPromise(){return new Promise((e,t)=>
4{this.request.addEventListener("success",()=>{e(this.request.result)}),this.request.addEventListener("error",()=>{t(this.request.error)})})}}function oY(e,t){return e.transaction([o$],t?"readwrite":"readonly").objectStore(o$)}function oJ(){let e=indexedDB.open(oz,1);return new Promise((t,n)=>{e.addEventListener("error",()=>{n(e.error)}),e.addEventListener("upgradeneeded",()=>{let t=e.result;try{t.createObjectStore(o$,{keyPath:oK})}catch(e){n(e)}}),e.addEventListener("success",async()=>{let n=e.result;n.objectStoreNames.contains(o$)?t(n):(n.close(),await new oG(indexedDB.deleteDatabase(oz)).toPromise(),t(await oJ()))})})}async function oQ(e,t,n){return new oG(oY(e,!0).put({[oK]:t,value:n})).toPromise()}async function oX(e,t){let n=oY(e,!1).get(t),i=await new oG(n).toPromise();return void 0===i?null:i.value}function oZ(e,t){return new oG(oY(e,!0).delete(t)).toPromise()}class o0{constructor(){this.type="LOCAL",this._shouldAllowMigration=!0,this.listeners={},this.localCache={},this.pollTimer=null,this.pendingWrites=0,this.receiver=null,this.sender=null,this.serviceWorkerReceiverAvailable=!1,this.activeServiceWorker=null,this._workerInitializationPromise=this.initializeServiceWorkerMessaging().then(()=>{},()=>{})}async _openDb(){return this.db||(this.db=await oJ()),this.db}async _withRetries(e){let t=0;for(;;)try{let t=await this._openDb();return await e(t)}catch(e){if(t++>3)throw e;this.db&&(this.db.close(),this.db=void 0)}}async initializeServiceWorkerMessaging(){return oH()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=oq._getInstance(oH()?self:null),this.receiver._subscribe("keyChanged",async(e,t)=>({keyProcessed:(await this._poll()).includes(t.key)})),this.receiver._subscribe("ping",async(e,t)=>["keyChanged"])}async initializeSender(){var e,t;if(this.activeServiceWorker=await oB(),!this.activeServiceWorker)return;this.sender=new oW(this.activeServiceWorker);let n=await this.sender._send("ping",{},800);n&&!(null===(e=n[0])||void 0===e)&&e.fulfilled&&!(null===(t=n[0])||void 0===t)&&t.value.includes("keyChanged")&&(this.serviceWorkerReceiverAvailable=!0)}async notifyServiceWorker(e){var t;if(!(!this.sender||!this.activeServiceWorker||((null===(t=null==navigator?void 0:navigator.serviceWorker)||void 0===t?void 0:t.controller)||null)!==this.activeServiceWorker))try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch{}}async _isAvailable(){try{if(!indexedDB)return!1;let e=await oJ();return await oQ(e,ox,"1"),await oZ(e,ox),!0}catch{}return!1}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites--}}async _set(e,t){return this._withPendingWrite(async()=>(await this._withRetries(n=>oQ(n,e,t)),this.localCache[e]=t,this.notifyServiceWorker(e)))}async _get(e){let t=await this._withRetries(t=>oX(t,e));return this.localCache[e]=t,t}async _remove(e){return this._withPendingWrite(async()=>(await this._withRetries(t=>oZ(t,e)),delete this.localCache[e],this.notifyServiceWorker(e)))}async _poll(){let e=await this._withRetries(e=>new oG(oY(e,!1).getAll()).toPromise());if(!e||0!==this.pendingWrites)return[];let t=[],n=new Set;if(0!==e.length)for(let{fbase_key:i,value:r}of e)n.add(i),JSON.stringify(this.localCache[i])!==JSON.stringify(r)&&(this.notifyListeners(i,r),t.push(i));for(let e of Object.keys(this.localCache))this.localCache[e]&&!n.has(e)&&(this.notifyListeners(e,null),t.push(e));return t}notifyListeners(e,t){this.localCache[e]=t;let n=this.listeners[e];if(n)for(let e of Array.from(n))e(t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval(async()=>this._poll(),800)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}_addListener(e,t){0===Object.keys(this.listeners).length&&this.startPolling(),this.listeners[e]||(this.listeners[e]=new Set,this._get(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),0===this.listeners[e].size&&delete this.listeners[e]),0===Object.keys(this.listeners).length&&this.stopPolling()}}function o1(e,t){return t?sj(t):(sn(e._popupRedirectResolver,e,"argument-error"),e._popupRedirectResolver)}o0.type="LOCAL",new so(3e4,6e4);class o2 extends on{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return ol(e,this._buildIdpRequest())}_linkToIdToken(e,t){return ol(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return ol(e,this._buildIdpRequest())}_buildIdpRequest(e){let t={requestUri:this.params.requestUri,sessionId:this.params.sessionId,postBody:this.params.postBody,tenantId:this.params.tenantId,pendingToken:this.params.pendingToken,returnSecureToken:!0,returnIdpCredential:!0};return e&&(t.idToken=e),t}}function o3(e){return oE(e.auth,new o2(e),e.bypassAuthState)}function o4(e){let{auth:t,user:n}=e;return sn(n,t,"internal-error"),oT(n,new o2(e),e.bypassAuthState)}async function o6(e){let{auth:t,user:n}=e;return sn(n,t,"internal-error"),ob(n,new o2(e),e.bypassAuthState)}class o5{constructor(e,t,n,i,r=!1){this.auth=e,this.resolver=n,this.user=i,this.bypassAuthState=r,this.pendingPromise=null,this.eventManager=null,this.filter=Array.isArray(t)?t:[t]}execute(){return new Promise(async(e,t)=>{this.pendingPromise={resolve:e,reject:t};try{this.eventManager=await this.resolver._initialize(this.auth),await this.onExecution(),this.eventManager.registerConsumer(this)}catch(e){this.reject(e)}})}async onAuthEvent(e){let{urlResponse:t,sessionId:n,postBody:i,tenantId:r,error:s,type:o}=e;if(s){this.reject(s);return}let a={auth:this.auth,requestUri:t,sessionId:n,tenantId:r||void 0,postBody:i||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(o)(a))}catch(e){this.reject(e)}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return o3;case"linkViaPopup":case"linkViaRedirect":return o6;case"reauthViaPopup":case"reauthViaRedirect":return o4;default:r9(this.auth,"internal-error")}}resolve(e){var t,n;t=this.pendingPromise,n="Pending promise was never set",t||si(n),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){var t,n;t=this.pendingPromise,n="Pending promise was never set",t||si(n),this.pendingPromise.reject(e),this.unregisterAndCleanUp()}unregisterAndCleanUp(){this.eventManager&&this.eventManager.unregisterConsumer(this),this.pendingPromise=null,this.cleanUp()}}let o9=new so(2e3,1e4);async function o8(e,t,n){if(eY(e.app))return Promise.reject(r8(e,"operation-not-supported-in-this-environment"));let i=ef(e);!function(e,t,n){if(!(t instanceof n))throw n.name!==t.constructor.name&&r9(e,"argument-error"),r7(e,"argument-error",`Type of ${t.constructor.name} does not match expected instance.Did you pass a reference from a different Auth SDK?`)}(e,t,od);let r=o1(i,n);return new o7(i,"signInViaPopup",t,r).executeNotNull()}class o7 extends o5{constructor(e,t,n,i,r){super(e,t,i,r),this.provider=n,this.authWindow=null,this.pollId=null,o7.currentPopupAction&&o7.currentPopupAction.cancel(),o7.currentPopupAction=this}async executeNotNull(){let e=await this.execute();return sn(e,this.auth,"internal-error"),e}async onExecution(){var e,t;e=1===this.filter.length,t="Popup operations only handle one event",e||si(t);let n=oj();this.authWindow=await this.resolver._openPopup(this.auth,this.provider,this.filter[0],n),this.authWindow.associatedEvent=n,this.resolver._originValidation(this.auth).catch(e=>{this.reject(e)}),this.resolver._isIframeWebStorageSupported(this.auth,e=>{e||this.reject(r8(this.auth,"web-storage-unsupported"))}),this.pollUserCancellation()}get eventId(){var e;return(null===(e=this.authWindow)||void 0===e?void 0:e.associatedEvent)||null}cancel(){this.reject(r8(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,o7.currentPopupAction=null}pollUserCancellation(){let e=()=>{var t,n;if(!(null===(n=null===(t=this.authWindow)||void 0===t?void 0:t.window)||void 0===n)&&n.closed){this.pollId=window.setTimeout(()=>{this.pollId=null,this.reject(r8(this.auth,"popup-closed-by-user"))},8e3);return}this.pollId=window.setTimeout(e,o9.get())};e()}}o7.currentPopupAction=null;let ae=new Map;class at extends o5{constructor(e,t,n=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,n),this.eventId=null}async execute(){let e=ae.get(this.auth._key());if(!e){try{let t=await an(this.resolver,this.auth)?await super.execute():null;e=()=>Promise.resolve(t)}catch(t){e=()=>Promise.reject(t)}ae.set(this.auth._key(),e)}return this.bypassAuthState||ae.set(this.auth._key(),()=>Promise.resolve(null)),e()}async onAuthEvent(e){if("signInViaRedirect"===e.type)return super.onAuthEvent(e);
4if("unknown"===e.type){this.resolve(null);return}if(e.eventId){let t=await this.auth._redirectUserForId(e.eventId);if(t)return this.user=t,super.onAuthEvent(e);this.resolve(null)}}async onExecution(){}cleanUp(){}}async function an(e,t){let n=sV("pendingRedirect",t.config.apiKey,t.name),i=sj(e._redirectPersistence);if(!await i._isAvailable())return!1;let r=await i._get(n)==="true";return await i._remove(n),r}function ai(e,t){ae.set(e._key(),t)}async function ar(e,t,n=!1){if(eY(e.app))return Promise.reject(se(e));let i=ef(e),r=o1(i,t),s=await new at(i,r,n).execute();return s&&!n&&(delete s.user._redirectEventId,await i._persistUserIfCurrent(s.user),await i._setRedirectUser(null,t)),s}class as{constructor(e){this.auth=e,this.cachedEventUids=new Set,this.consumers=new Set,this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1,this.lastProcessedEventTime=Date.now()}registerConsumer(e){this.consumers.add(e),this.queuedRedirectEvent&&this.isEventForConsumer(this.queuedRedirectEvent,e)&&(this.sendToConsumer(this.queuedRedirectEvent,e),this.saveEventToCache(this.queuedRedirectEvent),this.queuedRedirectEvent=null)}unregisterConsumer(e){this.consumers.delete(e)}onEvent(e){if(this.hasEventBeenHandled(e))return!1;let t=!1;return this.consumers.forEach(n=>{this.isEventForConsumer(e,n)&&(t=!0,this.sendToConsumer(e,n),this.saveEventToCache(e))}),this.hasHandledPotentialRedirect||!function(e){switch(e.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return!0;case"unknown":return aa(e);default:return!1}}(e)||(this.hasHandledPotentialRedirect=!0,t||(this.queuedRedirectEvent=e,t=!0)),t}sendToConsumer(e,t){var n;if(e.error&&!aa(e)){let i=(null===(n=e.error.code)||void 0===n?void 0:n.split("auth/")[1])||"internal-error";t.onError(r8(this.auth,i))}else t.onAuthEvent(e)}isEventForConsumer(e,t){let n=null===t.eventId||!!e.eventId&&e.eventId===t.eventId;return t.filter.includes(e.type)&&n}hasEventBeenHandled(e){return Date.now()-this.lastProcessedEventTime>=6e5&&this.cachedEventUids.clear(),this.cachedEventUids.has(ao(e))}saveEventToCache(e){this.cachedEventUids.add(ao(e)),this.lastProcessedEventTime=Date.now()}}function ao(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter(e=>e).join("-")}function aa({type:e,error:t}){return"unknown"===e&&(null==t?void 0:t.code)==="auth/no-auth-event"}async function al(e,t={}){return sd(e,"GET","/v1/projects",t)}let ah=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,ac=/^https?/;async function au(e){if(e.config.emulator)return;let{authorizedDomains:t}=await al(e);for(let e of t)try{if(function(e){let t=sr(),{protocol:n,hostname:i}=new URL(t);if(e.startsWith("chrome-extension://")){let r=new URL(e);return""===r.hostname&&""===i?"chrome-extension:"===n&&e.replace("chrome-extension://","")===t.replace("chrome-extension://",""):"chrome-extension:"===n&&r.hostname===i}if(!ac.test(n))return!1;if(ah.test(e))return i===e;let r=e.replace(/\./g,"\\.");return RegExp("^(.+\\."+r+"|"+r+")$","i").test(i)}(e))return}catch{}r9(e,"unauthorized-domain")}let ad=new so(3e4,6e4);function ap(){let e=oV().___jsl;if(null!=e&&e.H){for(let t of Object.keys(e.H))if(e.H[t].r=e.H[t].r||[],e.H[t].L=e.H[t].L||[],e.H[t].r=[...e.H[t].L],e.CP)for(let t=0;t<e.CP.length;t++)e.CP[t]=null}}let af=null,a_=new so(5e3,15e3),am={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},ag=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);async function av(e){let t=await (af=af||new Promise((t,n)=>{var i,r,s,o;function a(){ap(),gapi.load("gapi.iframes",{callback:()=>{t(gapi.iframes.getContext())},ontimeout:()=>{ap(),n(r8(e,"network-request-failed"))},timeout:ad.get()})}if(!(null===(r=null===(i=oV().gapi)||void 0===i?void 0:i.iframes)||void 0===r)&&r.Iframe)t(gapi.iframes.getContext());else if(!(null===(s=oV().gapi)||void 0===s)&&s.load)a();else{let t=`__iframefcb${Math.floor(1e6*Math.random())}`;return oV()[t]=()=>{gapi.load?a():n(r8(e,"network-request-failed"))},(o=`${s5.gapiScript}?onload=${t}`,s5.loadJS(o)).catch(e=>n(e))}}).catch(e=>{throw af=null,e})),n=oV().gapi;return sn(n,e,"internal-error"),t.open({where:document.body,url:function(e){let t=e.config;sn(t.authDomain,e,"auth-domain-config-required");let n=t.emulator?sa(t,"emulator/auth/iframe"):`https://${e.config.authDomain}
4/__/auth/iframe`,i={apiKey:t.apiKey,appName:e.name,v:eX},r=ag.get(e.config.apiHost);r&&(i.eid=r);let s=e._getFrameworks();return s.length&&(i.fw=s.join(",")),`${n}?${es(i).slice(1)}`}(e),messageHandlersFilter:n.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:am,dontclear:!0},t=>new Promise(async(n,i)=>{await t.restyle({setHideOnLeave:!1});let r=r8(e,"network-request-failed"),s=oV().setTimeout(()=>{i(r)},a_.get());function o(){oV().clearTimeout(s),n(t)}t.ping(o).then(o,()=>{i(r)})}))}let ay={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"};class aw{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch{}}}let aI=encodeURIComponent("fac");async function aC(e,t,n,i,r,s){sn(e.config.authDomain,e,"auth-domain-config-required"),sn(e.config.apiKey,e,"invalid-api-key");let o={apiKey:e.config.apiKey,appName:e.name,authType:n,redirectUrl:i,v:eX,eventId:r};if(t instanceof od)for(let[n,i]of(t.setDefaultLanguage(e.languageCode),o.providerId=t.providerId||"",et(t.getCustomParameters())||(o.customParameters=JSON.stringify(t.getCustomParameters())),Object.entries({})))o[n]=i;if(t instanceof op){let e=t.getScopes().filter(e=>""!==e);e.length>0&&(o.scopes=e.join(","))}for(let t of(e.tenantId&&(o.tid=e.tenantId),Object.keys(o)))void 0===o[t]&&delete o[t];let a=await e._getAppCheckToken(),l=a?`#${aI}=${encodeURIComponent(a)}`:"";return`${function({config:e}){return e.emulator?sa(e,"emulator/auth/handler"):`https://${e.authDomain}/__/auth/handler`}(e)}?${es(o).slice(1)}${l}`}let ab="webStorageSupport";class aT{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=oU,this._completeRedirectFn=ar,this._overrideRedirectResult=ai}async _openPopup(e,t,n,i){var r,s,o;s=null===(r=this.eventManagers[e._key()])||void 0===r?void 0:r.manager,o="_initialize() not called before _openPopup()",s||si(o);let a=await aC(e,t,n,sr(),i);return function(e,t,n,i=500,r=600){let s=Math.max((window.screen.availHeight-r)/2,0).toString(),o=Math.max((window.screen.availWidth-i)/2,0).toString(),a="",l=Object.assign(Object.assign({},ay),{width:i.toString(),height:r.toString(),top:s,left:o}),h=V().toLowerCase();n&&(a=sK(h)?"_blank":n),sz(h)&&(t=t||"http://localhost",l.scrollbars="yes");let c=Object.entries(l).reduce((e,[t,n])=>`${e}${t}=${n},`,"");if(function(e=V()){var t;return sX(e)&&!!(!(null===(t=window.navigator)||void 0===t)&&t.standalone)}(h)&&"_self"!==a)return function(e,t){let n=document.createElement("a");n.href=e,n.target=t;let i=document.createEvent("MouseEvent");i.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),n.dispatchEvent(i)}(t||"",a),new aw(null);let u=window.open(t||"",a,c);sn(u,e,"popup-blocked");try{u.focus()}catch{}return new aw(u)}(e,a,oj())}async _openRedirect(e,t,n,i){var r;return await this._originValidation(e),r=await aC(e,t,n,sr(),i),oV().location.href=r,new Promise(()=>{})}_initialize(e){let t=e._key();if(this.eventManagers[t]){var n;let{manager:e,promise:i}=this.eventManagers[t];return e?Promise.resolve(e):(n="If manager is not set, promise should be",i||si(n),i)}let i=this.initAndGetManager(e);return this.eventManagers[t]={promise:i},i.catch(()=>{delete this.eventManagers[t]}),i}async initAndGetManager(e){let t=await av(e),n=new as(e);return t.register("authEvent",t=>(sn(null==t?void 0:t.authEvent,e,"invalid-auth-event"),{status:n.onEvent(t.authEvent)?"ACK":"ERROR"}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[e._key()]={manager:n},this.iframes[e._key()]=t,n}_isIframeWebStorageSupported(e,t){this.iframes[e._key()].send(ab,{type:ab},n=>{var i;let r=null===(i=null==n?void 0:n[0])||void 0===i?void 0:i[ab];void 0!==r&&t(!!r),r9(e,"internal-error")},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){let t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=au(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return sZ()||s$()||sX()}}var aE="@firebase/auth",ak="1.7.9";class aS{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){var e;return this.assertAuthConfigured(),(null===(e=this.auth.currentUser)||void 0===e?void 0:e.uid)||null}async getToken(e){return this.assertAuthConfigured(),await this.auth._initializationPromise,this.auth.currentUser?{accessToken:await this.auth.currentUser.getIdToken(e)}:null}addAuthTokenListener(e){if(this.assertAuthConfigured(),this.internalListeners.has(e))return;let t=this.auth.onIdTokenChanged(t=>{e((null==t?void 0:t.stsTokenManager.accessToken)||null)});this.internalListeners.set(e,t),this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();let t=this.internalListeners.get(e);t&&(this.internalListeners.delete(e),t(),this.updateProactiveRefresh())}assertAuthConfigured(){sn(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}let aP=j("authIdTokenMaxAge")||300,aN=null,aR=e=>async t=>{let n=t&&await t.getIdTokenResult(),i=n&&(new Date().getTime()-Date.parse(n.issuedAtTime))/1e3;if(i&&i>aP)return;let r=null==n?void 0:n.token;aN!==r&&(aN=r,await fetch(e,{method:r?"POST":"DELETE",headers:r?{Authorization:`Bearer ${r}`}:{}}))};s5={loadJS:e=>
4new Promise((t,n)=>{var i,r;let s=document.createElement("script");s.setAttribute("src",e),s.onload=t,s.onerror=e=>{let t=r8("internal-error");t.customData=e,n(t)},s.type="text/javascript",s.charset="UTF-8",(null!==(r=null===(i=document.getElementsByTagName("head"))||void 0===i?void 0:i[0])&&void 0!==r?r:document).appendChild(s)}),gapiScript:"https://apis.google.com/js/api.js",recaptchaV2Script:"https://www.google.com/recaptcha/api.js",recaptchaEnterpriseScript:"https://www.google.com/recaptcha/enterprise.js?render="},y="Browser",eK(new e_("auth",(e,{options:t})=>{let n=e.getProvider("app").getImmediate(),i=e.getProvider("heartbeat"),r=e.getProvider("app-check-internal"),{apiKey:s,authDomain:o}=n.options;sn(s&&!s.includes(":"),"invalid-api-key",{appName:n.name});let a=new s4(n,i,r,{apiKey:s,authDomain:o,clientPlatform:y,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:s0(y)});return function(e,t){let n=(null==t?void 0:t.persistence)||[],i=(Array.isArray(n)?n:[n]).map(sj);null!=t&&t.errorMap&&e._updateErrorMap(t.errorMap),e._initializeWithPersistence(i,null==t?void 0:t.popupRedirectResolver)}(a,t),a},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,n)=>{e.getProvider("auth-internal").initialize()})),eK(new e_("auth-internal",e=>new aS(ef(e.getProvider("auth").getImmediate())),"PRIVATE").setInstantiationMode("EXPLICIT")),e1(aE,ak,function(e){switch(e){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";case"WebExtension":return"web-extension";default:return}}(y)),e1(aE,ak,"esm2017");let aO="",aA;if("u">typeof window){let e=window.location.hostname;e.includes("dev.vaidepromo")||e.includes("localhost")?(aO="https://dev.backsafearea.vaidepromo.com.br",aA=eZ({apiKey:"AIzaSyCv-cWJA0zjVuBNKGf6WSb_6B1hNP_r3C8",authDomain:"vai-de-promo-dev.firebaseapp.com",databaseURL:"https://vai-de-promo-dev-default-rtdb.firebaseio.com",projectId:"vai-de-promo-dev",storageBucket:"vai-de-promo-dev.appspot.com",messagingSenderId:"445506039967",appId:"1:445506039967:web:f234cadd71db13512fb2aa",measurementId:"G-23QSWHWKGW"})):(aO="https://backsafearea.vaidepromo.com.br",aA=eZ({apiKey:"AIzaSyAjTkQK8Dt2dS2fDj3XZmVfy1rDsuFIDIE",authDomain:"VAI-DE-PROMO.FIREBASEAPP.COM",databaseURL:"HTTPS://VAI-DE-PROMO-DEFAULT-RTDB.FIREBASEIO.COM",projectId:"VAI-DE-PROMO",storageBucket:"VAI-DE-PROMO.APPSPOT.COM",messagingSenderId:"548220451677",appId:"1:548220451677:WEB:9E9A995A95E98EE8E346B4",measurementId:"G-907H061FT2"}))}let aD=function(e=e0(),t){let n=eG(e,"database").getImmediate({identifier:void 0});if(!n._instanceStarted){let e=U("database");e&&function(e,t,n,i={}){var r;let s;(e=ef(e))._checkNotDeleted("useEmulator"),e._instanceStarted&&tw("Cannot call useEmulator() after instance has already been initialized.");let o=e._repoInternal;o.repoInfo_.nodeAdmin?(i.mockUserToken&&tw('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),s=new tj(tj.OWNER)):i.mockUserToken&&(s=new tj("string"==typeof i.mockUserToken?i.mockUserToken:function(e,t){if(e.uid)throw Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');let n=t||"demo-project",i=e.iat||0,r=e.sub||e.user_id;if(!r)throw Error("mockUserToken must contain 'sub' or 'user_id' field!");let s=Object.assign({iss:`https://securetoken.google.com/${n}`,aud:n,iat:i,exp:i+3600,auth_time:i,sub:r,user_id:r,firebase:{sign_in_provider:"custom",identities:{}}},e);return[O(JSON.stringify({alg:"none",type:"JWT"})),O(JSON.stringify(s)),""].join(".")}(i.mockUserToken,e.app.options.projectId))),r=s,o.repoInfo_=new tB(`${t}:${n}`,!1,o.repoInfo_.namespace,o.repoInfo_.webSocketOnly,o.repoInfo_.nodeAdmin,o.repoInfo_.persistenceKey,o.repoInfo_.includeNamespaceInQueryParams,!0),r&&(o.authTokenProvider_=r)}(n,...e)}return n}(aA),ax=function(e=e0()){let t=eG(e,"auth");if(t.isInitialized())return t.getImmediate();let n=function(e,t){let n=eG(e,"auth");if(n.isInitialized()){let e=n.getImmediate();if(ei(n.getOptions(),t??{}))return e;r9(e,"already-initialized")}return n.initialize({options:t})}(e,{popupRedirectResolver:aT,persistence:[o0,oF,oU]}),i=j("authTokenSyncURL");if(i&&"boolean"==typeof isSecureContext&&isSecureContext){let e=new URL(i,location.origin);if(location.origin===e.origin){var r,s;let t=aR(e.toString());r=()=>t(n.currentUser),ef(n).beforeAuthStateChanged(t,r),s=e=>t(e),ef(n).onIdTokenChanged(s,void 0,void 0)}}let o=F("auth");return o&&function(e,t,n){let i=ef(e);sn(i._canInitEmulator,i,"emulator-config-failed"),sn(/^https?:\/\//.test(t),i,"invalid-emulator-scheme");let r=oe(t),{host:s,port:o}=function(e){let t=oe(e),n=/(\/\/)?([^?#/]+)/.exec(e.substr(t.length));if(!n)return{host:"",port:null};let i=n[2].split("@").pop()||"",r=/^(\[[^\]]+\])(:|$)/.exec(i);if(r){let e=r[1];return{host:e,port:ot(i.substr(e.length+1))}}{let[e,t]=i.split(":");return{host:e,port:ot(t)}}}(t),a=null===o?"":`:${o}`;i.config.emulator={url:`${r}//${s}${a}/`},i.settings.appVerificationDisabledForTesting=!0,i.emulatorConfig=Object.freeze({host:s,port:o,protocol:r.replace(":",""),options:Object.freeze({disableWarnings:!1})}),function(){function e(){let e=document.createElement("p"),t=e.style;e.innerText="Running in emulator mode. Do not use with production credentials.",t.position="fixed",t.width="100%",t.backgroundColor="#ffffff",t.border=".1em solid #000000",t.color="#b50000",t.bottom="0px",t.left="0px",t.margin="0px",t.zIndex="10000",t.textAlign="center",e.classList.add("firebase-emulator-warning"),document.body.appendChild(e)}"u">typeof console&&"function"==typeof console.info&&console.info("WARNING: You are using the Auth Emulator, which is intended for local testing only. Do not use with production credentials."),"u">typeof window&&"u">typeof document&&("loading"===document.readyState?window.addEventListener("DOMContentLoaded",e):e())}()}(n,`http://${o}`),n}(aA),aL={firebaseUpdatePassword:async function(e){return await C.Z.post({url:`${aO}/firebase/update-password/`,payload:e})},firebaseSendUpdatePasswordEmail:async function(e){return await C.Z.get({url:`${aO}/firebase/send-update-password-email/${e}/`})}
4,firebaseSendVerificationEmail:async function(e){return await C.Z.get({url:`${aO}/firebase/send-verification-email/${e}/`})},firebaseVerifyEmail:async function(e){return await C.Z.post({url:`${aO}/firebase/verify-email/`,payload:e})},firebaseVerifyEmailRegistered:async function(e,t){return await C.Z.post({url:`${aO}/firebase/verify-user-exists/${e}/`,payload:{token:t}})},firebaseVerifyUpdatePasswordCode:async function(e){return await C.Z.post({url:`${aO}/firebase/verify-update-password-code/`,payload:e})}}}}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.