firebase 12.12.0 → 12.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/app/dist/esm/index.esm.js +1 -1
- package/app/dist/index.cjs.js +1 -1
- package/app/dist/index.mjs +1 -1
- package/compat/app/dist/esm/index.esm.js +1 -1
- package/compat/app/dist/index.cjs.js +1 -1
- package/compat/app/dist/index.mjs +1 -1
- package/compat/dist/esm/index.esm.js +2 -2
- package/compat/dist/index.node.cjs +2 -2
- package/compat/dist/index.rn.cjs.js +2 -2
- package/firebase-ai.js +1 -1
- package/firebase-ai.js.map +1 -1
- package/firebase-analytics.js +1 -1
- package/firebase-app-check.js +1 -1
- package/firebase-app-compat.js +2 -2
- package/firebase-app.js +4 -4
- package/firebase-auth-cordova.js +1 -1
- package/firebase-auth-web-extension.js +1 -1
- package/firebase-auth.js +1 -1
- package/firebase-compat.js +4 -4
- package/firebase-data-connect.js +1 -1
- package/firebase-database.js +1 -1
- package/firebase-firestore-compat.js +1 -1
- package/firebase-firestore-lite-pipelines.js +1 -1
- package/firebase-firestore-lite.js +1 -1
- package/firebase-firestore-pipelines.js +1 -1
- package/firebase-firestore.js +1 -1
- package/firebase-functions.js +1 -1
- package/firebase-installations.js +1 -1
- package/firebase-messaging-sw.js +1 -1
- package/firebase-messaging.js +1 -1
- package/firebase-performance-standalone-compat.js +3 -3
- package/firebase-performance.js +1 -1
- package/firebase-remote-config.js +1 -1
- package/firebase-storage.js +1 -1
- package/package.json +2 -2
package/firebase-compat.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
((e,t)=>{"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).firebase=t()})(this,function(){let n=()=>{},i={NODE_CLIENT:!1,NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"},g=function(e,t){if(!e)throw B(t)},B=function(e){return new Error("Firebase Database ("+i.SDK_VERSION+") INTERNAL ASSERT FAILED: "+e)},s=function(t){var r=[];let n=0;for(let i=0;i<t.length;i++){let e=t.charCodeAt(i);e<128?r[n++]=e:(e<2048?r[n++]=e>>6|192:(55296==(64512&e)&&i+1<t.length&&56320==(64512&t.charCodeAt(i+1))?(e=65536+((1023&e)<<10)+(1023&t.charCodeAt(++i)),r[n++]=e>>18|240,r[n++]=e>>12&63|128):r[n++]=e>>12|224,r[n++]=e>>6&63|128),r[n++]=63&e|128)}return r},a={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(r,e){if(!Array.isArray(r))throw Error("encodeByteArray takes an array as a parameter");this.init_();var n=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,i=[];for(let c=0;c<r.length;c+=3){var s=r[c],a=c+1<r.length,o=a?r[c+1]:0,l=c+2<r.length,h=l?r[c+2]:0;let e=(15&o)<<2|h>>6,t=63&h;l||(t=64,a)||(e=64),i.push(n[s>>2],n[(3&s)<<4|o>>4],n[e],n[t])}return i.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(s(e),t)},decodeString(r,n){if(this.HAS_NATIVE_SUPPORT&&!n)return atob(r);{var i=this.decodeStringToByteArray(r,n);var s=[];let e=0,t=0;for(;e<i.length;){var a,o,l,h=i[e++];h<128?s[t++]=String.fromCharCode(h):191<h&&h<224?(a=i[e++],s[t++]=String.fromCharCode((31&h)<<6|63&a)):239<h&&h<365?(a=((7&h)<<18|(63&i[e++])<<12|(63&i[e++])<<6|63&i[e++])-65536,s[t++]=String.fromCharCode(55296+(a>>10)),s[t++]=String.fromCharCode(56320+(1023&a))):(o=i[e++],l=i[e++],s[t++]=String.fromCharCode((15&h)<<12|(63&o)<<6|63&l))}return s.join("");return}},decodeStringToByteArray(e,t){this.init_();var r=t?this.charToByteMapWebSafe_:this.charToByteMap_,n=[];for(let l=0;l<e.length;){var i=r[e.charAt(l++)],s=l<e.length?r[e.charAt(l)]:0,a=++l<e.length?r[e.charAt(l)]:64,o=++l<e.length?r[e.charAt(l)]:64;if(++l,null==i||null==s||null==a||null==o)throw new j;n.push(i<<2|s>>4),64!==a&&(n.push(s<<4&240|a>>2),64!==o)&&n.push(a<<6&192|o)}return n},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),(this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e)>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class j extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}function o(e){var t=s(e);return a.encodeByteArray(t,!0)}let z=function(e){return o(e).replace(/\./g,"")},K=function(e){try{return a.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function W(e,t){if(!(t instanceof Object))return t;switch(t.constructor){case Date:return new Date(t.getTime());case Object:void 0===e&&(e={});break;case Array:e=[];break;default:return t}for(var r in t)t.hasOwnProperty(r)&&"__proto__"!==r&&(e[r]=W(e[r],t[r]));return e}function H(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}let G=()=>H().__FIREBASE_DEFAULTS__,$=()=>{var e;return"undefined"!=typeof process&&void 0!==process.env&&(e=process.env.__FIREBASE_DEFAULTS__)?JSON.parse(e):void 0},Q=()=>{if("undefined"!=typeof document){let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}var t=e&&K(e[1]);return t&&JSON.parse(t)}},Y=()=>{try{return n()||G()||$()||Q()}catch(e){console.info("Unable to get __FIREBASE_DEFAULTS__ due to: "+e)}},J=()=>Y()?.config;var p,X;class Z{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}wrapCallback(r){return(e,t)=>{e?this.reject(e):this.resolve(t),"function"==typeof r&&(this.promise.catch(()=>{}),1===r.length?r(e):r(e,t))}}}function ee(e,t){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');var r=t||"demo-project",n=e.iat||0,i=e.sub||e.user_id;if(i)return r={iss:"https://securetoken.google.com/"+r,aud:r,iat:n,exp:n+3600,auth_time:n,sub:i,user_id:i,firebase:{sign_in_provider:"custom",identities:{}},...e},[z(JSON.stringify({alg:"none",type:"JWT"})),z(JSON.stringify(r)),""].join(".");throw new Error("mockUserToken must contain 'sub' or 'user_id' field!")}function te(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function re(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(te())}function ne(){var e=Y()?.forceEnvironment;if("node"===e)return!0;if("browser"===e)return!1;try{return"[object process]"===Object.prototype.toString.call(global.process)}catch(e){return!1}}function ie(){return"undefined"!=typeof WorkerGlobalScope&&"undefined"!=typeof self&&self instanceof WorkerGlobalScope}function se(){var e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}function ae(){return"object"==typeof navigator&&"ReactNative"===navigator.product}function oe(){var e=te();return 0<=e.indexOf("MSIE ")||0<=e.indexOf("Trident/")}function le(){return!0===i.NODE_ADMIN}function he(){return!ne()&&navigator.userAgent&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}function ce(){return!ne()&&navigator.userAgent&&(navigator.userAgent.includes("Safari")||navigator.userAgent.includes("WebKit"))&&!navigator.userAgent.includes("Chrome")}function ue(){try{return"object"==typeof indexedDB}catch(e){return!1}}function de(){return new Promise((n,i)=>{try{let e=!0,t="validate-browser-context-for-indexeddb-analytics-module",r=self.indexedDB.open(t);r.onsuccess=()=>{r.result.close(),e||self.indexedDB.deleteDatabase(t),n(!0)},r.onupgradeneeded=()=>{e=!1},r.onerror=()=>{i(r.error?.message||"")}}catch(e){i(e)}})}function pe(){return!("undefined"==typeof navigator||!navigator.cookieEnabled)}class fe extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name="FirebaseError",Object.setPrototypeOf(this,fe.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ge.prototype.create)}}class ge{constructor(e,t,r){this.service=e,this.serviceName=t,this.errors=r}create(e,...t){var n,r=t[0]||{},i=this.service+"/"+e,s=this.errors[e],s=s?(n=r,s.replace(me,(e,t)=>{var r=n[t];return null!=r?String(r):`<${t}?>`})):"Error",s=this.serviceName+`: ${s} (${i}).`;return new fe(i,s,r)}}let me=/\{\$([^}]+)}/g;function ve(e){return JSON.parse(e)}function _e(e){return JSON.stringify(e)}function ye(e){let t={},r={},n={},i="";try{var s=e.split(".");t=ve(K(s[0])||""),r=ve(K(s[1])||""),i=s[2],n=r.d||{},delete r.d}catch(e){}return{header:t,claims:r,data:n,signature:i}}function we(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function be(e,t){if(Object.prototype.hasOwnProperty.call(e,t))return e[t]}function Ie(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function Te(e,t,r){var n,i={};for(n in e)Object.prototype.hasOwnProperty.call(e,n)&&(i[n]=t.call(r,e[n],n,e));return i}function Ee(e,t){if(e!==t){var r,n,i=Object.keys(e),s=Object.keys(t);for(r of i){if(!s.includes(r))return!1;var a=e[r],o=t[r];if(Ce(a)&&Ce(o)){if(!Ee(a,o))return!1}else if(a!==o)return!1}for(n of s)if(!i.includes(n))return!1}return!0}function Ce(e){return null!==e&&"object"==typeof e}function Se(e){let t=[];for(let[r,n]of Object.entries(e))Array.isArray(n)?n.forEach(e=>{t.push(encodeURIComponent(r)+"="+encodeURIComponent(e))}):t.push(encodeURIComponent(r)+"="+encodeURIComponent(n));return t.length?"&"+t.join("&"):""}function ke(e){let n={};return e.replace(/^\?/,"").split("&").forEach(e=>{var t,r;e&&([t,r]=e.split("="),n[decodeURIComponent(t)]=decodeURIComponent(r))}),n}function Ae(e){var t,r=e.indexOf("?");return r?(t=e.indexOf("#",r),e.substring(r,0<t?t:void 0)):""}class Ne{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_(r,n){n=n||0;var i=this.W_;if("string"==typeof r)for(let e=0;e<16;e++)i[e]=r.charCodeAt(n)<<24|r.charCodeAt(n+1)<<16|r.charCodeAt(n+2)<<8|r.charCodeAt(n+3),n+=4;else for(let t=0;t<16;t++)i[t]=r[n]<<24|r[n+1]<<16|r[n+2]<<8|r[n+3],n+=4;for(let d=16;d<80;d++){var e=i[d-3]^i[d-8]^i[d-14]^i[d-16];i[d]=4294967295&(e<<1|e>>>31)}let t=this.chain_[0],s=this.chain_[1],a=this.chain_[2],o=this.chain_[3],l=this.chain_[4],h,c;for(let p=0;p<80;p++){c=p<40?p<20?(h=o^s&(a^o),1518500249):(h=s^a^o,1859775393):p<60?(h=s&a|o&(s|a),2400959708):(h=s^a^o,3395469782);var u=(t<<5|t>>>27)+h+l+c+i[p]&4294967295;l=o,o=a,a=4294967295&(s<<30|s>>>2),s=t,t=u}this.chain_[0]=this.chain_[0]+t&4294967295,this.chain_[1]=this.chain_[1]+s&4294967295,this.chain_[2]=this.chain_[2]+a&4294967295,this.chain_[3]=this.chain_[3]+o&4294967295,this.chain_[4]=this.chain_[4]+l&4294967295}update(r,n){if(null!=r){var i=(n=void 0===n?r.length:n)-this.blockSize;let e=0;var s=this.buf_;let t=this.inbuf_;for(;e<n;){if(0===t)for(;e<=i;)this.compress_(r,e),e+=this.blockSize;if("string"==typeof r){for(;e<n;)if(s[t]=r.charCodeAt(e),++t,++e,t===this.blockSize){this.compress_(s),t=0;break}}else for(;e<n;)if(s[t]=r[e],++t,++e,t===this.blockSize){this.compress_(s),t=0;break}}this.inbuf_=t,this.total_+=n}}digest(){var t=[];let e=8*this.total_;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(let n=this.blockSize-1;56<=n;n--)this.buf_[n]=255&e,e/=256;this.compress_(this.buf_);let r=0;for(let i=0;i<5;i++)for(let e=24;0<=e;e-=8)t[r]=this.chain_[i]>>e&255,++r;return t}}function Re(e,t){var r=new Pe(e,t);return r.subscribe.bind(r)}class Pe{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(t){this.forEachObserver(e=>{e.next(t)})}error(t){this.forEachObserver(e=>{e.error(t)}),this.close(t)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,r){let n;if(void 0===e&&void 0===t&&void 0===r)throw new Error("Missing Observer.");void 0===(n=((e,t)=>{if("object"==typeof e&&null!==e)for(var r of t)if(r in e&&"function"==typeof e[r])return 1})(e,["next","error","complete"])?e:{next:e,error:t,complete:r}).next&&(n.next=De),void 0===n.error&&(n.error=De),void 0===n.complete&&(n.complete=De);var i=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then(()=>{try{this.finalError?n.error(this.finalError):n.complete()}catch(e){}}),this.observers.push(n),i}unsubscribeOne(e){void 0!==this.observers&&void 0!==this.observers[e]&&(delete this.observers[e],--this.observerCount,0===this.observerCount)&&void 0!==this.onNoObservers&&this.onNoObservers(this)}forEachObserver(t){if(!this.finalized)for(let e=0;e<this.observers.length;e++)this.sendOne(e,t)}sendOne(e,t){this.task.then(()=>{if(void 0!==this.observers&&void 0!==this.observers[e])try{t(this.observers[e])}catch(e){"undefined"!=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 De(){}function l(e,t,r,n){let i;var s;if(n<t?i="at least "+t:r<n&&(i=0===r?"none":"no more than "+r),i)throw s=e+" failed: Was called with "+n+(1===n?" argument.":" arguments.")+" Expects "+i+".",new Error(s)}function xe(e,t){return e+` failed: ${t} argument `}function Oe(e,t,r,n){if((!n||r)&&"function"!=typeof r)throw new Error(xe(e,t)+"must be a valid function.")}function Me(e,t,r,n){if((!n||r)&&("object"!=typeof r||null===r))throw new Error(xe(e,t)+"must be a valid context object.")}let Le=function(e){let t=0;for(let n=0;n<e.length;n++){var r=e.charCodeAt(n);r<128?t++:r<2048?t+=2:55296<=r&&r<=56319?(t+=4,n++):t+=3}return t},Fe=1e3,Ue=2,Ve=144e5,qe=.5;function Be(e,t=Fe,r=Ue){var n=t*Math.pow(r,e),i=Math.round(qe*n*(Math.random()-.5)*2);return Math.min(Ve,n+i)}function w(e){return e&&e._delegate?e._delegate:e}function je(e){try{return(e.startsWith("http://")||e.startsWith("https://")?new URL(e).hostname:e).endsWith(".cloudworkstations.dev")}catch{return!1}}async function ze(e){return(await fetch(e,{credentials:"include"})).ok}class c{constructor(e,t,r){this.name=e,this.instanceFactory=t,this.type=r,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 Ke="[DEFAULT]";class We{constructor(e,t){this.name=e,this.container=t,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){var t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){var r=new Z;if(this.instancesDeferred.set(t,r),this.isInitialized(t)||this.shouldAutoInitialize())try{var n=this.getOrInitializeService({instanceIdentifier:t});n&&r.resolve(n)}catch(e){}}return this.instancesDeferred.get(t).promise}getImmediate(e){var t=this.normalizeInstanceIdentifier(e?.identifier),r=e?.optional??!1;if(!this.isInitialized(t)&&!this.shouldAutoInitialize()){if(r)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:t})}catch(e){if(r)return null;throw e}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,this.shouldAutoInitialize()){if("EAGER"===e.instantiationMode)try{this.getOrInitializeService({instanceIdentifier:Ke})}catch(e){}for(var[t,r]of this.instancesDeferred.entries()){t=this.normalizeInstanceIdentifier(t);try{var n=this.getOrInitializeService({instanceIdentifier:t});r.resolve(n)}catch(e){}}}}clearInstance(e=Ke){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){var e=Array.from(this.instances.values());await Promise.all([...e.filter(e=>"INTERNAL"in e).map(e=>e.INTERNAL.delete()),...e.filter(e=>"_delete"in e).map(e=>e._delete())])}isComponentSet(){return null!=this.component}isInitialized(e=Ke){return this.instances.has(e)}getOptions(e=Ke){return this.instancesOptions.get(e)||{}}initialize(e={}){var{options:t={}}=e,r=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(r))throw Error(this.name+`(${r}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);var n,i,s=this.getOrInitializeService({instanceIdentifier:r,options:t});for([n,i]of this.instancesDeferred.entries())r===this.normalizeInstanceIdentifier(n)&&i.resolve(s);return s}onInit(e,t){var r=this.normalizeInstanceIdentifier(t);let n=this.onInitCallbacks.get(r)??new Set;n.add(e),this.onInitCallbacks.set(r,n);var i=this.instances.get(r);return i&&e(i,r),()=>{n.delete(e)}}invokeOnInitCallbacks(e,t){var r=this.onInitCallbacks.get(t);if(r)for(var n of r)try{n(e,t)}catch{}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let r=this.instances.get(e);if(!r&&this.component&&(r=this.component.instanceFactory(this.container,{instanceIdentifier:(n=e)===Ke?void 0:n,options:t}),this.instances.set(e,r),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(r,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,r)}catch{}var n;return r||null}normalizeInstanceIdentifier(e=Ke){return!this.component||this.component.multipleInstances?e:Ke}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class He{constructor(e){this.name=e,this.providers=new Map}addComponent(e){var t=this.getProvider(e.name);if(t.isComponentSet())throw new Error(`Component ${e.name} has already been registered with `+this.name);t.setComponent(e)}addOrOverwriteComponent(e){this.getProvider(e.name).isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){var t;return this.providers.has(e)?this.providers.get(e):(t=new We(e,this),this.providers.set(e,t),t)}getProviders(){return Array.from(this.providers.values())}}let Ge=[],$e=((t=p=p||{})[t.DEBUG=0]="DEBUG",t[t.VERBOSE=1]="VERBOSE",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.SILENT=5]="SILENT",{debug:p.DEBUG,verbose:p.VERBOSE,info:p.INFO,warn:p.WARN,error:p.ERROR,silent:p.SILENT}),Qe=p.INFO,Ye={[p.DEBUG]:"log",[p.VERBOSE]:"log",[p.INFO]:"info",[p.WARN]:"warn",[p.ERROR]:"error"},Je=(e,t,...r)=>{if(!(t<e.logLevel)){var n=(new Date).toISOString(),i=Ye[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${n}] ${e.name}:`,...r)}};class Xe{constructor(e){this.name=e,this._logLevel=Qe,this._logHandler=Je,this._userLogHandler=null,Ge.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in p))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?$e[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,p.DEBUG,...e),this._logHandler(this,p.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,p.VERBOSE,...e),this._logHandler(this,p.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,p.INFO,...e),this._logHandler(this,p.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,p.WARN,...e),this._logHandler(this,p.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,p.ERROR,...e),this._logHandler(this,p.ERROR,...e)}}let Ze=(t,e)=>e.some(e=>t instanceof e),et,tt;let rt=new WeakMap,nt=new WeakMap,it=new WeakMap,st=new WeakMap,at=new WeakMap;let ot={get(e,t,r){if(e instanceof IDBTransaction){if("done"===t)return nt.get(e);if("objectStoreNames"===t)return e.objectStoreNames||it.get(e);if("store"===t)return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return ct(e[t])},set(e,t,r){return e[t]=r,!0},has(e,t){return e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e}};function lt(n){return n!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(tt=tt||[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey]).includes(n)?function(...e){return n.apply(ut(this),e),ct(rt.get(this))}:function(...e){return ct(n.apply(ut(this),e))}:function(e,...t){var r=n.call(ut(this),e,...t);return it.set(r,e.sort?e.sort():[e]),ct(r)}}function ht(e){var s,t;return"function"==typeof e?lt(e):(e instanceof IDBTransaction&&(s=e,nt.has(s)||(t=new Promise((e,t)=>{let r=()=>{s.removeEventListener("complete",n),s.removeEventListener("error",i),s.removeEventListener("abort",i)},n=()=>{e(),r()},i=()=>{t(s.error||new DOMException("AbortError","AbortError")),r()};s.addEventListener("complete",n),s.addEventListener("error",i),s.addEventListener("abort",i)}),nt.set(s,t))),Ze(e,et=et||[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])?new Proxy(e,ot):e)}function ct(e){var s,t;return e instanceof IDBRequest?(s=e,(t=new Promise((e,t)=>{let r=()=>{s.removeEventListener("success",n),s.removeEventListener("error",i)},n=()=>{e(ct(s.result)),r()},i=()=>{t(s.error),r()};s.addEventListener("success",n),s.addEventListener("error",i)})).then(e=>{e instanceof IDBCursor&&rt.set(e,s)}).catch(()=>{}),at.set(t,s),t):st.has(e)?st.get(e):((t=ht(e))!==e&&(st.set(e,t),at.set(t,e)),t)}let ut=e=>at.get(e);function dt(e,t,{blocked:r,upgrade:n,blocking:i,terminated:s}={}){let a=indexedDB.open(e,t);var o=ct(a);return n&&a.addEventListener("upgradeneeded",e=>{n(ct(a.result),e.oldVersion,e.newVersion,ct(a.transaction),e)}),r&&a.addEventListener("blocked",e=>r(e.oldVersion,e.newVersion,e)),o.then(e=>{s&&e.addEventListener("close",()=>s()),i&&e.addEventListener("versionchange",e=>i(e.oldVersion,e.newVersion,e))}).catch(()=>{}),o}function pt(e,{blocked:t}={}){var r=indexedDB.deleteDatabase(e);return t&&r.addEventListener("blocked",e=>t(e.oldVersion,e)),ct(r).then(()=>{})}let ft=["get","getKey","getAll","getAllKeys","count"],gt=["put","add","delete","clear"],mt=new Map;function vt(e,t){if(e instanceof IDBDatabase&&!(t in e)&&"string"==typeof t){if(mt.get(t))return mt.get(t);let i=t.replace(/FromIndex$/,""),s=t!==i,a=gt.includes(i);var r;return i in(s?IDBIndex:IDBObjectStore).prototype&&(a||ft.includes(i))?(r=async function(e,...t){var r=this.transaction(e,a?"readwrite":"readonly");let n=r.store;return s&&(n=n.index(t.shift())),(await Promise.all([n[i](...t),a&&r.done]))[0]},mt.set(t,r),r):void 0}}ot={...X=ot,get:(e,t,r)=>vt(e,t)||X.get(e,t,r),has:(e,t)=>!!vt(e,t)||X.has(e,t)};class _t{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(e=>{var t;return"VERSION"===e.getComponent()?.type?(t=e.getImmediate()).library+"/"+t.version:null}).filter(e=>e).join(" ")}}let yt="@firebase/app",wt="0.14.11",bt=new Xe("@firebase/app");let It="[DEFAULT]",Tt={"@firebase/app":"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/ai":"fire-vertex","fire-js":"fire-js",firebase:"fire-js-all"},Et=new Map,Ct=new Map,St=new Map;function kt(t,r){try{t.container.addComponent(r)}catch(e){bt.debug(`Component ${r.name} failed to register with FirebaseApp `+t.name,e)}}function At(e,t){e.container.addOrOverwriteComponent(t)}function Nt(e){var t,r,n=e.name;if(St.has(n))return bt.debug(`There were multiple attempts to register component ${n}.`),!1;St.set(n,e);for(t of Et.values())kt(t,e);for(r of Ct.values())kt(r,e);return!0}function Rt(e,t){var r=e.container.getProvider("heartbeat").getImmediate({optional:!0});return r&&r.triggerHeartbeat(),e.container.getProvider(t)}function Pt(e){return void 0!==e.options}function Dt(e){return!Pt(e)&&("authIdToken"in e||"appCheckToken"in e||"releaseOnDeref"in e||"automaticDataCollectionEnabled"in e)}function h(e){return null!=e&&void 0!==e.settings}let xt=new ge("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 Ot{constructor(e,t,r){this._isDeleted=!1,this._options={...e},this._config={...t},this._name=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled,this._container=r,this.container.addComponent(new c("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 xt.create("app-deleted",{appName:this._name})}}function Mt(e,t){var r=K(e.split(".")[1]);null===r?console.error(`FirebaseServerApp ${t} is invalid: second part could not be parsed.`):void 0===JSON.parse(r).exp?console.error(`FirebaseServerApp ${t} is invalid: expiration claim could not be parsed`):1e3*JSON.parse(r).exp-(new Date).getTime()<=0&&console.error(`FirebaseServerApp ${t} is invalid: the token has expired.`)}class Lt extends Ot{constructor(e,t,r,n){var i=void 0===t.automaticDataCollectionEnabled||t.automaticDataCollectionEnabled,s={name:r,automaticDataCollectionEnabled:i};void 0!==e.apiKey?super(e,s,n):super(e.options,s,n),this._serverConfig={automaticDataCollectionEnabled:i,...t},this._serverConfig.authIdToken&&Mt(this._serverConfig.authIdToken,"authIdToken"),this._serverConfig.appCheckToken&&Mt(this._serverConfig.appCheckToken,"appCheckToken"),this._finalizationRegistry=null,"undefined"!=typeof FinalizationRegistry&&(this._finalizationRegistry=new FinalizationRegistry(()=>{this.automaticCleanup()})),this._refCount=0,this.incRefCount(this._serverConfig.releaseOnDeref),this._serverConfig.releaseOnDeref=void 0,t.releaseOnDeref=void 0,u(yt,wt,"serverapp")}toJSON(){}get refCount(){return this._refCount}incRefCount(e){this.isDeleted||(this._refCount++,void 0!==e&&null!==this._finalizationRegistry&&this._finalizationRegistry.register(e,this))}decRefCount(){return this.isDeleted?0:--this._refCount}automaticCleanup(){qt(this)}get settings(){return this.checkDestroyed(),this._serverConfig}checkDestroyed(){if(this.isDeleted)throw xt.create("server-app-deleted")}}let Ft="12.12.0";function Ut(e,t={}){let r=e;if("object"!=typeof t){let e=t;t={name:e}}var n={name:It,automaticDataCollectionEnabled:!0,...t};let i=n.name;if("string"!=typeof i||!i)throw xt.create("bad-app-name",{appName:String(i)});if(!(r=r||J()))throw xt.create("no-options");var s=Et.get(i);if(s){if(Ee(r,s.options)&&Ee(n,s.config))return s;throw xt.create("duplicate-app",{appName:i})}var a,o=new He(i);for(a of St.values())o.addComponent(a);s=new Ot(r,n,o);return Et.set(i,s),s}function Vt(e=It){var t=Et.get(e);if(!t&&e===It&&J())return Ut();if(t)return t;throw xt.create("no-app",{appName:e})}async function qt(e){let t=!1;var r=e.name;Et.has(r)?(t=!0,Et.delete(r)):Ct.has(r)&&e.decRefCount()<=0&&(Ct.delete(r),t=!0),t&&(await Promise.all(e.container.getProviders().map(e=>e.delete())),e.isDeleted=!0)}function u(e,t,r){let n=Tt[e]??e;r&&(n+="-"+r);var i,s=n.match(/\s|\//),a=t.match(/\s|\//);s||a?(i=[`Unable to register library "${n}" with version "${t}":`],s&&i.push(`library name "${n}" contains illegal characters (whitespace or "/")`),s&&a&&i.push("and"),a&&i.push(`version name "${t}" contains illegal characters (whitespace or "/")`),bt.warn(i.join(" "))):Nt(new c(n+"-version",()=>({library:n,version:t}),"VERSION"))}function Bt(e,t){if(null!==e&&"function"!=typeof e)throw xt.create("invalid-log-argument");var r,s=e,n=t;for(r of Ge){let i=null;n&&n.level&&(i=$e[n.level]),r.userLogHandler=null===s?null:(e,t,...r)=>{var n=r.map(e=>{if(null==e)return null;if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e)return e.toString();if(e instanceof Error)return e.message;try{return JSON.stringify(e)}catch(e){return null}}).filter(e=>e).join(" ");t>=(i??e.logLevel)&&s({level:p[t].toLowerCase(),message:n,args:r,type:e.name})}}}function jt(e){var t;t=e,Ge.forEach(e=>{e.setLogLevel(t)})}let zt="firebase-heartbeat-database",Kt=1,Wt="firebase-heartbeat-store",Ht=null;function Gt(){return Ht=Ht||dt(zt,Kt,{upgrade:(e,t)=>{if(0===t)try{e.createObjectStore(Wt)}catch(e){console.warn(e)}}}).catch(e=>{throw xt.create("idb-open",{originalErrorMessage:e.message})})}async function $t(e,t){try{var r=(await Gt()).transaction(Wt,"readwrite");await r.objectStore(Wt).put(t,Qt(e)),await r.done}catch(e){e instanceof fe?bt.warn(e.message):(r=xt.create("idb-set",{originalErrorMessage:e?.message}),bt.warn(r.message))}}function Qt(e){return e.name+"!"+e.options.appId}class Yt{constructor(e){this.container=e,this._heartbeatsCache=null;var t=this.container.getProvider("app").getImmediate();this._storage=new Xt(t),this._heartbeatsCachePromise=this._storage.read().then(e=>this._heartbeatsCache=e)}async triggerHeartbeat(){try{var e,r=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString();let t=Jt();if(null!=this._heartbeatsCache?.heartbeats||(this._heartbeatsCache=await this._heartbeatsCachePromise,null!=this._heartbeatsCache?.heartbeats))if(this._heartbeatsCache.lastSentHeartbeatDate!==t&&!this._heartbeatsCache.heartbeats.some(e=>e.date===t))return this._heartbeatsCache.heartbeats.push({date:t,agent:r}),30<this._heartbeatsCache.heartbeats.length&&(e=(e=>{if(0===e.length)return-1;let t=0,r=e[0].date;for(let n=1;n<e.length;n++)e[n].date<r&&(r=e[n].date,t=n);return t})(this._heartbeatsCache.heartbeats),this._heartbeatsCache.heartbeats.splice(e,1)),this._storage.overwrite(this._heartbeatsCache)}catch(e){bt.warn(e)}}async getHeartbeatsHeader(){try{var e,t,r,n;return(null===this._heartbeatsCache&&await this._heartbeatsCachePromise,null==this._heartbeatsCache?.heartbeats||0===this._heartbeatsCache.heartbeats.length)?"":(e=Jt(),{heartbeatsToSend:t,unsentEntries:r}=((e,t=1024)=>{let r=[],n=e.slice();for(let s of e){var i=r.find(e=>e.agent===s.agent);if(i){if(i.dates.push(s.date),Zt(r)>t){i.dates.pop();break}}else if(r.push({agent:s.agent,dates:[s.date]}),Zt(r)>t){r.pop();break}n=n.slice(1)}return{heartbeatsToSend:r,unsentEntries:n}})(this._heartbeatsCache.heartbeats),n=z(JSON.stringify({version:2,heartbeats:t})),this._heartbeatsCache.lastSentHeartbeatDate=e,0<r.length?(this._heartbeatsCache.heartbeats=r,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),n)}catch(e){return bt.warn(e),""}}}function Jt(){return(new Date).toISOString().substring(0,10)}class Xt{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!ue()&&de().then(()=>!0).catch(()=>!1)}async read(){var e;return await this._canUseIndexedDBPromise&&(e=await(async e=>{try{var t=(await Gt()).transaction(Wt),r=await t.objectStore(Wt).get(Qt(e));return await t.done,r}catch(e){e instanceof fe?bt.warn(e.message):(t=xt.create("idb-get",{originalErrorMessage:e?.message}),bt.warn(t.message))}})(this.app))?.heartbeats?e:{heartbeats:[]}}async overwrite(e){var t;if(await this._canUseIndexedDBPromise)return t=await this.read(),$t(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??t.lastSentHeartbeatDate,heartbeats:e.heartbeats})}async add(e){var t;if(await this._canUseIndexedDBPromise)return t=await this.read(),$t(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??t.lastSentHeartbeatDate,heartbeats:[...t.heartbeats,...e.heartbeats]})}}function Zt(e){return z(JSON.stringify({version:2,heartbeats:e})).length}t="",Nt(new c("platform-logger",e=>new _t(e),"PRIVATE")),Nt(new c("heartbeat",e=>new Yt(e),"PRIVATE")),u(yt,wt,t),u(yt,wt,"esm2020"),u("fire-js","");var er=Object.freeze({__proto__:null,SDK_VERSION:Ft,_DEFAULT_ENTRY_NAME:It,_addComponent:kt,_addOrOverwriteComponent:At,_apps:Et,_clearComponents:function(){St.clear()},_components:St,_getProvider:Rt,_isFirebaseApp:Pt,_isFirebaseServerApp:h,_isFirebaseServerAppSettings:Dt,_registerComponent:Nt,_removeServiceInstance:function(e,t,r=It){Rt(e,t).clearInstance(r)},_serverApps:Ct,deleteApp:qt,getApp:Vt,getApps:function(){return Array.from(Et.values())},initializeApp:Ut,initializeServerApp:function(e,t={}){if(("undefined"!=typeof window||ie())&&!ie())throw xt.create("invalid-server-app-environment");let r,n=t||{};if(e&&(Pt(e)?r=e.options:Dt(e)?n=e:r=e),void 0===n.automaticDataCollectionEnabled&&(n.automaticDataCollectionEnabled=!0),!(r=r||J()))throw xt.create("no-options");var i={...n,...r};if(void 0!==i.releaseOnDeref&&delete i.releaseOnDeref,void 0!==n.releaseOnDeref&&"undefined"==typeof FinalizationRegistry)throw xt.create("finalization-registry-not-supported",{});var i=""+[...JSON.stringify(i)].reduce((e,t)=>Math.imul(31,e)+t.charCodeAt(0)|0,0),s=Ct.get(i);if(s)s.incRefCount(n.releaseOnDeref);else{var a,o=new He(i);for(a of St.values())o.addComponent(a);s=new Lt(r,n,i,o),Ct.set(i,s)}return s},onLog:Bt,registerVersion:u,setLogLevel:jt,FirebaseError:fe});class tr{constructor(e,t){this._delegate=e,this.firebase=t,kt(e,new c("app-compat",()=>this,"PUBLIC")),this.container=e.container}get automaticDataCollectionEnabled(){return this._delegate.automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this._delegate.automaticDataCollectionEnabled=e}get name(){return this._delegate.name}get options(){return this._delegate.options}delete(){return new Promise(e=>{this._delegate.checkDestroyed(),e()}).then(()=>(this.firebase.INTERNAL.removeApp(this.name),qt(this._delegate)))}_getService(e,t=It){this._delegate.checkDestroyed();var r=this._delegate.container.getProvider(e);return r.isInitialized()||"EXPLICIT"!==r.getComponent()?.instantiationMode||r.initialize(),r.getImmediate({identifier:t})}_removeServiceInstance(e,t=It){this._delegate.container.getProvider(e).clearInstance(t)}_addComponent(e){kt(this._delegate,e)}_addOrOverwriteComponent(e){At(this._delegate,e)}toJSON(){return{name:this.name,automaticDataCollectionEnabled:this.automaticDataCollectionEnabled,options:this.options}}}let rr=new ge("app-compat","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance."});function nr(i){let s={},a={__esModule:!0,initializeApp:function(e,t={}){var r=Ut(e,t);if(we(s,r.name))return s[r.name];var n=new i(r,a);return s[r.name]=n},app:o,registerVersion:u,setLogLevel:jt,onLog:Bt,apps:null,SDK_VERSION:Ft,INTERNAL:{registerComponent:function(t){let r=t.name,n=r.replace("-compat","");{var e;Nt(t)&&"PUBLIC"===t.type&&(e=(e=o())=>{if("function"!=typeof e[n])throw rr.create("invalid-app-argument",{appName:r});return e[n]()},void 0!==t.serviceProps&&W(e,t.serviceProps),a[n]=e,i.prototype[n]=function(...e){return this._getService.bind(this,r).apply(this,t.multipleInstances?e:[])})}return"PUBLIC"===t.type?a[n]:null},removeApp:function(e){delete s[e]},useAsService:function(e,t){if("serverAuth"===t)return null;var r=t;return r},modularAPIs:er}};function o(e){if(e=e||It,we(s,e))return s[e];throw rr.create("no-app",{appName:e})}return a.default=a,Object.defineProperty(a,"apps",{get:function(){return Object.keys(s).map(e=>s[e])}}),o.App=i,a}var ir=function e(){let t=nr(tr);return t.INTERNAL={...t.INTERNAL,createFirebaseNamespace:e,extendNamespace:function(e){W(t,e)},createSubscribe:Re,ErrorFactory:ge,deepExtend:W},t}(),sr=new Xe("@firebase/app-compat");try{var ar=H();void 0!==ar.firebase&&(sr.warn(`
|
|
1
|
+
((e,t)=>{"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).firebase=t()})(this,function(){let n=()=>{},i={NODE_CLIENT:!1,NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"},g=function(e,t){if(!e)throw B(t)},B=function(e){return new Error("Firebase Database ("+i.SDK_VERSION+") INTERNAL ASSERT FAILED: "+e)},s=function(t){var r=[];let n=0;for(let i=0;i<t.length;i++){let e=t.charCodeAt(i);e<128?r[n++]=e:(e<2048?r[n++]=e>>6|192:(55296==(64512&e)&&i+1<t.length&&56320==(64512&t.charCodeAt(i+1))?(e=65536+((1023&e)<<10)+(1023&t.charCodeAt(++i)),r[n++]=e>>18|240,r[n++]=e>>12&63|128):r[n++]=e>>12|224,r[n++]=e>>6&63|128),r[n++]=63&e|128)}return r},a={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(r,e){if(!Array.isArray(r))throw Error("encodeByteArray takes an array as a parameter");this.init_();var n=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,i=[];for(let c=0;c<r.length;c+=3){var s=r[c],a=c+1<r.length,o=a?r[c+1]:0,l=c+2<r.length,h=l?r[c+2]:0;let e=(15&o)<<2|h>>6,t=63&h;l||(t=64,a)||(e=64),i.push(n[s>>2],n[(3&s)<<4|o>>4],n[e],n[t])}return i.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(s(e),t)},decodeString(r,n){if(this.HAS_NATIVE_SUPPORT&&!n)return atob(r);{var i=this.decodeStringToByteArray(r,n);var s=[];let e=0,t=0;for(;e<i.length;){var a,o,l,h=i[e++];h<128?s[t++]=String.fromCharCode(h):191<h&&h<224?(a=i[e++],s[t++]=String.fromCharCode((31&h)<<6|63&a)):239<h&&h<365?(a=((7&h)<<18|(63&i[e++])<<12|(63&i[e++])<<6|63&i[e++])-65536,s[t++]=String.fromCharCode(55296+(a>>10)),s[t++]=String.fromCharCode(56320+(1023&a))):(o=i[e++],l=i[e++],s[t++]=String.fromCharCode((15&h)<<12|(63&o)<<6|63&l))}return s.join("");return}},decodeStringToByteArray(e,t){this.init_();var r=t?this.charToByteMapWebSafe_:this.charToByteMap_,n=[];for(let l=0;l<e.length;){var i=r[e.charAt(l++)],s=l<e.length?r[e.charAt(l)]:0,a=++l<e.length?r[e.charAt(l)]:64,o=++l<e.length?r[e.charAt(l)]:64;if(++l,null==i||null==s||null==a||null==o)throw new j;n.push(i<<2|s>>4),64!==a&&(n.push(s<<4&240|a>>2),64!==o)&&n.push(a<<6&192|o)}return n},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),(this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e)>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class j extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}function o(e){var t=s(e);return a.encodeByteArray(t,!0)}let z=function(e){return o(e).replace(/\./g,"")},K=function(e){try{return a.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function W(e,t){if(!(t instanceof Object))return t;switch(t.constructor){case Date:return new Date(t.getTime());case Object:void 0===e&&(e={});break;case Array:e=[];break;default:return t}for(var r in t)t.hasOwnProperty(r)&&"__proto__"!==r&&(e[r]=W(e[r],t[r]));return e}function H(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}let G=()=>H().__FIREBASE_DEFAULTS__,$=()=>{var e;return"undefined"!=typeof process&&void 0!==process.env&&(e=process.env.__FIREBASE_DEFAULTS__)?JSON.parse(e):void 0},Q=()=>{if("undefined"!=typeof document){let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}var t=e&&K(e[1]);return t&&JSON.parse(t)}},Y=()=>{try{return n()||G()||$()||Q()}catch(e){console.info("Unable to get __FIREBASE_DEFAULTS__ due to: "+e)}},J=()=>Y()?.config;var p,X;class Z{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}wrapCallback(r){return(e,t)=>{e?this.reject(e):this.resolve(t),"function"==typeof r&&(this.promise.catch(()=>{}),1===r.length?r(e):r(e,t))}}}function ee(e,t){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');var r=t||"demo-project",n=e.iat||0,i=e.sub||e.user_id;if(i)return r={iss:"https://securetoken.google.com/"+r,aud:r,iat:n,exp:n+3600,auth_time:n,sub:i,user_id:i,firebase:{sign_in_provider:"custom",identities:{}},...e},[z(JSON.stringify({alg:"none",type:"JWT"})),z(JSON.stringify(r)),""].join(".");throw new Error("mockUserToken must contain 'sub' or 'user_id' field!")}function te(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function re(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(te())}function ne(){var e=Y()?.forceEnvironment;if("node"===e)return!0;if("browser"===e)return!1;try{return"[object process]"===Object.prototype.toString.call(global.process)}catch(e){return!1}}function ie(){return"undefined"!=typeof WorkerGlobalScope&&"undefined"!=typeof self&&self instanceof WorkerGlobalScope}function se(){var e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}function ae(){return"object"==typeof navigator&&"ReactNative"===navigator.product}function oe(){var e=te();return 0<=e.indexOf("MSIE ")||0<=e.indexOf("Trident/")}function le(){return!0===i.NODE_ADMIN}function he(){return!ne()&&navigator.userAgent&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}function ce(){return!ne()&&navigator.userAgent&&(navigator.userAgent.includes("Safari")||navigator.userAgent.includes("WebKit"))&&!navigator.userAgent.includes("Chrome")}function ue(){try{return"object"==typeof indexedDB}catch(e){return!1}}function de(){return new Promise((n,i)=>{try{let e=!0,t="validate-browser-context-for-indexeddb-analytics-module",r=self.indexedDB.open(t);r.onsuccess=()=>{r.result.close(),e||self.indexedDB.deleteDatabase(t),n(!0)},r.onupgradeneeded=()=>{e=!1},r.onerror=()=>{i(r.error?.message||"")}}catch(e){i(e)}})}function pe(){return!("undefined"==typeof navigator||!navigator.cookieEnabled)}class fe extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name="FirebaseError",Object.setPrototypeOf(this,fe.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ge.prototype.create)}}class ge{constructor(e,t,r){this.service=e,this.serviceName=t,this.errors=r}create(e,...t){var n,r=t[0]||{},i=this.service+"/"+e,s=this.errors[e],s=s?(n=r,s.replace(me,(e,t)=>{var r=n[t];return null!=r?String(r):`<${t}?>`})):"Error",s=this.serviceName+`: ${s} (${i}).`;return new fe(i,s,r)}}let me=/\{\$([^}]+)}/g;function ve(e){return JSON.parse(e)}function _e(e){return JSON.stringify(e)}function ye(e){let t={},r={},n={},i="";try{var s=e.split(".");t=ve(K(s[0])||""),r=ve(K(s[1])||""),i=s[2],n=r.d||{},delete r.d}catch(e){}return{header:t,claims:r,data:n,signature:i}}function we(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function be(e,t){if(Object.prototype.hasOwnProperty.call(e,t))return e[t]}function Ie(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function Te(e,t,r){var n,i={};for(n in e)Object.prototype.hasOwnProperty.call(e,n)&&(i[n]=t.call(r,e[n],n,e));return i}function Ee(e,t){if(e!==t){var r,n,i=Object.keys(e),s=Object.keys(t);for(r of i){if(!s.includes(r))return!1;var a=e[r],o=t[r];if(Ce(a)&&Ce(o)){if(!Ee(a,o))return!1}else if(a!==o)return!1}for(n of s)if(!i.includes(n))return!1}return!0}function Ce(e){return null!==e&&"object"==typeof e}function Se(e){let t=[];for(let[r,n]of Object.entries(e))Array.isArray(n)?n.forEach(e=>{t.push(encodeURIComponent(r)+"="+encodeURIComponent(e))}):t.push(encodeURIComponent(r)+"="+encodeURIComponent(n));return t.length?"&"+t.join("&"):""}function ke(e){let n={};return e.replace(/^\?/,"").split("&").forEach(e=>{var t,r;e&&([t,r]=e.split("="),n[decodeURIComponent(t)]=decodeURIComponent(r))}),n}function Ae(e){var t,r=e.indexOf("?");return r?(t=e.indexOf("#",r),e.substring(r,0<t?t:void 0)):""}class Ne{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_(r,n){n=n||0;var i=this.W_;if("string"==typeof r)for(let e=0;e<16;e++)i[e]=r.charCodeAt(n)<<24|r.charCodeAt(n+1)<<16|r.charCodeAt(n+2)<<8|r.charCodeAt(n+3),n+=4;else for(let t=0;t<16;t++)i[t]=r[n]<<24|r[n+1]<<16|r[n+2]<<8|r[n+3],n+=4;for(let d=16;d<80;d++){var e=i[d-3]^i[d-8]^i[d-14]^i[d-16];i[d]=4294967295&(e<<1|e>>>31)}let t=this.chain_[0],s=this.chain_[1],a=this.chain_[2],o=this.chain_[3],l=this.chain_[4],h,c;for(let p=0;p<80;p++){c=p<40?p<20?(h=o^s&(a^o),1518500249):(h=s^a^o,1859775393):p<60?(h=s&a|o&(s|a),2400959708):(h=s^a^o,3395469782);var u=(t<<5|t>>>27)+h+l+c+i[p]&4294967295;l=o,o=a,a=4294967295&(s<<30|s>>>2),s=t,t=u}this.chain_[0]=this.chain_[0]+t&4294967295,this.chain_[1]=this.chain_[1]+s&4294967295,this.chain_[2]=this.chain_[2]+a&4294967295,this.chain_[3]=this.chain_[3]+o&4294967295,this.chain_[4]=this.chain_[4]+l&4294967295}update(r,n){if(null!=r){var i=(n=void 0===n?r.length:n)-this.blockSize;let e=0;var s=this.buf_;let t=this.inbuf_;for(;e<n;){if(0===t)for(;e<=i;)this.compress_(r,e),e+=this.blockSize;if("string"==typeof r){for(;e<n;)if(s[t]=r.charCodeAt(e),++t,++e,t===this.blockSize){this.compress_(s),t=0;break}}else for(;e<n;)if(s[t]=r[e],++t,++e,t===this.blockSize){this.compress_(s),t=0;break}}this.inbuf_=t,this.total_+=n}}digest(){var t=[];let e=8*this.total_;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(let n=this.blockSize-1;56<=n;n--)this.buf_[n]=255&e,e/=256;this.compress_(this.buf_);let r=0;for(let i=0;i<5;i++)for(let e=24;0<=e;e-=8)t[r]=this.chain_[i]>>e&255,++r;return t}}function Re(e,t){var r=new Pe(e,t);return r.subscribe.bind(r)}class Pe{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(t){this.forEachObserver(e=>{e.next(t)})}error(t){this.forEachObserver(e=>{e.error(t)}),this.close(t)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,r){let n;if(void 0===e&&void 0===t&&void 0===r)throw new Error("Missing Observer.");void 0===(n=((e,t)=>{if("object"==typeof e&&null!==e)for(var r of t)if(r in e&&"function"==typeof e[r])return 1})(e,["next","error","complete"])?e:{next:e,error:t,complete:r}).next&&(n.next=De),void 0===n.error&&(n.error=De),void 0===n.complete&&(n.complete=De);var i=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then(()=>{try{this.finalError?n.error(this.finalError):n.complete()}catch(e){}}),this.observers.push(n),i}unsubscribeOne(e){void 0!==this.observers&&void 0!==this.observers[e]&&(delete this.observers[e],--this.observerCount,0===this.observerCount)&&void 0!==this.onNoObservers&&this.onNoObservers(this)}forEachObserver(t){if(!this.finalized)for(let e=0;e<this.observers.length;e++)this.sendOne(e,t)}sendOne(e,t){this.task.then(()=>{if(void 0!==this.observers&&void 0!==this.observers[e])try{t(this.observers[e])}catch(e){"undefined"!=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 De(){}function l(e,t,r,n){let i;var s;if(n<t?i="at least "+t:r<n&&(i=0===r?"none":"no more than "+r),i)throw s=e+" failed: Was called with "+n+(1===n?" argument.":" arguments.")+" Expects "+i+".",new Error(s)}function xe(e,t){return e+` failed: ${t} argument `}function Oe(e,t,r,n){if((!n||r)&&"function"!=typeof r)throw new Error(xe(e,t)+"must be a valid function.")}function Me(e,t,r,n){if((!n||r)&&("object"!=typeof r||null===r))throw new Error(xe(e,t)+"must be a valid context object.")}let Le=function(e){let t=0;for(let n=0;n<e.length;n++){var r=e.charCodeAt(n);r<128?t++:r<2048?t+=2:55296<=r&&r<=56319?(t+=4,n++):t+=3}return t},Fe=1e3,Ue=2,Ve=144e5,qe=.5;function Be(e,t=Fe,r=Ue){var n=t*Math.pow(r,e),i=Math.round(qe*n*(Math.random()-.5)*2);return Math.min(Ve,n+i)}function w(e){return e&&e._delegate?e._delegate:e}function je(e){try{return(e.startsWith("http://")||e.startsWith("https://")?new URL(e).hostname:e).endsWith(".cloudworkstations.dev")}catch{return!1}}async function ze(e){return(await fetch(e,{credentials:"include"})).ok}class c{constructor(e,t,r){this.name=e,this.instanceFactory=t,this.type=r,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 Ke="[DEFAULT]";class We{constructor(e,t){this.name=e,this.container=t,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){var t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){var r=new Z;if(this.instancesDeferred.set(t,r),this.isInitialized(t)||this.shouldAutoInitialize())try{var n=this.getOrInitializeService({instanceIdentifier:t});n&&r.resolve(n)}catch(e){}}return this.instancesDeferred.get(t).promise}getImmediate(e){var t=this.normalizeInstanceIdentifier(e?.identifier),r=e?.optional??!1;if(!this.isInitialized(t)&&!this.shouldAutoInitialize()){if(r)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:t})}catch(e){if(r)return null;throw e}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,this.shouldAutoInitialize()){if("EAGER"===e.instantiationMode)try{this.getOrInitializeService({instanceIdentifier:Ke})}catch(e){}for(var[t,r]of this.instancesDeferred.entries()){t=this.normalizeInstanceIdentifier(t);try{var n=this.getOrInitializeService({instanceIdentifier:t});r.resolve(n)}catch(e){}}}}clearInstance(e=Ke){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){var e=Array.from(this.instances.values());await Promise.all([...e.filter(e=>"INTERNAL"in e).map(e=>e.INTERNAL.delete()),...e.filter(e=>"_delete"in e).map(e=>e._delete())])}isComponentSet(){return null!=this.component}isInitialized(e=Ke){return this.instances.has(e)}getOptions(e=Ke){return this.instancesOptions.get(e)||{}}initialize(e={}){var{options:t={}}=e,r=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(r))throw Error(this.name+`(${r}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);var n,i,s=this.getOrInitializeService({instanceIdentifier:r,options:t});for([n,i]of this.instancesDeferred.entries())r===this.normalizeInstanceIdentifier(n)&&i.resolve(s);return s}onInit(e,t){var r=this.normalizeInstanceIdentifier(t);let n=this.onInitCallbacks.get(r)??new Set;n.add(e),this.onInitCallbacks.set(r,n);var i=this.instances.get(r);return i&&e(i,r),()=>{n.delete(e)}}invokeOnInitCallbacks(e,t){var r=this.onInitCallbacks.get(t);if(r)for(var n of r)try{n(e,t)}catch{}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let r=this.instances.get(e);if(!r&&this.component&&(r=this.component.instanceFactory(this.container,{instanceIdentifier:(n=e)===Ke?void 0:n,options:t}),this.instances.set(e,r),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(r,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,r)}catch{}var n;return r||null}normalizeInstanceIdentifier(e=Ke){return!this.component||this.component.multipleInstances?e:Ke}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class He{constructor(e){this.name=e,this.providers=new Map}addComponent(e){var t=this.getProvider(e.name);if(t.isComponentSet())throw new Error(`Component ${e.name} has already been registered with `+this.name);t.setComponent(e)}addOrOverwriteComponent(e){this.getProvider(e.name).isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){var t;return this.providers.has(e)?this.providers.get(e):(t=new We(e,this),this.providers.set(e,t),t)}getProviders(){return Array.from(this.providers.values())}}let Ge=[],$e=((t=p=p||{})[t.DEBUG=0]="DEBUG",t[t.VERBOSE=1]="VERBOSE",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.SILENT=5]="SILENT",{debug:p.DEBUG,verbose:p.VERBOSE,info:p.INFO,warn:p.WARN,error:p.ERROR,silent:p.SILENT}),Qe=p.INFO,Ye={[p.DEBUG]:"log",[p.VERBOSE]:"log",[p.INFO]:"info",[p.WARN]:"warn",[p.ERROR]:"error"},Je=(e,t,...r)=>{if(!(t<e.logLevel)){var n=(new Date).toISOString(),i=Ye[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${n}] ${e.name}:`,...r)}};class Xe{constructor(e){this.name=e,this._logLevel=Qe,this._logHandler=Je,this._userLogHandler=null,Ge.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in p))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?$e[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,p.DEBUG,...e),this._logHandler(this,p.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,p.VERBOSE,...e),this._logHandler(this,p.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,p.INFO,...e),this._logHandler(this,p.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,p.WARN,...e),this._logHandler(this,p.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,p.ERROR,...e),this._logHandler(this,p.ERROR,...e)}}let Ze=(t,e)=>e.some(e=>t instanceof e),et,tt;let rt=new WeakMap,nt=new WeakMap,it=new WeakMap,st=new WeakMap,at=new WeakMap;let ot={get(e,t,r){if(e instanceof IDBTransaction){if("done"===t)return nt.get(e);if("objectStoreNames"===t)return e.objectStoreNames||it.get(e);if("store"===t)return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return ct(e[t])},set(e,t,r){return e[t]=r,!0},has(e,t){return e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e}};function lt(n){return n!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(tt=tt||[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey]).includes(n)?function(...e){return n.apply(ut(this),e),ct(rt.get(this))}:function(...e){return ct(n.apply(ut(this),e))}:function(e,...t){var r=n.call(ut(this),e,...t);return it.set(r,e.sort?e.sort():[e]),ct(r)}}function ht(e){var s,t;return"function"==typeof e?lt(e):(e instanceof IDBTransaction&&(s=e,nt.has(s)||(t=new Promise((e,t)=>{let r=()=>{s.removeEventListener("complete",n),s.removeEventListener("error",i),s.removeEventListener("abort",i)},n=()=>{e(),r()},i=()=>{t(s.error||new DOMException("AbortError","AbortError")),r()};s.addEventListener("complete",n),s.addEventListener("error",i),s.addEventListener("abort",i)}),nt.set(s,t))),Ze(e,et=et||[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])?new Proxy(e,ot):e)}function ct(e){var s,t;return e instanceof IDBRequest?(s=e,(t=new Promise((e,t)=>{let r=()=>{s.removeEventListener("success",n),s.removeEventListener("error",i)},n=()=>{e(ct(s.result)),r()},i=()=>{t(s.error),r()};s.addEventListener("success",n),s.addEventListener("error",i)})).then(e=>{e instanceof IDBCursor&&rt.set(e,s)}).catch(()=>{}),at.set(t,s),t):st.has(e)?st.get(e):((t=ht(e))!==e&&(st.set(e,t),at.set(t,e)),t)}let ut=e=>at.get(e);function dt(e,t,{blocked:r,upgrade:n,blocking:i,terminated:s}={}){let a=indexedDB.open(e,t);var o=ct(a);return n&&a.addEventListener("upgradeneeded",e=>{n(ct(a.result),e.oldVersion,e.newVersion,ct(a.transaction),e)}),r&&a.addEventListener("blocked",e=>r(e.oldVersion,e.newVersion,e)),o.then(e=>{s&&e.addEventListener("close",()=>s()),i&&e.addEventListener("versionchange",e=>i(e.oldVersion,e.newVersion,e))}).catch(()=>{}),o}function pt(e,{blocked:t}={}){var r=indexedDB.deleteDatabase(e);return t&&r.addEventListener("blocked",e=>t(e.oldVersion,e)),ct(r).then(()=>{})}let ft=["get","getKey","getAll","getAllKeys","count"],gt=["put","add","delete","clear"],mt=new Map;function vt(e,t){if(e instanceof IDBDatabase&&!(t in e)&&"string"==typeof t){if(mt.get(t))return mt.get(t);let i=t.replace(/FromIndex$/,""),s=t!==i,a=gt.includes(i);var r;return i in(s?IDBIndex:IDBObjectStore).prototype&&(a||ft.includes(i))?(r=async function(e,...t){var r=this.transaction(e,a?"readwrite":"readonly");let n=r.store;return s&&(n=n.index(t.shift())),(await Promise.all([n[i](...t),a&&r.done]))[0]},mt.set(t,r),r):void 0}}ot={...X=ot,get:(e,t,r)=>vt(e,t)||X.get(e,t,r),has:(e,t)=>!!vt(e,t)||X.has(e,t)};class _t{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(e=>{var t;return"VERSION"===e.getComponent()?.type?(t=e.getImmediate()).library+"/"+t.version:null}).filter(e=>e).join(" ")}}let yt="@firebase/app",wt="0.14.11",bt=new Xe("@firebase/app");let It="[DEFAULT]",Tt={"@firebase/app":"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/ai":"fire-vertex","fire-js":"fire-js",firebase:"fire-js-all"},Et=new Map,Ct=new Map,St=new Map;function kt(t,r){try{t.container.addComponent(r)}catch(e){bt.debug(`Component ${r.name} failed to register with FirebaseApp `+t.name,e)}}function At(e,t){e.container.addOrOverwriteComponent(t)}function Nt(e){var t,r,n=e.name;if(St.has(n))return bt.debug(`There were multiple attempts to register component ${n}.`),!1;St.set(n,e);for(t of Et.values())kt(t,e);for(r of Ct.values())kt(r,e);return!0}function Rt(e,t){var r=e.container.getProvider("heartbeat").getImmediate({optional:!0});return r&&r.triggerHeartbeat(),e.container.getProvider(t)}function Pt(e){return void 0!==e.options}function Dt(e){return!Pt(e)&&("authIdToken"in e||"appCheckToken"in e||"releaseOnDeref"in e||"automaticDataCollectionEnabled"in e)}function h(e){return null!=e&&void 0!==e.settings}let xt=new ge("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 Ot{constructor(e,t,r){this._isDeleted=!1,this._options={...e},this._config={...t},this._name=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled,this._container=r,this.container.addComponent(new c("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 xt.create("app-deleted",{appName:this._name})}}function Mt(e,t){var r=K(e.split(".")[1]);null===r?console.error(`FirebaseServerApp ${t} is invalid: second part could not be parsed.`):void 0===JSON.parse(r).exp?console.error(`FirebaseServerApp ${t} is invalid: expiration claim could not be parsed`):1e3*JSON.parse(r).exp-(new Date).getTime()<=0&&console.error(`FirebaseServerApp ${t} is invalid: the token has expired.`)}class Lt extends Ot{constructor(e,t,r,n){var i=void 0===t.automaticDataCollectionEnabled||t.automaticDataCollectionEnabled,s={name:r,automaticDataCollectionEnabled:i};void 0!==e.apiKey?super(e,s,n):super(e.options,s,n),this._serverConfig={automaticDataCollectionEnabled:i,...t},this._serverConfig.authIdToken&&Mt(this._serverConfig.authIdToken,"authIdToken"),this._serverConfig.appCheckToken&&Mt(this._serverConfig.appCheckToken,"appCheckToken"),this._finalizationRegistry=null,"undefined"!=typeof FinalizationRegistry&&(this._finalizationRegistry=new FinalizationRegistry(()=>{this.automaticCleanup()})),this._refCount=0,this.incRefCount(this._serverConfig.releaseOnDeref),this._serverConfig.releaseOnDeref=void 0,t.releaseOnDeref=void 0,u(yt,wt,"serverapp")}toJSON(){}get refCount(){return this._refCount}incRefCount(e){this.isDeleted||(this._refCount++,void 0!==e&&null!==this._finalizationRegistry&&this._finalizationRegistry.register(e,this))}decRefCount(){return this.isDeleted?0:--this._refCount}automaticCleanup(){qt(this)}get settings(){return this.checkDestroyed(),this._serverConfig}checkDestroyed(){if(this.isDeleted)throw xt.create("server-app-deleted")}}let Ft="12.12.1";function Ut(e,t={}){let r=e;if("object"!=typeof t){let e=t;t={name:e}}var n={name:It,automaticDataCollectionEnabled:!0,...t};let i=n.name;if("string"!=typeof i||!i)throw xt.create("bad-app-name",{appName:String(i)});if(!(r=r||J()))throw xt.create("no-options");var s=Et.get(i);if(s){if(Ee(r,s.options)&&Ee(n,s.config))return s;throw xt.create("duplicate-app",{appName:i})}var a,o=new He(i);for(a of St.values())o.addComponent(a);s=new Ot(r,n,o);return Et.set(i,s),s}function Vt(e=It){var t=Et.get(e);if(!t&&e===It&&J())return Ut();if(t)return t;throw xt.create("no-app",{appName:e})}async function qt(e){let t=!1;var r=e.name;Et.has(r)?(t=!0,Et.delete(r)):Ct.has(r)&&e.decRefCount()<=0&&(Ct.delete(r),t=!0),t&&(await Promise.all(e.container.getProviders().map(e=>e.delete())),e.isDeleted=!0)}function u(e,t,r){let n=Tt[e]??e;r&&(n+="-"+r);var i,s=n.match(/\s|\//),a=t.match(/\s|\//);s||a?(i=[`Unable to register library "${n}" with version "${t}":`],s&&i.push(`library name "${n}" contains illegal characters (whitespace or "/")`),s&&a&&i.push("and"),a&&i.push(`version name "${t}" contains illegal characters (whitespace or "/")`),bt.warn(i.join(" "))):Nt(new c(n+"-version",()=>({library:n,version:t}),"VERSION"))}function Bt(e,t){if(null!==e&&"function"!=typeof e)throw xt.create("invalid-log-argument");var r,s=e,n=t;for(r of Ge){let i=null;n&&n.level&&(i=$e[n.level]),r.userLogHandler=null===s?null:(e,t,...r)=>{var n=r.map(e=>{if(null==e)return null;if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e)return e.toString();if(e instanceof Error)return e.message;try{return JSON.stringify(e)}catch(e){return null}}).filter(e=>e).join(" ");t>=(i??e.logLevel)&&s({level:p[t].toLowerCase(),message:n,args:r,type:e.name})}}}function jt(e){var t;t=e,Ge.forEach(e=>{e.setLogLevel(t)})}let zt="firebase-heartbeat-database",Kt=1,Wt="firebase-heartbeat-store",Ht=null;function Gt(){return Ht=Ht||dt(zt,Kt,{upgrade:(e,t)=>{if(0===t)try{e.createObjectStore(Wt)}catch(e){console.warn(e)}}}).catch(e=>{throw xt.create("idb-open",{originalErrorMessage:e.message})})}async function $t(e,t){try{var r=(await Gt()).transaction(Wt,"readwrite");await r.objectStore(Wt).put(t,Qt(e)),await r.done}catch(e){e instanceof fe?bt.warn(e.message):(r=xt.create("idb-set",{originalErrorMessage:e?.message}),bt.warn(r.message))}}function Qt(e){return e.name+"!"+e.options.appId}class Yt{constructor(e){this.container=e,this._heartbeatsCache=null;var t=this.container.getProvider("app").getImmediate();this._storage=new Xt(t),this._heartbeatsCachePromise=this._storage.read().then(e=>this._heartbeatsCache=e)}async triggerHeartbeat(){try{var e,r=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString();let t=Jt();if(null!=this._heartbeatsCache?.heartbeats||(this._heartbeatsCache=await this._heartbeatsCachePromise,null!=this._heartbeatsCache?.heartbeats))if(this._heartbeatsCache.lastSentHeartbeatDate!==t&&!this._heartbeatsCache.heartbeats.some(e=>e.date===t))return this._heartbeatsCache.heartbeats.push({date:t,agent:r}),30<this._heartbeatsCache.heartbeats.length&&(e=(e=>{if(0===e.length)return-1;let t=0,r=e[0].date;for(let n=1;n<e.length;n++)e[n].date<r&&(r=e[n].date,t=n);return t})(this._heartbeatsCache.heartbeats),this._heartbeatsCache.heartbeats.splice(e,1)),this._storage.overwrite(this._heartbeatsCache)}catch(e){bt.warn(e)}}async getHeartbeatsHeader(){try{var e,t,r,n;return(null===this._heartbeatsCache&&await this._heartbeatsCachePromise,null==this._heartbeatsCache?.heartbeats||0===this._heartbeatsCache.heartbeats.length)?"":(e=Jt(),{heartbeatsToSend:t,unsentEntries:r}=((e,t=1024)=>{let r=[],n=e.slice();for(let s of e){var i=r.find(e=>e.agent===s.agent);if(i){if(i.dates.push(s.date),Zt(r)>t){i.dates.pop();break}}else if(r.push({agent:s.agent,dates:[s.date]}),Zt(r)>t){r.pop();break}n=n.slice(1)}return{heartbeatsToSend:r,unsentEntries:n}})(this._heartbeatsCache.heartbeats),n=z(JSON.stringify({version:2,heartbeats:t})),this._heartbeatsCache.lastSentHeartbeatDate=e,0<r.length?(this._heartbeatsCache.heartbeats=r,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),n)}catch(e){return bt.warn(e),""}}}function Jt(){return(new Date).toISOString().substring(0,10)}class Xt{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!ue()&&de().then(()=>!0).catch(()=>!1)}async read(){var e;return await this._canUseIndexedDBPromise&&(e=await(async e=>{try{var t=(await Gt()).transaction(Wt),r=await t.objectStore(Wt).get(Qt(e));return await t.done,r}catch(e){e instanceof fe?bt.warn(e.message):(t=xt.create("idb-get",{originalErrorMessage:e?.message}),bt.warn(t.message))}})(this.app))?.heartbeats?e:{heartbeats:[]}}async overwrite(e){var t;if(await this._canUseIndexedDBPromise)return t=await this.read(),$t(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??t.lastSentHeartbeatDate,heartbeats:e.heartbeats})}async add(e){var t;if(await this._canUseIndexedDBPromise)return t=await this.read(),$t(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??t.lastSentHeartbeatDate,heartbeats:[...t.heartbeats,...e.heartbeats]})}}function Zt(e){return z(JSON.stringify({version:2,heartbeats:e})).length}t="",Nt(new c("platform-logger",e=>new _t(e),"PRIVATE")),Nt(new c("heartbeat",e=>new Yt(e),"PRIVATE")),u(yt,wt,t),u(yt,wt,"esm2020"),u("fire-js","");var er=Object.freeze({__proto__:null,SDK_VERSION:Ft,_DEFAULT_ENTRY_NAME:It,_addComponent:kt,_addOrOverwriteComponent:At,_apps:Et,_clearComponents:function(){St.clear()},_components:St,_getProvider:Rt,_isFirebaseApp:Pt,_isFirebaseServerApp:h,_isFirebaseServerAppSettings:Dt,_registerComponent:Nt,_removeServiceInstance:function(e,t,r=It){Rt(e,t).clearInstance(r)},_serverApps:Ct,deleteApp:qt,getApp:Vt,getApps:function(){return Array.from(Et.values())},initializeApp:Ut,initializeServerApp:function(e,t={}){if(("undefined"!=typeof window||ie())&&!ie())throw xt.create("invalid-server-app-environment");let r,n=t||{};if(e&&(Pt(e)?r=e.options:Dt(e)?n=e:r=e),void 0===n.automaticDataCollectionEnabled&&(n.automaticDataCollectionEnabled=!0),!(r=r||J()))throw xt.create("no-options");var i={...n,...r};if(void 0!==i.releaseOnDeref&&delete i.releaseOnDeref,void 0!==n.releaseOnDeref&&"undefined"==typeof FinalizationRegistry)throw xt.create("finalization-registry-not-supported",{});var i=""+[...JSON.stringify(i)].reduce((e,t)=>Math.imul(31,e)+t.charCodeAt(0)|0,0),s=Ct.get(i);if(s)s.incRefCount(n.releaseOnDeref);else{var a,o=new He(i);for(a of St.values())o.addComponent(a);s=new Lt(r,n,i,o),Ct.set(i,s)}return s},onLog:Bt,registerVersion:u,setLogLevel:jt,FirebaseError:fe});class tr{constructor(e,t){this._delegate=e,this.firebase=t,kt(e,new c("app-compat",()=>this,"PUBLIC")),this.container=e.container}get automaticDataCollectionEnabled(){return this._delegate.automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this._delegate.automaticDataCollectionEnabled=e}get name(){return this._delegate.name}get options(){return this._delegate.options}delete(){return new Promise(e=>{this._delegate.checkDestroyed(),e()}).then(()=>(this.firebase.INTERNAL.removeApp(this.name),qt(this._delegate)))}_getService(e,t=It){this._delegate.checkDestroyed();var r=this._delegate.container.getProvider(e);return r.isInitialized()||"EXPLICIT"!==r.getComponent()?.instantiationMode||r.initialize(),r.getImmediate({identifier:t})}_removeServiceInstance(e,t=It){this._delegate.container.getProvider(e).clearInstance(t)}_addComponent(e){kt(this._delegate,e)}_addOrOverwriteComponent(e){At(this._delegate,e)}toJSON(){return{name:this.name,automaticDataCollectionEnabled:this.automaticDataCollectionEnabled,options:this.options}}}let rr=new ge("app-compat","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance."});function nr(i){let s={},a={__esModule:!0,initializeApp:function(e,t={}){var r=Ut(e,t);if(we(s,r.name))return s[r.name];var n=new i(r,a);return s[r.name]=n},app:o,registerVersion:u,setLogLevel:jt,onLog:Bt,apps:null,SDK_VERSION:Ft,INTERNAL:{registerComponent:function(t){let r=t.name,n=r.replace("-compat","");{var e;Nt(t)&&"PUBLIC"===t.type&&(e=(e=o())=>{if("function"!=typeof e[n])throw rr.create("invalid-app-argument",{appName:r});return e[n]()},void 0!==t.serviceProps&&W(e,t.serviceProps),a[n]=e,i.prototype[n]=function(...e){return this._getService.bind(this,r).apply(this,t.multipleInstances?e:[])})}return"PUBLIC"===t.type?a[n]:null},removeApp:function(e){delete s[e]},useAsService:function(e,t){if("serverAuth"===t)return null;var r=t;return r},modularAPIs:er}};function o(e){if(e=e||It,we(s,e))return s[e];throw rr.create("no-app",{appName:e})}return a.default=a,Object.defineProperty(a,"apps",{get:function(){return Object.keys(s).map(e=>s[e])}}),o.App=i,a}var ir=function e(){let t=nr(tr);return t.INTERNAL={...t.INTERNAL,createFirebaseNamespace:e,extendNamespace:function(e){W(t,e)},createSubscribe:Re,ErrorFactory:ge,deepExtend:W},t}(),sr=new Xe("@firebase/app-compat");try{var ar=H();void 0!==ar.firebase&&(sr.warn(`
|
|
2
2
|
Warning: Firebase is already defined in the global scope. Please make sure
|
|
3
3
|
Firebase library is only loaded once.
|
|
4
4
|
`),lr=ar.firebase.SDK_VERSION)&&0<=lr.indexOf("LITE")&&sr.warn(`
|
|
5
5
|
Warning: You are trying to load Firebase while using Firebase Performance standalone script.
|
|
6
6
|
You should load Firebase Performance with this instance of Firebase to avoid loading duplicate code.
|
|
7
|
-
`)}catch{}let or=ir;u("@firebase/app-compat","0.5.11",void 0);or.registerVersion("firebase","12.12.0","app-compat");var ar="@firebase/installations",lr="0.6.21";let hr=1e4,cr="w:"+lr,ur="FIS_v2",dr="https://firebaseinstallations.googleapis.com/v1",pr=36e5;let fr=new ge("installations","Installations",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"not-registered":"Firebase Installation is not registered.","installation-not-found":"Firebase Installation not found.","request-failed":'{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',"app-offline":"Could not process request. Application offline.","delete-pending-registration":"Can't delete installation while there is a pending registration request."});function gr(e){return e instanceof fe&&e.code.includes("request-failed")}function mr({projectId:e}){return dr+`/projects/${e}/installations`}function vr(e){return{token:e.token,requestStatus:2,expiresIn:Number(e.expiresIn.replace("s","000")),creationTime:Date.now()}}async function _r(e,t){var r=(await t.json()).error;return fr.create("request-failed",{requestName:e,serverCode:r.code,serverMessage:r.message,serverStatus:r.status})}function yr({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function wr(e,{refreshToken:t}){var r=yr(e);return r.append("Authorization",(e=t,ur+" "+e)),r}async function br(e){var t=await e();return 500<=t.status&&t.status<600?e():t}function Ir(t){return new Promise(e=>{setTimeout(e,t)})}let Tr=/^[cdef][\w-]{21}$/,Er="";function Cr(){try{var e=new Uint8Array(17),t=((self.crypto||self.msCrypto).getRandomValues(e),e[0]=112+e[0]%16,(e=>btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_"))(e).substr(0,22));return Tr.test(t)?t:Er}catch{return Er}}function Sr(e){return e.appName+"!"+e.appId}let kr=new Map;function Ar(e,t){var r=Sr(e),e=(Nr(r,t),r),r=(()=>(!Rr&&"BroadcastChannel"in self&&((Rr=new BroadcastChannel("[Firebase] FID Change")).onmessage=e=>{Nr(e.data.key,e.data.fid)}),Rr))();r&&r.postMessage({key:e,fid:t}),0===kr.size&&Rr&&(Rr.close(),Rr=null)}function Nr(e,t){var r=kr.get(e);if(r)for(var n of r)n(t)}let Rr=null;let Pr="firebase-installations-database",Dr=1,xr="firebase-installations-store",Or=null;function Mr(){return Or=Or||dt(Pr,Dr,{upgrade:(e,t)=>{0===t&&e.createObjectStore(xr)}})}async function Lr(e,t){var r=Sr(e),n=(await Mr()).transaction(xr,"readwrite"),i=n.objectStore(xr),s=await i.get(r);return await i.put(t,r),await n.done,s&&s.fid===t.fid||Ar(e,t.fid),t}async function Fr(e){var t=Sr(e),r=(await Mr()).transaction(xr,"readwrite");await r.objectStore(xr).delete(t),await r.done}async function Ur(e,t){var r=Sr(e),n=(await Mr()).transaction(xr,"readwrite"),i=n.objectStore(xr),s=await i.get(r),a=t(s);return void 0===a?await i.delete(r):await i.put(a,r),await n.done,!a||s&&s.fid===a.fid||Ar(e,a.fid),a}async function Vr(r){let n;var e=await Ur(r.appConfig,e=>{var t=Br(e||{fid:Cr(),registrationStatus:0}),t=((e,t)=>{var r,n;return 0===t.registrationStatus?navigator.onLine?(r={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},n=(async(t,r)=>{try{var e=await(async({appConfig:e,heartbeatServiceProvider:t},{fid:r})=>{let n=mr(e);var i=yr(e),s=((s=t.getImmediate({optional:!0}))&&(s=await s.getHeartbeatsHeader())&&i.append("x-firebase-client",s),{fid:r,authVersion:ur,appId:e.appId,sdkVersion:cr});let a={method:"POST",headers:i,body:JSON.stringify(s)};if((i=await br(()=>fetch(n,a))).ok)return{fid:(s=await i.json()).fid||r,registrationStatus:2,refreshToken:s.refreshToken,authToken:vr(s.authToken)};throw await _r("Create Installation",i)})(t,r);return Lr(t.appConfig,e)}catch(e){throw gr(e)&&409===e.customData.serverCode?await Fr(t.appConfig):await Lr(t.appConfig,{fid:r.fid,registrationStatus:0}),e}})(e,r),{installationEntry:r,registrationPromise:n}):(r=Promise.reject(fr.create("app-offline")),{installationEntry:t,registrationPromise:r}):1===t.registrationStatus?{installationEntry:t,registrationPromise:(async e=>{let t=await qr(e.appConfig);for(;1===t.registrationStatus;)await Ir(100),t=await qr(e.appConfig);var r,n;return 0!==t.registrationStatus?t:({installationEntry:r,registrationPromise:n}=await Vr(e),n||r)})(e)}:{installationEntry:t}})(r,t);return n=t.registrationPromise,t.installationEntry});return e.fid===Er?{installationEntry:await n}:{installationEntry:e,registrationPromise:n}}function qr(e){return Ur(e,e=>{if(e)return Br(e);throw fr.create("installation-not-found")})}function Br(e){var t;return 1===(t=e).registrationStatus&&t.registrationTime+hr<Date.now()?{fid:e.fid,registrationStatus:0}:e}async function jr({appConfig:e,heartbeatServiceProvider:t},r){[i,s]=[e,r.fid];let n=mr(i)+`/${s}/authTokens:generate`;var i,s,a=wr(e,r),o=t.getImmediate({optional:!0}),o=(o&&(o=await o.getHeartbeatsHeader())&&a.append("x-firebase-client",o),{installation:{sdkVersion:cr,appId:e.appId}});let l={method:"POST",headers:a,body:JSON.stringify(o)};a=await br(()=>fetch(n,l));if(a.ok)return vr(await a.json());throw await _r("Generate Auth Token",a)}async function zr(n,i=!1){let s;var e=await Ur(n.appConfig,e=>{if(!Wr(e))throw fr.create("not-registered");var t,r=e.authToken;if(i||2!==(t=r).requestStatus||(e=>{var t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+pr})(t)){if(1===r.requestStatus)return s=(async(e,t)=>{let r=await Kr(e.appConfig);for(;1===r.authToken.requestStatus;)await Ir(100),r=await Kr(e.appConfig);var n=r.authToken;return 0===n.requestStatus?zr(e,t):n})(n,i),e;if(navigator.onLine)return t=e,r={requestStatus:1,requestTime:Date.now()},r={...t,authToken:r},s=(async(t,r)=>{try{var e=await jr(t,r),n={...r,authToken:e};return await Lr(t.appConfig,n),e}catch(e){var i;throw!gr(e)||401!==e.customData.serverCode&&404!==e.customData.serverCode?(i={...r,authToken:{requestStatus:0}},await Lr(t.appConfig,i)):await Fr(t.appConfig),e}})(n,r),r;throw fr.create("app-offline")}return e});return s?await s:e.authToken}function Kr(e){return Ur(e,e=>{var t,r;if(Wr(e))return t=e.authToken,1===(r=t).requestStatus&&r.requestTime+hr<Date.now()?{...e,authToken:{requestStatus:0}}:e;throw fr.create("not-registered")})}function Wr(e){return void 0!==e&&2===e.registrationStatus}async function Hr(e,t=!1){var r=e,n=(await(!(n=(await Vr(r)).registrationPromise)||!await n),await zr(r,t));return n.token}function Gr(e){return fr.create("missing-app-config-values",{valueName:e})}let $r="installations",Qr=e=>{var t=e.getProvider("app").getImmediate();return{app:t,appConfig:(e=>{if(!e||!e.options)throw Gr("App Configuration");if(!e.name)throw Gr("App Name");var t;for(t of["projectId","apiKey","appId"])if(!e.options[t])throw Gr(t);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}})(t),heartbeatServiceProvider:Rt(t,"heartbeat"),_delete:()=>Promise.resolve()}},Yr=e=>{let t=Rt(e.getProvider("app").getImmediate(),$r).getImmediate();return{getId:()=>(async e=>{var t=e,{installationEntry:r,registrationPromise:n}=await Vr(t);return(n||zr(t)).catch(console.error),r.fid})(t),getToken:e=>Hr(t,e)}};Nt(new c($r,Qr,"PUBLIC")),Nt(new c("installations-internal",Yr,"PRIVATE")),u(ar,lr),u(ar,lr,"esm2020");let Jr="analytics",Xr="firebase_id",Zr="origin",en=6e4,tn="https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig",rn="https://www.googletagmanager.com/gtag/js",nn=new Xe("@firebase/analytics"),sn=new ge("analytics","Analytics",{"already-exists":"A Firebase Analytics instance with the appId {$id} already exists. Only one Firebase Analytics instance can be created for each appId.","already-initialized":"initializeAnalytics() cannot be called again with different options than those it was initially called with. It can be called again with the same options to return the existing instance, or getAnalytics() can be used to get a reference to the already-initialized instance.","already-initialized-settings":"Firebase Analytics has already been initialized.settings() must be called before initializing any Analytics instanceor it will have no effect.","interop-component-reg-failed":"Firebase Analytics Interop Component failed to instantiate: {$reason}","invalid-analytics-context":"Firebase Analytics is not supported in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","indexeddb-unavailable":"IndexedDB unavailable or restricted in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","fetch-throttle":"The config fetch request timed out while in an exponential backoff state. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.","config-fetch-failed":"Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}","no-api-key":'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid API key.',"no-app-id":'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid app ID.',"no-client-id":'The "client_id" field is empty.',"invalid-gtag-resource":"Trusted Types detected an invalid gtag resource: {$gtagURL}."});function an(e){var t;return e.startsWith(rn)?e:(t=sn.create("invalid-gtag-resource",{gtagURL:e}),nn.warn(t.message),"")}function on(e){return Promise.all(e.map(e=>e.catch(e=>e)))}function ln(e,t){var r=((e,t)=>{let r;return r=window.trustedTypes?window.trustedTypes.createPolicy(e,t):r})("firebase-js-sdk-policy",{createScriptURL:an}),n=document.createElement("script"),i=rn+`?l=${e}&id=`+t;n.src=r?r?.createScriptURL(i):i,n.async=!0,document.head.appendChild(n)}function hn(k,A,N,R){return async function(e,...t){try{if("event"===e){var[r,n]=t,i=k,s=A,a=N,o=r,l=n;try{let r=[];if(l&&l.send_to){let e=l.send_to;Array.isArray(e)||(e=[e]);var h=await on(a);for(let t of e){var c=h.find(e=>e.measurementId===t),u=c&&s[c.appId];if(!u){r=[];break}r.push(u)}}0===r.length&&(r=Object.values(s)),await Promise.all(r),i("event",o,l||{})}catch(e){nn.error(e)}}else if("config"===e){var d,[p,f]=t,g=k,m=A,v=N,_=p,y=f,w=R[_];try{w?await m[w]:(d=(await on(v)).find(e=>e.measurementId===_))&&await m[d.appId]}catch(e){nn.error(e)}g("config",_,y)}else{var b,I,T,E,C,S;"consent"===e?([b,I]=t,k("consent",b,I)):"get"===e?([T,E,C]=t,k("get",T,E,C)):"set"===e?([S]=t,k("set",S)):k(e,...t)}}catch(e){nn.error(e)}}}let cn=30;let un=new class{constructor(e={},t=1e3){this.throttleMetadata=e,this.intervalMillis=t}getThrottleMetadata(e){return this.throttleMetadata[e]}setThrottleMetadata(e,t){this.throttleMetadata[e]=t}deleteThrottleMetadata(e){delete this.throttleMetadata[e]}};async function dn(e){var{appId:t,apiKey:r}=e,r={method:"GET",headers:new Headers({Accept:"application/json","x-goog-api-key":r})},t=tn.replace("{app-id}",t),t=await fetch(t,r);if(200===t.status||304===t.status)return t.json();{let e="";try{var n=await t.json();n.error?.message&&(e=n.error.message)}catch(e){}throw sn.create("config-fetch-failed",{httpStatus:t.status,responseMessage:e})}}async function pn(e,t=un,r){var{appId:n,apiKey:i,measurementId:s}=e.options;if(!n)throw sn.create("no-app-id");if(!i){if(s)return{measurementId:s,appId:n};throw sn.create("no-api-key")}var a=t.getThrottleMetadata(n)||{backoffCount:0,throttleEndTimeMillis:Date.now()};let o=new mn;return setTimeout(async()=>{o.abort()},void 0!==r?r:en),async function i(s,{throttleEndTimeMillis:e,backoffCount:a},o,l=un){let{appId:h,measurementId:c}=s;try{await fn(o,e)}catch(e){if(c)return nn.warn("Timed out fetching this Firebase app's measurement ID from the server. Falling back to the measurement ID "+c+` provided in the "measurementId" field in the local Firebase config. [${e?.message}]`),{appId:h,measurementId:c};throw e}try{let e=await dn(s);return l.deleteThrottleMetadata(h),e}catch(e){let t=e;if(!gn(t)){if(l.deleteThrottleMetadata(h),c)return nn.warn("Failed to fetch this Firebase app's measurement ID from the server. Falling back to the measurement ID "+c+` provided in the "measurementId" field in the local Firebase config. [${t?.message}]`),{appId:h,measurementId:c};throw e}let r=503===Number(t?.customData?.httpStatus)?Be(a,l.intervalMillis,cn):Be(a,l.intervalMillis),n={throttleEndTimeMillis:Date.now()+r,backoffCount:a+1};return l.setThrottleMetadata(h,n),nn.debug(`Calling attemptFetch again in ${r} millis`),i(s,n,o,l)}}({appId:n,apiKey:i,measurementId:s},a,o,t)}function fn(i,s){return new Promise((e,t)=>{var r=Math.max(s-Date.now(),0);let n=setTimeout(e,r);i.addEventListener(()=>{clearTimeout(n),t(sn.create("fetch-throttle",{throttleEndTimeMillis:s}))})})}function gn(e){var t;return!!(e instanceof fe&&e.customData)&&(429===(t=Number(e.customData.httpStatus))||500===t||503===t||504===t)}class mn{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach(e=>e())}}async function vn(t,e,r,n,i,s,a){var o=pn(t),l=(o.then(e=>{r[e.measurementId]=e.appId,t.options.measurementId&&e.measurementId!==t.options.measurementId&&nn.warn(`The measurement ID in the local Firebase config (${t.options.measurementId})`+` does not match the measurement ID fetched from the server (${e.measurementId}).`+" To ensure analytics events are always sent to the correct Analytics property, update the measurement ID field in the local config or remove it from the local config.")}).catch(e=>nn.error(e)),e.push(o),(async()=>{if(!ue())return nn.warn(sn.create("indexeddb-unavailable",{errorInfo:"IndexedDB is not available in this environment."}).message),!1;try{await de()}catch(e){return nn.warn(sn.create("indexeddb-unavailable",{errorInfo:e?.toString()}).message),!1}return!0})().then(e=>{if(e)return n.getId()})),[o,l]=await Promise.all([o,l]),h=((e=>{var t,r=window.document.getElementsByTagName("script");for(t of Object.values(r))if(t.src&&t.src.includes(rn)&&t.src.includes(e))return t})(s)||ln(s,o.measurementId),i("js",new Date),a?.config??{});return h[Zr]="firebase",h.update=!0,null!=l&&(h[Xr]=l),i("config",o.measurementId,h),o.measurementId}class _n{constructor(e){this.app=e}_delete(){return delete yn[this.app.options.appId],Promise.resolve()}}let yn={},wn=[],bn={},In="dataLayer",Tn="gtag",En,Cn,Sn=!1;function kn(e){if(Sn)throw sn.create("already-initialized");e.dataLayerName&&(In=e.dataLayerName),e.gtagName&&(Tn=e.gtagName)}function An(e,t,r){n=[],se()&&n.push("This is a browser extension environment."),pe()||n.push("Cookies are not available."),0<n.length&&(n=n.map((e,t)=>`(${t+1}) `+e).join(" "),n=sn.create("invalid-analytics-context",{errorInfo:n}),nn.warn(n.message));var n=e.options.appId;if(!n)throw sn.create("no-app-id");if(!e.options.apiKey){if(!e.options.measurementId)throw sn.create("no-api-key");nn.warn('The "apiKey" field is empty in the local Firebase config. This is needed to fetch the latest measurement ID for this Firebase app. Falling back to the measurement ID '+e.options.measurementId+' provided in the "measurementId" field in the local Firebase config.')}if(null!=yn[n])throw sn.create("already-exists",{id:n});if(!Sn){{var i=In;let e=[];Array.isArray(window[i])?e=window[i]:window[i]=e,e}var{wrappedGtag:s,gtagCore:a}=((e,t,r,n,i)=>{let s=function(){window[n].push(arguments)};return window[i]&&"function"==typeof window[i]&&(s=window[i]),window[i]=hn(s,e,t,r),{gtagCore:s,wrappedGtag:window[i]}})(yn,wn,bn,In,Tn);Cn=s,En=a,Sn=!0}return yn[n]=vn(e,wn,bn,t,En,In,r),new _n(e)}async function Nn(){if(se())return!1;if(!pe())return!1;if(!ue())return!1;try{return await de()}catch(e){return!1}}function Rn(e,t,r){e=w(e),(async(e,t,r,n)=>{if(n&&n.global)return e("set",{screen_name:r}),Promise.resolve();e("config",await t,{update:!0,screen_name:r})})(Cn,yn[e.app.options.appId],t,r).catch(e=>nn.error(e))}function Pn(e,t,r){e=w(e),(async(e,t,r,n)=>{if(n&&n.global)return e("set",{user_id:r}),Promise.resolve();e("config",await t,{update:!0,user_id:r})})(Cn,yn[e.app.options.appId],t,r).catch(e=>nn.error(e))}function Dn(e,t,r){e=w(e),(async(e,t,r,n)=>{if(n&&n.global){var i,s={};for(i of Object.keys(r))s["user_properties."+i]=r[i];return e("set",s),Promise.resolve()}e("config",await t,{update:!0,user_properties:r})})(Cn,yn[e.app.options.appId],t,r).catch(e=>nn.error(e))}function xn(e,t){e=w(e),(async(e,t)=>{var r=await e;window["ga-disable-"+r]=!t})(yn[e.app.options.appId],t).catch(e=>nn.error(e))}function On(e,t,r,n){e=w(e),(async(e,t,r,n,i)=>{var s;i&&i.global?e("event",r,n):(s=await t,e("event",r,{...n,send_to:s}))})(Cn,yn[e.app.options.appId],t,r,n).catch(e=>nn.error(e))}let Mn="@firebase/analytics",Ln="0.10.21";Nt(new c(Jr,(e,{options:t})=>An(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),t),"PUBLIC")),Nt(new c("analytics-internal",function(e){try{let n=e.getProvider(Jr).getImmediate();return{logEvent:(e,t,r)=>On(n,e,t,r),setUserProperties:(e,t)=>Dn(n,e,t)}}catch(e){throw sn.create("interop-component-reg-failed",{reason:e})}},"PRIVATE")),u(Mn,Ln),u(Mn,Ln,"esm2020");class Fn{constructor(e,t){this.app=e,this._delegate=t}logEvent(e,t,r){On(this._delegate,e,t,r)}setCurrentScreen(e,t){Rn(this._delegate,e,t)}setUserId(e,t){Pn(this._delegate,e,t)}setUserProperties(e,t){Dn(this._delegate,e,t)}setAnalyticsCollectionEnabled(e){xn(this._delegate,e)}}(t=e=e||{}).ADD_SHIPPING_INFO="add_shipping_info",t.ADD_PAYMENT_INFO="add_payment_info",t.ADD_TO_CART="add_to_cart",t.ADD_TO_WISHLIST="add_to_wishlist",t.BEGIN_CHECKOUT="begin_checkout",t.CHECKOUT_PROGRESS="checkout_progress",t.EXCEPTION="exception",t.GENERATE_LEAD="generate_lead",t.LOGIN="login",t.PAGE_VIEW="page_view",t.PURCHASE="purchase",t.REFUND="refund",t.REMOVE_FROM_CART="remove_from_cart",t.SCREEN_VIEW="screen_view",t.SEARCH="search",t.SELECT_CONTENT="select_content",t.SELECT_ITEM="select_item",t.SELECT_PROMOTION="select_promotion",t.SET_CHECKOUT_OPTION="set_checkout_option",t.SHARE="share",t.SIGN_UP="sign_up",t.TIMING_COMPLETE="timing_complete",t.VIEW_CART="view_cart",t.VIEW_ITEM="view_item",t.VIEW_ITEM_LIST="view_item_list",t.VIEW_PROMOTION="view_promotion",t.VIEW_SEARCH_RESULTS="view_search_results";let Un=e=>{var t=e.getProvider("app-compat").getImmediate(),r=e.getProvider("analytics").getImmediate();return new Fn(t,r)};sr={Analytics:Fn,settings:kn,isSupported:Nn,EventName:e},or.INTERNAL.registerComponent(new c("analytics-compat",Un,"PUBLIC").setServiceProps(sr).setMultipleInstances(!0)),or.registerVersion("@firebase/analytics-compat","0.2.27");let Vn=new Map,qn={activated:!1,tokenObservers:[]},Bn={initialized:!1,enabled:!1};function jn(e){return Vn.get(e)||{...qn}}let zn="https://content-firebaseappcheck.googleapis.com/v1",Kn="exchangeDebugToken",Wn={OFFSET_DURATION:3e5,RETRIAL_MIN_WAIT:3e4,RETRIAL_MAX_WAIT:96e4};class Hn{constructor(e,t,r,n,i){if(this.operation=e,this.retryPolicy=t,this.getWaitDuration=r,this.lowerBound=n,this.upperBound=i,this.pending=null,i<(this.nextErrorWaitInterval=n))throw new Error("Proactive refresh lower bound greater than upper bound!")}start(){this.nextErrorWaitInterval=this.lowerBound,this.process(!0).catch(()=>{})}stop(){this.pending&&(this.pending.reject("cancelled"),this.pending=null)}isRunning(){return!!this.pending}async process(e){this.stop();try{this.pending=new Z,this.pending.promise.catch(e=>{}),t=this.getNextRun(e),await new Promise(e=>{setTimeout(e,t)}),this.pending.resolve(),await this.pending.promise,this.pending=new Z,this.pending.promise.catch(e=>{}),await this.operation(),this.pending.resolve(),await this.pending.promise,this.process(!0).catch(()=>{})}catch(e){this.retryPolicy(e)?this.process(!1).catch(()=>{}):this.stop()}var t}getNextRun(e){var t;return e?(this.nextErrorWaitInterval=this.lowerBound,this.getWaitDuration()):(t=this.nextErrorWaitInterval,this.nextErrorWaitInterval*=2,this.nextErrorWaitInterval>this.upperBound&&(this.nextErrorWaitInterval=this.upperBound),t)}}let Gn=new ge("appCheck","AppCheck",{"already-initialized":"You have already called initializeAppCheck() for FirebaseApp {$appName} with different options. To avoid this error, call initializeAppCheck() with the same options as when it was originally called. This will return the already initialized instance.","use-before-activation":"App Check is being used before initializeAppCheck() is called for FirebaseApp {$appName}. Call initializeAppCheck() before instantiating other Firebase services.","fetch-network-error":"Fetch failed to connect to a network. Check Internet connection. Original error: {$originalErrorMessage}.","fetch-parse-error":"Fetch client could not parse response. Original error: {$originalErrorMessage}.","fetch-status-error":"Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.","storage-open":"Error thrown when opening storage. Original error: {$originalErrorMessage}.","storage-get":"Error thrown when reading from storage. Original error: {$originalErrorMessage}.","storage-set":"Error thrown when writing to storage. Original error: {$originalErrorMessage}.","recaptcha-error":"ReCAPTCHA error.","initial-throttle":"{$httpStatus} error. Attempts allowed again after {$time}",throttled:"Requests throttled due to previous {$httpStatus} error. Attempts allowed again after {$time}"});function $n(e=!1){return e?self.grecaptcha?.enterprise:self.grecaptcha}function Qn(e){if(!jn(e).activated)throw Gn.create("use-before-activation",{appName:e.name})}function Yn(e){var t=Math.round(e/1e3),r=Math.floor(t/86400),n=Math.floor((t-3600*r*24)/3600),i=Math.floor((t-3600*r*24-3600*n)/60),t=t-3600*r*24-3600*n-60*i;let s="";return r&&(s+=Jn(r)+"d:"),n&&(s+=Jn(n)+"h:"),s+=Jn(i)+"m:"+Jn(t)+"s"}function Jn(e){return 0===e?"00":10<=e?e.toString():"0"+e}async function Xn({url:e,body:t},r){var n={"Content-Type":"application/json"},i=r.getImmediate({optional:!0}),i=(i&&(i=await i.getHeartbeatsHeader())&&(n["X-Firebase-Client"]=i),{method:"POST",body:JSON.stringify(t),headers:n});let s;try{s=await fetch(e,i)}catch(e){throw Gn.create("fetch-network-error",{originalErrorMessage:e?.message})}if(200!==s.status)throw Gn.create("fetch-status-error",{httpStatus:s.status});let a;try{a=await s.json()}catch(e){throw Gn.create("fetch-parse-error",{originalErrorMessage:e?.message})}var n=a.ttl.match(/^([\d.]+)(s)$/);if(n&&n[2]&&!isNaN(Number(n[1])))return i=1e3*Number(n[1]),n=Date.now(),{token:a.token,expireTimeMillis:n+i,issuedAtTimeMillis:n};throw Gn.create("fetch-parse-error",{originalErrorMessage:"ttl field (timeToLive) is not in standard Protobuf Duration format: "+a.ttl})}function Zn(e,t){var{projectId:r,appId:n,apiKey:i}=e.options;return{url:`${zn}/projects/${r}/apps/${n}:${Kn}?key=`+i,body:{debug_token:t}}}let ei="firebase-app-check-database",ti=1,ri="firebase-app-check-store",ni="debug-token",ii=null;function si(){return ii=ii||new Promise((t,r)=>{try{var e=indexedDB.open(ei,ti);e.onsuccess=e=>{t(e.target.result)},e.onerror=e=>{r(Gn.create("storage-open",{originalErrorMessage:e.target.error?.message}))},e.onupgradeneeded=e=>{var t=e.target.result;0===e.oldVersion&&t.createObjectStore(ri,{keyPath:"compositeKey"})}}catch(e){r(Gn.create("storage-open",{originalErrorMessage:e?.message}))}})}async function ai(e,t){let n=(await si()).transaction(ri,"readwrite"),i=n.objectStore(ri).put({compositeKey:e,value:t});return new Promise((t,r)=>{i.onsuccess=e=>{t()},n.onerror=e=>{r(Gn.create("storage-set",{originalErrorMessage:e.target.error?.message}))}})}async function oi(e){let n=(await si()).transaction(ri,"readonly"),i=n.objectStore(ri).get(e);return new Promise((r,t)=>{i.onsuccess=e=>{var t=e.target.result;r(t?t.value:void 0)},n.onerror=e=>{t(Gn.create("storage-get",{originalErrorMessage:e.target.error?.message}))}})}function li(e){return e.options.appId+"-"+e.name}let hi=new Xe("@firebase/app-check");async function ci(t){if(ue()){let e=void 0;try{e=await oi(li(t))}catch(e){hi.warn("Failed to read token from IndexedDB. Error: "+e)}return e}}function ui(e,t){return ue()?ai(li(e),t).catch(e=>{hi.warn("Failed to write token to IndexedDB. Error: "+e)}):Promise.resolve()}async function di(){let e=void 0;try{e=await oi(ni)}catch(e){}var t,r;return e||(t=crypto.randomUUID(),r=t,ai(ni,r).catch(e=>hi.warn("Failed to persist debug token to IndexedDB. Error: "+e)),t)}function pi(){return Bn.enabled}async function fi(){var e=Bn;if(e.enabled&&e.token)return e.token.promise;throw Error(`
|
|
7
|
+
`)}catch{}let or=ir;u("@firebase/app-compat","0.5.11",void 0);or.registerVersion("firebase","12.12.1","app-compat");var ar="@firebase/installations",lr="0.6.21";let hr=1e4,cr="w:"+lr,ur="FIS_v2",dr="https://firebaseinstallations.googleapis.com/v1",pr=36e5;let fr=new ge("installations","Installations",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"not-registered":"Firebase Installation is not registered.","installation-not-found":"Firebase Installation not found.","request-failed":'{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',"app-offline":"Could not process request. Application offline.","delete-pending-registration":"Can't delete installation while there is a pending registration request."});function gr(e){return e instanceof fe&&e.code.includes("request-failed")}function mr({projectId:e}){return dr+`/projects/${e}/installations`}function vr(e){return{token:e.token,requestStatus:2,expiresIn:Number(e.expiresIn.replace("s","000")),creationTime:Date.now()}}async function _r(e,t){var r=(await t.json()).error;return fr.create("request-failed",{requestName:e,serverCode:r.code,serverMessage:r.message,serverStatus:r.status})}function yr({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function wr(e,{refreshToken:t}){var r=yr(e);return r.append("Authorization",(e=t,ur+" "+e)),r}async function br(e){var t=await e();return 500<=t.status&&t.status<600?e():t}function Ir(t){return new Promise(e=>{setTimeout(e,t)})}let Tr=/^[cdef][\w-]{21}$/,Er="";function Cr(){try{var e=new Uint8Array(17),t=((self.crypto||self.msCrypto).getRandomValues(e),e[0]=112+e[0]%16,(e=>btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_"))(e).substr(0,22));return Tr.test(t)?t:Er}catch{return Er}}function Sr(e){return e.appName+"!"+e.appId}let kr=new Map;function Ar(e,t){var r=Sr(e),e=(Nr(r,t),r),r=(()=>(!Rr&&"BroadcastChannel"in self&&((Rr=new BroadcastChannel("[Firebase] FID Change")).onmessage=e=>{Nr(e.data.key,e.data.fid)}),Rr))();r&&r.postMessage({key:e,fid:t}),0===kr.size&&Rr&&(Rr.close(),Rr=null)}function Nr(e,t){var r=kr.get(e);if(r)for(var n of r)n(t)}let Rr=null;let Pr="firebase-installations-database",Dr=1,xr="firebase-installations-store",Or=null;function Mr(){return Or=Or||dt(Pr,Dr,{upgrade:(e,t)=>{0===t&&e.createObjectStore(xr)}})}async function Lr(e,t){var r=Sr(e),n=(await Mr()).transaction(xr,"readwrite"),i=n.objectStore(xr),s=await i.get(r);return await i.put(t,r),await n.done,s&&s.fid===t.fid||Ar(e,t.fid),t}async function Fr(e){var t=Sr(e),r=(await Mr()).transaction(xr,"readwrite");await r.objectStore(xr).delete(t),await r.done}async function Ur(e,t){var r=Sr(e),n=(await Mr()).transaction(xr,"readwrite"),i=n.objectStore(xr),s=await i.get(r),a=t(s);return void 0===a?await i.delete(r):await i.put(a,r),await n.done,!a||s&&s.fid===a.fid||Ar(e,a.fid),a}async function Vr(r){let n;var e=await Ur(r.appConfig,e=>{var t=Br(e||{fid:Cr(),registrationStatus:0}),t=((e,t)=>{var r,n;return 0===t.registrationStatus?navigator.onLine?(r={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},n=(async(t,r)=>{try{var e=await(async({appConfig:e,heartbeatServiceProvider:t},{fid:r})=>{let n=mr(e);var i=yr(e),s=((s=t.getImmediate({optional:!0}))&&(s=await s.getHeartbeatsHeader())&&i.append("x-firebase-client",s),{fid:r,authVersion:ur,appId:e.appId,sdkVersion:cr});let a={method:"POST",headers:i,body:JSON.stringify(s)};if((i=await br(()=>fetch(n,a))).ok)return{fid:(s=await i.json()).fid||r,registrationStatus:2,refreshToken:s.refreshToken,authToken:vr(s.authToken)};throw await _r("Create Installation",i)})(t,r);return Lr(t.appConfig,e)}catch(e){throw gr(e)&&409===e.customData.serverCode?await Fr(t.appConfig):await Lr(t.appConfig,{fid:r.fid,registrationStatus:0}),e}})(e,r),{installationEntry:r,registrationPromise:n}):(r=Promise.reject(fr.create("app-offline")),{installationEntry:t,registrationPromise:r}):1===t.registrationStatus?{installationEntry:t,registrationPromise:(async e=>{let t=await qr(e.appConfig);for(;1===t.registrationStatus;)await Ir(100),t=await qr(e.appConfig);var r,n;return 0!==t.registrationStatus?t:({installationEntry:r,registrationPromise:n}=await Vr(e),n||r)})(e)}:{installationEntry:t}})(r,t);return n=t.registrationPromise,t.installationEntry});return e.fid===Er?{installationEntry:await n}:{installationEntry:e,registrationPromise:n}}function qr(e){return Ur(e,e=>{if(e)return Br(e);throw fr.create("installation-not-found")})}function Br(e){var t;return 1===(t=e).registrationStatus&&t.registrationTime+hr<Date.now()?{fid:e.fid,registrationStatus:0}:e}async function jr({appConfig:e,heartbeatServiceProvider:t},r){[i,s]=[e,r.fid];let n=mr(i)+`/${s}/authTokens:generate`;var i,s,a=wr(e,r),o=t.getImmediate({optional:!0}),o=(o&&(o=await o.getHeartbeatsHeader())&&a.append("x-firebase-client",o),{installation:{sdkVersion:cr,appId:e.appId}});let l={method:"POST",headers:a,body:JSON.stringify(o)};a=await br(()=>fetch(n,l));if(a.ok)return vr(await a.json());throw await _r("Generate Auth Token",a)}async function zr(n,i=!1){let s;var e=await Ur(n.appConfig,e=>{if(!Wr(e))throw fr.create("not-registered");var t,r=e.authToken;if(i||2!==(t=r).requestStatus||(e=>{var t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+pr})(t)){if(1===r.requestStatus)return s=(async(e,t)=>{let r=await Kr(e.appConfig);for(;1===r.authToken.requestStatus;)await Ir(100),r=await Kr(e.appConfig);var n=r.authToken;return 0===n.requestStatus?zr(e,t):n})(n,i),e;if(navigator.onLine)return t=e,r={requestStatus:1,requestTime:Date.now()},r={...t,authToken:r},s=(async(t,r)=>{try{var e=await jr(t,r),n={...r,authToken:e};return await Lr(t.appConfig,n),e}catch(e){var i;throw!gr(e)||401!==e.customData.serverCode&&404!==e.customData.serverCode?(i={...r,authToken:{requestStatus:0}},await Lr(t.appConfig,i)):await Fr(t.appConfig),e}})(n,r),r;throw fr.create("app-offline")}return e});return s?await s:e.authToken}function Kr(e){return Ur(e,e=>{var t,r;if(Wr(e))return t=e.authToken,1===(r=t).requestStatus&&r.requestTime+hr<Date.now()?{...e,authToken:{requestStatus:0}}:e;throw fr.create("not-registered")})}function Wr(e){return void 0!==e&&2===e.registrationStatus}async function Hr(e,t=!1){var r=e,n=(await(!(n=(await Vr(r)).registrationPromise)||!await n),await zr(r,t));return n.token}function Gr(e){return fr.create("missing-app-config-values",{valueName:e})}let $r="installations",Qr=e=>{var t=e.getProvider("app").getImmediate();return{app:t,appConfig:(e=>{if(!e||!e.options)throw Gr("App Configuration");if(!e.name)throw Gr("App Name");var t;for(t of["projectId","apiKey","appId"])if(!e.options[t])throw Gr(t);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}})(t),heartbeatServiceProvider:Rt(t,"heartbeat"),_delete:()=>Promise.resolve()}},Yr=e=>{let t=Rt(e.getProvider("app").getImmediate(),$r).getImmediate();return{getId:()=>(async e=>{var t=e,{installationEntry:r,registrationPromise:n}=await Vr(t);return(n||zr(t)).catch(console.error),r.fid})(t),getToken:e=>Hr(t,e)}};Nt(new c($r,Qr,"PUBLIC")),Nt(new c("installations-internal",Yr,"PRIVATE")),u(ar,lr),u(ar,lr,"esm2020");let Jr="analytics",Xr="firebase_id",Zr="origin",en=6e4,tn="https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig",rn="https://www.googletagmanager.com/gtag/js",nn=new Xe("@firebase/analytics"),sn=new ge("analytics","Analytics",{"already-exists":"A Firebase Analytics instance with the appId {$id} already exists. Only one Firebase Analytics instance can be created for each appId.","already-initialized":"initializeAnalytics() cannot be called again with different options than those it was initially called with. It can be called again with the same options to return the existing instance, or getAnalytics() can be used to get a reference to the already-initialized instance.","already-initialized-settings":"Firebase Analytics has already been initialized.settings() must be called before initializing any Analytics instanceor it will have no effect.","interop-component-reg-failed":"Firebase Analytics Interop Component failed to instantiate: {$reason}","invalid-analytics-context":"Firebase Analytics is not supported in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","indexeddb-unavailable":"IndexedDB unavailable or restricted in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","fetch-throttle":"The config fetch request timed out while in an exponential backoff state. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.","config-fetch-failed":"Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}","no-api-key":'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid API key.',"no-app-id":'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid app ID.',"no-client-id":'The "client_id" field is empty.',"invalid-gtag-resource":"Trusted Types detected an invalid gtag resource: {$gtagURL}."});function an(e){var t;return e.startsWith(rn)?e:(t=sn.create("invalid-gtag-resource",{gtagURL:e}),nn.warn(t.message),"")}function on(e){return Promise.all(e.map(e=>e.catch(e=>e)))}function ln(e,t){var r=((e,t)=>{let r;return r=window.trustedTypes?window.trustedTypes.createPolicy(e,t):r})("firebase-js-sdk-policy",{createScriptURL:an}),n=document.createElement("script"),i=rn+`?l=${e}&id=`+t;n.src=r?r?.createScriptURL(i):i,n.async=!0,document.head.appendChild(n)}function hn(k,A,N,R){return async function(e,...t){try{if("event"===e){var[r,n]=t,i=k,s=A,a=N,o=r,l=n;try{let r=[];if(l&&l.send_to){let e=l.send_to;Array.isArray(e)||(e=[e]);var h=await on(a);for(let t of e){var c=h.find(e=>e.measurementId===t),u=c&&s[c.appId];if(!u){r=[];break}r.push(u)}}0===r.length&&(r=Object.values(s)),await Promise.all(r),i("event",o,l||{})}catch(e){nn.error(e)}}else if("config"===e){var d,[p,f]=t,g=k,m=A,v=N,_=p,y=f,w=R[_];try{w?await m[w]:(d=(await on(v)).find(e=>e.measurementId===_))&&await m[d.appId]}catch(e){nn.error(e)}g("config",_,y)}else{var b,I,T,E,C,S;"consent"===e?([b,I]=t,k("consent",b,I)):"get"===e?([T,E,C]=t,k("get",T,E,C)):"set"===e?([S]=t,k("set",S)):k(e,...t)}}catch(e){nn.error(e)}}}let cn=30;let un=new class{constructor(e={},t=1e3){this.throttleMetadata=e,this.intervalMillis=t}getThrottleMetadata(e){return this.throttleMetadata[e]}setThrottleMetadata(e,t){this.throttleMetadata[e]=t}deleteThrottleMetadata(e){delete this.throttleMetadata[e]}};async function dn(e){var{appId:t,apiKey:r}=e,r={method:"GET",headers:new Headers({Accept:"application/json","x-goog-api-key":r})},t=tn.replace("{app-id}",t),t=await fetch(t,r);if(200===t.status||304===t.status)return t.json();{let e="";try{var n=await t.json();n.error?.message&&(e=n.error.message)}catch(e){}throw sn.create("config-fetch-failed",{httpStatus:t.status,responseMessage:e})}}async function pn(e,t=un,r){var{appId:n,apiKey:i,measurementId:s}=e.options;if(!n)throw sn.create("no-app-id");if(!i){if(s)return{measurementId:s,appId:n};throw sn.create("no-api-key")}var a=t.getThrottleMetadata(n)||{backoffCount:0,throttleEndTimeMillis:Date.now()};let o=new mn;return setTimeout(async()=>{o.abort()},void 0!==r?r:en),async function i(s,{throttleEndTimeMillis:e,backoffCount:a},o,l=un){let{appId:h,measurementId:c}=s;try{await fn(o,e)}catch(e){if(c)return nn.warn("Timed out fetching this Firebase app's measurement ID from the server. Falling back to the measurement ID "+c+` provided in the "measurementId" field in the local Firebase config. [${e?.message}]`),{appId:h,measurementId:c};throw e}try{let e=await dn(s);return l.deleteThrottleMetadata(h),e}catch(e){let t=e;if(!gn(t)){if(l.deleteThrottleMetadata(h),c)return nn.warn("Failed to fetch this Firebase app's measurement ID from the server. Falling back to the measurement ID "+c+` provided in the "measurementId" field in the local Firebase config. [${t?.message}]`),{appId:h,measurementId:c};throw e}let r=503===Number(t?.customData?.httpStatus)?Be(a,l.intervalMillis,cn):Be(a,l.intervalMillis),n={throttleEndTimeMillis:Date.now()+r,backoffCount:a+1};return l.setThrottleMetadata(h,n),nn.debug(`Calling attemptFetch again in ${r} millis`),i(s,n,o,l)}}({appId:n,apiKey:i,measurementId:s},a,o,t)}function fn(i,s){return new Promise((e,t)=>{var r=Math.max(s-Date.now(),0);let n=setTimeout(e,r);i.addEventListener(()=>{clearTimeout(n),t(sn.create("fetch-throttle",{throttleEndTimeMillis:s}))})})}function gn(e){var t;return!!(e instanceof fe&&e.customData)&&(429===(t=Number(e.customData.httpStatus))||500===t||503===t||504===t)}class mn{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach(e=>e())}}async function vn(t,e,r,n,i,s,a){var o=pn(t),l=(o.then(e=>{r[e.measurementId]=e.appId,t.options.measurementId&&e.measurementId!==t.options.measurementId&&nn.warn(`The measurement ID in the local Firebase config (${t.options.measurementId})`+` does not match the measurement ID fetched from the server (${e.measurementId}).`+" To ensure analytics events are always sent to the correct Analytics property, update the measurement ID field in the local config or remove it from the local config.")}).catch(e=>nn.error(e)),e.push(o),(async()=>{if(!ue())return nn.warn(sn.create("indexeddb-unavailable",{errorInfo:"IndexedDB is not available in this environment."}).message),!1;try{await de()}catch(e){return nn.warn(sn.create("indexeddb-unavailable",{errorInfo:e?.toString()}).message),!1}return!0})().then(e=>{if(e)return n.getId()})),[o,l]=await Promise.all([o,l]),h=((e=>{var t,r=window.document.getElementsByTagName("script");for(t of Object.values(r))if(t.src&&t.src.includes(rn)&&t.src.includes(e))return t})(s)||ln(s,o.measurementId),i("js",new Date),a?.config??{});return h[Zr]="firebase",h.update=!0,null!=l&&(h[Xr]=l),i("config",o.measurementId,h),o.measurementId}class _n{constructor(e){this.app=e}_delete(){return delete yn[this.app.options.appId],Promise.resolve()}}let yn={},wn=[],bn={},In="dataLayer",Tn="gtag",En,Cn,Sn=!1;function kn(e){if(Sn)throw sn.create("already-initialized");e.dataLayerName&&(In=e.dataLayerName),e.gtagName&&(Tn=e.gtagName)}function An(e,t,r){n=[],se()&&n.push("This is a browser extension environment."),pe()||n.push("Cookies are not available."),0<n.length&&(n=n.map((e,t)=>`(${t+1}) `+e).join(" "),n=sn.create("invalid-analytics-context",{errorInfo:n}),nn.warn(n.message));var n=e.options.appId;if(!n)throw sn.create("no-app-id");if(!e.options.apiKey){if(!e.options.measurementId)throw sn.create("no-api-key");nn.warn('The "apiKey" field is empty in the local Firebase config. This is needed to fetch the latest measurement ID for this Firebase app. Falling back to the measurement ID '+e.options.measurementId+' provided in the "measurementId" field in the local Firebase config.')}if(null!=yn[n])throw sn.create("already-exists",{id:n});if(!Sn){{var i=In;let e=[];Array.isArray(window[i])?e=window[i]:window[i]=e,e}var{wrappedGtag:s,gtagCore:a}=((e,t,r,n,i)=>{let s=function(){window[n].push(arguments)};return window[i]&&"function"==typeof window[i]&&(s=window[i]),window[i]=hn(s,e,t,r),{gtagCore:s,wrappedGtag:window[i]}})(yn,wn,bn,In,Tn);Cn=s,En=a,Sn=!0}return yn[n]=vn(e,wn,bn,t,En,In,r),new _n(e)}async function Nn(){if(se())return!1;if(!pe())return!1;if(!ue())return!1;try{return await de()}catch(e){return!1}}function Rn(e,t,r){e=w(e),(async(e,t,r,n)=>{if(n&&n.global)return e("set",{screen_name:r}),Promise.resolve();e("config",await t,{update:!0,screen_name:r})})(Cn,yn[e.app.options.appId],t,r).catch(e=>nn.error(e))}function Pn(e,t,r){e=w(e),(async(e,t,r,n)=>{if(n&&n.global)return e("set",{user_id:r}),Promise.resolve();e("config",await t,{update:!0,user_id:r})})(Cn,yn[e.app.options.appId],t,r).catch(e=>nn.error(e))}function Dn(e,t,r){e=w(e),(async(e,t,r,n)=>{if(n&&n.global){var i,s={};for(i of Object.keys(r))s["user_properties."+i]=r[i];return e("set",s),Promise.resolve()}e("config",await t,{update:!0,user_properties:r})})(Cn,yn[e.app.options.appId],t,r).catch(e=>nn.error(e))}function xn(e,t){e=w(e),(async(e,t)=>{var r=await e;window["ga-disable-"+r]=!t})(yn[e.app.options.appId],t).catch(e=>nn.error(e))}function On(e,t,r,n){e=w(e),(async(e,t,r,n,i)=>{var s;i&&i.global?e("event",r,n):(s=await t,e("event",r,{...n,send_to:s}))})(Cn,yn[e.app.options.appId],t,r,n).catch(e=>nn.error(e))}let Mn="@firebase/analytics",Ln="0.10.21";Nt(new c(Jr,(e,{options:t})=>An(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),t),"PUBLIC")),Nt(new c("analytics-internal",function(e){try{let n=e.getProvider(Jr).getImmediate();return{logEvent:(e,t,r)=>On(n,e,t,r),setUserProperties:(e,t)=>Dn(n,e,t)}}catch(e){throw sn.create("interop-component-reg-failed",{reason:e})}},"PRIVATE")),u(Mn,Ln),u(Mn,Ln,"esm2020");class Fn{constructor(e,t){this.app=e,this._delegate=t}logEvent(e,t,r){On(this._delegate,e,t,r)}setCurrentScreen(e,t){Rn(this._delegate,e,t)}setUserId(e,t){Pn(this._delegate,e,t)}setUserProperties(e,t){Dn(this._delegate,e,t)}setAnalyticsCollectionEnabled(e){xn(this._delegate,e)}}(t=e=e||{}).ADD_SHIPPING_INFO="add_shipping_info",t.ADD_PAYMENT_INFO="add_payment_info",t.ADD_TO_CART="add_to_cart",t.ADD_TO_WISHLIST="add_to_wishlist",t.BEGIN_CHECKOUT="begin_checkout",t.CHECKOUT_PROGRESS="checkout_progress",t.EXCEPTION="exception",t.GENERATE_LEAD="generate_lead",t.LOGIN="login",t.PAGE_VIEW="page_view",t.PURCHASE="purchase",t.REFUND="refund",t.REMOVE_FROM_CART="remove_from_cart",t.SCREEN_VIEW="screen_view",t.SEARCH="search",t.SELECT_CONTENT="select_content",t.SELECT_ITEM="select_item",t.SELECT_PROMOTION="select_promotion",t.SET_CHECKOUT_OPTION="set_checkout_option",t.SHARE="share",t.SIGN_UP="sign_up",t.TIMING_COMPLETE="timing_complete",t.VIEW_CART="view_cart",t.VIEW_ITEM="view_item",t.VIEW_ITEM_LIST="view_item_list",t.VIEW_PROMOTION="view_promotion",t.VIEW_SEARCH_RESULTS="view_search_results";let Un=e=>{var t=e.getProvider("app-compat").getImmediate(),r=e.getProvider("analytics").getImmediate();return new Fn(t,r)};sr={Analytics:Fn,settings:kn,isSupported:Nn,EventName:e},or.INTERNAL.registerComponent(new c("analytics-compat",Un,"PUBLIC").setServiceProps(sr).setMultipleInstances(!0)),or.registerVersion("@firebase/analytics-compat","0.2.27");let Vn=new Map,qn={activated:!1,tokenObservers:[]},Bn={initialized:!1,enabled:!1};function jn(e){return Vn.get(e)||{...qn}}let zn="https://content-firebaseappcheck.googleapis.com/v1",Kn="exchangeDebugToken",Wn={OFFSET_DURATION:3e5,RETRIAL_MIN_WAIT:3e4,RETRIAL_MAX_WAIT:96e4};class Hn{constructor(e,t,r,n,i){if(this.operation=e,this.retryPolicy=t,this.getWaitDuration=r,this.lowerBound=n,this.upperBound=i,this.pending=null,i<(this.nextErrorWaitInterval=n))throw new Error("Proactive refresh lower bound greater than upper bound!")}start(){this.nextErrorWaitInterval=this.lowerBound,this.process(!0).catch(()=>{})}stop(){this.pending&&(this.pending.reject("cancelled"),this.pending=null)}isRunning(){return!!this.pending}async process(e){this.stop();try{this.pending=new Z,this.pending.promise.catch(e=>{}),t=this.getNextRun(e),await new Promise(e=>{setTimeout(e,t)}),this.pending.resolve(),await this.pending.promise,this.pending=new Z,this.pending.promise.catch(e=>{}),await this.operation(),this.pending.resolve(),await this.pending.promise,this.process(!0).catch(()=>{})}catch(e){this.retryPolicy(e)?this.process(!1).catch(()=>{}):this.stop()}var t}getNextRun(e){var t;return e?(this.nextErrorWaitInterval=this.lowerBound,this.getWaitDuration()):(t=this.nextErrorWaitInterval,this.nextErrorWaitInterval*=2,this.nextErrorWaitInterval>this.upperBound&&(this.nextErrorWaitInterval=this.upperBound),t)}}let Gn=new ge("appCheck","AppCheck",{"already-initialized":"You have already called initializeAppCheck() for FirebaseApp {$appName} with different options. To avoid this error, call initializeAppCheck() with the same options as when it was originally called. This will return the already initialized instance.","use-before-activation":"App Check is being used before initializeAppCheck() is called for FirebaseApp {$appName}. Call initializeAppCheck() before instantiating other Firebase services.","fetch-network-error":"Fetch failed to connect to a network. Check Internet connection. Original error: {$originalErrorMessage}.","fetch-parse-error":"Fetch client could not parse response. Original error: {$originalErrorMessage}.","fetch-status-error":"Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.","storage-open":"Error thrown when opening storage. Original error: {$originalErrorMessage}.","storage-get":"Error thrown when reading from storage. Original error: {$originalErrorMessage}.","storage-set":"Error thrown when writing to storage. Original error: {$originalErrorMessage}.","recaptcha-error":"ReCAPTCHA error.","initial-throttle":"{$httpStatus} error. Attempts allowed again after {$time}",throttled:"Requests throttled due to previous {$httpStatus} error. Attempts allowed again after {$time}"});function $n(e=!1){return e?self.grecaptcha?.enterprise:self.grecaptcha}function Qn(e){if(!jn(e).activated)throw Gn.create("use-before-activation",{appName:e.name})}function Yn(e){var t=Math.round(e/1e3),r=Math.floor(t/86400),n=Math.floor((t-3600*r*24)/3600),i=Math.floor((t-3600*r*24-3600*n)/60),t=t-3600*r*24-3600*n-60*i;let s="";return r&&(s+=Jn(r)+"d:"),n&&(s+=Jn(n)+"h:"),s+=Jn(i)+"m:"+Jn(t)+"s"}function Jn(e){return 0===e?"00":10<=e?e.toString():"0"+e}async function Xn({url:e,body:t},r){var n={"Content-Type":"application/json"},i=r.getImmediate({optional:!0}),i=(i&&(i=await i.getHeartbeatsHeader())&&(n["X-Firebase-Client"]=i),{method:"POST",body:JSON.stringify(t),headers:n});let s;try{s=await fetch(e,i)}catch(e){throw Gn.create("fetch-network-error",{originalErrorMessage:e?.message})}if(200!==s.status)throw Gn.create("fetch-status-error",{httpStatus:s.status});let a;try{a=await s.json()}catch(e){throw Gn.create("fetch-parse-error",{originalErrorMessage:e?.message})}var n=a.ttl.match(/^([\d.]+)(s)$/);if(n&&n[2]&&!isNaN(Number(n[1])))return i=1e3*Number(n[1]),n=Date.now(),{token:a.token,expireTimeMillis:n+i,issuedAtTimeMillis:n};throw Gn.create("fetch-parse-error",{originalErrorMessage:"ttl field (timeToLive) is not in standard Protobuf Duration format: "+a.ttl})}function Zn(e,t){var{projectId:r,appId:n,apiKey:i}=e.options;return{url:`${zn}/projects/${r}/apps/${n}:${Kn}?key=`+i,body:{debug_token:t}}}let ei="firebase-app-check-database",ti=1,ri="firebase-app-check-store",ni="debug-token",ii=null;function si(){return ii=ii||new Promise((t,r)=>{try{var e=indexedDB.open(ei,ti);e.onsuccess=e=>{t(e.target.result)},e.onerror=e=>{r(Gn.create("storage-open",{originalErrorMessage:e.target.error?.message}))},e.onupgradeneeded=e=>{var t=e.target.result;0===e.oldVersion&&t.createObjectStore(ri,{keyPath:"compositeKey"})}}catch(e){r(Gn.create("storage-open",{originalErrorMessage:e?.message}))}})}async function ai(e,t){let n=(await si()).transaction(ri,"readwrite"),i=n.objectStore(ri).put({compositeKey:e,value:t});return new Promise((t,r)=>{i.onsuccess=e=>{t()},n.onerror=e=>{r(Gn.create("storage-set",{originalErrorMessage:e.target.error?.message}))}})}async function oi(e){let n=(await si()).transaction(ri,"readonly"),i=n.objectStore(ri).get(e);return new Promise((r,t)=>{i.onsuccess=e=>{var t=e.target.result;r(t?t.value:void 0)},n.onerror=e=>{t(Gn.create("storage-get",{originalErrorMessage:e.target.error?.message}))}})}function li(e){return e.options.appId+"-"+e.name}let hi=new Xe("@firebase/app-check");async function ci(t){if(ue()){let e=void 0;try{e=await oi(li(t))}catch(e){hi.warn("Failed to read token from IndexedDB. Error: "+e)}return e}}function ui(e,t){return ue()?ai(li(e),t).catch(e=>{hi.warn("Failed to write token to IndexedDB. Error: "+e)}):Promise.resolve()}async function di(){let e=void 0;try{e=await oi(ni)}catch(e){}var t,r;return e||(t=crypto.randomUUID(),r=t,ai(ni,r).catch(e=>hi.warn("Failed to persist debug token to IndexedDB. Error: "+e)),t)}function pi(){return Bn.enabled}async function fi(){var e=Bn;if(e.enabled&&e.token)return e.token.promise;throw Error(`
|
|
8
8
|
Can't get debug token in production mode.
|
|
9
|
-
`)}let gi={error:"UNKNOWN_ERROR"};async function mi(e,t=!1,r=!1){var n,i=e.app;Qn(i);let s=jn(i),a=s.token,o=void 0;if(a&&!bi(a)&&(s.token=void 0,a=void 0),a||(n=await s.cachedTokenPromise)&&(bi(n)?a=n:await ui(i,void 0)),!t&&a&&bi(a))return{token:a.token};let l=!1;if(pi())try{var h=await fi(),c=(s.exchangeTokenPromise||(s.exchangeTokenPromise=Xn(Zn(i,h),e.heartbeatServiceProvider).finally(()=>{s.exchangeTokenPromise=void 0}),l=!0),await s.exchangeTokenPromise);return await ui(i,c),{token:(s.token=c).token}}catch(e){return"appCheck/throttled"===e.code||"appCheck/initial-throttle"===e.code?hi.warn(e.message):r&&hi.error(e),Ii(e)}try{s.exchangeTokenPromise||(s.exchangeTokenPromise=s.provider.getToken().finally(()=>{s.exchangeTokenPromise=void 0}),l=!0),a=await jn(i).exchangeTokenPromise}catch(e){"appCheck/throttled"===e.code||"appCheck/initial-throttle"===e.code?hi.warn(e.message):r&&hi.error(e),o=e}let u;return a?o?u=bi(a)?{token:a.token,internalError:o}:Ii(o):(u={token:a.token},await ui(i,s.token=a)):u=Ii(o),l&&wi(i,u),u}function vi(t,e,r,n){var i=t.app,i=jn(i),s={next:r,error:n,type:e};if(i.tokenObservers=[...i.tokenObservers,s],i.token&&bi(i.token)){let e=i.token;Promise.resolve().then(()=>{r({token:e.token}),yi(t)}).catch(()=>{})}i.cachedTokenPromise.then(()=>yi(t))}function _i(e,t){var r=jn(e),n=r.tokenObservers.filter(e=>e.next!==t);0===n.length&&r.tokenRefresher&&r.tokenRefresher.isRunning()&&r.tokenRefresher.stop(),r.tokenObservers=n}function yi(e){var t=e.app,t=jn(t);let r=t.tokenRefresher;r||(r=(r=>{let n=r.app;return new Hn(async()=>{var e=jn(n);let t;if((t=e.token?await mi(r,!0):await mi(r)).error)throw t.error;if(t.internalError)throw t.internalError},()=>!0,()=>{var e,t=jn(n);return t.token?(e=t.token.issuedAtTimeMillis+.5*(t.token.expireTimeMillis-t.token.issuedAtTimeMillis)+3e5,t=t.token.expireTimeMillis-3e5,e=Math.min(e,t),Math.max(0,e-Date.now())):0},Wn.RETRIAL_MIN_WAIT,Wn.RETRIAL_MAX_WAIT)})(e),t.tokenRefresher=r),!r.isRunning()&&t.isTokenAutoRefreshEnabled&&r.start()}function wi(e,t){var r;for(r of jn(e).tokenObservers)try{"EXTERNAL"===r.type&&null!=t.error?r.error(t.error):r.next(t)}catch(e){}}function bi(e){return 0<e.expireTimeMillis-Date.now()}function Ii(e){return{token:(t=gi,a.encodeString(JSON.stringify(t),!1)),error:e};var t}class Ti{constructor(e,t){this.app=e,this.heartbeatServiceProvider=t}_delete(){var e,t=jn(this.app).tokenObservers;for(e of t)_i(this.app,e.next);return Promise.resolve()}}function Ei(t){return{getToken:e=>mi(t,e),getLimitedUseToken:()=>(async e=>{var t=e.app,r=(Qn(t),jn(t)).provider;return pi()?{token:t=(await Xn(Zn(t,await fi()),e.heartbeatServiceProvider)).token}:{token:t=(await r.getToken()).token}})(t),addTokenListener:e=>vi(t,"INTERNAL",e),removeTokenListener:e=>_i(t.app,e)}}let Ci="https://www.google.com/recaptcha/api.js",Si="https://www.google.com/recaptcha/enterprise.js";function ki(t,r){let n=new Z;jn(t).reCAPTCHAState={initialized:n};let i=Ri(t);var e,s=$n(!1);return s?Ni(t,r,s,i,n):(e=()=>{var e=$n(!1);if(!e)throw new Error("no recaptcha");Ni(t,r,e,i,n)},(s=document.createElement("script")).src=Ci,s.onload=e,document.head.appendChild(s)),n.promise}function Ai(t,r){let n=new Z;jn(t).reCAPTCHAState={initialized:n};let i=Ri(t);var e,s=$n(!0);return s?Ni(t,r,s,i,n):(e=()=>{var e=$n(!0);if(!e)throw new Error("no recaptcha");Ni(t,r,e,i,n)},(s=document.createElement("script")).src=Si,s.onload=e,document.head.appendChild(s)),n.promise}function Ni(n,i,s,a,o){s.ready(()=>{var e,t,r;e=n,t=s.render(a,{sitekey:i,size:"invisible",callback:()=>{jn(e).reCAPTCHAState.succeeded=!0},"error-callback":()=>{jn(e).reCAPTCHAState.succeeded=!1}}),(r=jn(e)).reCAPTCHAState={...r.reCAPTCHAState,widgetId:t},o.resolve(s)})}function Ri(e){var t="fire_app_check_"+e.name,r=document.createElement("div");return r.id=t,r.style.display="none",document.body.appendChild(r),t}async function Pi(n){Qn(n);let i=await jn(n).reCAPTCHAState.initialized.promise;return new Promise((e,t)=>{let r=jn(n).reCAPTCHAState;i.ready(()=>{e(i.execute(r.widgetId,{action:"fire_app_check"}))})})}class Di{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){Li(this._throttleData);var e=await Pi(this._app).catch(e=>{throw Gn.create("recaptcha-error")});if(!jn(this._app).reCAPTCHAState?.succeeded)throw Gn.create("recaptcha-error");let t;try{t=await Xn(((e,t)=>{var{projectId:r,appId:n,apiKey:i}=e.options;return{url:zn+`/projects/${r}/apps/${n}:exchangeRecaptchaV3Token?key=`+i,body:{recaptcha_v3_token:t}}})(this._app,e),this._heartbeatServiceProvider)}catch(e){throw e.code?.includes("fetch-status-error")?(this._throttleData=Mi(Number(e.customData?.httpStatus),this._throttleData),Gn.create("initial-throttle",{time:Yn(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,t}initialize(e){this._app=e,this._heartbeatServiceProvider=Rt(e,"heartbeat"),ki(e,this._siteKey).catch(()=>{})}isEqual(e){return e instanceof Di&&this._siteKey===e._siteKey}}class xi{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){Li(this._throttleData);var e=await Pi(this._app).catch(e=>{throw Gn.create("recaptcha-error")});if(!jn(this._app).reCAPTCHAState?.succeeded)throw Gn.create("recaptcha-error");let t;try{t=await Xn(((e,t)=>{var{projectId:r,appId:n,apiKey:i}=e.options;return{url:zn+`/projects/${r}/apps/${n}:exchangeRecaptchaEnterpriseToken?key=`+i,body:{recaptcha_enterprise_token:t}}})(this._app,e),this._heartbeatServiceProvider)}catch(e){throw e.code?.includes("fetch-status-error")?(this._throttleData=Mi(Number(e.customData?.httpStatus),this._throttleData),Gn.create("initial-throttle",{time:Yn(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,t}initialize(e){this._app=e,this._heartbeatServiceProvider=Rt(e,"heartbeat"),Ai(e,this._siteKey).catch(()=>{})}isEqual(e){return e instanceof xi&&this._siteKey===e._siteKey}}class Oi{constructor(e){this._customProviderOptions=e}async getToken(){var e,t=await this._customProviderOptions.getToken(),r=(e=t.token,"object"==typeof(r=ye(e).claims)&&r.hasOwnProperty("iat")?r.iat:null),r=null!==r&&r<Date.now()&&0<r?1e3*r:Date.now();return{...t,issuedAtTimeMillis:r}}initialize(e){this._app=e}isEqual(e){return e instanceof Oi&&this._customProviderOptions.getToken.toString()===e._customProviderOptions.getToken.toString()}}function Mi(e,t){var r,n;return 404===e||403===e?{backoffCount:1,allowRequestsAfter:Date.now()+864e5,httpStatus:e}:(n=Be(r=t?t.backoffCount:0,1e3,2),{backoffCount:r+1,allowRequestsAfter:Date.now()+n,httpStatus:e})}function Li(e){if(e&&Date.now()-e.allowRequestsAfter<=0)throw Gn.create("throttled",{time:Yn(e.allowRequestsAfter-Date.now()),httpStatus:e.httpStatus})}function Fi(e=Vt(),r){var t=Rt(e=w(e),"app-check");if(Bn.initialized||(i=H(),(n=Bn).initialized=!0,"string"!=typeof i.FIREBASE_APPCHECK_DEBUG_TOKEN&&!0!==i.FIREBASE_APPCHECK_DEBUG_TOKEN)||(n.enabled=!0,s=new Z,n.token=s,"string"==typeof i.FIREBASE_APPCHECK_DEBUG_TOKEN?s.resolve(i.FIREBASE_APPCHECK_DEBUG_TOKEN):s.resolve(di())),pi()&&fi().then(e=>console.log(`App Check debug token: ${e}. You will need to add it to your app's App Check settings in the Firebase console for it to work.`)),t.isInitialized()){var n=t.getImmediate(),i=t.getOptions();if(i.isTokenAutoRefreshEnabled===r.isTokenAutoRefreshEnabled&&i.provider.isEqual(r.provider))return n;throw Gn.create("already-initialized",{appName:e.name})}var s=t.initialize({options:r});{var[a,r,o=!1]=[e,r.provider,r.isTokenAutoRefreshEnabled];let t=((e,t)=>(Vn.set(e,t),Vn.get(e)))(a,{...qn});t.activated=!0,t.provider=r,t.cachedTokenPromise=ci(a).then(e=>(e&&bi(e)&&(t.token=e,wi(a,{token:e.token})),e)),t.isTokenAutoRefreshEnabled=o&&a.automaticDataCollectionEnabled,!a.automaticDataCollectionEnabled&&o&&hi.warn("`isTokenAutoRefreshEnabled` is true but `automaticDataCollectionEnabled` was set to false during `initializeApp()`. This blocks automatic token refresh."),t.provider.initialize(a)}return jn(e).isTokenAutoRefreshEnabled&&vi(s,"INTERNAL",()=>{}),s}let Ui="app-check-internal";Nt(new c("app-check",e=>{var t,r=e.getProvider("app").getImmediate(),n=e.getProvider("heartbeat");return e=r,t=n,new Ti(e,t)},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,r)=>{e.getProvider(Ui).initialize()})),Nt(new c(Ui,e=>Ei(e.getProvider("app-check").getImmediate()),"PUBLIC").setInstantiationMode("EXPLICIT")),u("@firebase/app-check","0.11.2");let Vi=new ge("appCheck","AppCheck",{"use-before-activation":"App Check is being used before activate() is called for FirebaseApp {$appName}. Call activate() before instantiating other Firebase services."});class qi{constructor(e){this.app=e}activate(e,t){let r;r="string"==typeof e?new Di(e):e instanceof xi||e instanceof Di||e instanceof Oi?e:new Oi({getToken:e.getToken}),this._delegate=Fi(this.app,{provider:r,isTokenAutoRefreshEnabled:t})}setTokenAutoRefreshEnabled(e){if(!this._delegate)throw Vi.create("use-before-activation",{appName:this.app.name});var t,r;t=this._delegate,e=e,(r=jn(t.app)).tokenRefresher&&(!0===e?r.tokenRefresher.start():r.tokenRefresher.stop()),r.isTokenAutoRefreshEnabled=e}getToken(e){if(this._delegate)return(async(e,t)=>{var r=await mi(e,t);if(r.error)throw r.error;if(r.internalError)throw r.internalError;return{token:r.token}})(this._delegate,e);throw Vi.create("use-before-activation",{appName:this.app.name})}onTokenChanged(r,n,e){if(this._delegate){var i=this._delegate;let e=()=>{},t=()=>{};return e=null!=r.next?r.next.bind(r):r,null!=r.error?t=r.error.bind(r):n&&(t=n),vi(i,"EXTERNAL",e,t),()=>_i(i.app,e)}throw Vi.create("use-before-activation",{appName:this.app.name})}}let Bi=e=>{var t=e.getProvider("app-compat").getImmediate();return new qi(t)};or.INTERNAL.registerComponent(new c("appCheck-compat",Bi,"PUBLIC").setServiceProps({ReCaptchaEnterpriseProvider:xi,ReCaptchaV3Provider:Di,CustomProvider:Oi})),or.registerVersion("@firebase/app-check-compat","0.4.2");let ji={FACEBOOK:"facebook.com",GITHUB:"github.com",GOOGLE:"google.com",PASSWORD:"password",PHONE:"phone",TWITTER:"twitter.com"},zi={EMAIL_SIGNIN:"EMAIL_SIGNIN",PASSWORD_RESET:"PASSWORD_RESET",RECOVER_EMAIL:"RECOVER_EMAIL",REVERT_SECOND_FACTOR_ADDITION:"REVERT_SECOND_FACTOR_ADDITION",VERIFY_AND_CHANGE_EMAIL:"VERIFY_AND_CHANGE_EMAIL",VERIFY_EMAIL:"VERIFY_EMAIL"};function Ki(){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."}}function Wi(){return{"admin-restricted-operation":"This operation is restricted to administrators only.","argument-error":"","app-not-authorized":"This app, identified by the domain where it's hosted, is not authorized to use Firebase Authentication with the provided API key. Review your key configuration in the Google API console.","app-not-installed":"The requested mobile application corresponding to the identifier (Android package name or iOS bundle ID) provided is not installed on this device.","captcha-check-failed":"The reCAPTCHA response token provided is either invalid, expired, already used or the domain associated with it does not match the list of whitelisted domains.","code-expired":"The SMS code has expired. Please re-send the verification code to try again.","cordova-not-ready":"Cordova framework is not ready.","cors-unsupported":"This browser is not supported.","credential-already-in-use":"This credential is already associated with a different user account.","custom-token-mismatch":"The custom token corresponds to a different audience.","requires-recent-login":"This operation is sensitive and requires recent authentication. Log in again before retrying this request.","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.","dynamic-link-not-activated":"Please activate Dynamic Links in the Firebase Console and agree to the terms and conditions.","email-change-needs-verification":"Multi-factor users must always have a verified email.","email-already-in-use":"The email address is already in use by another account.","emulator-config-failed":'Auth instance has already been used to make a network call. Auth can no longer be configured to use the emulator. Try calling "connectAuthEmulator()" sooner.',"expired-action-code":"The action code has expired.","cancelled-popup-request":"This operation has been cancelled due to another conflicting popup being opened.","internal-error":"An internal AuthError has occurred.","invalid-app-credential":"The phone verification request contains an invalid application verifier. The reCAPTCHA token response is either invalid or expired.","invalid-app-id":"The mobile app identifier is not registered for the current project.","invalid-user-token":"This user's credential isn't valid for this project. This can happen if the user's token has been tampered with, or if the user isn't for the project associated with this API key.","invalid-auth-event":"An internal AuthError has occurred.","invalid-verification-code":"The SMS verification code used to create the phone auth credential is invalid. Please resend the verification code sms and be sure to use the verification code provided by the user.","invalid-continue-uri":"The continue URL provided in the request is invalid.","invalid-cordova-configuration":"The following Cordova plugins must be installed to enable OAuth sign-in: cordova-plugin-buildinfo, cordova-universal-links-plugin, cordova-plugin-browsertab, cordova-plugin-inappbrowser and cordova-plugin-customurlscheme.","invalid-custom-token":"The custom token format is incorrect. Please check the documentation.","invalid-dynamic-link-domain":"The provided dynamic link domain is not configured or authorized for the current project.","invalid-email":"The email address is badly formatted.","invalid-emulator-scheme":"Emulator URL must start with a valid scheme (http:// or https://).","invalid-api-key":"Your API key is invalid, please check you have copied it correctly.","invalid-cert-hash":"The SHA-1 certificate hash provided is invalid.","invalid-credential":"The supplied auth credential is incorrect, malformed or has expired.","invalid-message-payload":"The email template corresponding to this action contains invalid characters in its message. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-multi-factor-session":"The request does not contain a valid proof of first factor successful sign-in.","invalid-oauth-provider":"EmailAuthProvider is not supported for this operation. This operation only supports OAuth providers.","invalid-oauth-client-id":"The OAuth client ID provided is either invalid or does not match the specified API key.","unauthorized-domain":"This domain is not authorized for OAuth operations for your Firebase project. Edit the list of authorized domains from the Firebase console.","invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","wrong-password":"The password is invalid or the user does not have a password.","invalid-persistence-type":"The specified persistence type is invalid. It can only be local, session or none.","invalid-phone-number":"The format of the phone number provided is incorrect. Please enter the phone number in a format that can be parsed into E.164 format. E.164 phone numbers are written in the format [+][country code][subscriber number including area code].","invalid-provider-id":"The specified provider ID is invalid.","invalid-recipient-email":"The email corresponding to this action failed to send as the provided recipient email address is invalid.","invalid-sender":"The email template corresponding to this action contains an invalid sender email or name. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-verification-id":"The verification ID used to create the phone auth credential is invalid.","invalid-tenant-id":"The Auth instance's tenant ID is invalid.","login-blocked":"Login blocked by user-provided method: {$originalMessage}","missing-android-pkg-name":"An Android Package Name must be provided if the Android App is required to be installed.","auth-domain-config-required":"Be sure to include authDomain when calling firebase.initializeApp(), by following the instructions in the Firebase console.","missing-app-credential":"The phone verification request is missing an application verifier assertion. A reCAPTCHA response token needs to be provided.","missing-verification-code":"The phone auth credential was created with an empty SMS verification code.","missing-continue-uri":"A continue URL must be provided in the request.","missing-iframe-start":"An internal AuthError has occurred.","missing-ios-bundle-id":"An iOS Bundle ID must be provided if an App Store ID is provided.","missing-or-invalid-nonce":"The request does not contain a valid nonce. This can occur if the SHA-256 hash of the provided raw nonce does not match the hashed nonce in the ID token payload.","missing-password":"A non-empty password must be provided","missing-multi-factor-info":"No second factor identifier is provided.","missing-multi-factor-session":"The request is missing proof of first factor successful sign-in.","missing-phone-number":"To send verification codes, provide a phone number for the recipient.","missing-verification-id":"The phone auth credential was created with an empty verification ID.","app-deleted":"This instance of FirebaseApp has been deleted.","multi-factor-info-not-found":"The user does not have a second factor matching the identifier provided.","multi-factor-auth-required":"Proof of ownership of a second factor is required to complete sign-in.","account-exists-with-different-credential":"An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address.","network-request-failed":"A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.","no-auth-event":"An internal AuthError has occurred.","no-such-provider":"User was not linked to an account with the given provider.","null-user":"A null user object was provided as the argument for an operation which requires a non-null user object.","operation-not-allowed":"The given sign-in provider is disabled for this Firebase project. Enable it in the Firebase console, under the sign-in method tab of the Auth section.","operation-not-supported-in-this-environment":'This operation is not supported in the environment this application is running on. "location.protocol" must be http, https or chrome-extension and web storage must be enabled.',"popup-blocked":"Unable to establish a connection with the popup. It may have been blocked by the browser.","popup-closed-by-user":"The popup has been closed by the user before finalizing the operation.","provider-already-linked":"User can only be linked to one identity for the given provider.","quota-exceeded":"The project's quota for this operation has been exceeded.","redirect-cancelled-by-user":"The redirect operation has been cancelled by the user before finalizing.","redirect-operation-pending":"A redirect sign-in operation is already pending.","rejected-credential":"The request contains malformed or mismatching credentials.","second-factor-already-in-use":"The second factor is already enrolled on this account.","maximum-second-factor-count-exceeded":"The maximum allowed number of second factors on a user has been exceeded.","tenant-id-mismatch":"The provided tenant ID does not match the Auth instance's tenant ID",timeout:"The operation has timed out.","user-token-expired":"The user's credential is no longer valid. The user must sign in again.","too-many-requests":"We have blocked all requests from this device due to unusual activity. Try again later.","unauthorized-continue-uri":"The domain of the continue URL is not whitelisted. Please whitelist the domain in the Firebase console.","unsupported-first-factor":"Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.","unsupported-persistence-type":"The current environment does not support the specified persistence type.","unsupported-tenant-operation":"This operation is not supported in a multi-tenant context.","unverified-email":"The operation requires a verified email.","user-cancelled":"The user did not grant your application the permissions it requested.","user-not-found":"There is no user record corresponding to this identifier. The user may have been deleted.","user-disabled":"The user account has been disabled by an administrator.","user-mismatch":"The supplied credentials do not correspond to the previously signed in user.","user-signed-out":"","weak-password":"The password must be 6 characters long or more.","web-storage-unsupported":"This browser is not supported or 3rd party cookies and data may be disabled.","already-initialized":"initializeAuth() has already been called with different options. To avoid this error, call initializeAuth() with the same options as when it was originally called, or call getAuth() to return the already initialized instance.","missing-recaptcha-token":"The reCAPTCHA token is missing when sending request to the backend.","invalid-recaptcha-token":"The reCAPTCHA token is invalid when sending request to the backend.","invalid-recaptcha-action":"The reCAPTCHA action is invalid when sending request to the backend.","recaptcha-not-enabled":"reCAPTCHA Enterprise integration is not enabled for this project.","missing-client-type":"The reCAPTCHA client type is missing when sending request to the backend.","missing-recaptcha-version":"The reCAPTCHA version is missing when sending request to the backend.","invalid-req-type":"Invalid request parameters.","invalid-recaptcha-version":"The reCAPTCHA version is invalid when sending request to the backend.","unsupported-password-policy-schema-version":"The password policy received from the backend uses a schema version that is not supported by this version of the Firebase SDK.","password-does-not-meet-requirements":"The password does not meet the requirements.","invalid-hosting-link-domain":"The provided Hosting link domain is not configured in Firebase Hosting or is not owned by the current project. This cannot be a default Hosting domain (`web.app` or `firebaseapp.com`)."}}let Hi=Ki,Gi=new ge("auth","Firebase",Ki()),$i=new Xe("@firebase/auth");function Qi(e,...t){$i.logLevel<=p.ERROR&&$i.error(`Auth (${Ft}): `+e,...t)}function Yi(e,...t){throw ts(e,...t)}function Ji(e,...t){return ts(e,...t)}function Xi(e,t,r){var n={...Hi(),[t]:r};return new ge("auth","Firebase",n).create(t,{appName:e.name})}function Zi(e){return Xi(e,"operation-not-supported-in-this-environment","Operations that alter the current user are not supported in conjunction with FirebaseServerApp")}function es(e,t,r){var n=r;if(!(t instanceof n))throw n.name!==t.constructor.name&&Yi(e,"argument-error"),Xi(e,"argument-error",`Type of ${t.constructor.name} does not match expected instance.`+"Did you pass a reference from a different Auth SDK?")}function ts(e,...t){var r,n;return"string"!=typeof e?(r=t[0],(n=[...t.slice(1)])[0]&&(n[0].appName=e.name),e._errorFactory.create(r,...n)):Gi.create(e,...t)}function m(e,t,...r){if(!e)throw ts(t,...r)}function rs(e){var t="INTERNAL ASSERTION FAILED: "+e;throw Qi(t),new Error(t)}function ns(e,t){e||rs(t)}function is(){return"undefined"!=typeof self&&self.location?.href||""}function ss(){return"http:"===as()||"https:"===as()}function as(){return"undefined"!=typeof self&&self.location?.protocol||null}class os{constructor(e,t){ns((this.shortDelay=e)<(this.longDelay=t),"Short delay should be less than long delay!"),this.isMobile=re()||ae()}get(){return"undefined"!=typeof navigator&&navigator&&"onLine"in navigator&&"boolean"==typeof navigator.onLine&&(ss()||se()||"connection"in navigator)&&!navigator.onLine?Math.min(5e3,this.shortDelay):this.isMobile?this.longDelay:this.shortDelay}}function ls(e,t){ns(e.emulator,"Emulator should always be set here");var r=e.emulator.url;return t?""+r+(t.startsWith("/")?t.slice(1):t):r}class hs{static initialize(e,t,r){this.fetchImpl=e,t&&(this.headersImpl=t),r&&(this.responseImpl=r)}static fetch(){return this.fetchImpl||("undefined"!=typeof self&&"fetch"in self?self.fetch:"undefined"!=typeof globalThis&&globalThis.fetch?globalThis.fetch:"undefined"!=typeof fetch?fetch:void rs("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"))}static headers(){return this.headersImpl||("undefined"!=typeof self&&"Headers"in self?self.Headers:"undefined"!=typeof globalThis&&globalThis.Headers?globalThis.Headers:"undefined"!=typeof Headers?Headers:void rs("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"))}static response(){return this.responseImpl||("undefined"!=typeof self&&"Response"in self?self.Response:"undefined"!=typeof globalThis&&globalThis.Response?globalThis.Response:"undefined"!=typeof Response?Response:void rs("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"))}}let cs={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-recaptcha-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"},us=["/v1/accounts:signInWithCustomToken","/v1/accounts:signInWithEmailLink","/v1/accounts:signInWithIdp","/v1/accounts:signInWithPassword","/v1/accounts:signInWithPhoneNumber","/v1/token"],ds=new os(3e4,6e4);function ps(e,t){return e.tenantId&&!t.tenantId?{...t,tenantId:e.tenantId}:t}async function fs(i,s,a,o,e={}){return gs(i,e,async()=>{let e={},t={};o&&("GET"===s?t=o:e={body:JSON.stringify(o)});var r=Se({key:i.config.apiKey,...t}).slice(1),n=await i._getAdditionalHeaders(),n=(n["Content-Type"]="application/json",i.languageCode&&(n["X-Firebase-Locale"]=i.languageCode),{method:s,headers:n,...e});return"undefined"!=typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||(n.referrerPolicy="no-referrer"),i.emulatorConfig&&je(i.emulatorConfig.host)&&(n.credentials="include"),hs.fetch()(await vs(i,i.config.apiHost,a,r),n)})}async function gs(t,e,r){t._canInitEmulator=!1;var n={...cs,...e};try{var i=new _s(t),s=await Promise.race([r(),i.promise]),a=(i.clearNetworkTimeout(),await s.json());if("needConfirmation"in a)throw ys(t,"account-exists-with-different-credential",a);if(s.ok&&!("errorMessage"in a))return a;var[o,l]=(s.ok?a.errorMessage:a.error.message).split(" : ");if("FEDERATED_USER_ID_ALREADY_LINKED"===o)throw ys(t,"credential-already-in-use",a);if("EMAIL_EXISTS"===o)throw ys(t,"email-already-in-use",a);if("USER_DISABLED"===o)throw ys(t,"user-disabled",a);var h=n[o]||o.toLowerCase().replace(/[_\s]+/g,"-");if(l)throw Xi(t,h,l);Yi(t,h)}catch(e){if(e instanceof fe)throw e;Yi(t,"network-request-failed",{message:String(e)})}}async function ms(e,t,r,n,i={}){var s=await fs(e,t,r,n,i);return"mfaPendingCredential"in s&&Yi(e,"multi-factor-auth-required",{_serverResponse:s}),s}async function vs(e,t,r,n){var i=""+t+r+"?"+n,s=e,i=s.config.emulator?ls(e.config,i):e.config.apiScheme+"://"+i;if(us.includes(r)&&(await s._persistenceManagerAvailable,"COOKIE"===s._getPersistenceType()))return s._getPersistence()._getFinalTarget(i).toString();return i}class _s{clearNetworkTimeout(){clearTimeout(this.timer)}constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((e,t)=>{this.timer=setTimeout(()=>t(Ji(this.auth,"network-request-failed")),ds.get())})}}function ys(e,t,r){var n={appName:e.name},n=(r.email&&(n.email=r.email),r.phoneNumber&&(n.phoneNumber=r.phoneNumber),Ji(e,t,n));return n.customData._tokenResponse=r,n}function ws(e){return void 0!==e&&void 0!==e.getResponse}function bs(e){return void 0!==e&&void 0!==e.enterprise}class Is{constructor(e){if(this.siteKey="",this.recaptchaEnforcementState=[],void 0===e.recaptchaKey)throw new Error("recaptchaKey undefined");this.siteKey=e.recaptchaKey.split("/")[3],this.recaptchaEnforcementState=e.recaptchaEnforcementState}getProviderEnforcementState(t){if(this.recaptchaEnforcementState&&0!==this.recaptchaEnforcementState.length)for(let e of this.recaptchaEnforcementState)if(e.provider&&e.provider===t){switch(e.enforcementState){case"ENFORCE":return"ENFORCE";case"AUDIT":return"AUDIT";case"OFF":return"OFF";default:return"ENFORCEMENT_STATE_UNSPECIFIED"}return}return null}isProviderEnabled(e){return"ENFORCE"===this.getProviderEnforcementState(e)||"AUDIT"===this.getProviderEnforcementState(e)}isAnyProviderEnabled(){return this.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")||this.isProviderEnabled("PHONE_PROVIDER")}}async function Ts(e,t){return fs(e,"GET","/v2/recaptchaConfig",ps(e,t))}async function Es(e,t){return fs(e,"POST","/v1/accounts:lookup",t)}function Cs(e){if(e)try{var t=new Date(Number(e));if(!isNaN(t.getTime()))return t.toUTCString()}catch(e){}}function Ss(e){return 1e3*Number(e)}function ks(e){var[t,r,n]=e.split(".");if(void 0===t||void 0===r||void 0===n)return Qi("JWT malformed, contained fewer than 3 sections"),null;try{var i=K(r);return i?JSON.parse(i):(Qi("Failed to decode base64 JWT payload"),null)}catch(e){return Qi("Caught error parsing JWT payload as JSON",e?.toString()),null}}function As(e){var t=ks(e);return m(t,"internal-error"),m(void 0!==t.exp,"internal-error"),m(void 0!==t.iat,"internal-error"),Number(t.exp)-Number(t.iat)}async function Ns(t,e,r=!1){if(r)return e;try{return await e}catch(e){throw e instanceof fe&&(r=[e.code][0],"auth/user-disabled"===r||"auth/user-token-expired"===r)&&(t.auth.currentUser===t&&await t.auth.signOut()),e}}class Rs{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;return e?(t=this.errorBackoff,this.errorBackoff=Math.min(2*this.errorBackoff,96e4),t):(this.errorBackoff=3e4,t=(this.user.stsTokenManager.expirationTime??0)-Date.now()-3e5,Math.max(0,t))}schedule(e=!1){var t;this.isRunning&&(t=this.getInterval(e),this.timerId=setTimeout(async()=>{await this.iteration()},t))}async iteration(){try{await this.user.getIdToken(!0)}catch(e){return void("auth/network-request-failed"===e?.code&&this.schedule(!0))}this.schedule()}}class Ps{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=Cs(this.lastLoginAt),this.creationTime=Cs(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function Ds(e){var t,r,n=e.auth,i=await e.getIdToken(),i=await Ns(e,Es(n,{idToken:i})),n=(m(i?.users.length,n,"internal-error"),i.users[0]),i=(e._notifyReloadListener(n),n.providerUserInfo?.length?xs(n.providerUserInfo):[]),i=(t=e.providerData,r=i,[...t.filter(t=>!r.some(e=>e.providerId===t.providerId)),...r]),s=!(e.email&&n.passwordHash||i.length),s=!!e.isAnonymous&&s,i={uid:n.localId,displayName:n.displayName||null,photoURL:n.photoUrl||null,email:n.email||null,emailVerified:n.emailVerified||!1,phoneNumber:n.phoneNumber||null,tenantId:n.tenantId||null,providerData:i,metadata:new Ps(n.createdAt,n.lastLoginAt),isAnonymous:s};Object.assign(e,i)}function xs(e){return e.map(({providerId:e,...t})=>({providerId:e,uid:t.rawId||"",displayName:t.displayName||null,email:t.email||null,phoneNumber:t.phoneNumber||null,photoURL:t.photoUrl||null}))}class Os{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){m(e.idToken,"internal-error"),m(void 0!==e.idToken,"internal-error"),m(void 0!==e.refreshToken,"internal-error");var t="expiresIn"in e&&void 0!==e.expiresIn?Number(e.expiresIn):As(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,t)}updateFromIdToken(e){m(0!==e.length,"internal-error");var t=As(e);this.updateTokensAndExpiration(e,null,t)}async getToken(e,t=!1){return t||!this.accessToken||this.isExpired?(m(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){i=t;var n,i,{accessToken:r,refreshToken:s,expiresIn:a}=await{accessToken:(r=await gs(n=e,{},async()=>{var e=Se({grant_type:"refresh_token",refresh_token:i}).slice(1),{tokenApiHost:t,apiKey:r}=n.config,t=await vs(n,t,"/v1/token","key="+r),r=await n._getAdditionalHeaders(),r=(r["Content-Type"]="application/x-www-form-urlencoded",{method:"POST",headers:r,body:e});return n.emulatorConfig&&je(n.emulatorConfig.host)&&(r.credentials="include"),hs.fetch()(t,r)})).access_token,expiresIn:r.expires_in,refreshToken:r.refresh_token};this.updateTokensAndExpiration(r,s,Number(a))}updateTokensAndExpiration(e,t,r){this.refreshToken=t||null,this.accessToken=e||null,this.expirationTime=Date.now()+1e3*r}static fromJSON(e,t){var{refreshToken:r,accessToken:n,expirationTime:i}=t,s=new Os;return r&&(m("string"==typeof r,"internal-error",{appName:e}),s.refreshToken=r),n&&(m("string"==typeof n,"internal-error",{appName:e}),s.accessToken=n),i&&(m("number"==typeof i,"internal-error",{appName:e}),s.expirationTime=i),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 Os,this.toJSON())}_performRefresh(){return rs("not implemented")}}function Ms(e,t){m("string"==typeof e||void 0===e,"internal-error",{appName:t})}class Ls{constructor({uid:e,auth:t,stsTokenManager:r,...n}){this.providerId="firebase",this.proactiveRefresh=new Rs(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=e,this.auth=t,this.stsTokenManager=r,this.accessToken=r.accessToken,this.displayName=n.displayName||null,this.email=n.email||null,this.emailVerified=n.emailVerified||!1,this.phoneNumber=n.phoneNumber||null,this.photoURL=n.photoURL||null,this.isAnonymous=n.isAnonymous||!1,this.tenantId=n.tenantId||null,this.providerData=n.providerData?[...n.providerData]:[],this.metadata=new Ps(n.createdAt||void 0,n.lastLoginAt||void 0)}async getIdToken(e){var t=await Ns(this,this.stsTokenManager.getToken(this.auth,e));return m(t,this.auth,"internal-error"),this.accessToken!==t&&(this.accessToken=t,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),t}getIdTokenResult(e){return(async(e,t=!1)=>{var r=w(e),n=await r.getIdToken(t),i=ks(n),s=(m(i&&i.exp&&i.auth_time&&i.iat,r.auth,"internal-error"),(r="object"==typeof i.firebase?i.firebase:void 0)?.sign_in_provider);return{claims:i,token:n,authTime:Cs(Ss(i.auth_time)),issuedAtTime:Cs(Ss(i.iat)),expirationTime:Cs(Ss(i.exp)),signInProvider:s||null,signInSecondFactor:r?.sign_in_second_factor||null}})(this,e)}reload(){return(async e=>{var t=w(e);await Ds(t),await t.auth._persistUserIfCurrent(t),t.auth._notifyListenersIfCurrent(t)})(this)}_assign(e){this!==e&&(m(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=>({...e})),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){var t=new Ls({...this,auth:e,stsTokenManager:this.stsTokenManager._clone()});return t.metadata._copy(this.metadata),t}_onReload(e){m(!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 r=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),r=!0),t&&await Ds(this),await this.auth._persistUserIfCurrent(this),r&&this.auth._notifyListenersIfCurrent(this)}async delete(){var e;return h(this.auth.app)?Promise.reject(Zi(this.auth)):(e=await this.getIdToken(),await Ns(this,(async(e,t)=>fs(e,"POST","/v1/accounts:delete",t))(this.auth,{idToken:e})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut())}toJSON(){return{uid:this.uid,email:this.email||void 0,emailVerified:this.emailVerified,displayName:this.displayName||void 0,isAnonymous:this.isAnonymous,photoURL:this.photoURL||void 0,phoneNumber:this.phoneNumber||void 0,tenantId:this.tenantId||void 0,providerData:this.providerData.map(e=>({...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 r=t.displayName??void 0,n=t.email??void 0,i=t.phoneNumber??void 0,s=t.photoURL??void 0,a=t.tenantId??void 0,o=t._redirectEventId??void 0,l=t.createdAt??void 0,h=t.lastLoginAt??void 0,{uid:c,emailVerified:u,isAnonymous:d,providerData:p,stsTokenManager:f}=t,f=(m(c&&f,e,"internal-error"),Os.fromJSON(this.name,f)),c=(m("string"==typeof c,e,"internal-error"),Ms(r,e.name),Ms(n,e.name),m("boolean"==typeof u,e,"internal-error"),m("boolean"==typeof d,e,"internal-error"),Ms(i,e.name),Ms(s,e.name),Ms(a,e.name),Ms(o,e.name),Ms(l,e.name),Ms(h,e.name),new Ls({uid:c,auth:e,email:n,emailVerified:u,displayName:r,isAnonymous:d,photoURL:s,phoneNumber:i,tenantId:a,stsTokenManager:f,createdAt:l,lastLoginAt:h}));return p&&Array.isArray(p)&&(c.providerData=p.map(e=>({...e}))),o&&(c._redirectEventId=o),c}static async _fromIdTokenResponse(e,t,r=!1){var n=new Os,n=(n.updateFromServerResponse(t),new Ls({uid:t.localId,auth:e,stsTokenManager:n,isAnonymous:r}));return await Ds(n),n}static async _fromGetAccountInfoResponse(e,t,r){var n=t.users[0],i=(m(void 0!==n.localId,"internal-error"),void 0!==n.providerUserInfo?xs(n.providerUserInfo):[]),s=!(n.email&&n.passwordHash||i?.length),a=new Os,a=(a.updateFromIdToken(r),new Ls({uid:n.localId,auth:e,stsTokenManager:a,isAnonymous:s})),s={uid:n.localId,displayName:n.displayName||null,photoURL:n.photoUrl||null,email:n.email||null,emailVerified:n.emailVerified||!1,phoneNumber:n.phoneNumber||null,tenantId:n.tenantId||null,providerData:i,metadata:new Ps(n.createdAt,n.lastLoginAt),isAnonymous:!(n.email&&n.passwordHash||i?.length)};return Object.assign(a,s),a}}let Fs=new Map;function Us(e){ns(e instanceof Function,"Expected a class definition");var t=Fs.get(e);return t?ns(t instanceof e,"Instance stored in cache mismatched with class"):(t=new e,Fs.set(e,t)),t}class Vs{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,t){this.storage[e]=t}async _get(e){var t=this.storage[e];return void 0===t?null:t}async _remove(e){delete this.storage[e]}_addListener(e,t){}_removeListener(e,t){}}Vs.type="NONE";let qs=Vs;function Bs(e,t,r){return`firebase:${e}:${t}:`+r}class js{constructor(e,t,r){this.persistence=e,this.auth=t,this.userKey=r;var{config:n,name:i}=this.auth;this.fullUserKey=Bs(this.userKey,n.apiKey,i),this.fullPersistenceKey=Bs("persistence",n.apiKey,i),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(){var e,t=await this.persistence._get(this.fullUserKey);return t?"string"==typeof t?(e=await Es(this.auth,{idToken:t}).catch(()=>{}))?Ls._fromGetAccountInfoResponse(this.auth,e,t):null:Ls._fromJSON(this.auth,t):null}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(e){var t;if(this.persistence!==e)return t=await this.getCurrentUser(),await this.removeCurrentUser(),this.persistence=e,t?this.setCurrentUser(t):void 0}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(t,e,r="authUser"){if(!e.length)return new js(Us(qs),t,r);var n,i=(await Promise.all(e.map(async e=>{if(await e._isAvailable())return e}))).filter(e=>e);let s=i[0]||Us(qs),a=Bs(r,t.config.apiKey,t.name),o=null;for(n of e)try{var l=await n._get(a);if(l){let e;if("string"==typeof l){var h=await Es(t,{idToken:l}).catch(()=>{});if(!h)break;e=await Ls._fromGetAccountInfoResponse(t,h,l)}else e=Ls._fromJSON(t,l);n!==s&&(o=e),s=n;break}}catch{}i=i.filter(e=>e._shouldAllowMigration);return s._shouldAllowMigration&&i.length&&(s=i[0],o&&await s._set(a,o.toJSON()),await Promise.all(e.map(async e=>{if(e!==s)try{await e._remove(a)}catch{}}))),new js(s,t,r)}}function zs(e){var t=e.toLowerCase();return t.includes("opera/")||t.includes("opr/")||t.includes("opios/")?"Opera":Gs(t)?"IEMobile":t.includes("msie")||t.includes("trident/")?"IE":t.includes("edge/")?"Edge":Ks(t)?"Firefox":t.includes("silk/")?"Silk":Qs(t)?"Blackberry":Ys(t)?"Webos":Ws(t)?"Safari":!t.includes("chrome/")&&!Hs(t)||t.includes("edge/")?$s(t)?"Android":2===(t=e.match(/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/))?.length?t[1]:"Other":"Chrome"}function Ks(e=te()){return/firefox\//i.test(e)}function Ws(e=te()){var t=e.toLowerCase();return t.includes("safari/")&&!t.includes("chrome/")&&!t.includes("crios/")&&!t.includes("android")}function Hs(e=te()){return/crios\//i.test(e)}function Gs(e=te()){return/iemobile/i.test(e)}function $s(e=te()){return/android/i.test(e)}function Qs(e=te()){return/blackberry/i.test(e)}function Ys(e=te()){return/webos/i.test(e)}function Js(e=te()){return/iphone|ipad|ipod/i.test(e)||/macintosh/i.test(e)&&/mobile/i.test(e)}function Xs(e=te()){return Js(e)||$s(e)||Ys(e)||Qs(e)||/windows phone/i.test(e)||Gs(e)}function Zs(e,t=[]){let r;switch(e){case"Browser":r=zs(te());break;case"Worker":r=zs(te())+"-"+e;break;default:r=e}var n=t.length?t.join(","):"FirebaseCore-web";return`${r}/JsCore/${Ft}/`+n}class ea{constructor(e){this.auth=e,this.queue=[]}pushCallback(n,e){var t=r=>new Promise((e,t)=>{try{e(n(r))}catch(e){t(e)}});t.onAbort=e,this.queue.push(t);let r=this.queue.length-1;return()=>{this.queue[r]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser!==e){var t=[];try{for(var r of this.queue)await r(e),r.onAbort&&t.push(r.onAbort)}catch(e){t.reverse();for(var n of t)try{n()}catch(e){}throw this.auth._errorFactory.create("login-blocked",{originalMessage:e?.message})}}}}class ta{constructor(e){var t=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=t.minPasswordLength??6,t.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=t.maxPasswordLength),void 0!==t.containsLowercaseCharacter&&(this.customStrengthOptions.containsLowercaseLetter=t.containsLowercaseCharacter),void 0!==t.containsUppercaseCharacter&&(this.customStrengthOptions.containsUppercaseLetter=t.containsUppercaseCharacter),void 0!==t.containsNumericCharacter&&(this.customStrengthOptions.containsNumericCharacter=t.containsNumericCharacter),void 0!==t.containsNonAlphanumericCharacter&&(this.customStrengthOptions.containsNonAlphanumericCharacter=t.containsNonAlphanumericCharacter),this.enforcementState=e.enforcementState,"ENFORCEMENT_STATE_UNSPECIFIED"===this.enforcementState&&(this.enforcementState="OFF"),this.allowedNonAlphanumericCharacters=e.allowedNonAlphanumericCharacters?.join("")??"",this.forceUpgradeOnSignin=e.forceUpgradeOnSignin??!1,this.schemaVersion=e.schemaVersion}validatePassword(e){var t={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,t),this.validatePasswordCharacterOptions(e,t),t.isValid&&(t.isValid=t.meetsMinPasswordLength??!0),t.isValid&&(t.isValid=t.meetsMaxPasswordLength??!0),t.isValid&&(t.isValid=t.containsLowercaseLetter??!0),t.isValid&&(t.isValid=t.containsUppercaseLetter??!0),t.isValid&&(t.isValid=t.containsNumericCharacter??!0),t.isValid&&(t.isValid=t.containsNonAlphanumericCharacter??!0),t}validatePasswordLengthOptions(e,t){var r=this.customStrengthOptions.minPasswordLength,n=this.customStrengthOptions.maxPasswordLength;r&&(t.meetsMinPasswordLength=e.length>=r),n&&(t.meetsMaxPasswordLength=e.length<=n)}validatePasswordCharacterOptions(e,t){var r;this.updatePasswordCharacterOptionsStatuses(t,!1,!1,!1,!1);for(let n=0;n<e.length;n++)r=e.charAt(n),this.updatePasswordCharacterOptionsStatuses(t,"a"<=r&&r<="z","A"<=r&&r<="Z","0"<=r&&r<="9",this.allowedNonAlphanumericCharacters.includes(r))}updatePasswordCharacterOptionsStatuses(e,t,r,n,i){this.customStrengthOptions.containsLowercaseLetter&&!e.containsLowercaseLetter&&(e.containsLowercaseLetter=t),this.customStrengthOptions.containsUppercaseLetter&&!e.containsUppercaseLetter&&(e.containsUppercaseLetter=r),this.customStrengthOptions.containsNumericCharacter&&!e.containsNumericCharacter&&(e.containsNumericCharacter=n),this.customStrengthOptions.containsNonAlphanumericCharacter&&!e.containsNonAlphanumericCharacter&&(e.containsNonAlphanumericCharacter=i)}}class ra{constructor(e,t,r,n){this.app=e,this.heartbeatServiceProvider=t,this.appCheckServiceProvider=r,this.config=n,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new ia(this),this.idTokenSubscription=new ia(this),this.beforeStateQueue=new ea(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=Gi,this._agentRecaptchaConfig=null,this._tenantRecaptchaConfigs={},this._projectPasswordPolicy=null,this._tenantPasswordPolicies={},this._resolvePersistenceManagerAvailable=void 0,this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=n.sdkClientVersion,this._persistenceManagerAvailable=new Promise(e=>this._resolvePersistenceManagerAvailable=e)}_initializeWithPersistence(e,t){return t&&(this._popupRedirectResolver=Us(t)),this._initializationPromise=this.queue(async()=>{if(!this._deleted&&(this.persistenceManager=await js.create(this,e),this._resolvePersistenceManagerAvailable?.(),!this._deleted)){if(this._popupRedirectResolver?._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch(e){}await this.initializeCurrentUser(t),this.lastNotifiedUid=this.currentUser?.uid||null,this._deleted||(this._isInitialized=!0)}}),this._initializationPromise}async _onStorageEvent(){var e;!this._deleted&&(e=await this.assertedPersistence.getCurrentUser(),this.currentUser||e)&&(this.currentUser&&e&&this.currentUser.uid===e.uid?(this._currentUser._assign(e),await this.currentUser.getIdToken()):await this._updateCurrentUser(e,!0))}async initializeCurrentUserFromIdToken(e){try{var t=await Es(this,{idToken:e}),r=await Ls._fromGetAccountInfoResponse(this,t,e);await this.directlySetCurrentUser(r)}catch(e){console.warn("FirebaseServerApp could not login user with provided authIdToken: ",e),await this.directlySetCurrentUser(null)}}async initializeCurrentUser(e){if(h(this.app)){let t=this.app.settings.authIdToken;return t?new Promise(e=>{setTimeout(()=>this.initializeCurrentUserFromIdToken(t).then(e,e))}):this.directlySetCurrentUser(null)}var t,r,n,i=await this.assertedPersistence.getCurrentUser();let s=i,a=!1;if(e&&this.config.authDomain&&(await this.getOrInitRedirectPersistenceManager(),t=this.redirectUser?._redirectEventId,r=s?._redirectEventId,n=await this.tryRedirectSignIn(e),t&&t!==r||!n?.user||(s=n.user,a=!0)),!s)return this.directlySetCurrentUser(null);if(s._redirectEventId)return m(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===s._redirectEventId?this.directlySetCurrentUser(s):this.reloadAndSetCurrentUserOrClear(s);if(a)try{await this.beforeStateQueue.runMiddleware(s)}catch(e){s=i,this._popupRedirectResolver._overrideRedirectResult(this,()=>Promise.reject(e))}return s?this.reloadAndSetCurrentUserOrClear(s):this.directlySetCurrentUser(null)}async tryRedirectSignIn(e){let t=null;try{t=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch(e){await this._setRedirectUser(null)}return t}async reloadAndSetCurrentUserOrClear(e){try{await Ds(e)}catch(e){if("auth/network-request-failed"!==e?.code)return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){var e;this.languageCode="undefined"!=typeof navigator&&((e=navigator).languages&&e.languages[0]||e.language)||null}async _delete(){this._deleted=!0}async updateCurrentUser(e){var t;return h(this.app)?Promise.reject(Zi(this)):((t=e?w(e):null)&&m(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&&m(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 h(this.app)?Promise.reject(Zi(this)):(await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0))}setPersistence(e){return h(this.app)?Promise.reject(Zi(this)):this.queue(async()=>{await this.assertedPersistence.setPersistence(Us(e))})}_getRecaptchaConfig(){return null==this.tenantId?this._agentRecaptchaConfig:this._tenantRecaptchaConfigs[this.tenantId]}async validatePassword(e){this._getPasswordPolicyInternal()||await this._updatePasswordPolicy();var 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(){var e,t=await fs(e=this,"GET","/v2/passwordPolicy",ps(e,{})),t=new ta(t);null===this.tenantId?this._projectPasswordPolicy=t:this._tenantPasswordPolicies[this.tenantId]=t}_getPersistenceType(){return this.assertedPersistence.persistence.type}_getPersistence(){return this.assertedPersistence.persistence}_updateErrorMap(e){this._errorFactory=new ge("auth","Firebase",e())}onAuthStateChanged(e,t,r){return this.registerStateListener(this.authStateSubscription,e,t,r)}beforeAuthStateChanged(e,t){return this.beforeStateQueue.pushCallback(e,t)}onIdTokenChanged(e,t,r){return this.registerStateListener(this.idTokenSubscription,e,t,r)}authStateReady(){return new Promise((t,r)=>{if(this.currentUser)t();else{let e=this.onAuthStateChanged(()=>{e(),t()},r)}})}async revokeAccessToken(e){var t;this.currentUser&&(t={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:e,idToken:await this.currentUser.getIdToken()},null!=this.tenantId&&(t.tenantId=this.tenantId),await fs(e=this,"POST","/v2/accounts:revokeToken",ps(e,t)))}toJSON(){return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:this._currentUser?.toJSON()}}async _setRedirectUser(e,t){var r=await this.getOrInitRedirectPersistenceManager(t);return null===e?r.removeCurrentUser():r.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){var t;return this.redirectPersistenceManager||(m(t=e&&Us(e)||this._popupRedirectResolver,this,"argument-error"),this.redirectPersistenceManager=await js.create(this,[Us(t._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()),this.redirectPersistenceManager}async _redirectUserForId(e){return this._isInitialized&&await this.queue(async()=>{}),this._currentUser?._redirectEventId===e?this._currentUser:this.redirectUser?._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;this._isInitialized&&(this.idTokenSubscription.next(this.currentUser),e=this.currentUser?.uid??null,this.lastNotifiedUid!==e)&&(this.lastNotifiedUid=e,this.authStateSubscription.next(this.currentUser))}registerStateListener(t,r,n,i){if(this._deleted)return()=>{};let e="function"==typeof r?r:r.next.bind(r),s=!1;var a=this._isInitialized?Promise.resolve():this._initializationPromise;if(m(a,this,"internal-error"),a.then(()=>{s||e(this.currentUser)}),"function"==typeof r){let e=t.addObserver(r,n,i);return()=>{s=!0,e()}}{let e=t.addObserver(r);return()=>{s=!0,e()}}}async directlySetCurrentUser(e){this.currentUser&&this.currentUser!==e&&this._currentUser._stopProactiveRefresh(),e&&this.isProactiveRefreshEnabled&&e._startProactiveRefresh(),(this.currentUser=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 m(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){e&&!this.frameworks.includes(e)&&(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=Zs(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){var e={"X-Client-Version":this.clientVersion},t=(this.app.options.appId&&(e["X-Firebase-gmpid"]=this.app.options.appId),await this.heartbeatServiceProvider.getImmediate({optional:!0})?.getHeartbeatsHeader()),t=(t&&(e["X-Firebase-Client"]=t),await this._getAppCheckToken());return t&&(e["X-Firebase-AppCheck"]=t),e}async _getAppCheckToken(){var e,t,r;return h(this.app)&&this.app.settings.appCheckToken?this.app.settings.appCheckToken:((e=await this.appCheckServiceProvider.getImmediate({optional:!0})?.getToken())?.error&&(t="Error while retrieving App Check token: "+e.error,r=[],$i.logLevel<=p.WARN)&&$i.warn(`Auth (${Ft}): `+t,...r),e?.token)}}function na(e){return w(e)}class ia{constructor(e){this.auth=e,this.observer=null,this.addObserver=Re(e=>this.observer=e)}get next(){return m(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}let sa={async loadJS(){throw new Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};function aa(e){return sa.loadJS(e)}function oa(e){return"__"+e+Math.floor(1e6*Math.random())}class la{constructor(e){this.auth=e,this.counter=1e12,this._widgets=new Map}render(e,t){var r=this.counter;return this._widgets.set(r,new ua(e,this.auth.name,t||{})),this.counter++,r}reset(e){var t=e||1e12;this._widgets.get(t)?.delete(),this._widgets.delete(t)}getResponse(e){return this._widgets.get(e||1e12)?.getResponse()||""}async execute(e){return this._widgets.get(e||1e12)?.execute(),""}}class ha{constructor(){this.enterprise=new ca}ready(e){e()}execute(e,t){return Promise.resolve("token")}render(e,t){return""}}class ca{ready(e){e()}execute(e,t){return Promise.resolve("token")}render(e,t){return""}}class ua{constructor(e,t,r){this.params=r,this.timerId=null,this.deleted=!1,this.responseToken=null,this.clickHandler=()=>{this.execute()};var n="string"==typeof e?document.getElementById(e):e;m(n,"argument-error",{appName:t}),this.container=n,this.isVisible="invisible"!==this.params.size,this.isVisible?this.execute():this.container.addEventListener("click",this.clickHandler)}getResponse(){return this.checkIfDeleted(),this.responseToken}delete(){this.checkIfDeleted(),this.deleted=!0,this.timerId&&(clearTimeout(this.timerId),this.timerId=null),this.container.removeEventListener("click",this.clickHandler)}execute(){this.checkIfDeleted(),this.timerId||(this.timerId=window.setTimeout(()=>{this.responseToken=(e=>{var t=[],r="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let n=0;n<e;n++)t.push(r.charAt(Math.floor(Math.random()*r.length)));return t.join("")})(50);let{callback:e,"expired-callback":t}=this.params;if(e)try{e(this.responseToken)}catch(e){}this.timerId=window.setTimeout(()=>{if(this.timerId=null,this.responseToken=null,t)try{t()}catch(e){}this.isVisible&&this.execute()},6e4)},500))}checkIfDeleted(){if(this.deleted)throw new Error("reCAPTCHA mock was already deleted!")}}let da="NO_RECAPTCHA";class pa{constructor(e){this.type="recaptcha-enterprise",this.auth=na(e)}async verify(i="verify",e=!1){function s(e,t,r){let n=window.grecaptcha;bs(n)?n.enterprise.ready(()=>{n.enterprise.execute(e,{action:i}).then(e=>{t(e)}).catch(()=>{t(da)})}):r(Error("No reCAPTCHA enterprise script loaded."))}return this.auth.settings.appVerificationDisabledForTesting?(new ha).execute("siteKey",{action:"verify"}):new Promise((r,n)=>{(async i=>{if(!e){if(null==i.tenantId&&null!=i._agentRecaptchaConfig)return i._agentRecaptchaConfig.siteKey;if(null!=i.tenantId&&void 0!==i._tenantRecaptchaConfigs[i.tenantId])return i._tenantRecaptchaConfigs[i.tenantId].siteKey}return new Promise(async(r,n)=>{Ts(i,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then(e=>{var t;if(void 0!==e.recaptchaKey)return t=new Is(e),null==i.tenantId?i._agentRecaptchaConfig=t:i._tenantRecaptchaConfigs[i.tenantId]=t,r(t.siteKey);n(new Error("recaptcha Enterprise site key undefined"))}).catch(e=>{n(e)})})})(this.auth).then(t=>{if(!e&&bs(window.grecaptcha))s(t,r,n);else if("undefined"==typeof window)n(new Error("RecaptchaVerifier is only supported in browser"));else{let e=sa.recaptchaEnterpriseScript;0!==e.length&&(e+=t),aa(e).then(()=>{s(t,r,n)}).catch(e=>{n(e)})}}).catch(e=>{n(e)})})}}async function fa(e,t,r,n=!1,i=!1){var s=new pa(e);let a;if(i)a=da;else try{a=await s.verify(r)}catch(e){a=await s.verify(r,!0)}var o,l,s={...t};return"mfaSmsEnrollment"===r||"mfaSmsSignIn"===r?"phoneEnrollmentInfo"in s?(l=s.phoneEnrollmentInfo.phoneNumber,o=s.phoneEnrollmentInfo.recaptchaToken,Object.assign(s,{phoneEnrollmentInfo:{phoneNumber:l,recaptchaToken:o,captchaResponse:a,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})):"phoneSignInInfo"in s&&(l=s.phoneSignInInfo.recaptchaToken,Object.assign(s,{phoneSignInInfo:{recaptchaToken:l,captchaResponse:a,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})):(n?Object.assign(s,{captchaResp:a}):Object.assign(s,{captchaResponse:a}),Object.assign(s,{clientType:"CLIENT_TYPE_WEB"}),Object.assign(s,{recaptchaVersion:"RECAPTCHA_ENTERPRISE"})),s}async function ga(r,n,i,s,e){var t;return"EMAIL_PASSWORD_PROVIDER"===e?r._getRecaptchaConfig()?.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")?(t=await fa(r,n,i,"getOobCode"===i),s(r,t)):s(r,n).catch(async e=>{var t;return"auth/missing-recaptcha-token"===e.code?(console.log(i+" is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow."),t=await fa(r,n,i,"getOobCode"===i),s(r,t)):Promise.reject(e)}):"PHONE_PROVIDER"===e?r._getRecaptchaConfig()?.isProviderEnabled("PHONE_PROVIDER")?(t=await fa(r,n,i),s(r,t).catch(async e=>{var t;if("AUDIT"===r._getRecaptchaConfig()?.getProviderEnforcementState("PHONE_PROVIDER")&&("auth/missing-recaptcha-token"===e.code||"auth/invalid-app-credential"===e.code))return console.log(`Failed to verify with reCAPTCHA Enterprise. Automatically triggering the reCAPTCHA v2 flow to complete the ${i} flow.`),t=await fa(r,n,i,!1,!0),s(r,t);return Promise.reject(e)})):(t=await fa(r,n,i,!1,!0),s(r,t)):Promise.reject(e+" provider is not supported.")}function ma(e,t,r){var n=na(e),i=(m(/^https?:\/\//.test(t),n,"invalid-emulator-scheme"),!!r?.disableWarnings),s=va(t),{host:a,port:o}=(e=>{var t,r=va(e);return(r=/(\/\/)?([^?#/]+)/.exec(e.substr(r.length)))?(r=r[2].split("@").pop()||"",(t=/^(\[[^\]]+\])(:|$)/.exec(r))?{host:t=t[1],port:_a(r.substr(t.length+1))}:([t,r]=r.split(":"),{host:t,port:_a(r)})):{host:"",port:null}})(t),l=null===o?"":":"+o,h={url:s+`//${a}${l}/`},o=Object.freeze({host:a,port:o,protocol:s.replace(":",""),options:Object.freeze({disableWarnings:i})});function c(){var 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)}n._canInitEmulator?(n.config.emulator=h,n.emulatorConfig=o,n.settings.appVerificationDisabledForTesting=!0,je(a)?ze(s+"//"+a+l):i||("undefined"!=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."),"undefined"!=typeof window&&"undefined"!=typeof document&&("loading"===document.readyState?window.addEventListener("DOMContentLoaded",c):c()))):(m(n.config.emulator&&n.emulatorConfig,n,"emulator-config-failed"),m(Ee(h,n.config.emulator)&&Ee(o,n.emulatorConfig),n,"emulator-config-failed"))}function va(e){var t=e.indexOf(":");return t<0?"":e.substr(0,t+1)}function _a(e){var t;return!e||(t=Number(e),isNaN(t))?null:t}class ya{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return rs("not implemented")}_getIdTokenResponse(e){return rs("not implemented")}_linkToIdToken(e,t){return rs("not implemented")}_getReauthenticationResolver(e){return rs("not implemented")}}async function wa(e,t){return fs(e,"POST","/v1/accounts:resetPassword",ps(e,t))}async function ba(e,t){return fs(e,"POST","/v1/accounts:signUp",t)}async function Ia(e,t){return ms(e,"POST","/v1/accounts:signInWithPassword",ps(e,t))}async function Ta(e,t){return fs(e,"POST","/v1/accounts:sendOobCode",ps(e,t))}async function Ea(e,t){return Ta(e,t)}async function Ca(e,t){return Ta(e,t)}class Sa extends ya{constructor(e,t,r,n=null){super("password",r),this._email=e,this._password=t,this._tenantId=n}static _fromEmailAndPassword(e,t){return new Sa(e,t,"password")}static _fromEmailAndCode(e,t,r=null){return new Sa(e,t,"emailLink",r)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){var t="string"==typeof e?JSON.parse(e):e;if(t?.email&&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 ga(e,{returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signInWithPassword",Ia,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return(async(e,t)=>ms(e,"POST","/v1/accounts:signInWithEmailLink",ps(e,t)))(e,{email:this._email,oobCode:this._password});default:Yi(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":return ga(e,{idToken:t,returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",ba,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return(async(e,t)=>ms(e,"POST","/v1/accounts:signInWithEmailLink",ps(e,t)))(e,{idToken:t,email:this._email,oobCode:this._password});default:Yi(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function ka(e,t){return ms(e,"POST","/v1/accounts:signInWithIdp",ps(e,t))}class Aa extends ya{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){var t=new Aa(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&&(t.pendingToken=e.pendingToken)):e.oauthToken&&e.oauthTokenSecret?(t.accessToken=e.oauthToken,t.secret=e.oauthTokenSecret):Yi("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){var t;let{providerId:r,signInMethod:n,...i}="string"==typeof e?JSON.parse(e):e;return r&&n?((t=new Aa(r,n)).idToken=i.idToken||void 0,t.accessToken=i.accessToken||void 0,t.secret=i.secret,t.nonce=i.nonce,t.pendingToken=i.pendingToken||null,t):null}_getIdTokenResponse(e){return ka(e,this.buildRequest())}_linkToIdToken(e,t){var r=this.buildRequest();return r.idToken=t,ka(e,r)}_getReauthenticationResolver(e){var t=this.buildRequest();return t.autoCreate=!1,ka(e,t)}buildRequest(){var e,t={requestUri:"http://localhost",returnSecureToken:!0};return this.pendingToken?t.pendingToken=this.pendingToken:(e={},this.idToken&&(e.id_token=this.idToken),this.accessToken&&(e.access_token=this.accessToken),this.secret&&(e.oauth_token_secret=this.secret),e.providerId=this.providerId,this.nonce&&!this.pendingToken&&(e.nonce=this.nonce),t.postBody=Se(e)),t}}async function Na(e,t){return fs(e,"POST","/v1/accounts:sendVerificationCode",ps(e,t))}let Ra={USER_NOT_FOUND:"user-not-found"};class Pa extends ya{constructor(e){super("phone","phone"),this.params=e}static _fromVerification(e,t){return new Pa({verificationId:e,verificationCode:t})}static _fromTokenResponse(e,t){return new Pa({phoneNumber:e,temporaryProof:t})}_getIdTokenResponse(e){return(async(e,t)=>ms(e,"POST","/v1/accounts:signInWithPhoneNumber",ps(e,t)))(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return(async(e,t)=>{var r=await ms(e,"POST","/v1/accounts:signInWithPhoneNumber",ps(e,t));if(r.temporaryProof)throw ys(e,"account-exists-with-different-credential",r);return r})(e,{idToken:t,...this._makeVerificationRequest()})}_getReauthenticationResolver(e){return(async(e,t)=>ms(e,"POST","/v1/accounts:signInWithPhoneNumber",ps(e,{...t,operation:"REAUTH"}),Ra))(e,this._makeVerificationRequest())}_makeVerificationRequest(){var{temporaryProof:e,phoneNumber:t,verificationId:r,verificationCode:n}=this.params;return e&&t?{temporaryProof:e,phoneNumber:t}:{sessionInfo:r,code:n}}toJSON(){var e={providerId:this.providerId};return this.params.phoneNumber&&(e.phoneNumber=this.params.phoneNumber),this.params.temporaryProof&&(e.temporaryProof=this.params.temporaryProof),this.params.verificationCode&&(e.verificationCode=this.params.verificationCode),this.params.verificationId&&(e.verificationId=this.params.verificationId),e}static fromJSON(e){var{verificationId:t,verificationCode:r,phoneNumber:n,temporaryProof:i}=e="string"==typeof e?JSON.parse(e):e;return r||t||n||i?new Pa({verificationId:t,verificationCode:r,phoneNumber:n,temporaryProof:i}):null}}class Da{constructor(e){var t=ke(Ae(e)),r=t.apiKey??null,n=t.oobCode??null,i=(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}})(t.mode??null);m(r&&n&&i,"argument-error"),this.apiKey=r,this.operation=i,this.code=n,this.continueUrl=t.continueUrl??null,this.languageCode=t.lang??null,this.tenantId=t.tenantId??null}static parseLink(e){t=ke(Ae(e=e)).link,r=t?ke(Ae(t)).deep_link_id:null;var t,r,n=((n=ke(Ae(e)).deep_link_id)?ke(Ae(n)).link:null)||n||r||t||e;try{return new Da(n)}catch{return null}}}class xa{constructor(){this.providerId=xa.PROVIDER_ID}static credential(e,t){return Sa._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){var r=Da.parseLink(t);return m(r,"argument-error"),Sa._fromEmailAndCode(e,r.code,r.tenantId)}}xa.PROVIDER_ID="password",xa.EMAIL_PASSWORD_SIGN_IN_METHOD="password",xa.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class Oa{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 Ma extends Oa{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class La extends Ma{static credentialFromJSON(e){var t="string"==typeof e?JSON.parse(e):e;return m("providerId"in t&&"signInMethod"in t,"argument-error"),Aa._fromParams(t)}credential(e){return this._credential({...e,nonce:e.rawNonce})}_credential(e){return m(e.idToken||e.accessToken,"argument-error"),Aa._fromParams({...e,providerId:this.providerId,signInMethod:this.providerId})}static credentialFromResult(e){return La.oauthCredentialFromTaggedObject(e)}static credentialFromError(e){return La.oauthCredentialFromTaggedObject(e.customData||{})}static oauthCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthIdToken:t,oauthAccessToken:r,oauthTokenSecret:n,pendingToken:i,nonce:s,providerId:a}=e;if(!(r||n||t||i))return null;if(!a)return null;try{return new La(a)._credential({idToken:t,accessToken:r,nonce:s,pendingToken:i})}catch(e){return null}}}class Fa extends Ma{constructor(){super("facebook.com")}static credential(e){return Aa._fromParams({providerId:Fa.PROVIDER_ID,signInMethod:Fa.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return Fa.credentialFromTaggedObject(e)}static credentialFromError(e){return Fa.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return Fa.credential(e.oauthAccessToken)}catch{return null}}}Fa.FACEBOOK_SIGN_IN_METHOD="facebook.com",Fa.PROVIDER_ID="facebook.com";class Ua extends Ma{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return Aa._fromParams({providerId:Ua.PROVIDER_ID,signInMethod:Ua.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return Ua.credentialFromTaggedObject(e)}static credentialFromError(e){return Ua.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthIdToken:t,oauthAccessToken:r}=e;if(!t&&!r)return null;try{return Ua.credential(t,r)}catch{return null}}}Ua.GOOGLE_SIGN_IN_METHOD="google.com",Ua.PROVIDER_ID="google.com";class Va extends Ma{constructor(){super("github.com")}static credential(e){return Aa._fromParams({providerId:Va.PROVIDER_ID,signInMethod:Va.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return Va.credentialFromTaggedObject(e)}static credentialFromError(e){return Va.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return Va.credential(e.oauthAccessToken)}catch{return null}}}Va.GITHUB_SIGN_IN_METHOD="github.com",Va.PROVIDER_ID="github.com";class qa extends ya{constructor(e,t){super(e,e),this.pendingToken=t}_getIdTokenResponse(e){return ka(e,this.buildRequest())}_linkToIdToken(e,t){var r=this.buildRequest();return r.idToken=t,ka(e,r)}_getReauthenticationResolver(e){var t=this.buildRequest();return t.autoCreate=!1,ka(e,t)}toJSON(){return{signInMethod:this.signInMethod,providerId:this.providerId,pendingToken:this.pendingToken}}static fromJSON(e){var{providerId:t,signInMethod:r,pendingToken:n}="string"==typeof e?JSON.parse(e):e;return t&&r&&n&&t===r?new qa(t,n):null}static _create(e,t){return new qa(e,t)}buildRequest(){return{requestUri:"http://localhost",returnSecureToken:!0,pendingToken:this.pendingToken}}}class Ba extends Oa{constructor(e){m(e.startsWith("saml."),"argument-error"),super(e)}static credentialFromResult(e){return Ba.samlCredentialFromTaggedObject(e)}static credentialFromError(e){return Ba.samlCredentialFromTaggedObject(e.customData||{})}static credentialFromJSON(e){var t=qa.fromJSON(e);return m(t,"argument-error"),t}static samlCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{pendingToken:t,providerId:r}=e;if(!t||!r)return null;try{return qa._create(r,t)}catch(e){return null}}}class ja extends Ma{constructor(){super("twitter.com")}static credential(e,t){return Aa._fromParams({providerId:ja.PROVIDER_ID,signInMethod:ja.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return ja.credentialFromTaggedObject(e)}static credentialFromError(e){return ja.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthAccessToken:t,oauthTokenSecret:r}=e;if(!t||!r)return null;try{return ja.credential(t,r)}catch{return null}}}async function za(e,t){return ms(e,"POST","/v1/accounts:signUp",ps(e,t))}ja.TWITTER_SIGN_IN_METHOD="twitter.com",ja.PROVIDER_ID="twitter.com";class Ka{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,r,n=!1){var i=await Ls._fromIdTokenResponse(e,r,n),s=Wa(r);return new Ka({user:i,providerId:s,_tokenResponse:r,operationType:t})}static async _forOperation(e,t,r){await e._updateTokensIfNecessary(r,!0);var n=Wa(r);return new Ka({user:e,providerId:n,_tokenResponse:r,operationType:t})}}function Wa(e){return e.providerId||("phoneNumber"in e?"phone":null)}class Ha extends fe{constructor(e,t,r,n){super(t.code,t.message),this.operationType=r,this.user=n,Object.setPrototypeOf(this,Ha.prototype),this.customData={appName:e.name,tenantId:e.tenantId??void 0,_serverResponse:t.customData._serverResponse,operationType:r}}static _fromErrorAndOperation(e,t,r,n){return new Ha(e,t,r,n)}}function Ga(t,r,e,n){return("reauthenticate"===r?e._getReauthenticationResolver(t):e._getIdTokenResponse(t)).catch(e=>{if("auth/multi-factor-auth-required"===e.code)throw Ha._fromErrorAndOperation(t,e,r,n);throw e})}function $a(e){return new Set(e.map(({providerId:e})=>e).filter(e=>!!e))}async function Qa(e,t){var r=w(e),n=(await Ja(!0,r,t),e=r.auth,t={idToken:await r.getIdToken(),deleteProvider:[t]},await fs(e,"POST","/v1/accounts:update",t)).providerUserInfo;let i=$a(n||[]);return r.providerData=r.providerData.filter(e=>i.has(e.providerId)),i.has("phone")||(r.phoneNumber=null),await r.auth._persistUserIfCurrent(r),r}async function Ya(e,t,r=!1){var n=await Ns(e,t._linkToIdToken(e.auth,await e.getIdToken()),r);return Ka._forOperation(e,"link",n)}async function Ja(e,t,r){await Ds(t);var n=!1===e?"provider-already-linked":"no-such-provider";m($a(t.providerData).has(r)===e,t.auth,n)}async function Xa(e,t,r=!1){var n=e.auth;if(h(n.app))return Promise.reject(Zi(n));var i="reauthenticate";try{var s=await Ns(e,Ga(n,i,t,e),r),a=(m(s.idToken,n,"internal-error"),ks(s.idToken)),o=(m(a,n,"internal-error"),a).sub;return m(e.uid===o,n,"user-mismatch"),Ka._forOperation(e,i,s)}catch(e){throw"auth/user-not-found"===e?.code&&Yi(n,"user-mismatch"),e}}async function Za(e,t,r=!1){var n;return h(e.app)?Promise.reject(Zi(e)):(n=await Ga(e,"signIn",t),n=await Ka._fromIdTokenResponse(e,"signIn",n),r||await e._updateCurrentUser(n.user),n)}async function eo(e,t){return Za(na(e),t)}async function to(e,t){var r=w(e);return await Ja(!1,r,t.providerId),Ya(r,t)}async function ro(e,t){return Xa(w(e),t)}async function no(e,t){var r,n;return h(e.app)?Promise.reject(Zi(e)):(n=await ms(r=na(e),"POST","/v1/accounts:signInWithCustomToken",ps(r,{token:t,returnSecureToken:!0})),n=await Ka._fromIdTokenResponse(r,"signIn",n),await r._updateCurrentUser(n.user),n)}class io{constructor(e,t){this.factorId=e,this.uid=t.mfaEnrollmentId,this.enrollmentTime=new Date(t.enrolledAt).toUTCString(),this.displayName=t.displayName}static _fromServerResponse(e,t){return"phoneInfo"in t?so._fromServerResponse(e,t):"totpInfo"in t?ao._fromServerResponse(e,t):Yi(e,"internal-error")}}class so extends io{constructor(e){super("phone",e),this.phoneNumber=e.phoneInfo}static _fromServerResponse(e,t){return new so(t)}}class ao extends io{constructor(e){super("totp",e)}static _fromServerResponse(e,t){return new ao(t)}}function oo(e,t,r){m(0<r.url?.length,e,"invalid-continue-uri"),m(void 0===r.dynamicLinkDomain||0<r.dynamicLinkDomain.length,e,"invalid-dynamic-link-domain"),m(void 0===r.linkDomain||0<r.linkDomain.length,e,"invalid-hosting-link-domain"),t.continueUrl=r.url,t.dynamicLinkDomain=r.dynamicLinkDomain,t.linkDomain=r.linkDomain,t.canHandleCodeInApp=r.handleCodeInApp,r.iOS&&(m(0<r.iOS.bundleId.length,e,"missing-ios-bundle-id"),t.iOSBundleId=r.iOS.bundleId),r.android&&(m(0<r.android.packageName.length,e,"missing-android-pkg-name"),t.androidInstallApp=r.android.installApp,t.androidMinimumVersionCode=r.android.minimumVersion,t.androidPackageName=r.android.packageName)}async function lo(e){var t=na(e);t._getPasswordPolicyInternal()&&await t._updatePasswordPolicy()}async function ho(e,t){await fs(e=w(e),"POST","/v1/accounts:update",ps(e,{oobCode:t}))}async function co(e,t){var r=w(e),n=await wa(r,{oobCode:t}),i=n.requestType;switch(m(i,r,"internal-error"),i){case"EMAIL_SIGNIN":break;case"VERIFY_AND_CHANGE_EMAIL":m(n.newEmail,r,"internal-error");break;case"REVERT_SECOND_FACTOR_ADDITION":m(n.mfaInfo,r,"internal-error");default:m(n.email,r,"internal-error")}let s=null;return n.mfaInfo&&(s=io._fromServerResponse(na(r),n.mfaInfo)),{data:{email:("VERIFY_AND_CHANGE_EMAIL"===n.requestType?n.newEmail:n.email)||null,previousEmail:("VERIFY_AND_CHANGE_EMAIL"===n.requestType?n.email:n.newEmail)||null,multiFactorInfo:s},operation:i}}async function uo(e,t){var r=ss()?is():"http://localhost",r=(await fs(e=w(e),"POST","/v1/accounts:createAuthUri",ps(e,{identifier:t,continueUri:r}))).signinMethods;return r||[]}async function po(e,t){var r=w(e),n={requestType:"VERIFY_EMAIL",idToken:await e.getIdToken()},r=(t&&oo(r.auth,n,t),await Ta(r.auth,n)).email;r!==e.email&&await e.reload()}async function fo(e,t,r){var n=w(e),i={requestType:"VERIFY_AND_CHANGE_EMAIL",idToken:await e.getIdToken(),newEmail:t},n=(r&&oo(n.auth,i,r),await Ta(n.auth,i)).email;n!==e.email&&await e.reload()}async function go(e,{displayName:t,photoURL:r}){var n,i,s;void 0===t&&void 0===r||(i=await(n=w(e)).getIdToken(),i=await Ns(n,(async(e,t)=>fs(e,"POST","/v1/accounts:update",t))(n.auth,{idToken:i,displayName:t,photoUrl:r,returnSecureToken:!0})),n.displayName=i.displayName||null,n.photoURL=i.photoUrl||null,(s=n.providerData.find(({providerId:e})=>"password"===e))&&(s.displayName=n.displayName,s.photoURL=n.photoURL),await n._updateTokensIfNecessary(i))}async function mo(e,t,r){var n=e.auth,i={idToken:await e.getIdToken(),returnSecureToken:!0},n=(t&&(i.email=t),r&&(i.password=r),await Ns(e,(async(e,t)=>fs(e,"POST","/v1/accounts:update",t))(n,i)));await e._updateTokensIfNecessary(n,!0)}class vo{constructor(e,t,r={}){this.isNewUser=e,this.providerId=t,this.profile=r}}class _o extends vo{constructor(e,t,r,n){super(e,t,r),this.username=n}}class yo extends vo{constructor(e,t){super(e,"facebook.com",t)}}class wo extends _o{constructor(e,t){super(e,"github.com",t,"string"==typeof t?.login?t?.login:null)}}class bo extends vo{constructor(e,t){super(e,"google.com",t)}}class Io extends _o{constructor(e,t,r){super(e,"twitter.com",t,r)}}function To(e){var{user:t,_tokenResponse:r}=e;if(t.isAnonymous&&!r)return{providerId:null,isNewUser:!1,profile:null};var n=r;if(!n)return null;var i=n.providerId,s=n.rawUserInfo?JSON.parse(n.rawUserInfo):{},a=n.isNewUser||"identitytoolkit#SignupNewUserResponse"===n.kind;if(!i&&n?.idToken){t=ks(n.idToken)?.firebase?.sign_in_provider;if(t)return t="anonymous"!==t&&"custom"!==t?t:null,new vo(a,t)}if(!i)return null;switch(i){case"facebook.com":return new yo(a,s);case"github.com":return new wo(a,s);case"google.com":return new bo(a,s);case"twitter.com":return new Io(a,s,n.screenName||null);case"custom":case"anonymous":return new vo(a,null);default:return new vo(a,i,s)}}class Eo{constructor(e,t,r){this.type=e,this.credential=t,this.user=r}static _fromIdtoken(e,t){return new Eo("enroll",e,t)}static _fromMfaPendingCredential(e){return new Eo("signin",e)}toJSON(){return{multiFactorSession:{["enroll"===this.type?"idToken":"pendingCredential"]:this.credential}}}static fromJSON(e){if(e?.multiFactorSession){if(e.multiFactorSession?.pendingCredential)return Eo._fromMfaPendingCredential(e.multiFactorSession.pendingCredential);if(e.multiFactorSession?.idToken)return Eo._fromIdtoken(e.multiFactorSession.idToken)}return null}}class Co{constructor(e,t,r){this.session=e,this.hints=t,this.signInResolver=r}static _fromError(e,i){let s=na(e),a=i.customData._serverResponse;var t=(a.mfaInfo||[]).map(e=>io._fromServerResponse(s,e));m(a.mfaPendingCredential,s,"internal-error");let o=Eo._fromMfaPendingCredential(a.mfaPendingCredential);return new Co(o,t,async e=>{var t=await e._process(s,o),r=(delete a.mfaInfo,delete a.mfaPendingCredential,{...a,idToken:t.idToken,refreshToken:t.refreshToken});switch(i.operationType){case"signIn":var n=await Ka._fromIdTokenResponse(s,i.operationType,r);return await s._updateCurrentUser(n.user),n;case"reauthenticate":return m(i.user,s,"internal-error"),Ka._forOperation(i.user,i.operationType,r);default:Yi(s,"internal-error")}})}async resolveSignIn(e){return this.signInResolver(e)}}function So(e,t){return fs(e,"POST","/v2/accounts/mfaEnrollment:start",ps(e,t))}class ko{constructor(t){this.user=t,this.enrolledFactors=[],t._onReload(e=>{e.mfaInfo&&(this.enrolledFactors=e.mfaInfo.map(e=>io._fromServerResponse(t.auth,e)))})}static _fromUser(e){return new ko(e)}async getSession(){return Eo._fromIdtoken(await this.user.getIdToken(),this.user)}async enroll(e,t){var r=e,n=await this.getSession(),r=await Ns(this.user,r._process(this.user.auth,n,t));return await this.user._updateTokensIfNecessary(r),this.user.reload()}async unenroll(e){let t="string"==typeof e?e:e.uid;var r,n,i=await this.user.getIdToken();try{var s=await Ns(this.user,(r=this.user.auth,n={idToken:i,mfaEnrollmentId:t},fs(r,"POST","/v2/accounts/mfaEnrollment:withdraw",ps(r,n))));this.enrolledFactors=this.enrolledFactors.filter(({uid:e})=>e!==t),await this.user._updateTokensIfNecessary(s),await this.user.reload()}catch(e){throw e}}}let Ao=new WeakMap;let No="__sak";class Ro{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(No,"1"),this.storage.removeItem(No),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){var 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 Po extends Ro{constructor(){super(()=>window.localStorage,"LOCAL"),this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t),this.listeners={},this.localCache={},this.pollTimer=null,this.fallbackToPolling=Xs(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(var t of Object.keys(this.listeners)){var r=this.storage.getItem(t),n=this.localCache[t];r!==n&&e(t,n,r)}}onStorageEvent(e,r=!1){if(e.key){let t=e.key;r?this.detachListener():this.stopPolling();var n=()=>{var e=this.storage.getItem(t);!r&&this.localCache[t]===e||this.notifyListeners(t,e)},i=this.storage.getItem(t);oe()&&10===document.documentMode&&i!==e.newValue&&e.newValue!==e.oldValue?setTimeout(n,10):n()}else this.forAllChangedKeys((e,t,r)=>{this.notifyListeners(e,r)})}notifyListeners(e,t){this.localCache[e]=t;var r=this.listeners[e];if(r)for(var n of Array.from(r))n(t&&JSON.parse(t))}startPolling(){this.stopPolling(),this.pollTimer=setInterval(()=>{this.forAllChangedKeys((e,t,r)=>{this.onStorageEvent(new StorageEvent("storage",{key:e,oldValue:t,newValue:r}),!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){var t=await super._get(e);return this.localCache[e]=JSON.stringify(t),t}async _remove(e){await super._remove(e),delete this.localCache[e]}}Po.type="LOCAL";let Do=Po;class xo extends Ro{constructor(){super(()=>window.sessionStorage,"SESSION")}_addListener(e,t){}_removeListener(e,t){}}xo.type="SESSION";let Oo=xo;class Mo{constructor(e){this.eventTarget=e,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(t){var e=this.receivers.find(e=>e.isListeningto(t));return e||(e=new Mo(t),this.receivers.push(e),e)}isListeningto(e){return this.eventTarget===e}async handleEvent(e){let t=e,{eventId:r,eventType:n,data:i}=t.data;var s=this.handlersMap[n];s?.size&&(t.ports[0].postMessage({status:"ack",eventId:r,eventType:n}),s=Array.from(s).map(async e=>e(t.origin,i)),s=await Promise.all(s.map(async e=>{try{return{fulfilled:!0,value:await e}}catch(e){return{fulfilled:!1,reason:e}}})),t.ports[0].postMessage({status:"done",eventId:r,eventType:n,response:s}))}_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 Lo(e="",t=10){let r="";for(let n=0;n<t;n++)r+=Math.floor(10*Math.random());return e+r}Mo.receivers=[];class Fo{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,a=50){let o="undefined"!=typeof MessageChannel?new MessageChannel:null;if(!o)throw new Error("connection_unavailable");let l,h;return new Promise((r,n)=>{let i=Lo("",20),s=(o.port1.start(),setTimeout(()=>{n(new Error("unsupported_event"))},a));h={messageChannel:o,onMessage(e){var t=e;if(t.data.eventId===i)switch(t.data.status){case"ack":clearTimeout(s),l=setTimeout(()=>{n(new Error("timeout"))},3e3);break;case"done":clearTimeout(l),r(t.data.response);break;default:clearTimeout(s),clearTimeout(l),n(new Error("invalid_response"))}}},this.handlers.add(h),o.port1.addEventListener("message",h.onMessage),this.target.postMessage({eventType:e,eventId:i,data:t},[o.port2])}).finally(()=>{h&&this.removeMessageHandler(h)})}}function Uo(){return window}function Vo(){return void 0!==Uo().WorkerGlobalScope&&"function"==typeof Uo().importScripts}let qo="firebaseLocalStorageDb",Bo="firebaseLocalStorage",jo="fbase_key";class zo{constructor(e){this.request=e}toPromise(){return new Promise((e,t)=>{this.request.addEventListener("success",()=>{e(this.request.result)}),this.request.addEventListener("error",()=>{t(this.request.error)})})}}function Ko(e,t){return e.transaction([Bo],t?"readwrite":"readonly").objectStore(Bo)}function Wo(){let n=indexedDB.open(qo,1);return new Promise((t,r)=>{n.addEventListener("error",()=>{r(n.error)}),n.addEventListener("upgradeneeded",()=>{var e=n.result;try{e.createObjectStore(Bo,{keyPath:jo})}catch(e){r(e)}}),n.addEventListener("success",async()=>{var e=n.result;e.objectStoreNames.contains(Bo)?t(e):(e.close(),e=indexedDB.deleteDatabase(qo),await new zo(e).toPromise(),t(await Wo()))})})}async function Ho(e,t,r){var n=Ko(e,!0).put({fbase_key:t,value:r});return new zo(n).toPromise()}function Go(e,t){var r=Ko(e,!0).delete(t);return new zo(r).toPromise()}class $o{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 Wo()),this.db}async _withRetries(e){let t=0;for(;;)try{return await e(await this._openDb())}catch(e){if(3<t++)throw e;this.db&&(this.db.close(),this.db=void 0)}}async initializeServiceWorkerMessaging(){return Vo()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=Mo._getInstance(Vo()?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;this.activeServiceWorker=await(async()=>{if(!navigator?.serviceWorker)return null;try{return(await navigator.serviceWorker.ready).active}catch{return null}})(),this.activeServiceWorker&&(this.sender=new Fo(this.activeServiceWorker),e=await this.sender._send("ping",{},800))&&e[0]?.fulfilled&&e[0]?.value.includes("keyChanged")&&(this.serviceWorkerReceiverAvailable=!0)}async notifyServiceWorker(e){if(this.sender&&this.activeServiceWorker&&(navigator?.serviceWorker?.controller||null)===this.activeServiceWorker)try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch{}}async _isAvailable(){try{var e;return indexedDB?(await Ho(e=await Wo(),No,"1"),await Go(e,No),!0):!1}catch{}return!1}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites--}}async _set(t,r){return this._withPendingWrite(async()=>(await this._withRetries(e=>Ho(e,t,r)),this.localCache[t]=r,this.notifyServiceWorker(t)))}async _get(t){var e=await this._withRetries(e=>(async(e,t)=>{var r=Ko(e,!1).get(t);return void 0===(r=await new zo(r).toPromise())?null:r.value})(e,t));return this.localCache[t]=e}async _remove(t){return this._withPendingWrite(async()=>(await this._withRetries(e=>Go(e,t)),delete this.localCache[t],this.notifyServiceWorker(t)))}async _poll(){var e=await this._withRetries(e=>{var t=Ko(e,!1).getAll();return new zo(t).toPromise()});if(!e)return[];if(0!==this.pendingWrites)return[];var t,r=[],n=new Set;if(0!==e.length)for(var{fbase_key:i,value:s}of e)n.add(i),JSON.stringify(this.localCache[i])!==JSON.stringify(s)&&(this.notifyListeners(i,s),r.push(i));for(t of Object.keys(this.localCache))this.localCache[t]&&!n.has(t)&&(this.notifyListeners(t,null),r.push(t));return r}notifyListeners(e,t){this.localCache[e]=t;var r=this.listeners[e];if(r)for(var n of Array.from(r))n(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()}}$o.type="LOCAL";let Qo=$o;function Yo(e,t){return fs(e,"POST","/v2/accounts/mfaSignIn:start",ps(e,t))}let Jo=oa("rcb"),Xo=new os(3e4,6e4);class Zo{constructor(){this.hostLanguage="",this.counter=0,this.librarySeparatelyLoaded=!!Uo().grecaptcha?.render}load(i,s=""){var e;return m((e=s).length<=6&&/^\s*[a-zA-Z0-9\-]*\s*$/.test(e),i,"argument-error"),this.shouldResolveImmediately(s)&&ws(Uo().grecaptcha)?Promise.resolve(Uo().grecaptcha):new Promise((t,r)=>{let n=Uo().setTimeout(()=>{r(Ji(i,"network-request-failed"))},Xo.get());Uo()[Jo]=()=>{Uo().clearTimeout(n),delete Uo()[Jo];var e=Uo().grecaptcha;if(e&&ws(e)){let n=e.render;e.render=(e,t)=>{var r=n(e,t);return this.counter++,r},this.hostLanguage=s,t(e)}else r(Ji(i,"internal-error"))},aa(sa.recaptchaV2Script+"?"+Se({onload:Jo,render:"explicit",hl:s})).catch(()=>{clearTimeout(n),r(Ji(i,"internal-error"))})})}clearedOneInstance(){this.counter--}shouldResolveImmediately(e){return!!Uo().grecaptcha?.render&&(e===this.hostLanguage||0<this.counter||this.librarySeparatelyLoaded)}}class el{async load(e){return new la(e)}clearedOneInstance(){}}let tl="recaptcha",rl={theme:"light",type:"image"};class nl{constructor(e,t,r={...rl}){this.parameters=r,this.type=tl,this.destroyed=!1,this.widgetId=null,this.tokenChangeListeners=new Set,this.renderPromise=null,this.recaptcha=null,this.auth=na(e),this.isInvisible="invisible"===this.parameters.size,m("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment");var n="string"==typeof t?document.getElementById(t):t;m(n,this.auth,"argument-error"),this.container=n,this.parameters.callback=this.makeTokenCallback(this.parameters.callback),this._recaptchaLoader=new(this.auth.settings.appVerificationDisabledForTesting?el:Zo),this.validateStartingState()}async verify(){this.assertNotDestroyed();let e=await this.render(),n=this.getAssertedRecaptcha();var t=n.getResponse(e);return t||new Promise(t=>{let r=e=>{e&&(this.tokenChangeListeners.delete(r),t(e))};this.tokenChangeListeners.add(r),this.isInvisible&&n.execute(e)})}render(){try{this.assertNotDestroyed()}catch(e){return Promise.reject(e)}return this.renderPromise||(this.renderPromise=this.makeRenderPromise().catch(e=>{throw this.renderPromise=null,e})),this.renderPromise}_reset(){this.assertNotDestroyed(),null!==this.widgetId&&this.getAssertedRecaptcha().reset(this.widgetId)}clear(){this.assertNotDestroyed(),this.destroyed=!0,this._recaptchaLoader.clearedOneInstance(),this.isInvisible||this.container.childNodes.forEach(e=>{this.container.removeChild(e)})}validateStartingState(){m(!this.parameters.sitekey,this.auth,"argument-error"),m(this.isInvisible||!this.container.hasChildNodes(),this.auth,"argument-error"),m("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment")}makeTokenCallback(r){return t=>{var e;this.tokenChangeListeners.forEach(e=>e(t)),"function"==typeof r?r(t):"string"==typeof r&&"function"==typeof(e=Uo()[r])&&e(t)}}assertNotDestroyed(){m(!this.destroyed,this.auth,"internal-error")}async makeRenderPromise(){if(await this.init(),!this.widgetId){let e=this.container;var t;this.isInvisible||(t=document.createElement("div"),e.appendChild(t),e=t),this.widgetId=this.getAssertedRecaptcha().render(e,this.parameters)}return this.widgetId}async init(){m(ss()&&!Vo(),this.auth,"internal-error"),await(()=>{let t=null;return new Promise(e=>{"complete"===document.readyState?e():(t=()=>e(),window.addEventListener("load",t))}).catch(e=>{throw t&&window.removeEventListener("load",t),e})})(),this.recaptcha=await this._recaptchaLoader.load(this.auth,this.auth.languageCode||void 0);var e=await((await fs(this.auth,"GET","/v1/recaptchaParams")).recaptchaSiteKey||"");m(e,this.auth,"internal-error"),this.parameters.sitekey=e}getAssertedRecaptcha(){return m(this.recaptcha,this.auth,"internal-error"),this.recaptcha}}class il{constructor(e,t){this.verificationId=e,this.onConfirmation=t}confirm(e){var t=Pa._fromVerification(this.verificationId,e);return this.onConfirmation(t)}}async function sl(t,r,n){if(!t._getRecaptchaConfig())try{e=na(t),i=await Ts(e,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}),i=new Is(i),null==e.tenantId?e._agentRecaptchaConfig=i:e._tenantRecaptchaConfigs[e.tenantId]=i,await(!i.isAnyProviderEnabled()||!new pa(e).verify())}catch(e){console.log("Failed to initialize reCAPTCHA Enterprise config. Triggering the reCAPTCHA v2 verification.")}var e,i,s,a,o,l,h;try{let e;return("session"in(e="string"==typeof r?{phoneNumber:r}:r)?(s=e.session,"phoneNumber"in e?(m("enroll"===s.type,t,"internal-error"),a={idToken:s.credential,phoneEnrollmentInfo:{phoneNumber:e.phoneNumber,clientType:"CLIENT_TYPE_WEB"}},(await ga(t,a,"mfaSmsEnrollment",async(e,t)=>t.phoneEnrollmentInfo.captchaResponse===da?(m(n?.type===tl,e,"argument-error"),So(e,await al(e,t,n))):So(e,t),"PHONE_PROVIDER").catch(e=>Promise.reject(e))).phoneSessionInfo):(m("signin"===s.type,t,"internal-error"),m(o=e.multiFactorHint?.uid||e.multiFactorUid,t,"missing-multi-factor-info"),l={mfaPendingCredential:s.credential,mfaEnrollmentId:o,phoneSignInInfo:{clientType:"CLIENT_TYPE_WEB"}},(await ga(t,l,"mfaSmsSignIn",async(e,t)=>t.phoneSignInInfo.captchaResponse===da?(m(n?.type===tl,e,"argument-error"),Yo(e,await al(e,t,n))):Yo(e,t),"PHONE_PROVIDER").catch(e=>Promise.reject(e))).phoneResponseInfo)):(h={phoneNumber:e.phoneNumber,clientType:"CLIENT_TYPE_WEB"},await ga(t,h,"sendVerificationCode",async(e,t)=>t.captchaResponse===da?(m(n?.type===tl,e,"argument-error"),Na(e,await al(e,t,n))):Na(e,t),"PHONE_PROVIDER").catch(e=>Promise.reject(e)))).sessionInfo}finally{n?._reset()}}async function al(e,t,r){m(r.type===tl,e,"argument-error");var n,i,s,a,o=await r.verify(),l=(m("string"==typeof o,e,"argument-error"),{...t});return"phoneEnrollmentInfo"in l?(i=l.phoneEnrollmentInfo.phoneNumber,s=l.phoneEnrollmentInfo.captchaResponse,a=l.phoneEnrollmentInfo.clientType,n=l.phoneEnrollmentInfo.recaptchaVersion,Object.assign(l,{phoneEnrollmentInfo:{phoneNumber:i,recaptchaToken:o,captchaResponse:s,clientType:a,recaptchaVersion:n}})):"phoneSignInInfo"in l?(i=l.phoneSignInInfo.captchaResponse,s=l.phoneSignInInfo.clientType,a=l.phoneSignInInfo.recaptchaVersion,Object.assign(l,{phoneSignInInfo:{recaptchaToken:o,captchaResponse:i,clientType:s,recaptchaVersion:a}})):Object.assign(l,{recaptchaToken:o}),l}class ol{constructor(e){this.providerId=ol.PROVIDER_ID,this.auth=na(e)}verifyPhoneNumber(e,t){return sl(this.auth,e,w(t))}static credential(e,t){return Pa._fromVerification(e,t)}static credentialFromResult(e){var t=e;return ol.credentialFromTaggedObject(t)}static credentialFromError(e){return ol.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){var t,r;return e&&({phoneNumber:t,temporaryProof:r}=e,t)&&r?Pa._fromTokenResponse(t,r):null}}function ll(e,t){return t?Us(t):(m(e._popupRedirectResolver,e,"argument-error"),e._popupRedirectResolver)}ol.PROVIDER_ID="phone",ol.PHONE_SIGN_IN_METHOD="phone";class hl extends ya{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return ka(e,this._buildIdpRequest())}_linkToIdToken(e,t){return ka(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return ka(e,this._buildIdpRequest())}_buildIdpRequest(e){var 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 cl(e){return Za(e.auth,new hl(e),e.bypassAuthState)}function ul(e){var{auth:t,user:r}=e;return m(r,t,"internal-error"),Xa(r,new hl(e),e.bypassAuthState)}async function dl(e){var{auth:t,user:r}=e;return m(r,t,"internal-error"),Ya(r,new hl(e),e.bypassAuthState)}class pl{constructor(e,t,r,n,i=!1){this.auth=e,this.resolver=r,this.user=n,this.bypassAuthState=i,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){var{urlResponse:t,sessionId:r,postBody:n,tenantId:i,error:s,type:a}=e;if(s)this.reject(s);else{s={auth:this.auth,requestUri:t,sessionId:r,tenantId:i||void 0,postBody:n||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(a)(s))}catch(e){this.reject(e)}}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return cl;case"linkViaPopup":case"linkViaRedirect":return dl;case"reauthViaPopup":case"reauthViaRedirect":return ul;default:Yi(this.auth,"internal-error")}}resolve(e){ns(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){ns(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.reject(e),this.unregisterAndCleanUp()}unregisterAndCleanUp(){this.eventManager&&this.eventManager.unregisterConsumer(this),this.pendingPromise=null,this.cleanUp()}}let fl=new os(2e3,1e4);class gl extends pl{constructor(e,t,r,n,i){super(e,t,n,i),this.provider=r,this.authWindow=null,this.pollId=null,gl.currentPopupAction&&gl.currentPopupAction.cancel(),gl.currentPopupAction=this}async executeNotNull(){var e=await this.execute();return m(e,this.auth,"internal-error"),e}async onExecution(){ns(1===this.filter.length,"Popup operations only handle one event");var e=Lo();this.authWindow=await this.resolver._openPopup(this.auth,this.provider,this.filter[0],e),this.authWindow.associatedEvent=e,this.resolver._originValidation(this.auth).catch(e=>{this.reject(e)}),this.resolver._isIframeWebStorageSupported(this.auth,e=>{e||this.reject(Ji(this.auth,"web-storage-unsupported"))}),this.pollUserCancellation()}get eventId(){return this.authWindow?.associatedEvent||null}cancel(){this.reject(Ji(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,gl.currentPopupAction=null}pollUserCancellation(){let e=()=>{this.authWindow?.window?.closed?this.pollId=window.setTimeout(()=>{this.pollId=null,this.reject(Ji(this.auth,"popup-closed-by-user"))},8e3):this.pollId=window.setTimeout(e,fl.get())};e()}}gl.currentPopupAction=null;let ml="pendingRedirect",vl=new Map;class _l extends pl{constructor(e,t,r=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,r),this.eventId=null}async execute(){let t=vl.get(this.auth._key());if(!t){try{let e=await(async(e,t)=>{var r,n=Il(t),i=bl(e);return!!await i._isAvailable()&&(r="true"===await i._get(n),await i._remove(n),r)})(this.resolver,this.auth)?await super.execute():null;t=()=>Promise.resolve(e)}catch(e){t=()=>Promise.reject(e)}vl.set(this.auth._key(),t)}return this.bypassAuthState||vl.set(this.auth._key(),()=>Promise.resolve(null)),t()}async onAuthEvent(e){if("signInViaRedirect"===e.type)return super.onAuthEvent(e);if("unknown"===e.type)this.resolve(null);else if(e.eventId){var t=await this.auth._redirectUserForId(e.eventId);if(t)return this.user=t,super.onAuthEvent(e);this.resolve(null)}}async onExecution(){}cleanUp(){}}async function yl(e,t){return bl(e)._set(Il(t),"true")}function wl(e,t){vl.set(e._key(),t)}function bl(e){return Us(e._redirectPersistence)}function Il(e){return Bs(ml,e.config.apiKey,e.name)}function Tl(e,t,r){return(async(e,t,r)=>{var n,i;return h(e.app)?Promise.reject(Zi(e)):(n=na(e),es(e,t,Oa),await n._initializationPromise,await yl(i=ll(n,r),n),i._openRedirect(n,t,"signInViaRedirect"))})(e,t,r)}function El(e,t,r){return(async(e,t,r)=>{var n=w(e);if(es(n.auth,t,Oa),h(n.auth.app))return Promise.reject(Zi(n.auth));await n.auth._initializationPromise;var i=ll(n.auth,r),s=(await yl(i,n.auth),await kl(n));return i._openRedirect(n.auth,t,"reauthViaRedirect",s)})(e,t,r)}function Cl(e,t,r){return(async(e,t,r)=>{var n=w(e),i=(es(n.auth,t,Oa),await n.auth._initializationPromise,ll(n.auth,r)),s=(await Ja(!1,n,t.providerId),await yl(i,n.auth),await kl(n));return i._openRedirect(n.auth,t,"linkViaRedirect",s)})(e,t,r)}async function Sl(e,t,r=!1){var n,i;return h(e.app)?Promise.reject(Zi(e)):(i=ll(n=na(e),t),(i=await new _l(n,i,r).execute())&&!r&&(delete i.user._redirectEventId,await n._persistUserIfCurrent(i.user),await n._setRedirectUser(null,t)),i)}async function kl(e){var t=Lo(e.uid+":::");return e._redirectEventId=t,await e.auth._setRedirectUser(e),await e.auth._persistUserIfCurrent(e),t}class Al{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(t){if(this.hasEventBeenHandled(t))return!1;let r=!1;return this.consumers.forEach(e=>{this.isEventForConsumer(t,e)&&(r=!0,this.sendToConsumer(t,e),this.saveEventToCache(t))}),this.hasHandledPotentialRedirect||!(e=>{switch(e.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return 1;case"unknown":return Rl(e);default:return}})(t)||(this.hasHandledPotentialRedirect=!0,r)||(this.queuedRedirectEvent=t,r=!0),r}sendToConsumer(e,t){var r;e.error&&!Rl(e)?(r=e.error.code?.split("auth/")[1]||"internal-error",t.onError(Ji(this.auth,r))):t.onAuthEvent(e)}isEventForConsumer(e,t){var r=null===t.eventId||!!e.eventId&&e.eventId===t.eventId;return t.filter.includes(e.type)&&r}hasEventBeenHandled(e){return 6e5<=Date.now()-this.lastProcessedEventTime&&this.cachedEventUids.clear(),this.cachedEventUids.has(Nl(e))}saveEventToCache(e){this.cachedEventUids.add(Nl(e)),this.lastProcessedEventTime=Date.now()}}function Nl(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter(e=>e).join("-")}function Rl({type:e,error:t}){return"unknown"===e&&"auth/no-auth-event"===t?.code}async function Pl(e,t={}){return fs(e,"GET","/v1/projects",t)}let Dl=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,xl=/^https?/;async function Ol(e){if(!e.config.emulator){var t,r=(await Pl(e)).authorizedDomains;for(t of r)try{if((e=>{var t,r=is(),{protocol:n,hostname:i}=new URL(r);return e.startsWith("chrome-extension://")?""===(t=new URL(e)).hostname&&""===i?"chrome-extension:"===n&&e.replace("chrome-extension://","")===r.replace("chrome-extension://",""):"chrome-extension:"===n&&t.hostname===i:xl.test(n)&&(Dl.test(e)?i===e:(r=e.replace(/\./g,"\\."),(t=new RegExp("^(.+\\."+r+"|"+r+")$","i")).test(i)))})(t))return}catch{}Yi(e,"unauthorized-domain")}}let Ml=new os(3e4,6e4);function Ll(){var t=Uo().___jsl;if(t?.H)for(var r of Object.keys(t.H))if(t.H[r].r=t.H[r].r||[],t.H[r].L=t.H[r].L||[],t.H[r].r=[...t.H[r].L],t.CP)for(let e=0;e<t.CP.length;e++)t.CP[e]=null}function Fl(i){return new Promise((e,t)=>{function r(){Ll(),gapi.load("gapi.iframes",{callback:()=>{e(gapi.iframes.getContext())},ontimeout:()=>{Ll(),t(Ji(i,"network-request-failed"))},timeout:Ml.get()})}if(Uo().gapi?.iframes?.Iframe)e(gapi.iframes.getContext());else{var n;if(!Uo().gapi?.load)return n=oa("iframefcb"),Uo()[n]=()=>{gapi.load?r():t(Ji(i,"network-request-failed"))},aa(sa.gapiScript+"?onload="+n).catch(e=>t(e));r()}}).catch(e=>{throw Ul=null,e})}let Ul=null;let Vl=new os(5e3,15e3),ql="__/auth/iframe",Bl="emulator/auth/iframe",jl={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},zl=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);async function Kl(a){e=a;var e,t,r,n=await(Ul=Ul||Fl(e)),i=Uo().gapi;return m(i,a,"internal-error"),n.open({where:document.body,url:(m((n=(e=a).config).authDomain,e,"auth-domain-config-required"),t=n.emulator?ls(n,Bl):`https://${e.config.authDomain}/`+ql,n={apiKey:n.apiKey,appName:e.name,v:Ft},(r=zl.get(e.config.apiHost))&&(n.eid=r),(r=e._getFrameworks()).length&&(n.fw=r.join(",")),t+"?"+Se(n).slice(1)),messageHandlersFilter:i.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:jl,dontclear:!0},s=>new Promise(async(e,t)=>{await s.restyle({setHideOnLeave:!1});let r=Ji(a,"network-request-failed"),n=Uo().setTimeout(()=>{t(r)},Vl.get());function i(){Uo().clearTimeout(n),e(s)}s.ping(i).then(i,()=>{t(r)})}))}let Wl={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"};class Hl{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch(e){}}}function Gl(e,t,r,n=500,i=600){var s=Math.max((window.screen.availHeight-i)/2,0).toString(),a=Math.max((window.screen.availWidth-n)/2,0).toString();let o="";var l,s={...Wl,width:n.toString(),height:i.toString(),top:s,left:a},a=te().toLowerCase(),s=(r&&(o=Hs(a)?"_blank":r),Ks(a)&&(t=t||"http://localhost",s.scrollbars="yes"),Object.entries(s).reduce((e,[t,r])=>""+e+t+`=${r},`,""));if([n=te()]=[a],Js(n)&&window.navigator?.standalone&&"_self"!==o)return i=t||"",r=o,(a=document.createElement("a")).href=i,a.target=r,(l=document.createEvent("MouseEvent")).initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),a.dispatchEvent(l),new Hl(null);a=window.open(t||"",o,s);m(a,e,"popup-blocked");try{a.focus()}catch(e){}return new Hl(a)}let $l="__/auth/handler",Ql="emulator/auth/handler",Yl=encodeURIComponent("fac");async function Jl(e,t,r,n,i,s){m(e.config.authDomain,e,"auth-domain-config-required"),m(e.config.apiKey,e,"invalid-api-key");var a={apiKey:e.config.apiKey,appName:e.name,authType:r,redirectUrl:n,v:Ft,eventId:i};if(t instanceof Oa){t.setDefaultLanguage(e.languageCode),a.providerId=t.providerId||"",Ie(t.getCustomParameters())||(a.customParameters=JSON.stringify(t.getCustomParameters()));for(var[o,l]of Object.entries(s||{}))a[o]=l}t instanceof Ma&&0<(u=t.getScopes().filter(e=>""!==e)).length&&(a.scopes=u.join(",")),e.tenantId&&(a.tid=e.tenantId);var h,c=a;for(h of Object.keys(c))void 0===c[h]&&delete c[h];var u=await e._getAppCheckToken(),u=u?`#${Yl}=`+encodeURIComponent(u):"";return`${r=[e.config][0],r.emulator?ls(r,Ql):`https://${r.authDomain}/`+$l}?`+Se(c).slice(1)+u}let Xl="webStorageSupport";class Zl{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=Oo,this._completeRedirectFn=Sl,this._overrideRedirectResult=wl}async _openPopup(e,t,r,n){return ns(this.eventManagers[e._key()]?.manager,"_initialize() not called before _openPopup()"),Gl(e,await Jl(e,t,r,is(),n),Lo())}async _openRedirect(e,t,r,n){await this._originValidation(e);var i=await Jl(e,t,r,is(),n);return Uo().location.href=i,new Promise(()=>{})}_initialize(e){let r=e._key();if(this.eventManagers[r]){let{manager:e,promise:t}=this.eventManagers[r];return e?Promise.resolve(e):(ns(t,"If manager is not set, promise should be"),t)}let t=this.initAndGetManager(e);return this.eventManagers[r]={promise:t},t.catch(()=>{delete this.eventManagers[r]}),t}async initAndGetManager(t){var e=await Kl(t);let r=new Al(t);return e.register("authEvent",e=>(m(e?.authEvent,t,"invalid-auth-event"),{status:r.onEvent(e.authEvent)?"ACK":"ERROR"}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[t._key()]={manager:r},this.iframes[t._key()]=e,r}_isIframeWebStorageSupported(r,n){this.iframes[r._key()].send(Xl,{type:Xl},e=>{var t=e?.[0]?.[Xl];void 0!==t&&n(!!t),Yi(r,"internal-error")},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){var t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=Ol(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return Xs()||Ws()||Js()}}let eh=Zl;class th extends class{constructor(e){this.factorId=e}_process(e,t,r){switch(t.type){case"enroll":return this._finalizeEnroll(e,t.credential,r);case"signin":return this._finalizeSignIn(e,t.credential);default:return rs("unexpected MultiFactorSessionType")}}}{constructor(e){super("phone"),this.credential=e}static _fromCredential(e){return new th(e)}_finalizeEnroll(e,t,r){return e=e,t={idToken:t,displayName:r,phoneVerificationInfo:this.credential._makeVerificationRequest()},fs(e,"POST","/v2/accounts/mfaEnrollment:finalize",ps(e,t))}_finalizeSignIn(e,t){return e=e,t={mfaPendingCredential:t,phoneVerificationInfo:this.credential._makeVerificationRequest()},fs(e,"POST","/v2/accounts/mfaSignIn:finalize",ps(e,t))}}class rh{constructor(){}static assertion(e){return th._fromCredential(e)}}rh.FACTOR_ID="phone";ir="@firebase/auth";class nh{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){return this.assertAuthConfigured(),this.auth.currentUser?.uid||null}async getToken(e){return this.assertAuthConfigured(),await this.auth._initializationPromise,this.auth.currentUser?{accessToken:await this.auth.currentUser.getIdToken(e)}:null}addAuthTokenListener(t){var e;this.assertAuthConfigured(),this.internalListeners.has(t)||(e=this.auth.onIdTokenChanged(e=>{t(e?.stsTokenManager.accessToken||null)}),this.internalListeners.set(t,e),this.updateProactiveRefresh())}removeAuthTokenListener(e){this.assertAuthConfigured();var t=this.internalListeners.get(e);t&&(this.internalListeners.delete(e),t(),this.updateProactiveRefresh())}assertAuthConfigured(){m(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){0<this.internalListeners.size?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}var ih;function sh(){return window}Y()?._authIdTokenMaxAge,sa={loadJS(n){return new Promise((e,r)=>{var t=document.createElement("script");t.setAttribute("src",n),t.onload=e,t.onerror=e=>{var t=Ji("internal-error");t.customData=e,r(t)},t.type="text/javascript",t.charset="UTF-8",(document.getElementsByTagName("head")?.[0]??document).appendChild(t)})},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="},ih="Browser",Nt(new c("auth",(e,{options:t})=>{var r=e.getProvider("app").getImmediate(),n=e.getProvider("heartbeat"),i=e.getProvider("app-check-internal"),{apiKey:s,authDomain:a}=r.options,s=(m(s&&!s.includes(":"),"invalid-api-key",{appName:r.name}),{apiKey:s,authDomain:a,clientPlatform:ih,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:Zs(ih)}),a=new ra(r,n,i,s);return e=a,r=(t=t)?.persistence||[],r=(Array.isArray(r)?r:[r]).map(Us),t?.errorMap&&e._updateErrorMap(t.errorMap),e._initializeWithPersistence(r,t?.popupRedirectResolver),a},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,r)=>{e.getProvider("auth-internal").initialize()})),Nt(new c("auth-internal",e=>{var t=na(e.getProvider("auth").getImmediate());return e=t,new nh(e)},"PRIVATE").setInstantiationMode("EXPLICIT")),u(ir,"1.13.0",(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}})(ih)),u(ir,"1.13.0","esm2020");async function ah(e,t,r){var n=sh().BuildInfo,i=(ns(t.sessionId,"AuthEvent did not contain a session ID"),i=(e=>{if(ns(/[0-9a-zA-Z]+/.test(e),"Can only convert alpha-numeric strings"),"undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e);var t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r})(t.sessionId),i=await crypto.subtle.digest("SHA-256",i),await(i=Array.from(new Uint8Array(i))).map(e=>e.toString(16).padStart(2,"0")).join("")),s={};return Js()?s.ibi=n.packageName:$s()?s.apn=n.packageName:Yi(e,"operation-not-supported-in-this-environment"),n.displayName&&(s.appDisplayName=n.displayName),s.sessionId=i,Jl(e,r,t.type,void 0,t.eventId??void 0,s)}function oh(n){let i=sh().cordova;return new Promise(r=>{i.plugins.browsertab.isAvailable(e=>{let t=null;e?i.plugins.browsertab.openUrl(n):t=i.InAppBrowser.open(n,(e=te(),/(iPad|iPhone|iPod).*OS 7_\d/i.test(e)||/(iPad|iPhone|iPod).*OS 8_\d/i.test(e)?"_blank":"_system"),"location=yes"),r(t)})})}let lh=20;class hh extends Al{constructor(){super(...arguments),this.passiveListeners=new Set,this.initPromise=new Promise(e=>{this.resolveInitialized=e})}addPassiveListener(e){this.passiveListeners.add(e)}removePassiveListener(e){this.passiveListeners.delete(e)}resetRedirect(){this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1}onEvent(t){return this.resolveInitialized(),this.passiveListeners.forEach(e=>e(t)),super.onEvent(t)}async initialized(){await this.initPromise}}function ch(e,t,r=null){return{type:t,eventId:r,urlResponse:null,sessionId:(()=>{var e=[],t="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let n=0;n<lh;n++){var r=Math.floor(Math.random()*t.length);e.push(t.charAt(r))}return e.join("")})(),postBody:null,tenantId:e.tenantId,error:Ji(e,"no-auth-event")}}async function uh(e){var t=await ph()._get(fh(e));return t&&await ph()._remove(fh(e)),t}function dh(e,t){i=gh(t=t),r=i.link?decodeURIComponent(i.link):void 0,n=gh(r).link,i=i.deep_link_id?decodeURIComponent(i.deep_link_id):void 0;var r,n,i=gh(i).link||i||n||r||t;return i.includes("/__/auth/callback")?(n=(r=((n=gh(i)).firebaseError?(e=>{try{return JSON.parse(e)}catch(e){return null}})(decodeURIComponent(n.firebaseError)):null)?.code?.split("auth/")?.[1])?Ji(r):null)?{type:e.type,eventId:e.eventId,tenantId:e.tenantId,error:n,urlResponse:null,sessionId:null,postBody:null}:{type:e.type,eventId:e.eventId,tenantId:e.tenantId,sessionId:e.sessionId,urlResponse:i,postBody:null}:null}function ph(){return Us(Do)}function fh(e){return Bs("authEvent",e.config.apiKey,e.name)}function gh(e){var t,r;return e?.includes("?")?([t,...r]=e.split("?"),ke(r.join("?"))):{}}class mh{constructor(){this._redirectPersistence=Oo,this._shouldInitProactively=!0,this.eventManagers=new Map,this.originValidationPromises={},this._completeRedirectFn=Sl,this._overrideRedirectResult=wl}async _initialize(e){var t=e._key();let r=this.eventManagers.get(t);return r||(r=new hh(e),this.eventManagers.set(t,r),this.attachCallbackListeners(e,r)),r}_openPopup(e){Yi(e,"operation-not-supported-in-this-environment")}async _openRedirect(e,t,r,n){i=e,m("function"==typeof(s=sh())?.universalLinks?.subscribe,i,"invalid-cordova-configuration",{missingPlugin:"cordova-universal-links-plugin-fix"}),m(void 0!==s?.BuildInfo?.packageName,i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-buildInfo"}),m("function"==typeof s?.cordova?.plugins?.browsertab?.openUrl,i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"}),m("function"==typeof s?.cordova?.plugins?.browsertab?.isAvailable,i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"}),m("function"==typeof s?.cordova?.InAppBrowser?.open,i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-inappbrowser"});var i,s=await this._initialize(e),a=(await s.initialized(),s.resetRedirect(),vl.clear(),await this._originValidation(e),ch(e,r,n)),a=(i=e,r=a,await ph()._set(fh(i),r),await ah(e,a,t));return(async(a,o,l)=>{let h=sh().cordova,c=()=>{};try{await new Promise((t,e)=>{let r=null;function n(){t();var e=h.plugins.browsertab?.close;"function"==typeof e&&e(),"function"==typeof l?.close&&l.close()}function i(){r=r||window.setTimeout(()=>{e(Ji(a,"redirect-cancelled-by-user"))},2e3)}function s(){"visible"===document?.visibilityState&&i()}o.addPassiveListener(n),document.addEventListener("resume",i,!1),$s()&&document.addEventListener("visibilitychange",s,!1),c=()=>{o.removePassiveListener(n),document.removeEventListener("resume",i,!1),document.removeEventListener("visibilitychange",s,!1),r&&window.clearTimeout(r)}})}finally{c()}})(e,s,await oh(a))}_isIframeWebStorageSupported(e,t){throw new Error("Method not implemented.")}_originValidation(e){var t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=(async e=>{var t=sh().BuildInfo,r={};Js()?r.iosBundleId=t.packageName:$s()?r.androidPackageName=t.packageName:Yi(e,"operation-not-supported-in-this-environment"),await Pl(e,r)})(e)),this.originValidationPromises[t]}attachCallbackListeners(n,i){var{universalLinks:e,handleOpenURL:t,BuildInfo:r}=sh();let s=setTimeout(async()=>{await uh(n),i.onEvent(_h())},500),a=async e=>{clearTimeout(s);var t=await uh(n);let r=null;t&&e?.url&&(r=dh(t,e.url)),i.onEvent(r||_h())},o=(void 0!==e&&"function"==typeof e.subscribe&&e.subscribe(null,a),t),l=r.packageName.toLowerCase()+"://";sh().handleOpenURL=async e=>{if(e.toLowerCase().startsWith(l)&&a({url:e}),"function"==typeof o)try{o(e)}catch(e){console.error(e)}}}}let vh=mh;function _h(){return{type:"unknown",eventId:null,sessionId:null,urlResponse:null,postBody:null,tenantId:null,error:Ji("no-auth-event")}}function yh(){return self?.location?.protocol||null}function wh(e=te()){return!("file:"!==yh()&&"ionic:"!==yh()&&"capacitor:"!==yh()||!e.toLowerCase().match(/iphone|ipad|ipod|android/))}function bh(e=te()){return oe()&&11===document?.documentMode||([e=te()]=[e],/Edge\/\d+/.test(e))}function Ih(){try{var e=self.localStorage,t=Lo();if(e)return e.setItem(t,"1"),e.removeItem(t),!bh()||ue()}catch(e){return Th()&&ue()}return!1}function Th(){return"undefined"!=typeof global&&"WorkerGlobalScope"in global&&"importScripts"in global}function Eh(){return("http:"===yh()||"https:"===yh()||se()||wh())&&!(ae()||ne())&&Ih()&&!Th()}function Ch(){return wh()&&"undefined"!=typeof document}let Sh={LOCAL:"local",NONE:"none",SESSION:"session"},kh=m,Ah="persistence";async function Nh(e){await e._initializationPromise;var t=Rh(),r=Bs(Ah,e.config.apiKey,e.name);t&&t.setItem(r,e._getPersistenceType())}function Rh(){try{return("undefined"!=typeof window?window:null)?.sessionStorage||null}catch(e){return null}}let Ph=m;class Dh{constructor(){this.browserResolver=Us(eh),this.cordovaResolver=Us(vh),this.underlyingResolver=null,this._redirectPersistence=Oo,this._completeRedirectFn=Sl,this._overrideRedirectResult=wl}async _initialize(e){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._initialize(e)}async _openPopup(e,t,r,n){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._openPopup(e,t,r,n)}async _openRedirect(e,t,r,n){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._openRedirect(e,t,r,n)}_isIframeWebStorageSupported(e,t){this.assertedUnderlyingResolver._isIframeWebStorageSupported(e,t)}_originValidation(e){return this.assertedUnderlyingResolver._originValidation(e)}get _shouldInitProactively(){return Ch()||this.browserResolver._shouldInitProactively}get assertedUnderlyingResolver(){return Ph(this.underlyingResolver,"internal-error"),this.underlyingResolver}async selectUnderlyingResolver(){var e;this.underlyingResolver||(e=await(!!Ch()&&new Promise(e=>{let t=setTimeout(()=>{e(!1)},1e3);document.addEventListener("deviceready",()=>{clearTimeout(t),e(!0)})})),this.underlyingResolver=e?this.cordovaResolver:this.browserResolver)}}function xh(e){return e.unwrap()}function Oh(e,t){var r,n,i,s=t.customData?._tokenResponse;"auth/multi-factor-auth-required"===t?.code?t.resolver=new Uh(e,(r=t,n=w(e),m((i=r).customData.operationType,n,"argument-error"),m(i.customData._serverResponse?.mfaPendingCredential,n,"argument-error"),Co._fromError(n,i))):s&&(i=Mh(n=t))&&(n.credential=i,n.tenantId=s.tenantId||void 0,n.email=s.email||void 0,n.phoneNumber=s.phoneNumber||void 0)}function Mh(e){var t=(e instanceof fe?e.customData:e)._tokenResponse;if(!t)return null;if(!(e instanceof fe)&&"temporaryProof"in t&&"phoneNumber"in t)return ol.credentialFromResult(e);var r=t.providerId;if(!r||r===ji.PASSWORD)return null;let n;switch(r){case ji.GOOGLE:n=Ua;break;case ji.FACEBOOK:n=Fa;break;case ji.GITHUB:n=Va;break;case ji.TWITTER:n=ja;break;default:var{oauthIdToken:i,oauthAccessToken:s,oauthTokenSecret:a,pendingToken:o,nonce:l}=t;return s||a||i||o?o?r.startsWith("saml.")?qa._create(r,o):Aa._fromParams({providerId:r,signInMethod:r,pendingToken:o,idToken:i,accessToken:s}):new La(r).credential({idToken:i,accessToken:s,rawNonce:l}):null}return e instanceof fe?n.credentialFromError(e):n.credentialFromResult(e)}function Lh(t,e){return e.catch(e=>{throw e instanceof fe&&Oh(t,e),e}).then(e=>{var t=e.operationType,r=e.user;return{operationType:t,credential:Mh(e),additionalUserInfo:To(e),user:Vh.getOrCreate(r)}})}async function Fh(t,e){let r=await e;return{verificationId:r.verificationId,confirm:e=>Lh(t,r.confirm(e))}}class Uh{constructor(e,t){this.resolver=t,this.auth=e.wrapped()}get session(){return this.resolver.session}get hints(){return this.resolver.hints}resolveSignIn(e){return Lh(xh(this.auth),this.resolver.resolveSignIn(e))}}class Vh{constructor(e){var t;this._delegate=e,this.multiFactor=(t=w(e),Ao.has(t)||Ao.set(t,ko._fromUser(t)),Ao.get(t))}static getOrCreate(e){return Vh.USER_MAP.has(e)||Vh.USER_MAP.set(e,new Vh(e)),Vh.USER_MAP.get(e)}delete(){return this._delegate.delete()}reload(){return this._delegate.reload()}toJSON(){return this._delegate.toJSON()}getIdTokenResult(e){return this._delegate.getIdTokenResult(e)}getIdToken(e){return this._delegate.getIdToken(e)}linkAndRetrieveDataWithCredential(e){return this.linkWithCredential(e)}async linkWithCredential(e){return Lh(this.auth,to(this._delegate,e))}async linkWithPhoneNumber(e,t){return Fh(this.auth,(async(e,t,r)=>{let n=w(e);await Ja(!1,n,"phone");var i=await sl(n.auth,t,w(r));return new il(i,e=>to(n,e))})(this._delegate,e,t))}async linkWithPopup(e){return Lh(this.auth,(async(e,t,r)=>{var n=w(e),i=(es(n.auth,t,Oa),ll(n.auth,r));return new gl(n.auth,"linkViaPopup",t,i,n).executeNotNull()})(this._delegate,e,Dh))}async linkWithRedirect(e){return await Nh(na(this.auth)),Cl(this._delegate,e,Dh)}reauthenticateAndRetrieveDataWithCredential(e){return this.reauthenticateWithCredential(e)}async reauthenticateWithCredential(e){return Lh(this.auth,ro(this._delegate,e))}reauthenticateWithPhoneNumber(e,t){return Fh(this.auth,(async(e,t,r)=>{let n=w(e);var i;return h(n.auth.app)?Promise.reject(Zi(n.auth)):(i=await sl(n.auth,t,w(r)),new il(i,e=>ro(n,e)))})(this._delegate,e,t))}reauthenticateWithPopup(e){return Lh(this.auth,(async(e,t,r)=>{var n=w(e);if(h(n.auth.app))return Promise.reject(Ji(n.auth,"operation-not-supported-in-this-environment"));es(n.auth,t,Oa);var i=ll(n.auth,r);return new gl(n.auth,"reauthViaPopup",t,i,n).executeNotNull()})(this._delegate,e,Dh))}async reauthenticateWithRedirect(e){return await Nh(na(this.auth)),El(this._delegate,e,Dh)}sendEmailVerification(e){return po(this._delegate,e)}async unlink(e){return await Qa(this._delegate,e),this}updateEmail(e){return t=this._delegate,e=e,h((r=w(t)).auth.app)?Promise.reject(Zi(r.auth)):mo(r,e,null);var t,r}updatePassword(e){return mo(w(this._delegate),null,e)}updatePhoneNumber(e){return(async(e,t)=>{var r=w(e);if(h(r.auth.app))return Promise.reject(Zi(r.auth));await Ya(r,t)})(this._delegate,e)}updateProfile(e){return go(this._delegate,e)}verifyBeforeUpdateEmail(e,t){return fo(this._delegate,e,t)}get emailVerified(){return this._delegate.emailVerified}get isAnonymous(){return this._delegate.isAnonymous}get metadata(){return this._delegate.metadata}get phoneNumber(){return this._delegate.phoneNumber}get providerData(){return this._delegate.providerData}get refreshToken(){return this._delegate.refreshToken}get tenantId(){return this._delegate.tenantId}get displayName(){return this._delegate.displayName}get email(){return this._delegate.email}get photoURL(){return this._delegate.photoURL}get providerId(){return this._delegate.providerId}get uid(){return this._delegate.uid}get auth(){return this._delegate.auth}}Vh.USER_MAP=new WeakMap;let qh=m;class Bh{constructor(e,t){var r,n;this.app=e,t.isInitialized()?this._delegate=t.getImmediate():(r=e.options.apiKey,qh(r,"invalid-api-key",{appName:e.name}),qh(r,"invalid-api-key",{appName:e.name}),n="undefined"!=typeof window?Dh:void 0,this._delegate=t.initialize({options:{persistence:((e,t)=>{var r=((e,t)=>{var r=Rh();if(!r)return[];var n=Bs(Ah,e,t);switch(r.getItem(n)){case Sh.NONE:return[qs];case Sh.LOCAL:return[Qo,Oo];case Sh.SESSION:return[Oo];default:return[]}})(e,t);if("undefined"==typeof self||r.includes(Qo)||r.push(Qo),"undefined"!=typeof window)for(var n of[Do,Oo])r.includes(n)||r.push(n);return r.includes(qs)||r.push(qs),r})(r,e.name),popupRedirectResolver:n}}),this._delegate._updateErrorMap(Wi)),this.linkUnderlyingAuth()}get emulatorConfig(){return this._delegate.emulatorConfig}get currentUser(){return this._delegate.currentUser?Vh.getOrCreate(this._delegate.currentUser):null}get languageCode(){return this._delegate.languageCode}set languageCode(e){this._delegate.languageCode=e}get settings(){return this._delegate.settings}get tenantId(){return this._delegate.tenantId}set tenantId(e){this._delegate.tenantId=e}useDeviceLanguage(){this._delegate.useDeviceLanguage()}signOut(){return this._delegate.signOut()}useEmulator(e,t){ma(this._delegate,e,t)}applyActionCode(e){return ho(this._delegate,e)}checkActionCode(e){return co(this._delegate,e)}confirmPasswordReset(e,t){return(async(t,e,r)=>{await wa(w(t),{oobCode:e,newPassword:r}).catch(async e=>{throw"auth/password-does-not-meet-requirements"===e.code&&lo(t),e})})(this._delegate,e,t)}async createUserWithEmailAndPassword(e,t){return Lh(this._delegate,(async(t,e,r)=>{var n,i;return h(t.app)?Promise.reject(Zi(t)):(i=await ga(n=na(t),{returnSecureToken:!0,email:e,password:r,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",za,"EMAIL_PASSWORD_PROVIDER").catch(e=>{throw"auth/password-does-not-meet-requirements"===e.code&&lo(t),e}),i=await Ka._fromIdTokenResponse(n,"signIn",i),await n._updateCurrentUser(i.user),i)})(this._delegate,e,t))}fetchProvidersForEmail(e){return this.fetchSignInMethodsForEmail(e)}fetchSignInMethodsForEmail(e){return uo(this._delegate,e)}isSignInWithEmailLink(e){return this._delegate,e=e,"EMAIL_SIGNIN"===Da.parseLink(e)?.operation}async getRedirectResult(){qh(Eh(),this._delegate,"operation-not-supported-in-this-environment");e=this._delegate,t=Dh,await na(e)._initializationPromise;var e,t,r=await Sl(e,t,!1);return r?Lh(this._delegate,Promise.resolve(r)):{credential:null,user:null}}addFrameworkForLogging(e){na(this._delegate)._logFramework(e)}onAuthStateChanged(e,t,r){var{next:n,error:i,complete:s}=jh(e,t,r);return this._delegate.onAuthStateChanged(n,i,s)}onIdTokenChanged(e,t,r){var{next:n,error:i,complete:s}=jh(e,t,r);return this._delegate.onIdTokenChanged(n,i,s)}sendSignInLinkToEmail(e,t){return(async(e,t,r)=>{let n=na(e);var i={requestType:"EMAIL_SIGNIN",email:t,clientType:"CLIENT_TYPE_WEB"};e=i,m((t=r).handleCodeInApp,n,"argument-error"),t&&oo(n,e,t),await ga(n,i,"getOobCode",Ca,"EMAIL_PASSWORD_PROVIDER")})(this._delegate,e,t)}sendPasswordResetEmail(e,t){return(async(e,t,r)=>{var n=na(e),i={requestType:"PASSWORD_RESET",email:t,clientType:"CLIENT_TYPE_WEB"};r&&oo(n,i,r),await ga(n,i,"getOobCode",Ea,"EMAIL_PASSWORD_PROVIDER")})(this._delegate,e,t||void 0)}async setPersistence(e){var t,r;t=this._delegate,r=e,kh(Object.values(Sh).includes(r),t,"invalid-persistence-type"),ae()?kh(r!==Sh.SESSION,t,"unsupported-persistence-type"):ne()?kh(r===Sh.NONE,t,"unsupported-persistence-type"):Th()?kh(r===Sh.NONE||r===Sh.LOCAL&&ue(),t,"unsupported-persistence-type"):kh(r===Sh.NONE||Ih(),t,"unsupported-persistence-type");let n;switch(e){case Sh.SESSION:n=Oo;break;case Sh.LOCAL:var i=await Us(Qo)._isAvailable();n=i?Qo:Do;break;case Sh.NONE:n=qs;break;default:return Yi("argument-error",{appName:this._delegate.name})}return this._delegate.setPersistence(n)}signInAndRetrieveDataWithCredential(e){return this.signInWithCredential(e)}signInAnonymously(){return Lh(this._delegate,(async e=>{var t,r;return h(e.app)?Promise.reject(Zi(e)):(await(t=na(e))._initializationPromise,t.currentUser?.isAnonymous?new Ka({user:t.currentUser,providerId:null,operationType:"signIn"}):(r=await za(t,{returnSecureToken:!0}),r=await Ka._fromIdTokenResponse(t,"signIn",r,!0),await t._updateCurrentUser(r.user),r))})(this._delegate))}signInWithCredential(e){return Lh(this._delegate,eo(this._delegate,e))}signInWithCustomToken(e){return Lh(this._delegate,no(this._delegate,e))}signInWithEmailAndPassword(e,t){return Lh(this._delegate,(r=this._delegate,e=e,t=t,h(r.app)?Promise.reject(Zi(r)):eo(w(r),xa.credential(e,t)).catch(async e=>{throw"auth/password-does-not-meet-requirements"===e.code&&lo(r),e})));var r}signInWithEmailLink(e,t){return Lh(this._delegate,(async(e,t,r)=>{var n,i;return h(e.app)?Promise.reject(Zi(e)):(n=w(e),m((i=xa.credentialWithLink(t,r||is()))._tenantId===(n.tenantId||null),n,"tenant-id-mismatch"),eo(n,i))})(this._delegate,e,t))}signInWithPhoneNumber(e,t){return Fh(this._delegate,(async(e,t,r)=>{if(h(e.app))return Promise.reject(Zi(e));let n=na(e);var i=await sl(n,t,w(r));return new il(i,e=>eo(n,e))})(this._delegate,e,t))}async signInWithPopup(e){return qh(Eh(),this._delegate,"operation-not-supported-in-this-environment"),Lh(this._delegate,(async(e,t,r)=>{var n,i;return h(e.app)?Promise.reject(Ji(e,"operation-not-supported-in-this-environment")):(n=na(e),es(e,t,Oa),i=ll(n,r),new gl(n,"signInViaPopup",t,i).executeNotNull())})(this._delegate,e,Dh))}async signInWithRedirect(e){return qh(Eh(),this._delegate,"operation-not-supported-in-this-environment"),await Nh(this._delegate),Tl(this._delegate,e,Dh)}updateCurrentUser(e){return this._delegate.updateCurrentUser(e)}verifyPasswordResetCode(e){return(async(e,t)=>{var r=(await co(w(e),t)).data;return r.email})(this._delegate,e)}unwrap(){return this._delegate}_delete(){return this._delegate._delete()}linkUnderlyingAuth(){this._delegate.wrapped=()=>this}}function jh(e,t,r){let n=e,i=("function"!=typeof e&&({next:n,error:t,complete:r}=e),n);return{next:e=>i(e&&Vh.getOrCreate(e)),error:t,complete:r}}Bh.Persistence=Sh;class zh{static credential(e,t){return ol.credential(e,t)}constructor(){this.providerId="phone",this._delegate=new ol(xh(or.auth()))}verifyPhoneNumber(e,t){return this._delegate.verifyPhoneNumber(e,t)}unwrap(){return this._delegate}}zh.PHONE_SIGN_IN_METHOD=ol.PHONE_SIGN_IN_METHOD,zh.PROVIDER_ID=ol.PROVIDER_ID;let Kh=m;class Wh{constructor(e,t,r=or.app()){Kh(r.options?.apiKey,"invalid-api-key",{appName:r.name}),this._delegate=new nl(r.auth(),e,t),this.type=this._delegate.type}clear(){this._delegate.clear()}render(){return this._delegate.render()}verify(){return this._delegate.verify()}}(t=or).INTERNAL.registerComponent(new c("auth-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),r=e.getProvider("auth");return new Bh(t,r)},"PUBLIC").setServiceProps({ActionCodeInfo:{Operation:{EMAIL_SIGNIN:zi.EMAIL_SIGNIN,PASSWORD_RESET:zi.PASSWORD_RESET,RECOVER_EMAIL:zi.RECOVER_EMAIL,REVERT_SECOND_FACTOR_ADDITION:zi.REVERT_SECOND_FACTOR_ADDITION,VERIFY_AND_CHANGE_EMAIL:zi.VERIFY_AND_CHANGE_EMAIL,VERIFY_EMAIL:zi.VERIFY_EMAIL}},EmailAuthProvider:xa,FacebookAuthProvider:Fa,GithubAuthProvider:Va,GoogleAuthProvider:Ua,OAuthProvider:La,SAMLAuthProvider:Ba,PhoneAuthProvider:zh,PhoneMultiFactorGenerator:rh,RecaptchaVerifier:Wh,TwitterAuthProvider:ja,Auth:Bh,AuthCredential:ya,Error:fe}).setInstantiationMode("LAZY").setMultipleInstances(!1)),t.registerVersion("@firebase/auth-compat","0.6.5");let Hh="@firebase/database",Gh="";function $h(e){Gh=e}class Qh{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),_e(t))}get(e){var t=this.domStorage_.getItem(this.prefixedName_(e));return null==t?null:ve(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}class Yh{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){null==t?delete this.cache_[e]:this.cache_[e]=t}get(e){return we(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}function Jh(e){try{var t;if("undefined"!=typeof window&&void 0!==window[e])return(t=window[e]).setItem("firebase:sentinel","cache"),t.removeItem("firebase:sentinel"),new Qh(t)}catch(e){}return new Yh}var Xh;function Zh(e){var t=(t=>{var r,n,i=[];let s=0;for(let a=0;a<t.length;a++){let e=t.charCodeAt(a);55296<=e&&e<=56319&&(r=e-55296,a++,g(a<t.length,"Surrogate pair missing trail surrogate."),n=t.charCodeAt(a)-56320,e=65536+(r<<10)+n),e<128?i[s++]=e:(e<2048?i[s++]=e>>6|192:(e<65536?i[s++]=e>>12|224:(i[s++]=e>>18|240,i[s++]=e>>12&63|128),i[s++]=e>>6&63|128),i[s++]=63&e|128)}return i})(e),r=new Ne,t=(r.update(t),r.digest());return a.encodeByteArray(t)}function ec(t){return function(...e){fc(t,...e)}}function tc(...e){var t="FIREBASE INTERNAL ERROR: "+cc(...e);lc.error(t)}function rc(e,t){return e===t?0:e<t?-1:1}function nc(e,t){if(t&&e in t)return t[e];throw new Error("Missing required key ("+e+") in object: "+_e(t))}function ic(e){if("object"!=typeof e||null===e)return _e(e);var t,r=[];for(t in e)r.push(t);r.sort();let n="{";for(let i=0;i<r.length;i++)0!==i&&(n+=","),n=(n=n+_e(r[i])+":")+ic(e[r[i]]);return n+="}"}function sc(e,t){var r=e.length;if(r<=t)return[e];var n=[];for(let i=0;i<r;i+=t)i+t>r?n.push(e.substring(i,r)):n.push(e.substring(i,i+t));return n}let ac=Jh("localStorage"),oc=Jh("sessionStorage"),lc=new Xe("@firebase/database"),hc=(()=>{let e=1;return function(){return e++}})(),cc=function(...e){let t="";for(let n=0;n<e.length;n++){var r=e[n];Array.isArray(r)||r&&"object"==typeof r&&"number"==typeof r.length?t+=cc.apply(null,r):t+="object"==typeof r?_e(r):r,t+=" "}return t},uc=null,dc=!0,pc=function(e,t){g(!t||!0===e||!1===e,"Can't turn on custom loggers persistently."),!0===e?(lc.logLevel=p.VERBOSE,uc=lc.log.bind(lc),t&&oc.set("logging_enabled",!0)):"function"==typeof e?uc=e:(uc=null,oc.remove("logging_enabled"))},fc=function(...e){var t;!0===dc&&(dc=!1,null===uc)&&!0===oc.get("logging_enabled")&&pc(!0),uc&&(t=cc.apply(null,e),uc(t))},gc=function(...e){var t="FIREBASE FATAL ERROR: "+cc(...e);throw lc.error(t),new Error(t)},mc=function(...e){var t="FIREBASE WARNING: "+cc(...e);lc.warn(t)},vc=function(){"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&mc("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().")},_c=function(e){return"number"==typeof e&&(e!=e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY)},yc="[MIN_NAME]",wc="[MAX_NAME]",bc=function(e,t){var r,n;return e===t?0:e===yc||t===wc?-1:t===yc||e===wc?1:(r=Ec(e),n=Ec(t),null!==r?null!==n?r-n==0?e.length-t.length:r-n:-1:null===n&&e<t?-1:1)};function Ic(e,t){for(var r in e)e.hasOwnProperty(r)&&t(r,e[r])}function Tc(e){g(!_c(e),"Invalid JSON number");let t,r,n,i,s;0===e?(r=0,n=0,t=1/e==-1/0?1:0):(t=e<0,e=Math.abs(e),n=e>=Math.pow(2,-1022)?(i=Math.min(Math.floor(Math.log(e)/Math.LN2),1023),r=i+1023,Math.round(e*Math.pow(2,52-i)-Math.pow(2,52))):(r=0,Math.round(e/Math.pow(2,-1074))));var a=[];for(s=52;s;--s)a.push(n%2?1:0),n=Math.floor(n/2);for(s=11;s;--s)a.push(r%2?1:0),r=Math.floor(r/2);a.push(t?1:0),a.reverse();var o=a.join("");let l="";for(s=0;s<64;s+=8){let e=parseInt(o.substr(s,8),2).toString(16);1===e.length&&(e="0"+e),l+=e}return l.toLowerCase()}function Ec(e){if(Sc.test(e)){var t=Number(e);if(t>=kc&&t<=Ac)return t}return null}function Cc(e,t){var r=setTimeout(e,t);return"number"==typeof r&&"undefined"!=typeof Deno&&Deno.unrefTimer?Deno.unrefTimer(r):"object"==typeof r&&r.unref&&r.unref(),r}let Sc=new RegExp("^-?(0*)\\d{1,10}$"),kc=-2147483648,Ac=2147483647,Nc=function(e){try{e()}catch(t){setTimeout(()=>{var e=t.stack||"";throw mc("Exception was thrown by user callback.",e),t},Math.floor(0))}};class Rc{constructor(e,t){this.appCheckProvider=t,this.appName=e.name,h(e)&&e.settings.appCheckToken&&(this.serverAppAppCheckToken=e.settings.appCheckToken),this.appCheck=t?.getImmediate({optional:!0}),this.appCheck||t?.get().then(e=>this.appCheck=e)}getToken(r){if(this.serverAppAppCheckToken){if(r)throw new Error("Attempted reuse of `FirebaseServerApp.appCheckToken` after previous usage failed.");return Promise.resolve({token:this.serverAppAppCheckToken})}return this.appCheck?this.appCheck.getToken(r):new Promise((e,t)=>{setTimeout(()=>{this.appCheck?this.getToken(r).then(e,t):e(null)},0)})}addTokenChangeListener(t){this.appCheckProvider?.get().then(e=>e.addTokenListener(t))}notifyForInvalidToken(){mc(`Provided AppCheck credentials for the app named "${this.appName}" `+"are invalid. This usually indicates your app was not initialized correctly.")}}class Pc{constructor(e,t,r){this.appName_=e,this.firebaseOptions_=t,this.authProvider_=r,this.auth_=null,this.auth_=r.getImmediate({optional:!0}),this.auth_||r.onInit(e=>this.auth_=e)}getToken(r){return this.auth_?this.auth_.getToken(r).catch(e=>e&&"auth/token-not-initialized"===e.code?(fc("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(e)):new Promise((e,t)=>{setTimeout(()=>{this.auth_?this.getToken(r).then(e,t):e(null)},0)})}addTokenChangeListener(t){this.auth_?this.auth_.addAuthTokenListener(t):this.authProvider_.get().then(e=>e.addAuthTokenListener(t))}removeTokenChangeListener(t){this.authProvider_.get().then(e=>e.removeAuthTokenListener(t))}notifyForInvalidToken(){let e='Provided authentication credentials for the app named "'+this.appName_+'" are invalid. This usually indicates your app was not initialized correctly. ';"credential"in this.firebaseOptions_?e+='Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':"serviceAccount"in this.firebaseOptions_?e+='Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':e+='Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.',mc(e)}}class Dc{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}Dc.OWNER="owner";let xc=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,Oc="websocket",Mc="long_polling";class Lc{constructor(e,t,r,n,i=!1,s="",a=!1,o=!1,l=null){this.secure=t,this.namespace=r,this.webSocketOnly=n,this.nodeAdmin=i,this.persistenceKey=s,this.includeNamespaceInQueryParams=a,this.isUsingEmulator=o,this.emulatorOptions=l,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=ac.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())&&ac.set("host:"+this._host,this.internalHost)}toString(){let e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e}toURLString(){var e=this.secure?"https://":"http://",t=this.includeNamespaceInQueryParams?"?ns="+this.namespace:"";return e+this.host+"/"+t}}function Fc(e,t,r){g("string"==typeof t,"typeof type must == string"),g("object"==typeof r,"typeof params must == object");let n;if(t===Oc)n=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?";else{if(t!==Mc)throw new Error("Unknown connection type: "+t);n=(e.secure?"https://":"http://")+e.internalHost+"/.lp?"}((t=e).host!==t.internalHost||t.isCustomHost()||t.includeNamespaceInQueryParams)&&(r.ns=e.namespace);let i=[];return Ic(r,(e,t)=>{i.push(e+"="+t)}),n+i.join("&")}class Uc{constructor(){this.counters_={}}incrementCounter(e,t=1){we(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return W(void 0,this.counters_)}}let Vc={},qc={};function Bc(e){var t=e.toString();return Vc[t]||(Vc[t]=new Uc),Vc[t]}class jc{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]&&Nc(()=>{this.onMessage_(e[t])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}class zc{constructor(e,t,r,n,i,s,a){this.connId=e,this.repoInfo=t,this.applicationId=r,this.appCheckToken=n,this.authToken=i,this.transportSessionId=s,this.lastSessionId=a,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=ec(e),this.stats_=Bc(t),this.urlFn=e=>(this.appCheckToken&&(e.ac=this.appCheckToken),Fc(t,Mc,e))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new jc(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null},Math.floor(3e4));var r=()=>{var e;this.isClosed_||(this.scriptTagHolder=new Kc((...e)=>{var[t,r,n,,,]=e;if(this.incrementIncomingBytes_(e),this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,"start"===t)this.id=r,this.password=n;else{if("close"!==t)throw new Error("Unrecognized command received: "+t);r?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(r,()=>{this.onClosed_()})):this.onClosed_()}},(...e)=>{var[t,r]=e;this.incrementIncomingBytes_(e),this.myPacketOrderer.handleResponse(t,r)},()=>{this.onClosed_()},this.urlFn),(e={start:"t"}).ser=Math.floor(1e8*Math.random()),this.scriptTagHolder.uniqueCallbackIdentifier&&(e.cb=this.scriptTagHolder.uniqueCallbackIdentifier),e.v="5",this.transportSessionId&&(e.s=this.transportSessionId),this.lastSessionId&&(e.ls=this.lastSessionId),this.applicationId&&(e.p=this.applicationId),this.appCheckToken&&(e.ac=this.appCheckToken),"undefined"!=typeof location&&location.hostname&&xc.test(location.hostname)&&(e.r="f"),e=this.urlFn(e),this.log_("Connecting via long-poll to "+e),this.scriptTagHolder.addTag(e,()=>{}))};if("complete"===document.readyState)r();else{let e=!1,t=function(){document.body?e||(e=!0,r()):setTimeout(t,Math.floor(10))};document.addEventListener?(document.addEventListener("DOMContentLoaded",t,!1),window.addEventListener("load",t,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",()=>{"complete"===document.readyState&&t()}),window.attachEvent("onload",t))}}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){zc.forceAllow_=!0}static forceDisallow(){zc.forceDisallow_=!0}static isAvailable(){return!!zc.forceAllow_||!(zc.forceDisallow_||"undefined"==typeof document||null==document.createElement||"object"==typeof window&&window.chrome&&window.chrome.extension&&!/^chrome/.test(window.location.href)||"object"==typeof Windows&&"object"==typeof Windows.UI)}markConnectionHealthy(){}shutdown_(){this.isClosed_=!0,this.scriptTagHolder&&(this.scriptTagHolder.close(),this.scriptTagHolder=null),this.myDisconnFrame&&(document.body.removeChild(this.myDisconnFrame),this.myDisconnFrame=null),this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null)}onClosed_(){this.isClosed_||(this.log_("Longpoll is closing itself"),this.shutdown_(),this.onDisconnect_&&(this.onDisconnect_(this.everConnected_),this.onDisconnect_=null))}close(){this.isClosed_||(this.log_("Longpoll is being closed."),this.shutdown_())}send(e){var t=_e(e),t=(this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length),o(t)),r=sc(t,1840);for(let n=0;n<r.length;n++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,r.length,r[n]),this.curSegmentNum++}addDisconnectPingFrame(e,t){this.myDisconnFrame=document.createElement("iframe");var r={dframe:"t"};r.id=e,r.pw=t,this.myDisconnFrame.src=this.urlFn(r),this.myDisconnFrame.style.display="none",document.body.appendChild(this.myDisconnFrame)}incrementIncomingBytes_(e){var t=_e(e).length;this.bytesReceived+=t,this.stats_.incrementCounter("bytes_received",t)}}class Kc{constructor(t,r,e,n){this.onDisconnect=e,this.urlFn=n,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(1e8*Math.random()),this.sendNewPolls=!0;{this.uniqueCallbackIdentifier=hc(),window["pLPCommand"+this.uniqueCallbackIdentifier]=t,window["pRTLPCB"+this.uniqueCallbackIdentifier]=r,this.myIFrame=Kc.createIFrame_();let e="";this.myIFrame.src&&"javascript:"===this.myIFrame.src.substr(0,"javascript:".length)&&(i=document.domain,e='<script>document.domain="'+i+'";<\/script>');var i="<html><body>"+e+"</body></html>";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(i),this.myIFrame.doc.close()}catch(e){fc("frame writing exception"),e.stack&&fc(e.stack),fc(e)}}}static createIFrame_(){var t=document.createElement("iframe");if(t.style.display="none",!document.body)throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";document.body.appendChild(t);try{t.contentWindow.document||fc("No IE domain setting required")}catch(e){var r=document.domain;t.src="javascript:void((function(){document.open();document.domain='"+r+"';document.close();})())"}return t.contentDocument?t.doc=t.contentDocument:t.contentWindow?t.doc=t.contentWindow.document:t.document&&(t.doc=t.document),t}close(){this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.textContent="",setTimeout(()=>{null!==this.myIFrame&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)},Math.floor(0)));var e=this.onDisconnect;e&&(this.onDisconnect=null,e())}startLongPoll(e,t){for(this.myID=e,this.myPW=t,this.alive=!0;this.newRequest_(););}newRequest_(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.size<(0<this.pendingSegs.length?2:1)){this.currentSerial++;var r={},r=(r.id=this.myID,r.pw=this.myPW,r.ser=this.currentSerial,this.urlFn(r));let e="",t=0;for(;0<this.pendingSegs.length;){if(!(this.pendingSegs[0].d.length+30+e.length<=1870))break;var n=this.pendingSegs.shift();e=e+"&seg"+t+"="+n.seg+"&ts"+t+"="+n.ts+"&d"+t+"="+n.d,t++}return r+=e,this.addLongPollTag_(r,this.currentSerial),!0}return!1}enqueueSegment(e,t,r){this.pendingSegs.push({seg:e,ts:t,d:r}),this.alive&&this.newRequest_()}addLongPollTag_(e,t){this.outstandingRequests.add(t);let r=()=>{this.outstandingRequests.delete(t),this.newRequest_()},n=setTimeout(r,Math.floor(25e3));this.addTag(e,()=>{clearTimeout(n),r()})}addTag(e,r){setTimeout(()=>{try{if(this.sendNewPolls){let t=this.myIFrame.doc.createElement("script");t.type="text/javascript",t.async=!0,t.src=e,t.onload=t.onreadystatechange=function(){var e=t.readyState;e&&"loaded"!==e&&"complete"!==e||(t.onload=t.onreadystatechange=null,t.parentNode&&t.parentNode.removeChild(t),r())},t.onerror=()=>{fc("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(t)}}catch(e){}},Math.floor(1))}}let Wc=null;"undefined"!=typeof MozWebSocket?Wc=MozWebSocket:"undefined"!=typeof WebSocket&&(Wc=WebSocket);class Hc{constructor(e,t,r,n,i,s,a){this.connId=e,this.applicationId=r,this.appCheckToken=n,this.authToken=i,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=ec(this.connId),this.stats_=Bc(t),this.connURL=Hc.connectionURL_(t,s,a,n,r),this.nodeAdmin=t.nodeAdmin}static connectionURL_(e,t,r,n,i){var s={v:"5"};return"undefined"!=typeof location&&location.hostname&&xc.test(location.hostname)&&(s.r="f"),t&&(s.s=t),r&&(s.ls=r),n&&(s.ac=n),i&&(s.p=i),Fc(e,Oc,s)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,ac.set("previous_websocket_failure",!0);try{le(),this.mySock=new Wc(this.connURL,[],void 0)}catch(e){this.log_("Error instantiating WebSocket.");var r=e.message||e.data;return r&&this.log_(r),void this.onClosed_()}this.mySock.onopen=()=>{this.log_("Websocket connected."),this.everConnected_=!0},this.mySock.onclose=()=>{this.log_("Websocket connection was disconnected."),this.mySock=null,this.onClosed_()},this.mySock.onmessage=e=>{this.handleIncomingFrame(e)},this.mySock.onerror=e=>{this.log_("WebSocket error. Closing connection.");var t=e.message||e.data;t&&this.log_(t),this.onClosed_()}}start(){}static forceDisallow(){Hc.forceDisallow_=!0}static isAvailable(){let e=!1;var t;return!(e="undefined"!=typeof navigator&&navigator.userAgent&&(t=navigator.userAgent.match(/Android ([0-9]{0,}\.[0-9]{0,})/))&&1<t.length&&parseFloat(t[1])<4.4?!0:e)&&null!==Wc&&!Hc.forceDisallow_}static previouslyFailed(){return ac.isInMemoryStorage||!0===ac.get("previous_websocket_failure")}markConnectionHealthy(){ac.remove("previous_websocket_failure")}appendFrame_(e){var t;this.frames.push(e),this.frames.length===this.totalFrames&&(t=this.frames.join(""),this.frames=null,t=ve(t),this.onMessage(t))}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if(g(null===this.frames,"We already have a frame buffer"),e.length<=6){var t=Number(e);if(!isNaN(t))return this.handleNewFrameCount_(t),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){var t;null!==this.mySock&&(t=e.data,this.bytesReceived+=t.length,this.stats_.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),null!==this.frames?this.appendFrame_(t):null!==(t=this.extractFrameCount_(t))&&this.appendFrame_(t))}send(e){this.resetKeepAlive();var t=_e(e),r=(this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length),sc(t,16384));1<r.length&&this.sendString_(String(r.length));for(let n=0;n<r.length;n++)this.sendString_(r[n])}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)}}}Hc.responsesRequiredToBeHealthy=2,Hc.healthyTimeout=3e4;class Gc{static get ALL_TRANSPORTS(){return[zc,Hc]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}constructor(e){this.initTransports_(e)}initTransports_(e){var t=Hc&&Hc.isAvailable();let r=t&&!Hc.previouslyFailed();if(e.webSocketOnly&&(t||mc("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),r=!0),r)this.transports_=[Hc];else{var n,i=this.transports_=[];for(n of Gc.ALL_TRANSPORTS)n&&n.isAvailable()&&i.push(n);Gc.globalTransportInitialized_=!0}}initialTransport(){if(0<this.transports_.length)return this.transports_[0];throw new Error("No transports available")}upgradeTransport(){return 1<this.transports_.length?this.transports_[1]:null}}Gc.globalTransportInitialized_=!1;class $c{constructor(e,t,r,n,i,s,a,o,l,h){this.id=e,this.repoInfo_=t,this.applicationId_=r,this.appCheckToken_=n,this.authToken_=i,this.onMessage_=s,this.onReady_=a,this.onDisconnect_=o,this.onKill_=l,this.lastSessionId=h,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=ec("c:"+this.id+":"),this.transportManager_=new Gc(t),this.log_("Connection created"),this.start_()}start_(){var e=this.transportManager_.initialTransport();this.conn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,null,this.lastSessionId),this.primaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;let t=this.connReceiver_(this.conn_),r=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,r)},Math.floor(0));e=e.healthyTimeout||0;0<e&&(this.healthyTimeout_=Cc(()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&102400<this.conn_.bytesReceived?(this.log_("Connection exceeded healthy timeout but has received "+this.conn_.bytesReceived+" bytes. Marking connection healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()):this.conn_&&10240<this.conn_.bytesSent?this.log_("Connection exceeded healthy timeout but has sent "+this.conn_.bytesSent+" bytes. Leaving connection alive."):(this.log_("Closing unhealthy connection after timeout."),this.close()))},Math.floor(e)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(t){return e=>{t===this.conn_?this.onConnectionLost_(e):t===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(t){return e=>{2!==this.state_&&(t===this.rx_?this.onPrimaryMessageReceived_(e):t===this.secondaryConn_?this.onSecondaryMessageReceived_(e):this.log_("message on old connection"))}}sendRequest(e){this.sendData_({t:"d",d:e})}tryCleanupConnection(){this.tx_===this.secondaryConn_&&this.rx_===this.secondaryConn_&&(this.log_("cleaning up and promoting a connection: "+this.secondaryConn_.connId),this.conn_=this.secondaryConn_,this.secondaryConn_=null)}onSecondaryControl_(e){var t;"t"in e&&("a"===(t=e.t)?this.upgradeIfSecondaryHealthy_():"r"===t?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),this.tx_!==this.secondaryConn_&&this.rx_!==this.secondaryConn_||this.close()):"o"===t&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_()))}onSecondaryMessageReceived_(e){var t=nc("t",e),r=nc("d",e);if("c"===t)this.onSecondaryControl_(r);else{if("d"!==t)throw new Error("Unknown protocol layer: "+t);this.pendingDataMessages.push(r)}}upgradeIfSecondaryHealthy_(){this.secondaryResponsesRequired_<=0?(this.log_("Secondary connection is healthy."),this.isHealthy_=!0,this.secondaryConn_.markConnectionHealthy(),this.proceedWithUpgrade_()):(this.log_("sending ping on secondary."),this.secondaryConn_.send({t:"c",d:{t:"p",d:{}}}))}proceedWithUpgrade_(){this.secondaryConn_.start(),this.log_("sending client ack on secondary"),this.secondaryConn_.send({t:"c",d:{t:"a",d:{}}}),this.log_("Ending transmission on primary"),this.conn_.send({t:"c",d:{t:"n",d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()}onPrimaryMessageReceived_(e){var t=nc("t",e),r=nc("d",e);"c"===t?this.onControl_(r):"d"===t&&this.onDataMessage_(r)}onDataMessage_(e){this.onPrimaryResponse_(),this.onMessage_(e)}onPrimaryResponse_(){this.isHealthy_||(this.primaryResponsesRequired_--,this.primaryResponsesRequired_<=0&&(this.log_("Primary connection is healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()))}onControl_(e){var t=nc("t",e);if("d"in e){var r=e.d;if("h"===t){var n={...r};this.repoInfo_.isUsingEmulator&&(n.h=this.repoInfo_.host),this.onHandshake_(n)}else if("n"===t){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(let e=0;e<this.pendingDataMessages.length;++e)this.onDataMessage_(this.pendingDataMessages[e]);this.pendingDataMessages=[],this.tryCleanupConnection()}else"s"===t?this.onConnectionShutdown_(r):"r"===t?this.onReset_(r):"e"===t?tc("Server Error: "+r):"o"===t?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):tc("Unknown control packet command: "+t)}}onHandshake_(e){var t=e.ts,r=e.v,n=e.h;this.sessionId=e.s,this.repoInfo_.host=n,0===this.state_&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,t),"5"!==r&&mc("Protocol version mismatch detected"),this.tryStartUpgrade_())}tryStartUpgrade_(){var e=this.transportManager_.upgradeTransport();e&&this.startUpgrade_(e)}startUpgrade_(e){this.secondaryConn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,this.sessionId),this.secondaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;var t=this.connReceiver_(this.secondaryConn_),r=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(t,r),Cc(()=>{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):Cc(()=>{this.sendPingOnPrimaryIfNecessary_()},Math.floor(5e3))}sendPingOnPrimaryIfNecessary_(){this.isHealthy_||1!==this.state_||(this.log_("sending ping on primary."),this.sendData_({t:"c",d:{t:"p",d:{}}}))}onSecondaryConnectionLost_(){var e=this.secondaryConn_;this.secondaryConn_=null,this.tx_!==e&&this.rx_!==e||this.close()}onConnectionLost_(e){this.conn_=null,e||0!==this.state_?1===this.state_&&this.log_("Realtime connection lost."):(this.log_("Realtime connection failed."),this.repoInfo_.isCacheableHost()&&(ac.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 Qc{put(e,t,r,n){}merge(e,t,r,n){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,t,r){}onDisconnectMerge(e,t,r){}onDisconnectCancel(e,t){}reportStats(e){}}class Yc{constructor(e){this.allowedEvents_=e,this.listeners_={},g(Array.isArray(e)&&0<e.length,"Requires a non-empty array")}trigger(t,...r){if(Array.isArray(this.listeners_[t])){var n=[...this.listeners_[t]];for(let e=0;e<n.length;e++)n[e].callback.apply(n[e].context,r)}}on(e,t,r){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:r});var n=this.getInitialEvent(e);n&&t.apply(r,n)}off(e,t,r){this.validateEventType_(e);var n=this.listeners_[e]||[];for(let i=0;i<n.length;i++)if(n[i].callback===t&&(!r||r===n[i].context))return void n.splice(i,1)}validateEventType_(t){g(this.allowedEvents_.find(e=>e===t),"Unknown event: "+t)}}class Jc extends Yc{static getInstance(){return new Jc}constructor(){super(["online"]),this.online_=!0,"undefined"==typeof window||void 0===window.addEventListener||re()||(window.addEventListener("online",()=>{this.online_||(this.online_=!0,this.trigger("online",!0))},!1),window.addEventListener("offline",()=>{this.online_&&(this.online_=!1,this.trigger("online",!1))},!1))}getInitialEvent(e){return g("online"===e,"Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}let Xc=32,Zc=768;class f{constructor(r,e){if(void 0===e){this.pieces_=r.split("/");let e=0;for(let t=0;t<this.pieces_.length;t++)0<this.pieces_[t].length&&(this.pieces_[e]=this.pieces_[t],e++);this.pieces_.length=e,this.pieceNum_=0}else this.pieces_=r,this.pieceNum_=e}toString(){let e="";for(let t=this.pieceNum_;t<this.pieces_.length;t++)""!==this.pieces_[t]&&(e+="/"+this.pieces_[t]);return e||"/"}}function v(){return new f("")}function _(e){return e.pieceNum_>=e.pieces_.length?null:e.pieces_[e.pieceNum_]}function eu(e){return e.pieces_.length-e.pieceNum_}function y(e){let t=e.pieceNum_;return t<e.pieces_.length&&t++,new f(e.pieces_,t)}function tu(e){return e.pieceNum_<e.pieces_.length?e.pieces_[e.pieces_.length-1]:null}function ru(e,t=0){return e.pieces_.slice(e.pieceNum_+t)}function nu(e){if(e.pieceNum_>=e.pieces_.length)return null;var t=[];for(let r=e.pieceNum_;r<e.pieces_.length-1;r++)t.push(e.pieces_[r]);return new f(t,0)}function iu(e,t){var r=[];for(let i=e.pieceNum_;i<e.pieces_.length;i++)r.push(e.pieces_[i]);if(t instanceof f)for(let e=t.pieceNum_;e<t.pieces_.length;e++)r.push(t.pieces_[e]);else{var n=t.split("/");for(let e=0;e<n.length;e++)0<n[e].length&&r.push(n[e])}return new f(r,0)}function b(e){return e.pieceNum_>=e.pieces_.length}function su(e,t){var r=_(e),n=_(t);if(null===r)return t;if(r===n)return su(y(e),y(t));throw new Error("INTERNAL ERROR: innerPath ("+t+") is not within outerPath ("+e+")")}function au(e,t){var r=ru(e,0),n=ru(t,0);for(let s=0;s<r.length&&s<n.length;s++){var i=bc(r[s],n[s]);if(0!==i)return i}return r.length===n.length?0:r.length<n.length?-1:1}function ou(e,t){if(eu(e)!==eu(t))return!1;for(let r=e.pieceNum_,n=t.pieceNum_;r<=e.pieces_.length;r++,n++)if(e.pieces_[r]!==t.pieces_[n])return!1;return!0}function lu(e,t){let r=e.pieceNum_,n=t.pieceNum_;if(eu(e)>eu(t))return!1;for(;r<e.pieces_.length;){if(e.pieces_[r]!==t.pieces_[n])return!1;++r,++n}return!0}class hu{constructor(e,t){this.errorPrefix_=t,this.parts_=ru(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let r=0;r<this.parts_.length;r++)this.byteLength_+=Le(this.parts_[r]);cu(this)}}function cu(e){if(e.byteLength_>Zc)throw new Error(e.errorPrefix_+"has a key path longer than "+Zc+" bytes ("+e.byteLength_+").");if(e.parts_.length>Xc)throw new Error(e.errorPrefix_+"path specified exceeds the maximum depth that can be written ("+Xc+") or object contains a cycle "+uu(e))}function uu(e){return 0===e.parts_.length?"":"in property '"+e.parts_.join(".")+"'"}class du extends Yc{static getInstance(){return new du}constructor(){super(["visible"]);let t,e;"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(e="visibilitychange",t="hidden"):void 0!==document.mozHidden?(e="mozvisibilitychange",t="mozHidden"):void 0!==document.msHidden?(e="msvisibilitychange",t="msHidden"):void 0!==document.webkitHidden&&(e="webkitvisibilitychange",t="webkitHidden")),this.visible_=!0,e&&document.addEventListener(e,()=>{var e=!document[t];e!==this.visible_&&(this.visible_=e,this.trigger("visible",e))},!1)}getInitialEvent(e){return g("visible"===e,"Unknown event type: "+e),[this.visible_]}}class pu extends Qc{constructor(e,t,r,n,i,s,a,o){if(super(),this.repoInfo_=e,this.applicationId_=t,this.onDataUpdate_=r,this.onConnectStatus_=n,this.onServerInfoUpdate_=i,this.authTokenProvider_=s,this.appCheckTokenProvider_=a,this.authOverride_=o,this.id=pu.nextPersistentConnectionId_++,this.log_=ec("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,o&&!le())throw new Error("Auth override specified in options, but not supported on non Node.js platforms");du.getInstance().on("visible",this.onVisible_,this),-1===e.host.indexOf("fblocal")&&Jc.getInstance().on("online",this.onOnline_,this)}sendRequest(e,t,r){var n=++this.requestNumber_,i={r:n,a:e,b:t};this.log_(_e(i)),g(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(i),r&&(this.requestCBHash_[n]=r)}get(e){this.initConnection_();let r=new Z;var t={p:e._path.toString(),q:e._queryObject},t=(this.outstandingGets_.push({action:"g",request:t,onComplete:e=>{var t=e.d;"ok"===e.s?r.resolve(t):r.reject(t)}}),this.outstandingGetCount_++,this.outstandingGets_.length-1);return this.connected_&&this.sendGet_(t),r.promise}listen(e,t,r,n){this.initConnection_();var i=e._queryIdentifier,s=e._path.toString(),a=(this.log_("Listen called for "+s+" "+i),this.listens.has(s)||this.listens.set(s,new Map),g(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),g(!this.listens.get(s).has(i),"listen() called twice for same path/queryId."),{onComplete:n,hashFn:t,query:e,tag:r});this.listens.get(s).set(i,a),this.connected_&&this.sendListen_(a)}sendGet_(t){let r=this.outstandingGets_[t];this.sendRequest("g",r.request,e=>{delete this.outstandingGets_[t],this.outstandingGetCount_--,0===this.outstandingGetCount_&&(this.outstandingGets_=[]),r.onComplete&&r.onComplete(e)})}sendListen_(i){let s=i.query,a=s._path.toString(),o=s._queryIdentifier;this.log_("Listen on "+a+" for "+o);var e={p:a};i.tag&&(e.q=s._queryObject,e.t=i.tag),e.h=i.hashFn(),this.sendRequest("q",e,e=>{var t=e.d,r=e.s,n=(pu.warnOnListenWarnings_(t,s),this.listens.get(a)&&this.listens.get(a).get(o));n===i&&(this.log_("listen response",e),"ok"!==r&&this.removeListen_(a,o),i.onComplete)&&i.onComplete(r,t)})}static warnOnListenWarnings_(e,t){var r,n;e&&"object"==typeof e&&we(e,"w")&&(r=be(e,"w"),Array.isArray(r))&&~r.indexOf("no_index")&&(r='".indexOn": "'+t._queryParams.getIndex().toString()+'"',n=t._path.toString(),mc("Using an unspecified index. Your data will be downloaded and "+`filtered on the client. Consider adding ${r} 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){var t;(e&&40===e.length||(e=e,"object"==typeof(t=ye(e).claims)&&!0===t.admin))&&(this.log_("Admin auth credential detected. Reducing max reconnect time."),this.maxReconnectDelay_=3e4)}refreshAppCheckToken(e){this.appCheckToken_=e,this.log_("App check token refreshed"),this.appCheckToken_?this.tryAppCheck():this.connected_&&this.sendRequest("unappeck",{},()=>{})}tryAuth(){if(this.connected_&&this.authToken_){let n=this.authToken_;r=n;var e=!!(e=ye(r).claims)&&"object"==typeof e&&e.hasOwnProperty("iat")?"auth":"gauth",t={cred:n};null===this.authOverride_?t.noauth=!0:"object"==typeof this.authOverride_&&(t.authvar=this.authOverride_),this.sendRequest(e,t,e=>{var t=e.s,r=e.d||"error";this.authToken_===n&&("ok"===t?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(t,r))})}var r,e}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},e=>{var t=e.s,r=e.d||"error";"ok"===t?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(t,r)})}unlisten(e,t){var r=e._path.toString(),n=e._queryIdentifier,i=(this.log_("Unlisten called for "+r+" "+n),g(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(r,n));i&&this.connected_&&this.sendUnlisten_(r,n,e._queryObject,t)}sendUnlisten_(e,t,r,n){this.log_("Unlisten on "+e+" for "+t);var i={p:e};n&&(i.q=r,i.t=n),this.sendRequest("n",i)}onDisconnectPut(e,t,r){this.initConnection_(),this.connected_?this.sendOnDisconnect_("o",e,t,r):this.onDisconnectRequestQueue_.push({pathString:e,action:"o",data:t,onComplete:r})}onDisconnectMerge(e,t,r){this.initConnection_(),this.connected_?this.sendOnDisconnect_("om",e,t,r):this.onDisconnectRequestQueue_.push({pathString:e,action:"om",data:t,onComplete:r})}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,r,n){var i={p:t,d:r};this.log_("onDisconnect "+e,i),this.sendRequest(e,i,e=>{n&&setTimeout(()=>{n(e.s,e.d)},Math.floor(0))})}put(e,t,r,n){this.putInternal("p",e,t,r,n)}merge(e,t,r,n){this.putInternal("m",e,t,r,n)}putInternal(e,t,r,n,i){this.initConnection_();var s={p:t,d:r},s=(void 0!==i&&(s.h=i),this.outstandingPuts_.push({action:e,request:s,onComplete:n}),this.outstandingPutCount_++,this.outstandingPuts_.length-1);this.connected_?this.sendPut_(s):this.log_("Buffering put: "+t)}sendPut_(t){let r=this.outstandingPuts_[t].action;var e=this.outstandingPuts_[t].request;let n=this.outstandingPuts_[t].onComplete;this.outstandingPuts_[t].queued=this.connected_,this.sendRequest(r,e,e=>{this.log_(r+" response",e),delete this.outstandingPuts_[t],this.outstandingPutCount_--,0===this.outstandingPutCount_&&(this.outstandingPuts_=[]),n&&n(e.s,e.d)})}reportStats(e){var t;this.connected_&&(this.log_("reportStats",t={c:e}),this.sendRequest("s",t,e=>{var t;"ok"!==e.s&&(t=e.d,this.log_("reportStats","Error sending stats: "+t))}))}onDataMessage_(e){if("r"in e){this.log_("from server: "+_e(e));var t=e.r,r=this.requestCBHash_[t];r&&(delete this.requestCBHash_[t],r(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):tc("Unrecognized action received from server: "+_e(e)+"\nAre you using the latest client?")}onReady_(e,t){this.log_("connection ready"),this.connected_=!0,this.lastConnectionEstablishedTime_=(new Date).getTime(),this.handleTimestamp_(e),this.lastSessionId=t,this.firstConnection_&&this.sendConnectStats_(),this.restoreState_(),this.firstConnection_=!1,this.onConnectStatus_(!0)}scheduleConnect_(e){g(!this.realtime_,"Scheduling a connect when we're already connected/ing?"),this.establishConnectionTimer_&&clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=setTimeout(()=>{this.establishConnectionTimer_=null,this.establishConnection_()},Math.floor(e))}initConnection_(){!this.realtime_&&this.firstConnection_&&this.scheduleConnect_(0)}onVisible_(e){e&&!this.visible_&&this.reconnectDelay_===this.maxReconnectDelay_&&(this.log_("Window became visible. Reducing delay."),this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0)),this.visible_=e}onOnline_(e){e?(this.log_("Browser went online."),this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0)):(this.log_("Browser went offline. Killing connection."),this.realtime_&&this.realtime_.close())}onRealtimeDisconnect_(){var e;this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()&&(this.visible_?this.lastConnectionEstablishedTime_&&(3e4<(new Date).getTime()-this.lastConnectionEstablishedTime_&&(this.reconnectDelay_=1e3),this.lastConnectionEstablishedTime_=null):(this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=(new Date).getTime()),e=Math.max(0,(new Date).getTime()-this.lastConnectionAttemptTime_),e=Math.max(0,this.reconnectDelay_-e),e=Math.random()*e,this.log_("Trying to reconnect in "+e+"ms"),this.scheduleConnect_(e),this.reconnectDelay_=Math.min(this.maxReconnectDelay_,1.3*this.reconnectDelay_)),this.onConnectStatus_(!1)}async establishConnection_(){if(this.shouldReconnect_()){this.log_("Making a connection attempt"),this.lastConnectionAttemptTime_=(new Date).getTime(),this.lastConnectionEstablishedTime_=null;var n=this.onDataMessage_.bind(this),i=this.onReady_.bind(this);let e=this.onRealtimeDisconnect_.bind(this);var s=this.id+":"+pu.nextConnectionId_++,a=this.lastSessionId;let t=!1,r=null;var o=function(){r?r.close():(t=!0,e())},l=(this.realtime_={close:o,sendRequest:function(e){g(r,"sendRequest call when we're not connected not allowed."),r.sendRequest(e)}},this.forceTokenRefresh_);this.forceTokenRefresh_=!1;try{var[h,c]=await Promise.all([this.authTokenProvider_.getToken(l),this.appCheckTokenProvider_.getToken(l)]);t?fc("getToken() completed but was canceled"):(fc("getToken() completed. Creating connection."),this.authToken_=h&&h.accessToken,this.appCheckToken_=c&&c.token,r=new $c(s,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,n,i,e,e=>{mc(e+" ("+this.repoInfo_.toString()+")"),this.interrupt("server_kill")},a))}catch(e){this.log_("Failed to get token: "+e),t||(this.repoInfo_.nodeAdmin&&mc(e),o())}}}interrupt(e){fc("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){fc("Resuming connection for reason: "+e),delete this.interruptReasons_[e],Ie(this.interruptReasons_)&&(this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(e){var t=e-(new Date).getTime();this.onServerInfoUpdate_({serverTimeOffset:t})}cancelSentTransactions_(){for(let t=0;t<this.outstandingPuts_.length;t++){var e=this.outstandingPuts_[t];e&&"h"in e.request&&e.queued&&(e.onComplete&&e.onComplete("disconnect"),delete this.outstandingPuts_[t],this.outstandingPutCount_--)}0===this.outstandingPutCount_&&(this.outstandingPuts_=[])}onListenRevoked_(e,t){let r;r=t?t.map(e=>ic(e)).join("$"):"default";var n=this.removeListen_(e,r);n&&n.onComplete&&n.onComplete("permission_denied")}removeListen_(e,t){var r,n=new f(e).toString();let i;return this.listens.has(n)?(r=this.listens.get(n),i=r.get(t),r.delete(t),0===r.size&&this.listens.delete(n)):i=void 0,i}onAuthRevoked_(e,t){fc("Auth token revoked: "+e+"/"+t),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAuthTokenCount_++,3<=this.invalidAuthTokenCount_&&(this.reconnectDelay_=3e4,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(e,t){fc("App check token revoked: "+e+"/"+t),this.appCheckToken_=null,this.forceTokenRefresh_=!0,"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAppCheckTokenCount_++,3<=this.invalidAppCheckTokenCount_&&this.appCheckTokenProvider_.notifyForInvalidToken())}onSecurityDebugPacket_(e){this.securityDebugCallback_?this.securityDebugCallback_(e):"msg"in e&&console.log("FIREBASE: "+e.msg.replace("\n","\nFIREBASE: "))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(var e of this.listens.values())for(var t of e.values())this.sendListen_(t);for(let n=0;n<this.outstandingPuts_.length;n++)this.outstandingPuts_[n]&&this.sendPut_(n);for(;this.onDisconnectRequestQueue_.length;){var r=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(r.action,r.pathString,r.data,r.onComplete)}for(let i=0;i<this.outstandingGets_.length;i++)this.outstandingGets_[i]&&this.sendGet_(i)}sendConnectStats_(){var e={};e["sdk.js."+Gh.replace(/\./g,"-")]=1,re()?e["framework.cordova"]=1:ae()&&(e["framework.reactnative"]=1),this.reportStats(e)}shouldReconnect_(){var e=Jc.getInstance().currentlyOnline();return Ie(this.interruptReasons_)&&e}}pu.nextPersistentConnectionId_=0,pu.nextConnectionId_=0;class d{constructor(e,t){this.name=e,this.node=t}static Wrap(e,t){return new d(e,t)}}class fu{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,t){var r=new d(yc,e),n=new d(yc,t);return 0!==this.compare(r,n)}minPost(){return d.MIN}}let gu;class mu extends fu{static get __EMPTY_NODE(){return gu}static set __EMPTY_NODE(e){gu=e}compare(e,t){return bc(e.name,t.name)}isDefinedOn(e){throw B("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,t){return!1}minPost(){return d.MIN}maxPost(){return new d(wc,gu)}makePost(e,t){return g("string"==typeof e,"KeyIndex indexValue must always be a string."),new d(e,gu)}toString(){return".key"}}let vu=new mu;class _u{constructor(e,t,r,n,i=null){this.isReverse_=n,this.resultGenerator_=i,this.nodeStack_=[];let s=1;for(;!e.isEmpty();)if(s=t?r(e.key,t):1,n&&(s*=-1),s<0)e=this.isReverse_?e.left:e.right;else{if(0===s){this.nodeStack_.push(e);break}this.nodeStack_.push(e),e=this.isReverse_?e.right:e.left}}getNext(){if(0===this.nodeStack_.length)return null;let e=this.nodeStack_.pop(),t;if(t=this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value},this.isReverse_)for(e=e.left;!e.isEmpty();)this.nodeStack_.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack_.push(e),e=e.left;return t}hasNext(){return 0<this.nodeStack_.length}peek(){var e;return 0===this.nodeStack_.length?null:(e=this.nodeStack_[this.nodeStack_.length-1],this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value})}}class yu{constructor(e,t,r,n,i){this.key=e,this.value=t,this.color=null!=r?r:yu.RED,this.left=null!=n?n:bu.EMPTY_NODE,this.right=null!=i?i:bu.EMPTY_NODE}copy(e,t,r,n,i){return new yu(null!=e?e:this.key,null!=t?t:this.value,null!=r?r:this.color,null!=n?n:this.left,null!=i?i:this.right)}count(){return this.left.count()+1+this.right.count()}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||!!e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min_(){return this.left.isEmpty()?this:this.left.min_()}minKey(){return this.min_().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,r){let n=this;var i=r(e,n.key);return(n=i<0?n.copy(null,null,null,n.left.insert(e,t,r),null):0===i?n.copy(null,t,null,null,null):n.copy(null,null,null,null,n.right.insert(e,t,r))).fixUp_()}removeMin_(){if(this.left.isEmpty())return bu.EMPTY_NODE;let e=this;return(e=(e=e.left.isRed_()||e.left.left.isRed_()?e:e.moveRedLeft_()).copy(null,null,null,e.left.removeMin_(),null)).fixUp_()}remove(e,t){let r,n;if(t(e,(r=this).key)<0)r=(r=r.left.isEmpty()||r.left.isRed_()||r.left.left.isRed_()?r:r.moveRedLeft_()).copy(null,null,null,r.left.remove(e,t),null);else{if(0===t(e,(r=(r=r.left.isRed_()?r.rotateRight_():r).right.isEmpty()||r.right.isRed_()||r.right.left.isRed_()?r:r.moveRedRight_()).key)){if(r.right.isEmpty())return bu.EMPTY_NODE;n=r.right.min_(),r=r.copy(n.key,n.value,null,null,r.right.removeMin_())}r=r.copy(null,null,null,null,r.right.remove(e,t))}return r.fixUp_()}isRed_(){return this.color}fixUp_(){let e=this;return e=(e=(e=e.right.isRed_()&&!e.left.isRed_()?e.rotateLeft_():e).left.isRed_()&&e.left.left.isRed_()?e.rotateRight_():e).left.isRed_()&&e.right.isRed_()?e.colorFlip_():e}moveRedLeft_(){let e=this.colorFlip_();return e=e.right.left.isRed_()?(e=(e=e.copy(null,null,null,null,e.right.rotateRight_())).rotateLeft_()).colorFlip_():e}moveRedRight_(){let e=this.colorFlip_();return e=e.left.left.isRed_()?(e=e.rotateRight_()).colorFlip_():e}rotateLeft_(){var e=this.copy(null,null,yu.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){var e=this.copy(null,null,yu.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip_(){var e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth_(){var e=this.check_();return Math.pow(2,e)<=this.count()+1}check_(){if(this.isRed_()&&this.left.isRed_())throw new Error("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed_())throw new Error("Right child of ("+this.key+","+this.value+") is red");var e=this.left.check_();if(e!==this.right.check_())throw new Error("Black depths differ");return e+(this.isRed_()?0:1)}}yu.RED=!0,yu.BLACK=!1;class wu{copy(e,t,r,n,i){return this}insert(e,t,r){return new yu(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 bu{constructor(e,t=bu.EMPTY_NODE){this.comparator_=e,this.root_=t}insert(e,t){return new bu(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,yu.BLACK,null,null))}remove(e){return new bu(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,yu.BLACK,null,null))}get(e){var t;let r=this.root_;for(;!r.isEmpty();){if(0===(t=this.comparator_(e,r.key)))return r.value;t<0?r=r.left:0<t&&(r=r.right)}return null}getPredecessorKey(e){let t,r=this.root_,n=null;for(;!r.isEmpty();){if(0===(t=this.comparator_(e,r.key))){if(r.left.isEmpty())return n?n.key:null;for(r=r.left;!r.right.isEmpty();)r=r.right;return r.key}t<0?r=r.left:0<t&&(r=(n=r).right)}throw new Error("Attempted to find predecessor key for a nonexistent key. What gives?")}isEmpty(){return this.root_.isEmpty()}count(){return this.root_.count()}minKey(){return this.root_.minKey()}maxKey(){return this.root_.maxKey()}inorderTraversal(e){return this.root_.inorderTraversal(e)}reverseTraversal(e){return this.root_.reverseTraversal(e)}getIterator(e){return new _u(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new _u(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new _u(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new _u(this.root_,null,this.comparator_,!0,e)}}function Iu(e,t){return bc(e.name,t.name)}function Tu(e,t){return bc(e,t)}bu.EMPTY_NODE=new wu;let Eu;function Cu(e){return"number"==typeof e?"number:"+Tc(e):"string:"+e}function Su(e){var t;e.isLeafNode()?(t=e.val(),g("string"==typeof t||"number"==typeof t||"object"==typeof t&&we(t,".sv"),"Priority must be a string or number.")):g(e===Eu||e.isEmpty(),"priority of unexpected type."),g(e===Eu||e.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")}let ku;class Au{static set __childrenNodeConstructor(e){ku=e}static get __childrenNodeConstructor(){return ku}constructor(e,t=Au.__childrenNodeConstructor.EMPTY_NODE){this.value_=e,this.priorityNode_=t,this.lazyHash_=null,g(null!=this.value_,"LeafNode shouldn't be created with null/undefined value."),Su(this.priorityNode_)}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new Au(this.value_,e)}getImmediateChild(e){return".priority"===e?this.priorityNode_:Au.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return b(e)?this:".priority"===_(e)?this.priorityNode_:Au.__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:Au.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,t).updatePriority(this.priorityNode_)}updateChild(e,t){var r=_(e);return null===r?t:t.isEmpty()&&".priority"!==r?this:(g(".priority"!==r||1===eu(e),".priority must be the last token in a path"),this.updateImmediateChild(r,Au.__childrenNodeConstructor.EMPTY_NODE.updateChild(y(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:"+Cu(this.priorityNode_.val())+":");var t=typeof this.value_;e=(e+=t+":")+("number"==t?Tc(this.value_):this.value_),this.lazyHash_=Zh(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===Au.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof Au.__childrenNodeConstructor?-1:(g(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){var t=typeof e.value_,r=typeof this.value_,n=Au.VALUE_TYPE_ORDER.indexOf(t),i=Au.VALUE_TYPE_ORDER.indexOf(r);return g(0<=n,"Unknown leaf type: "+t),g(0<=i,"Unknown leaf type: "+r),n===i?"object"==r?0:this.value_<e.value_?-1:this.value_===e.value_?0:1:i-n}withIndex(){return this}isIndexed(){return!0}equals(e){return e===this||!!e.isLeafNode()&&this.value_===e.value_&&this.priorityNode_.equals(e.priorityNode_)}}Au.VALUE_TYPE_ORDER=["object","boolean","number","string"];let Nu,Ru;class Pu extends fu{compare(e,t){var r=e.node.getPriority(),n=t.node.getPriority(),r=r.compareTo(n);return 0===r?bc(e.name,t.name):r}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return d.MIN}maxPost(){return new d(wc,new Au("[PRIORITY-POST]",Ru))}makePost(e,t){var r=Nu(e);return new d(t,new Au("[PRIORITY-POST]",r))}toString(){return".priority"}}let I=new Pu,Du=Math.log(2);class xu{constructor(e){this.count=(t=e+1,parseInt(Math.log(t)/Du,10)),this.current_=this.count-1,t=this.count;var t,r=parseInt(Array(t+1).join("1"),2);this.bits_=e+1&r}nextBitIsOne(){var e=!(this.bits_&1<<this.current_);return this.current_--,e}}function Ou(l,e,h,t){l.sort(e);let c=function(e,t){var r,n,i=t-e;let s,a;return 0==i?null:1==i?(s=l[e],a=h?h(s):s,new yu(a,s.node,yu.BLACK,null,null)):(i=parseInt(i/2,10)+e,r=c(e,i),n=c(i+1,t),s=l[i],a=h?h(s):s,new yu(a,s.node,yu.BLACK,r,n))};var r=(e=>{let s=null,a=null,o=l.length;function t(e,t){var r=o-e,n=o,n=(o-=e,c(1+r,n)),r=l[r],i=h?h(r):r,e=new yu(i,r.node,t,null,n);s=(s?s.left=e:a=e,e)}for(let i=0;i<e.count;++i){var r=e.nextBitIsOne(),n=Math.pow(2,e.count-(i+1));r?t(n,yu.BLACK):(t(n,yu.BLACK),t(n,yu.RED))}return a})(new xu(l.length));return new bu(t||e,r)}let Mu,Lu={};class Fu{static get Default(){return g((Lu,I),"ChildrenNode.ts has not been loaded"),Mu=Mu||new Fu({".priority":Lu},{".priority":I})}constructor(e,t){this.indexes_=e,this.indexSet_=t}get(e){var t=be(this.indexes_,e);if(t)return t instanceof bu?t:null;throw new Error("No index defined for "+e)}hasIndex(e){return we(this.indexSet_,e.toString())}addIndex(e,t){g(e!==vu,"KeyIndex always exists and isn't meant to be added to the IndexMap.");var r=[];let n=!1;var i=t.getIterator(d.Wrap);let s=i.getNext();for(;s;)n=n||e.isDefinedOn(s.node),r.push(s),s=i.getNext();let a;a=n?Ou(r,e.getCompare()):Lu;var o=e.toString(),l={...this.indexSet_},h=(l[o]=e,{...this.indexes_});return h[o]=a,new Fu(h,l)}addToIndexes(s,a){var e=Te(this.indexes_,(t,e)=>{var r=be(this.indexSet_,e);if(g(r,"Missing index implementation for "+e),t===Lu){if(r.isDefinedOn(s.node)){var n=[],i=a.getIterator(d.Wrap);let e=i.getNext();for(;e;)e.name!==s.name&&n.push(e),e=i.getNext();return n.push(s),Ou(n,r.getCompare())}return Lu}{r=a.get(s.name);let e=t;return(e=r?e.remove(new d(s.name,r)):e).insert(s,s.node)}});return new Fu(e,this.indexSet_)}removeFromIndexes(r,n){var e=Te(this.indexes_,e=>{var t;return e!==Lu&&(t=n.get(r.name))?e.remove(new d(r.name,t)):e});return new Fu(e,this.indexSet_)}}let Uu;class T{static get EMPTY_NODE(){return Uu=Uu||new T(new bu(Tu),null,Fu.Default)}constructor(e,t,r){this.children_=e,this.priorityNode_=t,this.indexMap_=r,this.lazyHash_=null,this.priorityNode_&&Su(this.priorityNode_),this.children_.isEmpty()&&g(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}isLeafNode(){return!1}getPriority(){return this.priorityNode_||Uu}updatePriority(e){return this.children_.isEmpty()?this:new T(this.children_,e,this.indexMap_)}getImmediateChild(e){var t;return".priority"===e?this.getPriority():null===(t=this.children_.get(e))?Uu:t}getChild(e){var t=_(e);return null===t?this:this.getImmediateChild(t).getChild(y(e))}hasChild(e){return null!==this.children_.get(e)}updateImmediateChild(r,n){if(g(n,"We should always be passing snapshot nodes"),".priority"===r)return this.updatePriority(n);{var i=new d(r,n);let e,t;t=n.isEmpty()?(e=this.children_.remove(r),this.indexMap_.removeFromIndexes(i,this.children_)):(e=this.children_.insert(r,n),this.indexMap_.addToIndexes(i,this.children_));i=e.isEmpty()?Uu:this.priorityNode_;return new T(e,i,t)}}updateChild(e,t){var r,n=_(e);return null===n?t:(g(".priority"!==_(e)||1===eu(e),".priority must be the last token in a path"),r=this.getImmediateChild(n).updateChild(y(e),t),this.updateImmediateChild(n,r))}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(r){if(this.isEmpty())return null;let n={},i=0,s=0,a=!0;if(this.forEachChild(I,(e,t)=>{n[e]=t.val(r),i++,a&&T.INTEGER_REGEXP_.test(e)?s=Math.max(s,Number(e)):a=!1}),!r&&a&&s<2*i){var e,t=[];for(e in n)t[e]=n[e];return t}return r&&!this.getPriority().isEmpty()&&(n[".priority"]=this.getPriority().val()),n}hash(){if(null===this.lazyHash_){let n="";this.getPriority().isEmpty()||(n+="priority:"+Cu(this.getPriority().val())+":"),this.forEachChild(I,(e,t)=>{var r=t.hash();""!==r&&(n+=":"+e+":"+r)}),this.lazyHash_=""===n?"":Zh(n)}return this.lazyHash_}getPredecessorChildName(e,t,r){var n=this.resolveIndex_(r);return n?(n=n.getPredecessorKey(new d(e,t)))?n.name:null:this.children_.getPredecessorKey(e)}getFirstChildName(e){var t=this.resolveIndex_(e);return t?(t=t.minKey())&&t.name:this.children_.minKey()}getFirstChild(e){var t=this.getFirstChildName(e);return t?new d(t,this.children_.get(t)):null}getLastChildName(e){var t=this.resolveIndex_(e);return t?(t=t.maxKey())&&t.name:this.children_.maxKey()}getLastChild(e){var t=this.getLastChildName(e);return t?new d(t,this.children_.get(t)):null}forEachChild(e,t){var r=this.resolveIndex_(e);return r?r.inorderTraversal(e=>t(e.name,e.node)):this.children_.inorderTraversal(t)}getIterator(e){return this.getIteratorFrom(e.minPost(),e)}getIteratorFrom(t,r){var e=this.resolveIndex_(r);if(e)return e.getIteratorFrom(t,e=>e);{var n=this.children_.getIteratorFrom(t.name,d.Wrap);let e=n.peek();for(;null!=e&&r.compare(e,t)<0;)n.getNext(),e=n.peek();return n}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(t,r){var e=this.resolveIndex_(r);if(e)return e.getReverseIteratorFrom(t,e=>e);{var n=this.children_.getReverseIteratorFrom(t.name,d.Wrap);let e=n.peek();for(;null!=e&&0<r.compare(e,t);)n.getNext(),e=n.peek();return n}}compareTo(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===qu?-1:0}withIndex(e){var t;return e===vu||this.indexMap_.hasIndex(e)?this:(t=this.indexMap_.addIndex(e,this.children_),new T(this.children_,this.priorityNode_,t))}isIndexed(e){return e===vu||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;if(!e.isLeafNode()){var r=e;if(this.getPriority().equals(r.getPriority())){if(this.children_.count()!==r.children_.count())return!1;{var n=this.getIterator(I),i=r.getIterator(I);let e=n.getNext(),t=i.getNext();for(;e&&t;){if(e.name!==t.name||!e.node.equals(t.node))return!1;e=n.getNext(),t=i.getNext()}return null===e&&null===t}}}return!1}resolveIndex_(e){return e===vu?null:this.indexMap_.get(e.toString())}}T.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;class Vu extends T{constructor(){super(new bu(Tu),T.EMPTY_NODE,Fu.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return T.EMPTY_NODE}isEmpty(){return!1}}let qu=new Vu,Bu=(Object.defineProperties(d,{MIN:{value:new d(yc,T.EMPTY_NODE)},MAX:{value:new d(wc,qu)}}),mu.__EMPTY_NODE=T.EMPTY_NODE,Au.__childrenNodeConstructor=T,t=qu,Eu=t,t=qu,Ru=t,!0);function ju(s,e=null){if(null===s)return T.EMPTY_NODE;var t,r;if("object"==typeof s&&".priority"in s&&(e=s[".priority"]),g(null===e||"string"==typeof e||"number"==typeof e||"object"==typeof e&&".sv"in e,"Invalid priority type found: "+typeof e),"object"!=typeof(s="object"==typeof s&&".value"in s&&null!==s[".value"]?s[".value"]:s)||".sv"in s)return t=s,new Au(t,ju(e));if(s instanceof Array||!Bu){let n=T.EMPTY_NODE;return Ic(s,(e,t)=>{var r;!we(s,e)||"."===e.substring(0,1)||!(r=ju(t)).isLeafNode()&&r.isEmpty()||(n=n.updateImmediateChild(e,r))}),n.updatePriority(ju(e))}{let n=[],i=!1;return Ic(s,(e,t)=>{var r;"."===e.substring(0,1)||(r=ju(t)).isEmpty()||(i=i||!r.getPriority().isEmpty(),n.push(new d(e,r)))}),0===n.length?T.EMPTY_NODE:(t=Ou(n,Iu,e=>e.name,Tu),i?(r=Ou(n,I.getCompare()),new T(t,ju(e),new Fu({".priority":r},{".priority":I}))):new T(t,ju(e),Fu.Default))}}Nu=ju;class zu extends fu{constructor(e){super(),this.indexPath_=e,g(!b(e)&&".priority"!==_(e),"Can't create PathIndex with empty path or .priority key")}extractChild(e){return e.getChild(this.indexPath_)}isDefinedOn(e){return!e.getChild(this.indexPath_).isEmpty()}compare(e,t){var r=this.extractChild(e.node),n=this.extractChild(t.node),r=r.compareTo(n);return 0===r?bc(e.name,t.name):r}makePost(e,t){var r=ju(e),r=T.EMPTY_NODE.updateChild(this.indexPath_,r);return new d(t,r)}maxPost(){var e=T.EMPTY_NODE.updateChild(this.indexPath_,qu);return new d(wc,e)}toString(){return ru(this.indexPath_,0).join("/")}}class Ku extends fu{compare(e,t){var r=e.node.compareTo(t.node);return 0===r?bc(e.name,t.name):r}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return d.MIN}maxPost(){return d.MAX}makePost(e,t){var r=ju(e);return new d(t,r)}toString(){return".value"}}let Wu=new Ku;function Hu(e){return{type:"value",snapshotNode:e}}function Gu(e,t){return{type:"child_added",snapshotNode:t,childName:e}}function $u(e,t){return{type:"child_removed",snapshotNode:t,childName:e}}function Qu(e,t,r){return{type:"child_changed",snapshotNode:t,childName:e,oldSnap:r}}class Yu{constructor(e){this.index_=e}updateChild(e,t,r,n,i,s){g(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");var a=e.getImmediateChild(t);return a.getChild(n).equals(r.getChild(n))&&a.isEmpty()===r.isEmpty()||(null!=s&&(r.isEmpty()?e.hasChild(t)?s.trackChildChange($u(t,a)):g(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):a.isEmpty()?s.trackChildChange(Gu(t,r)):s.trackChildChange(Qu(t,r,a))),e.isLeafNode()&&r.isEmpty())?e:e.updateImmediateChild(t,r).withIndex(this.index_)}updateFullNode(n,r,i){return null!=i&&(n.isLeafNode()||n.forEachChild(I,(e,t)=>{r.hasChild(e)||i.trackChildChange($u(e,t))}),r.isLeafNode()||r.forEachChild(I,(e,t)=>{var r;n.hasChild(e)?(r=n.getImmediateChild(e)).equals(t)||i.trackChildChange(Qu(e,t,r)):i.trackChildChange(Gu(e,t))})),r.withIndex(this.index_)}updatePriority(e,t){return e.isEmpty()?T.EMPTY_NODE:e.updatePriority(t)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}class Ju{constructor(e){this.indexedFilter_=new Yu(e.getIndex()),this.index_=e.getIndex(),this.startPost_=Ju.getStartPost_(e),this.endPost_=Ju.getEndPost_(e),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){var t=this.startIsInclusive_?this.index_.compare(this.getStartPost(),e)<=0:this.index_.compare(this.getStartPost(),e)<0,r=this.endIsInclusive_?this.index_.compare(e,this.getEndPost())<=0:this.index_.compare(e,this.getEndPost())<0;return t&&r}updateChild(e,t,r,n,i,s){return this.matches(new d(t,r))||(r=T.EMPTY_NODE),this.indexedFilter_.updateChild(e,t,r,n,i,s)}updateFullNode(e,t,r){let n=(t=t.isLeafNode()?T.EMPTY_NODE:t).withIndex(this.index_),i=(n=n.updatePriority(T.EMPTY_NODE),this);return t.forEachChild(I,(e,t)=>{i.matches(new d(e,t))||(n=n.updateImmediateChild(e,T.EMPTY_NODE))}),this.indexedFilter_.updateFullNode(e,n,r)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){var t;return e.hasStart()?(t=e.getIndexStartName(),e.getIndex().makePost(e.getIndexStartValue(),t)):e.getIndex().minPost()}static getEndPost_(e){var t;return e.hasEnd()?(t=e.getIndexEndName(),e.getIndex().makePost(e.getIndexEndValue(),t)):e.getIndex().maxPost()}}class Xu{constructor(e){this.withinDirectionalStart=e=>this.reverse_?this.withinEndPost(e):this.withinStartPost(e),this.withinDirectionalEnd=e=>this.reverse_?this.withinStartPost(e):this.withinEndPost(e),this.withinStartPost=e=>{var t=this.index_.compare(this.rangedFilter_.getStartPost(),e);return this.startIsInclusive_?t<=0:t<0},this.withinEndPost=e=>{var t=this.index_.compare(e,this.rangedFilter_.getEndPost());return this.endIsInclusive_?t<=0:t<0},this.rangedFilter_=new Ju(e),this.index_=e.getIndex(),this.limit_=e.getLimit(),this.reverse_=!e.isViewFromLeft(),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}updateChild(e,t,r,n,i,s){return this.rangedFilter_.matches(new d(t,r))||(r=T.EMPTY_NODE),e.getImmediateChild(t).equals(r)?e:e.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(e,t,r,n,i,s):this.fullLimitUpdateChild_(e,t,r,i,s)}updateFullNode(e,r,t){let n;if(r.isLeafNode()||r.isEmpty())n=T.EMPTY_NODE.withIndex(this.index_);else if(2*this.limit_<r.numChildren()&&r.isIndexed(this.index_)){n=T.EMPTY_NODE.withIndex(this.index_);let e,t=(e=this.reverse_?r.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):r.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_),0);for(;e.hasNext()&&t<this.limit_;){var i=e.getNext();if(this.withinDirectionalStart(i)){if(!this.withinDirectionalEnd(i))break;n=n.updateImmediateChild(i.name,i.node),t++}}}else{n=(n=r.withIndex(this.index_)).updatePriority(T.EMPTY_NODE);let e,t=(e=this.reverse_?n.getReverseIterator(this.index_):n.getIterator(this.index_),0);for(;e.hasNext();){var s=e.getNext();t<this.limit_&&this.withinDirectionalStart(s)&&this.withinDirectionalEnd(s)?t++:n=n.updateImmediateChild(s.name,T.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(e,n,t)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}fullLimitUpdateChild_(e,t,r,n,i){let s;if(this.reverse_){let r=this.index_.getCompare();s=(e,t)=>r(t,e)}else s=this.index_.getCompare();var a=e,o=(g(a.numChildren()===this.limit_,""),new d(t,r)),l=this.reverse_?a.getFirstChild(this.index_):a.getLastChild(this.index_),h=this.rangedFilter_.matches(o);if(a.hasChild(t)){var c=a.getImmediateChild(t);let e=n.getChildAfterChild(this.index_,l,this.reverse_);for(;null!=e&&(e.name===t||a.hasChild(e.name));)e=n.getChildAfterChild(this.index_,e,this.reverse_);var u=null==e?1:s(e,o);return h&&!r.isEmpty()&&0<=u?(null!=i&&i.trackChildChange(Qu(t,r,c)),a.updateImmediateChild(t,r)):(null!=i&&i.trackChildChange($u(t,c)),u=a.updateImmediateChild(t,T.EMPTY_NODE),null!=e&&this.rangedFilter_.matches(e)?(null!=i&&i.trackChildChange(Gu(e.name,e.node)),u.updateImmediateChild(e.name,e.node)):u)}return!r.isEmpty()&&h&&0<=s(l,o)?(null!=i&&(i.trackChildChange($u(l.name,l.node)),i.trackChildChange(Gu(t,r))),a.updateImmediateChild(t,r).updateImmediateChild(l.name,T.EMPTY_NODE)):e}}class Zu{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_=I}hasStart(){return this.startSet_}isViewFromLeft(){return""===this.viewFrom_?this.startSet_:"l"===this.viewFrom_}getIndexStartValue(){return g(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return g(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:yc}hasEnd(){return this.endSet_}getIndexEndValue(){return g(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return g(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:wc}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&""!==this.viewFrom_}getLimit(){return g(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_===I}copy(){var e=new Zu;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 ed(e,t,r){var n=e.copy();return n.startSet_=!0,n.indexStartValue_=t=void 0===t?null:t,null!=r?(n.startNameSet_=!0,n.indexStartName_=r):(n.startNameSet_=!1,n.indexStartName_=""),n}function td(e,t,r){var n=e.copy();return n.endSet_=!0,n.indexEndValue_=t=void 0===t?null:t,void 0!==r?(n.endNameSet_=!0,n.indexEndName_=r):(n.endNameSet_=!1,n.indexEndName_=""),n}function rd(e,t){var r=e.copy();return r.index_=t,r}function nd(t){var r,n={};if(!t.isDefault()){let e;e=t.index_===I?"$priority":t.index_===Wu?"$value":t.index_===vu?"$key":(g(t.index_ instanceof zu,"Unrecognized index type!"),t.index_.toString()),n.orderBy=_e(e),t.startSet_&&(n[r=t.startAfterSet_?"startAfter":"startAt"]=_e(t.indexStartValue_),t.startNameSet_)&&(n[r]+=","+_e(t.indexStartName_)),t.endSet_&&(n[r=t.endBeforeSet_?"endBefore":"endAt"]=_e(t.indexEndValue_),t.endNameSet_)&&(n[r]+=","+_e(t.indexEndName_)),t.limitSet_&&(t.isViewFromLeft()?n.limitToFirst=t.limit_:n.limitToLast=t.limit_)}return n}function id(t){var r={};if(t.startSet_&&(r.sp=t.indexStartValue_,t.startNameSet_&&(r.sn=t.indexStartName_),r.sin=!t.startAfterSet_),t.endSet_&&(r.ep=t.indexEndValue_,t.endNameSet_&&(r.en=t.indexEndName_),r.ein=!t.endBeforeSet_),t.limitSet_){r.l=t.limit_;let e=t.viewFrom_;""===e&&(e=t.isViewFromLeft()?"l":"r"),r.vf=e}return t.index_!==I&&(r.i=t.index_.toString()),r}class sd extends Qc{reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,t){return void 0!==t?"tag$"+t:(g(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}constructor(e,t,r,n){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=r,this.appCheckTokenProvider_=n,this.log_=ec("p:rest:"),this.listens_={}}listen(e,t,n,i){let s=e._path.toString(),a=(this.log_("Listen called for "+s+" "+e._queryIdentifier),sd.getListenId_(e,n)),o={};this.listens_[a]=o;var r=nd(e._queryParams);this.restRequest_(s+".json",r,(t,e)=>{let r=e;if(null===(t=404===t?r=null:t)&&this.onDataUpdate_(s,r,!1,n),be(this.listens_,a)===o){let e;e=t?401===t?"permission_denied":"rest_error:"+t:"ok",i(e,null)}})}unlisten(e,t){var r=sd.getListenId_(e,t);delete this.listens_[r]}get(e){var t=nd(e._queryParams);let n=e._path.toString(),i=new Z;return this.restRequest_(n+".json",t,(e,t)=>{let r=t;null===(e=404===e?r=null:e)?(this.onDataUpdate_(n,r,!1,null),i.resolve(r)):i.reject(new Error(r))}),i.promise}refreshAuthToken(e){}restRequest_(i,s={},a){return s.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then(([e,t])=>{e&&e.accessToken&&(s.auth=e.accessToken),t&&t.token&&(s.ac=t.token);let r=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+i+"?ns="+this.repoInfo_.namespace+Se(s),n=(this.log_("Sending REST request for "+r),new XMLHttpRequest);n.onreadystatechange=()=>{if(a&&4===n.readyState){this.log_("REST Response for "+r+" received. status:",n.status,"response:",n.responseText);let e=null;if(200<=n.status&&n.status<300){try{e=ve(n.responseText)}catch(e){mc("Failed to parse JSON response for "+r+": "+n.responseText)}a(null,e)}else 401!==n.status&&404!==n.status&&mc("Got unsuccessful REST response for "+r+" Status: "+n.status),a(n.status);a=null}},n.open("GET",r,!0),n.send()})}}class ad{constructor(){this.rootNode_=T.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}function od(){return{value:null,children:new Map}}function ld(e,t,r){var n;b(t)?(e.value=r,e.children.clear()):null!==e.value?e.value=e.value.updateChild(t,r):(n=_(t),e.children.has(n)||e.children.set(n,od()),ld(e.children.get(n),t=y(t),r))}function hd(e,r,n){var i;null!==e.value?n(r,e.value):(i=(e,t)=>{hd(t,new f(r.toString()+"/"+e),n)},e.children.forEach((e,t)=>{i(t,e)}))}class cd{constructor(e){this.collection_=e,this.last_=null}get(){var e=this.collection_.get();let r={...e};return this.last_&&Ic(this.last_,(e,t)=>{r[e]=r[e]-t}),this.last_=e,r}}class ud{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new cd(e);var r=1e4+2e4*Math.random();Cc(this.reportStats_.bind(this),Math.floor(r))}reportStats_(){var e=this.statsListener_.get();let r={},n=!1;Ic(e,(e,t)=>{0<t&&we(this.statsToReport_,e)&&(r[e]=t,n=!0)}),n&&this.server_.reportStats(r),Cc(this.reportStats_.bind(this),Math.floor(2*Math.random()*3e5))}}function dd(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function pd(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function fd(e){return{fromUser:!1,fromServer:!0,queryId:e,tagged:!0}}(t=Xh=Xh||{})[t.OVERWRITE=0]="OVERWRITE",t[t.MERGE=1]="MERGE",t[t.ACK_USER_WRITE=2]="ACK_USER_WRITE",t[t.LISTEN_COMPLETE=3]="LISTEN_COMPLETE";class gd{constructor(e,t,r){this.path=e,this.affectedTree=t,this.revert=r,this.type=Xh.ACK_USER_WRITE,this.source=dd()}operationForChild(e){var t;return b(this.path)?null!=this.affectedTree.value?(g(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this):(t=this.affectedTree.subtree(new f(e)),new gd(v(),t,this.revert)):(g(_(this.path)===e,"operationForChild called for unrelated child."),new gd(y(this.path),this.affectedTree,this.revert))}}class md{constructor(e,t){this.source=e,this.path=t,this.type=Xh.LISTEN_COMPLETE}operationForChild(e){return b(this.path)?new md(this.source,v()):new md(this.source,y(this.path))}}class vd{constructor(e,t,r){this.source=e,this.path=t,this.snap=r,this.type=Xh.OVERWRITE}operationForChild(e){return b(this.path)?new vd(this.source,v(),this.snap.getImmediateChild(e)):new vd(this.source,y(this.path),this.snap)}}class _d{constructor(e,t,r){this.source=e,this.path=t,this.children=r,this.type=Xh.MERGE}operationForChild(e){var t;return b(this.path)?(t=this.children.subtree(new f(e))).isEmpty()?null:t.value?new vd(this.source,v(),t.value):new _d(this.source,v(),t):(g(_(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new _d(this.source,y(this.path),this.children))}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}class yd{constructor(e,t,r){this.node_=e,this.fullyInitialized_=t,this.filtered_=r}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){var t;return b(e)?this.isFullyInitialized()&&!this.filtered_:(t=_(e),this.isCompleteForChild(t))}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}class wd{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function bd(r,e,t,n){var i=[];let s=[];return e.forEach(e=>{var t;"child_changed"===e.type&&r.index_.indexedValueChanged(e.oldSnap,e.snapshotNode)&&s.push((t=e.childName,{type:"child_moved",snapshotNode:e.snapshotNode,childName:t}))}),Id(r,i,"child_removed",e,n,t),Id(r,i,"child_added",e,n,t),Id(r,i,"child_moved",s,n,t),Id(r,i,"child_changed",e,n,t),Id(r,i,"value",e,n,t),i}function Id(s,a,t,e,o,l){var r=e.filter(e=>e.type===t);r.sort((e,t)=>{var r=s;if(null==e.childName||null==t.childName)throw B("Should only compare child_ events.");var n=new d(e.childName,e.snapshotNode),i=new d(t.childName,t.snapshotNode);return r.index_.compare(n,i)}),r.forEach(t=>{e=s,i=l,"value"!==(n=t).type&&"child_removed"!==n.type&&(n.prevName=i.getPredecessorChildName(n.childName,n.snapshotNode,e.index_));let r=n;var e,n,i;o.forEach(e=>{e.respondsTo(t.type)&&a.push(e.createEvent(r,s.query_))})})}function Td(e,t){return{eventCache:e,serverCache:t}}function Ed(e,t,r,n){return Td(new yd(t,r,n),e.serverCache)}function Cd(e,t,r,n){return Td(e.eventCache,new yd(t,r,n))}function Sd(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function kd(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}let Ad;class Nd{static fromObject(e){let r=new Nd(null);return Ic(e,(e,t)=>{r=r.set(new f(e),t)}),r}constructor(e,t=Ad=Ad||new bu(rc)){this.value=e,this.children=t}isEmpty(){return null===this.value&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){var r,n;return null!=this.value&&t(this.value)?{path:v(),value:this.value}:!b(e)&&(r=_(e),null!==(n=this.children.get(r)))&&null!=(n=n.findRootMostMatchingPathAndValue(y(e),t))?{path:iu(new f(r),n.path),value:n.value}:null}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,()=>!0)}subtree(e){var t;return b(e)?this:(t=_(e),null!==(t=this.children.get(t))?t.subtree(y(e)):new Nd(null))}set(e,t){var r,n;return b(e)?new Nd(t,this.children):(n=_(e),r=(this.children.get(n)||new Nd(null)).set(y(e),t),n=this.children.insert(n,r),new Nd(this.value,n))}remove(t){if(b(t))return this.children.isEmpty()?new Nd(null):new Nd(null,this.children);var r=_(t),n=this.children.get(r);if(n){n=n.remove(y(t));let e;return e=n.isEmpty()?this.children.remove(r):this.children.insert(r,n),null===this.value&&e.isEmpty()?new Nd(null):new Nd(this.value,e)}return this}get(e){var t;return b(e)?this.value:(t=_(e),(t=this.children.get(t))?t.get(y(e)):null)}setTree(t,r){if(b(t))return r;{var n=_(t),i=(this.children.get(n)||new Nd(null)).setTree(y(t),r);let e;return e=i.isEmpty()?this.children.remove(n):this.children.insert(n,i),new Nd(this.value,e)}}fold(e){return this.fold_(v(),e)}fold_(r,n){let i={};return this.children.inorderTraversal((e,t)=>{i[e]=t.fold_(iu(r,e),n)}),n(r,this.value,i)}findOnPath(e,t){return this.findOnPath_(e,v(),t)}findOnPath_(e,t,r){var n,i=!!this.value&&r(t,this.value);return i||(!b(e)&&(i=_(e),n=this.children.get(i))?n.findOnPath_(y(e),iu(t,i),r):null)}foreachOnPath(e,t){return this.foreachOnPath_(e,v(),t)}foreachOnPath_(e,t,r){var n,i;return b(e)?this:(this.value&&r(t,this.value),n=_(e),(i=this.children.get(n))?i.foreachOnPath_(y(e),iu(t,n),r):new Nd(null))}foreach(e){this.foreach_(v(),e)}foreach_(r,n){this.children.inorderTraversal((e,t)=>{t.foreach_(iu(r,e),n)}),this.value&&n(r,this.value)}foreachChild(r){this.children.inorderTraversal((e,t)=>{t.value&&r(e,t.value)})}}class Rd{constructor(e){this.writeTree_=e}static empty(){return new Rd(new Nd(null))}}function Pd(t,r,n){if(b(r))return new Rd(new Nd(n));var i=t.writeTree_.findRootMostValueAndPath(r);if(null==i)return s=new Nd(n),s=t.writeTree_.setTree(r,s),new Rd(s);{var s=i.path;let e=i.value;i=su(s,r);return e=e.updateChild(i,n),new Rd(t.writeTree_.set(s,e))}}function Dd(e,r,t){let n=e;return Ic(t,(e,t)=>{n=Pd(n,iu(r,e),t)}),n}function xd(e,t){var r;return b(t)?Rd.empty():(r=e.writeTree_.setTree(t,new Nd(null)),new Rd(r))}function Od(e,t){return null!=Md(e,t)}function Md(e,t){var r=e.writeTree_.findRootMostValueAndPath(t);return null!=r?e.writeTree_.get(r.path).getChild(su(r.path,t)):null}function Ld(e){let r=[];var t=e.writeTree_.value;return null!=t?t.isLeafNode()||t.forEachChild(I,(e,t)=>{r.push(new d(e,t))}):e.writeTree_.children.inorderTraversal((e,t)=>{null!=t.value&&r.push(new d(e,t.value))}),r}function Fd(e,t){var r;return b(t)?e:null!=(r=Md(e,t))?new Rd(new Nd(r)):new Rd(e.writeTree_.subtree(t))}function Ud(e){return e.writeTree_.isEmpty()}function Vd(e,t){return function n(i,e,s){{if(null!=e.value)return s.updateChild(i,e.value);{let r=null;return e.children.inorderTraversal((e,t)=>{".priority"===e?(g(null!==t.value,"Priority writes must always be leaf nodes"),r=t.value):s=n(iu(i,e),t,s)}),s=s.getChild(i).isEmpty()||null===r?s:s.updateChild(iu(i,".priority"),r)}}}(v(),e.writeTree_,t)}function qd(e,t){return Xd(t,e)}function Bd(t,r){var e,n=t.allWrites.findIndex(e=>e.writeId===r);g(0<=n,"removeWrite called with nonexistent writeId.");let i=t.allWrites[n],s=(t.allWrites.splice(n,1),i.visible),a=!1,o=t.allWrites.length-1;for(;s&&0<=o;){var l=t.allWrites[o];l.visible&&(o>=n&&((e,t)=>{if(e.snap)return lu(e.path,t);for(var r in e.children)if(e.children.hasOwnProperty(r)&&lu(iu(e.path,r),t))return 1})(l,i.path)?s=!1:lu(i.path,l.path)&&(a=!0)),o--}return!!s&&(a?((e=t).visibleWrites=zd(e.allWrites,jd,v()),0<e.allWrites.length?e.lastWriteId=e.allWrites[e.allWrites.length-1].writeId:e.lastWriteId=-1):i.snap?t.visibleWrites=xd(t.visibleWrites,i.path):Ic(i.children,e=>{t.visibleWrites=xd(t.visibleWrites,iu(i.path,e))}),!0)}function jd(e){return e.visible}function zd(e,t,r){let n=Rd.empty();for(let a=0;a<e.length;++a){var i=e[a];if(t(i)){var s=i.path;let e;if(i.snap)lu(r,s)?(e=su(r,s),n=Pd(n,e,i.snap)):lu(s,r)&&(e=su(s,r),n=Pd(n,v(),i.snap.getChild(e)));else{if(!i.children)throw B("WriteRecord should have .snap or .children");lu(r,s)?(e=su(r,s),n=Dd(n,e,i.children)):lu(s,r)&&(b(e=su(s,r))?n=Dd(n,v(),i.children):(s=be(i.children,_(e)))&&(i=s.getChild(y(e)),n=Pd(n,v(),i)))}}}return n}function Kd(e,t,r,n,i){var s;return n||i?(s=Fd(e.visibleWrites,t),!i&&Ud(s)?r:i||null!=r||Od(s,v())?Vd(zd(e.allWrites,function(e){return(e.visible||i)&&(!n||!~n.indexOf(e.writeId))&&(lu(e.path,t)||lu(t,e.path))},t),r||T.EMPTY_NODE):null):null!=(s=Md(e.visibleWrites,t))?s:Ud(s=Fd(e.visibleWrites,t))?r:null!=r||Od(s,v())?Vd(s,r||T.EMPTY_NODE):null}function Wd(e,t,r,n){return Kd(e.writeTree,e.treePath,t,r,n)}function Hd(e,t){{var r=e.writeTree;e=e.treePath;let i=T.EMPTY_NODE;var n=Md(r.visibleWrites,e);if(n)n.isLeafNode()||n.forEachChild(I,(e,t)=>{i=i.updateImmediateChild(e,t)});else if(t){let n=Fd(r.visibleWrites,e);t.forEachChild(I,(e,t)=>{var r=Vd(Fd(n,new f(e)),t);i=i.updateImmediateChild(e,r)}),Ld(n).forEach(e=>{i=i.updateImmediateChild(e.name,e.node)})}else Ld(Fd(r.visibleWrites,e)).forEach(e=>{i=i.updateImmediateChild(e.name,e.node)});return i}}function Gd(e,t,r,n){return i=e.writeTree,e=e.treePath,t=t,r=r,n=n,g(r||n,"Either existingEventSnap or existingServerSnap must exist"),s=iu(e,t),Od(i.visibleWrites,s)?null:Ud(s=Fd(i.visibleWrites,s))?n.getChild(t):Vd(s,n.getChild(t));var i,s}function $d(e,t){return r=e.writeTree,e=iu(e.treePath,t),Md(r.visibleWrites,e);var r}function Qd(e,r,n,i,s,a){{var o=e.writeTree,l=(e=e.treePath,n),h=i;n=s,i=a;let t;var c=Fd(o.visibleWrites,e),u=Md(c,v());if(null!=u)t=u;else{if(null==r)return[];t=Vd(c,r)}if((t=t.withIndex(i)).isEmpty()||t.isLeafNode())return[];{var d=[],p=i.getCompare(),f=n?t.getReverseIteratorFrom(l,i):t.getIteratorFrom(l,i);let e=f.getNext();for(;e&&d.length<h;)0!==p(e,l)&&d.push(e),e=f.getNext();return d}}}function Yd(e,t,r){return n=e.writeTree,r=r,i=iu(e.treePath,e=t),null!=(s=Md(n.visibleWrites,i))?s:r.isCompleteForChild(e)?Vd(Fd(n.visibleWrites,i),r.getNode().getImmediateChild(e)):null;var n,i,s}function Jd(e,t){return Xd(iu(e.treePath,t),e.writeTree)}function Xd(e,t){return{treePath:e,writeTree:t}}class Zd{constructor(){this.changeMap=new Map}trackChildChange(e){var t=e.type,r=e.childName,n=(g("child_added"===t||"child_changed"===t||"child_removed"===t,"Only child changes supported for tracking"),g(".priority"!==r,"Only non-priority child changes can be tracked."),this.changeMap.get(r));if(n){var i=n.type;if("child_added"===t&&"child_removed"===i)this.changeMap.set(r,Qu(r,e.snapshotNode,n.snapshotNode));else if("child_removed"===t&&"child_added"===i)this.changeMap.delete(r);else if("child_removed"===t&&"child_changed"===i)this.changeMap.set(r,$u(r,n.oldSnap));else if("child_changed"===t&&"child_added"===i)this.changeMap.set(r,Gu(r,e.snapshotNode));else{if("child_changed"!==t||"child_changed"!==i)throw B("Illegal combination of changes: "+e+" occurred after "+n);this.changeMap.set(r,Qu(r,e.snapshotNode,n.oldSnap))}}else this.changeMap.set(r,e)}getChanges(){return Array.from(this.changeMap.values())}}let ep=new class{getCompleteChild(e){return null}getChildAfterChild(e,t,r){return null}};class tp{constructor(e,t,r=null){this.writes_=e,this.viewCache_=t,this.optCompleteServerCache_=r}getCompleteChild(e){var t=this.viewCache_.eventCache;return t.isCompleteForChild(e)?t.getNode().getImmediateChild(e):(t=null!=this.optCompleteServerCache_?new yd(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache,Yd(this.writes_,e,t))}getChildAfterChild(e,t,r){var n=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:kd(this.viewCache_),n=Qd(this.writes_,n,t,1,r,e);return 0===n.length?null:n[0]}}function rp(e,t,r,n,i){var s=new Zd;let a,o;if(r.type===Xh.OVERWRITE){var l=r;a=l.source.fromUser?sp(e,t,l.path,l.snap,n,i,s):(g(l.source.fromServer,"Unknown source."),o=l.source.tagged||t.serverCache.isFiltered()&&!b(l.path),ip(e,t,l.path,l.snap,n,i,o,s))}else if(r.type===Xh.MERGE){var l=r;a=l.source.fromUser?((n,i,s,e,a,o,l)=>{let h=i;return e.foreach((e,t)=>{var r=iu(s,e);ap(i,_(r))&&(h=sp(n,h,r,t,a,o,l))}),e.foreach((e,t)=>{var r=iu(s,e);ap(i,_(r))||(h=sp(n,h,r,t,a,o,l))}),h})(e,t,l.path,l.children,n,i,s):(g(l.source.fromServer,"Unknown source."),o=l.source.tagged||t.serverCache.isFiltered(),lp(e,t,l.path,l.children,n,i,o,s))}else if(r.type===Xh.ACK_USER_WRITE){l=r;a=l.revert?((r,n,i,s,e,a)=>{let o;if(null!=$d(s,i))return n;{var l=new tp(s,n,e),h=n.eventCache.getNode();let t;if(b(i)||".priority"===_(i)){let e;e=e=n.serverCache.isFullyInitialized()?Wd(s,kd(n)):(c=n.serverCache.getNode(),g(c instanceof T,"serverChildren would be complete if leaf node"),Hd(s,c)),t=r.filter.updateFullNode(h,e,a)}else{var c=_(i);let e=Yd(s,c,n.serverCache);null==e&&n.serverCache.isCompleteForChild(c)&&(e=h.getImmediateChild(c)),(t=null!=e?r.filter.updateChild(h,c,e,y(i),l,a):n.eventCache.getNode().hasChild(c)?r.filter.updateChild(h,c,T.EMPTY_NODE,y(i),l,a):h).isEmpty()&&n.serverCache.isFullyInitialized()&&(o=Wd(s,kd(n))).isLeafNode()&&(t=r.filter.updateFullNode(t,o,a))}return o=n.serverCache.isFullyInitialized()||null!=$d(s,v()),Ed(n,t,o,r.filter.filtersNodes())}})(e,t,l.path,n,i,s):((e,t,i,r,s,a,o)=>{if(null!=$d(s,i))return t;let l=t.serverCache.isFiltered(),h=t.serverCache;if(null!=r.value){if(b(i)&&h.isFullyInitialized()||h.isCompleteForPath(i))return ip(e,t,i,h.getNode().getChild(i),s,a,l,o);if(b(i)){let r=new Nd(null);return h.getNode().forEachChild(vu,(e,t)=>{r=r.set(new f(e),t)}),lp(e,t,i,r,s,a,l,o)}return t}{let n=new Nd(null);return r.foreach((e,t)=>{var r=iu(i,e);h.isCompleteForPath(r)&&(n=n.set(e,h.getNode().getChild(r)))}),lp(e,t,i,n,s,a,l,o)}})(e,t,l.path,l.affectedTree,n,i,s)}else{if(r.type!==Xh.LISTEN_COMPLETE)throw B("Unknown operation type: "+r.type);a=(i=e,e=r.path,r=n,n=s,l=t.serverCache,l=Cd(t,l.getNode(),l.isFullyInitialized()||b(e),l.isFiltered()),np(i,l,e,r,ep,n))}var h,c,s=s.getChanges(),i=t,e=a,r=s,u=e.eventCache;return u.isFullyInitialized()&&(h=u.getNode().isLeafNode()||u.getNode().isEmpty(),c=Sd(i),0<r.length||!i.eventCache.isFullyInitialized()||h&&!u.getNode().equals(c)||!u.getNode().getPriority().equals(c.getPriority()))&&r.push(Hu(Sd(e))),{viewCache:a,changes:s}}function np(n,i,s,a,o,l){var h=i.eventCache;if(null!=$d(a,s))return i;{let t,r;if(b(s))g(i.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),t=i.serverCache.isFiltered()?(c=Hd(a,(c=kd(i))instanceof T?c:T.EMPTY_NODE),n.filter.updateFullNode(i.eventCache.getNode(),c,l)):(c=Wd(a,kd(i)),n.filter.updateFullNode(i.eventCache.getNode(),c,l));else{var c=_(s);if(".priority"===c){g(1===eu(s),"Can't have a priority with additional path components");var u=h.getNode(),d=Gd(a,s,u,r=i.serverCache.getNode());t=null!=d?n.filter.updatePriority(u,d):h.getNode()}else{u=y(s);let e;e=h.isCompleteForChild(c)?(r=i.serverCache.getNode(),null!=(d=Gd(a,s,h.getNode(),r))?h.getNode().getImmediateChild(c).updateChild(u,d):h.getNode().getImmediateChild(c)):Yd(a,c,i.serverCache),t=null!=e?n.filter.updateChild(h.getNode(),c,e,u,o,l):h.getNode()}}return Ed(i,t,h.isFullyInitialized()||b(s),n.filter.filtersNodes())}}function ip(e,t,r,n,i,s,a,o){var l=t.serverCache;let h;var c=a?e.filter:e.filter.getIndexedFilter();if(b(r))h=c.updateFullNode(l.getNode(),n,null);else if(c.filtersNodes()&&!l.isFiltered()){var u=l.getNode().updateChild(r,n);h=c.updateFullNode(l.getNode(),u,null)}else{u=_(r);if(!l.isCompleteForPath(r)&&1<eu(r))return t;var d=y(r),p=l.getNode().getImmediateChild(u).updateChild(d,n);h=".priority"===u?c.updatePriority(l.getNode(),p):c.updateChild(l.getNode(),u,p,d,ep,null)}u=Cd(t,h,l.isFullyInitialized()||b(r),c.filtersNodes());return np(e,u,r,i,new tp(i,u,s),o)}function sp(t,r,n,i,e,s,a){var o=r.eventCache;let l,h;var c=new tp(e,r,s);if(b(n))h=t.filter.updateFullNode(r.eventCache.getNode(),i,a),l=Ed(r,h,!0,t.filter.filtersNodes());else{var u=_(n);if(".priority"===u)h=t.filter.updatePriority(r.eventCache.getNode(),i),l=Ed(r,h,o.isFullyInitialized(),o.isFiltered());else{var d,p=y(n),f=o.getNode().getImmediateChild(u);let e;e=b(p)?i:null!=(d=c.getCompleteChild(u))?".priority"===tu(p)&&d.getChild(nu(p)).isEmpty()?d:d.updateChild(p,i):T.EMPTY_NODE,l=f.equals(e)?r:Ed(r,t.filter.updateChild(o.getNode(),u,e,p,c,a),o.isFullyInitialized(),t.filter.filtersNodes())}}return l}function ap(e,t){return e.eventCache.isCompleteForChild(t)}function op(e,r,t){return t.foreach((e,t)=>{r=r.updateChild(e,t)}),r}function lp(n,i,e,t,s,a,o,l){if(i.serverCache.getNode().isEmpty()&&!i.serverCache.isFullyInitialized())return i;let h=i,r,c=(r=b(e)?t:new Nd(null).setTree(e,t),i.serverCache.getNode());return r.children.inorderTraversal((e,t)=>{var r;c.hasChild(e)&&(r=op(0,i.serverCache.getNode().getImmediateChild(e),t),h=ip(n,h,new f(e),r,s,a,o,l))}),r.children.inorderTraversal((e,t)=>{var r=!i.serverCache.isCompleteForChild(e)&&null===t.value;c.hasChild(e)||r||(r=op(0,i.serverCache.getNode().getImmediateChild(e),t),h=ip(n,h,new f(e),r,s,a,o,l))}),h}class hp{constructor(e,t){this.query_=e,this.eventRegistrations_=[];var r=this.query_._queryParams,n=new Yu(r.getIndex()),r=(e=r).loadsAllData()?new Yu(e.getIndex()):new(e.hasLimit()?Xu:Ju)(e),i=(this.processor_={filter:r},t.serverCache),s=t.eventCache,a=n.updateFullNode(T.EMPTY_NODE,i.getNode(),null),o=r.updateFullNode(T.EMPTY_NODE,s.getNode(),null),a=new yd(a,i.isFullyInitialized(),n.filtersNodes()),i=new yd(o,s.isFullyInitialized(),r.filtersNodes());this.viewCache_=Td(i,a),this.eventGenerator_=new wd(this.query_)}get query(){return this.query_}}function cp(e){return 0===e.eventRegistrations_.length}function up(n,i,s){let a=[];if(s){g(null==i,"A cancel should cancel all event registrations.");let r=n.query._path;n.eventRegistrations_.forEach(e=>{var t=e.createCancelEvent(s,r);t&&a.push(t)})}if(i){let e=[];for(let t=0;t<n.eventRegistrations_.length;++t){var r=n.eventRegistrations_[t];if(r.matches(i)){if(i.hasAnyCallback()){e=e.concat(n.eventRegistrations_.slice(t+1));break}}else e.push(r)}n.eventRegistrations_=e}else n.eventRegistrations_=[];return a}function dp(e,t,r,n){t.type===Xh.MERGE&&null!==t.source.queryId&&(g(kd(e.viewCache_),"We should always have a full cache before handling merges"),g(Sd(e.viewCache_),"Missing event cache, even though we have a server cache"));var i=e.viewCache_,s=rp(e.processor_,i,t,r,n);return t=e.processor_,r=s.viewCache,g(r.eventCache.getNode().isIndexed(t.filter.getIndex()),"Event snap not indexed"),g(r.serverCache.getNode().isIndexed(t.filter.getIndex()),"Server snap not indexed"),g(s.viewCache.serverCache.isFullyInitialized()||!i.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),e.viewCache_=s.viewCache,pp(e,s.changes,s.viewCache.eventCache.getNode(),null)}function pp(e,t,r,n){var i=n?[n]:e.eventRegistrations_;return bd(e.eventGenerator_,t,r,i)}let fp;class gp{constructor(){this.views=new Map}}function mp(t,r,n,i){var e=r.source.queryId;if(null!==e)return e=t.views.get(e),g(null!=e,"SyncTree gave us an op for an invalid query."),dp(e,r,n,i);{let e=[];for(var s of t.views.values())e=e.concat(dp(s,r,n,i));return e}}function vp(e,r,n,i,s){var a=r._queryIdentifier,a=e.views.get(a);if(a)return a;{let e=Wd(n,s?i:null),t=!1;t=!!e||(e=i instanceof T?Hd(n,i):T.EMPTY_NODE,!1);a=Td(new yd(e,t,!1),new yd(i,s,!1));return new hp(r,a)}}function _p(e,t,n,i,s,r){var a=vp(e,t,i,s,r);e.views.has(t._queryIdentifier)||e.views.set(t._queryIdentifier,a),a.eventRegistrations_.push(n);{s=n,a=(i=a).viewCache_.eventCache;let r=[];return a.getNode().isLeafNode()||a.getNode().forEachChild(I,(e,t)=>{r.push(Gu(e,t))}),a.isFullyInitialized()&&r.push(Hu(a.getNode())),pp(i,r,a.getNode(),s)}}function yp(e,t,r,n){var i=t._queryIdentifier,s=[];let a=[];var o=Ep(e);if("default"===i)for(var[l,h]of e.views.entries())a=a.concat(up(h,r,n)),cp(h)&&(e.views.delete(l),h.query._queryParams.loadsAllData()||s.push(h.query));else{var c=e.views.get(i);c&&(a=a.concat(up(c,r,n)),cp(c))&&(e.views.delete(i),c.query._queryParams.loadsAllData()||s.push(c.query))}return o&&!Ep(e)&&s.push((g(fp,"Reference.ts has not been loaded"),new fp(t._repo,t._path))),{removed:s,events:a}}function wp(e){var t,r=[];for(t of e.views.values())t.query._queryParams.loadsAllData()||r.push(t);return r}function bp(e,t){let r=null;for(var n of e.views.values())r=r||(i=n,s=t,n=void 0,(n=kd(i.viewCache_))&&(i.query._queryParams.loadsAllData()||!b(s)&&!n.getImmediateChild(_(s)).isEmpty())?n.getChild(s):null);var i,s;return r}function Ip(e,t){var r;return t._queryParams.loadsAllData()?Cp(e):(r=t._queryIdentifier,e.views.get(r))}function Tp(e,t){return null!=Ip(e,t)}function Ep(e){return null!=Cp(e)}function Cp(e){for(var t of e.views.values())if(t.query._queryParams.loadsAllData())return t;return null}let Sp;let kp=1;class Ap{constructor(e){this.listenProvider_=e,this.syncPointTree_=new Nd(null),this.pendingWriteTree_={visibleWrites:Rd.empty(),allWrites:[],lastWriteId:-1},this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function Np(e,t,r,n,i){var s,a,o,l;return s=e.pendingWriteTree_,a=t,o=r,n=n,l=i,g(n>s.lastWriteId,"Stacking an older write on top of newer ones"),s.allWrites.push({path:a,snap:o,writeId:n,visible:l=void 0===l?!0:l}),l&&(s.visibleWrites=Pd(s.visibleWrites,a,o)),s.lastWriteId=n,i?Up(e,new vd(dd(),t,r)):[]}function Rp(e,t,r,n){i=e.pendingWriteTree_,s=t,a=r,n=n,g(n>i.lastWriteId,"Stacking an older merge on top of newer ones"),i.allWrites.push({path:s,children:a,writeId:n,visible:!0}),i.visibleWrites=Dd(i.visibleWrites,s,a),i.lastWriteId=n;var i,s,a,o=Nd.fromObject(r);return Up(e,new _d(dd(),t,o))}function Pp(e,t,r=!1){var n=((e,t)=>{for(let n=0;n<e.allWrites.length;n++){var r=e.allWrites[n];if(r.writeId===t)return r}return null})(e.pendingWriteTree_,t);if(Bd(e.pendingWriteTree_,t)){let t=new Nd(null);return null!=n.snap?t=t.set(v(),!0):Ic(n.children,e=>{t=t.set(new f(e),!0)}),Up(e,new gd(n.path,t,r))}return[]}function Dp(e,t,r){return Up(e,new vd(pd(),t,r))}function xp(r,t,n,i,s=!1){var a=t._path,o=r.syncPointTree_.get(a);let l=[];if(o&&("default"===t._queryIdentifier||Tp(o,t))){var h=yp(o,t,n,i),o=(0===o.views.size&&(r.syncPointTree_=r.syncPointTree_.remove(a)),h.removed);if(l=h.events,!s){var h=-1!==o.findIndex(e=>e._queryParams.loadsAllData()),c=r.syncPointTree_.findOnPath(a,(e,t)=>Ep(t));if(h&&!c){a=r.syncPointTree_.subtree(a);if(!a.isEmpty()){var u=a.fold((e,t,n)=>{if(t&&Ep(t))return[Cp(t)];{let r=[];return t&&(r=wp(t)),Ic(n,(e,t)=>{r=r.concat(t)}),r}});for(let e=0;e<u.length;++e){var d=u[e],p=d.query,d=qp(r,d);r.listenProvider_.startListening(Hp(p),Bp(r,p),d.hashFn,d.onComplete)}}}!c&&0<o.length&&!i&&(h?r.listenProvider_.stopListening(Hp(t),null):o.forEach(e=>{var t=r.queryToTagMap.get(jp(e));r.listenProvider_.stopListening(Hp(e),t)}))}var f=r,g=o;for(let e=0;e<g.length;++e){var m,v=g[e];v._queryParams.loadsAllData()||(v=jp(v),m=f.queryToTagMap.get(v),f.queryToTagMap.delete(v),f.tagToQueryMap.delete(m))}}return l}function Op(e,t,r,n){var i,s,a=zp(e,n);return null!=a?(i=(a=Kp(a)).path,a=a.queryId,s=su(i,t),Wp(e,i,new vd(fd(a),s,r))):[]}function Mp(e,t,r,n=!1){let i=t._path,s=null,a=!1,o=(e.syncPointTree_.foreachOnPath(i,(e,t)=>{var r=su(e,i);s=s||bp(t,r),a=a||Ep(t)}),e.syncPointTree_.get(i));o?(a=a||Ep(o),s=s||bp(o,v())):(o=new gp,e.syncPointTree_=e.syncPointTree_.set(i,o));let l;null!=s?l=!0:(l=!1,s=T.EMPTY_NODE,e.syncPointTree_.subtree(i).foreachChild((e,t)=>{var r=bp(t,v());r&&(s=s.updateImmediateChild(e,r))}));var h,c=Tp(o,t),u=(c||t._queryParams.loadsAllData()||(h=jp(t),g(!e.queryToTagMap.has(h),"View does not exist, but we have a tag"),u=kp++,e.queryToTagMap.set(h,u),e.tagToQueryMap.set(u,h)),qd(e.pendingWriteTree_,i));let d=_p(o,t,r,u,s,l);return c||a||n||(h=Ip(o,t),d=d.concat(((t,e,r)=>{var n=e._path,i=Bp(t,e),s=qp(t,r),s=t.listenProvider_.startListening(Hp(e),i,s.hashFn,s.onComplete),n=t.syncPointTree_.subtree(n);if(i)g(!Ep(n.value),"If we're adding a query, it shouldn't be shadowed");else{var a=n.fold((e,t,n)=>{if(!b(e)&&t&&Ep(t))return[Cp(t).query];{let r=[];return t&&(r=r.concat(wp(t).map(e=>e.query))),Ic(n,(e,t)=>{r=r.concat(t)}),r}});for(let e=0;e<a.length;++e){var o=a[e];t.listenProvider_.stopListening(Hp(o),Bp(t,o))}}return s})(e,t,h))),d}function Lp(e,n,t){var r=e.pendingWriteTree_,i=e.syncPointTree_.findOnPath(n,(e,t)=>{var r=bp(t,su(e,n));if(r)return r});return Kd(r,n,i,t,!0)}function Fp(e,t){let n=t._path,i=null,r=(e.syncPointTree_.foreachOnPath(n,(e,t)=>{var r=su(e,n);i=i||bp(t,r)}),e.syncPointTree_.get(n));r?i=i||bp(r,v()):(r=new gp,e.syncPointTree_=e.syncPointTree_.set(n,r));var s=null!=i,a=s?new yd(i,!0,!1):null,o=qd(e.pendingWriteTree_,t._path);return Sd(vp(r,t,o,s?a.getNode():T.EMPTY_NODE,s).viewCache_)}function Up(e,t){return function a(t,o,l,h){{if(b(t.path))return Vp(t,o,l,h);{let e=o.get(v()),r=(null==l&&null!=e&&(l=bp(e,v())),[]),n=_(t.path),i=t.operationForChild(n),s=o.children.get(n);if(s&&i){let e=l?l.getImmediateChild(n):null,t=Jd(h,n);r=r.concat(a(i,s,e,t))}return r=e?r.concat(mp(e,t,h,l)):r}}}(t,e.syncPointTree_,null,qd(e.pendingWriteTree_,v()))}function Vp(s,e,a,o){var t=e.get(v());null==a&&null!=t&&(a=bp(t,v()));let l=[];return e.children.inorderTraversal((e,t)=>{var r=a?a.getImmediateChild(e):null,n=Jd(o,e),i=s.operationForChild(e);i&&(l=l.concat(Vp(i,t,r,n)))}),l=t?l.concat(mp(t,s,o,a)):l}function qp(o,e){let l=e.query,h=Bp(o,l);return{hashFn:()=>(e.viewCache_.serverCache.getNode()||T.EMPTY_NODE).hash(),onComplete:e=>{var t,r,n,i,s,a;return"ok"===e?h?(t=o,r=l._path,n=h,(a=zp(t,n))?(i=(a=Kp(a)).path,a=a.queryId,s=su(i,r),Wp(t,i,new md(fd(a),s))):[]):(n=o,r=l._path,Up(n,new md(pd(),r))):(i=((e,t)=>{let r="Unknown Error";"too_big"===e?r="The data requested exceeds the maximum size that can be accessed with a single request.":"permission_denied"===e?r="Client doesn't have permission to access the desired data.":"unavailable"===e&&(r="The service is unavailable");var n=new Error(e+" at "+t._path.toString()+": "+r);return n.code=e.toUpperCase(),n})(e,l),xp(o,l,null,i))}}}function Bp(e,t){var r=jp(t);return e.queryToTagMap.get(r)}function jp(e){return e._path.toString()+"$"+e._queryIdentifier}function zp(e,t){return e.tagToQueryMap.get(t)}function Kp(e){var t=e.indexOf("$");return g(-1!==t&&t<e.length-1,"Bad queryKey."),{queryId:e.substr(t+1),path:new f(e.substr(0,t))}}function Wp(e,t,r){var n=e.syncPointTree_.get(t),i=(g(n,"Missing sync point for query tag that we're tracking"),qd(e.pendingWriteTree_,t));return mp(n,r,i,null)}function Hp(e){return e._queryParams.loadsAllData()&&!e._queryParams.isDefault()?(g(Sp,"Reference.ts has not been loaded"),new Sp(e._repo,e._path)):e}class Gp{constructor(e){this.node_=e}getImmediateChild(e){var t=this.node_.getImmediateChild(e);return new Gp(t)}node(){return this.node_}}class $p{constructor(e,t){this.syncTree_=e,this.path_=t}getImmediateChild(e){var t=iu(this.path_,e);return new $p(this.syncTree_,t)}node(){return Lp(this.syncTree_,this.path_)}}let Qp=function(e){return(e=e||{}).timestamp=e.timestamp||(new Date).getTime(),e},Yp=function(e,t,r){return e&&"object"==typeof e?(g(".sv"in e,"Unexpected leaf node or priority contents"),"string"==typeof e[".sv"]?Jp(e[".sv"],t,r):"object"==typeof e[".sv"]?Xp(e[".sv"],t):void g(!1,"Unexpected server value: "+JSON.stringify(e,null,2))):e},Jp=function(e,t,r){if("timestamp"===e)return r.timestamp;g(!1,"Unexpected server value: "+e)},Xp=function(e,t,r){e.hasOwnProperty("increment")||g(!1,"Unexpected server value: "+JSON.stringify(e,null,2));var n=e.increment,i=("number"!=typeof n&&g(!1,"Unexpected increment value: "+n),t.node());return g(null!=i,"Expected ChildrenNode.EMPTY_NODE for nulls"),!i.isLeafNode()||"number"!=typeof(i=i.getValue())?n:i+n},Zp=function(e,t,r,n){return tf(t,new $p(r,e),n)},ef=function(e,t,r){return tf(e,new Gp(t),r)};function tf(e,n,i){var t,r,s=e.getPriority().val(),s=Yp(s,n.getImmediateChild(".priority"),i);let a;return e.isLeafNode()?(r=e,(t=Yp(r.getValue(),n,i))!==r.getValue()||s!==r.getPriority().val()?new Au(t,ju(s)):e):(r=e,s!==(a=r).getPriority().val()&&(a=a.updatePriority(new Au(s))),r.forEachChild(I,(e,t)=>{var r=tf(t,n.getImmediateChild(e),i);r!==t&&(a=a.updateImmediateChild(e,r))}),a)}class rf{constructor(e="",t=null,r={children:{},childCount:0}){this.name=e,this.parent=t,this.node=r}}function nf(e,t){let r=t instanceof f?t:new f(t),n=e,i=_(r);for(;null!==i;){var s=be(n.node.children,i)||{children:{},childCount:0};n=new rf(i,n,s),r=y(r),i=_(r)}return n}function sf(e){return e.node.value}function af(e,t){e.node.value=t,cf(e)}function of(e){return 0<e.node.childCount}function lf(r,n){Ic(r.node.children,(e,t)=>{n(new rf(e,r,t))})}function hf(e){return new f(null===e.parent?e.name:hf(e.parent)+"/"+e.name)}function cf(e){var t,r,n,i;null!==e.parent&&(t=e.parent,r=e.name,n=(e=>void 0===sf(e)&&!of(e))(e=e),i=we(t.node.children,r),n&&i?(delete t.node.children[r],t.node.childCount--,cf(t)):n||i||(t.node.children[r]=e.node,t.node.childCount++,cf(t)))}function uf(e,t,r,n){n&&void 0===t||Ef(xe(e,"value"),t,r)}function df(e,t,s,r){if(!r||void 0!==t){let n=xe(e,"values");if(!t||"object"!=typeof t||Array.isArray(t))throw new Error(n+" must be an object containing the children to replace.");let i=[];Ic(t,(e,t)=>{var r=new f(e);if(Ef(n,t,iu(s,r)),".priority"===tu(r)&&!Tf(t))throw new Error(n+"contains an invalid value for '"+r.toString()+"', which must be a valid Firebase priority (a string, finite number, server value, or null).");i.push(r)});{var a=n;var o=i;let t,r;for(t=0;t<o.length;t++){var l=ru(r=o[t]);for(let e=0;e<l.length;e++)if((".priority"!==l[e]||e!==l.length-1)&&!wf(l[e]))throw new Error(a+"contains an invalid key ("+l[e]+") in path "+r.toString()+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"')}o.sort(au);let e=null;for(t=0;t<o.length;t++){if(r=o[t],null!==e&&lu(e,r))throw new Error(a+"contains a path "+e.toString()+" that is ancestor of another path "+r.toString());e=r}}}}function pf(e,t,r){if(!r||void 0!==t){if(_c(t))throw new Error(xe(e,"priority")+"is "+t.toString()+", but must be a valid Firebase priority (a string, finite number, server value, or null).");if(!Tf(t))throw new Error(xe(e,"priority")+"must be a valid Firebase priority (a string, finite number, server value, or null).")}}function ff(e,t,r,n){if(!(n&&void 0===r||wf(r)))throw new Error(xe(e,t)+'was an invalid key = "'+r+'". Firebase keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]").')}function gf(e,t,r,n){r=r&&r.replace(/^\/*\.info(\/|$)/,"/"),Cf(e,t,r,n)}function mf(e,t){if(".info"===_(t))throw new Error(e+" failed = Can't modify data under /.info/")}let vf=/[\[\].#$\/\u0000-\u001F\u007F]/,_f=/[\[\].#$\u0000-\u001F\u007F]/,yf=10485760,wf=function(e){return"string"==typeof e&&0!==e.length&&!vf.test(e)},bf=function(e){return"string"==typeof e&&0!==e.length&&!_f.test(e)},If=function(e){return e=e&&e.replace(/^\/*\.info(\/|$)/,"/"),bf(e)},Tf=function(e){return null===e||"string"==typeof e||"number"==typeof e&&!_c(e)||e&&"object"==typeof e&&we(e,".sv")},Ef=function(a,e,t){let o=t instanceof f?new hu(t,a):t;if(void 0===e)throw new Error(a+"contains undefined "+uu(o));if("function"==typeof e)throw new Error(a+"contains a function "+uu(o)+" with contents = "+e.toString());if(_c(e))throw new Error(a+"contains "+e.toString()+" "+uu(o));if("string"==typeof e&&e.length>yf/3&&Le(e)>yf)throw new Error(a+"contains a string greater than "+yf+" utf8 bytes "+uu(o)+" ('"+e.substring(0,50)+"...')");if(e&&"object"==typeof e){let i=!1,s=!1;if(Ic(e,(e,t)=>{if(".value"===e)i=!0;else if(".priority"!==e&&".sv"!==e&&(s=!0,!wf(e)))throw new Error(a+" contains an invalid key ("+e+") "+uu(o)+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');var r,n;r=o,e=e,0<r.parts_.length&&(r.byteLength_+=1),r.parts_.push(e),r.byteLength_+=Le(e),cu(r),Ef(a,t,o),e=o,n=e.parts_.pop(),e.byteLength_-=Le(n),0<e.parts_.length&&--e.byteLength_}),i&&s)throw new Error(a+' contains ".value" child '+uu(o)+" in addition to actual children.")}},Cf=function(e,t,r,n){if(!(n&&void 0===r||bf(r)))throw new Error(xe(e,t)+'was an invalid path = "'+r+'". Paths must be non-empty strings and can\'t contain ".", "#", "$", "[", or "]"')},Sf=function(e,t){var r=t.path.toString();if("string"!=typeof t.repoInfo.host||0===t.repoInfo.host.length||!wf(t.repoInfo.namespace)&&"localhost"!==t.repoInfo.host.split(":")[0]||0!==r.length&&!If(r))throw new Error(xe(e,"url")+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')};class kf{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function Af(e,t){let r=null;for(let s=0;s<t.length;s++){var n=t[s],i=n.getPath();null===r||ou(i,r.path)||(e.eventLists_.push(r),r=null),(r=null===r?{events:[],path:i}:r).events.push(n)}r&&e.eventLists_.push(r)}function Nf(e,t,r){Af(e,r),Pf(e,e=>ou(e,t))}function Rf(e,t,r){Af(e,r),Pf(e,e=>lu(e,t)||lu(t,e))}function Pf(t,e){t.recursionDepth_++;let r=!0;for(let o=0;o<t.eventLists_.length;o++){var n=t.eventLists_[o];if(n)if(e(n.path)){s=a=i=void 0;var i=t.eventLists_[o];for(let e=0;e<i.events.length;e++){var s,a=i.events[e];null!==a&&(i.events[e]=null,s=a.getEventRunner(),uc&&fc("event: "+a.toString()),Nc(s))}t.eventLists_[o]=null}else r=!1}r&&(t.eventLists_=[]),t.recursionDepth_--}let Df="repo_interrupt",xf=25;class Of{constructor(e,t,r,n){this.repoInfo_=e,this.forceRestClient_=t,this.authTokenProvider_=r,this.appCheckProvider_=n,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new kf,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=od(),this.transactionQueueTree_=new rf,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function Mf(a,e,t){if(a.stats_=Bc(a.repoInfo_),a.forceRestClient_||0<=("object"==typeof window&&window.navigator&&window.navigator.userAgent||"").search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i))a.server_=new sd(a.repoInfo_,(e,t,r,n)=>{Uf(a,e,t,r,n)},a.authTokenProvider_,a.appCheckProvider_),setTimeout(()=>Vf(a,!0),0);else{if(null!=t){if("object"!=typeof t)throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{_e(t)}catch(e){throw new Error("Invalid authOverride provided: "+e)}}a.persistentConnection_=new pu(a.repoInfo_,e,(e,t,r,n)=>{Uf(a,e,t,r,n)},e=>{Vf(a,e)},e=>{var r;r=a,Ic(e,(e,t)=>{qf(r,e,t)})},a.authTokenProvider_,a.appCheckProvider_,t),a.server_=a.persistentConnection_}var r;a.authTokenProvider_.addTokenChangeListener(e=>{a.server_.refreshAuthToken(e)}),a.appCheckProvider_.addTokenChangeListener(e=>{a.server_.refreshAppCheckToken(e.token)}),a.statsReporter_=(e=()=>new ud(a.stats_,a.server_),r=a.repoInfo_.toString(),qc[r]||(qc[r]=e()),qc[r]),a.infoData_=new ad,a.infoSyncTree_=new Ap({startListening:(e,t,r,n)=>{let i=[];var s=a.infoData_.getNode(e._path);return s.isEmpty()||(i=Dp(a.infoSyncTree_,e._path,s),setTimeout(()=>{n("ok")},0)),i},stopListening:()=>{}}),qf(a,"connected",!1),a.serverSyncTree_=new Ap({startListening:(n,e,t,i)=>(a.server_.listen(n,t,e,(e,t)=>{var r=i(e,t);Rf(a.eventQueue_,n._path,r)}),[]),stopListening:(e,t)=>{a.server_.unlisten(e,t)}})}function Lf(e){var t=e.infoData_.getNode(new f(".info/serverTimeOffset")).val()||0;return(new Date).getTime()+t}function Ff(e){return Qp({timestamp:Lf(e)})}function Uf(e,t,r,n,i){e.dataUpdateCount++;var s,a,o,l,h,c,u=new f(t);r=e.interceptServerDataCallback_?e.interceptServerDataCallback_(t,r):r;let d=[],p=u;0<(d=i?n?(c=Te(r,e=>ju(e)),t=e.serverSyncTree_,s=u,a=c,(c=zp(t,i))?(o=(c=Kp(c)).path,c=c.queryId,l=su(o,s),h=Nd.fromObject(a),Wp(t,o,new _d(fd(c),l,h))):[]):(o=ju(r),Op(e.serverSyncTree_,u,o,i)):n?(c=Te(r,e=>ju(e)),s=e.serverSyncTree_,a=u,t=c,l=Nd.fromObject(t),Up(s,new _d(pd(),a,l))):(h=ju(r),Dp(e.serverSyncTree_,u,h))).length&&(p=Jf(e,u)),Rf(e.eventQueue_,p,d)}function Vf(e,t){if(qf(e,"connected",t),!1===t){var a=e;Gf(a,"onDisconnectEvents");let n=Ff(a),i=od(),s=(hd(a.onDisconnect_,v(),(e,t)=>{var r=Zp(e,t,a.serverSyncTree_,n);ld(i,e,r)}),[]);hd(i,v(),(e,t)=>{s=s.concat(Dp(a.serverSyncTree_,e,t));var r=tg(a,e);Jf(a,r)}),a.onDisconnect_=od(),Rf(a.eventQueue_,v(),s)}}function qf(e,t,r){var n=new f("/.info/"+t),i=ju(r),i=(e.infoData_.updateSnapshot(n,i),Dp(e.infoSyncTree_,n,i));Rf(e.eventQueue_,n,i)}function Bf(e){return e.nextWriteId_++}function jf(n,i,e,t,s){Gf(n,"set",{path:i.toString(),value:e,priority:t});var r=Ff(n),a=ju(e,t),o=Lp(n.serverSyncTree_,i),o=ef(a,o,r);let l=Bf(n);r=Np(n.serverSyncTree_,i,o,l,!0),Af(n.eventQueue_,r),n.server_.put(i.toString(),a.val(!0),(e,t)=>{var r="ok"===e,r=(r||mc("set at "+i+" failed: "+e),Pp(n.serverSyncTree_,l,!r));Rf(n.eventQueue_,i,r),$f(0,s,e,t)}),o=tg(n,i);Jf(n,o),Rf(n.eventQueue_,o,[])}function zf(r,n,i){r.server_.onDisconnectCancel(n.toString(),(e,t)=>{"ok"===e&&!function e(r,t){var n;return b(t)?(r.value=null,r.children.clear(),!0):null!==r.value?!r.value.isLeafNode()&&(n=r.value,r.value=null,n.forEachChild(I,(e,t)=>{ld(r,new f(e),t)}),e(r,t)):!(0<r.children.size)||(n=_(t),t=y(t),r.children.has(n)&&e(r.children.get(n),t)&&r.children.delete(n),0===r.children.size)}(r.onDisconnect_,n),$f(0,i,e,t)})}function Kf(r,n,e,i){let s=ju(e);r.server_.onDisconnectPut(n.toString(),s.val(!0),(e,t)=>{"ok"===e&&ld(r.onDisconnect_,n,s),$f(0,i,e,t)})}function Wf(e,t,r){let n;n=".info"===_(t._path)?xp(e.infoSyncTree_,t,r):xp(e.serverSyncTree_,t,r),Nf(e.eventQueue_,t._path,n)}function Hf(e){e.persistentConnection_&&e.persistentConnection_.interrupt(Df)}function Gf(e,...t){let r="";e.persistentConnection_&&(r=e.persistentConnection_.id+":"),fc(r,...t)}function $f(e,n,i,s){n&&Nc(()=>{if("ok"===i)n(null);else{var t=(i||"error").toUpperCase();let e=t;s&&(e+=": "+s);var r=new Error(e);r.code=t,n(r)}})}function Qf(e,t,r){return Lp(e.serverSyncTree_,t,r)||T.EMPTY_NODE}function Yf(o,l=o.transactionQueueTree_){if(l||eg(o,l),sf(l)){var h=Zf(o,l),e=(g(0<h.length,"Sending zero length transaction queue"),h.every(e=>0===e.status));if(e){var c=o;var u=hf(l);var d=h;let e=d.map(e=>e.currentWriteId),t=Qf(c,u,e),r=t,n=t.hash();for(let a=0;a<d.length;a++){var p=d[a],f=(g(0===p.status,"tryToSendTransactionQueue_: items in queue should all be run."),p.status=1,p.retryCount++,su(u,p.path));r=r.updateChild(f,p.currentOutputSnapshotRaw)}let i=r.val(!0),s=u;c.server_.put(s.toString(),i,t=>{Gf(c,"transaction put response",{path:s.toString(),status:t});let r=[];if("ok"===t){var n=[];for(let e=0;e<d.length;e++)d[e].status=2,r=r.concat(Pp(c.serverSyncTree_,d[e].currentWriteId)),d[e].onComplete&&n.push(()=>d[e].onComplete(null,!0,d[e].currentOutputSnapshotResolved)),d[e].unwatcher();eg(c,nf(c.transactionQueueTree_,u)),Yf(c,c.transactionQueueTree_),Rf(c.eventQueue_,u,r);for(let t=0;t<n.length;t++)Nc(n[t])}else{if("datastale"===t)for(let e=0;e<d.length;e++)3===d[e].status?d[e].status=4:d[e].status=0;else{mc("transaction at "+s.toString()+" failed: "+t);for(let e=0;e<d.length;e++)d[e].status=4,d[e].abortReason=t}Jf(c,u)}},n)}}else of(l)&&lf(l,e=>{Yf(o,e)})}function Jf(e,t){var r=Xf(e,t),n=hf(r),r=Zf(e,r),i=e,s=r,a=n;if(0!==s.length){var o=[];let r=[];var l=s.filter(e=>0===e.status).map(e=>e.currentWriteId);for(let n=0;n<s.length;n++){var h=s[n],c=su(a,h.path);let e=!1,t;if(g(null!==c,"rerunTransactionsUnderNode_: relativePath should not be null."),4===h.status)e=!0,t=h.abortReason,r=r.concat(Pp(i.serverSyncTree_,h.currentWriteId,!0));else if(0===h.status)if(h.retryCount>=xf)e=!0,t="maxretry",r=r.concat(Pp(i.serverSyncTree_,h.currentWriteId,!0));else{var c=Qf(i,h.path,l),u=(h.currentInputSnapshot=c,s[n].update(c.val()));if(void 0!==u){Ef("transaction failed: Data returned ",u,h.path);let e=ju(u);"object"==typeof u&&null!=u&&we(u,".priority")||(e=e.updatePriority(c.getPriority()));var u=h.currentWriteId,d=Ff(i),c=ef(e,c,d);h.currentOutputSnapshotRaw=e,h.currentOutputSnapshotResolved=c,h.currentWriteId=Bf(i),l.splice(l.indexOf(u),1),r=(r=r.concat(Np(i.serverSyncTree_,h.path,c,h.currentWriteId,h.applyLocally))).concat(Pp(i.serverSyncTree_,u,!0))}else e=!0,t="nodata",r=r.concat(Pp(i.serverSyncTree_,h.currentWriteId,!0))}Rf(i.eventQueue_,a,r),r=[],e&&(s[n].status=2,(e=>{setTimeout(e,Math.floor(0))})(s[n].unwatcher),s[n].onComplete)&&("nodata"===t?o.push(()=>s[n].onComplete(null,!1,s[n].currentInputSnapshot)):o.push(()=>s[n].onComplete(new Error(t),!1,null)))}eg(i,i.transactionQueueTree_);for(let e=0;e<o.length;e++)Nc(o[e]);Yf(i,i.transactionQueueTree_)}return n}function Xf(e,t){let r,n=e.transactionQueueTree_;for(r=_(t);null!==r&&void 0===sf(n);)n=nf(n,r),t=y(t),r=_(t);return n}function Zf(e,t){var r=[];return function t(r,e,n){let i=sf(e);if(i)for(let e=0;e<i.length;e++)n.push(i[e]);lf(e,e=>{t(r,e,n)})}(e,t,r),r.sort((e,t)=>e.order-t.order),r}function eg(t,r){var n=sf(r);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,af(r,0<n.length?n:void 0)}lf(r,e=>{eg(t,e)})}function tg(t,e){var r=hf(Xf(t,e)),n=nf(t.transactionQueueTree_,e);return((e,t,r)=>{let n=r?e:e.parent;for(;null!==n;){if(t(n))return;n=n.parent}})(n,e=>{rg(t,e)}),rg(t,n),function t(e,r,n,i){n&&!i&&r(e),lf(e,e=>{t(e,r,!0,i)}),n&&i&&r(e)}(n,e=>{rg(t,e)}),r}function rg(i,s){var a=sf(s);if(a){var o=[];let e=[],t=-1;for(let r=0;r<a.length;r++)3!==a[r].status&&(1===a[r].status?(g(t===r-1,"All SENT items should be at beginning of queue."),a[t=r].status=3,a[r].abortReason="set"):(g(0===a[r].status,"Unexpected transaction status in abort"),a[r].unwatcher(),e=e.concat(Pp(i.serverSyncTree_,a[r].currentWriteId,!0)),a[r].onComplete&&o.push(a[r].onComplete.bind(null,new Error("set"),!1,null))));-1===t?af(s,void 0):a.length=t+1,Rf(i.eventQueue_,hf(s),e);for(let n=0;n<o.length;n++)Nc(o[n])}}let ng=function(e,t){var r=ig(e),n=r.namespace,i=("firebase.com"===r.domain&&gc(r.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),n&&"undefined"!==n||"localhost"===r.domain||gc("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),r.secure||vc(),"ws"===r.scheme||"wss"===r.scheme);return{repoInfo:new Lc(r.host,r.secure,n,i,t,"",n!==r.subdomain),path:new f(r.pathString)}},ig=function(n){let i="",s="",a="",o="",l="",h=!0,c="https",u=443;if("string"==typeof n){let e=n.indexOf("//"),t=(0<=e&&(c=n.substring(0,e-1),n=n.substring(e+2)),n.indexOf("/")),r=(-1===t&&(t=n.length),n.indexOf("?"));-1===r&&(r=n.length),i=n.substring(0,Math.min(t,r)),t<r&&(o=(e=>{let t="";var r=e.split("/");for(let n=0;n<r.length;n++)if(0<r[n].length){let e=r[n];try{e=decodeURIComponent(e.replace(/\+/g," "))}catch(e){}t+="/"+e}return t})(n.substring(t,r)));var d=(e=>{var t,r,n={};for(t of(e="?"===e.charAt(0)?e.substring(1):e).split("&"))0!==t.length&&(2===(r=t.split("=")).length?n[decodeURIComponent(r[0])]=decodeURIComponent(r[1]):mc(`Invalid query segment '${t}' in query '${e}'`));return n})(n.substring(Math.min(n.length,r))),p=(0<=(e=i.indexOf(":"))?(h="https"===c||"wss"===c,u=parseInt(i.substring(e+1),10)):e=i.length,i.slice(0,e));"localhost"===p.toLowerCase()?s="localhost":p.split(".").length<=2?s=p:(p=i.indexOf("."),a=i.substring(0,p).toLowerCase(),s=i.substring(p+1),l=a),"ns"in d&&(l=d.ns)}return{host:i,port:u,domain:s,subdomain:a,secure:h,scheme:c,pathString:o,namespace:l}},sg="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",ag=(()=>{let s=0,a=[];return function(e){var t=e===s;s=e;let r;var n=new Array(8);for(r=7;0<=r;r--)n[r]=sg.charAt(e%64),e=Math.floor(e/64);g(0===e,"Cannot push at time == 0");let i=n.join("");if(t){for(r=11;0<=r&&63===a[r];r--)a[r]=0;a[r]++}else for(r=0;r<12;r++)a[r]=Math.floor(64*Math.random());for(r=0;r<12;r++)i+=sg.charAt(a[r]);return g(20===i.length,"nextPushId: Length should be 20."),i}})();class og{constructor(e,t,r,n){this.eventType=e,this.eventRegistration=t,this.snapshot=r,this.prevName=n}getPath(){var e=this.snapshot.ref;return("value"===this.eventType?e:e.parent)._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+_e(this.snapshot.exportVal())}}class lg{constructor(e,t,r){this.eventRegistration=e,this.error=t,this.path=r}getPath(){return this.path}getEventType(){return"cancel"}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.path.toString()+":cancel"}}class hg{constructor(e,t){this.snapshotCallback=e,this.cancelCallback=t}onValue(e,t){this.snapshotCallback.call(null,e,t)}onCancel(e){return g(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 cg{constructor(e,t){this._repo=e,this._path=t}cancel(){var e=new Z;return zf(this._repo,this._path,e.wrapCallback(()=>{})),e.promise}remove(){mf("OnDisconnect.remove",this._path);var e=new Z;return Kf(this._repo,this._path,null,e.wrapCallback(()=>{})),e.promise}set(e){mf("OnDisconnect.set",this._path),uf("OnDisconnect.set",e,this._path,!1);var t=new Z;return Kf(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}setWithPriority(e,t){mf("OnDisconnect.setWithPriority",this._path),uf("OnDisconnect.setWithPriority",e,this._path,!1),pf("OnDisconnect.setWithPriority",t,!1);var n=new Z;{var i=this._repo,s=this._path,a=n.wrapCallback(()=>{});let r=ju(e,t);i.server_.onDisconnectPut(s.toString(),r.val(!0),(e,t)=>{"ok"===e&&ld(i.onDisconnect_,s,r),$f(0,a,e,t)})}return n.promise}update(e){mf("OnDisconnect.update",this._path),df("OnDisconnect.update",e,this._path,!1);var n,i,r,s,t=new Z;return n=this._repo,i=this._path,r=e,s=t.wrapCallback(()=>{}),Ie(r)?(fc("onDisconnect().update() called with empty data. Don't do anything."),$f(0,s,"ok",void 0)):n.server_.onDisconnectMerge(i.toString(),r,(e,t)=>{"ok"===e&&Ic(r,(e,t)=>{var r=ju(t);ld(n.onDisconnect_,iu(i,e),r)}),$f(0,s,e,t)}),t.promise}}class ug{constructor(e,t,r,n){this._repo=e,this._path=t,this._queryParams=r,this._orderByCalled=n}get key(){return b(this._path)?null:tu(this._path)}get ref(){return new gg(this._repo,this._path)}get _queryIdentifier(){var e=id(this._queryParams),e=ic(e);return"{}"===e?"default":e}get _queryObject(){return id(this._queryParams)}isEqual(e){var t,r,n;return(e=w(e))instanceof ug&&(t=this._repo===e._repo,r=ou(this._path,e._path),n=this._queryIdentifier===e._queryIdentifier,t)&&r&&n}toJSON(){return this.toString()}toString(){return this._repo.toString()+(e=>{let t="";for(let r=e.pieceNum_;r<e.pieces_.length;r++)""!==e.pieces_[r]&&(t+="/"+encodeURIComponent(String(e.pieces_[r])));return t||"/"})(this._path)}}function dg(e,t){if(!0===e._orderByCalled)throw new Error(t+": You can't combine multiple orderBy calls.")}function pg(e){let t=null,r=null;if(e.hasStart()&&(t=e.getIndexStartValue()),e.hasEnd()&&(r=e.getIndexEndValue()),e.getIndex()===vu){var n="Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().",i="Query: When ordering by key, the argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() must be a string.";if(e.hasStart()){if(e.getIndexStartName()!==yc)throw new Error(n);if("string"!=typeof t)throw new Error(i)}if(e.hasEnd()){if(e.getIndexEndName()!==wc)throw new Error(n);if("string"!=typeof r)throw new Error(i)}}else if(e.getIndex()===I){if(null!=t&&!Tf(t)||null!=r&&!Tf(r))throw new Error("Query: When ordering by priority, the first argument passed to startAt(), startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value (null, a number, or a string).")}else if(g(e.getIndex()instanceof zu||e.getIndex()===Wu,"unknown index type."),null!=t&&"object"==typeof t||null!=r&&"object"==typeof r)throw new Error("Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() cannot be an object.")}function fg(e){if(e.hasStart()&&e.hasEnd()&&e.hasLimit()&&!e.hasAnchoredLimit())throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use limitToFirst() or limitToLast() instead.")}class gg extends ug{constructor(e,t){super(e,t,new Zu,!1)}get parent(){var e=nu(this._path);return null===e?null:new gg(this._repo,e)}get root(){let e=this;for(;null!==e.parent;)e=e.parent;return e}}class mg{constructor(e,t,r){this._node=e,this.ref=t,this._index=r}get priority(){return this._node.getPriority().val()}get key(){return this.ref.key}get size(){return this._node.numChildren()}child(e){var t=new f(e),r=yg(this.ref,e);return new mg(this._node.getChild(t),r,I)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(r){return!this._node.isLeafNode()&&!!this._node.forEachChild(this._index,(e,t)=>r(new mg(t,yg(this.ref,e),I)))}hasChild(e){var t=new f(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 vg(e,t){return(e=w(e))._checkNotDeleted("ref"),void 0!==t?yg(e._root,t):e._root}function _g(e,t){(e=w(e))._checkNotDeleted("refFromURL");var r=ng(t,e._repo.repoInfo_.nodeAdmin),n=(Sf("refFromURL",r),r.repoInfo);return e._repo.repoInfo_.isCustomHost()||n.host===e._repo.repoInfo_.host||gc("refFromURL: Host name does not match the current database: (found "+n.host+" but expected "+e._repo.repoInfo_.host+")"),vg(e,r.path.toString())}function yg(e,t){return(null===_((e=w(e))._path)?gf:Cf)("child","path",t,!1),new gg(e._repo,iu(e._path,t))}function wg(e,t){e=w(e),mf("set",e._path),uf("set",t,e._path,!1);var r=new Z;return jf(e._repo,e._path,t,null,r.wrapCallback(()=>{})),r.promise}function bg(e,t){df("update",t,e._path,!1);var i=new Z;{var a=e._repo,o=e._path,l=(e=t,i.wrapCallback(()=>{}));Gf(a,"update",{path:o.toString(),value:e});let r=!0,n=Ff(a),s={};if(Ic(e,(e,t)=>{r=!1,s[e]=Zp(iu(o,e),ju(t),a.serverSyncTree_,n)}),r)fc("update() called with empty data. Don't do anything."),$f(0,l,"ok",void 0);else{let i=Bf(a);var h=Rp(a.serverSyncTree_,o,s,i);Af(a.eventQueue_,h),a.server_.merge(o.toString(),e,(e,t)=>{var r="ok"===e,r=(r||mc("update at "+o+" failed: "+e),Pp(a.serverSyncTree_,i,!r)),n=0<r.length?Jf(a,o):o;Rf(a.eventQueue_,n,r),$f(0,l,e,t)}),Ic(e,e=>{var t=tg(a,iu(o,e));Jf(a,t)}),Rf(a.eventQueue_,o,[])}}return i.promise}function Ig(t){t=w(t);var i,s,a,e=new hg(()=>{}),e=new Tg(e);return i=t._repo,s=t,a=e,(null!=(e=Fp(i.serverSyncTree_,s))?Promise.resolve(e):i.server_.get(s).then(e=>{var t,r=ju(e).withIndex(s._queryParams.getIndex());Mp(i.serverSyncTree_,s,a,!0);let n;return n=s._queryParams.loadsAllData()?Dp(i.serverSyncTree_,s._path,r):(t=Bp(i.serverSyncTree_,s),Op(i.serverSyncTree_,s._path,r,t)),Rf(i.eventQueue_,s._path,n),xp(i.serverSyncTree_,s,a,null,!0),r},e=>(Gf(i,"get for query "+_e(s)+" failed: "+e),Promise.reject(new Error(e))))).then(e=>new mg(e,new gg(t._repo,t._path),t._queryParams.getIndex()))}class Tg{constructor(e){this.callbackContext=e}respondsTo(e){return"value"===e}createEvent(e,t){var r=t._queryParams.getIndex();return new og("value",this,new mg(e.snapshotNode,new gg(t._repo,t._path),r))}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 lg(this,e,t):null}matches(e){return e instanceof Tg&&(!e.callbackContext||!this.callbackContext||e.callbackContext.matches(this.callbackContext))}hasAnyCallback(){return null!==this.callbackContext}}class Eg{constructor(e,t){this.eventType=e,this.callbackContext=t}respondsTo(e){var t="children_added"===e?"child_added":e;return this.eventType===("children_removed"===t?"child_removed":t)}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new lg(this,e,t):null}createEvent(e,t){g(null!=e.childName,"Child events should have a childName.");var r=yg(new gg(t._repo,t._path),e.childName),n=t._queryParams.getIndex();return new og(e.type,this,new mg(e.snapshotNode,r,n),e.prevName)}getEventRunner(e){return"cancel"===e.getEventType()?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,e.prevName)}matches(e){return e instanceof Eg&&this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext))}hasAnyCallback(){return!!this.callbackContext}}function Cg(n,e,t,r,i){let s;if("object"==typeof r&&(s=void 0,i=r),"function"==typeof r&&(s=r),i&&i.onlyOnce){let r=t;var a=(e,t)=>{Wf(n._repo,n,o),r(e,t)};a.userCallback=t.userCallback,a.context=t.context,t=a}a=new hg(t,s||void 0);let o="value"===e?new Tg(a):new Eg(e,a);{r=n._repo,i=n,t=o;let e;e=".info"===_(i._path)?Mp(r.infoSyncTree_,i,t):Mp(r.serverSyncTree_,i,t),Nf(r.eventQueue_,i._path,e)}return()=>Wf(n._repo,n,o)}function Sg(e,t,r,n){return Cg(e,"value",t,r,n)}function kg(e,t,r,n){Cg(e,"child_added",t,r,n)}function Ag(e,t,r,n){Cg(e,"child_changed",t,r,n)}function Ng(e,t,r,n){Cg(e,"child_moved",t,r,n)}function Rg(e,t,r,n){Cg(e,"child_removed",t,r,n)}function Pg(e,t,r){let n=null;var i=r?new hg(r):null;"value"===t?n=new Tg(i):t&&(n=new Eg(t,i)),Wf(e._repo,e,n)}class Dg{}class xg extends Dg{constructor(e,t){super(),this._value=e,this._key=t,this.type="endAt"}_apply(e){uf("endAt",this._value,e._path,!0);var t=td(e._queryParams,this._value,this._key);if(fg(t),pg(t),e._queryParams.hasEnd())throw new Error("endAt: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new ug(e._repo,e._path,t,e._orderByCalled)}}class Og extends Dg{constructor(e,t){super(),this._value=e,this._key=t,this.type="endBefore"}_apply(e){uf("endBefore",this._value,e._path,!1);var t=((e,t,r)=>{let n;return(n=e.index_===vu||r?td(e,t,r):td(e,t,yc)).endBeforeSet_=!0,n})(e._queryParams,this._value,this._key);if(fg(t),pg(t),e._queryParams.hasEnd())throw new Error("endBefore: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new ug(e._repo,e._path,t,e._orderByCalled)}}class Mg extends Dg{constructor(e,t){super(),this._value=e,this._key=t,this.type="startAt"}_apply(e){uf("startAt",this._value,e._path,!0);var t=ed(e._queryParams,this._value,this._key);if(fg(t),pg(t),e._queryParams.hasStart())throw new Error("startAt: Starting point was already set (by another call to startAt, startBefore or equalTo).");return new ug(e._repo,e._path,t,e._orderByCalled)}}class Lg extends Dg{constructor(e,t){super(),this._value=e,this._key=t,this.type="startAfter"}_apply(e){uf("startAfter",this._value,e._path,!1);var t=((e,t,r)=>{let n;return(n=e.index_===vu||r?ed(e,t,r):ed(e,t,wc)).startAfterSet_=!0,n})(e._queryParams,this._value,this._key);if(fg(t),pg(t),e._queryParams.hasStart())throw new Error("startAfter: Starting point was already set (by another call to startAt, startAfter, or equalTo).");return new ug(e._repo,e._path,t,e._orderByCalled)}}class Fg extends Dg{constructor(e){super(),this._limit=e,this.type="limitToFirst"}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToFirst: Limit was already set (by another call to limitToFirst or limitToLast).");return new ug(e._repo,e._path,(t=e._queryParams,r=this._limit,(n=t.copy()).limitSet_=!0,n.limit_=r,n.viewFrom_="l",n),e._orderByCalled);var t,r,n}}class Ug extends Dg{constructor(e){super(),this._limit=e,this.type="limitToLast"}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToLast: Limit was already set (by another call to limitToFirst or limitToLast).");return new ug(e._repo,e._path,(t=e._queryParams,r=this._limit,(n=t.copy()).limitSet_=!0,n.limit_=r,n.viewFrom_="r",n),e._orderByCalled);var t,r,n}}class Vg extends Dg{constructor(e){super(),this._path=e,this.type="orderByChild"}_apply(e){dg(e,"orderByChild");var t=new f(this._path);if(b(t))throw new Error("orderByChild: cannot pass in empty path. Use orderByValue() instead.");t=new zu(t),t=rd(e._queryParams,t);return pg(t),new ug(e._repo,e._path,t,!0)}}class qg extends Dg{constructor(){super(...arguments),this.type="orderByKey"}_apply(e){dg(e,"orderByKey");var t=rd(e._queryParams,vu);return pg(t),new ug(e._repo,e._path,t,!0)}}class Bg extends Dg{constructor(){super(...arguments),this.type="orderByPriority"}_apply(e){dg(e,"orderByPriority");var t=rd(e._queryParams,I);return pg(t),new ug(e._repo,e._path,t,!0)}}class jg extends Dg{constructor(){super(...arguments),this.type="orderByValue"}_apply(e){dg(e,"orderByValue");var t=rd(e._queryParams,Wu);return pg(t),new ug(e._repo,e._path,t,!0)}}class zg extends Dg{constructor(e,t){super(),this._value=e,this._key=t,this.type="equalTo"}_apply(e){if(uf("equalTo",this._value,e._path,!1),e._queryParams.hasStart())throw new Error("equalTo: Starting point was already set (by another call to startAt/startAfter or equalTo).");if(e._queryParams.hasEnd())throw new Error("equalTo: Ending point was already set (by another call to endAt/endBefore or equalTo).");return new xg(this._value,this._key)._apply(new Mg(this._value,this._key)._apply(e))}}function Kg(e,...t){let r=w(e);for(var n of t)r=n._apply(r);return r}t=gg,g(!fp,"__referenceConstructor has already been defined"),fp=t,t=gg,g(!Sp,"__referenceConstructor has already been defined"),Sp=t;let Wg="FIREBASE_DATABASE_EMULATOR_HOST",Hg={},Gg=!1;function $g(e,t,r,n,i){let s=n||e.options.databaseURL,a=(void 0===s&&(e.options.projectId||gc("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),fc("Using default host for project ",e.options.projectId),s=e.options.projectId+"-default-rtdb.firebaseio.com"),ng(s,i)),o=a.repoInfo,l,h=void 0;(h="undefined"!=typeof process&&process.env?process.env[Wg]:h)?(l=!0,s=`http://${h}?ns=`+o.namespace,a=ng(s,i),o=a.repoInfo):l=!a.repoInfo.secure;var c=i&&l?new Dc(Dc.OWNER):new Pc(e.name,e.options,t),c=(Sf("Invalid Firebase Database URL",a),b(a.path)||gc("Database URL must point to the root of a Firebase Database (not including a child path)."),((e,t,r,n)=>{let i=Hg[t.name];var s;return i||(i={},Hg[t.name]=i),(s=i[e.toURLString()])&&gc("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call."),s=new Of(e,Gg,r,n),i[e.toURLString()]=s})(o,e,c,new Rc(e,r)));return new Qg(c,e)}class Qg{constructor(e,t){this._repoInternal=e,this.app=t,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(Mf(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new gg(this._repo,v())),this._rootInternal}_delete(){var e,t,r;return null!==this._rootInternal&&(e=this._repo,t=this.app.name,(r=Hg[t])&&r[e.key]===e||gc(`Database ${t}(${e.repoInfo_}) has already been deleted.`),Hf(e),delete r[e.key],this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){null===this._rootInternal&&gc("Cannot call "+e+" on a deleted database.")}}function Yg(){Gc.IS_TRANSPORT_INITIALIZED&&mc("Transport has already been initialized. Please call this function before calling ref or setting up a listener")}function Jg(){Yg(),zc.forceDisallow()}function Xg(){Yg(),Hc.forceDisallow(),zc.forceAllow()}function Zg(e,t,r,n={}){(e=w(e))._checkNotDeleted("useEmulator");var i,s=t+":"+r,a=e._repoInternal;if(e._instanceStarted){if(s===e._repoInternal.repoInfo_.host&&Ee(n,a.repoInfo_.emulatorOptions))return;gc("connectDatabaseEmulator() cannot initialize or alter the emulator configuration after the database instance has started.")}let o=void 0;a.repoInfo_.nodeAdmin?(n.mockUserToken&&gc('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),o=new Dc(Dc.OWNER)):n.mockUserToken&&(i="string"==typeof n.mockUserToken?n.mockUserToken:ee(n.mockUserToken,e.app.options.projectId),o=new Dc(i)),je(t)&&ze(t),r=a,e=s,t=n,n=o,i=e.lastIndexOf(":"),i=je(e.substring(0,i)),r.repoInfo_=new Lc(e,i,r.repoInfo_.namespace,r.repoInfo_.webSocketOnly,r.repoInfo_.nodeAdmin,r.repoInfo_.persistenceKey,r.repoInfo_.includeNamespaceInQueryParams,!0,t),n&&(r.authTokenProvider_=n)}function em(e){(e=w(e))._checkNotDeleted("goOnline"),(e=e._repo).persistentConnection_&&e.persistentConnection_.resume(Df)}function tm(e,t){pc(e,t)}let rm={".sv":"timestamp"};class nm{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}}function im(i,e,t){if(i=w(i),mf("Reference.transaction",i._path),".length"===i.key||".keys"===i.key)throw"Reference.transaction failed: "+i.key+" is a read-only object.";var r=t?.applyLocally??!0;let s=new Z;var n=Sg(i,()=>{}),t=i._repo,a=i._path,o=(e,t,r)=>{var n;e?s.reject(e):(n=new mg(r,new gg(i._repo,i._path),I),s.resolve(new nm(t,n)))},l=n,h=r;Gf(t,"transaction on "+a);var c,n={path:a,update:e,onComplete:o,status:null,order:hc(),applyLocally:h,retryCount:0,unwatcher:l,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},r=Qf(t,a,void 0);if(n.currentInputSnapshot=r,void 0===(c=n.update(r.val())))n.unwatcher(),n.currentOutputSnapshotRaw=null,n.currentOutputSnapshotResolved=null,n.onComplete&&n.onComplete(null,!1,n.currentInputSnapshot);else{Ef("transaction failed: Data returned ",c,n.path),n.status=0;var u=nf(t.transactionQueueTree_,a),d=sf(u)||[];d.push(n),af(u,d);let e;"object"==typeof c&&null!==c&&we(c,".priority")?(e=be(c,".priority"),g(Tf(e),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.")):(u=Lp(t.serverSyncTree_,a)||T.EMPTY_NODE,e=u.getPriority().val());d=Ff(t),u=ju(c,e),c=ef(u,r,d),r=(n.currentOutputSnapshotRaw=u,n.currentOutputSnapshotResolved=c,n.currentWriteId=Bf(t),Np(t.serverSyncTree_,a,c,n.currentWriteId,n.applyLocally));Rf(t.eventQueue_,a,r),Yf(t,t.transactionQueueTree_)}return s.promise}pu.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)},pu.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)},$h(Ft),Nt(new c("database",(e,{instanceIdentifier:t})=>$g(e.getProvider("app").getImmediate(),e.getProvider("auth-internal"),e.getProvider("app-check-internal"),t),"PUBLIC").setMultipleInstances(!0)),u(Hh,"1.1.2",hD),u(Hh,"1.1.2","esm2020");function sm(e){var t="FIREBASE WARNING: "+e;am.warn(t)}let am=new Xe("@firebase/database-compat");class om{constructor(e){this._delegate=e}cancel(t){l("OnDisconnect.cancel",0,1,arguments.length),Oe("OnDisconnect.cancel","onComplete",t,!0);var e=this._delegate.cancel();return t&&e.then(()=>t(null),e=>t(e)),e}remove(t){l("OnDisconnect.remove",0,1,arguments.length),Oe("OnDisconnect.remove","onComplete",t,!0);var e=this._delegate.remove();return t&&e.then(()=>t(null),e=>t(e)),e}set(e,t){l("OnDisconnect.set",1,2,arguments.length),Oe("OnDisconnect.set","onComplete",t,!0);var r=this._delegate.set(e);return t&&r.then(()=>t(null),e=>t(e)),r}setWithPriority(e,t,r){l("OnDisconnect.setWithPriority",2,3,arguments.length),Oe("OnDisconnect.setWithPriority","onComplete",r,!0);var n=this._delegate.setWithPriority(e,t);return r&&n.then(()=>r(null),e=>r(e)),n}update(t,r){if(l("OnDisconnect.update",1,2,arguments.length),Array.isArray(t)){var n={};for(let e=0;e<t.length;++e)n[""+e]=t[e];t=n,sm("Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.")}Oe("OnDisconnect.update","onComplete",r,!0);var e=this._delegate.update(t);return r&&e.then(()=>r(null),e=>r(e)),e}}class lm{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return l("TransactionResult.toJSON",0,1,arguments.length),{committed:this.committed,snapshot:this.snapshot.toJSON()}}}class hm{constructor(e,t){this._database=e,this._delegate=t}val(){return l("DataSnapshot.val",0,0,arguments.length),this._delegate.val()}exportVal(){return l("DataSnapshot.exportVal",0,0,arguments.length),this._delegate.exportVal()}toJSON(){return l("DataSnapshot.toJSON",0,1,arguments.length),this._delegate.toJSON()}exists(){return l("DataSnapshot.exists",0,0,arguments.length),this._delegate.exists()}child(e){return l("DataSnapshot.child",0,1,arguments.length),e=String(e),Cf("DataSnapshot.child","path",e,!1),new hm(this._database,this._delegate.child(e))}hasChild(e){return l("DataSnapshot.hasChild",1,1,arguments.length),Cf("DataSnapshot.hasChild","path",e,!1),this._delegate.hasChild(e)}getPriority(){return l("DataSnapshot.getPriority",0,0,arguments.length),this._delegate.priority}forEach(t){return l("DataSnapshot.forEach",1,1,arguments.length),Oe("DataSnapshot.forEach","action",t,!1),this._delegate.forEach(e=>t(new hm(this._database,e)))}hasChildren(){return l("DataSnapshot.hasChildren",0,0,arguments.length),this._delegate.hasChildren()}get key(){return this._delegate.key}numChildren(){return l("DataSnapshot.numChildren",0,0,arguments.length),this._delegate.size}getRef(){return l("DataSnapshot.ref",0,0,arguments.length),new um(this._database,this._delegate.ref)}get ref(){return this.getRef()}}class cm{constructor(e,t){this.database=e,this._delegate=t}on(e,r,t,n){l("Query.on",2,4,arguments.length),Oe("Query.on","callback",r,!1);let i=cm.getCancelAndContextArgs_("Query.on",t,n);var s=(e,t)=>{r.call(i.context,new hm(this.database,e),t)},a=(s.userCallback=r,s.context=i.context,i.cancel?.bind(i.context));switch(e){case"value":return Sg(this._delegate,s,a),r;case"child_added":return kg(this._delegate,s,a),r;case"child_removed":return Rg(this._delegate,s,a),r;case"child_changed":return Ag(this._delegate,s,a),r;case"child_moved":return Ng(this._delegate,s,a),r;default:throw new Error(xe("Query.on","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}}off(e,t,r){l("Query.off",0,3,arguments.length);var n,i="Query.off",s=e,a=!0;if(!a||void 0!==s)switch(s){case"value":case"child_added":case"child_removed":case"child_changed":case"child_moved":break;default:throw new Error(xe(i,"eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}Oe("Query.off","callback",t,!0),Me("Query.off","context",r,!0),t?((n=()=>{}).userCallback=t,n.context=r,Pg(this._delegate,e,n)):Pg(this._delegate,e)}get(){return Ig(this._delegate).then(e=>new hm(this.database,e))}once(e,n,t,r){l("Query.once",1,4,arguments.length),Oe("Query.once","callback",n,!0);let i=cm.getCancelAndContextArgs_("Query.once",t,r),s=new Z;var a=(e,t)=>{var r=new hm(this.database,e);n&&n.call(i.context,r,t),s.resolve(r)},o=(a.userCallback=n,a.context=i.context,e=>{i.cancel&&i.cancel.call(i.context,e),s.reject(e)});switch(e){case"value":Sg(this._delegate,a,o,{onlyOnce:!0});break;case"child_added":kg(this._delegate,a,o,{onlyOnce:!0});break;case"child_removed":Rg(this._delegate,a,o,{onlyOnce:!0});break;case"child_changed":Ag(this._delegate,a,o,{onlyOnce:!0});break;case"child_moved":Ng(this._delegate,a,o,{onlyOnce:!0});break;default:throw new Error(xe("Query.once","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}return s.promise}limitToFirst(e){return l("Query.limitToFirst",1,1,arguments.length),new cm(this.database,Kg(this._delegate,(e=>{if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToFirst: First argument must be a positive integer.");return new Fg(e)})(e)))}limitToLast(e){return l("Query.limitToLast",1,1,arguments.length),new cm(this.database,Kg(this._delegate,(e=>{if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToLast: First argument must be a positive integer.");return new Ug(e)})(e)))}orderByChild(e){return l("Query.orderByChild",1,1,arguments.length),new cm(this.database,Kg(this._delegate,(e=>{if("$key"===e)throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');if("$priority"===e)throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');if("$value"===e)throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');return Cf("orderByChild","path",e,!1),new Vg(e)})(e)))}orderByKey(){return l("Query.orderByKey",0,0,arguments.length),new cm(this.database,Kg(this._delegate,new qg))}orderByPriority(){return l("Query.orderByPriority",0,0,arguments.length),new cm(this.database,Kg(this._delegate,new Bg))}orderByValue(){return l("Query.orderByValue",0,0,arguments.length),new cm(this.database,Kg(this._delegate,new jg))}startAt(e=null,t){return l("Query.startAt",0,2,arguments.length),new cm(this.database,Kg(this._delegate,([e=null,t]=[e,t],ff("startAt","key",t,!0),new Mg(e,t))))}startAfter(e=null,t){return l("Query.startAfter",0,2,arguments.length),new cm(this.database,Kg(this._delegate,(e=e,t=t,ff("startAfter","key",t,!0),new Lg(e,t))))}endAt(e=null,t){return l("Query.endAt",0,2,arguments.length),new cm(this.database,Kg(this._delegate,(e=e,t=t,ff("endAt","key",t,!0),new xg(e,t))))}endBefore(e=null,t){return l("Query.endBefore",0,2,arguments.length),new cm(this.database,Kg(this._delegate,(e=e,t=t,ff("endBefore","key",t,!0),new Og(e,t))))}equalTo(e,t){return l("Query.equalTo",1,2,arguments.length),new cm(this.database,Kg(this._delegate,(e=e,t=t,ff("equalTo","key",t,!0),new zg(e,t))))}toString(){return l("Query.toString",0,0,arguments.length),this._delegate.toString()}toJSON(){return l("Query.toJSON",0,1,arguments.length),this._delegate.toJSON()}isEqual(e){if(l("Query.isEqual",1,1,arguments.length),e instanceof cm)return this._delegate.isEqual(e._delegate);throw new Error("Query.isEqual failed: First argument must be an instance of firebase.database.Query.")}static getCancelAndContextArgs_(e,t,r){var n={cancel:void 0,context:void 0};if(t&&r)n.cancel=t,Oe(e,"cancel",n.cancel,!0),n.context=r,Me(e,"context",n.context,!0);else if(t)if("object"==typeof t&&null!==t)n.context=t;else{if("function"!=typeof t)throw new Error(xe(e,"cancelOrContext")+" must either be a cancel callback or a context object.");n.cancel=t}return n}get ref(){return new um(this.database,new gg(this._delegate._repo,this._delegate._path))}}class um extends cm{constructor(e,t){super(e,new ug(t._repo,t._path,new Zu,!1)),this.database=e,this._delegate=t}getKey(){return l("Reference.key",0,0,arguments.length),this._delegate.key}child(e){return l("Reference.child",1,1,arguments.length),"number"==typeof e&&(e=String(e)),new um(this.database,yg(this._delegate,e))}getParent(){l("Reference.parent",0,0,arguments.length);var e=this._delegate.parent;return e?new um(this.database,e):null}getRoot(){return l("Reference.root",0,0,arguments.length),new um(this.database,this._delegate.root)}set(e,t){l("Reference.set",1,2,arguments.length),Oe("Reference.set","onComplete",t,!0);var r=wg(this._delegate,e);return t&&r.then(()=>t(null),e=>t(e)),r}update(t,r){if(l("Reference.update",1,2,arguments.length),Array.isArray(t)){var n={};for(let e=0;e<t.length;++e)n[""+e]=t[e];t=n,sm("Passing an Array to Firebase.update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.")}mf("Reference.update",this._delegate._path),Oe("Reference.update","onComplete",r,!0);var e=bg(this._delegate,t);return r&&e.then(()=>r(null),e=>r(e)),e}setWithPriority(e,t,r){l("Reference.setWithPriority",2,3,arguments.length),Oe("Reference.setWithPriority","onComplete",r,!0);var n=((e,t,r)=>{if(mf("setWithPriority",e._path),uf("setWithPriority",t,e._path,!1),pf("setWithPriority",r,!1),".length"===e.key||".keys"===e.key)throw"setWithPriority failed: "+e.key+" is a read-only object.";var n=new Z;return jf(e._repo,e._path,t,r,n.wrapCallback(()=>{})),n.promise})(this._delegate,e,t);return r&&n.then(()=>r(null),e=>r(e)),n}remove(t){l("Reference.remove",0,1,arguments.length),Oe("Reference.remove","onComplete",t,!0);e=this._delegate,mf("remove",e._path);var e,r=wg(e,null);return t&&r.then(()=>t(null),e=>t(e)),r}transaction(e,t,r){l("Reference.transaction",1,3,arguments.length),Oe("Reference.transaction","transactionUpdate",e,!1),Oe("Reference.transaction","onComplete",t,!0);var n,i="Reference.transaction",s="applyLocally",a=r,o=!0;if(o&&void 0===a||"boolean"==typeof a)return n=im(this._delegate,e,{applyLocally:r}).then(e=>new lm(e.committed,new hm(this.database,e.snapshot))),t&&n.then(e=>t(null,e.committed,e.snapshot),e=>t(e,!1,null)),n;throw new Error(xe(i,s)+"must be a boolean.")}setPriority(e,t){l("Reference.setPriority",1,2,arguments.length),Oe("Reference.setPriority","onComplete",t,!0);r=this._delegate,e=e,r=w(r),mf("setPriority",r._path),pf("setPriority",e,!1),n=new Z,jf(r._repo,iu(r._path,".priority"),e,null,n.wrapCallback(()=>{}));var r,n=n.promise;return t&&n.then(()=>t(null),e=>t(e)),n}push(e,t){l("Reference.push",0,2,arguments.length),Oe("Reference.push","onComplete",t,!0);var r=((e,t)=>{e=w(e),mf("push",e._path),uf("push",t,e._path,!0);var r=Lf(e._repo),r=ag(r),n=yg(e,r);let i=yg(e,r),s;return s=null!=t?wg(i,t).then(()=>i):Promise.resolve(i),n.then=s.then.bind(s),n.catch=s.then.bind(s,void 0),n})(this._delegate,e),n=r.then(e=>new um(this.database,e)),r=(t&&n.then(()=>t(null),e=>t(e)),new um(this.database,r));return r.then=n.then.bind(n),r.catch=n.catch.bind(n,void 0),r}onDisconnect(){return mf("Reference.onDisconnect",this._delegate._path),new om(new cg(this._delegate._repo,this._delegate._path))}get key(){return this.getKey()}get parent(){return this.getParent()}get root(){return this.getRoot()}}class dm{constructor(e,t){this._delegate=e,this.app=t,this.INTERNAL={delete:()=>this._delegate._delete(),forceWebSockets:Jg,forceLongPolling:Xg}}useEmulator(e,t,r={}){Zg(this._delegate,e,t,r)}ref(e){var t;return l("database.ref",0,1,arguments.length),e instanceof um?(t=_g(this._delegate,e.toString()),new um(this,t)):(t=vg(this._delegate,e),new um(this,t))}refFromURL(e){l("database.refFromURL",1,1,arguments.length);var t=_g(this._delegate,e);return new um(this,t)}goOffline(){var e;l("database.goOffline",0,0,arguments.length),(e=w(e=this._delegate))._checkNotDeleted("goOffline"),Hf(e._repo)}goOnline(){return l("database.goOnline",0,0,arguments.length),em(this._delegate)}}dm.ServerValue={TIMESTAMP:rm,increment:e=>({".sv":{increment:e}})};ar=Object.freeze({__proto__:null,initStandalone:function({app:e,url:t,version:r,customAuthImpl:n,customAppCheckImpl:i,namespace:s,nodeAdmin:a=!1}){$h(r);var o=new He("database-standalone"),l=new We("auth-internal",o);l.setComponent(new c("auth-internal",()=>n,"PRIVATE"));let h=void 0;return i&&(h=new We("app-check-internal",o)).setComponent(new c("app-check-internal",()=>i,"PRIVATE")),{instance:new dm($g(e,l,h,t,a),e),namespace:s}}});let pm=dm.ServerValue;(t=or).INTERNAL.registerComponent(new c("database-compat",(e,{instanceIdentifier:t})=>{var r=e.getProvider("app-compat").getImmediate(),n=e.getProvider("database").getImmediate({identifier:t});return new dm(n,r)},"PUBLIC").setServiceProps({Reference:um,Query:cm,Database:dm,DataSnapshot:hm,enableLogging:tm,INTERNAL:ar,ServerValue:pm}).setMultipleInstances(!0)),t.registerVersion("@firebase/database-compat","2.1.3");var fm,gm,mm,vm,_m,ym,wm,bm,Im,Tm,Em,e,Cm,lr="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},Sm=(!(function(){var e,t,s;function r(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.C=Array(this.blockSize),this.o=this.h=0,this.u()}function n(){}function a(e,t,r){r=r||0;var n=Array(16);if("string"==typeof t)for(var i=0;i<16;++i)n[i]=t.charCodeAt(r++)|t.charCodeAt(r++)<<8|t.charCodeAt(r++)<<16|t.charCodeAt(r++)<<24;else for(i=0;i<16;++i)n[i]=t[r++]|t[r++]<<8|t[r++]<<16|t[r++]<<24;t=e.g[0],r=e.g[1];var i=e.g[2],s=e.g[3],a=t+(s^r&(i^s))+n[0]+3614090360&4294967295;a=(r=(i=(s=(t=(r=(i=(s=(t=(r=(i=(s=(t=(r=(i=(s=(t=(r=(i=(s=(t=(r=(i=(s=(t=(r=(i=(s=(t=(r=(i=(s=(t=(r=(i=(s=(t=(r=(i=(s=(t=(r=(i=(s=(t=(r=(i=(s=(t=(r=(i=(s=(t=(r=(i=(s=(t=(r=(i=(s=(t=r+(a<<7&4294967295|a>>>25))+((a=s+(i^t&(r^i))+n[1]+3905402710&4294967295)<<12&4294967295|a>>>20))+((a=i+(r^s&(t^r))+n[2]+606105819&4294967295)<<17&4294967295|a>>>15))+((a=r+(t^i&(s^t))+n[3]+3250441966&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^r&(i^s))+n[4]+4118548399&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(r^i))+n[5]+1200080426&4294967295)<<12&4294967295|a>>>20))+((a=i+(r^s&(t^r))+n[6]+2821735955&4294967295)<<17&4294967295|a>>>15))+((a=r+(t^i&(s^t))+n[7]+4249261313&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^r&(i^s))+n[8]+1770035416&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(r^i))+n[9]+2336552879&4294967295)<<12&4294967295|a>>>20))+((a=i+(r^s&(t^r))+n[10]+4294925233&4294967295)<<17&4294967295|a>>>15))+((a=r+(t^i&(s^t))+n[11]+2304563134&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^r&(i^s))+n[12]+1804603682&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(r^i))+n[13]+4254626195&4294967295)<<12&4294967295|a>>>20))+((a=i+(r^s&(t^r))+n[14]+2792965006&4294967295)<<17&4294967295|a>>>15))+((a=r+(t^i&(s^t))+n[15]+1236535329&4294967295)<<22&4294967295|a>>>10))+((a=t+(i^s&(r^i))+n[1]+4129170786&4294967295)<<5&4294967295|a>>>27))+((a=s+(r^i&(t^r))+n[6]+3225465664&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^r&(s^t))+n[11]+643717713&4294967295)<<14&4294967295|a>>>18))+((a=r+(s^t&(i^s))+n[0]+3921069994&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(r^i))+n[5]+3593408605&4294967295)<<5&4294967295|a>>>27))+((a=s+(r^i&(t^r))+n[10]+38016083&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^r&(s^t))+n[15]+3634488961&4294967295)<<14&4294967295|a>>>18))+((a=r+(s^t&(i^s))+n[4]+3889429448&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(r^i))+n[9]+568446438&4294967295)<<5&4294967295|a>>>27))+((a=s+(r^i&(t^r))+n[14]+3275163606&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^r&(s^t))+n[3]+4107603335&4294967295)<<14&4294967295|a>>>18))+((a=r+(s^t&(i^s))+n[8]+1163531501&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(r^i))+n[13]+2850285829&4294967295)<<5&4294967295|a>>>27))+((a=s+(r^i&(t^r))+n[2]+4243563512&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^r&(s^t))+n[7]+1735328473&4294967295)<<14&4294967295|a>>>18))+((a=r+(s^t&(i^s))+n[12]+2368359562&4294967295)<<20&4294967295|a>>>12))+((a=t+(r^i^s)+n[5]+4294588738&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^r^i)+n[8]+2272392833&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^r)+n[11]+1839030562&4294967295)<<16&4294967295|a>>>16))+((a=r+(i^s^t)+n[14]+4259657740&4294967295)<<23&4294967295|a>>>9))+((a=t+(r^i^s)+n[1]+2763975236&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^r^i)+n[4]+1272893353&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^r)+n[7]+4139469664&4294967295)<<16&4294967295|a>>>16))+((a=r+(i^s^t)+n[10]+3200236656&4294967295)<<23&4294967295|a>>>9))+((a=t+(r^i^s)+n[13]+681279174&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^r^i)+n[0]+3936430074&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^r)+n[3]+3572445317&4294967295)<<16&4294967295|a>>>16))+((a=r+(i^s^t)+n[6]+76029189&4294967295)<<23&4294967295|a>>>9))+((a=t+(r^i^s)+n[9]+3654602809&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^r^i)+n[12]+3873151461&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^r)+n[15]+530742520&4294967295)<<16&4294967295|a>>>16))+((a=r+(i^s^t)+n[2]+3299628645&4294967295)<<23&4294967295|a>>>9))+((a=t+(i^(r|~s))+n[0]+4096336452&4294967295)<<6&4294967295|a>>>26))+((a=s+(r^(t|~i))+n[7]+1126891415&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~r))+n[14]+2878612391&4294967295)<<15&4294967295|a>>>17))+((a=r+(s^(i|~t))+n[5]+4237533241&4294967295)<<21&4294967295|a>>>11))+((a=t+(i^(r|~s))+n[12]+1700485571&4294967295)<<6&4294967295|a>>>26))+((a=s+(r^(t|~i))+n[3]+2399980690&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~r))+n[10]+4293915773&4294967295)<<15&4294967295|a>>>17))+((a=r+(s^(i|~t))+n[1]+2240044497&4294967295)<<21&4294967295|a>>>11))+((a=t+(i^(r|~s))+n[8]+1873313359&4294967295)<<6&4294967295|a>>>26))+((a=s+(r^(t|~i))+n[15]+4264355552&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~r))+n[6]+2734768916&4294967295)<<15&4294967295|a>>>17))+((a=r+(s^(i|~t))+n[13]+1309151649&4294967295)<<21&4294967295|a>>>11))+((s=(t=r+((a=t+(i^(r|~s))+n[4]+4149444226&4294967295)<<6&4294967295|a>>>26))+((a=s+(r^(t|~i))+n[11]+3174756917&4294967295)<<10&4294967295|a>>>22))^((i=s+((a=i+(t^(s|~r))+n[2]+718787259&4294967295)<<15&4294967295|a>>>17))|~t))+n[9]+3951481745&4294967295,e.g[0]=e.g[0]+t&4294967295,e.g[1]=e.g[1]+(i+(a<<21&4294967295|a>>>11))&4294967295,e.g[2]=e.g[2]+i&4294967295,e.g[3]=e.g[3]+s&4294967295}function l(e,t){this.h=t;var r=[];let n=!0;for(let s=e.length-1;0<=s;s--){var i=0|e[s];n&&i==t||(r[s]=i,n=!1)}this.g=r}t=r,s=function(){this.blockSize=-1},n.prototype=s.prototype,t.F=s.prototype,t.prototype=new n,(t.prototype.constructor=t).D=function(e,t,r){for(var n=Array(arguments.length-2),i=2;i<arguments.length;i++)n[i-2]=arguments[i];return s.prototype[t].apply(e,n)},r.prototype.u=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.o=this.h=0},r.prototype.v=function(e,t){var r=(t=void 0===t?e.length:t)-this.blockSize,n=this.C;let i=this.h,s=0;for(;s<t;){if(0==i)for(;s<=r;)a(this,e,s),s+=this.blockSize;if("string"==typeof e){for(;s<t;)if(n[i++]=e.charCodeAt(s++),i==this.blockSize){a(this,n),i=0;break}}else for(;s<t;)if(n[i++]=e[s++],i==this.blockSize){a(this,n),i=0;break}}this.h=i,this.o+=t},r.prototype.A=function(){var t=Array((this.h<56?this.blockSize:2*this.blockSize)-this.h);t[0]=128;for(var r=1;r<t.length-8;++r)t[r]=0;for(var r=8*this.o,n=t.length-8;n<t.length;++n)t[n]=255&r,r/=256;for(this.v(t),t=Array(16),n=r=0;n<4;++n)for(let e=0;e<32;e+=8)t[r++]=this.g[n]>>>e&255;return t};var i={};function o(e){return-128<=e&&e<128?(t=e,r=function(e){return new l([0|e],e<0?-1:0)},n=i,Object.prototype.hasOwnProperty.call(n,t)?n[t]:n[t]=r(t)):new l([0|e],e<0?-1:0);var t,r,n}function h(e){if(isNaN(e)||!isFinite(e))return c;if(e<0)return g(h(-e));var t=[];let r=1;for(let n=0;e>=r;n++)t[n]=e/r|0,r*=4294967296;return new l(t,0)}var c=o(0),u=o(1),d=o(16777216);function p(t){if(0==t.h){for(let e=0;e<t.g.length;e++)if(0!=t.g[e])return;return 1}}function f(e){return-1==e.h}function g(e){var t=e.g.length,r=[];for(let n=0;n<t;n++)r[n]=~e.g[n];return new l(r,~e.h).add(u)}function m(e,t){return e.add(g(t))}function v(e,t){for(;(65535&e[t])!=e[t];)e[t+1]+=e[t]>>>16,e[t]&=65535,t++}function _(e,t){this.g=e,this.h=t}function y(e,t){if(p(t))throw Error("division by zero");if(p(e))return new _(c,c);if(f(e))return t=y(g(e),t),new _(g(t.g),g(t.h));if(f(t))return t=y(e,g(t)),new _(g(t.g),t.h);if(30<e.g.length){if(f(e)||f(t))throw Error("slowDivide_ only works with positive integers.");for(var r=u,n=t;n.l(e)<=0;)r=w(r),n=w(n);for(var i=b(r,1),s=b(n,1),n=b(n,2),r=b(r,2);!p(n);){var a=s.add(n);a.l(e)<=0&&(i=i.add(r),s=a),n=b(n,1),r=b(r,1)}return t=m(e,i.j(t)),new _(i,t)}for(i=c;0<=e.l(t);){for(r=Math.max(1,Math.floor(e.m()/t.m())),n=(n=Math.ceil(Math.log(r)/Math.LN2))<=48?1:Math.pow(2,n-48),a=(s=h(r)).j(t);f(a)||0<a.l(e);)a=(s=h(r-=n)).j(t);p(s)&&(s=u),i=i.add(s),e=m(e,a)}return new _(i,e)}function w(e){var t=e.g.length+1,r=[];for(let n=0;n<t;n++)r[n]=e.i(n)<<1|e.i(n-1)>>>31;return new l(r,e.h)}function b(e,t){var r=t>>5,n=(t%=32,e.g.length-r),i=[];for(let s=0;s<n;s++)i[s]=0<t?e.i(s+r)>>>t|e.i(s+r+1)<<32-t:e.i(s+r);return new l(i,e.h)}(e=l.prototype).m=function(){if(f(this))return-g(this).m();let e=0,t=1;for(let n=0;n<this.g.length;n++){var r=this.i(n);e+=(0<=r?r:4294967296+r)*t,t*=4294967296}return e},e.toString=function(t){if((t=t||10)<2||36<t)throw Error("radix out of range: "+t);if(p(this))return"0";if(f(this))return"-"+g(this).toString(t);var r=h(Math.pow(t,6)),n=this;let i="";for(;;){var s=y(n,r).g;let e=((0<(n=m(n,s.j(r))).g.length?n.g[0]:n.h)>>>0).toString(t);if(p(n=s))return e+i;for(;e.length<6;)e="0"+e;i=e+i}},e.i=function(e){return e<0?0:e<this.g.length?this.g[e]:this.h},e.l=function(e){return f(e=m(this,e))?-1:p(e)?0:1},e.abs=function(){return f(this)?g(this):this},e.add=function(e){var t=Math.max(this.g.length,e.g.length),r=[];let n=0;for(let a=0;a<=t;a++){var i=n+(65535&this.i(a))+(65535&e.i(a)),s=(i>>>16)+(this.i(a)>>>16)+(e.i(a)>>>16);n=s>>>16,i&=65535,s&=65535,r[a]=s<<16|i}return new l(r,-2147483648&r[r.length-1]?-1:0)},e.j=function(t){if(p(this)||p(t))return c;if(f(this))return f(t)?g(this).j(g(t)):g(g(this).j(t));if(f(t))return g(this.j(g(t)));if(this.l(d)<0&&t.l(d)<0)return h(this.m()*t.m());for(var e=this.g.length+t.g.length,r=[],n=0;n<2*e;n++)r[n]=0;for(n=0;n<this.g.length;n++)for(let e=0;e<t.g.length;e++){var i=this.i(n)>>>16,s=65535&this.i(n),a=t.i(e)>>>16,o=65535&t.i(e);r[2*n+2*e]+=s*o,v(r,2*n+2*e),r[2*n+2*e+1]+=i*o,v(r,2*n+2*e+1),r[2*n+2*e+1]+=s*a,v(r,2*n+2*e+1),r[2*n+2*e+2]+=i*a,v(r,2*n+2*e+2)}for(t=0;t<e;t++)r[t]=r[2*t+1]<<16|r[2*t];for(t=e;t<2*e;t++)r[t]=0;return new l(r,0)},e.B=function(e){return y(this,e).h},e.and=function(e){var t=Math.max(this.g.length,e.g.length),r=[];for(let n=0;n<t;n++)r[n]=this.i(n)&e.i(n);return new l(r,this.h&e.h)},e.or=function(e){var t=Math.max(this.g.length,e.g.length),r=[];for(let n=0;n<t;n++)r[n]=this.i(n)|e.i(n);return new l(r,this.h|e.h)},e.xor=function(e){var t=Math.max(this.g.length,e.g.length),r=[];for(let n=0;n<t;n++)r[n]=this.i(n)^e.i(n);return new l(r,this.h^e.h)},r.prototype.digest=r.prototype.A,r.prototype.reset=r.prototype.u,r.prototype.update=r.prototype.v,gm=r,l.prototype.multiply=l.prototype.j,l.prototype.modulo=l.prototype.B,l.prototype.compare=l.prototype.l,l.prototype.toNumber=l.prototype.m,l.prototype.getBits=l.prototype.i,l.fromNumber=h,l.fromString=function e(t,r){if(0==t.length)throw Error("number format error: empty string");if((r=r||10)<2||36<r)throw Error("radix out of range: "+r);if("-"==t.charAt(0))return g(e(t.substring(1),r));if(0<=t.indexOf("-"))throw Error('number format error: interior "-" character');var n=h(Math.pow(r,8));let i=c;for(let o=0;o<t.length;o+=8){var s=Math.min(8,t.length-o),a=parseInt(t.substring(o,o+s),r);i=(s<8?(s=h(Math.pow(r,s)),i.j(s)):i=i.j(n)).add(h(a))}return i},fm=l}).apply(void 0!==lr?lr:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{}),"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{});!(function(){var e,L=Object.defineProperty;var F=(e=>{e=["object"==typeof globalThis&&globalThis,e,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof Sm&&Sm];for(var t=0;t<e.length;++t){var r=e[t];if(r&&r.Math==Math)return r}throw Error("Cannot find global object")})(this);function U(e,t){if(t)e:{var r=F;e=e.split(".");for(var n=0;n<e.length-1;n++){var i=e[n];if(!(i in r))break e;r=r[i]}(t=t(n=r[e=e[e.length-1]]))!=n&&null!=t&&L(r,e,{configurable:!0,writable:!0,value:t})}}U("Symbol.dispose",function(e){return e||Symbol("Symbol.dispose")}),U("Array.prototype.values",function(e){return e||function(){return this[Symbol.iterator]()}}),U("Object.entries",function(e){return e||function(e){var t,r=[];for(t in e)Object.prototype.hasOwnProperty.call(e,t)&&r.push([t,e[t]]);return r}});var V=V||{},N=this||self;function d(e){var t=typeof e;return"object"==t&&null!=e||"function"==t}function q(e,t,r){return e.call.apply(e.bind,arguments)}function v(e,t,r){return(v=q).apply(null,arguments)}function B(t){var r=Array.prototype.slice.call(arguments,1);return function(){var e=r.slice();return e.push.apply(e,arguments),t.apply(this,e)}}function t(e,s){function t(){}t.prototype=s.prototype,e.Z=s.prototype,e.prototype=new t,(e.prototype.constructor=e).Ob=function(e,t,r){for(var n=Array(arguments.length-2),i=2;i<arguments.length;i++)n[i-2]=arguments[i];return s.prototype[t].apply(e,n)}}var j="undefined"!=typeof AsyncContext&&"function"==typeof AsyncContext.Snapshot?e=>e&&AsyncContext.Snapshot.wrap(e):e=>e;function z(t){var r=t.length;if(0<r){var n=Array(r);for(let e=0;e<r;e++)n[e]=t[e];return n}return[]}function K(t){for(let e=1;e<arguments.length;e++){var r=arguments[e];if("array"==(n="object"!=(n=typeof r)?n:r?Array.isArray(r)?"array":n:"null")||"object"==n&&"number"==typeof r.length){var n=t.length||0,i=r.length||0;t.length=n+i;for(let e=0;e<i;e++)t[n+e]=r[e]}else t.push(r)}}var W=new class{constructor(e,t){this.i=e,this.j=t,this.h=0,this.g=null}get(){let e;return 0<this.h?(this.h--,e=this.g,this.g=e.next,e.next=null):e=this.i(),e}}(()=>new H,e=>e.reset());class H{constructor(){this.next=this.g=this.h=null}set(e,t){this.h=e,this.g=t,this.next=null}reset(){this.next=this.g=this.h=null}}let r,n=!1,G=new class{constructor(){this.h=this.g=null}add(e,t){var r=W.get();r.set(e,t),this.h?this.h.next=r:this.g=r,this.h=r}},$=()=>{let e=Promise.resolve(void 0);r=()=>{e.then(Q)}};function Q(){for(var e;e=(()=>{let e=G,t=null;return e.g&&(t=e.g,e.g=e.g.next,e.g||(e.h=null),t.next=null),t})();){try{e.h.call(e.g)}catch(e){(e=>{N.setTimeout(()=>{throw e},0)})(e)}var t=W;t.j(e),t.h<100&&(t.h++,e.next=t.g,t.g=e)}n=!1}function i(){this.u=this.u,this.C=this.C}function o(e,t){this.type=e,this.g=this.target=t,this.defaultPrevented=!1}i.prototype.u=!1,i.prototype.dispose=function(){this.u||(this.u=!0,this.N())},i.prototype[Symbol.dispose]=function(){this.dispose()},i.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()},o.prototype.h=function(){this.defaultPrevented=!0};var Y=(()=>{if(!N.addEventListener||!Object.defineProperty)return!1;var e=!1,t=Object.defineProperty({},"passive",{get:function(){e=!0}});try{var r=()=>{};N.addEventListener("test",r,t),N.removeEventListener("test",r,t)}catch(e){}return e})();function R(e){return/^[\s\xa0]*$/.test(e)}function s(e,t){o.call(this,e?e.type:""),this.relatedTarget=this.g=this.target=null,this.button=this.screenY=this.screenX=this.clientY=this.clientX=0,this.key="",this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1,this.state=null,this.pointerId=0,this.pointerType="",this.i=null,e&&this.init(e,t)}t(s,o),s.prototype.init=function(e,t){var r=this.type=e.type,n=e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:null;this.target=e.target||e.srcElement,this.g=t,(t=e.relatedTarget)||("mouseover"==r?t=e.fromElement:"mouseout"==r&&(t=e.toElement)),this.relatedTarget=t,n?(this.clientX=void 0!==n.clientX?n.clientX:n.pageX,this.clientY=void 0!==n.clientY?n.clientY:n.pageY,this.screenX=n.screenX||0,this.screenY=n.screenY||0):(this.clientX=void 0!==e.clientX?e.clientX:e.pageX,this.clientY=void 0!==e.clientY?e.clientY:e.pageY,this.screenX=e.screenX||0,this.screenY=e.screenY||0),this.button=e.button,this.key=e.key||"",this.ctrlKey=e.ctrlKey,this.altKey=e.altKey,this.shiftKey=e.shiftKey,this.metaKey=e.metaKey,this.pointerId=e.pointerId||0,this.pointerType=e.pointerType,this.state=e.state,(this.i=e).defaultPrevented&&s.Z.h.call(this)},s.prototype.h=function(){s.Z.h.call(this);var e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1};var l="closure_listenable_"+(1e6*Math.random()|0),J=0;function X(e,t,r,n,i){this.listener=e,this.proxy=null,this.src=t,this.type=r,this.capture=!!n,this.ha=i,this.key=++J,this.da=this.fa=!1}function Z(e){e.da=!0,e.listener=null,e.proxy=null,e.src=null,e.ha=null}function ee(e,t,r){for(var n in e)t.call(r,e[n],n,e)}function te(e){var t,r={};for(t in e)r[t]=e[t];return r}let re="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function ne(t){let r,n;for(let i=1;i<arguments.length;i++){for(r in n=arguments[i])t[r]=n[r];for(let e=0;e<re.length;e++)r=re[e],Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}}function ie(e){this.src=e,this.g={},this.h=0}function se(e,t){var r,n,i,s=t.type;s in e.g&&(r=e.g[s],(i=0<=(n=Array.prototype.indexOf.call(r,t,void 0)))&&Array.prototype.splice.call(r,n,1),i)&&(Z(t),0==e.g[s].length)&&(delete e.g[s],e.h--)}function ae(e,t,r,n){for(let s=0;s<e.length;++s){var i=e[s];if(!i.da&&i.listener==t&&i.capture==!!r&&i.ha==n)return s}return-1}ie.prototype.add=function(e,t,r,n,i){var s=e.toString(),a=((e=this.g[s])||(e=this.g[s]=[],this.h++),ae(e,t,n,i));return-1<a?(t=e[a],r||(t.fa=!1)):((t=new X(t,this.src,s,!!n,i)).fa=r,e.push(t)),t};var oe="closure_lm_"+(1e6*Math.random()|0),le={};function he(t,r,n,i,s){if(i&&i.once)return function t(r,n,i,s,a){if(Array.isArray(n)){for(let e=0;e<n.length;e++)t(r,n[e],i,s,a);return null}i=me(i);return r&&r[l]?r.K(n,i,d(s)?!!s.capture:!!s,a):ce(r,n,i,!0,s,a)}(t,r,n,i,s);if(Array.isArray(r)){for(let e=0;e<r.length;e++)he(t,r[e],n,i,s);return null}return n=me(n),t&&t[l]?t.J(r,n,d(i)?!!i.capture:!!i,s):ce(t,r,n,!1,i,s)}function ce(e,t,r,n,i,s){if(!t)throw Error("Invalid event type");var a=d(i)?!!i.capture:!!i;let o=fe(e);if(o||(e[oe]=o=new ie(e)),!(r=o.add(t,r,n,a,s)).proxy)if(n=(()=>{let r=pe;return function e(t){return r.call(e.src,e.listener,t)}})(),(r.proxy=n).src=e,n.listener=r,e.addEventListener)void 0===(i=Y?i:a)&&(i=!1),e.addEventListener(t.toString(),n,i);else if(e.attachEvent)e.attachEvent(de(t.toString()),n);else{if(!e.addListener||!e.removeListener)throw Error("addEventListener and attachEvent are unavailable.");e.addListener(n)}return r}function ue(e){var t,r,n;"number"!=typeof e&&e&&!e.da&&((t=e.src)&&t[l]?se(t.i,e):(r=e.type,n=e.proxy,t.removeEventListener?t.removeEventListener(r,n,e.capture):t.detachEvent?t.detachEvent(de(r),n):t.addListener&&t.removeListener&&t.removeListener(n),(r=fe(t))?(se(r,e),0==r.h&&(r.src=null,t[oe]=null)):Z(e)))}function de(e){return e in le?le[e]:le[e]="on"+e}function pe(e,t){var r,n;return e=!!e.da||(t=new s(t,this),r=e.listener,n=e.ha||e.src,e.fa&&ue(e),r.call(n,t))}function fe(e){return(e=e[oe])instanceof ie?e:null}var ge="__closure_events_fn_"+(1e9*Math.random()>>>0);function me(t){return"function"==typeof t?t:(t[ge]||(t[ge]=function(e){return t.handleEvent(e)}),t[ge])}function a(){i.call(this),this.i=new ie(this),(this.M=this).G=null}function h(e,t){var r,n,i=e.G;if(i)for(r=[];i;i=i.G)r.push(i);e=e.M,i=t.type||t,"string"==typeof t?t=new o(t,e):t instanceof o?t.target=t.target||e:(n=t,ne(t=new o(i,e),n)),n=!0;let s,a;if(r)for(a=r.length-1;0<=a;a--)n=ve(s=t.g=r[a],i,!0,t)&&n;if(n=ve(s=t.g=e,i,!0,t)&&n,n=ve(s,i,!1,t)&&n,r)for(a=0;a<r.length;a++)n=ve(s=t.g=r[a],i,!1,t)&&n}function ve(e,t,r,n){if(!(t=e.i.g[String(t)]))return!0;t=t.concat();let i=!0;for(let l=0;l<t.length;++l){var s,a,o=t[l];o&&!o.da&&o.capture==r&&(s=o.listener,a=o.ha||o.src,o.fa&&se(e.i,o),i=!1!==s.call(a,n)&&i)}return i&&!n.defaultPrevented}function _e(e){e.g=((e,t)=>{if("function"!=typeof e){if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=v(e.handleEvent,e)}return 2147483647<Number(t)?-1:N.setTimeout(e,t||0)})(()=>{e.g=null,e.i&&(e.i=!1,_e(e))},e.l);var t=e.h;e.h=null,e.m.apply(null,t)}t(a,i),a.prototype[l]=!0,a.prototype.removeEventListener=function(e,t,r,n){!function e(t,r,n,i,s){if(Array.isArray(r))for(var a=0;a<r.length;a++)e(t,r[a],n,i,s);else i=d(i)?!!i.capture:!!i,n=me(n),t&&t[l]?(t=t.i,(a=String(r).toString())in t.g&&-1<(n=ae(r=t.g[a],n,i,s))&&(Z(r[n]),Array.prototype.splice.call(r,n,1),0==r.length)&&(delete t.g[a],t.h--)):(t=t&&fe(t))&&(r=t.g[r.toString()],n=(t=-1)<(t=r?ae(r,n,i,s):t)?r[t]:null)&&ue(n)}(this,e,t,r,n)},a.prototype.N=function(){if(a.Z.N.call(this),this.i){var t,r=this.i;for(t in r.g){var n=r.g[t];for(let e=0;e<n.length;e++)Z(n[e]);delete r.g[t],r.h--}}this.G=null},a.prototype.J=function(e,t,r,n){return this.i.add(String(e),t,!1,r,n)},a.prototype.K=function(e,t,r,n){return this.i.add(String(e),t,!0,r,n)};class ye extends i{constructor(e,t){super(),this.m=e,this.l=t,this.h=null,this.i=!1,this.g=null}j(e){this.h=arguments,this.g?this.i=!0:_e(this)}N(){super.N(),this.g&&(N.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function c(e){i.call(this),this.h=e,this.g={}}t(c,i);var we=[];function be(e){ee(e.g,function(e,t){this.g.hasOwnProperty(t)&&ue(e)},e),e.g={}}c.prototype.N=function(){c.Z.N.call(this),be(this)},c.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var Ie=N.JSON.stringify,Te=N.JSON.parse,Ee=class{stringify(e){return N.JSON.stringify(e,void 0)}parse(e){return N.JSON.parse(e,void 0)}};function Ce(){}function Se(){}var ke={OPEN:"a",hb:"b",ERROR:"c",tb:"d"};function Ae(){o.call(this,"d")}function Ne(){o.call(this,"c")}t(Ae,o),t(Ne,o);var u={},Re=null;function Pe(){return Re=Re||new a}function De(e){o.call(this,u.Ia,e)}function xe(){var e=Pe();h(e,new De(e))}function Oe(e,t){o.call(this,u.STAT_EVENT,e),this.stat=t}function P(e){var t=Pe();h(t,new Oe(t,e))}function Me(e,t){o.call(this,u.Ja,e),this.size=t}function _(e,t){if("function"!=typeof e)throw Error("Fn must not be null and must be a function");return N.setTimeout(function(){e()},t)}function p(){this.g=!0}function D(e,t,r,n){e.info(function(){return"XMLHTTP TEXT ("+t+"): "+((e,t)=>{if(!e.g)return t;if(!t)return null;try{var r=JSON.parse(t);if(r)for(e=0;e<r.length;e++)if(Array.isArray(r[e])){var n=r[e];if(!(n.length<2)){var i=n[1];if(Array.isArray(i)&&!(i.length<1)){var s=i[0];if("noop"!=s&&"stop"!=s&&"close"!=s)for(let e=1;e<i.length;e++)i[e]=""}}}return Ie(r)}catch(e){return t}})(e,r)+(n?" "+n:"")})}u.Ia="serverreachability",t(De,o),u.STAT_EVENT="statevent",t(Oe,o),u.Ja="timingevent",t(Me,o),p.prototype.ua=function(){this.g=!1},p.prototype.info=function(){};var Le={NO_ERROR:0,cb:1,qb:2,pb:3,kb:4,ob:5,rb:6,Ga:7,TIMEOUT:8,ub:9},Fe={ib:"complete",Fb:"success",ERROR:"error",Ga:"abort",xb:"ready",yb:"readystatechange",TIMEOUT:"timeout",sb:"incrementaldata",wb:"progress",lb:"downloadprogress",Nb:"uploadprogress"};function Ue(){}function f(e){return encodeURIComponent(String(e))}function g(e,t,r,n){this.j=e,this.i=t,this.l=r,this.S=n||1,this.V=new c(this),this.H=45e3,this.J=null,this.o=!1,this.u=this.B=this.A=this.M=this.F=this.T=this.D=null,this.G=[],this.g=null,this.C=0,this.m=this.v=null,this.X=-1,this.K=!1,this.P=0,this.O=null,this.W=this.L=this.U=this.R=!1,this.h=new Ve}function Ve(){this.i=null,this.g="",this.h=!1}t(Ue,Ce),Ue.prototype.g=function(){return new XMLHttpRequest};var qe=new Ue,Be={},je={};function ze(e,t,r){e.M=1,e.A=ot(y(t)),e.u=r,e.R=!0,Ke(e,null)}function Ke(e,t){e.F=Date.now(),He(e),e.B=y(e.A);var a,o,l,h,c,u,r=e.B,n=e.S,i=(Array.isArray(n)||(n=[String(n)]),wt(r.i,"t",n),e.C=0,r=e.j.L,e.h=new Ve,e.g=tr(e.j,r?t:null,!e.u),0<e.P&&(e.O=new ye(v(e.Y,e,e.g),e.P)),t=e.V,r=e.g,n=e.ba,"readystatechange");Array.isArray(i)||(i&&(we[0]=i.toString()),i=we);for(let d=0;d<i.length;d++){var s=he(r,i[d],n||t.handleEvent,!1,t.h||t);if(!s)break;t.g[s.key]=s}t=e.J?te(e.J):{},e.u?(e.v||(e.v="POST"),t["Content-Type"]="application/x-www-form-urlencoded",e.g.ea(e.B,e.v,e.u,t)):(e.v="GET",e.g.ea(e.B,e.v,null,t)),xe(),a=e.i,o=e.v,l=e.B,h=e.l,c=e.S,u=e.u,a.info(function(){if(a.g)if(u){var t="",r=u.split("&");for(let e=0;e<r.length;e++){var n,i,s=r[e].split("=");1<s.length&&(n=s[0],s=s[1],t=2<=(i=n.split("_")).length&&"type"==i[1]?t+(n+"=")+s+"&":t+(n+"=redacted&"))}}else t=null;else t=u;return"XMLHTTP REQ ("+h+") [attempt "+c+"]: "+o+"\n"+l+"\n"+t})}function We(e){return e.g&&"GET"==e.v&&2!=e.M&&e.j.Aa}function He(e){e.T=Date.now()+e.H,Ge(e,e.H)}function Ge(e,t){if(null!=e.D)throw Error("WatchDog timer not null");e.D=_(v(e.aa,e),t)}function $e(e){e.D&&(N.clearTimeout(e.D),e.D=null)}function x(e){0==e.j.I||e.K||Jt(e.j,e)}function O(e){$e(e);var t=e.O;t&&"function"==typeof t.dispose&&t.dispose(),e.O=null,be(e.V),e.g&&(t=e.g,e.g=null,t.abort(),t.dispose())}function Qe(e,t){try{var r=e.j;if(0!=r.I&&(r.g==e||et(r.h,e)))if(!e.L&&et(r.h,e)&&3==r.I){try{var n=r.Ba.g.parse(t)}catch(e){n=null}if(Array.isArray(n)&&3==n.length){var i=n;if(0==i[0]){e:if(!r.v){if(r.g){if(!(r.g.F+3e3<e.F))break e;Yt(r),qt(r)}Gt(r),P(18)}}else r.xa=i[1],0<r.xa-r.K&&i[2]<37500&&r.F&&0==r.A&&!r.C&&(r.C=_(v(r.Va,r),6e3));Ze(r.h)<=1&&r.ta&&(r.ta=void 0)}else S(r,11)}else if(!e.L&&r.g!=e||Yt(r),!R(t))for(i=r.Ba.g.parse(t),t=0;t<i.length;t++){var s,a,o,l,h,c,u,d,p,f,g=i[t],m=g[0];m<=r.K||(r.K=m,g=g[1],2==r.I?"c"==g[0]?(r.M=g[1],r.ba=g[2],null!=(s=g[3])&&(r.ka=s,r.j.info("VER="+r.ka)),null!=(a=g[4])&&(r.za=a,r.j.info("SVER="+r.za)),null!=(o=g[5])&&"number"==typeof o&&0<o&&(n=1.5*o,r.O=n,r.j.info("backChannelRequestTimeoutMs_="+n)),n=r,(l=e.g)&&(!(h=l.g?l.g.getResponseHeader("X-Client-Wire-Protocol"):null)||(c=n.h).g||-1==h.indexOf("spdy")&&-1==h.indexOf("quic")&&-1==h.indexOf("h2")||(c.j=c.l,c.g=new Set,c.h&&(tt(c,c.h),c.h=null)),n.G)&&(u=l.g?l.g.getResponseHeader("X-HTTP-Session-Id"):null)&&(n.wa=u,b(n.J,n.G,u)),r.I=3,r.l&&r.l.ra(),r.aa&&(r.T=Date.now()-e.F,r.j.info("Handshake RTT: "+r.T+"ms")),d=e,(n=r).na=er(n,n.L?n.ba:null,n.W),d.L?(rt(n.h,d),p=d,(f=n.O)&&(p.H=f),p.D&&($e(p),He(p)),n.g=d):Ht(n),0<r.i.length&&jt(r)):"stop"!=g[0]&&"close"!=g[0]||S(r,7):3==r.I&&("stop"==g[0]||"close"==g[0]?"stop"==g[0]?S(r,7):Vt(r):"noop"!=g[0]&&r.l&&r.l.qa(g),r.A=0))}xe()}catch(e){}}g.prototype.ba=function(e){e=e.target;var t=this.O;t&&3==M(e)?t.j():this.Y(e)},g.prototype.Y=function(e){try{if(e==this.g)e:{var t=M(this.g),r=this.g.ya();this.g.ca();if(!(t<3)&&(3!=t||this.g&&(this.h.h||this.g.la()||Lt(this.g)))){this.K||4!=t||7==r||xe(),$e(this);var n,i,s=this.g.ca(),a=(this.X=s,(e=>{if(!We(e))return e.g.la();var t=Lt(e.g);if(""===t)return"";let r="",n=t.length,i=4==M(e.g);if(!e.h.i){if("undefined"==typeof TextDecoder)return O(e),x(e),"";e.h.i=new N.TextDecoder}for(let s=0;s<n;s++)e.h.h=!0,r+=e.h.i.decode(t[s],{stream:!(i&&s==n-1)});return t.length=0,e.h.g+=r,e.C=0,e.h.g})(this));if(this.o=200==s,I=this.i,T=this.v,E=this.B,C=this.l,S=this.S,k=t,A=s,I.info(function(){return"XMLHTTP RESP ("+C+") [ attempt "+S+"]: "+T+"\n"+E+"\n"+k+" "+A}),this.o){if(this.U&&!this.L){t:{if(this.g){var o,l=this.g;if((o=l.g?l.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!R(o)){var h=o;break t}}h=null}if(!(e=h)){this.o=!1,this.m=3,P(12),O(this),x(this);break e}D(this.i,this.l,e,"Initial handshake response via X-HTTP-Initial-Response"),this.L=!0,Qe(this,e)}if(this.R){for(e=!0;!this.K&&this.C<a.length;){if(y=a,b=w=void 0,w=(_=this).C,(n=-1==(b=y.indexOf("\n",w))?je:(w=Number(y.substring(w,b)),isNaN(w)?Be:(b+=1)+w>y.length?je:(y=y.slice(b,b+w),_.C=b+w,y)))==je){4==t&&(this.m=4,P(14),e=!1),D(this.i,this.l,null,"[Incomplete Response]");break}if(n==Be){this.m=4,P(15),D(this.i,this.l,a,"[Invalid Chunk]"),e=!1;break}D(this.i,this.l,n,null),Qe(this,n)}We(this)&&0!=this.C&&(this.h.g=this.h.g.slice(this.C),this.C=0),4!=t||0!=a.length||this.h.h||(this.m=1,P(16),e=!1),this.o=this.o&&e,e?0<a.length&&!this.W&&(this.W=!0,(i=this.j).g==this)&&i.aa&&!i.P&&(i.j.info("Great, no buffering proxy detected. Bytes received: "+a.length),$t(i),i.P=!0,P(11)):(D(this.i,this.l,a,"[Invalid Chunked Response]"),O(this),x(this))}else D(this.i,this.l,a,null),Qe(this,a);4==t&&O(this),this.o&&!this.K&&(4==t?Jt(this.j,this):(this.o=!1,He(this)))}else{{var c=this.g;var u,d,p,f={};c=(c.g&&2<=M(c)&&c.g.getAllResponseHeaders()||"").split("\r\n");for(let e=0;e<c.length;e++)R(c[e])||(u=(e=>{for(var t=1,r=(e=e.split(":"),[]);0<t&&e.length;)r.push(e.shift()),t--;return e.length&&r.push(e.join(":")),r})(c[e]),d=u[0],"string"==typeof(u=u[1])&&(u=u.trim(),p=f[d]||[],(f[d]=p).push(u)));var g,m=f,v=function(e){return e.join(", ")};for(g in m)v.call(void 0,m[g],g,m)}400==s&&0<a.indexOf("Unknown SID")?(this.m=3,P(12)):(this.m=0,P(13)),O(this),x(this)}}}}catch(e){}var _,y,w,b,I,T,E,C,S,k,A},g.prototype.cancel=function(){this.K=!0,O(this)},g.prototype.aa=function(){this.D=null;var e,t,r=Date.now();0<=r-this.T?(e=this.i,t=this.B,e.info(function(){return"TIMEOUT: "+t}),2!=this.M&&(xe(),P(17)),O(this),this.m=2,x(this)):Ge(this,this.T-r)};var Ye=class{constructor(e,t){this.g=e,this.map=t}};function Je(e){this.l=e||10,e=N.PerformanceNavigationTiming?0<(e=N.performance.getEntriesByType("navigation")).length&&("hq"==e[0].nextHopProtocol||"h2"==e[0].nextHopProtocol):!!(N.chrome&&N.chrome.loadTimes&&N.chrome.loadTimes()&&N.chrome.loadTimes().wasFetchedViaSpdy),this.j=e?this.l:1,this.g=null,1<this.j&&(this.g=new Set),this.h=null,this.i=[]}function Xe(e){return e.h||e.g&&e.g.size>=e.j}function Ze(e){return e.h?1:e.g?e.g.size:0}function et(e,t){return e.h?e.h==t:e.g&&e.g.has(t)}function tt(e,t){e.g?e.g.add(t):e.h=t}function rt(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function nt(t){if(null!=t.h)return t.i.concat(t.h.G);if(null==t.g||0===t.g.size)return z(t.i);{let e=t.i;for(var r of t.g.values())e=e.concat(r.G);return e}}Je.prototype.cancel=function(){if(this.i=nt(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&0!==this.g.size){for(var e of this.g.values())e.cancel();this.g.clear()}};var it=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function m(e){this.g=this.o=this.j="",this.u=null,this.m=this.h="",this.l=!1;let t;e instanceof m?(this.l=e.l,w(this,e.j),this.o=e.o,this.g=e.g,st(this,e.u),this.h=e.h,at(this,bt(e.i)),this.m=e.m):e&&(t=String(e).match(it))?(this.l=!1,w(this,t[1]||"",!0),this.o=lt(t[2]||""),this.g=lt(t[3]||"",!0),st(this,t[4]),this.h=lt(t[5]||"",!0),at(this,t[6]||"",!0),this.m=lt(t[7]||"")):(this.l=!1,this.i=new mt(null,this.l))}function y(e){return new m(e)}function w(e,t,r){e.j=r?lt(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function st(e,t){if(t){if(t=Number(t),isNaN(t)||t<0)throw Error("Bad port number "+t);e.u=t}else e.u=null}function at(e,t,r){var n,i;t instanceof mt?(e.i=t,n=e.i,(i=e.l)&&!n.j&&(I(n),n.i=null,n.g.forEach(function(e,t){var r=t.toLowerCase();t!=r&&(vt(this,t),wt(this,r,e))},n)),n.j=i):(r||(t=ht(t,ft)),e.i=new mt(t,e.l))}function b(e,t,r){e.i.set(t,r)}function ot(e){return b(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function lt(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function ht(e,t,r){return"string"==typeof e?(e=encodeURI(e).replace(t,ct),e=r?e.replace(/%25([0-9a-fA-F]{2})/g,"%$1"):e):null}function ct(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}m.prototype.toString=function(){var e=[],t=this.j,r=(t&&e.push(ht(t,ut,!0),":"),this.g);return!r&&"file"!=t||(e.push("//"),(t=this.o)&&e.push(ht(t,ut,!0),"@"),e.push(f(r).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null==(r=this.u))||e.push(":",String(r)),(r=this.h)&&(this.g&&"/"!=r.charAt(0)&&e.push("/"),e.push(ht(r,"/"==r.charAt(0)?pt:dt,!0))),(r=this.i.toString())&&e.push("?",r),(r=this.m)&&e.push("#",ht(r,gt)),e.join("")},m.prototype.resolve=function(e){var t=y(this);let r=!!e.j;r?w(t,e.j):r=!!e.o,r?t.o=e.o:r=!!e.g,r?t.g=e.g:r=null!=e.u;var n=e.h;if(r)st(t,e.u);else if(r=!!e.h)if("/"!=n.charAt(0)&&(this.g&&!this.h?n="/"+n:-1!=(i=t.h.lastIndexOf("/"))&&(n=t.h.slice(0,i+1)+n)),".."==(i=n)||"."==i)n="";else if(-1!=i.indexOf("./")||-1!=i.indexOf("/.")){var n=0==i.lastIndexOf("/",0),i=i.split("/"),s=[];for(let e=0;e<i.length;){var a=i[e++];"."==a?n&&e==i.length&&s.push(""):".."==a?((1<s.length||1==s.length&&""!=s[0])&&s.pop(),n&&e==i.length&&s.push("")):(s.push(a),n=!0)}n=s.join("/")}else n=i;return r?t.h=n:r=""!==e.i.toString(),r?at(t,bt(e.i)):r=!!e.m,r&&(t.m=e.m),t};var ut=/[#\/\?@]/g,dt=/[#\?:]/g,pt=/[#\?]/g,ft=/[#\?@]/g,gt=/#/g;function mt(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function I(r){if(!r.g&&(r.g=new Map,r.h=0,r.i)){var n=r.i,i=function(e,t){r.add(decodeURIComponent(e.replace(/\+/g," ")),t)};if(n){n=n.split("&");for(let r=0;r<n.length;r++){var s=n[r].indexOf("=");let e,t=null;0<=s?(e=n[r].substring(0,s),t=n[r].substring(s+1)):e=n[r],i(e,t?decodeURIComponent(t.replace(/\+/g," ")):"")}}}}function vt(e,t){I(e),t=T(e,t),e.g.has(t)&&(e.i=null,e.h-=e.g.get(t).length,e.g.delete(t))}function _t(e,t){return I(e),t=T(e,t),e.g.has(t)}function yt(e,t){I(e);let r=[];if("string"==typeof t)_t(e,t)&&(r=r.concat(e.g.get(T(e,t))));else for(e=Array.from(e.g.values()),t=0;t<e.length;t++)r=r.concat(e[t]);return r}function wt(e,t,r){vt(e,t),0<r.length&&(e.i=null,e.g.set(T(e,t),z(r)),e.h+=r.length)}function bt(e){var t=new mt;return t.i=e.i,e.g&&(t.g=new Map(e.g),t.h=e.h),t}function T(e,t){return t=String(t),t=e.j?t.toLowerCase():t}function E(e,t,r,n,i){try{i&&(i.onload=null,i.onerror=null,i.onabort=null,i.ontimeout=null),n(r)}catch(e){}}function It(){this.g=new Ee}function Tt(e){this.i=e.Sb||null,this.h=e.ab||!1}function Et(e,t){a.call(this),this.H=e,this.o=t,this.m=void 0,this.status=this.readyState=0,this.responseType=this.responseText=this.response=this.statusText="",this.onreadystatechange=null,this.A=new Headers,this.h=null,this.F="GET",this.D="",this.g=!1,this.B=this.j=this.l=null,this.v=new AbortController}function Ct(e){e.j.read().then(e.Ma.bind(e)).catch(e.ga.bind(e))}function St(e){e.readyState=4,e.l=null,e.j=null,e.B=null,kt(e)}function kt(e){e.onreadystatechange&&e.onreadystatechange.call(e)}function At(e){let r="";return ee(e,function(e,t){r=(r=r+t+":")+e+"\r\n"}),r}function Nt(e,t,r){e:{for(n in r){var n=!1;break e}n=!0}n||(r=At(r),"string"==typeof e?null!=r&&f(r):b(e,t,r))}function C(e){a.call(this),this.headers=new Map,this.L=e||null,this.h=!1,this.g=null,this.D="",this.o=0,this.l="",this.j=this.B=this.v=this.A=!1,this.m=null,this.F="",this.H=!1}(e=mt.prototype).add=function(e,t){I(this),this.i=null,e=T(this,e);let r=this.g.get(e);return r||this.g.set(e,r=[]),r.push(t),this.h+=1,this},e.forEach=function(r,n){I(this),this.g.forEach(function(e,t){e.forEach(function(e){r.call(n,e,t,this)},this)},this)},e.set=function(e,t){return I(this),this.i=null,_t(this,e=T(this,e))&&(this.h-=this.g.get(e).length),this.g.set(e,[t]),this.h+=1,this},e.get=function(e,t){return e&&0<(e=yt(this,e)).length?String(e[0]):t},e.toString=function(){if(this.i)return this.i;if(!this.g)return"";var r=[],e=Array.from(this.g.keys());for(let s=0;s<e.length;s++){var n=f(i=e[s]),i=yt(this,i);for(let t=0;t<i.length;t++){let e=n;""!==i[t]&&(e+="="+f(i[t])),r.push(e)}}return this.i=r.join("&")},t(Tt,Ce),Tt.prototype.g=function(){return new Et(this.i,this.h)},t(Et,a),(e=Et.prototype).open=function(e,t){if(0!=this.readyState)throw this.abort(),Error("Error reopening a connection");this.F=e,this.D=t,this.readyState=1,kt(this)},e.send=function(e){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");if(this.v.signal.aborted)throw this.abort(),Error("Request was aborted.");this.g=!0;var t={headers:this.A,method:this.F,credentials:this.m,cache:void 0,signal:this.v.signal};e&&(t.body=e),(this.H||N).fetch(new Request(this.D,t)).then(this.Pa.bind(this),this.ga.bind(this))},e.abort=function(){this.response=this.responseText="",this.A=new Headers,this.status=0,this.v.abort(),this.j&&this.j.cancel("Request was aborted.").catch(()=>{}),1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,St(this)),this.readyState=0},e.Pa=function(e){if(this.g&&(this.l=e,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=e.headers,this.readyState=2,kt(this)),this.g)&&(this.readyState=3,kt(this),this.g))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Na.bind(this),this.ga.bind(this));else if(void 0!==N.ReadableStream&&"body"in e){if(this.j=e.body.getReader(),this.o){if(this.responseType)throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');this.response=[]}else this.response=this.responseText="",this.B=new TextDecoder;Ct(this)}else e.text().then(this.Oa.bind(this),this.ga.bind(this))},e.Ma=function(e){var t;this.g&&(this.o&&e.value?this.response.push(e.value):!this.o&&(t=e.value||new Uint8Array(0),t=this.B.decode(t,{stream:!e.done}))&&(this.response=this.responseText+=t),(e.done?St:kt)(this),3==this.readyState)&&Ct(this)},e.Oa=function(e){this.g&&(this.response=this.responseText=e,St(this))},e.Na=function(e){this.g&&(this.response=e,St(this))},e.ga=function(){this.g&&St(this)},e.setRequestHeader=function(e,t){this.A.append(e,t)},e.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},e.getAllResponseHeaders=function(){if(!this.h)return"";for(var e=[],t=this.h.entries(),r=t.next();!r.done;)r=r.value,e.push(r[0]+": "+r[1]),r=t.next();return e.join("\r\n")},Object.defineProperty(Et.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}}),t(C,a);var Rt=/^https?$/i,Pt=["POST","PUT"];function Dt(e,t){e.h=!1,e.g&&(e.j=!0,e.g.abort(),e.j=!1),e.l=t,e.o=5,xt(e),Mt(e)}function xt(e){e.A||(e.A=!0,h(e,"complete"),h(e,"error"))}function Ot(t){if(t.h&&void 0!==V)if(t.v&&4==M(t))setTimeout(t.Ca.bind(t),0);else if(h(t,"readystatechange"),4==M(t)){t.h=!1;try{var e,r,n=t.ca();switch(n){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var i=!0;break;default:i=!1}if(!(e=i)){if(r=0===n){let e=String(t.D).match(it)[1]||null;!e&&N.self&&N.self.location&&(e=N.self.location.protocol.slice(0,-1)),r=!Rt.test(e?e.toLowerCase():"")}e=r}if(e)h(t,"complete"),h(t,"success");else{t.o=6;try{var s=2<M(t)?t.g.statusText:""}catch(e){s=""}t.l=s+" ["+t.ca()+"]",xt(t)}}finally{Mt(t)}}}function Mt(e,t){if(e.g){e.m&&(clearTimeout(e.m),e.m=null);var r=e.g;e.g=null,t||h(e,"ready");try{r.onreadystatechange=null}catch(e){}}}function M(e){return e.g?e.g.readyState:0}function Lt(e){try{if(e.g){if("response"in e.g)return e.g.response;switch(e.F){case"":case"text":return e.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in e.g)return e.g.mozResponseArrayBuffer}}return null}catch(e){return null}}function Ft(e,t,r){return r&&r.internalChannelParams&&r.internalChannelParams[e]||t}function Ut(e){this.za=0,this.i=[],this.j=new p,this.ba=this.na=this.J=this.W=this.g=this.wa=this.G=this.H=this.u=this.U=this.o=null,this.Ya=this.V=0,this.Sa=Ft("failFast",!1,e),this.F=this.C=this.v=this.m=this.l=null,this.X=!0,this.xa=this.K=-1,this.Y=this.A=this.D=0,this.Qa=Ft("baseRetryDelayMs",5e3,e),this.Za=Ft("retryDelaySeedMs",1e4,e),this.Ta=Ft("forwardChannelMaxRetries",2,e),this.va=Ft("forwardChannelRequestTimeoutMs",2e4,e),this.ma=e&&e.xmlHttpFactory||void 0,this.Ua=e&&e.Rb||void 0,this.Aa=e&&e.useFetchStreams||!1,this.O=void 0,this.L=e&&e.supportsCrossDomainXhr||!1,this.M="",this.h=new Je(e&&e.concurrentRequestLimit),this.Ba=new It,this.S=e&&e.fastHandshake||!1,this.R=e&&e.encodeInitMessageHeaders||!1,this.S&&this.R&&(this.R=!1),this.Ra=e&&e.Pb||!1,e&&e.ua&&this.j.ua(),e&&e.forceLongPolling&&(this.X=!1),this.aa=!this.S&&this.X&&e&&e.detectBufferingProxy||!1,this.ia=void 0,e&&e.longPollingTimeout&&0<e.longPollingTimeout&&(this.ia=e.longPollingTimeout),this.ta=void 0,this.T=0,this.P=!1,this.ja=this.B=null}function Vt(e){if(Bt(e),3==e.I){var t=e.V++,r=y(e.J);if(b(r,"SID",e.M),b(r,"RID",t),b(r,"TYPE","terminate"),Kt(e,r),(t=new g(e,e.j,t)).M=2,t.A=ot(y(r)),r=!1,N.navigator&&N.navigator.sendBeacon)try{r=N.navigator.sendBeacon(t.A.toString(),"")}catch(e){}!r&&N.Image&&((new Image).src=t.A,r=!0),r||(t.g=tr(t.j,null),t.g.ea(t.A)),t.F=Date.now(),He(t)}Zt(e)}function qt(e){e.g&&($t(e),e.g.cancel(),e.g=null)}function Bt(e){qt(e),e.v&&(N.clearTimeout(e.v),e.v=null),Yt(e),e.h.cancel(),e.m&&("number"==typeof e.m&&N.clearTimeout(e.m),e.m=null)}function jt(e){var t;Xe(e.h)||e.m||(e.m=!0,t=e.Ea,r||$(),n||(r(),n=!0),G.add(t,e),e.D=0)}function zt(e,t){var r=t?t.l:e.V++,n=y(e.J);b(n,"SID",e.M),b(n,"RID",r),b(n,"AID",e.K),Kt(e,n),e.u&&e.o&&Nt(n,e.u,e.o),r=new g(e,e.j,r,e.D+1),null===e.u&&(r.J=e.o),t&&(e.i=t.G.concat(e.i)),t=Wt(e,r,1e3),r.H=Math.round(.5*e.va)+Math.round(.5*e.va*Math.random()),tt(e.h,r),ze(r,n,t)}function Kt(e,r){e.H&&ee(e.H,function(e,t){b(r,t,e)}),e.l&&ee({},function(e,t){b(r,t,e)})}function Wt(e,t,i){i=Math.min(e.i.length,i);var s=e.l?v(e.l.Ka,e.l,e):null;e:{let r=e.i,n=-1;for(;;){var a=["count="+i];-1==n?0<i?(n=r[0].g,a.push("ofs="+n)):n=0:a.push("ofs="+n);let e=!0;for(let t=0;t<i;t++){var o=r[t].g,l=r[t].map;if((o-=n)<0)n=Math.max(0,r[t].g-100),e=!1;else try{o="req"+o+"_"||"";try{var h,c,u=l instanceof Map?l:Object.entries(l);for([h,c]of u){let e=c;d(c)&&(e=Ie(c)),a.push(o+h+"="+encodeURIComponent(e))}}catch(e){throw a.push(o+"type="+encodeURIComponent("_badmap")),e}}catch(e){s&&s(l)}}if(e){u=a.join("&");break e}}u=void 0}return e=e.i.splice(0,i),t.G=e,u}function Ht(e){var t;e.g||e.v||(e.Y=1,t=e.Da,r||$(),n||(r(),n=!0),G.add(t,e),e.A=0)}function Gt(e){return!(e.g||e.v||3<=e.A)&&(e.Y++,e.v=_(v(e.Da,e),Xt(e,e.A)),e.A++,1)}function $t(e){null!=e.B&&(N.clearTimeout(e.B),e.B=null)}function Qt(e){e.g=new g(e,e.j,"rpc",e.Y),null===e.u&&(e.g.J=e.o),e.g.P=0;var t=y(e.na),r=(b(t,"RID","rpc"),b(t,"SID",e.M),b(t,"AID",e.K),b(t,"CI",e.F?"0":"1"),!e.F&&e.ia&&b(t,"TO",e.ia),b(t,"TYPE","xmlhttp"),Kt(e,t),e.u&&e.o&&Nt(t,e.u,e.o),e.O&&(e.g.H=e.O),e.g);e=e.ba,r.M=1,r.A=ot(y(t)),r.u=null,r.R=!0,Ke(r,e)}function Yt(e){null!=e.C&&(N.clearTimeout(e.C),e.C=null)}function Jt(e,t){var r,n,i,s=null;if(e.g==t){Yt(e),$t(e),e.g=null;var a=2}else{if(!et(e.h,t))return;s=t.G,rt(e.h,t),a=1}if(0!=e.I)if(t.o)(1==a?(s=t.u?t.u.length:0,t=Date.now()-t.F,r=e.D,h(a=Pe(),new Me(a,s)),jt):Ht)(e);else if(3==(r=t.m)||0==r&&0<t.X||(1!=a||(i=t,Ze((n=e).h)>=n.h.j-(n.m?1:0))||(n.m?(n.i=i.G.concat(n.i),0):1==n.I||2==n.I||n.D>=(n.Sa?0:n.Ta)||(n.m=_(v(n.Ea,n,i),Xt(n,n.D)),n.D++,0)))&&(2!=a||!Gt(e)))switch(s&&0<s.length&&(t=e.h,t.i=t.i.concat(s)),r){case 1:S(e,5);break;case 4:S(e,10);break;case 3:S(e,6);break;default:S(e,2)}}function Xt(e,t){let r=e.Qa+Math.floor(Math.random()*e.Za);return e.isActive()||(r*=2),r*t}function S(e,t){var r,n,i;e.j.info("Error code "+t),2==t?(r=v(e.bb,e),n=!(i=e.Ua),i=new m(i||"//www.google.com/images/cleardot.gif"),N.location&&"http"==N.location.protocol||w(i,"https"),ot(i),(n?(t,r)=>{var n=new p;if(N.Image){let e=new Image;e.onload=B(E,n,"TestLoadImage: loaded",!0,r,e),e.onerror=B(E,n,"TestLoadImage: error",!1,r,e),e.onabort=B(E,n,"TestLoadImage: abort",!1,r,e),e.ontimeout=B(E,n,"TestLoadImage: timeout",!1,r,e),N.setTimeout(function(){e.ontimeout&&e.ontimeout()},1e4),e.src=t}else r(!1)}:(e,t)=>{let r=new p,n=new AbortController,i=setTimeout(()=>{n.abort(),E(r,0,!1,t)},1e4);fetch(e,{signal:n.signal}).then(e=>{clearTimeout(i),e.ok?E(r,0,!0,t):E(r,0,!1,t)}).catch(()=>{clearTimeout(i),E(r,0,!1,t)})})(i.toString(),r)):P(2),e.I=0,e.l&&e.l.pa(t),Zt(e),Bt(e)}function Zt(e){var t;e.I=0,e.ja=[],e.l&&(0==(t=nt(e.h)).length&&0==e.i.length||(K(e.ja,t),K(e.ja,e.i),e.h.i.length=0,z(e.i),e.i.length=0),e.l.oa())}function er(e,t,r){var n,i,s=r instanceof m?y(r):new m(r);return""!=s.g?(t&&(s.g=t+"."+s.g),st(s,s.u)):(s=(n=N.location).protocol,t=t?t+"."+n.hostname:n.hostname,n=+n.port,i=new m(null),s&&w(i,s),t&&(i.g=t),n&&st(i,n),r&&(i.h=r),s=i),r=e.G,t=e.wa,r&&t&&b(s,r,t),b(s,"VER",e.ka),Kt(e,s),s}function tr(e,t,r){if(t&&!e.L)throw Error("Can't create secondary domain capable XhrIo object.");return(t=e.Aa&&!e.ma?new C(new Tt({ab:r})):new C(e.ma)).Fa(e.L),t}function rr(){}function nr(){}function k(e,t){a.call(this),this.g=new Ut(t),this.l=e,this.h=t&&t.messageUrlParams||null,e=t&&t.messageHeaders||null,t&&t.clientProtocolHeaderRequired&&(e?e["X-Client-Protocol"]="webchannel":e={"X-Client-Protocol":"webchannel"}),this.g.o=e,e=t&&t.initMessageHeaders||null,t&&t.messageContentType&&(e?e["X-WebChannel-Content-Type"]=t.messageContentType:e={"X-WebChannel-Content-Type":t.messageContentType}),t&&t.sa&&(e?e["X-WebChannel-Client-Profile"]=t.sa:e={"X-WebChannel-Client-Profile":t.sa}),this.g.U=e,(e=t&&t.Qb)&&!R(e)&&(this.g.u=e),this.A=t&&t.supportsCrossDomainXhr||!1,this.v=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!R(t)&&(this.g.G=t,null!==(e=this.h))&&t in e&&t in(e=this.h)&&delete e[t],this.j=new A(this)}function ir(e){Ae.call(this),e.__headers__&&(this.headers=e.__headers__,this.statusCode=e.__status__,delete e.__headers__,delete e.__status__);var t=e.__sm__;if(t){e:{for(var r in t){e=r;break e}e=void 0}(this.i=e)&&(e=this.i,t=null!==t&&e in t?t[e]:void 0),this.data=t}else this.data=e}function sr(){Ne.call(this),this.status=1}function A(e){this.g=e}(e=C.prototype).Fa=function(e){this.H=e},e.ea=function(e,t,r,n){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.D+"; newUri="+e);t=t?t.toUpperCase():"GET",this.D=e,this.l="",this.o=0,this.A=!1,this.h=!0,this.g=(this.L||qe).g(),this.g.onreadystatechange=j(v(this.Ca,this));try{this.B=!0,this.g.open(t,String(e),!0),this.B=!1}catch(e){return void Dt(this,e)}if(e=r||"",r=new Map(this.headers),n)if(Object.getPrototypeOf(n)===Object.prototype)for(var i in n)r.set(i,n[i]);else{if("function"!=typeof n.keys||"function"!=typeof n.get)throw Error("Unknown input type for opt_headers: "+String(n));for(var s of n.keys())r.set(s,n.get(s))}n=Array.from(r.keys()).find(e=>"content-type"==e.toLowerCase()),i=N.FormData&&e instanceof N.FormData,0<=Array.prototype.indexOf.call(Pt,t,void 0)&&!n&&!i&&r.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8");for(var[a,o]of r)this.g.setRequestHeader(a,o);this.F&&(this.g.responseType=this.F),"withCredentials"in this.g&&this.g.withCredentials!==this.H&&(this.g.withCredentials=this.H);try{this.m&&(clearTimeout(this.m),this.m=null),this.v=!0,this.g.send(e),this.v=!1}catch(e){Dt(this,e)}},e.abort=function(e){this.g&&this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1,this.o=e||7,h(this,"complete"),h(this,"abort"),Mt(this))},e.N=function(){this.g&&(this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1),Mt(this,!0)),C.Z.N.call(this)},e.Ca=function(){this.u||(this.B||this.v||this.j?Ot(this):this.Xa())},e.Xa=function(){Ot(this)},e.isActive=function(){return!!this.g},e.ca=function(){try{return 2<M(this)?this.g.status:-1}catch(e){return-1}},e.la=function(){try{return this.g?this.g.responseText:""}catch(e){return""}},e.La=function(e){var t;if(this.g)return t=this.g.responseText,e&&0==t.indexOf(e)&&(t=t.substring(e.length)),Te(t)},e.ya=function(){return this.o},e.Ha=function(){return"string"==typeof this.l?this.l:String(this.l)},(e=Ut.prototype).ka=8,e.I=1,e.connect=function(e,t,r,n){P(0),this.W=e,this.H=t||{},r&&void 0!==n&&(this.H.OSID=r,this.H.OAID=n),this.F=this.X,this.J=er(this,null,this.W),jt(this)},e.Ea=function(t){if(this.m)if(this.m=null,1==this.I){if(!t){this.V=Math.floor(1e5*Math.random()),t=this.V++;var r=new g(this,this.j,t);let e=this.o;if(this.U&&(e?ne(e=te(e),this.U):e=this.U),null!==this.u||this.R||(r.J=e,e=null),this.S)e:{for(var n=0,i=0;i<this.i.length;i++){var s=this.i[i];if("__data__"in s.map&&"string"==typeof(s=s.map.__data__)?s=s.length:s=void 0,void 0===s)break;if(4096<(n+=s)){n=i;break e}if(4096===n||i===this.i.length-1){n=i+1;break e}}n=1e3}else n=1e3;n=Wt(this,r,n),b(i=y(this.J),"RID",t),b(i,"CVER",22),this.G&&b(i,"X-HTTP-Session-Id",this.G),Kt(this,i),e&&(this.R?n="headers="+f(At(e))+"&"+n:this.u&&Nt(i,this.u,e)),tt(this.h,r),this.Ra&&b(i,"TYPE","init"),this.S?(b(i,"$req",n),b(i,"SID","null"),r.U=!0,ze(r,i,null)):ze(r,i,n),this.I=2}}else 3==this.I&&(t?zt(this,t):0==this.i.length||Xe(this.h)||zt(this))},e.Da=function(){var e;this.v=null,Qt(this),this.aa&&!(this.P||null==this.g||this.T<=0)&&(e=4*this.T,this.j.info("BP detection timer enabled: "+e),this.B=_(v(this.Wa,this),e))},e.Wa=function(){this.B&&(this.B=null,this.j.info("BP detection timeout reached."),this.j.info("Buffering proxy detected and switch to long-polling!"),this.F=!1,this.P=!0,P(10),qt(this),Qt(this))},e.Va=function(){null!=this.C&&(this.C=null,qt(this),Gt(this),P(19))},e.bb=function(e){e?(this.j.info("Successfully pinged google.com"),P(2)):(this.j.info("Failed to ping google.com"),P(1))},e.isActive=function(){return!!this.l&&this.l.isActive(this)},(e=rr.prototype).ra=function(){},e.qa=function(){},e.pa=function(){},e.oa=function(){},e.isActive=function(){return!0},e.Ka=function(){},nr.prototype.g=function(e,t){return new k(e,t)},t(k,a),k.prototype.m=function(){this.g.l=this.j,this.A&&(this.g.L=!0),this.g.connect(this.l,this.h||void 0)},k.prototype.close=function(){Vt(this.g)},k.prototype.o=function(e){var t,r=this.g;"string"==typeof e?((t={}).__data__=e,e=t):this.v&&((t={}).__data__=Ie(e),e=t),r.i.push(new Ye(r.Ya++,e)),3==r.I&&jt(r)},k.prototype.N=function(){this.g.l=null,delete this.j,Vt(this.g),delete this.g,k.Z.N.call(this)},t(ir,Ae),t(sr,Ne),t(A,rr),A.prototype.ra=function(){h(this.g,"a")},A.prototype.qa=function(e){h(this.g,new ir(e))},A.prototype.pa=function(e){h(this.g,new sr)},A.prototype.oa=function(){h(this.g,"b")},nr.prototype.createWebChannel=nr.prototype.g,k.prototype.send=k.prototype.o,k.prototype.open=k.prototype.m,Tm=function(){return new nr},Im=Pe,bm=u,wm={jb:0,mb:1,nb:2,Hb:3,Mb:4,Jb:5,Kb:6,Ib:7,Gb:8,Lb:9,PROXY:10,NOPROXY:11,Eb:12,Ab:13,Bb:14,zb:15,Cb:16,Db:17,fb:18,eb:19,gb:20},Le.NO_ERROR=0,Le.TIMEOUT=8,Le.HTTP_ERROR=6,ym=Le,Fe.COMPLETE="complete",_m=Fe,(Se.EventType=ke).OPEN="a",ke.CLOSE="b",ke.ERROR="c",ke.MESSAGE="d",a.prototype.listen=a.prototype.J,vm=Se,C.prototype.listenOnce=C.prototype.K,C.prototype.getLastError=C.prototype.Ha,C.prototype.getLastErrorCode=C.prototype.ya,C.prototype.getStatus=C.prototype.ca,C.prototype.getResponseJson=C.prototype.La,C.prototype.getResponseText=C.prototype.la,C.prototype.send=C.prototype.ea,C.prototype.setWithCredentials=C.prototype.Fa,mm=C}).apply(void 0!==Sm?Sm:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});class km{constructor(e){this.uid=e}isAuthenticated(){return null!=this.uid}toKey(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"}isEqual(e){return e.uid===this.uid}}km.UNAUTHENTICATED=new km(null),km.GOOGLE_CREDENTIALS=new km("google-credentials-uid"),km.FIRST_PARTY=new km("first-party-uid"),km.MOCK_USER=new km("mock-user");let Am="12.12.0";let Nm=new Xe("@firebase/firestore");function Rm(){return Nm.logLevel}function E(e,...t){var r;Nm.logLevel<=p.DEBUG&&(r=t.map(xm),Nm.debug(`Firestore (${Am}): `+e,...r))}function Pm(e,...t){var r;Nm.logLevel<=p.ERROR&&(r=t.map(xm),Nm.error(`Firestore (${Am}): `+e,...r))}function Dm(e,...t){var r;Nm.logLevel<=p.WARN&&(r=t.map(xm),Nm.warn(`Firestore (${Am}): `+e,...r))}function xm(t){if("string"==typeof t)return t;try{return JSON.stringify(t)}catch(e){return t}}function C(e,t,r){let n="Unexpected state";"string"==typeof t?n=t:r=t,Om(e,n,r)}function Om(e,t,r){let n=`FIRESTORE (${Am}) INTERNAL ASSERTION FAILED: ${t} (ID: ${e.toString(16)})`;if(void 0!==r)try{n+=" CONTEXT: "+JSON.stringify(r)}catch(e){n+=" CONTEXT: "+r}throw Pm(n),new Error(n)}function S(e,t,r,n){let i="Unexpected state";"string"==typeof r?i=r:n=r,e||Om(t,i,n)}let k={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class A extends fe{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: `+this.message}}class Mm{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class Lm{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization","Bearer "+e)}}class Fm{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(km.UNAUTHENTICATED))}shutdown(){}}class Um{constructor(e){this.token=e,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(e,t){this.changeListener=t,e.enqueueRetryable(()=>t(this.token.user))}shutdown(){this.changeListener=null}}class Vm{constructor(e){this.t=e,this.currentUser=km.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(t,r){S(void 0===this.o,42304);let n=this.i,i=e=>this.i!==n?(n=this.i,r(e)):Promise.resolve(),s=new Mm,a=(this.o=()=>{this.i++,this.currentUser=this.u(),s.resolve(),s=new Mm,t.enqueueRetryable(()=>i(this.currentUser))},()=>{let e=s;t.enqueueRetryable(async()=>{await e.promise,await i(this.currentUser)})}),o=e=>{E("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.o&&(this.auth.addAuthTokenListener(this.o),a())};this.t.onInit(e=>o(e)),setTimeout(()=>{var e;this.auth||((e=this.t.getImmediate({optional:!0}))?o(e):(E("FirebaseAuthCredentialsProvider","Auth not yet detected"),s.resolve(),s=new Mm))},0),a()}getToken(){let t=this.i,e=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(e).then(e=>this.i!==t?(E("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):e?(S("string"==typeof e.accessToken,31837,{l:e}),new Lm(e.accessToken,this.currentUser)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.o&&this.auth.removeAuthTokenListener(this.o),this.o=void 0}u(){var e=this.auth&&this.auth.getUid();return S(null===e||"string"==typeof e,2055,{h:e}),new km(e)}}class qm{constructor(e,t,r){this.P=e,this.T=t,this.I=r,this.type="FirstParty",this.user=km.FIRST_PARTY,this.R=new Map}A(){return this.I?this.I():null}get headers(){this.R.set("X-Goog-AuthUser",this.P);var e=this.A();return e&&this.R.set("Authorization",e),this.T&&this.R.set("X-Goog-Iam-Authorization-Token",this.T),this.R}}class Bm{constructor(e,t,r){this.P=e,this.T=t,this.I=r}getToken(){return Promise.resolve(new qm(this.P,this.T,this.I))}start(e,t){e.enqueueRetryable(()=>t(km.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class jm{constructor(e){this.value=e,this.type="AppCheck",this.headers=new Map,e&&0<e.length&&this.headers.set("x-firebase-appcheck",this.value)}}class zm{constructor(e,t){this.V=t,this.forceRefresh=!1,this.appCheck=null,this.m=null,this.p=null,h(e)&&e.settings.appCheckToken&&(this.p=e.settings.appCheckToken)}start(t,r){S(void 0===this.o,3512);let n=e=>{null!=e.error&&E("FirebaseAppCheckTokenProvider","Error getting App Check token; using placeholder token instead. Error: "+e.error.message);var t=e.token!==this.m;return this.m=e.token,E("FirebaseAppCheckTokenProvider",`Received ${t?"new":"existing"} token.`),t?r(e.token):Promise.resolve()},i=(this.o=e=>{t.enqueueRetryable(()=>n(e))},e=>{E("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.o&&this.appCheck.addTokenListener(this.o)});this.V.onInit(e=>i(e)),setTimeout(()=>{var e;this.appCheck||((e=this.V.getImmediate({optional:!0}))?i(e):E("FirebaseAppCheckTokenProvider","AppCheck not yet detected"))},0)}getToken(){var e;return this.p?Promise.resolve(new jm(this.p)):(e=this.forceRefresh,this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>e?(S("string"==typeof e.token,44558,{tokenResult:e}),this.m=e.token,new jm(e.token)):null):Promise.resolve(null))}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.o&&this.appCheck.removeTokenListener(this.o),this.o=void 0}}class Km{static newId(){var t=62*Math.floor(256/62);let r="";for(;r.length<20;){var n=(t=>{var r="undefined"!=typeof self&&(self.crypto||self.msCrypto),n=new Uint8Array(t);if(r&&"function"==typeof r.getRandomValues)r.getRandomValues(n);else for(let e=0;e<t;e++)n[e]=Math.floor(256*Math.random());return n})(40);for(let e=0;e<n.length;++e)r.length<20&&n[e]<t&&(r+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(n[e]%62))}return r}}function N(e,t){return e<t?-1:t<e?1:0}function Wm(r,n){let e=Math.min(r.length,n.length);for(let i=0;i<e;i++){let e=r.charAt(i),t=n.charAt(i);if(e!==t)return $m(e)===$m(t)?N(e,t):$m(e)?1:-1}return N(r.length,n.length)}let Hm=55296,Gm=57343;function $m(e){var t=e.charCodeAt(0);return t>=Hm&&t<=Gm}function Qm(e,r,n){return e.length===r.length&&e.every((e,t)=>n(e,r[t]))}function Ym(e){return e+"\0"}let Jm="__name__";class Xm{constructor(e,t,r){void 0===t?t=0:t>e.length&&C(637,{offset:t,range:e.length}),void 0===r?r=e.length-t:r>e.length-t&&C(1746,{length:r,range:e.length-t}),this.segments=e,this.offset=t,this.len=r}get length(){return this.len}isEqual(e){return 0===Xm.comparator(this,e)}child(e){let t=this.segments.slice(this.offset,this.limit());return e instanceof Xm?e.forEach(e=>{t.push(e)}):t.push(e),this.construct(t)}limit(){return this.offset+this.length}popFirst(e){return this.construct(this.segments,this.offset+(e=void 0===e?1:e),this.length-e)}popLast(){return this.construct(this.segments,this.offset,this.length-1)}firstSegment(){return this.segments[this.offset]}lastSegment(){return this.get(this.length-1)}get(e){return this.segments[this.offset+e]}isEmpty(){return 0===this.length}isPrefixOf(e){if(e.length<this.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}isImmediateParentOf(e){if(this.length+1!==e.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}forEach(e){for(let t=this.offset,r=this.limit();t<r;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(t,r){let e=Math.min(t.length,r.length);for(let n=0;n<e;n++){let e=Xm.compareSegments(t.get(n),r.get(n));if(0!==e)return e}return N(t.length,r.length)}static compareSegments(e,t){var r=Xm.isNumericId(e),n=Xm.isNumericId(t);return r&&!n?-1:!r&&n?1:r&&n?Xm.extractNumericId(e).compare(Xm.extractNumericId(t)):Wm(e,t)}static isNumericId(e){return e.startsWith("__id")&&e.endsWith("__")}static extractNumericId(e){return fm.fromString(e.substring(4,e.length-2))}}class R extends Xm{construct(e,t,r){return new R(e,t,r)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}toUriEncodedString(){return this.toArray().map(encodeURIComponent).join("/")}static fromString(...e){var t,r=[];for(t of e){if(0<=t.indexOf("//"))throw new A(k.INVALID_ARGUMENT,`Invalid segment (${t}). Paths must not contain // in them.`);r.push(...t.split("/").filter(e=>0<e.length))}return new R(r)}static emptyPath(){return new R([])}}let Zm=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class ev extends Xm{construct(e,t,r){return new ev(e,t,r)}static isValidIdentifier(e){return Zm.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),e=ev.isValidIdentifier(e)?e:"`"+e+"`")).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&this.get(0)===Jm}static keyField(){return new ev([Jm])}static fromServerFormat(t){let e=[],r="",n=0;var i=()=>{if(0===r.length)throw new A(k.INVALID_ARGUMENT,`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);e.push(r),r=""};let s=!1;for(;n<t.length;){let e=t[n];if("\\"===e){if(n+1===t.length)throw new A(k.INVALID_ARGUMENT,"Path has trailing escape character: "+t);let e=t[n+1];if("\\"!==e&&"."!==e&&"`"!==e)throw new A(k.INVALID_ARGUMENT,"Path has invalid escape sequence: "+t);r+=e,n+=2}else"`"===e?s=!s:"."!==e||s?r+=e:i(),n++}if(i(),s)throw new A(k.INVALID_ARGUMENT,"Unterminated ` in path: "+t);return new ev(e)}static emptyPath(){return new ev([])}}class P{constructor(e){this.path=e}static fromPath(e){return new P(R.fromString(e))}static fromName(e){return new P(R.fromString(e).popFirst(5))}static empty(){return new P(R.emptyPath())}get collectionGroup(){return this.path.popLast().lastSegment()}hasCollectionId(e){return 2<=this.path.length&&this.path.get(this.path.length-2)===e}getCollectionGroup(){return this.path.get(this.path.length-2)}getCollectionPath(){return this.path.popLast()}isEqual(e){return null!==e&&0===R.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return R.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new P(new R(e.slice()))}}function tv(e,t,r){if(!r)throw new A(k.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function rv(e,t,r,n){if(!0===t&&!0===n)throw new A(k.INVALID_ARGUMENT,e+` and ${r} cannot be used together.`)}function nv(e){if(!P.isDocumentKey(e))throw new A(k.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function iv(e){if(P.isDocumentKey(e))throw new A(k.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function sv(e){return"object"==typeof e&&null!==e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}function av(e){var t,r;return void 0===e?"undefined":null===e?"null":"string"==typeof e?(20<e.length&&(e=e.substring(0,20)+"..."),JSON.stringify(e)):"number"==typeof e||"boolean"==typeof e?""+e:"object"==typeof e?e instanceof Array?"an array":(t=(r=e).constructor?r.constructor.name:null)?`a custom ${t} object`:"an object":"function"==typeof e?"a function":C(12329,{type:typeof e})}function D(e,t){if((e="_delegate"in e?e._delegate:e)instanceof t)return e;if(t.name===e.constructor.name)throw new A(k.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");var r=av(e);throw new A(k.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: `+r)}function ov(e,t){if(t<=0)throw new A(k.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}function lv(e,t){var r={typeString:e};return t&&(r.value=t),r}function hv(e,t){if(!sv(e))throw new A(k.INVALID_ARGUMENT,"JSON must be an object");let r;for(var n in t)if(t[n]){var i=t[n].typeString,s="value"in t[n]?{value:t[n].value}:void 0;if(!(n in e)){r=`JSON missing required field: '${n}'`;break}var a=e[n];if(i&&typeof a!==i){r=`JSON field '${n}' must be a ${i}.`;break}if(void 0!==s&&a!==s.value){r=`Expected '${n}' field to equal '${s.value}'`;break}}if(r)throw new A(k.INVALID_ARGUMENT,r);return 1}let cv=-62135596800;class x{static now(){return x.fromMillis(Date.now())}static fromDate(e){return x.fromMillis(e.getTime())}static fromMillis(e){var t=Math.floor(e/1e3),r=Math.floor(1e6*(e-1e3*t));return new x(t,r)}constructor(e,t){if(this.seconds=e,(this.nanoseconds=t)<0)throw new A(k.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(1e9<=t)throw new A(k.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<cv)throw new A(k.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(253402300800<=e)throw new A(k.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?N(this.nanoseconds,e.nanoseconds):N(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{type:x._jsonSchemaVersion,seconds:this.seconds,nanoseconds:this.nanoseconds}}static fromJSON(e){if(hv(e,x._jsonSchema))return new x(e.seconds,e.nanoseconds)}valueOf(){var e=this.seconds-cv;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}x._jsonSchemaVersion="firestore/timestamp/1.0",x._jsonSchema={type:lv("string",x._jsonSchemaVersion),seconds:lv("number"),nanoseconds:lv("number")};class O{static fromTimestamp(e){return new O(e)}static min(){return new O(new x(0,0))}static max(){return new O(new x(253402300799,999999999))}constructor(e){this.timestamp=e}compareTo(e){return this.timestamp._compareTo(e.timestamp)}isEqual(e){return this.timestamp.isEqual(e.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}}let uv=-1;class dv{constructor(e,t,r,n){this.indexId=e,this.collectionGroup=t,this.fields=r,this.indexState=n}}function pv(e){return e.fields.find(e=>2===e.kind)}function fv(e){return e.fields.filter(e=>2!==e.kind)}dv.UNKNOWN_ID=-1;class gv{constructor(e,t){this.fieldPath=e,this.kind=t}}class mv{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new mv(0,yv.min())}}function vv(e,t){var r=e.toTimestamp().seconds,n=e.toTimestamp().nanoseconds+1,r=O.fromTimestamp(1e9===n?new x(r+1,0):new x(r,n));return new yv(r,P.empty(),t)}function _v(e){return new yv(e.readTime,e.key,uv)}class yv{constructor(e,t,r){this.readTime=e,this.documentKey=t,this.largestBatchId=r}static min(){return new yv(O.min(),P.empty(),uv)}static max(){return new yv(O.max(),P.empty(),uv)}}function wv(e,t){var r=e.readTime.compareTo(t.readTime);return 0!==r||0!==(r=P.comparator(e.documentKey,t.documentKey))?r:N(e.largestBatchId,t.largestBatchId)}let bv="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class Iv{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}async function Tv(e){if(e.code!==k.FAILED_PRECONDITION||e.message!==bv)throw e;E("LocalStore","Unexpectedly lost primary lease")}class M{constructor(e){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,e(e=>{this.isDone=!0,this.result=e,this.nextCallback&&this.nextCallback(e)},e=>{this.isDone=!0,this.error=e,this.catchCallback&&this.catchCallback(e)})}catch(e){return this.next(void 0,e)}next(n,i){return this.callbackAttached&&C(59440),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(i,this.error):this.wrapSuccess(n,this.result):new M((t,r)=>{this.nextCallback=e=>{this.wrapSuccess(n,e).next(t,r)},this.catchCallback=e=>{this.wrapFailure(i,e).next(t,r)}})}toPromise(){return new Promise((e,t)=>{this.next(e,t)})}wrapUserFunction(e){try{var t=e();return t instanceof M?t:M.resolve(t)}catch(e){return M.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):M.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):M.reject(t)}static resolve(r){return new M((e,t)=>{e(r)})}static reject(r){return new M((e,t)=>{t(r)})}static waitFor(e){return new M((t,r)=>{let n=0,i=0,s=!1;e.forEach(e=>{++n,e.next(()=>{++i,s&&i===n&&t()},e=>r(e))}),s=!0,i===n&&t()})}static or(e){let t=M.resolve(!1);for(let r of e)t=t.next(e=>e?M.resolve(e):r());return t}static forEach(e,r){let n=[];return e.forEach((e,t)=>{n.push(r.call(this,e,t))}),this.waitFor(n)}static mapArray(o,l){return new M((r,n)=>{let i=o.length,s=new Array(i),a=0;for(let e=0;e<i;e++){let t=e;l(o[t]).next(e=>{s[t]=e,++a===i&&r(s)},e=>n(e))}})}static doWhile(n,i){return new M((e,t)=>{let r=()=>{!0===n()?i().next(()=>{r()},t):e()};r()})}}let Ev="SimpleDb";class Cv{static open(e,t,r,n){try{return new Cv(t,e.transaction(n,r))}catch(e){throw new Nv(t,e)}}constructor(r,e){this.action=r,this.transaction=e,this.aborted=!1,this.S=new Mm,this.transaction.oncomplete=()=>{this.S.resolve()},this.transaction.onabort=()=>{e.error?this.S.reject(new Nv(r,e.error)):this.S.resolve()},this.transaction.onerror=e=>{var t=Ov(e.target.error);this.S.reject(new Nv(r,t))}}get D(){return this.S.promise}abort(e){e&&this.S.reject(e),this.aborted||(E(Ev,"Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}C(){var e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}store(e){var t=this.transaction.objectStore(e);return new Pv(t)}}class Sv{static delete(e){return E(Ev,"Removing database:",e),Dv(H().indexedDB.deleteDatabase(e)).toPromise()}static v(){var e,t,r;return!(!ue()||!Sv.F()&&(e=te(),t=0<(t=Sv.M(e))&&t<10,r=0<(r=kv(e))&&r<4.5,0<e.indexOf("MSIE ")||0<e.indexOf("Trident/")||0<e.indexOf("Edge/")||t||r))}static F(){return"undefined"!=typeof process&&"YES"===process.__PRIVATE_env?.__PRIVATE_USE_MOCK_PERSISTENCE}static O(e,t){return e.store(t)}static M(e){var t=e.match(/i(?:phone|pad|pod) os ([\d_]+)/i),t=t?t[1].split("_").slice(0,2).join("."):"-1";return Number(t)}constructor(e,t,r){this.name=e,this.version=t,this.N=r,this.B=null,12.2===Sv.M(te())&&Pm("Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.")}async L(s){return this.db||(E(Ev,"Opening database:",this.name),this.db=await new Promise((r,n)=>{let i=indexedDB.open(this.name,this.version);i.onsuccess=e=>{var t=e.target.result;r(t)},i.onblocked=()=>{n(new Nv(s,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},i.onerror=e=>{var t=e.target.error;"VersionError"===t.name?n(new A(k.FAILED_PRECONDITION,"A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")):"InvalidStateError"===t.name?n(new A(k.FAILED_PRECONDITION,"Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: "+t)):n(new Nv(s,t))},i.onupgradeneeded=e=>{E(Ev,'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);var t=e.target.result;this.N.k(t,i.transaction,e.oldVersion,this.version).next(()=>{E(Ev,"Database upgrade to version "+this.version+" complete")})}})),this.q&&(this.db.onversionchange=e=>this.q(e)),this.db}K(t){this.q=t,this.db&&(this.db.onversionchange=e=>t(e))}async runTransaction(r,e,n,i){var s="readonly"===e;let a=0;for(;;){++a;try{this.db=await this.L(r);let t=Cv.open(this.db,r,s?"readonly":"readwrite",n),e=i(t).next(e=>(t.C(),e)).catch(e=>(t.abort(e),M.reject(e))).toPromise();return e.catch(()=>{}),await t.D,e}catch(r){let e=r,t="FirebaseError"!==e.name&&a<3;if(E(Ev,"Transaction failed with error:",e.message,"Retrying:",t),this.close(),!t)return Promise.reject(e)}}}close(){this.db&&this.db.close(),this.db=void 0}}function kv(e){var t=e.match(/Android ([\d.]+)/i),t=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(t)}class Av{constructor(e){this.U=e,this.$=!1,this.W=null}get isDone(){return this.$}get G(){return this.W}set cursor(e){this.U=e}done(){this.$=!0}j(e){this.W=e}delete(){return Dv(this.U.delete())}}class Nv extends A{constructor(e,t){super(k.UNAVAILABLE,`IndexedDB transaction '${e}' failed: `+t),this.name="IndexedDbTransactionError"}}function Rv(e){return"IndexedDbTransactionError"===e.name}class Pv{constructor(e){this.store=e}put(e,t){let r;return Dv(r=void 0!==t?(E(Ev,"PUT",this.store.name,e,t),this.store.put(t,e)):(E(Ev,"PUT",this.store.name,"<auto-key>",e),this.store.put(e)))}add(e){return E(Ev,"ADD",this.store.name,e,e),Dv(this.store.add(e))}get(t){return Dv(this.store.get(t)).next(e=>(void 0===e&&(e=null),E(Ev,"GET",this.store.name,t,e),e))}delete(e){return E(Ev,"DELETE",this.store.name,e),Dv(this.store.delete(e))}count(){return E(Ev,"COUNT",this.store.name),Dv(this.store.count())}J(e,t){var n=this.options(e,t),r=n.index?this.store.index(n.index):this.store;if("function"==typeof r.getAll){let e=r.getAll(n.range);return new M((t,r)=>{e.onerror=e=>{r(e.target.error)},e.onsuccess=e=>{t(e.target.result)}})}{let e=this.cursor(n),r=[];return this.H(e,(e,t)=>{r.push(t)}).next(()=>r)}}Z(e,t){let n=this.store.getAll(e,null===t?void 0:t);return new M((t,r)=>{n.onerror=e=>{r(e.target.error)},n.onsuccess=e=>{t(e.target.result)}})}X(e,t){E(Ev,"DELETE ALL",this.store.name);var r=this.options(e,t),r=(r.Y=!1,this.cursor(r));return this.H(r,(e,t,r)=>r.delete())}ee(e,t){let r;t?r=e:(r={},t=e);var n=this.cursor(r);return this.H(n,t)}te(i){let e=this.cursor({});return new M((r,n)=>{e.onerror=e=>{var t=Ov(e.target.error);n(t)},e.onsuccess=e=>{let t=e.target.result;t?i(t.primaryKey,t.value).next(e=>{e?t.continue():r()}):r()}})}H(e,s){let a=[];return new M((i,t)=>{e.onerror=e=>{t(e.target.error)},e.onsuccess=e=>{var n=e.target.result;if(n){let t=new Av(n),r=s(n.primaryKey,n.value,t);if(r instanceof M){let e=r.catch(e=>(t.done(),M.reject(e)));a.push(e)}t.isDone?i():null===t.G?n.continue():n.continue(t.G)}else i()}}).next(()=>M.waitFor(a))}options(e,t){let r;return void 0!==e&&("string"==typeof e?r=e:t=e),{index:r,range:t}}cursor(e){let t="next";var r;return e.reverse&&(t="prev"),e.index?(r=this.store.index(e.index),e.Y?r.openKeyCursor(e.range,t):r.openCursor(e.range,t)):this.store.openCursor(e.range,t)}}function Dv(e){return new M((r,n)=>{e.onsuccess=e=>{var t=e.target.result;r(t)},e.onerror=e=>{var t=Ov(e.target.error);n(t)}})}let xv=!1;function Ov(e){let t=Sv.M(te());if(12.2<=t&&t<13){let t="An internal error was encountered in the Indexed Database server";if(0<=e.message.indexOf(t)){let e=new A("internal",`IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${t}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);return xv||(xv=!0,setTimeout(()=>{throw e},0)),e}}return e}let Mv="IndexBackfiller";class Lv{constructor(e,t){this.asyncQueue=e,this.ne=t,this.task=null}start(){this.re(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return null!==this.task}re(e){E(Mv,`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,async()=>{this.task=null;try{var e=await this.ne.ie();E(Mv,"Documents written: "+e)}catch(e){Rv(e)?E(Mv,"Ignoring IndexedDB error during index backfill: ",e):await Tv(e)}await this.re(6e4)})}}class Fv{constructor(e,t){this.localStore=e,this.persistence=t}async ie(t=50){return this.persistence.runTransaction("Backfill Indexes","readwrite-primary",e=>this.se(e,t))}se(e,t){let r=new Set,n=t,i=!0;return M.doWhile(()=>!0===i&&0<n,()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next(t=>{if(null!==t&&!r.has(t))return E(Mv,"Processing collection: "+t),this.oe(e,t,n).next(e=>{n-=e,r.add(t)});i=!1})).next(()=>t-n)}oe(n,i,e){return this.localStore.indexManager.getMinOffsetFromCollectionGroup(n,i).next(r=>this.localStore.localDocuments.getNextDocuments(n,i,r,e).next(e=>{let t=e.changes;return this.localStore.indexManager.updateIndexEntries(n,t).next(()=>this._e(r,e)).next(e=>(E(Mv,"Updating offset: "+e),this.localStore.indexManager.updateCollectionGroup(n,i,e))).next(()=>t.size)}))}_e(e,t){let n=e;return t.changes.forEach((e,t)=>{var r=_v(t);0<wv(r,n)&&(n=r)}),new yv(n.readTime,n.documentKey,Math.max(t.batchId,e.largestBatchId))}}class Uv{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.ae(e),this.ue=e=>t.writeSequenceNumber(e))}ae(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){var e=++this.previousValue;return this.ue&&this.ue(e),e}}let Vv=Uv.ce=-1;function qv(e){return null==e}function Bv(e){return 0===e&&1/e==-1/0}function jv(e){return"number"==typeof e&&Number.isInteger(e)&&!Bv(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}let zv="";function Kv(e){let t="";for(let r=0;r<e.length;r++)0<t.length&&(t=Wv(t)),t=((t,e)=>{let r=e,n=t.length;for(let i=0;i<n;i++){let e=t.charAt(i);switch(e){case"\0":r+="";break;case zv:r+="";break;default:r+=e}}return r})(e.get(r),t);return Wv(t)}function Wv(e){return e+zv+""}function Hv(r){let e=r.length;if(S(2<=e,64408,{path:r}),2===e)return S(r.charAt(0)===zv&&""===r.charAt(1),56145,{path:r}),R.emptyPath();var __PRIVATE_lastReasonableEscapeIndex=e-2,n=[];let i="";for(let a=0;a<e;){let t=r.indexOf(zv,a);switch((t<0||t>__PRIVATE_lastReasonableEscapeIndex)&&C(50515,{path:r}),r.charAt(t+1)){case"":var s=r.substring(a,t);let e;0===i.length?e=s:(i+=s,e=i,i=""),n.push(e);break;case"":i=i+r.substring(a,t)+"\0";break;case"":i+=r.substring(a,t+1);break;default:C(61167,{path:r})}a=t+2}return new R(n)}let Gv="remoteDocuments",$v="owner",Qv="owner",Yv="mutationQueues",Jv="mutations",Xv="batchId",Zv="userMutationsIndex",e_=["userId","batchId"];function t_(e,t){return[e,Kv(t)]}function r_(e,t,r){return[e,Kv(t),r]}let n_={},i_="documentMutations",s_="remoteDocumentsV14",a_=["prefixPath","collectionGroup","readTime","documentId"],o_="documentKeyIndex",l_=["prefixPath","collectionGroup","documentId"],h_="collectionGroupIndex",c_=["collectionGroup","readTime","prefixPath","documentId"],u_="remoteDocumentGlobal",d_="remoteDocumentGlobalKey",p_="targets",f_="queryTargetsIndex",g_=["canonicalId","targetId"],m_="targetDocuments",v_=["targetId","path"],__="documentTargetsIndex",y_=["path","targetId"],w_="targetGlobalKey",b_="targetGlobal",I_="collectionParents",T_=["collectionId","parent"],E_="clientMetadata",C_="bundles",S_="namedQueries",k_="indexConfiguration",A_="collectionGroupIndex",N_="indexState",R_=["indexId","uid"],P_="sequenceNumberIndex",D_=["uid","sequenceNumber"],x_="indexEntries",O_=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],M_="documentKeyIndex",L_=["indexId","uid","orderedDocumentKey"],F_="documentOverlays",U_=["userId","collectionPath","documentId"],V_="collectionPathOverlayIndex",q_=["userId","collectionPath","largestBatchId"],B_="collectionGroupOverlayIndex",j_=["userId","collectionGroup","largestBatchId"],z_="globals",K_=[Yv,Jv,i_,Gv,p_,$v,b_,m_,E_,u_,I_,C_,S_],W_=[...K_,F_],H_=[Yv,Jv,i_,s_,p_,$v,b_,m_,E_,u_,I_,C_,S_,F_],G_=H_,$_=[...G_,k_,N_,x_],Q_=$_,Y_=[...$_,z_],J_=Y_;class X_ extends Iv{constructor(e,t){super(),this.le=e,this.currentSequenceNumber=t}}function Z_(e,t){var r=e;return Sv.O(r.le,t)}function ey(e){let t=0;for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}function ty(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t(r,e[r])}function ry(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class ny{constructor(e,t){this.comparator=e,this.root=t||sy.EMPTY}insert(e,t){return new ny(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,sy.BLACK,null,null))}remove(e){return new ny(this.comparator,this.root.remove(e,this.comparator).copy(null,null,sy.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){var r=this.comparator(e,t.key);if(0===r)return t.value;r<0?t=t.left:0<r&&(t=t.right)}return null}indexOf(e){let t=0,r=this.root;for(;!r.isEmpty();){var n=this.comparator(e,r.key);if(0===n)return t+r.left.size;r=n<0?r.left:(t+=r.left.size+1,r.right)}return-1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(e){return this.root.inorderTraversal(e)}forEach(r){this.inorderTraversal((e,t)=>(r(e,t),!1))}toString(){let r=[];return this.inorderTraversal((e,t)=>(r.push(e+":"+t),!1)),`{${r.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new iy(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new iy(this.root,e,this.comparator,!1)}getReverseIterator(){return new iy(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new iy(this.root,e,this.comparator,!0)}}class iy{constructor(e,t,r,n){this.isReverse=n,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?r(e.key,t):1,t&&n&&(i*=-1),i<0)e=this.isReverse?e.left:e.right;else{if(0===i){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop();var t={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t}hasNext(){return 0<this.nodeStack.length}peek(){var e;return 0===this.nodeStack.length?null:{key:(e=this.nodeStack[this.nodeStack.length-1]).key,value:e.value}}}class sy{constructor(e,t,r,n,i){this.key=e,this.value=t,this.color=null!=r?r:sy.RED,this.left=null!=n?n:sy.EMPTY,this.right=null!=i?i:sy.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,r,n,i){return new sy(null!=e?e:this.key,null!=t?t:this.value,null!=r?r:this.color,null!=n?n:this.left,null!=i?i:this.right)}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,r){var n=this,i=r(e,n.key);return(n=i<0?n.copy(null,null,null,n.left.insert(e,t,r),null):0===i?n.copy(null,t,null,null,null):n.copy(null,null,null,null,n.right.insert(e,t,r))).fixUp()}removeMin(){if(this.left.isEmpty())return sy.EMPTY;let e=this;return(e=(e=e.left.isRed()||e.left.left.isRed()?e:e.moveRedLeft()).copy(null,null,null,e.left.removeMin(),null)).fixUp()}remove(e,t){let r,n=this;if(t(e,n.key)<0)n=(n=n.left.isEmpty()||n.left.isRed()||n.left.left.isRed()?n:n.moveRedLeft()).copy(null,null,null,n.left.remove(e,t),null);else{if(0===t(e,(n=(n=n.left.isRed()?n.rotateRight():n).right.isEmpty()||n.right.isRed()||n.right.left.isRed()?n:n.moveRedRight()).key)){if(n.right.isEmpty())return sy.EMPTY;r=n.right.min(),n=n.copy(r.key,r.value,null,null,n.right.removeMin())}n=n.copy(null,null,null,null,n.right.remove(e,t))}return n.fixUp()}isRed(){return this.color}fixUp(){let e=this;return e=(e=(e=e.right.isRed()&&!e.left.isRed()?e.rotateLeft():e).left.isRed()&&e.left.left.isRed()?e.rotateRight():e).left.isRed()&&e.right.isRed()?e.colorFlip():e}moveRedLeft(){let e=this.colorFlip();return e=e.right.left.isRed()?(e=(e=e.copy(null,null,null,null,e.right.rotateRight())).rotateLeft()).colorFlip():e}moveRedRight(){let e=this.colorFlip();return e=e.left.left.isRed()?(e=e.rotateRight()).colorFlip():e}rotateLeft(){var e=this.copy(null,null,sy.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){var e=this.copy(null,null,sy.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){var e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth(){var e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw C(43730,{key:this.key,value:this.value});if(this.right.isRed())throw C(14113,{key:this.key,value:this.value});var e=this.left.check();if(e!==this.right.check())throw C(27949);return e+(this.isRed()?0:1)}}sy.EMPTY=null,sy.RED=!0,sy.BLACK=!1,sy.EMPTY=new class{constructor(){this.size=0}get key(){throw C(57766)}get value(){throw C(16141)}get color(){throw C(16727)}get left(){throw C(29726)}get right(){throw C(36894)}copy(e,t,r,n,i){return this}insert(e,t,r){return new sy(e,t)}remove(e,t){return this}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}isRed(){return!1}checkMaxDepth(){return!0}check(){return 0}};class L{constructor(e){this.comparator=e,this.data=new ny(this.comparator)}has(e){return null!==this.data.get(e)}first(){return this.data.minKey()}last(){return this.data.maxKey()}get size(){return this.data.size}indexOf(e){return this.data.indexOf(e)}forEach(r){this.data.inorderTraversal((e,t)=>(r(e),!1))}forEachInRange(e,t){for(var r=this.data.getIteratorFrom(e[0]);r.hasNext();){var n=r.getNext();if(0<=this.comparator(n.key,e[1]))return;t(n.key)}}forEachWhile(e,t){for(var r=void 0!==t?this.data.getIteratorFrom(t):this.data.getIterator();r.hasNext();)if(!e(r.getNext().key))return}firstAfterOrEqual(e){var t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new ay(this.data.getIterator())}getIteratorFrom(e){return new ay(this.data.getIteratorFrom(e))}add(e){return this.copy(this.data.remove(e).insert(e,!0))}delete(e){return this.has(e)?this.copy(this.data.remove(e)):this}isEmpty(){return this.data.isEmpty()}unionWith(e){let t=this;return t.size<e.size&&(t=e,e=this),e.forEach(e=>{t=t.add(e)}),t}isEqual(e){if(!(e instanceof L))return!1;if(this.size!==e.size)return!1;for(var r=this.data.getIterator(),n=e.data.getIterator();r.hasNext();){let e=r.getNext().key,t=n.getNext().key;if(0!==this.comparator(e,t))return!1}return!0}toArray(){let t=[];return this.forEach(e=>{t.push(e)}),t}toString(){let t=[];return this.forEach(e=>t.push(e)),"SortedSet("+t.toString()+")"}copy(e){var t=new L(this.comparator);return t.data=e,t}}class ay{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function oy(e){return e.hasNext()?e.getNext():void 0}class ly{constructor(e){(this.fields=e).sort(ev.comparator)}static empty(){return new ly([])}unionWith(e){let t=new L(ev.comparator);for(let e of this.fields)t=t.add(e);for(var r of e)t=t.add(r);return new ly(t.toArray())}covers(e){for(var t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return Qm(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class hy extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class cy{constructor(e){this.binaryString=e}static fromBase64String(e){var t=(e=>{try{return atob(e)}catch(e){throw"undefined"!=typeof DOMException&&e instanceof DOMException?new hy("Invalid base64 string: "+e):e}})(e);return new cy(t)}static fromUint8Array(e){var t=(e=>{let t="";for(let r=0;r<e.length;++r)t+=String.fromCharCode(e[r]);return t})(e);return new cy(t)}[Symbol.iterator](){let e=0;return{next:()=>e<this.binaryString.length?{value:this.binaryString.charCodeAt(e++),done:!1}:{value:void 0,done:!0}}}toBase64(){return e=this.binaryString,btoa(e);var e}toUint8Array(){var e=this.binaryString,t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return N(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}cy.EMPTY_BYTE_STRING=new cy("");let uy=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function dy(t){if(S(!!t,39018),"string"!=typeof t)return{seconds:py(t.seconds),nanos:py(t.nanos)};{let e=0;var r=uy.exec(t),r=(S(!!r,46558,{timestamp:t}),r[1]&&(r=((r=r[1])+"000000000").substr(0,9),e=Number(r)),new Date(t));return{seconds:Math.floor(r.getTime()/1e3),nanos:e}}}function py(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function fy(e){return"string"==typeof e?cy.fromBase64String(e):cy.fromUint8Array(e)}let gy="server_timestamp",my="__type__",vy="__previous_value__",_y="__local_write_time__";function yy(e){return(e?.mapValue?.fields||{})[my]?.stringValue===gy}function wy(e){var t=e.mapValue.fields[vy];return yy(t)?wy(t):t}function by(e){var t=dy(e.mapValue.fields[_y].timestampValue);return new x(t.seconds,t.nanos)}class Iy{constructor(e,t,r,n,i,s,a,o,l,h,c){this.databaseId=e,this.appId=t,this.persistenceKey=r,this.host=n,this.ssl=i,this.forceLongPolling=s,this.autoDetectLongPolling=a,this.longPollingOptions=o,this.useFetchStreams=l,this.isUsingEmulator=h,this.apiKey=c}}let Ty="(default)";class Ey{constructor(e,t){this.projectId=e,this.database=t||Ty}static empty(){return new Ey("","")}get isDefaultDatabase(){return this.database===Ty}isEqual(e){return e instanceof Ey&&e.projectId===this.projectId&&e.database===this.database}}let Cy="__type__",Sy="__max__",ky={mapValue:{fields:{__type__:{stringValue:Sy}}}},Ay="__vector__",Ny="value",Ry={nullValue:"NULL_VALUE"};function Py(e){return"nullValue"in e?0:"booleanValue"in e?1:"integerValue"in e||"doubleValue"in e?2:"timestampValue"in e?3:"stringValue"in e?5:"bytesValue"in e?6:"referenceValue"in e?7:"geoPointValue"in e?8:"arrayValue"in e?9:"mapValue"in e?yy(e)?4:Hy(e)?9007199254740991:Ky(e)?10:11:C(28295,{value:e})}function Dy(t,r){if(t===r)return!0;var n,i,s,a,o,e=Py(t);if(e!==Py(r))return!1;switch(e){case 0:case 9007199254740991:return!0;case 1:return t.booleanValue===r.booleanValue;case 4:return by(t).isEqual(by(r));case 3:return s=r,"string"==typeof(i=t).timestampValue&&"string"==typeof s.timestampValue&&i.timestampValue.length===s.timestampValue.length?i.timestampValue===s.timestampValue:(a=dy(i.timestampValue),o=dy(s.timestampValue),a.seconds===o.seconds&&a.nanos===o.nanos);case 5:return t.stringValue===r.stringValue;case 6:return i=r,fy(t.bytesValue).isEqual(fy(i.bytesValue));case 7:return t.referenceValue===r.referenceValue;case 8:return s=r,py((n=t).geoPointValue.latitude)===py(s.geoPointValue.latitude)&&py(n.geoPointValue.longitude)===py(s.geoPointValue.longitude);case 2:return n=r,"integerValue"in(h=t)&&"integerValue"in n?py(h.integerValue)===py(n.integerValue):"doubleValue"in h&&"doubleValue"in n&&((a=py(h.doubleValue))===(o=py(n.doubleValue))?Bv(a)===Bv(o):isNaN(a)&&isNaN(o));case 9:return Qm(t.arrayValue.values||[],r.arrayValue.values||[],Dy);case 10:case 11:var l=t,h=r,c=l.mapValue.fields||{},u=h.mapValue.fields||{};if(ey(c)!==ey(u))return!1;for(let e in c)if(c.hasOwnProperty(e)&&(void 0===u[e]||!Dy(c[e],u[e])))return!1;return!0;default:return C(52216,{left:t})}}function xy(e,t){return void 0!==(e.values||[]).find(e=>Dy(e,t))}function Oy(e,n){if(e===n)return 0;var i,s,a,o,l,h,c,u,d=Py(e),t=Py(n);if(d!==t)return N(d,t);switch(d){case 0:case 9007199254740991:return 0;case 1:return N(e.booleanValue,n.booleanValue);case 2:return h=n,c=py((l=e).integerValue||l.doubleValue),u=py(h.integerValue||h.doubleValue),c<u?-1:u<c?1:c===u?0:isNaN(c)?isNaN(u)?0:-1:1;case 3:return My(e.timestampValue,n.timestampValue);case 4:return My(by(e),by(n));case 5:return Wm(e.stringValue,n.stringValue);case 6:return l=e.bytesValue,h=n.bytesValue,c=fy(l),u=fy(h),c.compareTo(u);case 7:var p=e.referenceValue,f=n.referenceValue,g=p.split("/"),m=f.split("/");for(let t=0;t<g.length&&t<m.length;t++){let e=N(g[t],m[t]);if(0!==e)return e}return N(g.length,m.length);case 8:return p=e.geoPointValue,f=n.geoPointValue,0!==(o=N(py(p.latitude),py(f.latitude)))?o:N(py(p.longitude),py(f.longitude));case 9:return Ly(e.arrayValue,n.arrayValue);case 10:return v=e.mapValue,i=n.mapValue,o=v.fields||{},s=i.fields||{},o=o[Ny]?.arrayValue,s=s[Ny]?.arrayValue,0!==(a=N(o?.values?.length||0,s?.values?.length||0))?a:Ly(o,s);case 11:var v=e.mapValue,_=n.mapValue;if(v===ky.mapValue&&_===ky.mapValue)return 0;if(v===ky.mapValue)return 1;if(_===ky.mapValue)return-1;var y=v.fields||{},w=Object.keys(y),b=_.fields||{},I=Object.keys(b);w.sort(),I.sort();for(let r=0;r<w.length&&r<I.length;++r){let e=Wm(w[r],I[r]);if(0!==e)return e;var T=Oy(y[w[r]],b[I[r]]);if(0!==T)return T}return N(w.length,I.length);default:throw C(23264,{he:d})}}function My(e,t){var r,n,i;return"string"==typeof e&&"string"==typeof t&&e.length===t.length?N(e,t):(r=dy(e),n=dy(t),0!==(i=N(r.seconds,n.seconds))?i:N(r.nanos,n.nanos))}function Ly(e,t){var r=e.values||[],n=t.values||[];for(let i=0;i<r.length&&i<n.length;++i){let e=Oy(r[i],n[i]);if(e)return e}return N(r.length,n.length)}function Fy(e){return function s(e){return"nullValue"in e?"null":"booleanValue"in e?""+e.booleanValue:"integerValue"in e?""+e.integerValue:"doubleValue"in e?""+e.doubleValue:"timestampValue"in e?(e=>{let t=dy(e);return`time(${t.seconds},${t.nanos})`})(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?(e=>fy(e).toBase64())(e.bytesValue):"referenceValue"in e?(e=>P.fromName(e).toString())(e.referenceValue):"geoPointValue"in e?(e=>`geo(${e.latitude},${e.longitude})`)(e.geoPointValue):"arrayValue"in e?(e=>{let t="[",r=!0;for(var n of e.values||[])r?r=!1:t+=",",t+=s(n);return t+"]"})(e.arrayValue):"mapValue"in e?(e=>{let t=Object.keys(e.fields||{}).sort(),r="{",n=!0;for(var i of t)n?n=!1:r+=",",r+=i+":"+s(e.fields[i]);return r+"}"})(e.mapValue):C(61005,{value:e})}(e)}function Uy(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/`+t.path.canonicalString()}}function Vy(e){return!!e&&"integerValue"in e}function qy(e){return!!e&&"arrayValue"in e}function By(e){return e&&"nullValue"in e}function jy(e){return e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function zy(e){return e&&"mapValue"in e}function Ky(e){return(e?.mapValue?.fields||{})[Cy]?.stringValue===Ay}function Wy(t){if(t.geoPointValue)return{geoPointValue:{...t.geoPointValue}};if(t.timestampValue&&"object"==typeof t.timestampValue)return{timestampValue:{...t.timestampValue}};if(t.mapValue){let r={mapValue:{fields:{}}};return ty(t.mapValue.fields,(e,t)=>r.mapValue.fields[e]=Wy(t)),r}if(t.arrayValue){var r={arrayValue:{values:[]}};for(let e=0;e<(t.arrayValue.values||[]).length;++e)r.arrayValue.values[e]=Wy(t.arrayValue.values[e]);return r}return{...t}}function Hy(e){return(((e.mapValue||{}).fields||{}).__type__||{}).stringValue===Sy}let Gy={mapValue:{fields:{[Cy]:{stringValue:Ay},[Ny]:{arrayValue:{}}}}};function $y(e,t){var r=Oy(e.value,t.value);return 0!==r?r:e.inclusive&&!t.inclusive?-1:!e.inclusive&&t.inclusive?1:0}function Qy(e,t){var r=Oy(e.value,t.value);return 0!==r?r:e.inclusive&&!t.inclusive?1:!e.inclusive&&t.inclusive?-1:0}class Yy{constructor(e){this.value=e}static empty(){return new Yy({mapValue:{}})}field(r){if(r.isEmpty())return this.value;{let e=this.value;for(let t=0;t<r.length-1;++t)if(!zy(e=(e.mapValue.fields||{})[r.get(t)]))return null;return(e=(e.mapValue.fields||{})[r.lastSegment()])||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=Wy(t)}setAll(e){let r=ev.emptyPath(),n={},i=[];e.forEach((e,t)=>{if(!r.isImmediateParentOf(t)){let e=this.getFieldsMap(r);this.applyChanges(e,n,i),n={},i=[],r=t.popLast()}e?n[t.lastSegment()]=Wy(e):i.push(t.lastSegment())});var t=this.getFieldsMap(r);this.applyChanges(t,n,i)}delete(e){var t=this.field(e.popLast());zy(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return Dy(this.value,e.value)}getFieldsMap(t){let r=this.value;r.mapValue.fields||(r.mapValue={fields:{}});for(let n=0;n<t.length;++n){let e=r.mapValue.fields[t.get(n)];zy(e)&&e.mapValue.fields||(e={mapValue:{fields:{}}},r.mapValue.fields[t.get(n)]=e),r=e}return r.mapValue.fields}applyChanges(r,e,t){ty(e,(e,t)=>r[e]=t);for(let e of t)delete r[e]}clone(){return new Yy(Wy(this.value))}}class Jy{constructor(e,t,r,n,i,s,a){this.key=e,this.documentType=t,this.version=r,this.readTime=n,this.createTime=i,this.data=s,this.documentState=a}static newInvalidDocument(e){return new Jy(e,0,O.min(),O.min(),O.min(),Yy.empty(),0)}static newFoundDocument(e,t,r,n){return new Jy(e,1,t,O.min(),r,n,0)}static newNoDocument(e,t){return new Jy(e,2,t,O.min(),O.min(),Yy.empty(),0)}static newUnknownDocument(e,t){return new Jy(e,3,t,O.min(),O.min(),Yy.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(O.min())||2!==this.documentType&&0!==this.documentType||(this.createTime=e),this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=Yy.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=Yy.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=O.min(),this}setReadTime(e){return this.readTime=e,this}get hasLocalMutations(){return 1===this.documentState}get hasCommittedMutations(){return 2===this.documentState}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return 0!==this.documentType}isFoundDocument(){return 1===this.documentType}isNoDocument(){return 2===this.documentType}isUnknownDocument(){return 3===this.documentType}isEqual(e){return e instanceof Jy&&this.key.isEqual(e.key)&&this.version.isEqual(e.version)&&this.documentType===e.documentType&&this.documentState===e.documentState&&this.data.isEqual(e.data)}mutableCopy(){return new Jy(this.key,this.documentType,this.version,this.readTime,this.createTime,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class Xy{constructor(e,t){this.position=e,this.inclusive=t}}function Zy(e,t,r){let n=0;for(let a=0;a<e.position.length;a++){var i=t[a],s=e.position[a];if(n=i.field.isKeyField()?P.comparator(P.fromName(s.referenceValue),r.key):Oy(s,r.data.field(i.field)),"desc"===i.dir&&(n*=-1),0!==n)break}return n}function ew(e,t){if(null===e)return null===t;if(null===t)return!1;if(e.inclusive!==t.inclusive||e.position.length!==t.position.length)return!1;for(let r=0;r<e.position.length;r++)if(!Dy(e.position[r],t.position[r]))return!1;return!0}class tw{constructor(e,t="asc"){this.field=e,this.dir=t}}class rw{}class F extends rw{constructor(e,t,r){super(),this.field=e,this.op=t,this.value=r}static create(e,t,r){return e.isKeyField()?"in"===t||"not-in"===t?this.createKeyFieldInFilter(e,t,r):new hw(e,t,r):"array-contains"===t?new pw(e,r):"in"===t?new fw(e,r):"not-in"===t?new gw(e,r):"array-contains-any"===t?new mw(e,r):new F(e,t,r)}static createKeyFieldInFilter(e,t,r){return new("in"===t?cw:uw)(e,r)}matches(e){var t=e.data.field(this.field);return"!="===this.op?null!==t&&void 0===t.nullValue&&this.matchesComparison(Oy(t,this.value)):null!==t&&Py(this.value)===Py(t)&&this.matchesComparison(Oy(t,this.value))}matchesComparison(e){switch(this.op){case"<":return e<0;case"<=":return e<=0;case"==":return 0===e;case"!=":return 0!==e;case">":return 0<e;case">=":return 0<=e;default:return C(47266,{operator:this.op})}}isInequality(){return 0<=["<","<=",">",">=","!=","not-in"].indexOf(this.op)}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class U extends rw{constructor(e,t){super(),this.filters=e,this.op=t,this.Pe=null}static create(e,t){return new U(e,t)}matches(t){return nw(this)?void 0===this.filters.find(e=>!e.matches(t)):void 0!==this.filters.find(e=>e.matches(t))}getFlattenedFilters(){return null===this.Pe&&(this.Pe=this.filters.reduce((e,t)=>e.concat(t.getFlattenedFilters()),[])),this.Pe}getFilters(){return Object.assign([],this.filters)}}function nw(e){return"and"===e.op}function iw(e){return"or"===e.op}function sw(e){return aw(e)&&nw(e)}function aw(e){for(var t of e.filters)if(t instanceof U)return!1;return!0}function ow(e,t){var r=e.filters.concat(t);return U.create(r,e.op)}function lw(e){return e instanceof F?`${(t=e).field.canonicalString()} ${t.op} `+Fy(t.value):e instanceof U?(t=e).op.toString()+" {"+t.getFilters().map(lw).join(" ,")+"}":"Filter";var t}class hw extends F{constructor(e,t,r){super(e,t,r),this.key=P.fromName(r.referenceValue)}matches(e){var t=P.comparator(e.key,this.key);return this.matchesComparison(t)}}class cw extends F{constructor(e,t){super(e,"in",t),this.keys=dw(0,t)}matches(t){return this.keys.some(e=>e.isEqual(t.key))}}class uw extends F{constructor(e,t){super(e,"not-in",t),this.keys=dw(0,t)}matches(t){return!this.keys.some(e=>e.isEqual(t.key))}}function dw(e,t){return(t.arrayValue?.values||[]).map(e=>P.fromName(e.referenceValue))}class pw extends F{constructor(e,t){super(e,"array-contains",t)}matches(e){var t=e.data.field(this.field);return qy(t)&&xy(t.arrayValue,this.value)}}class fw extends F{constructor(e,t){super(e,"in",t)}matches(e){var t=e.data.field(this.field);return null!==t&&xy(this.value.arrayValue,t)}}class gw extends F{constructor(e,t){super(e,"not-in",t)}matches(e){var t;return!xy(this.value.arrayValue,{nullValue:"NULL_VALUE"})&&null!==(t=e.data.field(this.field))&&void 0===t.nullValue&&!xy(this.value.arrayValue,t)}}class mw extends F{constructor(e,t){super(e,"array-contains-any",t)}matches(e){var t=e.data.field(this.field);return!(!qy(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>xy(this.value.arrayValue,e))}}class vw{constructor(e,t=null,r=[],n=[],i=null,s=null,a=null){this.path=e,this.collectionGroup=t,this.orderBy=r,this.filters=n,this.limit=i,this.startAt=s,this.endAt=a,this.Te=null}}function _w(e,t=null,r=[],n=[],i=null,s=null,a=null){return new vw(e,t,r,n,i,s,a)}function yw(e){var t=e;if(null===t.Te){let e=t.path.canonicalString();null!==t.collectionGroup&&(e+="|cg:"+t.collectionGroup),e=(e=(e+="|f:")+t.filters.map(e=>function t(e){var r;return e instanceof F?e.field.canonicalString()+e.op.toString()+Fy(e.value):sw(e)?e.filters.map(e=>t(e)).join(","):(r=e.filters.map(e=>t(e)).join(","),e.op+`(${r})`)}(e)).join(",")+"|ob:")+t.orderBy.map(e=>(e=e).field.canonicalString()+e.dir).join(","),qv(t.limit)||(e=(e+="|l:")+t.limit),t.startAt&&(e=(e=(e+="|lb:")+(t.startAt.inclusive?"b:":"a:"))+t.startAt.position.map(e=>Fy(e)).join(",")),t.endAt&&(e=(e=(e+="|ub:")+(t.endAt.inclusive?"a:":"b:"))+t.endAt.position.map(e=>Fy(e)).join(",")),t.Te=e}return t.Te}function ww(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let i=0;i<e.orderBy.length;i++)if(r=e.orderBy[i],n=t.orderBy[i],r.dir!==n.dir||!r.field.isEqual(n.field))return!1;var r,n;if(e.filters.length!==t.filters.length)return!1;for(let s=0;s<e.filters.length;s++)if(!function n(e,t){return e instanceof F?(r=e,(s=t)instanceof F&&r.op===s.op&&r.field.isEqual(s.field)&&Dy(r.value,s.value)):e instanceof U?(r=e,(i=t)instanceof U&&r.op===i.op&&r.filters.length===i.filters.length&&r.filters.reduce((e,t,r)=>e&&n(t,i.filters[r]),!0)):void C(19439);var i,r,s}(e.filters[s],t.filters[s]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!ew(e.startAt,t.startAt)&&ew(e.endAt,t.endAt)}function bw(e){return P.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function Iw(e,t){return e.filters.filter(e=>e instanceof F&&e.field.isEqual(t))}function Tw(e,r,n){let i=Ry,s=!0;for(let n of Iw(e,r)){let e=Ry,t=!0;switch(n.op){case"<":case"<=":e="nullValue"in(a=n.value)?Ry:"booleanValue"in a?{booleanValue:!1}:"integerValue"in a||"doubleValue"in a?{doubleValue:NaN}:"timestampValue"in a?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"stringValue"in a?{stringValue:""}:"bytesValue"in a?{bytesValue:""}:"referenceValue"in a?Uy(Ey.empty(),P.empty()):"geoPointValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in a?{arrayValue:{}}:"mapValue"in a?Ky(a)?Gy:{mapValue:{}}:C(35942,{value:a});break;case"==":case"in":case">=":e=n.value;break;case">":e=n.value,t=!1;break;case"!=":case"not-in":e=Ry}$y({value:i,inclusive:s},{value:e,inclusive:t})<0&&(i=e,s=t)}var a;if(null!==n)for(let t=0;t<e.orderBy.length;++t)if(e.orderBy[t].field.isEqual(r)){let e=n.position[t];$y({value:i,inclusive:s},{value:e,inclusive:n.inclusive})<0&&(i=e,s=n.inclusive);break}return{value:i,inclusive:s}}function Ew(e,r,n){let i=ky,s=!0;for(let n of Iw(e,r)){let e=ky,t=!0;switch(n.op){case">=":case">":e="nullValue"in(a=n.value)?{booleanValue:!1}:"booleanValue"in a?{doubleValue:NaN}:"integerValue"in a||"doubleValue"in a?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"timestampValue"in a?{stringValue:""}:"stringValue"in a?{bytesValue:""}:"bytesValue"in a?Uy(Ey.empty(),P.empty()):"referenceValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in a?{arrayValue:{}}:"arrayValue"in a?Gy:"mapValue"in a?Ky(a)?{mapValue:{}}:ky:C(61959,{value:a}),t=!1;break;case"==":case"in":case"<=":e=n.value;break;case"<":e=n.value,t=!1;break;case"!=":case"not-in":e=ky}0<Qy({value:i,inclusive:s},{value:e,inclusive:t})&&(i=e,s=t)}var a;if(null!==n)for(let t=0;t<e.orderBy.length;++t)if(e.orderBy[t].field.isEqual(r)){let e=n.position[t];0<Qy({value:i,inclusive:s},{value:e,inclusive:n.inclusive})&&(i=e,s=n.inclusive);break}return{value:i,inclusive:s}}class Cw{constructor(e,t=null,r=[],n=[],i=null,s="F",a=null,o=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=r,this.filters=n,this.limit=i,this.limitType=s,this.startAt=a,this.endAt=o,this.Ee=null,this.Ie=null,this.Re=null,this.startAt,this.endAt}}function Sw(e,t,r,n,i,s,a,o){return new Cw(e,t,r,n,i,s,a,o)}function kw(e){return new Cw(e)}function Aw(e){return 0===e.filters.length&&null===e.limit&&null==e.startAt&&null==e.endAt&&(0===e.explicitOrderBy.length||1===e.explicitOrderBy.length&&e.explicitOrderBy[0].field.isKeyField())}function Nw(e){return null!==e.collectionGroup}function Rw(e){let n=e;if(null===n.Ee){n.Ee=[];let t=new Set;for(var i of n.explicitOrderBy)n.Ee.push(i),t.add(i.field.canonicalString());let r=0<n.explicitOrderBy.length?n.explicitOrderBy[n.explicitOrderBy.length-1].dir:"asc",e=(e=>{let t=new L(ev.comparator);return e.filters.forEach(e=>{e.getFlattenedFilters().forEach(e=>{e.isInequality()&&(t=t.add(e.field))})}),t})(n);e.forEach(e=>{t.has(e.canonicalString())||e.isKeyField()||n.Ee.push(new tw(e,r))}),t.has(ev.keyField().canonicalString())||n.Ee.push(new tw(ev.keyField(),r))}return n.Ee}function Pw(e){var t=e;return t.Ie||(t.Ie=((e,t)=>{if("F"===e.limitType)return _w(e.path,e.collectionGroup,t,e.filters,e.limit,e.startAt,e.endAt);t=t.map(e=>{var t="desc"===e.dir?"asc":"desc";return new tw(e.field,t)});var r=e.endAt?new Xy(e.endAt.position,e.endAt.inclusive):null,n=e.startAt?new Xy(e.startAt.position,e.startAt.inclusive):null;return _w(e.path,e.collectionGroup,t,e.filters,e.limit,r,n)})(t,Rw(e))),t.Ie}function Dw(e,t){var r=e.filters.concat([t]);return new Cw(e.path,e.collectionGroup,e.explicitOrderBy.slice(),r,e.limit,e.limitType,e.startAt,e.endAt)}function xw(e,t,r){return new Cw(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,r,e.startAt,e.endAt)}function Ow(e,t){return ww(Pw(e),Pw(t))&&e.limitType===t.limitType}function Mw(e){return yw(Pw(e))+"|lt:"+e.limitType}function Lw(e){return`Query(target=${(e=>{let t=e.path.canonicalString();return null!==e.collectionGroup&&(t+=" collectionGroup="+e.collectionGroup),0<e.filters.length&&(t+=`, filters: [${e.filters.map(e=>lw(e)).join(", ")}]`),qv(e.limit)||(t+=", limit: "+e.limit),0<e.orderBy.length&&(t+=`, orderBy: [${e.orderBy.map(e=>`${(e=e).field.canonicalString()} (${e.dir})`).join(", ")}]`),e.startAt&&(t=(t=(t+=", startAt: ")+(e.startAt.inclusive?"b:":"a:"))+e.startAt.position.map(e=>Fy(e)).join(",")),`Target(${t=e.endAt?(t=(t+=", endAt: ")+(e.endAt.inclusive?"a:":"b:"))+e.endAt.position.map(e=>Fy(e)).join(","):t})`})(Pw(e))}; limitType=${e.limitType})`}function Fw(e,t){return t.isFoundDocument()&&(s=e,o=(a=t).key.path,null!==s.collectionGroup?a.key.hasCollectionId(s.collectionGroup)&&s.path.isPrefixOf(o):P.isDocumentKey(s.path)?s.path.isEqual(o):s.path.isImmediateParentOf(o))&&((e,t)=>{for(var r of Rw(e))if(!r.field.isKeyField()&&null===t.data.field(r.field))return;return 1})(e,t)&&((e,t)=>{for(var r of e.filters)if(!r.matches(t))return;return 1})(e,t)&&(a=t,!(s=e).startAt||(n=s.startAt,r=Rw(s),i=Zy(n,r,a),n.inclusive?i<=0:i<0))&&(!s.endAt||(r=s.endAt,n=Rw(s),i=Zy(r,n,a),r.inclusive?0<=i:0<i));var r,n,i,s,a,o}function Uw(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function Vw(e){return(t,r)=>{let n=!1;for(var i of Rw(e)){let e=((e,t,r)=>{var n=e.field.isKeyField()?P.comparator(t.key,r.key):((e,t,r)=>{var n=t.data.field(e),i=r.data.field(e);return null!==n&&null!==i?Oy(n,i):C(42886)})(e.field,t,r);switch(e.dir){case"asc":return n;case"desc":return-1*n;default:return C(19790,{direction:e.dir})}})(i,t,r);if(0!==e)return e;n=n||i.field.isKeyField()}return 0}}class qw{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(r){let e=this.mapKeyFn(r),n=this.inner[e];if(void 0!==n)for(let[e,t]of n)if(this.equalsFn(e,r))return t}has(e){return void 0!==this.get(e)}set(t,r){var e=this.mapKeyFn(t),n=this.inner[e];if(void 0===n)this.inner[e]=[[t,r]];else{for(let e=0;e<n.length;e++)if(this.equalsFn(n[e][0],t))return void(n[e]=[t,r]);n.push([t,r])}this.innerSize++}delete(t){var r=this.mapKeyFn(t),n=this.inner[r];if(void 0!==n)for(let e=0;e<n.length;e++)if(this.equalsFn(n[e][0],t))return 1===n.length?delete this.inner[r]:n.splice(e,1),this.innerSize--,!0;return!1}forEach(n){ty(this.inner,(e,t)=>{for(let[e,r]of t)n(e,r)})}isEmpty(){return ry(this.inner)}size(){return this.innerSize}}let Bw=new ny(P.comparator);let jw=new ny(P.comparator);function zw(...e){let t=jw;for(var r of e)t=t.insert(r.key,r);return t}function Kw(e){let r=jw;return e.forEach((e,t)=>r=r.insert(e,t.overlayedDocument)),r}function Ww(){return new qw(e=>e.toString(),(e,t)=>e.isEqual(t))}let Hw=new ny(P.comparator),Gw=new L(P.comparator);function V(...e){let t=Gw;for(var r of e)t=t.add(r);return t}let $w=new L(N);function Qw(e,t){if(e.useProto3Json){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:Bv(t)?"-0":t}}function Yw(e){return{integerValue:""+e}}function Jw(e,t){return jv(t)?Yw(t):Qw(e,t)}class Xw{constructor(){this._=void 0}}function Zw(e,t){return e instanceof sb?Vy(e=t)||(e=e)&&"doubleValue"in e?t:{integerValue:0}:null}class eb extends Xw{}class tb extends Xw{constructor(e){super(),this.elements=e}}function rb(e,t){var r=ob(t);for(let t of e.elements)r.some(e=>Dy(e,t))||r.push(t);return{arrayValue:{values:r}}}class nb extends Xw{constructor(e){super(),this.elements=e}}function ib(e,t){let r=ob(t);for(let t of e.elements)r=r.filter(e=>!Dy(e,t));return{arrayValue:{values:r}}}class sb extends Xw{constructor(e,t){super(),this.serializer=e,this.Ae=t}}function ab(e){return py(e.integerValue||e.doubleValue)}function ob(e){return qy(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class lb{constructor(e,t){this.field=e,this.transform=t}}class hb{constructor(e,t){this.version=e,this.transformResults=t}}class cb{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new cb}static exists(e){return new cb(void 0,e)}static updateTime(e){return new cb(e)}get isNone(){return void 0===this.updateTime&&void 0===this.exists}isEqual(e){return this.exists===e.exists&&(this.updateTime?!!e.updateTime&&this.updateTime.isEqual(e.updateTime):!e.updateTime)}}function ub(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class db{}function pb(e,r){if(!e.hasLocalMutations||r&&0===r.fields.length)return null;if(null===r)return e.isNoDocument()?new bb(e.key,cb.none()):new mb(e.key,e.data,cb.none());{var n,i=e.data,s=Yy.empty();let t=new L(ev.comparator);for(n of r.fields)if(!t.has(n)){let e=i.field(n);null===e&&1<n.length&&(n=n.popLast(),e=i.field(n)),null===e?s.delete(n):s.set(n,e),t=t.add(n)}return new vb(e.key,s,new ly(t.toArray()),cb.none())}}function fb(e,t,r,n){return e instanceof mb?(s=t,a=r,o=n,ub((i=e).precondition,s)?(l=i.value.clone(),h=wb(i.fieldTransforms,o,s),l.setAll(h),s.convertToFoundDocument(s.version,l).setHasLocalMutations(),null):a):e instanceof vb?(i=t,o=r,s=n,ub((a=e).precondition,i)?(h=wb(a.fieldTransforms,s,i),(l=i.data).setAll(_b(a)),l.setAll(h),i.convertToFoundDocument(i.version,l).setHasLocalMutations(),null===o?null:o.unionWith(a.fieldMask.fields).unionWith(a.fieldTransforms.map(e=>e.field))):o):(n=t,t=r,ub(e.precondition,n)?(n.convertToNoDocument(n.version).setHasLocalMutations(),null):t);var i,s,a,o,l,h}function gb(e,t){return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&(r=e.fieldTransforms,n=t.fieldTransforms,!!(void 0===r&&void 0===n||r&&n&&Qm(r,n,(e,t)=>(t=t,(e=e).field.isEqual(t.field)&&(e=e.transform,t=t.transform,e instanceof tb&&t instanceof tb||e instanceof nb&&t instanceof nb?Qm(e.elements,t.elements,Dy):e instanceof sb&&t instanceof sb?Dy(e.Ae,t.Ae):e instanceof eb&&t instanceof eb)))))&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask));var r,n}class mb extends db{constructor(e,t,r,n=[]){super(),this.key=e,this.value=t,this.precondition=r,this.fieldTransforms=n,this.type=0}getFieldMask(){return null}}class vb extends db{constructor(e,t,r,n,i=[]){super(),this.key=e,this.data=t,this.fieldMask=r,this.precondition=n,this.fieldTransforms=i,this.type=1}getFieldMask(){return this.fieldMask}}function _b(r){let n=new Map;return r.fieldMask.fields.forEach(e=>{var t;e.isEmpty()||(t=r.data.field(e),n.set(e,t))}),n}function yb(e,t,r){var n,i,s,a=new Map;S(e.length===r.length,32656,{Ve:r.length,de:e.length});for(let c=0;c<r.length;c++){var o=e[c],l=o.transform,h=t.data.field(o.field);a.set(o.field,(n=l,i=h,s=r[c],n instanceof tb?rb(n,i):n instanceof nb?ib(n,i):s))}return a}function wb(e,r,n){var i,s,a,o,l,h,c,u=new Map;for(i of e){let e=i.transform,t=n.data.field(i.field);u.set(i.field,(s=e,a=t,o=r,c=h=l=void 0,s instanceof eb?(o=o,h=a,c={fields:{[my]:{stringValue:gy},[_y]:{timestampValue:{seconds:o.seconds,nanos:o.nanoseconds}}}},(h=h&&yy(h)?wy(h):h)&&(c.fields[vy]=h),{mapValue:c}):s instanceof tb?rb(s,a):s instanceof nb?ib(s,a):(c=Zw(o=s,a),l=ab(c)+ab(o.Ae),Vy(c)&&Vy(o.Ae)?Yw(l):Qw(o.serializer,l))))}return u}class bb extends db{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class Ib extends db{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class Tb{constructor(e,t,r,n){this.batchId=e,this.localWriteTime=t,this.baseMutations=r,this.mutations=n}applyToRemoteDocument(e,t){var r,n,i,s,a,o,l,h=t.mutationResults;for(let u=0;u<this.mutations.length;u++){var c=this.mutations[u];c.key.isEqual(e.key)&&(r=c,n=e,i=h[u],l=c=o=a=s=void 0,r instanceof mb?(a=n,o=i,c=(s=r).value.clone(),l=yb(s.fieldTransforms,a,o.transformResults),c.setAll(l),a.convertToFoundDocument(o.version,c).setHasCommittedMutations()):r instanceof vb?(s=n,a=i,ub((o=r).precondition,s)?(l=yb(o.fieldTransforms,s,a.transformResults),(c=s.data).setAll(_b(o)),c.setAll(l),s.convertToFoundDocument(a.version,c).setHasCommittedMutations()):s.convertToUnknownDocument(a.version)):n.convertToNoDocument(i.version).setHasCommittedMutations())}}applyToLocalView(e,t){for(var r of this.baseMutations)r.key.isEqual(e.key)&&(t=fb(r,e,t,this.localWriteTime));for(var n of this.mutations)n.key.isEqual(e.key)&&(t=fb(n,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(n,i){let s=Ww();return this.mutations.forEach(e=>{var t=n.get(e.key),r=t.overlayedDocument,t=this.applyToLocalView(r,t.mutatedFields),t=pb(r,i.has(e.key)?null:t);null!==t&&s.set(e.key,t),r.isValidDocument()||r.convertToNoDocument(O.min())}),s}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),V())}isEqual(e){return this.batchId===e.batchId&&Qm(this.mutations,e.mutations,(e,t)=>gb(e,t))&&Qm(this.baseMutations,e.baseMutations,(e,t)=>gb(e,t))}}class Eb{constructor(e,t,r,n){this.batch=e,this.commitVersion=t,this.mutationResults=r,this.docVersions=n}static from(e,t,r){S(e.mutations.length===r.length,58842,{me:e.mutations.length,fe:r.length});let n=Hw;var i=e.mutations;for(let s=0;s<i.length;s++)n=n.insert(i[s].key,r[s].version);return new Eb(e,t,r,n)}}class Cb{constructor(e,t){this.largestBatchId=e,this.mutation=t}getKey(){return this.mutation.key}isEqual(e){return null!==e&&this.mutation===e.mutation}toString(){return`Overlay{
|
|
9
|
+
`)}let gi={error:"UNKNOWN_ERROR"};async function mi(e,t=!1,r=!1){var n,i=e.app;Qn(i);let s=jn(i),a=s.token,o=void 0;if(a&&!bi(a)&&(s.token=void 0,a=void 0),a||(n=await s.cachedTokenPromise)&&(bi(n)?a=n:await ui(i,void 0)),!t&&a&&bi(a))return{token:a.token};let l=!1;if(pi())try{var h=await fi(),c=(s.exchangeTokenPromise||(s.exchangeTokenPromise=Xn(Zn(i,h),e.heartbeatServiceProvider).finally(()=>{s.exchangeTokenPromise=void 0}),l=!0),await s.exchangeTokenPromise);return await ui(i,c),{token:(s.token=c).token}}catch(e){return"appCheck/throttled"===e.code||"appCheck/initial-throttle"===e.code?hi.warn(e.message):r&&hi.error(e),Ii(e)}try{s.exchangeTokenPromise||(s.exchangeTokenPromise=s.provider.getToken().finally(()=>{s.exchangeTokenPromise=void 0}),l=!0),a=await jn(i).exchangeTokenPromise}catch(e){"appCheck/throttled"===e.code||"appCheck/initial-throttle"===e.code?hi.warn(e.message):r&&hi.error(e),o=e}let u;return a?o?u=bi(a)?{token:a.token,internalError:o}:Ii(o):(u={token:a.token},await ui(i,s.token=a)):u=Ii(o),l&&wi(i,u),u}function vi(t,e,r,n){var i=t.app,i=jn(i),s={next:r,error:n,type:e};if(i.tokenObservers=[...i.tokenObservers,s],i.token&&bi(i.token)){let e=i.token;Promise.resolve().then(()=>{r({token:e.token}),yi(t)}).catch(()=>{})}i.cachedTokenPromise.then(()=>yi(t))}function _i(e,t){var r=jn(e),n=r.tokenObservers.filter(e=>e.next!==t);0===n.length&&r.tokenRefresher&&r.tokenRefresher.isRunning()&&r.tokenRefresher.stop(),r.tokenObservers=n}function yi(e){var t=e.app,t=jn(t);let r=t.tokenRefresher;r||(r=(r=>{let n=r.app;return new Hn(async()=>{var e=jn(n);let t;if((t=e.token?await mi(r,!0):await mi(r)).error)throw t.error;if(t.internalError)throw t.internalError},()=>!0,()=>{var e,t=jn(n);return t.token?(e=t.token.issuedAtTimeMillis+.5*(t.token.expireTimeMillis-t.token.issuedAtTimeMillis)+3e5,t=t.token.expireTimeMillis-3e5,e=Math.min(e,t),Math.max(0,e-Date.now())):0},Wn.RETRIAL_MIN_WAIT,Wn.RETRIAL_MAX_WAIT)})(e),t.tokenRefresher=r),!r.isRunning()&&t.isTokenAutoRefreshEnabled&&r.start()}function wi(e,t){var r;for(r of jn(e).tokenObservers)try{"EXTERNAL"===r.type&&null!=t.error?r.error(t.error):r.next(t)}catch(e){}}function bi(e){return 0<e.expireTimeMillis-Date.now()}function Ii(e){return{token:(t=gi,a.encodeString(JSON.stringify(t),!1)),error:e};var t}class Ti{constructor(e,t){this.app=e,this.heartbeatServiceProvider=t}_delete(){var e,t=jn(this.app).tokenObservers;for(e of t)_i(this.app,e.next);return Promise.resolve()}}function Ei(t){return{getToken:e=>mi(t,e),getLimitedUseToken:()=>(async e=>{var t=e.app,r=(Qn(t),jn(t)).provider;return pi()?{token:t=(await Xn(Zn(t,await fi()),e.heartbeatServiceProvider)).token}:{token:t=(await r.getToken()).token}})(t),addTokenListener:e=>vi(t,"INTERNAL",e),removeTokenListener:e=>_i(t.app,e)}}let Ci="https://www.google.com/recaptcha/api.js",Si="https://www.google.com/recaptcha/enterprise.js";function ki(t,r){let n=new Z;jn(t).reCAPTCHAState={initialized:n};let i=Ri(t);var e,s=$n(!1);return s?Ni(t,r,s,i,n):(e=()=>{var e=$n(!1);if(!e)throw new Error("no recaptcha");Ni(t,r,e,i,n)},(s=document.createElement("script")).src=Ci,s.onload=e,document.head.appendChild(s)),n.promise}function Ai(t,r){let n=new Z;jn(t).reCAPTCHAState={initialized:n};let i=Ri(t);var e,s=$n(!0);return s?Ni(t,r,s,i,n):(e=()=>{var e=$n(!0);if(!e)throw new Error("no recaptcha");Ni(t,r,e,i,n)},(s=document.createElement("script")).src=Si,s.onload=e,document.head.appendChild(s)),n.promise}function Ni(n,i,s,a,o){s.ready(()=>{var e,t,r;e=n,t=s.render(a,{sitekey:i,size:"invisible",callback:()=>{jn(e).reCAPTCHAState.succeeded=!0},"error-callback":()=>{jn(e).reCAPTCHAState.succeeded=!1}}),(r=jn(e)).reCAPTCHAState={...r.reCAPTCHAState,widgetId:t},o.resolve(s)})}function Ri(e){var t="fire_app_check_"+e.name,r=document.createElement("div");return r.id=t,r.style.display="none",document.body.appendChild(r),t}async function Pi(n){Qn(n);let i=await jn(n).reCAPTCHAState.initialized.promise;return new Promise((e,t)=>{let r=jn(n).reCAPTCHAState;i.ready(()=>{e(i.execute(r.widgetId,{action:"fire_app_check"}))})})}class Di{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){Li(this._throttleData);var e=await Pi(this._app).catch(e=>{throw Gn.create("recaptcha-error")});if(!jn(this._app).reCAPTCHAState?.succeeded)throw Gn.create("recaptcha-error");let t;try{t=await Xn(((e,t)=>{var{projectId:r,appId:n,apiKey:i}=e.options;return{url:zn+`/projects/${r}/apps/${n}:exchangeRecaptchaV3Token?key=`+i,body:{recaptcha_v3_token:t}}})(this._app,e),this._heartbeatServiceProvider)}catch(e){throw e.code?.includes("fetch-status-error")?(this._throttleData=Mi(Number(e.customData?.httpStatus),this._throttleData),Gn.create("initial-throttle",{time:Yn(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,t}initialize(e){this._app=e,this._heartbeatServiceProvider=Rt(e,"heartbeat"),ki(e,this._siteKey).catch(()=>{})}isEqual(e){return e instanceof Di&&this._siteKey===e._siteKey}}class xi{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){Li(this._throttleData);var e=await Pi(this._app).catch(e=>{throw Gn.create("recaptcha-error")});if(!jn(this._app).reCAPTCHAState?.succeeded)throw Gn.create("recaptcha-error");let t;try{t=await Xn(((e,t)=>{var{projectId:r,appId:n,apiKey:i}=e.options;return{url:zn+`/projects/${r}/apps/${n}:exchangeRecaptchaEnterpriseToken?key=`+i,body:{recaptcha_enterprise_token:t}}})(this._app,e),this._heartbeatServiceProvider)}catch(e){throw e.code?.includes("fetch-status-error")?(this._throttleData=Mi(Number(e.customData?.httpStatus),this._throttleData),Gn.create("initial-throttle",{time:Yn(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,t}initialize(e){this._app=e,this._heartbeatServiceProvider=Rt(e,"heartbeat"),Ai(e,this._siteKey).catch(()=>{})}isEqual(e){return e instanceof xi&&this._siteKey===e._siteKey}}class Oi{constructor(e){this._customProviderOptions=e}async getToken(){var e,t=await this._customProviderOptions.getToken(),r=(e=t.token,"object"==typeof(r=ye(e).claims)&&r.hasOwnProperty("iat")?r.iat:null),r=null!==r&&r<Date.now()&&0<r?1e3*r:Date.now();return{...t,issuedAtTimeMillis:r}}initialize(e){this._app=e}isEqual(e){return e instanceof Oi&&this._customProviderOptions.getToken.toString()===e._customProviderOptions.getToken.toString()}}function Mi(e,t){var r,n;return 404===e||403===e?{backoffCount:1,allowRequestsAfter:Date.now()+864e5,httpStatus:e}:(n=Be(r=t?t.backoffCount:0,1e3,2),{backoffCount:r+1,allowRequestsAfter:Date.now()+n,httpStatus:e})}function Li(e){if(e&&Date.now()-e.allowRequestsAfter<=0)throw Gn.create("throttled",{time:Yn(e.allowRequestsAfter-Date.now()),httpStatus:e.httpStatus})}function Fi(e=Vt(),r){var t=Rt(e=w(e),"app-check");if(Bn.initialized||(i=H(),(n=Bn).initialized=!0,"string"!=typeof i.FIREBASE_APPCHECK_DEBUG_TOKEN&&!0!==i.FIREBASE_APPCHECK_DEBUG_TOKEN)||(n.enabled=!0,s=new Z,n.token=s,"string"==typeof i.FIREBASE_APPCHECK_DEBUG_TOKEN?s.resolve(i.FIREBASE_APPCHECK_DEBUG_TOKEN):s.resolve(di())),pi()&&fi().then(e=>console.log(`App Check debug token: ${e}. You will need to add it to your app's App Check settings in the Firebase console for it to work.`)),t.isInitialized()){var n=t.getImmediate(),i=t.getOptions();if(i.isTokenAutoRefreshEnabled===r.isTokenAutoRefreshEnabled&&i.provider.isEqual(r.provider))return n;throw Gn.create("already-initialized",{appName:e.name})}var s=t.initialize({options:r});{var[a,r,o=!1]=[e,r.provider,r.isTokenAutoRefreshEnabled];let t=((e,t)=>(Vn.set(e,t),Vn.get(e)))(a,{...qn});t.activated=!0,t.provider=r,t.cachedTokenPromise=ci(a).then(e=>(e&&bi(e)&&(t.token=e,wi(a,{token:e.token})),e)),t.isTokenAutoRefreshEnabled=o&&a.automaticDataCollectionEnabled,!a.automaticDataCollectionEnabled&&o&&hi.warn("`isTokenAutoRefreshEnabled` is true but `automaticDataCollectionEnabled` was set to false during `initializeApp()`. This blocks automatic token refresh."),t.provider.initialize(a)}return jn(e).isTokenAutoRefreshEnabled&&vi(s,"INTERNAL",()=>{}),s}let Ui="app-check-internal";Nt(new c("app-check",e=>{var t,r=e.getProvider("app").getImmediate(),n=e.getProvider("heartbeat");return e=r,t=n,new Ti(e,t)},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,r)=>{e.getProvider(Ui).initialize()})),Nt(new c(Ui,e=>Ei(e.getProvider("app-check").getImmediate()),"PUBLIC").setInstantiationMode("EXPLICIT")),u("@firebase/app-check","0.11.2");let Vi=new ge("appCheck","AppCheck",{"use-before-activation":"App Check is being used before activate() is called for FirebaseApp {$appName}. Call activate() before instantiating other Firebase services."});class qi{constructor(e){this.app=e}activate(e,t){let r;r="string"==typeof e?new Di(e):e instanceof xi||e instanceof Di||e instanceof Oi?e:new Oi({getToken:e.getToken}),this._delegate=Fi(this.app,{provider:r,isTokenAutoRefreshEnabled:t})}setTokenAutoRefreshEnabled(e){if(!this._delegate)throw Vi.create("use-before-activation",{appName:this.app.name});var t,r;t=this._delegate,e=e,(r=jn(t.app)).tokenRefresher&&(!0===e?r.tokenRefresher.start():r.tokenRefresher.stop()),r.isTokenAutoRefreshEnabled=e}getToken(e){if(this._delegate)return(async(e,t)=>{var r=await mi(e,t);if(r.error)throw r.error;if(r.internalError)throw r.internalError;return{token:r.token}})(this._delegate,e);throw Vi.create("use-before-activation",{appName:this.app.name})}onTokenChanged(r,n,e){if(this._delegate){var i=this._delegate;let e=()=>{},t=()=>{};return e=null!=r.next?r.next.bind(r):r,null!=r.error?t=r.error.bind(r):n&&(t=n),vi(i,"EXTERNAL",e,t),()=>_i(i.app,e)}throw Vi.create("use-before-activation",{appName:this.app.name})}}let Bi=e=>{var t=e.getProvider("app-compat").getImmediate();return new qi(t)};or.INTERNAL.registerComponent(new c("appCheck-compat",Bi,"PUBLIC").setServiceProps({ReCaptchaEnterpriseProvider:xi,ReCaptchaV3Provider:Di,CustomProvider:Oi})),or.registerVersion("@firebase/app-check-compat","0.4.2");let ji={FACEBOOK:"facebook.com",GITHUB:"github.com",GOOGLE:"google.com",PASSWORD:"password",PHONE:"phone",TWITTER:"twitter.com"},zi={EMAIL_SIGNIN:"EMAIL_SIGNIN",PASSWORD_RESET:"PASSWORD_RESET",RECOVER_EMAIL:"RECOVER_EMAIL",REVERT_SECOND_FACTOR_ADDITION:"REVERT_SECOND_FACTOR_ADDITION",VERIFY_AND_CHANGE_EMAIL:"VERIFY_AND_CHANGE_EMAIL",VERIFY_EMAIL:"VERIFY_EMAIL"};function Ki(){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."}}function Wi(){return{"admin-restricted-operation":"This operation is restricted to administrators only.","argument-error":"","app-not-authorized":"This app, identified by the domain where it's hosted, is not authorized to use Firebase Authentication with the provided API key. Review your key configuration in the Google API console.","app-not-installed":"The requested mobile application corresponding to the identifier (Android package name or iOS bundle ID) provided is not installed on this device.","captcha-check-failed":"The reCAPTCHA response token provided is either invalid, expired, already used or the domain associated with it does not match the list of whitelisted domains.","code-expired":"The SMS code has expired. Please re-send the verification code to try again.","cordova-not-ready":"Cordova framework is not ready.","cors-unsupported":"This browser is not supported.","credential-already-in-use":"This credential is already associated with a different user account.","custom-token-mismatch":"The custom token corresponds to a different audience.","requires-recent-login":"This operation is sensitive and requires recent authentication. Log in again before retrying this request.","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.","dynamic-link-not-activated":"Please activate Dynamic Links in the Firebase Console and agree to the terms and conditions.","email-change-needs-verification":"Multi-factor users must always have a verified email.","email-already-in-use":"The email address is already in use by another account.","emulator-config-failed":'Auth instance has already been used to make a network call. Auth can no longer be configured to use the emulator. Try calling "connectAuthEmulator()" sooner.',"expired-action-code":"The action code has expired.","cancelled-popup-request":"This operation has been cancelled due to another conflicting popup being opened.","internal-error":"An internal AuthError has occurred.","invalid-app-credential":"The phone verification request contains an invalid application verifier. The reCAPTCHA token response is either invalid or expired.","invalid-app-id":"The mobile app identifier is not registered for the current project.","invalid-user-token":"This user's credential isn't valid for this project. This can happen if the user's token has been tampered with, or if the user isn't for the project associated with this API key.","invalid-auth-event":"An internal AuthError has occurred.","invalid-verification-code":"The SMS verification code used to create the phone auth credential is invalid. Please resend the verification code sms and be sure to use the verification code provided by the user.","invalid-continue-uri":"The continue URL provided in the request is invalid.","invalid-cordova-configuration":"The following Cordova plugins must be installed to enable OAuth sign-in: cordova-plugin-buildinfo, cordova-universal-links-plugin, cordova-plugin-browsertab, cordova-plugin-inappbrowser and cordova-plugin-customurlscheme.","invalid-custom-token":"The custom token format is incorrect. Please check the documentation.","invalid-dynamic-link-domain":"The provided dynamic link domain is not configured or authorized for the current project.","invalid-email":"The email address is badly formatted.","invalid-emulator-scheme":"Emulator URL must start with a valid scheme (http:// or https://).","invalid-api-key":"Your API key is invalid, please check you have copied it correctly.","invalid-cert-hash":"The SHA-1 certificate hash provided is invalid.","invalid-credential":"The supplied auth credential is incorrect, malformed or has expired.","invalid-message-payload":"The email template corresponding to this action contains invalid characters in its message. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-multi-factor-session":"The request does not contain a valid proof of first factor successful sign-in.","invalid-oauth-provider":"EmailAuthProvider is not supported for this operation. This operation only supports OAuth providers.","invalid-oauth-client-id":"The OAuth client ID provided is either invalid or does not match the specified API key.","unauthorized-domain":"This domain is not authorized for OAuth operations for your Firebase project. Edit the list of authorized domains from the Firebase console.","invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","wrong-password":"The password is invalid or the user does not have a password.","invalid-persistence-type":"The specified persistence type is invalid. It can only be local, session or none.","invalid-phone-number":"The format of the phone number provided is incorrect. Please enter the phone number in a format that can be parsed into E.164 format. E.164 phone numbers are written in the format [+][country code][subscriber number including area code].","invalid-provider-id":"The specified provider ID is invalid.","invalid-recipient-email":"The email corresponding to this action failed to send as the provided recipient email address is invalid.","invalid-sender":"The email template corresponding to this action contains an invalid sender email or name. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-verification-id":"The verification ID used to create the phone auth credential is invalid.","invalid-tenant-id":"The Auth instance's tenant ID is invalid.","login-blocked":"Login blocked by user-provided method: {$originalMessage}","missing-android-pkg-name":"An Android Package Name must be provided if the Android App is required to be installed.","auth-domain-config-required":"Be sure to include authDomain when calling firebase.initializeApp(), by following the instructions in the Firebase console.","missing-app-credential":"The phone verification request is missing an application verifier assertion. A reCAPTCHA response token needs to be provided.","missing-verification-code":"The phone auth credential was created with an empty SMS verification code.","missing-continue-uri":"A continue URL must be provided in the request.","missing-iframe-start":"An internal AuthError has occurred.","missing-ios-bundle-id":"An iOS Bundle ID must be provided if an App Store ID is provided.","missing-or-invalid-nonce":"The request does not contain a valid nonce. This can occur if the SHA-256 hash of the provided raw nonce does not match the hashed nonce in the ID token payload.","missing-password":"A non-empty password must be provided","missing-multi-factor-info":"No second factor identifier is provided.","missing-multi-factor-session":"The request is missing proof of first factor successful sign-in.","missing-phone-number":"To send verification codes, provide a phone number for the recipient.","missing-verification-id":"The phone auth credential was created with an empty verification ID.","app-deleted":"This instance of FirebaseApp has been deleted.","multi-factor-info-not-found":"The user does not have a second factor matching the identifier provided.","multi-factor-auth-required":"Proof of ownership of a second factor is required to complete sign-in.","account-exists-with-different-credential":"An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address.","network-request-failed":"A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.","no-auth-event":"An internal AuthError has occurred.","no-such-provider":"User was not linked to an account with the given provider.","null-user":"A null user object was provided as the argument for an operation which requires a non-null user object.","operation-not-allowed":"The given sign-in provider is disabled for this Firebase project. Enable it in the Firebase console, under the sign-in method tab of the Auth section.","operation-not-supported-in-this-environment":'This operation is not supported in the environment this application is running on. "location.protocol" must be http, https or chrome-extension and web storage must be enabled.',"popup-blocked":"Unable to establish a connection with the popup. It may have been blocked by the browser.","popup-closed-by-user":"The popup has been closed by the user before finalizing the operation.","provider-already-linked":"User can only be linked to one identity for the given provider.","quota-exceeded":"The project's quota for this operation has been exceeded.","redirect-cancelled-by-user":"The redirect operation has been cancelled by the user before finalizing.","redirect-operation-pending":"A redirect sign-in operation is already pending.","rejected-credential":"The request contains malformed or mismatching credentials.","second-factor-already-in-use":"The second factor is already enrolled on this account.","maximum-second-factor-count-exceeded":"The maximum allowed number of second factors on a user has been exceeded.","tenant-id-mismatch":"The provided tenant ID does not match the Auth instance's tenant ID",timeout:"The operation has timed out.","user-token-expired":"The user's credential is no longer valid. The user must sign in again.","too-many-requests":"We have blocked all requests from this device due to unusual activity. Try again later.","unauthorized-continue-uri":"The domain of the continue URL is not whitelisted. Please whitelist the domain in the Firebase console.","unsupported-first-factor":"Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.","unsupported-persistence-type":"The current environment does not support the specified persistence type.","unsupported-tenant-operation":"This operation is not supported in a multi-tenant context.","unverified-email":"The operation requires a verified email.","user-cancelled":"The user did not grant your application the permissions it requested.","user-not-found":"There is no user record corresponding to this identifier. The user may have been deleted.","user-disabled":"The user account has been disabled by an administrator.","user-mismatch":"The supplied credentials do not correspond to the previously signed in user.","user-signed-out":"","weak-password":"The password must be 6 characters long or more.","web-storage-unsupported":"This browser is not supported or 3rd party cookies and data may be disabled.","already-initialized":"initializeAuth() has already been called with different options. To avoid this error, call initializeAuth() with the same options as when it was originally called, or call getAuth() to return the already initialized instance.","missing-recaptcha-token":"The reCAPTCHA token is missing when sending request to the backend.","invalid-recaptcha-token":"The reCAPTCHA token is invalid when sending request to the backend.","invalid-recaptcha-action":"The reCAPTCHA action is invalid when sending request to the backend.","recaptcha-not-enabled":"reCAPTCHA Enterprise integration is not enabled for this project.","missing-client-type":"The reCAPTCHA client type is missing when sending request to the backend.","missing-recaptcha-version":"The reCAPTCHA version is missing when sending request to the backend.","invalid-req-type":"Invalid request parameters.","invalid-recaptcha-version":"The reCAPTCHA version is invalid when sending request to the backend.","unsupported-password-policy-schema-version":"The password policy received from the backend uses a schema version that is not supported by this version of the Firebase SDK.","password-does-not-meet-requirements":"The password does not meet the requirements.","invalid-hosting-link-domain":"The provided Hosting link domain is not configured in Firebase Hosting or is not owned by the current project. This cannot be a default Hosting domain (`web.app` or `firebaseapp.com`)."}}let Hi=Ki,Gi=new ge("auth","Firebase",Ki()),$i=new Xe("@firebase/auth");function Qi(e,...t){$i.logLevel<=p.ERROR&&$i.error(`Auth (${Ft}): `+e,...t)}function Yi(e,...t){throw ts(e,...t)}function Ji(e,...t){return ts(e,...t)}function Xi(e,t,r){var n={...Hi(),[t]:r};return new ge("auth","Firebase",n).create(t,{appName:e.name})}function Zi(e){return Xi(e,"operation-not-supported-in-this-environment","Operations that alter the current user are not supported in conjunction with FirebaseServerApp")}function es(e,t,r){var n=r;if(!(t instanceof n))throw n.name!==t.constructor.name&&Yi(e,"argument-error"),Xi(e,"argument-error",`Type of ${t.constructor.name} does not match expected instance.`+"Did you pass a reference from a different Auth SDK?")}function ts(e,...t){var r,n;return"string"!=typeof e?(r=t[0],(n=[...t.slice(1)])[0]&&(n[0].appName=e.name),e._errorFactory.create(r,...n)):Gi.create(e,...t)}function m(e,t,...r){if(!e)throw ts(t,...r)}function rs(e){var t="INTERNAL ASSERTION FAILED: "+e;throw Qi(t),new Error(t)}function ns(e,t){e||rs(t)}function is(){return"undefined"!=typeof self&&self.location?.href||""}function ss(){return"http:"===as()||"https:"===as()}function as(){return"undefined"!=typeof self&&self.location?.protocol||null}class os{constructor(e,t){ns((this.shortDelay=e)<(this.longDelay=t),"Short delay should be less than long delay!"),this.isMobile=re()||ae()}get(){return"undefined"!=typeof navigator&&navigator&&"onLine"in navigator&&"boolean"==typeof navigator.onLine&&(ss()||se()||"connection"in navigator)&&!navigator.onLine?Math.min(5e3,this.shortDelay):this.isMobile?this.longDelay:this.shortDelay}}function ls(e,t){ns(e.emulator,"Emulator should always be set here");var r=e.emulator.url;return t?""+r+(t.startsWith("/")?t.slice(1):t):r}class hs{static initialize(e,t,r){this.fetchImpl=e,t&&(this.headersImpl=t),r&&(this.responseImpl=r)}static fetch(){return this.fetchImpl||("undefined"!=typeof self&&"fetch"in self?self.fetch:"undefined"!=typeof globalThis&&globalThis.fetch?globalThis.fetch:"undefined"!=typeof fetch?fetch:void rs("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"))}static headers(){return this.headersImpl||("undefined"!=typeof self&&"Headers"in self?self.Headers:"undefined"!=typeof globalThis&&globalThis.Headers?globalThis.Headers:"undefined"!=typeof Headers?Headers:void rs("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"))}static response(){return this.responseImpl||("undefined"!=typeof self&&"Response"in self?self.Response:"undefined"!=typeof globalThis&&globalThis.Response?globalThis.Response:"undefined"!=typeof Response?Response:void rs("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"))}}let cs={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-recaptcha-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"},us=["/v1/accounts:signInWithCustomToken","/v1/accounts:signInWithEmailLink","/v1/accounts:signInWithIdp","/v1/accounts:signInWithPassword","/v1/accounts:signInWithPhoneNumber","/v1/token"],ds=new os(3e4,6e4);function ps(e,t){return e.tenantId&&!t.tenantId?{...t,tenantId:e.tenantId}:t}async function fs(i,s,a,o,e={}){return gs(i,e,async()=>{let e={},t={};o&&("GET"===s?t=o:e={body:JSON.stringify(o)});var r=Se({key:i.config.apiKey,...t}).slice(1),n=await i._getAdditionalHeaders(),n=(n["Content-Type"]="application/json",i.languageCode&&(n["X-Firebase-Locale"]=i.languageCode),{method:s,headers:n,...e});return"undefined"!=typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||(n.referrerPolicy="no-referrer"),i.emulatorConfig&&je(i.emulatorConfig.host)&&(n.credentials="include"),hs.fetch()(await vs(i,i.config.apiHost,a,r),n)})}async function gs(t,e,r){t._canInitEmulator=!1;var n={...cs,...e};try{var i=new _s(t),s=await Promise.race([r(),i.promise]),a=(i.clearNetworkTimeout(),await s.json());if("needConfirmation"in a)throw ys(t,"account-exists-with-different-credential",a);if(s.ok&&!("errorMessage"in a))return a;var[o,l]=(s.ok?a.errorMessage:a.error.message).split(" : ");if("FEDERATED_USER_ID_ALREADY_LINKED"===o)throw ys(t,"credential-already-in-use",a);if("EMAIL_EXISTS"===o)throw ys(t,"email-already-in-use",a);if("USER_DISABLED"===o)throw ys(t,"user-disabled",a);var h=n[o]||o.toLowerCase().replace(/[_\s]+/g,"-");if(l)throw Xi(t,h,l);Yi(t,h)}catch(e){if(e instanceof fe)throw e;Yi(t,"network-request-failed",{message:String(e)})}}async function ms(e,t,r,n,i={}){var s=await fs(e,t,r,n,i);return"mfaPendingCredential"in s&&Yi(e,"multi-factor-auth-required",{_serverResponse:s}),s}async function vs(e,t,r,n){var i=""+t+r+"?"+n,s=e,i=s.config.emulator?ls(e.config,i):e.config.apiScheme+"://"+i;if(us.includes(r)&&(await s._persistenceManagerAvailable,"COOKIE"===s._getPersistenceType()))return s._getPersistence()._getFinalTarget(i).toString();return i}class _s{clearNetworkTimeout(){clearTimeout(this.timer)}constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((e,t)=>{this.timer=setTimeout(()=>t(Ji(this.auth,"network-request-failed")),ds.get())})}}function ys(e,t,r){var n={appName:e.name},n=(r.email&&(n.email=r.email),r.phoneNumber&&(n.phoneNumber=r.phoneNumber),Ji(e,t,n));return n.customData._tokenResponse=r,n}function ws(e){return void 0!==e&&void 0!==e.getResponse}function bs(e){return void 0!==e&&void 0!==e.enterprise}class Is{constructor(e){if(this.siteKey="",this.recaptchaEnforcementState=[],void 0===e.recaptchaKey)throw new Error("recaptchaKey undefined");this.siteKey=e.recaptchaKey.split("/")[3],this.recaptchaEnforcementState=e.recaptchaEnforcementState}getProviderEnforcementState(t){if(this.recaptchaEnforcementState&&0!==this.recaptchaEnforcementState.length)for(let e of this.recaptchaEnforcementState)if(e.provider&&e.provider===t){switch(e.enforcementState){case"ENFORCE":return"ENFORCE";case"AUDIT":return"AUDIT";case"OFF":return"OFF";default:return"ENFORCEMENT_STATE_UNSPECIFIED"}return}return null}isProviderEnabled(e){return"ENFORCE"===this.getProviderEnforcementState(e)||"AUDIT"===this.getProviderEnforcementState(e)}isAnyProviderEnabled(){return this.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")||this.isProviderEnabled("PHONE_PROVIDER")}}async function Ts(e,t){return fs(e,"GET","/v2/recaptchaConfig",ps(e,t))}async function Es(e,t){return fs(e,"POST","/v1/accounts:lookup",t)}function Cs(e){if(e)try{var t=new Date(Number(e));if(!isNaN(t.getTime()))return t.toUTCString()}catch(e){}}function Ss(e){return 1e3*Number(e)}function ks(e){var[t,r,n]=e.split(".");if(void 0===t||void 0===r||void 0===n)return Qi("JWT malformed, contained fewer than 3 sections"),null;try{var i=K(r);return i?JSON.parse(i):(Qi("Failed to decode base64 JWT payload"),null)}catch(e){return Qi("Caught error parsing JWT payload as JSON",e?.toString()),null}}function As(e){var t=ks(e);return m(t,"internal-error"),m(void 0!==t.exp,"internal-error"),m(void 0!==t.iat,"internal-error"),Number(t.exp)-Number(t.iat)}async function Ns(t,e,r=!1){if(r)return e;try{return await e}catch(e){throw e instanceof fe&&(r=[e.code][0],"auth/user-disabled"===r||"auth/user-token-expired"===r)&&(t.auth.currentUser===t&&await t.auth.signOut()),e}}class Rs{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;return e?(t=this.errorBackoff,this.errorBackoff=Math.min(2*this.errorBackoff,96e4),t):(this.errorBackoff=3e4,t=(this.user.stsTokenManager.expirationTime??0)-Date.now()-3e5,Math.max(0,t))}schedule(e=!1){var t;this.isRunning&&(t=this.getInterval(e),this.timerId=setTimeout(async()=>{await this.iteration()},t))}async iteration(){try{await this.user.getIdToken(!0)}catch(e){return void("auth/network-request-failed"===e?.code&&this.schedule(!0))}this.schedule()}}class Ps{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=Cs(this.lastLoginAt),this.creationTime=Cs(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function Ds(e){var t,r,n=e.auth,i=await e.getIdToken(),i=await Ns(e,Es(n,{idToken:i})),n=(m(i?.users.length,n,"internal-error"),i.users[0]),i=(e._notifyReloadListener(n),n.providerUserInfo?.length?xs(n.providerUserInfo):[]),i=(t=e.providerData,r=i,[...t.filter(t=>!r.some(e=>e.providerId===t.providerId)),...r]),s=!(e.email&&n.passwordHash||i.length),s=!!e.isAnonymous&&s,i={uid:n.localId,displayName:n.displayName||null,photoURL:n.photoUrl||null,email:n.email||null,emailVerified:n.emailVerified||!1,phoneNumber:n.phoneNumber||null,tenantId:n.tenantId||null,providerData:i,metadata:new Ps(n.createdAt,n.lastLoginAt),isAnonymous:s};Object.assign(e,i)}function xs(e){return e.map(({providerId:e,...t})=>({providerId:e,uid:t.rawId||"",displayName:t.displayName||null,email:t.email||null,phoneNumber:t.phoneNumber||null,photoURL:t.photoUrl||null}))}class Os{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){m(e.idToken,"internal-error"),m(void 0!==e.idToken,"internal-error"),m(void 0!==e.refreshToken,"internal-error");var t="expiresIn"in e&&void 0!==e.expiresIn?Number(e.expiresIn):As(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,t)}updateFromIdToken(e){m(0!==e.length,"internal-error");var t=As(e);this.updateTokensAndExpiration(e,null,t)}async getToken(e,t=!1){return t||!this.accessToken||this.isExpired?(m(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){i=t;var n,i,{accessToken:r,refreshToken:s,expiresIn:a}=await{accessToken:(r=await gs(n=e,{},async()=>{var e=Se({grant_type:"refresh_token",refresh_token:i}).slice(1),{tokenApiHost:t,apiKey:r}=n.config,t=await vs(n,t,"/v1/token","key="+r),r=await n._getAdditionalHeaders(),r=(r["Content-Type"]="application/x-www-form-urlencoded",{method:"POST",headers:r,body:e});return n.emulatorConfig&&je(n.emulatorConfig.host)&&(r.credentials="include"),hs.fetch()(t,r)})).access_token,expiresIn:r.expires_in,refreshToken:r.refresh_token};this.updateTokensAndExpiration(r,s,Number(a))}updateTokensAndExpiration(e,t,r){this.refreshToken=t||null,this.accessToken=e||null,this.expirationTime=Date.now()+1e3*r}static fromJSON(e,t){var{refreshToken:r,accessToken:n,expirationTime:i}=t,s=new Os;return r&&(m("string"==typeof r,"internal-error",{appName:e}),s.refreshToken=r),n&&(m("string"==typeof n,"internal-error",{appName:e}),s.accessToken=n),i&&(m("number"==typeof i,"internal-error",{appName:e}),s.expirationTime=i),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 Os,this.toJSON())}_performRefresh(){return rs("not implemented")}}function Ms(e,t){m("string"==typeof e||void 0===e,"internal-error",{appName:t})}class Ls{constructor({uid:e,auth:t,stsTokenManager:r,...n}){this.providerId="firebase",this.proactiveRefresh=new Rs(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=e,this.auth=t,this.stsTokenManager=r,this.accessToken=r.accessToken,this.displayName=n.displayName||null,this.email=n.email||null,this.emailVerified=n.emailVerified||!1,this.phoneNumber=n.phoneNumber||null,this.photoURL=n.photoURL||null,this.isAnonymous=n.isAnonymous||!1,this.tenantId=n.tenantId||null,this.providerData=n.providerData?[...n.providerData]:[],this.metadata=new Ps(n.createdAt||void 0,n.lastLoginAt||void 0)}async getIdToken(e){var t=await Ns(this,this.stsTokenManager.getToken(this.auth,e));return m(t,this.auth,"internal-error"),this.accessToken!==t&&(this.accessToken=t,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),t}getIdTokenResult(e){return(async(e,t=!1)=>{var r=w(e),n=await r.getIdToken(t),i=ks(n),s=(m(i&&i.exp&&i.auth_time&&i.iat,r.auth,"internal-error"),(r="object"==typeof i.firebase?i.firebase:void 0)?.sign_in_provider);return{claims:i,token:n,authTime:Cs(Ss(i.auth_time)),issuedAtTime:Cs(Ss(i.iat)),expirationTime:Cs(Ss(i.exp)),signInProvider:s||null,signInSecondFactor:r?.sign_in_second_factor||null}})(this,e)}reload(){return(async e=>{var t=w(e);await Ds(t),await t.auth._persistUserIfCurrent(t),t.auth._notifyListenersIfCurrent(t)})(this)}_assign(e){this!==e&&(m(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=>({...e})),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){var t=new Ls({...this,auth:e,stsTokenManager:this.stsTokenManager._clone()});return t.metadata._copy(this.metadata),t}_onReload(e){m(!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 r=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),r=!0),t&&await Ds(this),await this.auth._persistUserIfCurrent(this),r&&this.auth._notifyListenersIfCurrent(this)}async delete(){var e;return h(this.auth.app)?Promise.reject(Zi(this.auth)):(e=await this.getIdToken(),await Ns(this,(async(e,t)=>fs(e,"POST","/v1/accounts:delete",t))(this.auth,{idToken:e})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut())}toJSON(){return{uid:this.uid,email:this.email||void 0,emailVerified:this.emailVerified,displayName:this.displayName||void 0,isAnonymous:this.isAnonymous,photoURL:this.photoURL||void 0,phoneNumber:this.phoneNumber||void 0,tenantId:this.tenantId||void 0,providerData:this.providerData.map(e=>({...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 r=t.displayName??void 0,n=t.email??void 0,i=t.phoneNumber??void 0,s=t.photoURL??void 0,a=t.tenantId??void 0,o=t._redirectEventId??void 0,l=t.createdAt??void 0,h=t.lastLoginAt??void 0,{uid:c,emailVerified:u,isAnonymous:d,providerData:p,stsTokenManager:f}=t,f=(m(c&&f,e,"internal-error"),Os.fromJSON(this.name,f)),c=(m("string"==typeof c,e,"internal-error"),Ms(r,e.name),Ms(n,e.name),m("boolean"==typeof u,e,"internal-error"),m("boolean"==typeof d,e,"internal-error"),Ms(i,e.name),Ms(s,e.name),Ms(a,e.name),Ms(o,e.name),Ms(l,e.name),Ms(h,e.name),new Ls({uid:c,auth:e,email:n,emailVerified:u,displayName:r,isAnonymous:d,photoURL:s,phoneNumber:i,tenantId:a,stsTokenManager:f,createdAt:l,lastLoginAt:h}));return p&&Array.isArray(p)&&(c.providerData=p.map(e=>({...e}))),o&&(c._redirectEventId=o),c}static async _fromIdTokenResponse(e,t,r=!1){var n=new Os,n=(n.updateFromServerResponse(t),new Ls({uid:t.localId,auth:e,stsTokenManager:n,isAnonymous:r}));return await Ds(n),n}static async _fromGetAccountInfoResponse(e,t,r){var n=t.users[0],i=(m(void 0!==n.localId,"internal-error"),void 0!==n.providerUserInfo?xs(n.providerUserInfo):[]),s=!(n.email&&n.passwordHash||i?.length),a=new Os,a=(a.updateFromIdToken(r),new Ls({uid:n.localId,auth:e,stsTokenManager:a,isAnonymous:s})),s={uid:n.localId,displayName:n.displayName||null,photoURL:n.photoUrl||null,email:n.email||null,emailVerified:n.emailVerified||!1,phoneNumber:n.phoneNumber||null,tenantId:n.tenantId||null,providerData:i,metadata:new Ps(n.createdAt,n.lastLoginAt),isAnonymous:!(n.email&&n.passwordHash||i?.length)};return Object.assign(a,s),a}}let Fs=new Map;function Us(e){ns(e instanceof Function,"Expected a class definition");var t=Fs.get(e);return t?ns(t instanceof e,"Instance stored in cache mismatched with class"):(t=new e,Fs.set(e,t)),t}class Vs{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,t){this.storage[e]=t}async _get(e){var t=this.storage[e];return void 0===t?null:t}async _remove(e){delete this.storage[e]}_addListener(e,t){}_removeListener(e,t){}}Vs.type="NONE";let qs=Vs;function Bs(e,t,r){return`firebase:${e}:${t}:`+r}class js{constructor(e,t,r){this.persistence=e,this.auth=t,this.userKey=r;var{config:n,name:i}=this.auth;this.fullUserKey=Bs(this.userKey,n.apiKey,i),this.fullPersistenceKey=Bs("persistence",n.apiKey,i),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(){var e,t=await this.persistence._get(this.fullUserKey);return t?"string"==typeof t?(e=await Es(this.auth,{idToken:t}).catch(()=>{}))?Ls._fromGetAccountInfoResponse(this.auth,e,t):null:Ls._fromJSON(this.auth,t):null}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(e){var t;if(this.persistence!==e)return t=await this.getCurrentUser(),await this.removeCurrentUser(),this.persistence=e,t?this.setCurrentUser(t):void 0}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(t,e,r="authUser"){if(!e.length)return new js(Us(qs),t,r);var n,i=(await Promise.all(e.map(async e=>{if(await e._isAvailable())return e}))).filter(e=>e);let s=i[0]||Us(qs),a=Bs(r,t.config.apiKey,t.name),o=null;for(n of e)try{var l=await n._get(a);if(l){let e;if("string"==typeof l){var h=await Es(t,{idToken:l}).catch(()=>{});if(!h)break;e=await Ls._fromGetAccountInfoResponse(t,h,l)}else e=Ls._fromJSON(t,l);n!==s&&(o=e),s=n;break}}catch{}i=i.filter(e=>e._shouldAllowMigration);return s._shouldAllowMigration&&i.length&&(s=i[0],o&&await s._set(a,o.toJSON()),await Promise.all(e.map(async e=>{if(e!==s)try{await e._remove(a)}catch{}}))),new js(s,t,r)}}function zs(e){var t=e.toLowerCase();return t.includes("opera/")||t.includes("opr/")||t.includes("opios/")?"Opera":Gs(t)?"IEMobile":t.includes("msie")||t.includes("trident/")?"IE":t.includes("edge/")?"Edge":Ks(t)?"Firefox":t.includes("silk/")?"Silk":Qs(t)?"Blackberry":Ys(t)?"Webos":Ws(t)?"Safari":!t.includes("chrome/")&&!Hs(t)||t.includes("edge/")?$s(t)?"Android":2===(t=e.match(/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/))?.length?t[1]:"Other":"Chrome"}function Ks(e=te()){return/firefox\//i.test(e)}function Ws(e=te()){var t=e.toLowerCase();return t.includes("safari/")&&!t.includes("chrome/")&&!t.includes("crios/")&&!t.includes("android")}function Hs(e=te()){return/crios\//i.test(e)}function Gs(e=te()){return/iemobile/i.test(e)}function $s(e=te()){return/android/i.test(e)}function Qs(e=te()){return/blackberry/i.test(e)}function Ys(e=te()){return/webos/i.test(e)}function Js(e=te()){return/iphone|ipad|ipod/i.test(e)||/macintosh/i.test(e)&&/mobile/i.test(e)}function Xs(e=te()){return Js(e)||$s(e)||Ys(e)||Qs(e)||/windows phone/i.test(e)||Gs(e)}function Zs(e,t=[]){let r;switch(e){case"Browser":r=zs(te());break;case"Worker":r=zs(te())+"-"+e;break;default:r=e}var n=t.length?t.join(","):"FirebaseCore-web";return`${r}/JsCore/${Ft}/`+n}class ea{constructor(e){this.auth=e,this.queue=[]}pushCallback(n,e){var t=r=>new Promise((e,t)=>{try{e(n(r))}catch(e){t(e)}});t.onAbort=e,this.queue.push(t);let r=this.queue.length-1;return()=>{this.queue[r]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser!==e){var t=[];try{for(var r of this.queue)await r(e),r.onAbort&&t.push(r.onAbort)}catch(e){t.reverse();for(var n of t)try{n()}catch(e){}throw this.auth._errorFactory.create("login-blocked",{originalMessage:e?.message})}}}}class ta{constructor(e){var t=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=t.minPasswordLength??6,t.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=t.maxPasswordLength),void 0!==t.containsLowercaseCharacter&&(this.customStrengthOptions.containsLowercaseLetter=t.containsLowercaseCharacter),void 0!==t.containsUppercaseCharacter&&(this.customStrengthOptions.containsUppercaseLetter=t.containsUppercaseCharacter),void 0!==t.containsNumericCharacter&&(this.customStrengthOptions.containsNumericCharacter=t.containsNumericCharacter),void 0!==t.containsNonAlphanumericCharacter&&(this.customStrengthOptions.containsNonAlphanumericCharacter=t.containsNonAlphanumericCharacter),this.enforcementState=e.enforcementState,"ENFORCEMENT_STATE_UNSPECIFIED"===this.enforcementState&&(this.enforcementState="OFF"),this.allowedNonAlphanumericCharacters=e.allowedNonAlphanumericCharacters?.join("")??"",this.forceUpgradeOnSignin=e.forceUpgradeOnSignin??!1,this.schemaVersion=e.schemaVersion}validatePassword(e){var t={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,t),this.validatePasswordCharacterOptions(e,t),t.isValid&&(t.isValid=t.meetsMinPasswordLength??!0),t.isValid&&(t.isValid=t.meetsMaxPasswordLength??!0),t.isValid&&(t.isValid=t.containsLowercaseLetter??!0),t.isValid&&(t.isValid=t.containsUppercaseLetter??!0),t.isValid&&(t.isValid=t.containsNumericCharacter??!0),t.isValid&&(t.isValid=t.containsNonAlphanumericCharacter??!0),t}validatePasswordLengthOptions(e,t){var r=this.customStrengthOptions.minPasswordLength,n=this.customStrengthOptions.maxPasswordLength;r&&(t.meetsMinPasswordLength=e.length>=r),n&&(t.meetsMaxPasswordLength=e.length<=n)}validatePasswordCharacterOptions(e,t){var r;this.updatePasswordCharacterOptionsStatuses(t,!1,!1,!1,!1);for(let n=0;n<e.length;n++)r=e.charAt(n),this.updatePasswordCharacterOptionsStatuses(t,"a"<=r&&r<="z","A"<=r&&r<="Z","0"<=r&&r<="9",this.allowedNonAlphanumericCharacters.includes(r))}updatePasswordCharacterOptionsStatuses(e,t,r,n,i){this.customStrengthOptions.containsLowercaseLetter&&!e.containsLowercaseLetter&&(e.containsLowercaseLetter=t),this.customStrengthOptions.containsUppercaseLetter&&!e.containsUppercaseLetter&&(e.containsUppercaseLetter=r),this.customStrengthOptions.containsNumericCharacter&&!e.containsNumericCharacter&&(e.containsNumericCharacter=n),this.customStrengthOptions.containsNonAlphanumericCharacter&&!e.containsNonAlphanumericCharacter&&(e.containsNonAlphanumericCharacter=i)}}class ra{constructor(e,t,r,n){this.app=e,this.heartbeatServiceProvider=t,this.appCheckServiceProvider=r,this.config=n,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new ia(this),this.idTokenSubscription=new ia(this),this.beforeStateQueue=new ea(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=Gi,this._agentRecaptchaConfig=null,this._tenantRecaptchaConfigs={},this._projectPasswordPolicy=null,this._tenantPasswordPolicies={},this._resolvePersistenceManagerAvailable=void 0,this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=n.sdkClientVersion,this._persistenceManagerAvailable=new Promise(e=>this._resolvePersistenceManagerAvailable=e)}_initializeWithPersistence(e,t){return t&&(this._popupRedirectResolver=Us(t)),this._initializationPromise=this.queue(async()=>{if(!this._deleted&&(this.persistenceManager=await js.create(this,e),this._resolvePersistenceManagerAvailable?.(),!this._deleted)){if(this._popupRedirectResolver?._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch(e){}await this.initializeCurrentUser(t),this.lastNotifiedUid=this.currentUser?.uid||null,this._deleted||(this._isInitialized=!0)}}),this._initializationPromise}async _onStorageEvent(){var e;!this._deleted&&(e=await this.assertedPersistence.getCurrentUser(),this.currentUser||e)&&(this.currentUser&&e&&this.currentUser.uid===e.uid?(this._currentUser._assign(e),await this.currentUser.getIdToken()):await this._updateCurrentUser(e,!0))}async initializeCurrentUserFromIdToken(e){try{var t=await Es(this,{idToken:e}),r=await Ls._fromGetAccountInfoResponse(this,t,e);await this.directlySetCurrentUser(r)}catch(e){console.warn("FirebaseServerApp could not login user with provided authIdToken: ",e),await this.directlySetCurrentUser(null)}}async initializeCurrentUser(e){if(h(this.app)){let t=this.app.settings.authIdToken;return t?new Promise(e=>{setTimeout(()=>this.initializeCurrentUserFromIdToken(t).then(e,e))}):this.directlySetCurrentUser(null)}var t,r,n,i=await this.assertedPersistence.getCurrentUser();let s=i,a=!1;if(e&&this.config.authDomain&&(await this.getOrInitRedirectPersistenceManager(),t=this.redirectUser?._redirectEventId,r=s?._redirectEventId,n=await this.tryRedirectSignIn(e),t&&t!==r||!n?.user||(s=n.user,a=!0)),!s)return this.directlySetCurrentUser(null);if(s._redirectEventId)return m(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===s._redirectEventId?this.directlySetCurrentUser(s):this.reloadAndSetCurrentUserOrClear(s);if(a)try{await this.beforeStateQueue.runMiddleware(s)}catch(e){s=i,this._popupRedirectResolver._overrideRedirectResult(this,()=>Promise.reject(e))}return s?this.reloadAndSetCurrentUserOrClear(s):this.directlySetCurrentUser(null)}async tryRedirectSignIn(e){let t=null;try{t=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch(e){await this._setRedirectUser(null)}return t}async reloadAndSetCurrentUserOrClear(e){try{await Ds(e)}catch(e){if("auth/network-request-failed"!==e?.code)return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){var e;this.languageCode="undefined"!=typeof navigator&&((e=navigator).languages&&e.languages[0]||e.language)||null}async _delete(){this._deleted=!0}async updateCurrentUser(e){var t;return h(this.app)?Promise.reject(Zi(this)):((t=e?w(e):null)&&m(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&&m(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 h(this.app)?Promise.reject(Zi(this)):(await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0))}setPersistence(e){return h(this.app)?Promise.reject(Zi(this)):this.queue(async()=>{await this.assertedPersistence.setPersistence(Us(e))})}_getRecaptchaConfig(){return null==this.tenantId?this._agentRecaptchaConfig:this._tenantRecaptchaConfigs[this.tenantId]}async validatePassword(e){this._getPasswordPolicyInternal()||await this._updatePasswordPolicy();var 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(){var e,t=await fs(e=this,"GET","/v2/passwordPolicy",ps(e,{})),t=new ta(t);null===this.tenantId?this._projectPasswordPolicy=t:this._tenantPasswordPolicies[this.tenantId]=t}_getPersistenceType(){return this.assertedPersistence.persistence.type}_getPersistence(){return this.assertedPersistence.persistence}_updateErrorMap(e){this._errorFactory=new ge("auth","Firebase",e())}onAuthStateChanged(e,t,r){return this.registerStateListener(this.authStateSubscription,e,t,r)}beforeAuthStateChanged(e,t){return this.beforeStateQueue.pushCallback(e,t)}onIdTokenChanged(e,t,r){return this.registerStateListener(this.idTokenSubscription,e,t,r)}authStateReady(){return new Promise((t,r)=>{if(this.currentUser)t();else{let e=this.onAuthStateChanged(()=>{e(),t()},r)}})}async revokeAccessToken(e){var t;this.currentUser&&(t={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:e,idToken:await this.currentUser.getIdToken()},null!=this.tenantId&&(t.tenantId=this.tenantId),await fs(e=this,"POST","/v2/accounts:revokeToken",ps(e,t)))}toJSON(){return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:this._currentUser?.toJSON()}}async _setRedirectUser(e,t){var r=await this.getOrInitRedirectPersistenceManager(t);return null===e?r.removeCurrentUser():r.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){var t;return this.redirectPersistenceManager||(m(t=e&&Us(e)||this._popupRedirectResolver,this,"argument-error"),this.redirectPersistenceManager=await js.create(this,[Us(t._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()),this.redirectPersistenceManager}async _redirectUserForId(e){return this._isInitialized&&await this.queue(async()=>{}),this._currentUser?._redirectEventId===e?this._currentUser:this.redirectUser?._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;this._isInitialized&&(this.idTokenSubscription.next(this.currentUser),e=this.currentUser?.uid??null,this.lastNotifiedUid!==e)&&(this.lastNotifiedUid=e,this.authStateSubscription.next(this.currentUser))}registerStateListener(t,r,n,i){if(this._deleted)return()=>{};let e="function"==typeof r?r:r.next.bind(r),s=!1;var a=this._isInitialized?Promise.resolve():this._initializationPromise;if(m(a,this,"internal-error"),a.then(()=>{s||e(this.currentUser)}),"function"==typeof r){let e=t.addObserver(r,n,i);return()=>{s=!0,e()}}{let e=t.addObserver(r);return()=>{s=!0,e()}}}async directlySetCurrentUser(e){this.currentUser&&this.currentUser!==e&&this._currentUser._stopProactiveRefresh(),e&&this.isProactiveRefreshEnabled&&e._startProactiveRefresh(),(this.currentUser=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 m(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){e&&!this.frameworks.includes(e)&&(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=Zs(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){var e={"X-Client-Version":this.clientVersion},t=(this.app.options.appId&&(e["X-Firebase-gmpid"]=this.app.options.appId),await this.heartbeatServiceProvider.getImmediate({optional:!0})?.getHeartbeatsHeader()),t=(t&&(e["X-Firebase-Client"]=t),await this._getAppCheckToken());return t&&(e["X-Firebase-AppCheck"]=t),e}async _getAppCheckToken(){var e,t,r;return h(this.app)&&this.app.settings.appCheckToken?this.app.settings.appCheckToken:((e=await this.appCheckServiceProvider.getImmediate({optional:!0})?.getToken())?.error&&(t="Error while retrieving App Check token: "+e.error,r=[],$i.logLevel<=p.WARN)&&$i.warn(`Auth (${Ft}): `+t,...r),e?.token)}}function na(e){return w(e)}class ia{constructor(e){this.auth=e,this.observer=null,this.addObserver=Re(e=>this.observer=e)}get next(){return m(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}let sa={async loadJS(){throw new Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};function aa(e){return sa.loadJS(e)}function oa(e){return"__"+e+Math.floor(1e6*Math.random())}class la{constructor(e){this.auth=e,this.counter=1e12,this._widgets=new Map}render(e,t){var r=this.counter;return this._widgets.set(r,new ua(e,this.auth.name,t||{})),this.counter++,r}reset(e){var t=e||1e12;this._widgets.get(t)?.delete(),this._widgets.delete(t)}getResponse(e){return this._widgets.get(e||1e12)?.getResponse()||""}async execute(e){return this._widgets.get(e||1e12)?.execute(),""}}class ha{constructor(){this.enterprise=new ca}ready(e){e()}execute(e,t){return Promise.resolve("token")}render(e,t){return""}}class ca{ready(e){e()}execute(e,t){return Promise.resolve("token")}render(e,t){return""}}class ua{constructor(e,t,r){this.params=r,this.timerId=null,this.deleted=!1,this.responseToken=null,this.clickHandler=()=>{this.execute()};var n="string"==typeof e?document.getElementById(e):e;m(n,"argument-error",{appName:t}),this.container=n,this.isVisible="invisible"!==this.params.size,this.isVisible?this.execute():this.container.addEventListener("click",this.clickHandler)}getResponse(){return this.checkIfDeleted(),this.responseToken}delete(){this.checkIfDeleted(),this.deleted=!0,this.timerId&&(clearTimeout(this.timerId),this.timerId=null),this.container.removeEventListener("click",this.clickHandler)}execute(){this.checkIfDeleted(),this.timerId||(this.timerId=window.setTimeout(()=>{this.responseToken=(e=>{var t=[],r="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let n=0;n<e;n++)t.push(r.charAt(Math.floor(Math.random()*r.length)));return t.join("")})(50);let{callback:e,"expired-callback":t}=this.params;if(e)try{e(this.responseToken)}catch(e){}this.timerId=window.setTimeout(()=>{if(this.timerId=null,this.responseToken=null,t)try{t()}catch(e){}this.isVisible&&this.execute()},6e4)},500))}checkIfDeleted(){if(this.deleted)throw new Error("reCAPTCHA mock was already deleted!")}}let da="NO_RECAPTCHA";class pa{constructor(e){this.type="recaptcha-enterprise",this.auth=na(e)}async verify(i="verify",e=!1){function s(e,t,r){let n=window.grecaptcha;bs(n)?n.enterprise.ready(()=>{n.enterprise.execute(e,{action:i}).then(e=>{t(e)}).catch(()=>{t(da)})}):r(Error("No reCAPTCHA enterprise script loaded."))}return this.auth.settings.appVerificationDisabledForTesting?(new ha).execute("siteKey",{action:"verify"}):new Promise((r,n)=>{(async i=>{if(!e){if(null==i.tenantId&&null!=i._agentRecaptchaConfig)return i._agentRecaptchaConfig.siteKey;if(null!=i.tenantId&&void 0!==i._tenantRecaptchaConfigs[i.tenantId])return i._tenantRecaptchaConfigs[i.tenantId].siteKey}return new Promise(async(r,n)=>{Ts(i,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then(e=>{var t;if(void 0!==e.recaptchaKey)return t=new Is(e),null==i.tenantId?i._agentRecaptchaConfig=t:i._tenantRecaptchaConfigs[i.tenantId]=t,r(t.siteKey);n(new Error("recaptcha Enterprise site key undefined"))}).catch(e=>{n(e)})})})(this.auth).then(t=>{if(!e&&bs(window.grecaptcha))s(t,r,n);else if("undefined"==typeof window)n(new Error("RecaptchaVerifier is only supported in browser"));else{let e=sa.recaptchaEnterpriseScript;0!==e.length&&(e+=t),aa(e).then(()=>{s(t,r,n)}).catch(e=>{n(e)})}}).catch(e=>{n(e)})})}}async function fa(e,t,r,n=!1,i=!1){var s=new pa(e);let a;if(i)a=da;else try{a=await s.verify(r)}catch(e){a=await s.verify(r,!0)}var o,l,s={...t};return"mfaSmsEnrollment"===r||"mfaSmsSignIn"===r?"phoneEnrollmentInfo"in s?(l=s.phoneEnrollmentInfo.phoneNumber,o=s.phoneEnrollmentInfo.recaptchaToken,Object.assign(s,{phoneEnrollmentInfo:{phoneNumber:l,recaptchaToken:o,captchaResponse:a,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})):"phoneSignInInfo"in s&&(l=s.phoneSignInInfo.recaptchaToken,Object.assign(s,{phoneSignInInfo:{recaptchaToken:l,captchaResponse:a,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})):(n?Object.assign(s,{captchaResp:a}):Object.assign(s,{captchaResponse:a}),Object.assign(s,{clientType:"CLIENT_TYPE_WEB"}),Object.assign(s,{recaptchaVersion:"RECAPTCHA_ENTERPRISE"})),s}async function ga(r,n,i,s,e){var t;return"EMAIL_PASSWORD_PROVIDER"===e?r._getRecaptchaConfig()?.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")?(t=await fa(r,n,i,"getOobCode"===i),s(r,t)):s(r,n).catch(async e=>{var t;return"auth/missing-recaptcha-token"===e.code?(console.log(i+" is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow."),t=await fa(r,n,i,"getOobCode"===i),s(r,t)):Promise.reject(e)}):"PHONE_PROVIDER"===e?r._getRecaptchaConfig()?.isProviderEnabled("PHONE_PROVIDER")?(t=await fa(r,n,i),s(r,t).catch(async e=>{var t;if("AUDIT"===r._getRecaptchaConfig()?.getProviderEnforcementState("PHONE_PROVIDER")&&("auth/missing-recaptcha-token"===e.code||"auth/invalid-app-credential"===e.code))return console.log(`Failed to verify with reCAPTCHA Enterprise. Automatically triggering the reCAPTCHA v2 flow to complete the ${i} flow.`),t=await fa(r,n,i,!1,!0),s(r,t);return Promise.reject(e)})):(t=await fa(r,n,i,!1,!0),s(r,t)):Promise.reject(e+" provider is not supported.")}function ma(e,t,r){var n=na(e),i=(m(/^https?:\/\//.test(t),n,"invalid-emulator-scheme"),!!r?.disableWarnings),s=va(t),{host:a,port:o}=(e=>{var t,r=va(e);return(r=/(\/\/)?([^?#/]+)/.exec(e.substr(r.length)))?(r=r[2].split("@").pop()||"",(t=/^(\[[^\]]+\])(:|$)/.exec(r))?{host:t=t[1],port:_a(r.substr(t.length+1))}:([t,r]=r.split(":"),{host:t,port:_a(r)})):{host:"",port:null}})(t),l=null===o?"":":"+o,h={url:s+`//${a}${l}/`},o=Object.freeze({host:a,port:o,protocol:s.replace(":",""),options:Object.freeze({disableWarnings:i})});function c(){var 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)}n._canInitEmulator?(n.config.emulator=h,n.emulatorConfig=o,n.settings.appVerificationDisabledForTesting=!0,je(a)?ze(s+"//"+a+l):i||("undefined"!=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."),"undefined"!=typeof window&&"undefined"!=typeof document&&("loading"===document.readyState?window.addEventListener("DOMContentLoaded",c):c()))):(m(n.config.emulator&&n.emulatorConfig,n,"emulator-config-failed"),m(Ee(h,n.config.emulator)&&Ee(o,n.emulatorConfig),n,"emulator-config-failed"))}function va(e){var t=e.indexOf(":");return t<0?"":e.substr(0,t+1)}function _a(e){var t;return!e||(t=Number(e),isNaN(t))?null:t}class ya{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return rs("not implemented")}_getIdTokenResponse(e){return rs("not implemented")}_linkToIdToken(e,t){return rs("not implemented")}_getReauthenticationResolver(e){return rs("not implemented")}}async function wa(e,t){return fs(e,"POST","/v1/accounts:resetPassword",ps(e,t))}async function ba(e,t){return fs(e,"POST","/v1/accounts:signUp",t)}async function Ia(e,t){return ms(e,"POST","/v1/accounts:signInWithPassword",ps(e,t))}async function Ta(e,t){return fs(e,"POST","/v1/accounts:sendOobCode",ps(e,t))}async function Ea(e,t){return Ta(e,t)}async function Ca(e,t){return Ta(e,t)}class Sa extends ya{constructor(e,t,r,n=null){super("password",r),this._email=e,this._password=t,this._tenantId=n}static _fromEmailAndPassword(e,t){return new Sa(e,t,"password")}static _fromEmailAndCode(e,t,r=null){return new Sa(e,t,"emailLink",r)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){var t="string"==typeof e?JSON.parse(e):e;if(t?.email&&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 ga(e,{returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signInWithPassword",Ia,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return(async(e,t)=>ms(e,"POST","/v1/accounts:signInWithEmailLink",ps(e,t)))(e,{email:this._email,oobCode:this._password});default:Yi(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":return ga(e,{idToken:t,returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",ba,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return(async(e,t)=>ms(e,"POST","/v1/accounts:signInWithEmailLink",ps(e,t)))(e,{idToken:t,email:this._email,oobCode:this._password});default:Yi(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function ka(e,t){return ms(e,"POST","/v1/accounts:signInWithIdp",ps(e,t))}class Aa extends ya{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){var t=new Aa(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&&(t.pendingToken=e.pendingToken)):e.oauthToken&&e.oauthTokenSecret?(t.accessToken=e.oauthToken,t.secret=e.oauthTokenSecret):Yi("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){var t;let{providerId:r,signInMethod:n,...i}="string"==typeof e?JSON.parse(e):e;return r&&n?((t=new Aa(r,n)).idToken=i.idToken||void 0,t.accessToken=i.accessToken||void 0,t.secret=i.secret,t.nonce=i.nonce,t.pendingToken=i.pendingToken||null,t):null}_getIdTokenResponse(e){return ka(e,this.buildRequest())}_linkToIdToken(e,t){var r=this.buildRequest();return r.idToken=t,ka(e,r)}_getReauthenticationResolver(e){var t=this.buildRequest();return t.autoCreate=!1,ka(e,t)}buildRequest(){var e,t={requestUri:"http://localhost",returnSecureToken:!0};return this.pendingToken?t.pendingToken=this.pendingToken:(e={},this.idToken&&(e.id_token=this.idToken),this.accessToken&&(e.access_token=this.accessToken),this.secret&&(e.oauth_token_secret=this.secret),e.providerId=this.providerId,this.nonce&&!this.pendingToken&&(e.nonce=this.nonce),t.postBody=Se(e)),t}}async function Na(e,t){return fs(e,"POST","/v1/accounts:sendVerificationCode",ps(e,t))}let Ra={USER_NOT_FOUND:"user-not-found"};class Pa extends ya{constructor(e){super("phone","phone"),this.params=e}static _fromVerification(e,t){return new Pa({verificationId:e,verificationCode:t})}static _fromTokenResponse(e,t){return new Pa({phoneNumber:e,temporaryProof:t})}_getIdTokenResponse(e){return(async(e,t)=>ms(e,"POST","/v1/accounts:signInWithPhoneNumber",ps(e,t)))(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return(async(e,t)=>{var r=await ms(e,"POST","/v1/accounts:signInWithPhoneNumber",ps(e,t));if(r.temporaryProof)throw ys(e,"account-exists-with-different-credential",r);return r})(e,{idToken:t,...this._makeVerificationRequest()})}_getReauthenticationResolver(e){return(async(e,t)=>ms(e,"POST","/v1/accounts:signInWithPhoneNumber",ps(e,{...t,operation:"REAUTH"}),Ra))(e,this._makeVerificationRequest())}_makeVerificationRequest(){var{temporaryProof:e,phoneNumber:t,verificationId:r,verificationCode:n}=this.params;return e&&t?{temporaryProof:e,phoneNumber:t}:{sessionInfo:r,code:n}}toJSON(){var e={providerId:this.providerId};return this.params.phoneNumber&&(e.phoneNumber=this.params.phoneNumber),this.params.temporaryProof&&(e.temporaryProof=this.params.temporaryProof),this.params.verificationCode&&(e.verificationCode=this.params.verificationCode),this.params.verificationId&&(e.verificationId=this.params.verificationId),e}static fromJSON(e){var{verificationId:t,verificationCode:r,phoneNumber:n,temporaryProof:i}=e="string"==typeof e?JSON.parse(e):e;return r||t||n||i?new Pa({verificationId:t,verificationCode:r,phoneNumber:n,temporaryProof:i}):null}}class Da{constructor(e){var t=ke(Ae(e)),r=t.apiKey??null,n=t.oobCode??null,i=(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}})(t.mode??null);m(r&&n&&i,"argument-error"),this.apiKey=r,this.operation=i,this.code=n,this.continueUrl=t.continueUrl??null,this.languageCode=t.lang??null,this.tenantId=t.tenantId??null}static parseLink(e){t=ke(Ae(e=e)).link,r=t?ke(Ae(t)).deep_link_id:null;var t,r,n=((n=ke(Ae(e)).deep_link_id)?ke(Ae(n)).link:null)||n||r||t||e;try{return new Da(n)}catch{return null}}}class xa{constructor(){this.providerId=xa.PROVIDER_ID}static credential(e,t){return Sa._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){var r=Da.parseLink(t);return m(r,"argument-error"),Sa._fromEmailAndCode(e,r.code,r.tenantId)}}xa.PROVIDER_ID="password",xa.EMAIL_PASSWORD_SIGN_IN_METHOD="password",xa.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class Oa{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 Ma extends Oa{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class La extends Ma{static credentialFromJSON(e){var t="string"==typeof e?JSON.parse(e):e;return m("providerId"in t&&"signInMethod"in t,"argument-error"),Aa._fromParams(t)}credential(e){return this._credential({...e,nonce:e.rawNonce})}_credential(e){return m(e.idToken||e.accessToken,"argument-error"),Aa._fromParams({...e,providerId:this.providerId,signInMethod:this.providerId})}static credentialFromResult(e){return La.oauthCredentialFromTaggedObject(e)}static credentialFromError(e){return La.oauthCredentialFromTaggedObject(e.customData||{})}static oauthCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthIdToken:t,oauthAccessToken:r,oauthTokenSecret:n,pendingToken:i,nonce:s,providerId:a}=e;if(!(r||n||t||i))return null;if(!a)return null;try{return new La(a)._credential({idToken:t,accessToken:r,nonce:s,pendingToken:i})}catch(e){return null}}}class Fa extends Ma{constructor(){super("facebook.com")}static credential(e){return Aa._fromParams({providerId:Fa.PROVIDER_ID,signInMethod:Fa.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return Fa.credentialFromTaggedObject(e)}static credentialFromError(e){return Fa.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return Fa.credential(e.oauthAccessToken)}catch{return null}}}Fa.FACEBOOK_SIGN_IN_METHOD="facebook.com",Fa.PROVIDER_ID="facebook.com";class Ua extends Ma{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return Aa._fromParams({providerId:Ua.PROVIDER_ID,signInMethod:Ua.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return Ua.credentialFromTaggedObject(e)}static credentialFromError(e){return Ua.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthIdToken:t,oauthAccessToken:r}=e;if(!t&&!r)return null;try{return Ua.credential(t,r)}catch{return null}}}Ua.GOOGLE_SIGN_IN_METHOD="google.com",Ua.PROVIDER_ID="google.com";class Va extends Ma{constructor(){super("github.com")}static credential(e){return Aa._fromParams({providerId:Va.PROVIDER_ID,signInMethod:Va.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return Va.credentialFromTaggedObject(e)}static credentialFromError(e){return Va.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return Va.credential(e.oauthAccessToken)}catch{return null}}}Va.GITHUB_SIGN_IN_METHOD="github.com",Va.PROVIDER_ID="github.com";class qa extends ya{constructor(e,t){super(e,e),this.pendingToken=t}_getIdTokenResponse(e){return ka(e,this.buildRequest())}_linkToIdToken(e,t){var r=this.buildRequest();return r.idToken=t,ka(e,r)}_getReauthenticationResolver(e){var t=this.buildRequest();return t.autoCreate=!1,ka(e,t)}toJSON(){return{signInMethod:this.signInMethod,providerId:this.providerId,pendingToken:this.pendingToken}}static fromJSON(e){var{providerId:t,signInMethod:r,pendingToken:n}="string"==typeof e?JSON.parse(e):e;return t&&r&&n&&t===r?new qa(t,n):null}static _create(e,t){return new qa(e,t)}buildRequest(){return{requestUri:"http://localhost",returnSecureToken:!0,pendingToken:this.pendingToken}}}class Ba extends Oa{constructor(e){m(e.startsWith("saml."),"argument-error"),super(e)}static credentialFromResult(e){return Ba.samlCredentialFromTaggedObject(e)}static credentialFromError(e){return Ba.samlCredentialFromTaggedObject(e.customData||{})}static credentialFromJSON(e){var t=qa.fromJSON(e);return m(t,"argument-error"),t}static samlCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{pendingToken:t,providerId:r}=e;if(!t||!r)return null;try{return qa._create(r,t)}catch(e){return null}}}class ja extends Ma{constructor(){super("twitter.com")}static credential(e,t){return Aa._fromParams({providerId:ja.PROVIDER_ID,signInMethod:ja.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return ja.credentialFromTaggedObject(e)}static credentialFromError(e){return ja.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthAccessToken:t,oauthTokenSecret:r}=e;if(!t||!r)return null;try{return ja.credential(t,r)}catch{return null}}}async function za(e,t){return ms(e,"POST","/v1/accounts:signUp",ps(e,t))}ja.TWITTER_SIGN_IN_METHOD="twitter.com",ja.PROVIDER_ID="twitter.com";class Ka{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,r,n=!1){var i=await Ls._fromIdTokenResponse(e,r,n),s=Wa(r);return new Ka({user:i,providerId:s,_tokenResponse:r,operationType:t})}static async _forOperation(e,t,r){await e._updateTokensIfNecessary(r,!0);var n=Wa(r);return new Ka({user:e,providerId:n,_tokenResponse:r,operationType:t})}}function Wa(e){return e.providerId||("phoneNumber"in e?"phone":null)}class Ha extends fe{constructor(e,t,r,n){super(t.code,t.message),this.operationType=r,this.user=n,Object.setPrototypeOf(this,Ha.prototype),this.customData={appName:e.name,tenantId:e.tenantId??void 0,_serverResponse:t.customData._serverResponse,operationType:r}}static _fromErrorAndOperation(e,t,r,n){return new Ha(e,t,r,n)}}function Ga(t,r,e,n){return("reauthenticate"===r?e._getReauthenticationResolver(t):e._getIdTokenResponse(t)).catch(e=>{if("auth/multi-factor-auth-required"===e.code)throw Ha._fromErrorAndOperation(t,e,r,n);throw e})}function $a(e){return new Set(e.map(({providerId:e})=>e).filter(e=>!!e))}async function Qa(e,t){var r=w(e),n=(await Ja(!0,r,t),e=r.auth,t={idToken:await r.getIdToken(),deleteProvider:[t]},await fs(e,"POST","/v1/accounts:update",t)).providerUserInfo;let i=$a(n||[]);return r.providerData=r.providerData.filter(e=>i.has(e.providerId)),i.has("phone")||(r.phoneNumber=null),await r.auth._persistUserIfCurrent(r),r}async function Ya(e,t,r=!1){var n=await Ns(e,t._linkToIdToken(e.auth,await e.getIdToken()),r);return Ka._forOperation(e,"link",n)}async function Ja(e,t,r){await Ds(t);var n=!1===e?"provider-already-linked":"no-such-provider";m($a(t.providerData).has(r)===e,t.auth,n)}async function Xa(e,t,r=!1){var n=e.auth;if(h(n.app))return Promise.reject(Zi(n));var i="reauthenticate";try{var s=await Ns(e,Ga(n,i,t,e),r),a=(m(s.idToken,n,"internal-error"),ks(s.idToken)),o=(m(a,n,"internal-error"),a).sub;return m(e.uid===o,n,"user-mismatch"),Ka._forOperation(e,i,s)}catch(e){throw"auth/user-not-found"===e?.code&&Yi(n,"user-mismatch"),e}}async function Za(e,t,r=!1){var n;return h(e.app)?Promise.reject(Zi(e)):(n=await Ga(e,"signIn",t),n=await Ka._fromIdTokenResponse(e,"signIn",n),r||await e._updateCurrentUser(n.user),n)}async function eo(e,t){return Za(na(e),t)}async function to(e,t){var r=w(e);return await Ja(!1,r,t.providerId),Ya(r,t)}async function ro(e,t){return Xa(w(e),t)}async function no(e,t){var r,n;return h(e.app)?Promise.reject(Zi(e)):(n=await ms(r=na(e),"POST","/v1/accounts:signInWithCustomToken",ps(r,{token:t,returnSecureToken:!0})),n=await Ka._fromIdTokenResponse(r,"signIn",n),await r._updateCurrentUser(n.user),n)}class io{constructor(e,t){this.factorId=e,this.uid=t.mfaEnrollmentId,this.enrollmentTime=new Date(t.enrolledAt).toUTCString(),this.displayName=t.displayName}static _fromServerResponse(e,t){return"phoneInfo"in t?so._fromServerResponse(e,t):"totpInfo"in t?ao._fromServerResponse(e,t):Yi(e,"internal-error")}}class so extends io{constructor(e){super("phone",e),this.phoneNumber=e.phoneInfo}static _fromServerResponse(e,t){return new so(t)}}class ao extends io{constructor(e){super("totp",e)}static _fromServerResponse(e,t){return new ao(t)}}function oo(e,t,r){m(0<r.url?.length,e,"invalid-continue-uri"),m(void 0===r.dynamicLinkDomain||0<r.dynamicLinkDomain.length,e,"invalid-dynamic-link-domain"),m(void 0===r.linkDomain||0<r.linkDomain.length,e,"invalid-hosting-link-domain"),t.continueUrl=r.url,t.dynamicLinkDomain=r.dynamicLinkDomain,t.linkDomain=r.linkDomain,t.canHandleCodeInApp=r.handleCodeInApp,r.iOS&&(m(0<r.iOS.bundleId.length,e,"missing-ios-bundle-id"),t.iOSBundleId=r.iOS.bundleId),r.android&&(m(0<r.android.packageName.length,e,"missing-android-pkg-name"),t.androidInstallApp=r.android.installApp,t.androidMinimumVersionCode=r.android.minimumVersion,t.androidPackageName=r.android.packageName)}async function lo(e){var t=na(e);t._getPasswordPolicyInternal()&&await t._updatePasswordPolicy()}async function ho(e,t){await fs(e=w(e),"POST","/v1/accounts:update",ps(e,{oobCode:t}))}async function co(e,t){var r=w(e),n=await wa(r,{oobCode:t}),i=n.requestType;switch(m(i,r,"internal-error"),i){case"EMAIL_SIGNIN":break;case"VERIFY_AND_CHANGE_EMAIL":m(n.newEmail,r,"internal-error");break;case"REVERT_SECOND_FACTOR_ADDITION":m(n.mfaInfo,r,"internal-error");default:m(n.email,r,"internal-error")}let s=null;return n.mfaInfo&&(s=io._fromServerResponse(na(r),n.mfaInfo)),{data:{email:("VERIFY_AND_CHANGE_EMAIL"===n.requestType?n.newEmail:n.email)||null,previousEmail:("VERIFY_AND_CHANGE_EMAIL"===n.requestType?n.email:n.newEmail)||null,multiFactorInfo:s},operation:i}}async function uo(e,t){var r=ss()?is():"http://localhost",r=(await fs(e=w(e),"POST","/v1/accounts:createAuthUri",ps(e,{identifier:t,continueUri:r}))).signinMethods;return r||[]}async function po(e,t){var r=w(e),n={requestType:"VERIFY_EMAIL",idToken:await e.getIdToken()},r=(t&&oo(r.auth,n,t),await Ta(r.auth,n)).email;r!==e.email&&await e.reload()}async function fo(e,t,r){var n=w(e),i={requestType:"VERIFY_AND_CHANGE_EMAIL",idToken:await e.getIdToken(),newEmail:t},n=(r&&oo(n.auth,i,r),await Ta(n.auth,i)).email;n!==e.email&&await e.reload()}async function go(e,{displayName:t,photoURL:r}){var n,i,s;void 0===t&&void 0===r||(i=await(n=w(e)).getIdToken(),i=await Ns(n,(async(e,t)=>fs(e,"POST","/v1/accounts:update",t))(n.auth,{idToken:i,displayName:t,photoUrl:r,returnSecureToken:!0})),n.displayName=i.displayName||null,n.photoURL=i.photoUrl||null,(s=n.providerData.find(({providerId:e})=>"password"===e))&&(s.displayName=n.displayName,s.photoURL=n.photoURL),await n._updateTokensIfNecessary(i))}async function mo(e,t,r){var n=e.auth,i={idToken:await e.getIdToken(),returnSecureToken:!0},n=(t&&(i.email=t),r&&(i.password=r),await Ns(e,(async(e,t)=>fs(e,"POST","/v1/accounts:update",t))(n,i)));await e._updateTokensIfNecessary(n,!0)}class vo{constructor(e,t,r={}){this.isNewUser=e,this.providerId=t,this.profile=r}}class _o extends vo{constructor(e,t,r,n){super(e,t,r),this.username=n}}class yo extends vo{constructor(e,t){super(e,"facebook.com",t)}}class wo extends _o{constructor(e,t){super(e,"github.com",t,"string"==typeof t?.login?t?.login:null)}}class bo extends vo{constructor(e,t){super(e,"google.com",t)}}class Io extends _o{constructor(e,t,r){super(e,"twitter.com",t,r)}}function To(e){var{user:t,_tokenResponse:r}=e;if(t.isAnonymous&&!r)return{providerId:null,isNewUser:!1,profile:null};var n=r;if(!n)return null;var i=n.providerId,s=n.rawUserInfo?JSON.parse(n.rawUserInfo):{},a=n.isNewUser||"identitytoolkit#SignupNewUserResponse"===n.kind;if(!i&&n?.idToken){t=ks(n.idToken)?.firebase?.sign_in_provider;if(t)return t="anonymous"!==t&&"custom"!==t?t:null,new vo(a,t)}if(!i)return null;switch(i){case"facebook.com":return new yo(a,s);case"github.com":return new wo(a,s);case"google.com":return new bo(a,s);case"twitter.com":return new Io(a,s,n.screenName||null);case"custom":case"anonymous":return new vo(a,null);default:return new vo(a,i,s)}}class Eo{constructor(e,t,r){this.type=e,this.credential=t,this.user=r}static _fromIdtoken(e,t){return new Eo("enroll",e,t)}static _fromMfaPendingCredential(e){return new Eo("signin",e)}toJSON(){return{multiFactorSession:{["enroll"===this.type?"idToken":"pendingCredential"]:this.credential}}}static fromJSON(e){if(e?.multiFactorSession){if(e.multiFactorSession?.pendingCredential)return Eo._fromMfaPendingCredential(e.multiFactorSession.pendingCredential);if(e.multiFactorSession?.idToken)return Eo._fromIdtoken(e.multiFactorSession.idToken)}return null}}class Co{constructor(e,t,r){this.session=e,this.hints=t,this.signInResolver=r}static _fromError(e,i){let s=na(e),a=i.customData._serverResponse;var t=(a.mfaInfo||[]).map(e=>io._fromServerResponse(s,e));m(a.mfaPendingCredential,s,"internal-error");let o=Eo._fromMfaPendingCredential(a.mfaPendingCredential);return new Co(o,t,async e=>{var t=await e._process(s,o),r=(delete a.mfaInfo,delete a.mfaPendingCredential,{...a,idToken:t.idToken,refreshToken:t.refreshToken});switch(i.operationType){case"signIn":var n=await Ka._fromIdTokenResponse(s,i.operationType,r);return await s._updateCurrentUser(n.user),n;case"reauthenticate":return m(i.user,s,"internal-error"),Ka._forOperation(i.user,i.operationType,r);default:Yi(s,"internal-error")}})}async resolveSignIn(e){return this.signInResolver(e)}}function So(e,t){return fs(e,"POST","/v2/accounts/mfaEnrollment:start",ps(e,t))}class ko{constructor(t){this.user=t,this.enrolledFactors=[],t._onReload(e=>{e.mfaInfo&&(this.enrolledFactors=e.mfaInfo.map(e=>io._fromServerResponse(t.auth,e)))})}static _fromUser(e){return new ko(e)}async getSession(){return Eo._fromIdtoken(await this.user.getIdToken(),this.user)}async enroll(e,t){var r=e,n=await this.getSession(),r=await Ns(this.user,r._process(this.user.auth,n,t));return await this.user._updateTokensIfNecessary(r),this.user.reload()}async unenroll(e){let t="string"==typeof e?e:e.uid;var r,n,i=await this.user.getIdToken();try{var s=await Ns(this.user,(r=this.user.auth,n={idToken:i,mfaEnrollmentId:t},fs(r,"POST","/v2/accounts/mfaEnrollment:withdraw",ps(r,n))));this.enrolledFactors=this.enrolledFactors.filter(({uid:e})=>e!==t),await this.user._updateTokensIfNecessary(s),await this.user.reload()}catch(e){throw e}}}let Ao=new WeakMap;let No="__sak";class Ro{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(No,"1"),this.storage.removeItem(No),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){var 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 Po extends Ro{constructor(){super(()=>window.localStorage,"LOCAL"),this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t),this.listeners={},this.localCache={},this.pollTimer=null,this.fallbackToPolling=Xs(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(var t of Object.keys(this.listeners)){var r=this.storage.getItem(t),n=this.localCache[t];r!==n&&e(t,n,r)}}onStorageEvent(e,r=!1){if(e.key){let t=e.key;r?this.detachListener():this.stopPolling();var n=()=>{var e=this.storage.getItem(t);!r&&this.localCache[t]===e||this.notifyListeners(t,e)},i=this.storage.getItem(t);oe()&&10===document.documentMode&&i!==e.newValue&&e.newValue!==e.oldValue?setTimeout(n,10):n()}else this.forAllChangedKeys((e,t,r)=>{this.notifyListeners(e,r)})}notifyListeners(e,t){this.localCache[e]=t;var r=this.listeners[e];if(r)for(var n of Array.from(r))n(t&&JSON.parse(t))}startPolling(){this.stopPolling(),this.pollTimer=setInterval(()=>{this.forAllChangedKeys((e,t,r)=>{this.onStorageEvent(new StorageEvent("storage",{key:e,oldValue:t,newValue:r}),!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){var t=await super._get(e);return this.localCache[e]=JSON.stringify(t),t}async _remove(e){await super._remove(e),delete this.localCache[e]}}Po.type="LOCAL";let Do=Po;class xo extends Ro{constructor(){super(()=>window.sessionStorage,"SESSION")}_addListener(e,t){}_removeListener(e,t){}}xo.type="SESSION";let Oo=xo;class Mo{constructor(e){this.eventTarget=e,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(t){var e=this.receivers.find(e=>e.isListeningto(t));return e||(e=new Mo(t),this.receivers.push(e),e)}isListeningto(e){return this.eventTarget===e}async handleEvent(e){let t=e,{eventId:r,eventType:n,data:i}=t.data;var s=this.handlersMap[n];s?.size&&(t.ports[0].postMessage({status:"ack",eventId:r,eventType:n}),s=Array.from(s).map(async e=>e(t.origin,i)),s=await Promise.all(s.map(async e=>{try{return{fulfilled:!0,value:await e}}catch(e){return{fulfilled:!1,reason:e}}})),t.ports[0].postMessage({status:"done",eventId:r,eventType:n,response:s}))}_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 Lo(e="",t=10){let r="";for(let n=0;n<t;n++)r+=Math.floor(10*Math.random());return e+r}Mo.receivers=[];class Fo{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,a=50){let o="undefined"!=typeof MessageChannel?new MessageChannel:null;if(!o)throw new Error("connection_unavailable");let l,h;return new Promise((r,n)=>{let i=Lo("",20),s=(o.port1.start(),setTimeout(()=>{n(new Error("unsupported_event"))},a));h={messageChannel:o,onMessage(e){var t=e;if(t.data.eventId===i)switch(t.data.status){case"ack":clearTimeout(s),l=setTimeout(()=>{n(new Error("timeout"))},3e3);break;case"done":clearTimeout(l),r(t.data.response);break;default:clearTimeout(s),clearTimeout(l),n(new Error("invalid_response"))}}},this.handlers.add(h),o.port1.addEventListener("message",h.onMessage),this.target.postMessage({eventType:e,eventId:i,data:t},[o.port2])}).finally(()=>{h&&this.removeMessageHandler(h)})}}function Uo(){return window}function Vo(){return void 0!==Uo().WorkerGlobalScope&&"function"==typeof Uo().importScripts}let qo="firebaseLocalStorageDb",Bo="firebaseLocalStorage",jo="fbase_key";class zo{constructor(e){this.request=e}toPromise(){return new Promise((e,t)=>{this.request.addEventListener("success",()=>{e(this.request.result)}),this.request.addEventListener("error",()=>{t(this.request.error)})})}}function Ko(e,t){return e.transaction([Bo],t?"readwrite":"readonly").objectStore(Bo)}function Wo(){let n=indexedDB.open(qo,1);return new Promise((t,r)=>{n.addEventListener("error",()=>{r(n.error)}),n.addEventListener("upgradeneeded",()=>{var e=n.result;try{e.createObjectStore(Bo,{keyPath:jo})}catch(e){r(e)}}),n.addEventListener("success",async()=>{var e=n.result;e.objectStoreNames.contains(Bo)?t(e):(e.close(),e=indexedDB.deleteDatabase(qo),await new zo(e).toPromise(),t(await Wo()))})})}async function Ho(e,t,r){var n=Ko(e,!0).put({fbase_key:t,value:r});return new zo(n).toPromise()}function Go(e,t){var r=Ko(e,!0).delete(t);return new zo(r).toPromise()}class $o{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 Wo()),this.db}async _withRetries(e){let t=0;for(;;)try{return await e(await this._openDb())}catch(e){if(3<t++)throw e;this.db&&(this.db.close(),this.db=void 0)}}async initializeServiceWorkerMessaging(){return Vo()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=Mo._getInstance(Vo()?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;this.activeServiceWorker=await(async()=>{if(!navigator?.serviceWorker)return null;try{return(await navigator.serviceWorker.ready).active}catch{return null}})(),this.activeServiceWorker&&(this.sender=new Fo(this.activeServiceWorker),e=await this.sender._send("ping",{},800))&&e[0]?.fulfilled&&e[0]?.value.includes("keyChanged")&&(this.serviceWorkerReceiverAvailable=!0)}async notifyServiceWorker(e){if(this.sender&&this.activeServiceWorker&&(navigator?.serviceWorker?.controller||null)===this.activeServiceWorker)try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch{}}async _isAvailable(){try{var e;return indexedDB?(await Ho(e=await Wo(),No,"1"),await Go(e,No),!0):!1}catch{}return!1}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites--}}async _set(t,r){return this._withPendingWrite(async()=>(await this._withRetries(e=>Ho(e,t,r)),this.localCache[t]=r,this.notifyServiceWorker(t)))}async _get(t){var e=await this._withRetries(e=>(async(e,t)=>{var r=Ko(e,!1).get(t);return void 0===(r=await new zo(r).toPromise())?null:r.value})(e,t));return this.localCache[t]=e}async _remove(t){return this._withPendingWrite(async()=>(await this._withRetries(e=>Go(e,t)),delete this.localCache[t],this.notifyServiceWorker(t)))}async _poll(){var e=await this._withRetries(e=>{var t=Ko(e,!1).getAll();return new zo(t).toPromise()});if(!e)return[];if(0!==this.pendingWrites)return[];var t,r=[],n=new Set;if(0!==e.length)for(var{fbase_key:i,value:s}of e)n.add(i),JSON.stringify(this.localCache[i])!==JSON.stringify(s)&&(this.notifyListeners(i,s),r.push(i));for(t of Object.keys(this.localCache))this.localCache[t]&&!n.has(t)&&(this.notifyListeners(t,null),r.push(t));return r}notifyListeners(e,t){this.localCache[e]=t;var r=this.listeners[e];if(r)for(var n of Array.from(r))n(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()}}$o.type="LOCAL";let Qo=$o;function Yo(e,t){return fs(e,"POST","/v2/accounts/mfaSignIn:start",ps(e,t))}let Jo=oa("rcb"),Xo=new os(3e4,6e4);class Zo{constructor(){this.hostLanguage="",this.counter=0,this.librarySeparatelyLoaded=!!Uo().grecaptcha?.render}load(i,s=""){var e;return m((e=s).length<=6&&/^\s*[a-zA-Z0-9\-]*\s*$/.test(e),i,"argument-error"),this.shouldResolveImmediately(s)&&ws(Uo().grecaptcha)?Promise.resolve(Uo().grecaptcha):new Promise((t,r)=>{let n=Uo().setTimeout(()=>{r(Ji(i,"network-request-failed"))},Xo.get());Uo()[Jo]=()=>{Uo().clearTimeout(n),delete Uo()[Jo];var e=Uo().grecaptcha;if(e&&ws(e)){let n=e.render;e.render=(e,t)=>{var r=n(e,t);return this.counter++,r},this.hostLanguage=s,t(e)}else r(Ji(i,"internal-error"))},aa(sa.recaptchaV2Script+"?"+Se({onload:Jo,render:"explicit",hl:s})).catch(()=>{clearTimeout(n),r(Ji(i,"internal-error"))})})}clearedOneInstance(){this.counter--}shouldResolveImmediately(e){return!!Uo().grecaptcha?.render&&(e===this.hostLanguage||0<this.counter||this.librarySeparatelyLoaded)}}class el{async load(e){return new la(e)}clearedOneInstance(){}}let tl="recaptcha",rl={theme:"light",type:"image"};class nl{constructor(e,t,r={...rl}){this.parameters=r,this.type=tl,this.destroyed=!1,this.widgetId=null,this.tokenChangeListeners=new Set,this.renderPromise=null,this.recaptcha=null,this.auth=na(e),this.isInvisible="invisible"===this.parameters.size,m("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment");var n="string"==typeof t?document.getElementById(t):t;m(n,this.auth,"argument-error"),this.container=n,this.parameters.callback=this.makeTokenCallback(this.parameters.callback),this._recaptchaLoader=new(this.auth.settings.appVerificationDisabledForTesting?el:Zo),this.validateStartingState()}async verify(){this.assertNotDestroyed();let e=await this.render(),n=this.getAssertedRecaptcha();var t=n.getResponse(e);return t||new Promise(t=>{let r=e=>{e&&(this.tokenChangeListeners.delete(r),t(e))};this.tokenChangeListeners.add(r),this.isInvisible&&n.execute(e)})}render(){try{this.assertNotDestroyed()}catch(e){return Promise.reject(e)}return this.renderPromise||(this.renderPromise=this.makeRenderPromise().catch(e=>{throw this.renderPromise=null,e})),this.renderPromise}_reset(){this.assertNotDestroyed(),null!==this.widgetId&&this.getAssertedRecaptcha().reset(this.widgetId)}clear(){this.assertNotDestroyed(),this.destroyed=!0,this._recaptchaLoader.clearedOneInstance(),this.isInvisible||this.container.childNodes.forEach(e=>{this.container.removeChild(e)})}validateStartingState(){m(!this.parameters.sitekey,this.auth,"argument-error"),m(this.isInvisible||!this.container.hasChildNodes(),this.auth,"argument-error"),m("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment")}makeTokenCallback(r){return t=>{var e;this.tokenChangeListeners.forEach(e=>e(t)),"function"==typeof r?r(t):"string"==typeof r&&"function"==typeof(e=Uo()[r])&&e(t)}}assertNotDestroyed(){m(!this.destroyed,this.auth,"internal-error")}async makeRenderPromise(){if(await this.init(),!this.widgetId){let e=this.container;var t;this.isInvisible||(t=document.createElement("div"),e.appendChild(t),e=t),this.widgetId=this.getAssertedRecaptcha().render(e,this.parameters)}return this.widgetId}async init(){m(ss()&&!Vo(),this.auth,"internal-error"),await(()=>{let t=null;return new Promise(e=>{"complete"===document.readyState?e():(t=()=>e(),window.addEventListener("load",t))}).catch(e=>{throw t&&window.removeEventListener("load",t),e})})(),this.recaptcha=await this._recaptchaLoader.load(this.auth,this.auth.languageCode||void 0);var e=await((await fs(this.auth,"GET","/v1/recaptchaParams")).recaptchaSiteKey||"");m(e,this.auth,"internal-error"),this.parameters.sitekey=e}getAssertedRecaptcha(){return m(this.recaptcha,this.auth,"internal-error"),this.recaptcha}}class il{constructor(e,t){this.verificationId=e,this.onConfirmation=t}confirm(e){var t=Pa._fromVerification(this.verificationId,e);return this.onConfirmation(t)}}async function sl(t,r,n){if(!t._getRecaptchaConfig())try{e=na(t),i=await Ts(e,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}),i=new Is(i),null==e.tenantId?e._agentRecaptchaConfig=i:e._tenantRecaptchaConfigs[e.tenantId]=i,await(!i.isAnyProviderEnabled()||!new pa(e).verify())}catch(e){console.log("Failed to initialize reCAPTCHA Enterprise config. Triggering the reCAPTCHA v2 verification.")}var e,i,s,a,o,l,h;try{let e;return("session"in(e="string"==typeof r?{phoneNumber:r}:r)?(s=e.session,"phoneNumber"in e?(m("enroll"===s.type,t,"internal-error"),a={idToken:s.credential,phoneEnrollmentInfo:{phoneNumber:e.phoneNumber,clientType:"CLIENT_TYPE_WEB"}},(await ga(t,a,"mfaSmsEnrollment",async(e,t)=>t.phoneEnrollmentInfo.captchaResponse===da?(m(n?.type===tl,e,"argument-error"),So(e,await al(e,t,n))):So(e,t),"PHONE_PROVIDER").catch(e=>Promise.reject(e))).phoneSessionInfo):(m("signin"===s.type,t,"internal-error"),m(o=e.multiFactorHint?.uid||e.multiFactorUid,t,"missing-multi-factor-info"),l={mfaPendingCredential:s.credential,mfaEnrollmentId:o,phoneSignInInfo:{clientType:"CLIENT_TYPE_WEB"}},(await ga(t,l,"mfaSmsSignIn",async(e,t)=>t.phoneSignInInfo.captchaResponse===da?(m(n?.type===tl,e,"argument-error"),Yo(e,await al(e,t,n))):Yo(e,t),"PHONE_PROVIDER").catch(e=>Promise.reject(e))).phoneResponseInfo)):(h={phoneNumber:e.phoneNumber,clientType:"CLIENT_TYPE_WEB"},await ga(t,h,"sendVerificationCode",async(e,t)=>t.captchaResponse===da?(m(n?.type===tl,e,"argument-error"),Na(e,await al(e,t,n))):Na(e,t),"PHONE_PROVIDER").catch(e=>Promise.reject(e)))).sessionInfo}finally{n?._reset()}}async function al(e,t,r){m(r.type===tl,e,"argument-error");var n,i,s,a,o=await r.verify(),l=(m("string"==typeof o,e,"argument-error"),{...t});return"phoneEnrollmentInfo"in l?(i=l.phoneEnrollmentInfo.phoneNumber,s=l.phoneEnrollmentInfo.captchaResponse,a=l.phoneEnrollmentInfo.clientType,n=l.phoneEnrollmentInfo.recaptchaVersion,Object.assign(l,{phoneEnrollmentInfo:{phoneNumber:i,recaptchaToken:o,captchaResponse:s,clientType:a,recaptchaVersion:n}})):"phoneSignInInfo"in l?(i=l.phoneSignInInfo.captchaResponse,s=l.phoneSignInInfo.clientType,a=l.phoneSignInInfo.recaptchaVersion,Object.assign(l,{phoneSignInInfo:{recaptchaToken:o,captchaResponse:i,clientType:s,recaptchaVersion:a}})):Object.assign(l,{recaptchaToken:o}),l}class ol{constructor(e){this.providerId=ol.PROVIDER_ID,this.auth=na(e)}verifyPhoneNumber(e,t){return sl(this.auth,e,w(t))}static credential(e,t){return Pa._fromVerification(e,t)}static credentialFromResult(e){var t=e;return ol.credentialFromTaggedObject(t)}static credentialFromError(e){return ol.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){var t,r;return e&&({phoneNumber:t,temporaryProof:r}=e,t)&&r?Pa._fromTokenResponse(t,r):null}}function ll(e,t){return t?Us(t):(m(e._popupRedirectResolver,e,"argument-error"),e._popupRedirectResolver)}ol.PROVIDER_ID="phone",ol.PHONE_SIGN_IN_METHOD="phone";class hl extends ya{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return ka(e,this._buildIdpRequest())}_linkToIdToken(e,t){return ka(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return ka(e,this._buildIdpRequest())}_buildIdpRequest(e){var 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 cl(e){return Za(e.auth,new hl(e),e.bypassAuthState)}function ul(e){var{auth:t,user:r}=e;return m(r,t,"internal-error"),Xa(r,new hl(e),e.bypassAuthState)}async function dl(e){var{auth:t,user:r}=e;return m(r,t,"internal-error"),Ya(r,new hl(e),e.bypassAuthState)}class pl{constructor(e,t,r,n,i=!1){this.auth=e,this.resolver=r,this.user=n,this.bypassAuthState=i,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){var{urlResponse:t,sessionId:r,postBody:n,tenantId:i,error:s,type:a}=e;if(s)this.reject(s);else{s={auth:this.auth,requestUri:t,sessionId:r,tenantId:i||void 0,postBody:n||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(a)(s))}catch(e){this.reject(e)}}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return cl;case"linkViaPopup":case"linkViaRedirect":return dl;case"reauthViaPopup":case"reauthViaRedirect":return ul;default:Yi(this.auth,"internal-error")}}resolve(e){ns(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){ns(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.reject(e),this.unregisterAndCleanUp()}unregisterAndCleanUp(){this.eventManager&&this.eventManager.unregisterConsumer(this),this.pendingPromise=null,this.cleanUp()}}let fl=new os(2e3,1e4);class gl extends pl{constructor(e,t,r,n,i){super(e,t,n,i),this.provider=r,this.authWindow=null,this.pollId=null,gl.currentPopupAction&&gl.currentPopupAction.cancel(),gl.currentPopupAction=this}async executeNotNull(){var e=await this.execute();return m(e,this.auth,"internal-error"),e}async onExecution(){ns(1===this.filter.length,"Popup operations only handle one event");var e=Lo();this.authWindow=await this.resolver._openPopup(this.auth,this.provider,this.filter[0],e),this.authWindow.associatedEvent=e,this.resolver._originValidation(this.auth).catch(e=>{this.reject(e)}),this.resolver._isIframeWebStorageSupported(this.auth,e=>{e||this.reject(Ji(this.auth,"web-storage-unsupported"))}),this.pollUserCancellation()}get eventId(){return this.authWindow?.associatedEvent||null}cancel(){this.reject(Ji(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,gl.currentPopupAction=null}pollUserCancellation(){let e=()=>{this.authWindow?.window?.closed?this.pollId=window.setTimeout(()=>{this.pollId=null,this.reject(Ji(this.auth,"popup-closed-by-user"))},8e3):this.pollId=window.setTimeout(e,fl.get())};e()}}gl.currentPopupAction=null;let ml="pendingRedirect",vl=new Map;class _l extends pl{constructor(e,t,r=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,r),this.eventId=null}async execute(){let t=vl.get(this.auth._key());if(!t){try{let e=await(async(e,t)=>{var r,n=Il(t),i=bl(e);return!!await i._isAvailable()&&(r="true"===await i._get(n),await i._remove(n),r)})(this.resolver,this.auth)?await super.execute():null;t=()=>Promise.resolve(e)}catch(e){t=()=>Promise.reject(e)}vl.set(this.auth._key(),t)}return this.bypassAuthState||vl.set(this.auth._key(),()=>Promise.resolve(null)),t()}async onAuthEvent(e){if("signInViaRedirect"===e.type)return super.onAuthEvent(e);if("unknown"===e.type)this.resolve(null);else if(e.eventId){var t=await this.auth._redirectUserForId(e.eventId);if(t)return this.user=t,super.onAuthEvent(e);this.resolve(null)}}async onExecution(){}cleanUp(){}}async function yl(e,t){return bl(e)._set(Il(t),"true")}function wl(e,t){vl.set(e._key(),t)}function bl(e){return Us(e._redirectPersistence)}function Il(e){return Bs(ml,e.config.apiKey,e.name)}function Tl(e,t,r){return(async(e,t,r)=>{var n,i;return h(e.app)?Promise.reject(Zi(e)):(n=na(e),es(e,t,Oa),await n._initializationPromise,await yl(i=ll(n,r),n),i._openRedirect(n,t,"signInViaRedirect"))})(e,t,r)}function El(e,t,r){return(async(e,t,r)=>{var n=w(e);if(es(n.auth,t,Oa),h(n.auth.app))return Promise.reject(Zi(n.auth));await n.auth._initializationPromise;var i=ll(n.auth,r),s=(await yl(i,n.auth),await kl(n));return i._openRedirect(n.auth,t,"reauthViaRedirect",s)})(e,t,r)}function Cl(e,t,r){return(async(e,t,r)=>{var n=w(e),i=(es(n.auth,t,Oa),await n.auth._initializationPromise,ll(n.auth,r)),s=(await Ja(!1,n,t.providerId),await yl(i,n.auth),await kl(n));return i._openRedirect(n.auth,t,"linkViaRedirect",s)})(e,t,r)}async function Sl(e,t,r=!1){var n,i;return h(e.app)?Promise.reject(Zi(e)):(i=ll(n=na(e),t),(i=await new _l(n,i,r).execute())&&!r&&(delete i.user._redirectEventId,await n._persistUserIfCurrent(i.user),await n._setRedirectUser(null,t)),i)}async function kl(e){var t=Lo(e.uid+":::");return e._redirectEventId=t,await e.auth._setRedirectUser(e),await e.auth._persistUserIfCurrent(e),t}class Al{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(t){if(this.hasEventBeenHandled(t))return!1;let r=!1;return this.consumers.forEach(e=>{this.isEventForConsumer(t,e)&&(r=!0,this.sendToConsumer(t,e),this.saveEventToCache(t))}),this.hasHandledPotentialRedirect||!(e=>{switch(e.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return 1;case"unknown":return Rl(e);default:return}})(t)||(this.hasHandledPotentialRedirect=!0,r)||(this.queuedRedirectEvent=t,r=!0),r}sendToConsumer(e,t){var r;e.error&&!Rl(e)?(r=e.error.code?.split("auth/")[1]||"internal-error",t.onError(Ji(this.auth,r))):t.onAuthEvent(e)}isEventForConsumer(e,t){var r=null===t.eventId||!!e.eventId&&e.eventId===t.eventId;return t.filter.includes(e.type)&&r}hasEventBeenHandled(e){return 6e5<=Date.now()-this.lastProcessedEventTime&&this.cachedEventUids.clear(),this.cachedEventUids.has(Nl(e))}saveEventToCache(e){this.cachedEventUids.add(Nl(e)),this.lastProcessedEventTime=Date.now()}}function Nl(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter(e=>e).join("-")}function Rl({type:e,error:t}){return"unknown"===e&&"auth/no-auth-event"===t?.code}async function Pl(e,t={}){return fs(e,"GET","/v1/projects",t)}let Dl=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,xl=/^https?/;async function Ol(e){if(!e.config.emulator){var t,r=(await Pl(e)).authorizedDomains;for(t of r)try{if((e=>{var t,r=is(),{protocol:n,hostname:i}=new URL(r);return e.startsWith("chrome-extension://")?""===(t=new URL(e)).hostname&&""===i?"chrome-extension:"===n&&e.replace("chrome-extension://","")===r.replace("chrome-extension://",""):"chrome-extension:"===n&&t.hostname===i:xl.test(n)&&(Dl.test(e)?i===e:(r=e.replace(/\./g,"\\."),(t=new RegExp("^(.+\\."+r+"|"+r+")$","i")).test(i)))})(t))return}catch{}Yi(e,"unauthorized-domain")}}let Ml=new os(3e4,6e4);function Ll(){var t=Uo().___jsl;if(t?.H)for(var r of Object.keys(t.H))if(t.H[r].r=t.H[r].r||[],t.H[r].L=t.H[r].L||[],t.H[r].r=[...t.H[r].L],t.CP)for(let e=0;e<t.CP.length;e++)t.CP[e]=null}function Fl(i){return new Promise((e,t)=>{function r(){Ll(),gapi.load("gapi.iframes",{callback:()=>{e(gapi.iframes.getContext())},ontimeout:()=>{Ll(),t(Ji(i,"network-request-failed"))},timeout:Ml.get()})}if(Uo().gapi?.iframes?.Iframe)e(gapi.iframes.getContext());else{var n;if(!Uo().gapi?.load)return n=oa("iframefcb"),Uo()[n]=()=>{gapi.load?r():t(Ji(i,"network-request-failed"))},aa(sa.gapiScript+"?onload="+n).catch(e=>t(e));r()}}).catch(e=>{throw Ul=null,e})}let Ul=null;let Vl=new os(5e3,15e3),ql="__/auth/iframe",Bl="emulator/auth/iframe",jl={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},zl=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);async function Kl(a){e=a;var e,t,r,n=await(Ul=Ul||Fl(e)),i=Uo().gapi;return m(i,a,"internal-error"),n.open({where:document.body,url:(m((n=(e=a).config).authDomain,e,"auth-domain-config-required"),t=n.emulator?ls(n,Bl):`https://${e.config.authDomain}/`+ql,n={apiKey:n.apiKey,appName:e.name,v:Ft},(r=zl.get(e.config.apiHost))&&(n.eid=r),(r=e._getFrameworks()).length&&(n.fw=r.join(",")),t+"?"+Se(n).slice(1)),messageHandlersFilter:i.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:jl,dontclear:!0},s=>new Promise(async(e,t)=>{await s.restyle({setHideOnLeave:!1});let r=Ji(a,"network-request-failed"),n=Uo().setTimeout(()=>{t(r)},Vl.get());function i(){Uo().clearTimeout(n),e(s)}s.ping(i).then(i,()=>{t(r)})}))}let Wl={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"};class Hl{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch(e){}}}function Gl(e,t,r,n=500,i=600){var s=Math.max((window.screen.availHeight-i)/2,0).toString(),a=Math.max((window.screen.availWidth-n)/2,0).toString();let o="";var l,s={...Wl,width:n.toString(),height:i.toString(),top:s,left:a},a=te().toLowerCase(),s=(r&&(o=Hs(a)?"_blank":r),Ks(a)&&(t=t||"http://localhost",s.scrollbars="yes"),Object.entries(s).reduce((e,[t,r])=>""+e+t+`=${r},`,""));if([n=te()]=[a],Js(n)&&window.navigator?.standalone&&"_self"!==o)return i=t||"",r=o,(a=document.createElement("a")).href=i,a.target=r,(l=document.createEvent("MouseEvent")).initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),a.dispatchEvent(l),new Hl(null);a=window.open(t||"",o,s);m(a,e,"popup-blocked");try{a.focus()}catch(e){}return new Hl(a)}let $l="__/auth/handler",Ql="emulator/auth/handler",Yl=encodeURIComponent("fac");async function Jl(e,t,r,n,i,s){m(e.config.authDomain,e,"auth-domain-config-required"),m(e.config.apiKey,e,"invalid-api-key");var a={apiKey:e.config.apiKey,appName:e.name,authType:r,redirectUrl:n,v:Ft,eventId:i};if(t instanceof Oa){t.setDefaultLanguage(e.languageCode),a.providerId=t.providerId||"",Ie(t.getCustomParameters())||(a.customParameters=JSON.stringify(t.getCustomParameters()));for(var[o,l]of Object.entries(s||{}))a[o]=l}t instanceof Ma&&0<(u=t.getScopes().filter(e=>""!==e)).length&&(a.scopes=u.join(",")),e.tenantId&&(a.tid=e.tenantId);var h,c=a;for(h of Object.keys(c))void 0===c[h]&&delete c[h];var u=await e._getAppCheckToken(),u=u?`#${Yl}=`+encodeURIComponent(u):"";return`${r=[e.config][0],r.emulator?ls(r,Ql):`https://${r.authDomain}/`+$l}?`+Se(c).slice(1)+u}let Xl="webStorageSupport";class Zl{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=Oo,this._completeRedirectFn=Sl,this._overrideRedirectResult=wl}async _openPopup(e,t,r,n){return ns(this.eventManagers[e._key()]?.manager,"_initialize() not called before _openPopup()"),Gl(e,await Jl(e,t,r,is(),n),Lo())}async _openRedirect(e,t,r,n){await this._originValidation(e);var i=await Jl(e,t,r,is(),n);return Uo().location.href=i,new Promise(()=>{})}_initialize(e){let r=e._key();if(this.eventManagers[r]){let{manager:e,promise:t}=this.eventManagers[r];return e?Promise.resolve(e):(ns(t,"If manager is not set, promise should be"),t)}let t=this.initAndGetManager(e);return this.eventManagers[r]={promise:t},t.catch(()=>{delete this.eventManagers[r]}),t}async initAndGetManager(t){var e=await Kl(t);let r=new Al(t);return e.register("authEvent",e=>(m(e?.authEvent,t,"invalid-auth-event"),{status:r.onEvent(e.authEvent)?"ACK":"ERROR"}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[t._key()]={manager:r},this.iframes[t._key()]=e,r}_isIframeWebStorageSupported(r,n){this.iframes[r._key()].send(Xl,{type:Xl},e=>{var t=e?.[0]?.[Xl];void 0!==t&&n(!!t),Yi(r,"internal-error")},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){var t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=Ol(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return Xs()||Ws()||Js()}}let eh=Zl;class th extends class{constructor(e){this.factorId=e}_process(e,t,r){switch(t.type){case"enroll":return this._finalizeEnroll(e,t.credential,r);case"signin":return this._finalizeSignIn(e,t.credential);default:return rs("unexpected MultiFactorSessionType")}}}{constructor(e){super("phone"),this.credential=e}static _fromCredential(e){return new th(e)}_finalizeEnroll(e,t,r){return e=e,t={idToken:t,displayName:r,phoneVerificationInfo:this.credential._makeVerificationRequest()},fs(e,"POST","/v2/accounts/mfaEnrollment:finalize",ps(e,t))}_finalizeSignIn(e,t){return e=e,t={mfaPendingCredential:t,phoneVerificationInfo:this.credential._makeVerificationRequest()},fs(e,"POST","/v2/accounts/mfaSignIn:finalize",ps(e,t))}}class rh{constructor(){}static assertion(e){return th._fromCredential(e)}}rh.FACTOR_ID="phone";ir="@firebase/auth";class nh{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){return this.assertAuthConfigured(),this.auth.currentUser?.uid||null}async getToken(e){return this.assertAuthConfigured(),await this.auth._initializationPromise,this.auth.currentUser?{accessToken:await this.auth.currentUser.getIdToken(e)}:null}addAuthTokenListener(t){var e;this.assertAuthConfigured(),this.internalListeners.has(t)||(e=this.auth.onIdTokenChanged(e=>{t(e?.stsTokenManager.accessToken||null)}),this.internalListeners.set(t,e),this.updateProactiveRefresh())}removeAuthTokenListener(e){this.assertAuthConfigured();var t=this.internalListeners.get(e);t&&(this.internalListeners.delete(e),t(),this.updateProactiveRefresh())}assertAuthConfigured(){m(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){0<this.internalListeners.size?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}var ih;function sh(){return window}Y()?._authIdTokenMaxAge,sa={loadJS(n){return new Promise((e,r)=>{var t=document.createElement("script");t.setAttribute("src",n),t.onload=e,t.onerror=e=>{var t=Ji("internal-error");t.customData=e,r(t)},t.type="text/javascript",t.charset="UTF-8",(document.getElementsByTagName("head")?.[0]??document).appendChild(t)})},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="},ih="Browser",Nt(new c("auth",(e,{options:t})=>{var r=e.getProvider("app").getImmediate(),n=e.getProvider("heartbeat"),i=e.getProvider("app-check-internal"),{apiKey:s,authDomain:a}=r.options,s=(m(s&&!s.includes(":"),"invalid-api-key",{appName:r.name}),{apiKey:s,authDomain:a,clientPlatform:ih,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:Zs(ih)}),a=new ra(r,n,i,s);return e=a,r=(t=t)?.persistence||[],r=(Array.isArray(r)?r:[r]).map(Us),t?.errorMap&&e._updateErrorMap(t.errorMap),e._initializeWithPersistence(r,t?.popupRedirectResolver),a},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,r)=>{e.getProvider("auth-internal").initialize()})),Nt(new c("auth-internal",e=>{var t=na(e.getProvider("auth").getImmediate());return e=t,new nh(e)},"PRIVATE").setInstantiationMode("EXPLICIT")),u(ir,"1.13.0",(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}})(ih)),u(ir,"1.13.0","esm2020");async function ah(e,t,r){var n=sh().BuildInfo,i=(ns(t.sessionId,"AuthEvent did not contain a session ID"),i=(e=>{if(ns(/[0-9a-zA-Z]+/.test(e),"Can only convert alpha-numeric strings"),"undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e);var t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r})(t.sessionId),i=await crypto.subtle.digest("SHA-256",i),await(i=Array.from(new Uint8Array(i))).map(e=>e.toString(16).padStart(2,"0")).join("")),s={};return Js()?s.ibi=n.packageName:$s()?s.apn=n.packageName:Yi(e,"operation-not-supported-in-this-environment"),n.displayName&&(s.appDisplayName=n.displayName),s.sessionId=i,Jl(e,r,t.type,void 0,t.eventId??void 0,s)}function oh(n){let i=sh().cordova;return new Promise(r=>{i.plugins.browsertab.isAvailable(e=>{let t=null;e?i.plugins.browsertab.openUrl(n):t=i.InAppBrowser.open(n,(e=te(),/(iPad|iPhone|iPod).*OS 7_\d/i.test(e)||/(iPad|iPhone|iPod).*OS 8_\d/i.test(e)?"_blank":"_system"),"location=yes"),r(t)})})}let lh=20;class hh extends Al{constructor(){super(...arguments),this.passiveListeners=new Set,this.initPromise=new Promise(e=>{this.resolveInitialized=e})}addPassiveListener(e){this.passiveListeners.add(e)}removePassiveListener(e){this.passiveListeners.delete(e)}resetRedirect(){this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1}onEvent(t){return this.resolveInitialized(),this.passiveListeners.forEach(e=>e(t)),super.onEvent(t)}async initialized(){await this.initPromise}}function ch(e,t,r=null){return{type:t,eventId:r,urlResponse:null,sessionId:(()=>{var e=[],t="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let n=0;n<lh;n++){var r=Math.floor(Math.random()*t.length);e.push(t.charAt(r))}return e.join("")})(),postBody:null,tenantId:e.tenantId,error:Ji(e,"no-auth-event")}}async function uh(e){var t=await ph()._get(fh(e));return t&&await ph()._remove(fh(e)),t}function dh(e,t){i=gh(t=t),r=i.link?decodeURIComponent(i.link):void 0,n=gh(r).link,i=i.deep_link_id?decodeURIComponent(i.deep_link_id):void 0;var r,n,i=gh(i).link||i||n||r||t;return i.includes("/__/auth/callback")?(n=(r=((n=gh(i)).firebaseError?(e=>{try{return JSON.parse(e)}catch(e){return null}})(decodeURIComponent(n.firebaseError)):null)?.code?.split("auth/")?.[1])?Ji(r):null)?{type:e.type,eventId:e.eventId,tenantId:e.tenantId,error:n,urlResponse:null,sessionId:null,postBody:null}:{type:e.type,eventId:e.eventId,tenantId:e.tenantId,sessionId:e.sessionId,urlResponse:i,postBody:null}:null}function ph(){return Us(Do)}function fh(e){return Bs("authEvent",e.config.apiKey,e.name)}function gh(e){var t,r;return e?.includes("?")?([t,...r]=e.split("?"),ke(r.join("?"))):{}}class mh{constructor(){this._redirectPersistence=Oo,this._shouldInitProactively=!0,this.eventManagers=new Map,this.originValidationPromises={},this._completeRedirectFn=Sl,this._overrideRedirectResult=wl}async _initialize(e){var t=e._key();let r=this.eventManagers.get(t);return r||(r=new hh(e),this.eventManagers.set(t,r),this.attachCallbackListeners(e,r)),r}_openPopup(e){Yi(e,"operation-not-supported-in-this-environment")}async _openRedirect(e,t,r,n){i=e,m("function"==typeof(s=sh())?.universalLinks?.subscribe,i,"invalid-cordova-configuration",{missingPlugin:"cordova-universal-links-plugin-fix"}),m(void 0!==s?.BuildInfo?.packageName,i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-buildInfo"}),m("function"==typeof s?.cordova?.plugins?.browsertab?.openUrl,i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"}),m("function"==typeof s?.cordova?.plugins?.browsertab?.isAvailable,i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"}),m("function"==typeof s?.cordova?.InAppBrowser?.open,i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-inappbrowser"});var i,s=await this._initialize(e),a=(await s.initialized(),s.resetRedirect(),vl.clear(),await this._originValidation(e),ch(e,r,n)),a=(i=e,r=a,await ph()._set(fh(i),r),await ah(e,a,t));return(async(a,o,l)=>{let h=sh().cordova,c=()=>{};try{await new Promise((t,e)=>{let r=null;function n(){t();var e=h.plugins.browsertab?.close;"function"==typeof e&&e(),"function"==typeof l?.close&&l.close()}function i(){r=r||window.setTimeout(()=>{e(Ji(a,"redirect-cancelled-by-user"))},2e3)}function s(){"visible"===document?.visibilityState&&i()}o.addPassiveListener(n),document.addEventListener("resume",i,!1),$s()&&document.addEventListener("visibilitychange",s,!1),c=()=>{o.removePassiveListener(n),document.removeEventListener("resume",i,!1),document.removeEventListener("visibilitychange",s,!1),r&&window.clearTimeout(r)}})}finally{c()}})(e,s,await oh(a))}_isIframeWebStorageSupported(e,t){throw new Error("Method not implemented.")}_originValidation(e){var t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=(async e=>{var t=sh().BuildInfo,r={};Js()?r.iosBundleId=t.packageName:$s()?r.androidPackageName=t.packageName:Yi(e,"operation-not-supported-in-this-environment"),await Pl(e,r)})(e)),this.originValidationPromises[t]}attachCallbackListeners(n,i){var{universalLinks:e,handleOpenURL:t,BuildInfo:r}=sh();let s=setTimeout(async()=>{await uh(n),i.onEvent(_h())},500),a=async e=>{clearTimeout(s);var t=await uh(n);let r=null;t&&e?.url&&(r=dh(t,e.url)),i.onEvent(r||_h())},o=(void 0!==e&&"function"==typeof e.subscribe&&e.subscribe(null,a),t),l=r.packageName.toLowerCase()+"://";sh().handleOpenURL=async e=>{if(e.toLowerCase().startsWith(l)&&a({url:e}),"function"==typeof o)try{o(e)}catch(e){console.error(e)}}}}let vh=mh;function _h(){return{type:"unknown",eventId:null,sessionId:null,urlResponse:null,postBody:null,tenantId:null,error:Ji("no-auth-event")}}function yh(){return self?.location?.protocol||null}function wh(e=te()){return!("file:"!==yh()&&"ionic:"!==yh()&&"capacitor:"!==yh()||!e.toLowerCase().match(/iphone|ipad|ipod|android/))}function bh(e=te()){return oe()&&11===document?.documentMode||([e=te()]=[e],/Edge\/\d+/.test(e))}function Ih(){try{var e=self.localStorage,t=Lo();if(e)return e.setItem(t,"1"),e.removeItem(t),!bh()||ue()}catch(e){return Th()&&ue()}return!1}function Th(){return"undefined"!=typeof global&&"WorkerGlobalScope"in global&&"importScripts"in global}function Eh(){return("http:"===yh()||"https:"===yh()||se()||wh())&&!(ae()||ne())&&Ih()&&!Th()}function Ch(){return wh()&&"undefined"!=typeof document}let Sh={LOCAL:"local",NONE:"none",SESSION:"session"},kh=m,Ah="persistence";async function Nh(e){await e._initializationPromise;var t=Rh(),r=Bs(Ah,e.config.apiKey,e.name);t&&t.setItem(r,e._getPersistenceType())}function Rh(){try{return("undefined"!=typeof window?window:null)?.sessionStorage||null}catch(e){return null}}let Ph=m;class Dh{constructor(){this.browserResolver=Us(eh),this.cordovaResolver=Us(vh),this.underlyingResolver=null,this._redirectPersistence=Oo,this._completeRedirectFn=Sl,this._overrideRedirectResult=wl}async _initialize(e){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._initialize(e)}async _openPopup(e,t,r,n){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._openPopup(e,t,r,n)}async _openRedirect(e,t,r,n){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._openRedirect(e,t,r,n)}_isIframeWebStorageSupported(e,t){this.assertedUnderlyingResolver._isIframeWebStorageSupported(e,t)}_originValidation(e){return this.assertedUnderlyingResolver._originValidation(e)}get _shouldInitProactively(){return Ch()||this.browserResolver._shouldInitProactively}get assertedUnderlyingResolver(){return Ph(this.underlyingResolver,"internal-error"),this.underlyingResolver}async selectUnderlyingResolver(){var e;this.underlyingResolver||(e=await(!!Ch()&&new Promise(e=>{let t=setTimeout(()=>{e(!1)},1e3);document.addEventListener("deviceready",()=>{clearTimeout(t),e(!0)})})),this.underlyingResolver=e?this.cordovaResolver:this.browserResolver)}}function xh(e){return e.unwrap()}function Oh(e,t){var r,n,i,s=t.customData?._tokenResponse;"auth/multi-factor-auth-required"===t?.code?t.resolver=new Uh(e,(r=t,n=w(e),m((i=r).customData.operationType,n,"argument-error"),m(i.customData._serverResponse?.mfaPendingCredential,n,"argument-error"),Co._fromError(n,i))):s&&(i=Mh(n=t))&&(n.credential=i,n.tenantId=s.tenantId||void 0,n.email=s.email||void 0,n.phoneNumber=s.phoneNumber||void 0)}function Mh(e){var t=(e instanceof fe?e.customData:e)._tokenResponse;if(!t)return null;if(!(e instanceof fe)&&"temporaryProof"in t&&"phoneNumber"in t)return ol.credentialFromResult(e);var r=t.providerId;if(!r||r===ji.PASSWORD)return null;let n;switch(r){case ji.GOOGLE:n=Ua;break;case ji.FACEBOOK:n=Fa;break;case ji.GITHUB:n=Va;break;case ji.TWITTER:n=ja;break;default:var{oauthIdToken:i,oauthAccessToken:s,oauthTokenSecret:a,pendingToken:o,nonce:l}=t;return s||a||i||o?o?r.startsWith("saml.")?qa._create(r,o):Aa._fromParams({providerId:r,signInMethod:r,pendingToken:o,idToken:i,accessToken:s}):new La(r).credential({idToken:i,accessToken:s,rawNonce:l}):null}return e instanceof fe?n.credentialFromError(e):n.credentialFromResult(e)}function Lh(t,e){return e.catch(e=>{throw e instanceof fe&&Oh(t,e),e}).then(e=>{var t=e.operationType,r=e.user;return{operationType:t,credential:Mh(e),additionalUserInfo:To(e),user:Vh.getOrCreate(r)}})}async function Fh(t,e){let r=await e;return{verificationId:r.verificationId,confirm:e=>Lh(t,r.confirm(e))}}class Uh{constructor(e,t){this.resolver=t,this.auth=e.wrapped()}get session(){return this.resolver.session}get hints(){return this.resolver.hints}resolveSignIn(e){return Lh(xh(this.auth),this.resolver.resolveSignIn(e))}}class Vh{constructor(e){var t;this._delegate=e,this.multiFactor=(t=w(e),Ao.has(t)||Ao.set(t,ko._fromUser(t)),Ao.get(t))}static getOrCreate(e){return Vh.USER_MAP.has(e)||Vh.USER_MAP.set(e,new Vh(e)),Vh.USER_MAP.get(e)}delete(){return this._delegate.delete()}reload(){return this._delegate.reload()}toJSON(){return this._delegate.toJSON()}getIdTokenResult(e){return this._delegate.getIdTokenResult(e)}getIdToken(e){return this._delegate.getIdToken(e)}linkAndRetrieveDataWithCredential(e){return this.linkWithCredential(e)}async linkWithCredential(e){return Lh(this.auth,to(this._delegate,e))}async linkWithPhoneNumber(e,t){return Fh(this.auth,(async(e,t,r)=>{let n=w(e);await Ja(!1,n,"phone");var i=await sl(n.auth,t,w(r));return new il(i,e=>to(n,e))})(this._delegate,e,t))}async linkWithPopup(e){return Lh(this.auth,(async(e,t,r)=>{var n=w(e),i=(es(n.auth,t,Oa),ll(n.auth,r));return new gl(n.auth,"linkViaPopup",t,i,n).executeNotNull()})(this._delegate,e,Dh))}async linkWithRedirect(e){return await Nh(na(this.auth)),Cl(this._delegate,e,Dh)}reauthenticateAndRetrieveDataWithCredential(e){return this.reauthenticateWithCredential(e)}async reauthenticateWithCredential(e){return Lh(this.auth,ro(this._delegate,e))}reauthenticateWithPhoneNumber(e,t){return Fh(this.auth,(async(e,t,r)=>{let n=w(e);var i;return h(n.auth.app)?Promise.reject(Zi(n.auth)):(i=await sl(n.auth,t,w(r)),new il(i,e=>ro(n,e)))})(this._delegate,e,t))}reauthenticateWithPopup(e){return Lh(this.auth,(async(e,t,r)=>{var n=w(e);if(h(n.auth.app))return Promise.reject(Ji(n.auth,"operation-not-supported-in-this-environment"));es(n.auth,t,Oa);var i=ll(n.auth,r);return new gl(n.auth,"reauthViaPopup",t,i,n).executeNotNull()})(this._delegate,e,Dh))}async reauthenticateWithRedirect(e){return await Nh(na(this.auth)),El(this._delegate,e,Dh)}sendEmailVerification(e){return po(this._delegate,e)}async unlink(e){return await Qa(this._delegate,e),this}updateEmail(e){return t=this._delegate,e=e,h((r=w(t)).auth.app)?Promise.reject(Zi(r.auth)):mo(r,e,null);var t,r}updatePassword(e){return mo(w(this._delegate),null,e)}updatePhoneNumber(e){return(async(e,t)=>{var r=w(e);if(h(r.auth.app))return Promise.reject(Zi(r.auth));await Ya(r,t)})(this._delegate,e)}updateProfile(e){return go(this._delegate,e)}verifyBeforeUpdateEmail(e,t){return fo(this._delegate,e,t)}get emailVerified(){return this._delegate.emailVerified}get isAnonymous(){return this._delegate.isAnonymous}get metadata(){return this._delegate.metadata}get phoneNumber(){return this._delegate.phoneNumber}get providerData(){return this._delegate.providerData}get refreshToken(){return this._delegate.refreshToken}get tenantId(){return this._delegate.tenantId}get displayName(){return this._delegate.displayName}get email(){return this._delegate.email}get photoURL(){return this._delegate.photoURL}get providerId(){return this._delegate.providerId}get uid(){return this._delegate.uid}get auth(){return this._delegate.auth}}Vh.USER_MAP=new WeakMap;let qh=m;class Bh{constructor(e,t){var r,n;this.app=e,t.isInitialized()?this._delegate=t.getImmediate():(r=e.options.apiKey,qh(r,"invalid-api-key",{appName:e.name}),qh(r,"invalid-api-key",{appName:e.name}),n="undefined"!=typeof window?Dh:void 0,this._delegate=t.initialize({options:{persistence:((e,t)=>{var r=((e,t)=>{var r=Rh();if(!r)return[];var n=Bs(Ah,e,t);switch(r.getItem(n)){case Sh.NONE:return[qs];case Sh.LOCAL:return[Qo,Oo];case Sh.SESSION:return[Oo];default:return[]}})(e,t);if("undefined"==typeof self||r.includes(Qo)||r.push(Qo),"undefined"!=typeof window)for(var n of[Do,Oo])r.includes(n)||r.push(n);return r.includes(qs)||r.push(qs),r})(r,e.name),popupRedirectResolver:n}}),this._delegate._updateErrorMap(Wi)),this.linkUnderlyingAuth()}get emulatorConfig(){return this._delegate.emulatorConfig}get currentUser(){return this._delegate.currentUser?Vh.getOrCreate(this._delegate.currentUser):null}get languageCode(){return this._delegate.languageCode}set languageCode(e){this._delegate.languageCode=e}get settings(){return this._delegate.settings}get tenantId(){return this._delegate.tenantId}set tenantId(e){this._delegate.tenantId=e}useDeviceLanguage(){this._delegate.useDeviceLanguage()}signOut(){return this._delegate.signOut()}useEmulator(e,t){ma(this._delegate,e,t)}applyActionCode(e){return ho(this._delegate,e)}checkActionCode(e){return co(this._delegate,e)}confirmPasswordReset(e,t){return(async(t,e,r)=>{await wa(w(t),{oobCode:e,newPassword:r}).catch(async e=>{throw"auth/password-does-not-meet-requirements"===e.code&&lo(t),e})})(this._delegate,e,t)}async createUserWithEmailAndPassword(e,t){return Lh(this._delegate,(async(t,e,r)=>{var n,i;return h(t.app)?Promise.reject(Zi(t)):(i=await ga(n=na(t),{returnSecureToken:!0,email:e,password:r,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",za,"EMAIL_PASSWORD_PROVIDER").catch(e=>{throw"auth/password-does-not-meet-requirements"===e.code&&lo(t),e}),i=await Ka._fromIdTokenResponse(n,"signIn",i),await n._updateCurrentUser(i.user),i)})(this._delegate,e,t))}fetchProvidersForEmail(e){return this.fetchSignInMethodsForEmail(e)}fetchSignInMethodsForEmail(e){return uo(this._delegate,e)}isSignInWithEmailLink(e){return this._delegate,e=e,"EMAIL_SIGNIN"===Da.parseLink(e)?.operation}async getRedirectResult(){qh(Eh(),this._delegate,"operation-not-supported-in-this-environment");e=this._delegate,t=Dh,await na(e)._initializationPromise;var e,t,r=await Sl(e,t,!1);return r?Lh(this._delegate,Promise.resolve(r)):{credential:null,user:null}}addFrameworkForLogging(e){na(this._delegate)._logFramework(e)}onAuthStateChanged(e,t,r){var{next:n,error:i,complete:s}=jh(e,t,r);return this._delegate.onAuthStateChanged(n,i,s)}onIdTokenChanged(e,t,r){var{next:n,error:i,complete:s}=jh(e,t,r);return this._delegate.onIdTokenChanged(n,i,s)}sendSignInLinkToEmail(e,t){return(async(e,t,r)=>{let n=na(e);var i={requestType:"EMAIL_SIGNIN",email:t,clientType:"CLIENT_TYPE_WEB"};e=i,m((t=r).handleCodeInApp,n,"argument-error"),t&&oo(n,e,t),await ga(n,i,"getOobCode",Ca,"EMAIL_PASSWORD_PROVIDER")})(this._delegate,e,t)}sendPasswordResetEmail(e,t){return(async(e,t,r)=>{var n=na(e),i={requestType:"PASSWORD_RESET",email:t,clientType:"CLIENT_TYPE_WEB"};r&&oo(n,i,r),await ga(n,i,"getOobCode",Ea,"EMAIL_PASSWORD_PROVIDER")})(this._delegate,e,t||void 0)}async setPersistence(e){var t,r;t=this._delegate,r=e,kh(Object.values(Sh).includes(r),t,"invalid-persistence-type"),ae()?kh(r!==Sh.SESSION,t,"unsupported-persistence-type"):ne()?kh(r===Sh.NONE,t,"unsupported-persistence-type"):Th()?kh(r===Sh.NONE||r===Sh.LOCAL&&ue(),t,"unsupported-persistence-type"):kh(r===Sh.NONE||Ih(),t,"unsupported-persistence-type");let n;switch(e){case Sh.SESSION:n=Oo;break;case Sh.LOCAL:var i=await Us(Qo)._isAvailable();n=i?Qo:Do;break;case Sh.NONE:n=qs;break;default:return Yi("argument-error",{appName:this._delegate.name})}return this._delegate.setPersistence(n)}signInAndRetrieveDataWithCredential(e){return this.signInWithCredential(e)}signInAnonymously(){return Lh(this._delegate,(async e=>{var t,r;return h(e.app)?Promise.reject(Zi(e)):(await(t=na(e))._initializationPromise,t.currentUser?.isAnonymous?new Ka({user:t.currentUser,providerId:null,operationType:"signIn"}):(r=await za(t,{returnSecureToken:!0}),r=await Ka._fromIdTokenResponse(t,"signIn",r,!0),await t._updateCurrentUser(r.user),r))})(this._delegate))}signInWithCredential(e){return Lh(this._delegate,eo(this._delegate,e))}signInWithCustomToken(e){return Lh(this._delegate,no(this._delegate,e))}signInWithEmailAndPassword(e,t){return Lh(this._delegate,(r=this._delegate,e=e,t=t,h(r.app)?Promise.reject(Zi(r)):eo(w(r),xa.credential(e,t)).catch(async e=>{throw"auth/password-does-not-meet-requirements"===e.code&&lo(r),e})));var r}signInWithEmailLink(e,t){return Lh(this._delegate,(async(e,t,r)=>{var n,i;return h(e.app)?Promise.reject(Zi(e)):(n=w(e),m((i=xa.credentialWithLink(t,r||is()))._tenantId===(n.tenantId||null),n,"tenant-id-mismatch"),eo(n,i))})(this._delegate,e,t))}signInWithPhoneNumber(e,t){return Fh(this._delegate,(async(e,t,r)=>{if(h(e.app))return Promise.reject(Zi(e));let n=na(e);var i=await sl(n,t,w(r));return new il(i,e=>eo(n,e))})(this._delegate,e,t))}async signInWithPopup(e){return qh(Eh(),this._delegate,"operation-not-supported-in-this-environment"),Lh(this._delegate,(async(e,t,r)=>{var n,i;return h(e.app)?Promise.reject(Ji(e,"operation-not-supported-in-this-environment")):(n=na(e),es(e,t,Oa),i=ll(n,r),new gl(n,"signInViaPopup",t,i).executeNotNull())})(this._delegate,e,Dh))}async signInWithRedirect(e){return qh(Eh(),this._delegate,"operation-not-supported-in-this-environment"),await Nh(this._delegate),Tl(this._delegate,e,Dh)}updateCurrentUser(e){return this._delegate.updateCurrentUser(e)}verifyPasswordResetCode(e){return(async(e,t)=>{var r=(await co(w(e),t)).data;return r.email})(this._delegate,e)}unwrap(){return this._delegate}_delete(){return this._delegate._delete()}linkUnderlyingAuth(){this._delegate.wrapped=()=>this}}function jh(e,t,r){let n=e,i=("function"!=typeof e&&({next:n,error:t,complete:r}=e),n);return{next:e=>i(e&&Vh.getOrCreate(e)),error:t,complete:r}}Bh.Persistence=Sh;class zh{static credential(e,t){return ol.credential(e,t)}constructor(){this.providerId="phone",this._delegate=new ol(xh(or.auth()))}verifyPhoneNumber(e,t){return this._delegate.verifyPhoneNumber(e,t)}unwrap(){return this._delegate}}zh.PHONE_SIGN_IN_METHOD=ol.PHONE_SIGN_IN_METHOD,zh.PROVIDER_ID=ol.PROVIDER_ID;let Kh=m;class Wh{constructor(e,t,r=or.app()){Kh(r.options?.apiKey,"invalid-api-key",{appName:r.name}),this._delegate=new nl(r.auth(),e,t),this.type=this._delegate.type}clear(){this._delegate.clear()}render(){return this._delegate.render()}verify(){return this._delegate.verify()}}(t=or).INTERNAL.registerComponent(new c("auth-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),r=e.getProvider("auth");return new Bh(t,r)},"PUBLIC").setServiceProps({ActionCodeInfo:{Operation:{EMAIL_SIGNIN:zi.EMAIL_SIGNIN,PASSWORD_RESET:zi.PASSWORD_RESET,RECOVER_EMAIL:zi.RECOVER_EMAIL,REVERT_SECOND_FACTOR_ADDITION:zi.REVERT_SECOND_FACTOR_ADDITION,VERIFY_AND_CHANGE_EMAIL:zi.VERIFY_AND_CHANGE_EMAIL,VERIFY_EMAIL:zi.VERIFY_EMAIL}},EmailAuthProvider:xa,FacebookAuthProvider:Fa,GithubAuthProvider:Va,GoogleAuthProvider:Ua,OAuthProvider:La,SAMLAuthProvider:Ba,PhoneAuthProvider:zh,PhoneMultiFactorGenerator:rh,RecaptchaVerifier:Wh,TwitterAuthProvider:ja,Auth:Bh,AuthCredential:ya,Error:fe}).setInstantiationMode("LAZY").setMultipleInstances(!1)),t.registerVersion("@firebase/auth-compat","0.6.5");let Hh="@firebase/database",Gh="";function $h(e){Gh=e}class Qh{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),_e(t))}get(e){var t=this.domStorage_.getItem(this.prefixedName_(e));return null==t?null:ve(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}class Yh{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){null==t?delete this.cache_[e]:this.cache_[e]=t}get(e){return we(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}function Jh(e){try{var t;if("undefined"!=typeof window&&void 0!==window[e])return(t=window[e]).setItem("firebase:sentinel","cache"),t.removeItem("firebase:sentinel"),new Qh(t)}catch(e){}return new Yh}var Xh;function Zh(e){var t=(t=>{var r,n,i=[];let s=0;for(let a=0;a<t.length;a++){let e=t.charCodeAt(a);55296<=e&&e<=56319&&(r=e-55296,a++,g(a<t.length,"Surrogate pair missing trail surrogate."),n=t.charCodeAt(a)-56320,e=65536+(r<<10)+n),e<128?i[s++]=e:(e<2048?i[s++]=e>>6|192:(e<65536?i[s++]=e>>12|224:(i[s++]=e>>18|240,i[s++]=e>>12&63|128),i[s++]=e>>6&63|128),i[s++]=63&e|128)}return i})(e),r=new Ne,t=(r.update(t),r.digest());return a.encodeByteArray(t)}function ec(t){return function(...e){fc(t,...e)}}function tc(...e){var t="FIREBASE INTERNAL ERROR: "+cc(...e);lc.error(t)}function rc(e,t){return e===t?0:e<t?-1:1}function nc(e,t){if(t&&e in t)return t[e];throw new Error("Missing required key ("+e+") in object: "+_e(t))}function ic(e){if("object"!=typeof e||null===e)return _e(e);var t,r=[];for(t in e)r.push(t);r.sort();let n="{";for(let i=0;i<r.length;i++)0!==i&&(n+=","),n=(n=n+_e(r[i])+":")+ic(e[r[i]]);return n+="}"}function sc(e,t){var r=e.length;if(r<=t)return[e];var n=[];for(let i=0;i<r;i+=t)i+t>r?n.push(e.substring(i,r)):n.push(e.substring(i,i+t));return n}let ac=Jh("localStorage"),oc=Jh("sessionStorage"),lc=new Xe("@firebase/database"),hc=(()=>{let e=1;return function(){return e++}})(),cc=function(...e){let t="";for(let n=0;n<e.length;n++){var r=e[n];Array.isArray(r)||r&&"object"==typeof r&&"number"==typeof r.length?t+=cc.apply(null,r):t+="object"==typeof r?_e(r):r,t+=" "}return t},uc=null,dc=!0,pc=function(e,t){g(!t||!0===e||!1===e,"Can't turn on custom loggers persistently."),!0===e?(lc.logLevel=p.VERBOSE,uc=lc.log.bind(lc),t&&oc.set("logging_enabled",!0)):"function"==typeof e?uc=e:(uc=null,oc.remove("logging_enabled"))},fc=function(...e){var t;!0===dc&&(dc=!1,null===uc)&&!0===oc.get("logging_enabled")&&pc(!0),uc&&(t=cc.apply(null,e),uc(t))},gc=function(...e){var t="FIREBASE FATAL ERROR: "+cc(...e);throw lc.error(t),new Error(t)},mc=function(...e){var t="FIREBASE WARNING: "+cc(...e);lc.warn(t)},vc=function(){"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&mc("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().")},_c=function(e){return"number"==typeof e&&(e!=e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY)},yc="[MIN_NAME]",wc="[MAX_NAME]",bc=function(e,t){var r,n;return e===t?0:e===yc||t===wc?-1:t===yc||e===wc?1:(r=Ec(e),n=Ec(t),null!==r?null!==n?r-n==0?e.length-t.length:r-n:-1:null===n&&e<t?-1:1)};function Ic(e,t){for(var r in e)e.hasOwnProperty(r)&&t(r,e[r])}function Tc(e){g(!_c(e),"Invalid JSON number");let t,r,n,i,s;0===e?(r=0,n=0,t=1/e==-1/0?1:0):(t=e<0,e=Math.abs(e),n=e>=Math.pow(2,-1022)?(i=Math.min(Math.floor(Math.log(e)/Math.LN2),1023),r=i+1023,Math.round(e*Math.pow(2,52-i)-Math.pow(2,52))):(r=0,Math.round(e/Math.pow(2,-1074))));var a=[];for(s=52;s;--s)a.push(n%2?1:0),n=Math.floor(n/2);for(s=11;s;--s)a.push(r%2?1:0),r=Math.floor(r/2);a.push(t?1:0),a.reverse();var o=a.join("");let l="";for(s=0;s<64;s+=8){let e=parseInt(o.substr(s,8),2).toString(16);1===e.length&&(e="0"+e),l+=e}return l.toLowerCase()}function Ec(e){if(Sc.test(e)){var t=Number(e);if(t>=kc&&t<=Ac)return t}return null}function Cc(e,t){var r=setTimeout(e,t);return"number"==typeof r&&"undefined"!=typeof Deno&&Deno.unrefTimer?Deno.unrefTimer(r):"object"==typeof r&&r.unref&&r.unref(),r}let Sc=new RegExp("^-?(0*)\\d{1,10}$"),kc=-2147483648,Ac=2147483647,Nc=function(e){try{e()}catch(t){setTimeout(()=>{var e=t.stack||"";throw mc("Exception was thrown by user callback.",e),t},Math.floor(0))}};class Rc{constructor(e,t){this.appCheckProvider=t,this.appName=e.name,h(e)&&e.settings.appCheckToken&&(this.serverAppAppCheckToken=e.settings.appCheckToken),this.appCheck=t?.getImmediate({optional:!0}),this.appCheck||t?.get().then(e=>this.appCheck=e)}getToken(r){if(this.serverAppAppCheckToken){if(r)throw new Error("Attempted reuse of `FirebaseServerApp.appCheckToken` after previous usage failed.");return Promise.resolve({token:this.serverAppAppCheckToken})}return this.appCheck?this.appCheck.getToken(r):new Promise((e,t)=>{setTimeout(()=>{this.appCheck?this.getToken(r).then(e,t):e(null)},0)})}addTokenChangeListener(t){this.appCheckProvider?.get().then(e=>e.addTokenListener(t))}notifyForInvalidToken(){mc(`Provided AppCheck credentials for the app named "${this.appName}" `+"are invalid. This usually indicates your app was not initialized correctly.")}}class Pc{constructor(e,t,r){this.appName_=e,this.firebaseOptions_=t,this.authProvider_=r,this.auth_=null,this.auth_=r.getImmediate({optional:!0}),this.auth_||r.onInit(e=>this.auth_=e)}getToken(r){return this.auth_?this.auth_.getToken(r).catch(e=>e&&"auth/token-not-initialized"===e.code?(fc("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(e)):new Promise((e,t)=>{setTimeout(()=>{this.auth_?this.getToken(r).then(e,t):e(null)},0)})}addTokenChangeListener(t){this.auth_?this.auth_.addAuthTokenListener(t):this.authProvider_.get().then(e=>e.addAuthTokenListener(t))}removeTokenChangeListener(t){this.authProvider_.get().then(e=>e.removeAuthTokenListener(t))}notifyForInvalidToken(){let e='Provided authentication credentials for the app named "'+this.appName_+'" are invalid. This usually indicates your app was not initialized correctly. ';"credential"in this.firebaseOptions_?e+='Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':"serviceAccount"in this.firebaseOptions_?e+='Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':e+='Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.',mc(e)}}class Dc{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}Dc.OWNER="owner";let xc=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,Oc="websocket",Mc="long_polling";class Lc{constructor(e,t,r,n,i=!1,s="",a=!1,o=!1,l=null){this.secure=t,this.namespace=r,this.webSocketOnly=n,this.nodeAdmin=i,this.persistenceKey=s,this.includeNamespaceInQueryParams=a,this.isUsingEmulator=o,this.emulatorOptions=l,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=ac.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())&&ac.set("host:"+this._host,this.internalHost)}toString(){let e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e}toURLString(){var e=this.secure?"https://":"http://",t=this.includeNamespaceInQueryParams?"?ns="+this.namespace:"";return e+this.host+"/"+t}}function Fc(e,t,r){g("string"==typeof t,"typeof type must == string"),g("object"==typeof r,"typeof params must == object");let n;if(t===Oc)n=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?";else{if(t!==Mc)throw new Error("Unknown connection type: "+t);n=(e.secure?"https://":"http://")+e.internalHost+"/.lp?"}((t=e).host!==t.internalHost||t.isCustomHost()||t.includeNamespaceInQueryParams)&&(r.ns=e.namespace);let i=[];return Ic(r,(e,t)=>{i.push(e+"="+t)}),n+i.join("&")}class Uc{constructor(){this.counters_={}}incrementCounter(e,t=1){we(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return W(void 0,this.counters_)}}let Vc={},qc={};function Bc(e){var t=e.toString();return Vc[t]||(Vc[t]=new Uc),Vc[t]}class jc{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]&&Nc(()=>{this.onMessage_(e[t])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}class zc{constructor(e,t,r,n,i,s,a){this.connId=e,this.repoInfo=t,this.applicationId=r,this.appCheckToken=n,this.authToken=i,this.transportSessionId=s,this.lastSessionId=a,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=ec(e),this.stats_=Bc(t),this.urlFn=e=>(this.appCheckToken&&(e.ac=this.appCheckToken),Fc(t,Mc,e))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new jc(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null},Math.floor(3e4));var r=()=>{var e;this.isClosed_||(this.scriptTagHolder=new Kc((...e)=>{var[t,r,n,,,]=e;if(this.incrementIncomingBytes_(e),this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,"start"===t)this.id=r,this.password=n;else{if("close"!==t)throw new Error("Unrecognized command received: "+t);r?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(r,()=>{this.onClosed_()})):this.onClosed_()}},(...e)=>{var[t,r]=e;this.incrementIncomingBytes_(e),this.myPacketOrderer.handleResponse(t,r)},()=>{this.onClosed_()},this.urlFn),(e={start:"t"}).ser=Math.floor(1e8*Math.random()),this.scriptTagHolder.uniqueCallbackIdentifier&&(e.cb=this.scriptTagHolder.uniqueCallbackIdentifier),e.v="5",this.transportSessionId&&(e.s=this.transportSessionId),this.lastSessionId&&(e.ls=this.lastSessionId),this.applicationId&&(e.p=this.applicationId),this.appCheckToken&&(e.ac=this.appCheckToken),"undefined"!=typeof location&&location.hostname&&xc.test(location.hostname)&&(e.r="f"),e=this.urlFn(e),this.log_("Connecting via long-poll to "+e),this.scriptTagHolder.addTag(e,()=>{}))};if("complete"===document.readyState)r();else{let e=!1,t=function(){document.body?e||(e=!0,r()):setTimeout(t,Math.floor(10))};document.addEventListener?(document.addEventListener("DOMContentLoaded",t,!1),window.addEventListener("load",t,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",()=>{"complete"===document.readyState&&t()}),window.attachEvent("onload",t))}}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){zc.forceAllow_=!0}static forceDisallow(){zc.forceDisallow_=!0}static isAvailable(){return!!zc.forceAllow_||!(zc.forceDisallow_||"undefined"==typeof document||null==document.createElement||"object"==typeof window&&window.chrome&&window.chrome.extension&&!/^chrome/.test(window.location.href)||"object"==typeof Windows&&"object"==typeof Windows.UI)}markConnectionHealthy(){}shutdown_(){this.isClosed_=!0,this.scriptTagHolder&&(this.scriptTagHolder.close(),this.scriptTagHolder=null),this.myDisconnFrame&&(document.body.removeChild(this.myDisconnFrame),this.myDisconnFrame=null),this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null)}onClosed_(){this.isClosed_||(this.log_("Longpoll is closing itself"),this.shutdown_(),this.onDisconnect_&&(this.onDisconnect_(this.everConnected_),this.onDisconnect_=null))}close(){this.isClosed_||(this.log_("Longpoll is being closed."),this.shutdown_())}send(e){var t=_e(e),t=(this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length),o(t)),r=sc(t,1840);for(let n=0;n<r.length;n++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,r.length,r[n]),this.curSegmentNum++}addDisconnectPingFrame(e,t){this.myDisconnFrame=document.createElement("iframe");var r={dframe:"t"};r.id=e,r.pw=t,this.myDisconnFrame.src=this.urlFn(r),this.myDisconnFrame.style.display="none",document.body.appendChild(this.myDisconnFrame)}incrementIncomingBytes_(e){var t=_e(e).length;this.bytesReceived+=t,this.stats_.incrementCounter("bytes_received",t)}}class Kc{constructor(t,r,e,n){this.onDisconnect=e,this.urlFn=n,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(1e8*Math.random()),this.sendNewPolls=!0;{this.uniqueCallbackIdentifier=hc(),window["pLPCommand"+this.uniqueCallbackIdentifier]=t,window["pRTLPCB"+this.uniqueCallbackIdentifier]=r,this.myIFrame=Kc.createIFrame_();let e="";this.myIFrame.src&&"javascript:"===this.myIFrame.src.substr(0,"javascript:".length)&&(i=document.domain,e='<script>document.domain="'+i+'";<\/script>');var i="<html><body>"+e+"</body></html>";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(i),this.myIFrame.doc.close()}catch(e){fc("frame writing exception"),e.stack&&fc(e.stack),fc(e)}}}static createIFrame_(){var t=document.createElement("iframe");if(t.style.display="none",!document.body)throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";document.body.appendChild(t);try{t.contentWindow.document||fc("No IE domain setting required")}catch(e){var r=document.domain;t.src="javascript:void((function(){document.open();document.domain='"+r+"';document.close();})())"}return t.contentDocument?t.doc=t.contentDocument:t.contentWindow?t.doc=t.contentWindow.document:t.document&&(t.doc=t.document),t}close(){this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.textContent="",setTimeout(()=>{null!==this.myIFrame&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)},Math.floor(0)));var e=this.onDisconnect;e&&(this.onDisconnect=null,e())}startLongPoll(e,t){for(this.myID=e,this.myPW=t,this.alive=!0;this.newRequest_(););}newRequest_(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.size<(0<this.pendingSegs.length?2:1)){this.currentSerial++;var r={},r=(r.id=this.myID,r.pw=this.myPW,r.ser=this.currentSerial,this.urlFn(r));let e="",t=0;for(;0<this.pendingSegs.length;){if(!(this.pendingSegs[0].d.length+30+e.length<=1870))break;var n=this.pendingSegs.shift();e=e+"&seg"+t+"="+n.seg+"&ts"+t+"="+n.ts+"&d"+t+"="+n.d,t++}return r+=e,this.addLongPollTag_(r,this.currentSerial),!0}return!1}enqueueSegment(e,t,r){this.pendingSegs.push({seg:e,ts:t,d:r}),this.alive&&this.newRequest_()}addLongPollTag_(e,t){this.outstandingRequests.add(t);let r=()=>{this.outstandingRequests.delete(t),this.newRequest_()},n=setTimeout(r,Math.floor(25e3));this.addTag(e,()=>{clearTimeout(n),r()})}addTag(e,r){setTimeout(()=>{try{if(this.sendNewPolls){let t=this.myIFrame.doc.createElement("script");t.type="text/javascript",t.async=!0,t.src=e,t.onload=t.onreadystatechange=function(){var e=t.readyState;e&&"loaded"!==e&&"complete"!==e||(t.onload=t.onreadystatechange=null,t.parentNode&&t.parentNode.removeChild(t),r())},t.onerror=()=>{fc("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(t)}}catch(e){}},Math.floor(1))}}let Wc=null;"undefined"!=typeof MozWebSocket?Wc=MozWebSocket:"undefined"!=typeof WebSocket&&(Wc=WebSocket);class Hc{constructor(e,t,r,n,i,s,a){this.connId=e,this.applicationId=r,this.appCheckToken=n,this.authToken=i,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=ec(this.connId),this.stats_=Bc(t),this.connURL=Hc.connectionURL_(t,s,a,n,r),this.nodeAdmin=t.nodeAdmin}static connectionURL_(e,t,r,n,i){var s={v:"5"};return"undefined"!=typeof location&&location.hostname&&xc.test(location.hostname)&&(s.r="f"),t&&(s.s=t),r&&(s.ls=r),n&&(s.ac=n),i&&(s.p=i),Fc(e,Oc,s)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,ac.set("previous_websocket_failure",!0);try{le(),this.mySock=new Wc(this.connURL,[],void 0)}catch(e){this.log_("Error instantiating WebSocket.");var r=e.message||e.data;return r&&this.log_(r),void this.onClosed_()}this.mySock.onopen=()=>{this.log_("Websocket connected."),this.everConnected_=!0},this.mySock.onclose=()=>{this.log_("Websocket connection was disconnected."),this.mySock=null,this.onClosed_()},this.mySock.onmessage=e=>{this.handleIncomingFrame(e)},this.mySock.onerror=e=>{this.log_("WebSocket error. Closing connection.");var t=e.message||e.data;t&&this.log_(t),this.onClosed_()}}start(){}static forceDisallow(){Hc.forceDisallow_=!0}static isAvailable(){let e=!1;var t;return!(e="undefined"!=typeof navigator&&navigator.userAgent&&(t=navigator.userAgent.match(/Android ([0-9]{0,}\.[0-9]{0,})/))&&1<t.length&&parseFloat(t[1])<4.4?!0:e)&&null!==Wc&&!Hc.forceDisallow_}static previouslyFailed(){return ac.isInMemoryStorage||!0===ac.get("previous_websocket_failure")}markConnectionHealthy(){ac.remove("previous_websocket_failure")}appendFrame_(e){var t;this.frames.push(e),this.frames.length===this.totalFrames&&(t=this.frames.join(""),this.frames=null,t=ve(t),this.onMessage(t))}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if(g(null===this.frames,"We already have a frame buffer"),e.length<=6){var t=Number(e);if(!isNaN(t))return this.handleNewFrameCount_(t),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){var t;null!==this.mySock&&(t=e.data,this.bytesReceived+=t.length,this.stats_.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),null!==this.frames?this.appendFrame_(t):null!==(t=this.extractFrameCount_(t))&&this.appendFrame_(t))}send(e){this.resetKeepAlive();var t=_e(e),r=(this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length),sc(t,16384));1<r.length&&this.sendString_(String(r.length));for(let n=0;n<r.length;n++)this.sendString_(r[n])}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)}}}Hc.responsesRequiredToBeHealthy=2,Hc.healthyTimeout=3e4;class Gc{static get ALL_TRANSPORTS(){return[zc,Hc]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}constructor(e){this.initTransports_(e)}initTransports_(e){var t=Hc&&Hc.isAvailable();let r=t&&!Hc.previouslyFailed();if(e.webSocketOnly&&(t||mc("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),r=!0),r)this.transports_=[Hc];else{var n,i=this.transports_=[];for(n of Gc.ALL_TRANSPORTS)n&&n.isAvailable()&&i.push(n);Gc.globalTransportInitialized_=!0}}initialTransport(){if(0<this.transports_.length)return this.transports_[0];throw new Error("No transports available")}upgradeTransport(){return 1<this.transports_.length?this.transports_[1]:null}}Gc.globalTransportInitialized_=!1;class $c{constructor(e,t,r,n,i,s,a,o,l,h){this.id=e,this.repoInfo_=t,this.applicationId_=r,this.appCheckToken_=n,this.authToken_=i,this.onMessage_=s,this.onReady_=a,this.onDisconnect_=o,this.onKill_=l,this.lastSessionId=h,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=ec("c:"+this.id+":"),this.transportManager_=new Gc(t),this.log_("Connection created"),this.start_()}start_(){var e=this.transportManager_.initialTransport();this.conn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,null,this.lastSessionId),this.primaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;let t=this.connReceiver_(this.conn_),r=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,r)},Math.floor(0));e=e.healthyTimeout||0;0<e&&(this.healthyTimeout_=Cc(()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&102400<this.conn_.bytesReceived?(this.log_("Connection exceeded healthy timeout but has received "+this.conn_.bytesReceived+" bytes. Marking connection healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()):this.conn_&&10240<this.conn_.bytesSent?this.log_("Connection exceeded healthy timeout but has sent "+this.conn_.bytesSent+" bytes. Leaving connection alive."):(this.log_("Closing unhealthy connection after timeout."),this.close()))},Math.floor(e)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(t){return e=>{t===this.conn_?this.onConnectionLost_(e):t===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(t){return e=>{2!==this.state_&&(t===this.rx_?this.onPrimaryMessageReceived_(e):t===this.secondaryConn_?this.onSecondaryMessageReceived_(e):this.log_("message on old connection"))}}sendRequest(e){this.sendData_({t:"d",d:e})}tryCleanupConnection(){this.tx_===this.secondaryConn_&&this.rx_===this.secondaryConn_&&(this.log_("cleaning up and promoting a connection: "+this.secondaryConn_.connId),this.conn_=this.secondaryConn_,this.secondaryConn_=null)}onSecondaryControl_(e){var t;"t"in e&&("a"===(t=e.t)?this.upgradeIfSecondaryHealthy_():"r"===t?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),this.tx_!==this.secondaryConn_&&this.rx_!==this.secondaryConn_||this.close()):"o"===t&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_()))}onSecondaryMessageReceived_(e){var t=nc("t",e),r=nc("d",e);if("c"===t)this.onSecondaryControl_(r);else{if("d"!==t)throw new Error("Unknown protocol layer: "+t);this.pendingDataMessages.push(r)}}upgradeIfSecondaryHealthy_(){this.secondaryResponsesRequired_<=0?(this.log_("Secondary connection is healthy."),this.isHealthy_=!0,this.secondaryConn_.markConnectionHealthy(),this.proceedWithUpgrade_()):(this.log_("sending ping on secondary."),this.secondaryConn_.send({t:"c",d:{t:"p",d:{}}}))}proceedWithUpgrade_(){this.secondaryConn_.start(),this.log_("sending client ack on secondary"),this.secondaryConn_.send({t:"c",d:{t:"a",d:{}}}),this.log_("Ending transmission on primary"),this.conn_.send({t:"c",d:{t:"n",d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()}onPrimaryMessageReceived_(e){var t=nc("t",e),r=nc("d",e);"c"===t?this.onControl_(r):"d"===t&&this.onDataMessage_(r)}onDataMessage_(e){this.onPrimaryResponse_(),this.onMessage_(e)}onPrimaryResponse_(){this.isHealthy_||(this.primaryResponsesRequired_--,this.primaryResponsesRequired_<=0&&(this.log_("Primary connection is healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()))}onControl_(e){var t=nc("t",e);if("d"in e){var r=e.d;if("h"===t){var n={...r};this.repoInfo_.isUsingEmulator&&(n.h=this.repoInfo_.host),this.onHandshake_(n)}else if("n"===t){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(let e=0;e<this.pendingDataMessages.length;++e)this.onDataMessage_(this.pendingDataMessages[e]);this.pendingDataMessages=[],this.tryCleanupConnection()}else"s"===t?this.onConnectionShutdown_(r):"r"===t?this.onReset_(r):"e"===t?tc("Server Error: "+r):"o"===t?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):tc("Unknown control packet command: "+t)}}onHandshake_(e){var t=e.ts,r=e.v,n=e.h;this.sessionId=e.s,this.repoInfo_.host=n,0===this.state_&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,t),"5"!==r&&mc("Protocol version mismatch detected"),this.tryStartUpgrade_())}tryStartUpgrade_(){var e=this.transportManager_.upgradeTransport();e&&this.startUpgrade_(e)}startUpgrade_(e){this.secondaryConn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,this.sessionId),this.secondaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;var t=this.connReceiver_(this.secondaryConn_),r=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(t,r),Cc(()=>{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):Cc(()=>{this.sendPingOnPrimaryIfNecessary_()},Math.floor(5e3))}sendPingOnPrimaryIfNecessary_(){this.isHealthy_||1!==this.state_||(this.log_("sending ping on primary."),this.sendData_({t:"c",d:{t:"p",d:{}}}))}onSecondaryConnectionLost_(){var e=this.secondaryConn_;this.secondaryConn_=null,this.tx_!==e&&this.rx_!==e||this.close()}onConnectionLost_(e){this.conn_=null,e||0!==this.state_?1===this.state_&&this.log_("Realtime connection lost."):(this.log_("Realtime connection failed."),this.repoInfo_.isCacheableHost()&&(ac.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 Qc{put(e,t,r,n){}merge(e,t,r,n){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,t,r){}onDisconnectMerge(e,t,r){}onDisconnectCancel(e,t){}reportStats(e){}}class Yc{constructor(e){this.allowedEvents_=e,this.listeners_={},g(Array.isArray(e)&&0<e.length,"Requires a non-empty array")}trigger(t,...r){if(Array.isArray(this.listeners_[t])){var n=[...this.listeners_[t]];for(let e=0;e<n.length;e++)n[e].callback.apply(n[e].context,r)}}on(e,t,r){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:r});var n=this.getInitialEvent(e);n&&t.apply(r,n)}off(e,t,r){this.validateEventType_(e);var n=this.listeners_[e]||[];for(let i=0;i<n.length;i++)if(n[i].callback===t&&(!r||r===n[i].context))return void n.splice(i,1)}validateEventType_(t){g(this.allowedEvents_.find(e=>e===t),"Unknown event: "+t)}}class Jc extends Yc{static getInstance(){return new Jc}constructor(){super(["online"]),this.online_=!0,"undefined"==typeof window||void 0===window.addEventListener||re()||(window.addEventListener("online",()=>{this.online_||(this.online_=!0,this.trigger("online",!0))},!1),window.addEventListener("offline",()=>{this.online_&&(this.online_=!1,this.trigger("online",!1))},!1))}getInitialEvent(e){return g("online"===e,"Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}let Xc=32,Zc=768;class f{constructor(r,e){if(void 0===e){this.pieces_=r.split("/");let e=0;for(let t=0;t<this.pieces_.length;t++)0<this.pieces_[t].length&&(this.pieces_[e]=this.pieces_[t],e++);this.pieces_.length=e,this.pieceNum_=0}else this.pieces_=r,this.pieceNum_=e}toString(){let e="";for(let t=this.pieceNum_;t<this.pieces_.length;t++)""!==this.pieces_[t]&&(e+="/"+this.pieces_[t]);return e||"/"}}function v(){return new f("")}function _(e){return e.pieceNum_>=e.pieces_.length?null:e.pieces_[e.pieceNum_]}function eu(e){return e.pieces_.length-e.pieceNum_}function y(e){let t=e.pieceNum_;return t<e.pieces_.length&&t++,new f(e.pieces_,t)}function tu(e){return e.pieceNum_<e.pieces_.length?e.pieces_[e.pieces_.length-1]:null}function ru(e,t=0){return e.pieces_.slice(e.pieceNum_+t)}function nu(e){if(e.pieceNum_>=e.pieces_.length)return null;var t=[];for(let r=e.pieceNum_;r<e.pieces_.length-1;r++)t.push(e.pieces_[r]);return new f(t,0)}function iu(e,t){var r=[];for(let i=e.pieceNum_;i<e.pieces_.length;i++)r.push(e.pieces_[i]);if(t instanceof f)for(let e=t.pieceNum_;e<t.pieces_.length;e++)r.push(t.pieces_[e]);else{var n=t.split("/");for(let e=0;e<n.length;e++)0<n[e].length&&r.push(n[e])}return new f(r,0)}function b(e){return e.pieceNum_>=e.pieces_.length}function su(e,t){var r=_(e),n=_(t);if(null===r)return t;if(r===n)return su(y(e),y(t));throw new Error("INTERNAL ERROR: innerPath ("+t+") is not within outerPath ("+e+")")}function au(e,t){var r=ru(e,0),n=ru(t,0);for(let s=0;s<r.length&&s<n.length;s++){var i=bc(r[s],n[s]);if(0!==i)return i}return r.length===n.length?0:r.length<n.length?-1:1}function ou(e,t){if(eu(e)!==eu(t))return!1;for(let r=e.pieceNum_,n=t.pieceNum_;r<=e.pieces_.length;r++,n++)if(e.pieces_[r]!==t.pieces_[n])return!1;return!0}function lu(e,t){let r=e.pieceNum_,n=t.pieceNum_;if(eu(e)>eu(t))return!1;for(;r<e.pieces_.length;){if(e.pieces_[r]!==t.pieces_[n])return!1;++r,++n}return!0}class hu{constructor(e,t){this.errorPrefix_=t,this.parts_=ru(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let r=0;r<this.parts_.length;r++)this.byteLength_+=Le(this.parts_[r]);cu(this)}}function cu(e){if(e.byteLength_>Zc)throw new Error(e.errorPrefix_+"has a key path longer than "+Zc+" bytes ("+e.byteLength_+").");if(e.parts_.length>Xc)throw new Error(e.errorPrefix_+"path specified exceeds the maximum depth that can be written ("+Xc+") or object contains a cycle "+uu(e))}function uu(e){return 0===e.parts_.length?"":"in property '"+e.parts_.join(".")+"'"}class du extends Yc{static getInstance(){return new du}constructor(){super(["visible"]);let t,e;"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(e="visibilitychange",t="hidden"):void 0!==document.mozHidden?(e="mozvisibilitychange",t="mozHidden"):void 0!==document.msHidden?(e="msvisibilitychange",t="msHidden"):void 0!==document.webkitHidden&&(e="webkitvisibilitychange",t="webkitHidden")),this.visible_=!0,e&&document.addEventListener(e,()=>{var e=!document[t];e!==this.visible_&&(this.visible_=e,this.trigger("visible",e))},!1)}getInitialEvent(e){return g("visible"===e,"Unknown event type: "+e),[this.visible_]}}class pu extends Qc{constructor(e,t,r,n,i,s,a,o){if(super(),this.repoInfo_=e,this.applicationId_=t,this.onDataUpdate_=r,this.onConnectStatus_=n,this.onServerInfoUpdate_=i,this.authTokenProvider_=s,this.appCheckTokenProvider_=a,this.authOverride_=o,this.id=pu.nextPersistentConnectionId_++,this.log_=ec("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,o&&!le())throw new Error("Auth override specified in options, but not supported on non Node.js platforms");du.getInstance().on("visible",this.onVisible_,this),-1===e.host.indexOf("fblocal")&&Jc.getInstance().on("online",this.onOnline_,this)}sendRequest(e,t,r){var n=++this.requestNumber_,i={r:n,a:e,b:t};this.log_(_e(i)),g(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(i),r&&(this.requestCBHash_[n]=r)}get(e){this.initConnection_();let r=new Z;var t={p:e._path.toString(),q:e._queryObject},t=(this.outstandingGets_.push({action:"g",request:t,onComplete:e=>{var t=e.d;"ok"===e.s?r.resolve(t):r.reject(t)}}),this.outstandingGetCount_++,this.outstandingGets_.length-1);return this.connected_&&this.sendGet_(t),r.promise}listen(e,t,r,n){this.initConnection_();var i=e._queryIdentifier,s=e._path.toString(),a=(this.log_("Listen called for "+s+" "+i),this.listens.has(s)||this.listens.set(s,new Map),g(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),g(!this.listens.get(s).has(i),"listen() called twice for same path/queryId."),{onComplete:n,hashFn:t,query:e,tag:r});this.listens.get(s).set(i,a),this.connected_&&this.sendListen_(a)}sendGet_(t){let r=this.outstandingGets_[t];this.sendRequest("g",r.request,e=>{delete this.outstandingGets_[t],this.outstandingGetCount_--,0===this.outstandingGetCount_&&(this.outstandingGets_=[]),r.onComplete&&r.onComplete(e)})}sendListen_(i){let s=i.query,a=s._path.toString(),o=s._queryIdentifier;this.log_("Listen on "+a+" for "+o);var e={p:a};i.tag&&(e.q=s._queryObject,e.t=i.tag),e.h=i.hashFn(),this.sendRequest("q",e,e=>{var t=e.d,r=e.s,n=(pu.warnOnListenWarnings_(t,s),this.listens.get(a)&&this.listens.get(a).get(o));n===i&&(this.log_("listen response",e),"ok"!==r&&this.removeListen_(a,o),i.onComplete)&&i.onComplete(r,t)})}static warnOnListenWarnings_(e,t){var r,n;e&&"object"==typeof e&&we(e,"w")&&(r=be(e,"w"),Array.isArray(r))&&~r.indexOf("no_index")&&(r='".indexOn": "'+t._queryParams.getIndex().toString()+'"',n=t._path.toString(),mc("Using an unspecified index. Your data will be downloaded and "+`filtered on the client. Consider adding ${r} 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){var t;(e&&40===e.length||(e=e,"object"==typeof(t=ye(e).claims)&&!0===t.admin))&&(this.log_("Admin auth credential detected. Reducing max reconnect time."),this.maxReconnectDelay_=3e4)}refreshAppCheckToken(e){this.appCheckToken_=e,this.log_("App check token refreshed"),this.appCheckToken_?this.tryAppCheck():this.connected_&&this.sendRequest("unappeck",{},()=>{})}tryAuth(){if(this.connected_&&this.authToken_){let n=this.authToken_;r=n;var e=!!(e=ye(r).claims)&&"object"==typeof e&&e.hasOwnProperty("iat")?"auth":"gauth",t={cred:n};null===this.authOverride_?t.noauth=!0:"object"==typeof this.authOverride_&&(t.authvar=this.authOverride_),this.sendRequest(e,t,e=>{var t=e.s,r=e.d||"error";this.authToken_===n&&("ok"===t?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(t,r))})}var r,e}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},e=>{var t=e.s,r=e.d||"error";"ok"===t?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(t,r)})}unlisten(e,t){var r=e._path.toString(),n=e._queryIdentifier,i=(this.log_("Unlisten called for "+r+" "+n),g(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(r,n));i&&this.connected_&&this.sendUnlisten_(r,n,e._queryObject,t)}sendUnlisten_(e,t,r,n){this.log_("Unlisten on "+e+" for "+t);var i={p:e};n&&(i.q=r,i.t=n),this.sendRequest("n",i)}onDisconnectPut(e,t,r){this.initConnection_(),this.connected_?this.sendOnDisconnect_("o",e,t,r):this.onDisconnectRequestQueue_.push({pathString:e,action:"o",data:t,onComplete:r})}onDisconnectMerge(e,t,r){this.initConnection_(),this.connected_?this.sendOnDisconnect_("om",e,t,r):this.onDisconnectRequestQueue_.push({pathString:e,action:"om",data:t,onComplete:r})}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,r,n){var i={p:t,d:r};this.log_("onDisconnect "+e,i),this.sendRequest(e,i,e=>{n&&setTimeout(()=>{n(e.s,e.d)},Math.floor(0))})}put(e,t,r,n){this.putInternal("p",e,t,r,n)}merge(e,t,r,n){this.putInternal("m",e,t,r,n)}putInternal(e,t,r,n,i){this.initConnection_();var s={p:t,d:r},s=(void 0!==i&&(s.h=i),this.outstandingPuts_.push({action:e,request:s,onComplete:n}),this.outstandingPutCount_++,this.outstandingPuts_.length-1);this.connected_?this.sendPut_(s):this.log_("Buffering put: "+t)}sendPut_(t){let r=this.outstandingPuts_[t].action;var e=this.outstandingPuts_[t].request;let n=this.outstandingPuts_[t].onComplete;this.outstandingPuts_[t].queued=this.connected_,this.sendRequest(r,e,e=>{this.log_(r+" response",e),delete this.outstandingPuts_[t],this.outstandingPutCount_--,0===this.outstandingPutCount_&&(this.outstandingPuts_=[]),n&&n(e.s,e.d)})}reportStats(e){var t;this.connected_&&(this.log_("reportStats",t={c:e}),this.sendRequest("s",t,e=>{var t;"ok"!==e.s&&(t=e.d,this.log_("reportStats","Error sending stats: "+t))}))}onDataMessage_(e){if("r"in e){this.log_("from server: "+_e(e));var t=e.r,r=this.requestCBHash_[t];r&&(delete this.requestCBHash_[t],r(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):tc("Unrecognized action received from server: "+_e(e)+"\nAre you using the latest client?")}onReady_(e,t){this.log_("connection ready"),this.connected_=!0,this.lastConnectionEstablishedTime_=(new Date).getTime(),this.handleTimestamp_(e),this.lastSessionId=t,this.firstConnection_&&this.sendConnectStats_(),this.restoreState_(),this.firstConnection_=!1,this.onConnectStatus_(!0)}scheduleConnect_(e){g(!this.realtime_,"Scheduling a connect when we're already connected/ing?"),this.establishConnectionTimer_&&clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=setTimeout(()=>{this.establishConnectionTimer_=null,this.establishConnection_()},Math.floor(e))}initConnection_(){!this.realtime_&&this.firstConnection_&&this.scheduleConnect_(0)}onVisible_(e){e&&!this.visible_&&this.reconnectDelay_===this.maxReconnectDelay_&&(this.log_("Window became visible. Reducing delay."),this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0)),this.visible_=e}onOnline_(e){e?(this.log_("Browser went online."),this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0)):(this.log_("Browser went offline. Killing connection."),this.realtime_&&this.realtime_.close())}onRealtimeDisconnect_(){var e;this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()&&(this.visible_?this.lastConnectionEstablishedTime_&&(3e4<(new Date).getTime()-this.lastConnectionEstablishedTime_&&(this.reconnectDelay_=1e3),this.lastConnectionEstablishedTime_=null):(this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=(new Date).getTime()),e=Math.max(0,(new Date).getTime()-this.lastConnectionAttemptTime_),e=Math.max(0,this.reconnectDelay_-e),e=Math.random()*e,this.log_("Trying to reconnect in "+e+"ms"),this.scheduleConnect_(e),this.reconnectDelay_=Math.min(this.maxReconnectDelay_,1.3*this.reconnectDelay_)),this.onConnectStatus_(!1)}async establishConnection_(){if(this.shouldReconnect_()){this.log_("Making a connection attempt"),this.lastConnectionAttemptTime_=(new Date).getTime(),this.lastConnectionEstablishedTime_=null;var n=this.onDataMessage_.bind(this),i=this.onReady_.bind(this);let e=this.onRealtimeDisconnect_.bind(this);var s=this.id+":"+pu.nextConnectionId_++,a=this.lastSessionId;let t=!1,r=null;var o=function(){r?r.close():(t=!0,e())},l=(this.realtime_={close:o,sendRequest:function(e){g(r,"sendRequest call when we're not connected not allowed."),r.sendRequest(e)}},this.forceTokenRefresh_);this.forceTokenRefresh_=!1;try{var[h,c]=await Promise.all([this.authTokenProvider_.getToken(l),this.appCheckTokenProvider_.getToken(l)]);t?fc("getToken() completed but was canceled"):(fc("getToken() completed. Creating connection."),this.authToken_=h&&h.accessToken,this.appCheckToken_=c&&c.token,r=new $c(s,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,n,i,e,e=>{mc(e+" ("+this.repoInfo_.toString()+")"),this.interrupt("server_kill")},a))}catch(e){this.log_("Failed to get token: "+e),t||(this.repoInfo_.nodeAdmin&&mc(e),o())}}}interrupt(e){fc("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){fc("Resuming connection for reason: "+e),delete this.interruptReasons_[e],Ie(this.interruptReasons_)&&(this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(e){var t=e-(new Date).getTime();this.onServerInfoUpdate_({serverTimeOffset:t})}cancelSentTransactions_(){for(let t=0;t<this.outstandingPuts_.length;t++){var e=this.outstandingPuts_[t];e&&"h"in e.request&&e.queued&&(e.onComplete&&e.onComplete("disconnect"),delete this.outstandingPuts_[t],this.outstandingPutCount_--)}0===this.outstandingPutCount_&&(this.outstandingPuts_=[])}onListenRevoked_(e,t){let r;r=t?t.map(e=>ic(e)).join("$"):"default";var n=this.removeListen_(e,r);n&&n.onComplete&&n.onComplete("permission_denied")}removeListen_(e,t){var r,n=new f(e).toString();let i;return this.listens.has(n)?(r=this.listens.get(n),i=r.get(t),r.delete(t),0===r.size&&this.listens.delete(n)):i=void 0,i}onAuthRevoked_(e,t){fc("Auth token revoked: "+e+"/"+t),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAuthTokenCount_++,3<=this.invalidAuthTokenCount_&&(this.reconnectDelay_=3e4,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(e,t){fc("App check token revoked: "+e+"/"+t),this.appCheckToken_=null,this.forceTokenRefresh_=!0,"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAppCheckTokenCount_++,3<=this.invalidAppCheckTokenCount_&&this.appCheckTokenProvider_.notifyForInvalidToken())}onSecurityDebugPacket_(e){this.securityDebugCallback_?this.securityDebugCallback_(e):"msg"in e&&console.log("FIREBASE: "+e.msg.replace("\n","\nFIREBASE: "))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(var e of this.listens.values())for(var t of e.values())this.sendListen_(t);for(let n=0;n<this.outstandingPuts_.length;n++)this.outstandingPuts_[n]&&this.sendPut_(n);for(;this.onDisconnectRequestQueue_.length;){var r=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(r.action,r.pathString,r.data,r.onComplete)}for(let i=0;i<this.outstandingGets_.length;i++)this.outstandingGets_[i]&&this.sendGet_(i)}sendConnectStats_(){var e={};e["sdk.js."+Gh.replace(/\./g,"-")]=1,re()?e["framework.cordova"]=1:ae()&&(e["framework.reactnative"]=1),this.reportStats(e)}shouldReconnect_(){var e=Jc.getInstance().currentlyOnline();return Ie(this.interruptReasons_)&&e}}pu.nextPersistentConnectionId_=0,pu.nextConnectionId_=0;class d{constructor(e,t){this.name=e,this.node=t}static Wrap(e,t){return new d(e,t)}}class fu{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,t){var r=new d(yc,e),n=new d(yc,t);return 0!==this.compare(r,n)}minPost(){return d.MIN}}let gu;class mu extends fu{static get __EMPTY_NODE(){return gu}static set __EMPTY_NODE(e){gu=e}compare(e,t){return bc(e.name,t.name)}isDefinedOn(e){throw B("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,t){return!1}minPost(){return d.MIN}maxPost(){return new d(wc,gu)}makePost(e,t){return g("string"==typeof e,"KeyIndex indexValue must always be a string."),new d(e,gu)}toString(){return".key"}}let vu=new mu;class _u{constructor(e,t,r,n,i=null){this.isReverse_=n,this.resultGenerator_=i,this.nodeStack_=[];let s=1;for(;!e.isEmpty();)if(s=t?r(e.key,t):1,n&&(s*=-1),s<0)e=this.isReverse_?e.left:e.right;else{if(0===s){this.nodeStack_.push(e);break}this.nodeStack_.push(e),e=this.isReverse_?e.right:e.left}}getNext(){if(0===this.nodeStack_.length)return null;let e=this.nodeStack_.pop(),t;if(t=this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value},this.isReverse_)for(e=e.left;!e.isEmpty();)this.nodeStack_.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack_.push(e),e=e.left;return t}hasNext(){return 0<this.nodeStack_.length}peek(){var e;return 0===this.nodeStack_.length?null:(e=this.nodeStack_[this.nodeStack_.length-1],this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value})}}class yu{constructor(e,t,r,n,i){this.key=e,this.value=t,this.color=null!=r?r:yu.RED,this.left=null!=n?n:bu.EMPTY_NODE,this.right=null!=i?i:bu.EMPTY_NODE}copy(e,t,r,n,i){return new yu(null!=e?e:this.key,null!=t?t:this.value,null!=r?r:this.color,null!=n?n:this.left,null!=i?i:this.right)}count(){return this.left.count()+1+this.right.count()}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||!!e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min_(){return this.left.isEmpty()?this:this.left.min_()}minKey(){return this.min_().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,r){let n=this;var i=r(e,n.key);return(n=i<0?n.copy(null,null,null,n.left.insert(e,t,r),null):0===i?n.copy(null,t,null,null,null):n.copy(null,null,null,null,n.right.insert(e,t,r))).fixUp_()}removeMin_(){if(this.left.isEmpty())return bu.EMPTY_NODE;let e=this;return(e=(e=e.left.isRed_()||e.left.left.isRed_()?e:e.moveRedLeft_()).copy(null,null,null,e.left.removeMin_(),null)).fixUp_()}remove(e,t){let r,n;if(t(e,(r=this).key)<0)r=(r=r.left.isEmpty()||r.left.isRed_()||r.left.left.isRed_()?r:r.moveRedLeft_()).copy(null,null,null,r.left.remove(e,t),null);else{if(0===t(e,(r=(r=r.left.isRed_()?r.rotateRight_():r).right.isEmpty()||r.right.isRed_()||r.right.left.isRed_()?r:r.moveRedRight_()).key)){if(r.right.isEmpty())return bu.EMPTY_NODE;n=r.right.min_(),r=r.copy(n.key,n.value,null,null,r.right.removeMin_())}r=r.copy(null,null,null,null,r.right.remove(e,t))}return r.fixUp_()}isRed_(){return this.color}fixUp_(){let e=this;return e=(e=(e=e.right.isRed_()&&!e.left.isRed_()?e.rotateLeft_():e).left.isRed_()&&e.left.left.isRed_()?e.rotateRight_():e).left.isRed_()&&e.right.isRed_()?e.colorFlip_():e}moveRedLeft_(){let e=this.colorFlip_();return e=e.right.left.isRed_()?(e=(e=e.copy(null,null,null,null,e.right.rotateRight_())).rotateLeft_()).colorFlip_():e}moveRedRight_(){let e=this.colorFlip_();return e=e.left.left.isRed_()?(e=e.rotateRight_()).colorFlip_():e}rotateLeft_(){var e=this.copy(null,null,yu.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){var e=this.copy(null,null,yu.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip_(){var e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth_(){var e=this.check_();return Math.pow(2,e)<=this.count()+1}check_(){if(this.isRed_()&&this.left.isRed_())throw new Error("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed_())throw new Error("Right child of ("+this.key+","+this.value+") is red");var e=this.left.check_();if(e!==this.right.check_())throw new Error("Black depths differ");return e+(this.isRed_()?0:1)}}yu.RED=!0,yu.BLACK=!1;class wu{copy(e,t,r,n,i){return this}insert(e,t,r){return new yu(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 bu{constructor(e,t=bu.EMPTY_NODE){this.comparator_=e,this.root_=t}insert(e,t){return new bu(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,yu.BLACK,null,null))}remove(e){return new bu(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,yu.BLACK,null,null))}get(e){var t;let r=this.root_;for(;!r.isEmpty();){if(0===(t=this.comparator_(e,r.key)))return r.value;t<0?r=r.left:0<t&&(r=r.right)}return null}getPredecessorKey(e){let t,r=this.root_,n=null;for(;!r.isEmpty();){if(0===(t=this.comparator_(e,r.key))){if(r.left.isEmpty())return n?n.key:null;for(r=r.left;!r.right.isEmpty();)r=r.right;return r.key}t<0?r=r.left:0<t&&(r=(n=r).right)}throw new Error("Attempted to find predecessor key for a nonexistent key. What gives?")}isEmpty(){return this.root_.isEmpty()}count(){return this.root_.count()}minKey(){return this.root_.minKey()}maxKey(){return this.root_.maxKey()}inorderTraversal(e){return this.root_.inorderTraversal(e)}reverseTraversal(e){return this.root_.reverseTraversal(e)}getIterator(e){return new _u(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new _u(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new _u(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new _u(this.root_,null,this.comparator_,!0,e)}}function Iu(e,t){return bc(e.name,t.name)}function Tu(e,t){return bc(e,t)}bu.EMPTY_NODE=new wu;let Eu;function Cu(e){return"number"==typeof e?"number:"+Tc(e):"string:"+e}function Su(e){var t;e.isLeafNode()?(t=e.val(),g("string"==typeof t||"number"==typeof t||"object"==typeof t&&we(t,".sv"),"Priority must be a string or number.")):g(e===Eu||e.isEmpty(),"priority of unexpected type."),g(e===Eu||e.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")}let ku;class Au{static set __childrenNodeConstructor(e){ku=e}static get __childrenNodeConstructor(){return ku}constructor(e,t=Au.__childrenNodeConstructor.EMPTY_NODE){this.value_=e,this.priorityNode_=t,this.lazyHash_=null,g(null!=this.value_,"LeafNode shouldn't be created with null/undefined value."),Su(this.priorityNode_)}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new Au(this.value_,e)}getImmediateChild(e){return".priority"===e?this.priorityNode_:Au.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return b(e)?this:".priority"===_(e)?this.priorityNode_:Au.__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:Au.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,t).updatePriority(this.priorityNode_)}updateChild(e,t){var r=_(e);return null===r?t:t.isEmpty()&&".priority"!==r?this:(g(".priority"!==r||1===eu(e),".priority must be the last token in a path"),this.updateImmediateChild(r,Au.__childrenNodeConstructor.EMPTY_NODE.updateChild(y(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:"+Cu(this.priorityNode_.val())+":");var t=typeof this.value_;e=(e+=t+":")+("number"==t?Tc(this.value_):this.value_),this.lazyHash_=Zh(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===Au.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof Au.__childrenNodeConstructor?-1:(g(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){var t=typeof e.value_,r=typeof this.value_,n=Au.VALUE_TYPE_ORDER.indexOf(t),i=Au.VALUE_TYPE_ORDER.indexOf(r);return g(0<=n,"Unknown leaf type: "+t),g(0<=i,"Unknown leaf type: "+r),n===i?"object"==r?0:this.value_<e.value_?-1:this.value_===e.value_?0:1:i-n}withIndex(){return this}isIndexed(){return!0}equals(e){return e===this||!!e.isLeafNode()&&this.value_===e.value_&&this.priorityNode_.equals(e.priorityNode_)}}Au.VALUE_TYPE_ORDER=["object","boolean","number","string"];let Nu,Ru;class Pu extends fu{compare(e,t){var r=e.node.getPriority(),n=t.node.getPriority(),r=r.compareTo(n);return 0===r?bc(e.name,t.name):r}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return d.MIN}maxPost(){return new d(wc,new Au("[PRIORITY-POST]",Ru))}makePost(e,t){var r=Nu(e);return new d(t,new Au("[PRIORITY-POST]",r))}toString(){return".priority"}}let I=new Pu,Du=Math.log(2);class xu{constructor(e){this.count=(t=e+1,parseInt(Math.log(t)/Du,10)),this.current_=this.count-1,t=this.count;var t,r=parseInt(Array(t+1).join("1"),2);this.bits_=e+1&r}nextBitIsOne(){var e=!(this.bits_&1<<this.current_);return this.current_--,e}}function Ou(l,e,h,t){l.sort(e);let c=function(e,t){var r,n,i=t-e;let s,a;return 0==i?null:1==i?(s=l[e],a=h?h(s):s,new yu(a,s.node,yu.BLACK,null,null)):(i=parseInt(i/2,10)+e,r=c(e,i),n=c(i+1,t),s=l[i],a=h?h(s):s,new yu(a,s.node,yu.BLACK,r,n))};var r=(e=>{let s=null,a=null,o=l.length;function t(e,t){var r=o-e,n=o,n=(o-=e,c(1+r,n)),r=l[r],i=h?h(r):r,e=new yu(i,r.node,t,null,n);s=(s?s.left=e:a=e,e)}for(let i=0;i<e.count;++i){var r=e.nextBitIsOne(),n=Math.pow(2,e.count-(i+1));r?t(n,yu.BLACK):(t(n,yu.BLACK),t(n,yu.RED))}return a})(new xu(l.length));return new bu(t||e,r)}let Mu,Lu={};class Fu{static get Default(){return g((Lu,I),"ChildrenNode.ts has not been loaded"),Mu=Mu||new Fu({".priority":Lu},{".priority":I})}constructor(e,t){this.indexes_=e,this.indexSet_=t}get(e){var t=be(this.indexes_,e);if(t)return t instanceof bu?t:null;throw new Error("No index defined for "+e)}hasIndex(e){return we(this.indexSet_,e.toString())}addIndex(e,t){g(e!==vu,"KeyIndex always exists and isn't meant to be added to the IndexMap.");var r=[];let n=!1;var i=t.getIterator(d.Wrap);let s=i.getNext();for(;s;)n=n||e.isDefinedOn(s.node),r.push(s),s=i.getNext();let a;a=n?Ou(r,e.getCompare()):Lu;var o=e.toString(),l={...this.indexSet_},h=(l[o]=e,{...this.indexes_});return h[o]=a,new Fu(h,l)}addToIndexes(s,a){var e=Te(this.indexes_,(t,e)=>{var r=be(this.indexSet_,e);if(g(r,"Missing index implementation for "+e),t===Lu){if(r.isDefinedOn(s.node)){var n=[],i=a.getIterator(d.Wrap);let e=i.getNext();for(;e;)e.name!==s.name&&n.push(e),e=i.getNext();return n.push(s),Ou(n,r.getCompare())}return Lu}{r=a.get(s.name);let e=t;return(e=r?e.remove(new d(s.name,r)):e).insert(s,s.node)}});return new Fu(e,this.indexSet_)}removeFromIndexes(r,n){var e=Te(this.indexes_,e=>{var t;return e!==Lu&&(t=n.get(r.name))?e.remove(new d(r.name,t)):e});return new Fu(e,this.indexSet_)}}let Uu;class T{static get EMPTY_NODE(){return Uu=Uu||new T(new bu(Tu),null,Fu.Default)}constructor(e,t,r){this.children_=e,this.priorityNode_=t,this.indexMap_=r,this.lazyHash_=null,this.priorityNode_&&Su(this.priorityNode_),this.children_.isEmpty()&&g(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}isLeafNode(){return!1}getPriority(){return this.priorityNode_||Uu}updatePriority(e){return this.children_.isEmpty()?this:new T(this.children_,e,this.indexMap_)}getImmediateChild(e){var t;return".priority"===e?this.getPriority():null===(t=this.children_.get(e))?Uu:t}getChild(e){var t=_(e);return null===t?this:this.getImmediateChild(t).getChild(y(e))}hasChild(e){return null!==this.children_.get(e)}updateImmediateChild(r,n){if(g(n,"We should always be passing snapshot nodes"),".priority"===r)return this.updatePriority(n);{var i=new d(r,n);let e,t;t=n.isEmpty()?(e=this.children_.remove(r),this.indexMap_.removeFromIndexes(i,this.children_)):(e=this.children_.insert(r,n),this.indexMap_.addToIndexes(i,this.children_));i=e.isEmpty()?Uu:this.priorityNode_;return new T(e,i,t)}}updateChild(e,t){var r,n=_(e);return null===n?t:(g(".priority"!==_(e)||1===eu(e),".priority must be the last token in a path"),r=this.getImmediateChild(n).updateChild(y(e),t),this.updateImmediateChild(n,r))}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(r){if(this.isEmpty())return null;let n={},i=0,s=0,a=!0;if(this.forEachChild(I,(e,t)=>{n[e]=t.val(r),i++,a&&T.INTEGER_REGEXP_.test(e)?s=Math.max(s,Number(e)):a=!1}),!r&&a&&s<2*i){var e,t=[];for(e in n)t[e]=n[e];return t}return r&&!this.getPriority().isEmpty()&&(n[".priority"]=this.getPriority().val()),n}hash(){if(null===this.lazyHash_){let n="";this.getPriority().isEmpty()||(n+="priority:"+Cu(this.getPriority().val())+":"),this.forEachChild(I,(e,t)=>{var r=t.hash();""!==r&&(n+=":"+e+":"+r)}),this.lazyHash_=""===n?"":Zh(n)}return this.lazyHash_}getPredecessorChildName(e,t,r){var n=this.resolveIndex_(r);return n?(n=n.getPredecessorKey(new d(e,t)))?n.name:null:this.children_.getPredecessorKey(e)}getFirstChildName(e){var t=this.resolveIndex_(e);return t?(t=t.minKey())&&t.name:this.children_.minKey()}getFirstChild(e){var t=this.getFirstChildName(e);return t?new d(t,this.children_.get(t)):null}getLastChildName(e){var t=this.resolveIndex_(e);return t?(t=t.maxKey())&&t.name:this.children_.maxKey()}getLastChild(e){var t=this.getLastChildName(e);return t?new d(t,this.children_.get(t)):null}forEachChild(e,t){var r=this.resolveIndex_(e);return r?r.inorderTraversal(e=>t(e.name,e.node)):this.children_.inorderTraversal(t)}getIterator(e){return this.getIteratorFrom(e.minPost(),e)}getIteratorFrom(t,r){var e=this.resolveIndex_(r);if(e)return e.getIteratorFrom(t,e=>e);{var n=this.children_.getIteratorFrom(t.name,d.Wrap);let e=n.peek();for(;null!=e&&r.compare(e,t)<0;)n.getNext(),e=n.peek();return n}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(t,r){var e=this.resolveIndex_(r);if(e)return e.getReverseIteratorFrom(t,e=>e);{var n=this.children_.getReverseIteratorFrom(t.name,d.Wrap);let e=n.peek();for(;null!=e&&0<r.compare(e,t);)n.getNext(),e=n.peek();return n}}compareTo(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===qu?-1:0}withIndex(e){var t;return e===vu||this.indexMap_.hasIndex(e)?this:(t=this.indexMap_.addIndex(e,this.children_),new T(this.children_,this.priorityNode_,t))}isIndexed(e){return e===vu||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;if(!e.isLeafNode()){var r=e;if(this.getPriority().equals(r.getPriority())){if(this.children_.count()!==r.children_.count())return!1;{var n=this.getIterator(I),i=r.getIterator(I);let e=n.getNext(),t=i.getNext();for(;e&&t;){if(e.name!==t.name||!e.node.equals(t.node))return!1;e=n.getNext(),t=i.getNext()}return null===e&&null===t}}}return!1}resolveIndex_(e){return e===vu?null:this.indexMap_.get(e.toString())}}T.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;class Vu extends T{constructor(){super(new bu(Tu),T.EMPTY_NODE,Fu.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return T.EMPTY_NODE}isEmpty(){return!1}}let qu=new Vu,Bu=(Object.defineProperties(d,{MIN:{value:new d(yc,T.EMPTY_NODE)},MAX:{value:new d(wc,qu)}}),mu.__EMPTY_NODE=T.EMPTY_NODE,Au.__childrenNodeConstructor=T,t=qu,Eu=t,t=qu,Ru=t,!0);function ju(s,e=null){if(null===s)return T.EMPTY_NODE;var t,r;if("object"==typeof s&&".priority"in s&&(e=s[".priority"]),g(null===e||"string"==typeof e||"number"==typeof e||"object"==typeof e&&".sv"in e,"Invalid priority type found: "+typeof e),"object"!=typeof(s="object"==typeof s&&".value"in s&&null!==s[".value"]?s[".value"]:s)||".sv"in s)return t=s,new Au(t,ju(e));if(s instanceof Array||!Bu){let n=T.EMPTY_NODE;return Ic(s,(e,t)=>{var r;!we(s,e)||"."===e.substring(0,1)||!(r=ju(t)).isLeafNode()&&r.isEmpty()||(n=n.updateImmediateChild(e,r))}),n.updatePriority(ju(e))}{let n=[],i=!1;return Ic(s,(e,t)=>{var r;"."===e.substring(0,1)||(r=ju(t)).isEmpty()||(i=i||!r.getPriority().isEmpty(),n.push(new d(e,r)))}),0===n.length?T.EMPTY_NODE:(t=Ou(n,Iu,e=>e.name,Tu),i?(r=Ou(n,I.getCompare()),new T(t,ju(e),new Fu({".priority":r},{".priority":I}))):new T(t,ju(e),Fu.Default))}}Nu=ju;class zu extends fu{constructor(e){super(),this.indexPath_=e,g(!b(e)&&".priority"!==_(e),"Can't create PathIndex with empty path or .priority key")}extractChild(e){return e.getChild(this.indexPath_)}isDefinedOn(e){return!e.getChild(this.indexPath_).isEmpty()}compare(e,t){var r=this.extractChild(e.node),n=this.extractChild(t.node),r=r.compareTo(n);return 0===r?bc(e.name,t.name):r}makePost(e,t){var r=ju(e),r=T.EMPTY_NODE.updateChild(this.indexPath_,r);return new d(t,r)}maxPost(){var e=T.EMPTY_NODE.updateChild(this.indexPath_,qu);return new d(wc,e)}toString(){return ru(this.indexPath_,0).join("/")}}class Ku extends fu{compare(e,t){var r=e.node.compareTo(t.node);return 0===r?bc(e.name,t.name):r}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return d.MIN}maxPost(){return d.MAX}makePost(e,t){var r=ju(e);return new d(t,r)}toString(){return".value"}}let Wu=new Ku;function Hu(e){return{type:"value",snapshotNode:e}}function Gu(e,t){return{type:"child_added",snapshotNode:t,childName:e}}function $u(e,t){return{type:"child_removed",snapshotNode:t,childName:e}}function Qu(e,t,r){return{type:"child_changed",snapshotNode:t,childName:e,oldSnap:r}}class Yu{constructor(e){this.index_=e}updateChild(e,t,r,n,i,s){g(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");var a=e.getImmediateChild(t);return a.getChild(n).equals(r.getChild(n))&&a.isEmpty()===r.isEmpty()||(null!=s&&(r.isEmpty()?e.hasChild(t)?s.trackChildChange($u(t,a)):g(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):a.isEmpty()?s.trackChildChange(Gu(t,r)):s.trackChildChange(Qu(t,r,a))),e.isLeafNode()&&r.isEmpty())?e:e.updateImmediateChild(t,r).withIndex(this.index_)}updateFullNode(n,r,i){return null!=i&&(n.isLeafNode()||n.forEachChild(I,(e,t)=>{r.hasChild(e)||i.trackChildChange($u(e,t))}),r.isLeafNode()||r.forEachChild(I,(e,t)=>{var r;n.hasChild(e)?(r=n.getImmediateChild(e)).equals(t)||i.trackChildChange(Qu(e,t,r)):i.trackChildChange(Gu(e,t))})),r.withIndex(this.index_)}updatePriority(e,t){return e.isEmpty()?T.EMPTY_NODE:e.updatePriority(t)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}class Ju{constructor(e){this.indexedFilter_=new Yu(e.getIndex()),this.index_=e.getIndex(),this.startPost_=Ju.getStartPost_(e),this.endPost_=Ju.getEndPost_(e),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){var t=this.startIsInclusive_?this.index_.compare(this.getStartPost(),e)<=0:this.index_.compare(this.getStartPost(),e)<0,r=this.endIsInclusive_?this.index_.compare(e,this.getEndPost())<=0:this.index_.compare(e,this.getEndPost())<0;return t&&r}updateChild(e,t,r,n,i,s){return this.matches(new d(t,r))||(r=T.EMPTY_NODE),this.indexedFilter_.updateChild(e,t,r,n,i,s)}updateFullNode(e,t,r){let n=(t=t.isLeafNode()?T.EMPTY_NODE:t).withIndex(this.index_),i=(n=n.updatePriority(T.EMPTY_NODE),this);return t.forEachChild(I,(e,t)=>{i.matches(new d(e,t))||(n=n.updateImmediateChild(e,T.EMPTY_NODE))}),this.indexedFilter_.updateFullNode(e,n,r)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){var t;return e.hasStart()?(t=e.getIndexStartName(),e.getIndex().makePost(e.getIndexStartValue(),t)):e.getIndex().minPost()}static getEndPost_(e){var t;return e.hasEnd()?(t=e.getIndexEndName(),e.getIndex().makePost(e.getIndexEndValue(),t)):e.getIndex().maxPost()}}class Xu{constructor(e){this.withinDirectionalStart=e=>this.reverse_?this.withinEndPost(e):this.withinStartPost(e),this.withinDirectionalEnd=e=>this.reverse_?this.withinStartPost(e):this.withinEndPost(e),this.withinStartPost=e=>{var t=this.index_.compare(this.rangedFilter_.getStartPost(),e);return this.startIsInclusive_?t<=0:t<0},this.withinEndPost=e=>{var t=this.index_.compare(e,this.rangedFilter_.getEndPost());return this.endIsInclusive_?t<=0:t<0},this.rangedFilter_=new Ju(e),this.index_=e.getIndex(),this.limit_=e.getLimit(),this.reverse_=!e.isViewFromLeft(),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}updateChild(e,t,r,n,i,s){return this.rangedFilter_.matches(new d(t,r))||(r=T.EMPTY_NODE),e.getImmediateChild(t).equals(r)?e:e.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(e,t,r,n,i,s):this.fullLimitUpdateChild_(e,t,r,i,s)}updateFullNode(e,r,t){let n;if(r.isLeafNode()||r.isEmpty())n=T.EMPTY_NODE.withIndex(this.index_);else if(2*this.limit_<r.numChildren()&&r.isIndexed(this.index_)){n=T.EMPTY_NODE.withIndex(this.index_);let e,t=(e=this.reverse_?r.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):r.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_),0);for(;e.hasNext()&&t<this.limit_;){var i=e.getNext();if(this.withinDirectionalStart(i)){if(!this.withinDirectionalEnd(i))break;n=n.updateImmediateChild(i.name,i.node),t++}}}else{n=(n=r.withIndex(this.index_)).updatePriority(T.EMPTY_NODE);let e,t=(e=this.reverse_?n.getReverseIterator(this.index_):n.getIterator(this.index_),0);for(;e.hasNext();){var s=e.getNext();t<this.limit_&&this.withinDirectionalStart(s)&&this.withinDirectionalEnd(s)?t++:n=n.updateImmediateChild(s.name,T.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(e,n,t)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}fullLimitUpdateChild_(e,t,r,n,i){let s;if(this.reverse_){let r=this.index_.getCompare();s=(e,t)=>r(t,e)}else s=this.index_.getCompare();var a=e,o=(g(a.numChildren()===this.limit_,""),new d(t,r)),l=this.reverse_?a.getFirstChild(this.index_):a.getLastChild(this.index_),h=this.rangedFilter_.matches(o);if(a.hasChild(t)){var c=a.getImmediateChild(t);let e=n.getChildAfterChild(this.index_,l,this.reverse_);for(;null!=e&&(e.name===t||a.hasChild(e.name));)e=n.getChildAfterChild(this.index_,e,this.reverse_);var u=null==e?1:s(e,o);return h&&!r.isEmpty()&&0<=u?(null!=i&&i.trackChildChange(Qu(t,r,c)),a.updateImmediateChild(t,r)):(null!=i&&i.trackChildChange($u(t,c)),u=a.updateImmediateChild(t,T.EMPTY_NODE),null!=e&&this.rangedFilter_.matches(e)?(null!=i&&i.trackChildChange(Gu(e.name,e.node)),u.updateImmediateChild(e.name,e.node)):u)}return!r.isEmpty()&&h&&0<=s(l,o)?(null!=i&&(i.trackChildChange($u(l.name,l.node)),i.trackChildChange(Gu(t,r))),a.updateImmediateChild(t,r).updateImmediateChild(l.name,T.EMPTY_NODE)):e}}class Zu{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_=I}hasStart(){return this.startSet_}isViewFromLeft(){return""===this.viewFrom_?this.startSet_:"l"===this.viewFrom_}getIndexStartValue(){return g(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return g(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:yc}hasEnd(){return this.endSet_}getIndexEndValue(){return g(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return g(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:wc}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&""!==this.viewFrom_}getLimit(){return g(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_===I}copy(){var e=new Zu;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 ed(e,t,r){var n=e.copy();return n.startSet_=!0,n.indexStartValue_=t=void 0===t?null:t,null!=r?(n.startNameSet_=!0,n.indexStartName_=r):(n.startNameSet_=!1,n.indexStartName_=""),n}function td(e,t,r){var n=e.copy();return n.endSet_=!0,n.indexEndValue_=t=void 0===t?null:t,void 0!==r?(n.endNameSet_=!0,n.indexEndName_=r):(n.endNameSet_=!1,n.indexEndName_=""),n}function rd(e,t){var r=e.copy();return r.index_=t,r}function nd(t){var r,n={};if(!t.isDefault()){let e;e=t.index_===I?"$priority":t.index_===Wu?"$value":t.index_===vu?"$key":(g(t.index_ instanceof zu,"Unrecognized index type!"),t.index_.toString()),n.orderBy=_e(e),t.startSet_&&(n[r=t.startAfterSet_?"startAfter":"startAt"]=_e(t.indexStartValue_),t.startNameSet_)&&(n[r]+=","+_e(t.indexStartName_)),t.endSet_&&(n[r=t.endBeforeSet_?"endBefore":"endAt"]=_e(t.indexEndValue_),t.endNameSet_)&&(n[r]+=","+_e(t.indexEndName_)),t.limitSet_&&(t.isViewFromLeft()?n.limitToFirst=t.limit_:n.limitToLast=t.limit_)}return n}function id(t){var r={};if(t.startSet_&&(r.sp=t.indexStartValue_,t.startNameSet_&&(r.sn=t.indexStartName_),r.sin=!t.startAfterSet_),t.endSet_&&(r.ep=t.indexEndValue_,t.endNameSet_&&(r.en=t.indexEndName_),r.ein=!t.endBeforeSet_),t.limitSet_){r.l=t.limit_;let e=t.viewFrom_;""===e&&(e=t.isViewFromLeft()?"l":"r"),r.vf=e}return t.index_!==I&&(r.i=t.index_.toString()),r}class sd extends Qc{reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,t){return void 0!==t?"tag$"+t:(g(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}constructor(e,t,r,n){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=r,this.appCheckTokenProvider_=n,this.log_=ec("p:rest:"),this.listens_={}}listen(e,t,n,i){let s=e._path.toString(),a=(this.log_("Listen called for "+s+" "+e._queryIdentifier),sd.getListenId_(e,n)),o={};this.listens_[a]=o;var r=nd(e._queryParams);this.restRequest_(s+".json",r,(t,e)=>{let r=e;if(null===(t=404===t?r=null:t)&&this.onDataUpdate_(s,r,!1,n),be(this.listens_,a)===o){let e;e=t?401===t?"permission_denied":"rest_error:"+t:"ok",i(e,null)}})}unlisten(e,t){var r=sd.getListenId_(e,t);delete this.listens_[r]}get(e){var t=nd(e._queryParams);let n=e._path.toString(),i=new Z;return this.restRequest_(n+".json",t,(e,t)=>{let r=t;null===(e=404===e?r=null:e)?(this.onDataUpdate_(n,r,!1,null),i.resolve(r)):i.reject(new Error(r))}),i.promise}refreshAuthToken(e){}restRequest_(i,s={},a){return s.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then(([e,t])=>{e&&e.accessToken&&(s.auth=e.accessToken),t&&t.token&&(s.ac=t.token);let r=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+i+"?ns="+this.repoInfo_.namespace+Se(s),n=(this.log_("Sending REST request for "+r),new XMLHttpRequest);n.onreadystatechange=()=>{if(a&&4===n.readyState){this.log_("REST Response for "+r+" received. status:",n.status,"response:",n.responseText);let e=null;if(200<=n.status&&n.status<300){try{e=ve(n.responseText)}catch(e){mc("Failed to parse JSON response for "+r+": "+n.responseText)}a(null,e)}else 401!==n.status&&404!==n.status&&mc("Got unsuccessful REST response for "+r+" Status: "+n.status),a(n.status);a=null}},n.open("GET",r,!0),n.send()})}}class ad{constructor(){this.rootNode_=T.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}function od(){return{value:null,children:new Map}}function ld(e,t,r){var n;b(t)?(e.value=r,e.children.clear()):null!==e.value?e.value=e.value.updateChild(t,r):(n=_(t),e.children.has(n)||e.children.set(n,od()),ld(e.children.get(n),t=y(t),r))}function hd(e,r,n){var i;null!==e.value?n(r,e.value):(i=(e,t)=>{hd(t,new f(r.toString()+"/"+e),n)},e.children.forEach((e,t)=>{i(t,e)}))}class cd{constructor(e){this.collection_=e,this.last_=null}get(){var e=this.collection_.get();let r={...e};return this.last_&&Ic(this.last_,(e,t)=>{r[e]=r[e]-t}),this.last_=e,r}}class ud{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new cd(e);var r=1e4+2e4*Math.random();Cc(this.reportStats_.bind(this),Math.floor(r))}reportStats_(){var e=this.statsListener_.get();let r={},n=!1;Ic(e,(e,t)=>{0<t&&we(this.statsToReport_,e)&&(r[e]=t,n=!0)}),n&&this.server_.reportStats(r),Cc(this.reportStats_.bind(this),Math.floor(2*Math.random()*3e5))}}function dd(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function pd(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function fd(e){return{fromUser:!1,fromServer:!0,queryId:e,tagged:!0}}(t=Xh=Xh||{})[t.OVERWRITE=0]="OVERWRITE",t[t.MERGE=1]="MERGE",t[t.ACK_USER_WRITE=2]="ACK_USER_WRITE",t[t.LISTEN_COMPLETE=3]="LISTEN_COMPLETE";class gd{constructor(e,t,r){this.path=e,this.affectedTree=t,this.revert=r,this.type=Xh.ACK_USER_WRITE,this.source=dd()}operationForChild(e){var t;return b(this.path)?null!=this.affectedTree.value?(g(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this):(t=this.affectedTree.subtree(new f(e)),new gd(v(),t,this.revert)):(g(_(this.path)===e,"operationForChild called for unrelated child."),new gd(y(this.path),this.affectedTree,this.revert))}}class md{constructor(e,t){this.source=e,this.path=t,this.type=Xh.LISTEN_COMPLETE}operationForChild(e){return b(this.path)?new md(this.source,v()):new md(this.source,y(this.path))}}class vd{constructor(e,t,r){this.source=e,this.path=t,this.snap=r,this.type=Xh.OVERWRITE}operationForChild(e){return b(this.path)?new vd(this.source,v(),this.snap.getImmediateChild(e)):new vd(this.source,y(this.path),this.snap)}}class _d{constructor(e,t,r){this.source=e,this.path=t,this.children=r,this.type=Xh.MERGE}operationForChild(e){var t;return b(this.path)?(t=this.children.subtree(new f(e))).isEmpty()?null:t.value?new vd(this.source,v(),t.value):new _d(this.source,v(),t):(g(_(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new _d(this.source,y(this.path),this.children))}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}class yd{constructor(e,t,r){this.node_=e,this.fullyInitialized_=t,this.filtered_=r}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){var t;return b(e)?this.isFullyInitialized()&&!this.filtered_:(t=_(e),this.isCompleteForChild(t))}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}class wd{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function bd(r,e,t,n){var i=[];let s=[];return e.forEach(e=>{var t;"child_changed"===e.type&&r.index_.indexedValueChanged(e.oldSnap,e.snapshotNode)&&s.push((t=e.childName,{type:"child_moved",snapshotNode:e.snapshotNode,childName:t}))}),Id(r,i,"child_removed",e,n,t),Id(r,i,"child_added",e,n,t),Id(r,i,"child_moved",s,n,t),Id(r,i,"child_changed",e,n,t),Id(r,i,"value",e,n,t),i}function Id(s,a,t,e,o,l){var r=e.filter(e=>e.type===t);r.sort((e,t)=>{var r=s;if(null==e.childName||null==t.childName)throw B("Should only compare child_ events.");var n=new d(e.childName,e.snapshotNode),i=new d(t.childName,t.snapshotNode);return r.index_.compare(n,i)}),r.forEach(t=>{e=s,i=l,"value"!==(n=t).type&&"child_removed"!==n.type&&(n.prevName=i.getPredecessorChildName(n.childName,n.snapshotNode,e.index_));let r=n;var e,n,i;o.forEach(e=>{e.respondsTo(t.type)&&a.push(e.createEvent(r,s.query_))})})}function Td(e,t){return{eventCache:e,serverCache:t}}function Ed(e,t,r,n){return Td(new yd(t,r,n),e.serverCache)}function Cd(e,t,r,n){return Td(e.eventCache,new yd(t,r,n))}function Sd(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function kd(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}let Ad;class Nd{static fromObject(e){let r=new Nd(null);return Ic(e,(e,t)=>{r=r.set(new f(e),t)}),r}constructor(e,t=Ad=Ad||new bu(rc)){this.value=e,this.children=t}isEmpty(){return null===this.value&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){var r,n;return null!=this.value&&t(this.value)?{path:v(),value:this.value}:!b(e)&&(r=_(e),null!==(n=this.children.get(r)))&&null!=(n=n.findRootMostMatchingPathAndValue(y(e),t))?{path:iu(new f(r),n.path),value:n.value}:null}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,()=>!0)}subtree(e){var t;return b(e)?this:(t=_(e),null!==(t=this.children.get(t))?t.subtree(y(e)):new Nd(null))}set(e,t){var r,n;return b(e)?new Nd(t,this.children):(n=_(e),r=(this.children.get(n)||new Nd(null)).set(y(e),t),n=this.children.insert(n,r),new Nd(this.value,n))}remove(t){if(b(t))return this.children.isEmpty()?new Nd(null):new Nd(null,this.children);var r=_(t),n=this.children.get(r);if(n){n=n.remove(y(t));let e;return e=n.isEmpty()?this.children.remove(r):this.children.insert(r,n),null===this.value&&e.isEmpty()?new Nd(null):new Nd(this.value,e)}return this}get(e){var t;return b(e)?this.value:(t=_(e),(t=this.children.get(t))?t.get(y(e)):null)}setTree(t,r){if(b(t))return r;{var n=_(t),i=(this.children.get(n)||new Nd(null)).setTree(y(t),r);let e;return e=i.isEmpty()?this.children.remove(n):this.children.insert(n,i),new Nd(this.value,e)}}fold(e){return this.fold_(v(),e)}fold_(r,n){let i={};return this.children.inorderTraversal((e,t)=>{i[e]=t.fold_(iu(r,e),n)}),n(r,this.value,i)}findOnPath(e,t){return this.findOnPath_(e,v(),t)}findOnPath_(e,t,r){var n,i=!!this.value&&r(t,this.value);return i||(!b(e)&&(i=_(e),n=this.children.get(i))?n.findOnPath_(y(e),iu(t,i),r):null)}foreachOnPath(e,t){return this.foreachOnPath_(e,v(),t)}foreachOnPath_(e,t,r){var n,i;return b(e)?this:(this.value&&r(t,this.value),n=_(e),(i=this.children.get(n))?i.foreachOnPath_(y(e),iu(t,n),r):new Nd(null))}foreach(e){this.foreach_(v(),e)}foreach_(r,n){this.children.inorderTraversal((e,t)=>{t.foreach_(iu(r,e),n)}),this.value&&n(r,this.value)}foreachChild(r){this.children.inorderTraversal((e,t)=>{t.value&&r(e,t.value)})}}class Rd{constructor(e){this.writeTree_=e}static empty(){return new Rd(new Nd(null))}}function Pd(t,r,n){if(b(r))return new Rd(new Nd(n));var i=t.writeTree_.findRootMostValueAndPath(r);if(null==i)return s=new Nd(n),s=t.writeTree_.setTree(r,s),new Rd(s);{var s=i.path;let e=i.value;i=su(s,r);return e=e.updateChild(i,n),new Rd(t.writeTree_.set(s,e))}}function Dd(e,r,t){let n=e;return Ic(t,(e,t)=>{n=Pd(n,iu(r,e),t)}),n}function xd(e,t){var r;return b(t)?Rd.empty():(r=e.writeTree_.setTree(t,new Nd(null)),new Rd(r))}function Od(e,t){return null!=Md(e,t)}function Md(e,t){var r=e.writeTree_.findRootMostValueAndPath(t);return null!=r?e.writeTree_.get(r.path).getChild(su(r.path,t)):null}function Ld(e){let r=[];var t=e.writeTree_.value;return null!=t?t.isLeafNode()||t.forEachChild(I,(e,t)=>{r.push(new d(e,t))}):e.writeTree_.children.inorderTraversal((e,t)=>{null!=t.value&&r.push(new d(e,t.value))}),r}function Fd(e,t){var r;return b(t)?e:null!=(r=Md(e,t))?new Rd(new Nd(r)):new Rd(e.writeTree_.subtree(t))}function Ud(e){return e.writeTree_.isEmpty()}function Vd(e,t){return function n(i,e,s){{if(null!=e.value)return s.updateChild(i,e.value);{let r=null;return e.children.inorderTraversal((e,t)=>{".priority"===e?(g(null!==t.value,"Priority writes must always be leaf nodes"),r=t.value):s=n(iu(i,e),t,s)}),s=s.getChild(i).isEmpty()||null===r?s:s.updateChild(iu(i,".priority"),r)}}}(v(),e.writeTree_,t)}function qd(e,t){return Xd(t,e)}function Bd(t,r){var e,n=t.allWrites.findIndex(e=>e.writeId===r);g(0<=n,"removeWrite called with nonexistent writeId.");let i=t.allWrites[n],s=(t.allWrites.splice(n,1),i.visible),a=!1,o=t.allWrites.length-1;for(;s&&0<=o;){var l=t.allWrites[o];l.visible&&(o>=n&&((e,t)=>{if(e.snap)return lu(e.path,t);for(var r in e.children)if(e.children.hasOwnProperty(r)&&lu(iu(e.path,r),t))return 1})(l,i.path)?s=!1:lu(i.path,l.path)&&(a=!0)),o--}return!!s&&(a?((e=t).visibleWrites=zd(e.allWrites,jd,v()),0<e.allWrites.length?e.lastWriteId=e.allWrites[e.allWrites.length-1].writeId:e.lastWriteId=-1):i.snap?t.visibleWrites=xd(t.visibleWrites,i.path):Ic(i.children,e=>{t.visibleWrites=xd(t.visibleWrites,iu(i.path,e))}),!0)}function jd(e){return e.visible}function zd(e,t,r){let n=Rd.empty();for(let a=0;a<e.length;++a){var i=e[a];if(t(i)){var s=i.path;let e;if(i.snap)lu(r,s)?(e=su(r,s),n=Pd(n,e,i.snap)):lu(s,r)&&(e=su(s,r),n=Pd(n,v(),i.snap.getChild(e)));else{if(!i.children)throw B("WriteRecord should have .snap or .children");lu(r,s)?(e=su(r,s),n=Dd(n,e,i.children)):lu(s,r)&&(b(e=su(s,r))?n=Dd(n,v(),i.children):(s=be(i.children,_(e)))&&(i=s.getChild(y(e)),n=Pd(n,v(),i)))}}}return n}function Kd(e,t,r,n,i){var s;return n||i?(s=Fd(e.visibleWrites,t),!i&&Ud(s)?r:i||null!=r||Od(s,v())?Vd(zd(e.allWrites,function(e){return(e.visible||i)&&(!n||!~n.indexOf(e.writeId))&&(lu(e.path,t)||lu(t,e.path))},t),r||T.EMPTY_NODE):null):null!=(s=Md(e.visibleWrites,t))?s:Ud(s=Fd(e.visibleWrites,t))?r:null!=r||Od(s,v())?Vd(s,r||T.EMPTY_NODE):null}function Wd(e,t,r,n){return Kd(e.writeTree,e.treePath,t,r,n)}function Hd(e,t){{var r=e.writeTree;e=e.treePath;let i=T.EMPTY_NODE;var n=Md(r.visibleWrites,e);if(n)n.isLeafNode()||n.forEachChild(I,(e,t)=>{i=i.updateImmediateChild(e,t)});else if(t){let n=Fd(r.visibleWrites,e);t.forEachChild(I,(e,t)=>{var r=Vd(Fd(n,new f(e)),t);i=i.updateImmediateChild(e,r)}),Ld(n).forEach(e=>{i=i.updateImmediateChild(e.name,e.node)})}else Ld(Fd(r.visibleWrites,e)).forEach(e=>{i=i.updateImmediateChild(e.name,e.node)});return i}}function Gd(e,t,r,n){return i=e.writeTree,e=e.treePath,t=t,r=r,n=n,g(r||n,"Either existingEventSnap or existingServerSnap must exist"),s=iu(e,t),Od(i.visibleWrites,s)?null:Ud(s=Fd(i.visibleWrites,s))?n.getChild(t):Vd(s,n.getChild(t));var i,s}function $d(e,t){return r=e.writeTree,e=iu(e.treePath,t),Md(r.visibleWrites,e);var r}function Qd(e,r,n,i,s,a){{var o=e.writeTree,l=(e=e.treePath,n),h=i;n=s,i=a;let t;var c=Fd(o.visibleWrites,e),u=Md(c,v());if(null!=u)t=u;else{if(null==r)return[];t=Vd(c,r)}if((t=t.withIndex(i)).isEmpty()||t.isLeafNode())return[];{var d=[],p=i.getCompare(),f=n?t.getReverseIteratorFrom(l,i):t.getIteratorFrom(l,i);let e=f.getNext();for(;e&&d.length<h;)0!==p(e,l)&&d.push(e),e=f.getNext();return d}}}function Yd(e,t,r){return n=e.writeTree,r=r,i=iu(e.treePath,e=t),null!=(s=Md(n.visibleWrites,i))?s:r.isCompleteForChild(e)?Vd(Fd(n.visibleWrites,i),r.getNode().getImmediateChild(e)):null;var n,i,s}function Jd(e,t){return Xd(iu(e.treePath,t),e.writeTree)}function Xd(e,t){return{treePath:e,writeTree:t}}class Zd{constructor(){this.changeMap=new Map}trackChildChange(e){var t=e.type,r=e.childName,n=(g("child_added"===t||"child_changed"===t||"child_removed"===t,"Only child changes supported for tracking"),g(".priority"!==r,"Only non-priority child changes can be tracked."),this.changeMap.get(r));if(n){var i=n.type;if("child_added"===t&&"child_removed"===i)this.changeMap.set(r,Qu(r,e.snapshotNode,n.snapshotNode));else if("child_removed"===t&&"child_added"===i)this.changeMap.delete(r);else if("child_removed"===t&&"child_changed"===i)this.changeMap.set(r,$u(r,n.oldSnap));else if("child_changed"===t&&"child_added"===i)this.changeMap.set(r,Gu(r,e.snapshotNode));else{if("child_changed"!==t||"child_changed"!==i)throw B("Illegal combination of changes: "+e+" occurred after "+n);this.changeMap.set(r,Qu(r,e.snapshotNode,n.oldSnap))}}else this.changeMap.set(r,e)}getChanges(){return Array.from(this.changeMap.values())}}let ep=new class{getCompleteChild(e){return null}getChildAfterChild(e,t,r){return null}};class tp{constructor(e,t,r=null){this.writes_=e,this.viewCache_=t,this.optCompleteServerCache_=r}getCompleteChild(e){var t=this.viewCache_.eventCache;return t.isCompleteForChild(e)?t.getNode().getImmediateChild(e):(t=null!=this.optCompleteServerCache_?new yd(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache,Yd(this.writes_,e,t))}getChildAfterChild(e,t,r){var n=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:kd(this.viewCache_),n=Qd(this.writes_,n,t,1,r,e);return 0===n.length?null:n[0]}}function rp(e,t,r,n,i){var s=new Zd;let a,o;if(r.type===Xh.OVERWRITE){var l=r;a=l.source.fromUser?sp(e,t,l.path,l.snap,n,i,s):(g(l.source.fromServer,"Unknown source."),o=l.source.tagged||t.serverCache.isFiltered()&&!b(l.path),ip(e,t,l.path,l.snap,n,i,o,s))}else if(r.type===Xh.MERGE){var l=r;a=l.source.fromUser?((n,i,s,e,a,o,l)=>{let h=i;return e.foreach((e,t)=>{var r=iu(s,e);ap(i,_(r))&&(h=sp(n,h,r,t,a,o,l))}),e.foreach((e,t)=>{var r=iu(s,e);ap(i,_(r))||(h=sp(n,h,r,t,a,o,l))}),h})(e,t,l.path,l.children,n,i,s):(g(l.source.fromServer,"Unknown source."),o=l.source.tagged||t.serverCache.isFiltered(),lp(e,t,l.path,l.children,n,i,o,s))}else if(r.type===Xh.ACK_USER_WRITE){l=r;a=l.revert?((r,n,i,s,e,a)=>{let o;if(null!=$d(s,i))return n;{var l=new tp(s,n,e),h=n.eventCache.getNode();let t;if(b(i)||".priority"===_(i)){let e;e=e=n.serverCache.isFullyInitialized()?Wd(s,kd(n)):(c=n.serverCache.getNode(),g(c instanceof T,"serverChildren would be complete if leaf node"),Hd(s,c)),t=r.filter.updateFullNode(h,e,a)}else{var c=_(i);let e=Yd(s,c,n.serverCache);null==e&&n.serverCache.isCompleteForChild(c)&&(e=h.getImmediateChild(c)),(t=null!=e?r.filter.updateChild(h,c,e,y(i),l,a):n.eventCache.getNode().hasChild(c)?r.filter.updateChild(h,c,T.EMPTY_NODE,y(i),l,a):h).isEmpty()&&n.serverCache.isFullyInitialized()&&(o=Wd(s,kd(n))).isLeafNode()&&(t=r.filter.updateFullNode(t,o,a))}return o=n.serverCache.isFullyInitialized()||null!=$d(s,v()),Ed(n,t,o,r.filter.filtersNodes())}})(e,t,l.path,n,i,s):((e,t,i,r,s,a,o)=>{if(null!=$d(s,i))return t;let l=t.serverCache.isFiltered(),h=t.serverCache;if(null!=r.value){if(b(i)&&h.isFullyInitialized()||h.isCompleteForPath(i))return ip(e,t,i,h.getNode().getChild(i),s,a,l,o);if(b(i)){let r=new Nd(null);return h.getNode().forEachChild(vu,(e,t)=>{r=r.set(new f(e),t)}),lp(e,t,i,r,s,a,l,o)}return t}{let n=new Nd(null);return r.foreach((e,t)=>{var r=iu(i,e);h.isCompleteForPath(r)&&(n=n.set(e,h.getNode().getChild(r)))}),lp(e,t,i,n,s,a,l,o)}})(e,t,l.path,l.affectedTree,n,i,s)}else{if(r.type!==Xh.LISTEN_COMPLETE)throw B("Unknown operation type: "+r.type);a=(i=e,e=r.path,r=n,n=s,l=t.serverCache,l=Cd(t,l.getNode(),l.isFullyInitialized()||b(e),l.isFiltered()),np(i,l,e,r,ep,n))}var h,c,s=s.getChanges(),i=t,e=a,r=s,u=e.eventCache;return u.isFullyInitialized()&&(h=u.getNode().isLeafNode()||u.getNode().isEmpty(),c=Sd(i),0<r.length||!i.eventCache.isFullyInitialized()||h&&!u.getNode().equals(c)||!u.getNode().getPriority().equals(c.getPriority()))&&r.push(Hu(Sd(e))),{viewCache:a,changes:s}}function np(n,i,s,a,o,l){var h=i.eventCache;if(null!=$d(a,s))return i;{let t,r;if(b(s))g(i.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),t=i.serverCache.isFiltered()?(c=Hd(a,(c=kd(i))instanceof T?c:T.EMPTY_NODE),n.filter.updateFullNode(i.eventCache.getNode(),c,l)):(c=Wd(a,kd(i)),n.filter.updateFullNode(i.eventCache.getNode(),c,l));else{var c=_(s);if(".priority"===c){g(1===eu(s),"Can't have a priority with additional path components");var u=h.getNode(),d=Gd(a,s,u,r=i.serverCache.getNode());t=null!=d?n.filter.updatePriority(u,d):h.getNode()}else{u=y(s);let e;e=h.isCompleteForChild(c)?(r=i.serverCache.getNode(),null!=(d=Gd(a,s,h.getNode(),r))?h.getNode().getImmediateChild(c).updateChild(u,d):h.getNode().getImmediateChild(c)):Yd(a,c,i.serverCache),t=null!=e?n.filter.updateChild(h.getNode(),c,e,u,o,l):h.getNode()}}return Ed(i,t,h.isFullyInitialized()||b(s),n.filter.filtersNodes())}}function ip(e,t,r,n,i,s,a,o){var l=t.serverCache;let h;var c=a?e.filter:e.filter.getIndexedFilter();if(b(r))h=c.updateFullNode(l.getNode(),n,null);else if(c.filtersNodes()&&!l.isFiltered()){var u=l.getNode().updateChild(r,n);h=c.updateFullNode(l.getNode(),u,null)}else{u=_(r);if(!l.isCompleteForPath(r)&&1<eu(r))return t;var d=y(r),p=l.getNode().getImmediateChild(u).updateChild(d,n);h=".priority"===u?c.updatePriority(l.getNode(),p):c.updateChild(l.getNode(),u,p,d,ep,null)}u=Cd(t,h,l.isFullyInitialized()||b(r),c.filtersNodes());return np(e,u,r,i,new tp(i,u,s),o)}function sp(t,r,n,i,e,s,a){var o=r.eventCache;let l,h;var c=new tp(e,r,s);if(b(n))h=t.filter.updateFullNode(r.eventCache.getNode(),i,a),l=Ed(r,h,!0,t.filter.filtersNodes());else{var u=_(n);if(".priority"===u)h=t.filter.updatePriority(r.eventCache.getNode(),i),l=Ed(r,h,o.isFullyInitialized(),o.isFiltered());else{var d,p=y(n),f=o.getNode().getImmediateChild(u);let e;e=b(p)?i:null!=(d=c.getCompleteChild(u))?".priority"===tu(p)&&d.getChild(nu(p)).isEmpty()?d:d.updateChild(p,i):T.EMPTY_NODE,l=f.equals(e)?r:Ed(r,t.filter.updateChild(o.getNode(),u,e,p,c,a),o.isFullyInitialized(),t.filter.filtersNodes())}}return l}function ap(e,t){return e.eventCache.isCompleteForChild(t)}function op(e,r,t){return t.foreach((e,t)=>{r=r.updateChild(e,t)}),r}function lp(n,i,e,t,s,a,o,l){if(i.serverCache.getNode().isEmpty()&&!i.serverCache.isFullyInitialized())return i;let h=i,r,c=(r=b(e)?t:new Nd(null).setTree(e,t),i.serverCache.getNode());return r.children.inorderTraversal((e,t)=>{var r;c.hasChild(e)&&(r=op(0,i.serverCache.getNode().getImmediateChild(e),t),h=ip(n,h,new f(e),r,s,a,o,l))}),r.children.inorderTraversal((e,t)=>{var r=!i.serverCache.isCompleteForChild(e)&&null===t.value;c.hasChild(e)||r||(r=op(0,i.serverCache.getNode().getImmediateChild(e),t),h=ip(n,h,new f(e),r,s,a,o,l))}),h}class hp{constructor(e,t){this.query_=e,this.eventRegistrations_=[];var r=this.query_._queryParams,n=new Yu(r.getIndex()),r=(e=r).loadsAllData()?new Yu(e.getIndex()):new(e.hasLimit()?Xu:Ju)(e),i=(this.processor_={filter:r},t.serverCache),s=t.eventCache,a=n.updateFullNode(T.EMPTY_NODE,i.getNode(),null),o=r.updateFullNode(T.EMPTY_NODE,s.getNode(),null),a=new yd(a,i.isFullyInitialized(),n.filtersNodes()),i=new yd(o,s.isFullyInitialized(),r.filtersNodes());this.viewCache_=Td(i,a),this.eventGenerator_=new wd(this.query_)}get query(){return this.query_}}function cp(e){return 0===e.eventRegistrations_.length}function up(n,i,s){let a=[];if(s){g(null==i,"A cancel should cancel all event registrations.");let r=n.query._path;n.eventRegistrations_.forEach(e=>{var t=e.createCancelEvent(s,r);t&&a.push(t)})}if(i){let e=[];for(let t=0;t<n.eventRegistrations_.length;++t){var r=n.eventRegistrations_[t];if(r.matches(i)){if(i.hasAnyCallback()){e=e.concat(n.eventRegistrations_.slice(t+1));break}}else e.push(r)}n.eventRegistrations_=e}else n.eventRegistrations_=[];return a}function dp(e,t,r,n){t.type===Xh.MERGE&&null!==t.source.queryId&&(g(kd(e.viewCache_),"We should always have a full cache before handling merges"),g(Sd(e.viewCache_),"Missing event cache, even though we have a server cache"));var i=e.viewCache_,s=rp(e.processor_,i,t,r,n);return t=e.processor_,r=s.viewCache,g(r.eventCache.getNode().isIndexed(t.filter.getIndex()),"Event snap not indexed"),g(r.serverCache.getNode().isIndexed(t.filter.getIndex()),"Server snap not indexed"),g(s.viewCache.serverCache.isFullyInitialized()||!i.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),e.viewCache_=s.viewCache,pp(e,s.changes,s.viewCache.eventCache.getNode(),null)}function pp(e,t,r,n){var i=n?[n]:e.eventRegistrations_;return bd(e.eventGenerator_,t,r,i)}let fp;class gp{constructor(){this.views=new Map}}function mp(t,r,n,i){var e=r.source.queryId;if(null!==e)return e=t.views.get(e),g(null!=e,"SyncTree gave us an op for an invalid query."),dp(e,r,n,i);{let e=[];for(var s of t.views.values())e=e.concat(dp(s,r,n,i));return e}}function vp(e,r,n,i,s){var a=r._queryIdentifier,a=e.views.get(a);if(a)return a;{let e=Wd(n,s?i:null),t=!1;t=!!e||(e=i instanceof T?Hd(n,i):T.EMPTY_NODE,!1);a=Td(new yd(e,t,!1),new yd(i,s,!1));return new hp(r,a)}}function _p(e,t,n,i,s,r){var a=vp(e,t,i,s,r);e.views.has(t._queryIdentifier)||e.views.set(t._queryIdentifier,a),a.eventRegistrations_.push(n);{s=n,a=(i=a).viewCache_.eventCache;let r=[];return a.getNode().isLeafNode()||a.getNode().forEachChild(I,(e,t)=>{r.push(Gu(e,t))}),a.isFullyInitialized()&&r.push(Hu(a.getNode())),pp(i,r,a.getNode(),s)}}function yp(e,t,r,n){var i=t._queryIdentifier,s=[];let a=[];var o=Ep(e);if("default"===i)for(var[l,h]of e.views.entries())a=a.concat(up(h,r,n)),cp(h)&&(e.views.delete(l),h.query._queryParams.loadsAllData()||s.push(h.query));else{var c=e.views.get(i);c&&(a=a.concat(up(c,r,n)),cp(c))&&(e.views.delete(i),c.query._queryParams.loadsAllData()||s.push(c.query))}return o&&!Ep(e)&&s.push((g(fp,"Reference.ts has not been loaded"),new fp(t._repo,t._path))),{removed:s,events:a}}function wp(e){var t,r=[];for(t of e.views.values())t.query._queryParams.loadsAllData()||r.push(t);return r}function bp(e,t){let r=null;for(var n of e.views.values())r=r||(i=n,s=t,n=void 0,(n=kd(i.viewCache_))&&(i.query._queryParams.loadsAllData()||!b(s)&&!n.getImmediateChild(_(s)).isEmpty())?n.getChild(s):null);var i,s;return r}function Ip(e,t){var r;return t._queryParams.loadsAllData()?Cp(e):(r=t._queryIdentifier,e.views.get(r))}function Tp(e,t){return null!=Ip(e,t)}function Ep(e){return null!=Cp(e)}function Cp(e){for(var t of e.views.values())if(t.query._queryParams.loadsAllData())return t;return null}let Sp;let kp=1;class Ap{constructor(e){this.listenProvider_=e,this.syncPointTree_=new Nd(null),this.pendingWriteTree_={visibleWrites:Rd.empty(),allWrites:[],lastWriteId:-1},this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function Np(e,t,r,n,i){var s,a,o,l;return s=e.pendingWriteTree_,a=t,o=r,n=n,l=i,g(n>s.lastWriteId,"Stacking an older write on top of newer ones"),s.allWrites.push({path:a,snap:o,writeId:n,visible:l=void 0===l?!0:l}),l&&(s.visibleWrites=Pd(s.visibleWrites,a,o)),s.lastWriteId=n,i?Up(e,new vd(dd(),t,r)):[]}function Rp(e,t,r,n){i=e.pendingWriteTree_,s=t,a=r,n=n,g(n>i.lastWriteId,"Stacking an older merge on top of newer ones"),i.allWrites.push({path:s,children:a,writeId:n,visible:!0}),i.visibleWrites=Dd(i.visibleWrites,s,a),i.lastWriteId=n;var i,s,a,o=Nd.fromObject(r);return Up(e,new _d(dd(),t,o))}function Pp(e,t,r=!1){var n=((e,t)=>{for(let n=0;n<e.allWrites.length;n++){var r=e.allWrites[n];if(r.writeId===t)return r}return null})(e.pendingWriteTree_,t);if(Bd(e.pendingWriteTree_,t)){let t=new Nd(null);return null!=n.snap?t=t.set(v(),!0):Ic(n.children,e=>{t=t.set(new f(e),!0)}),Up(e,new gd(n.path,t,r))}return[]}function Dp(e,t,r){return Up(e,new vd(pd(),t,r))}function xp(r,t,n,i,s=!1){var a=t._path,o=r.syncPointTree_.get(a);let l=[];if(o&&("default"===t._queryIdentifier||Tp(o,t))){var h=yp(o,t,n,i),o=(0===o.views.size&&(r.syncPointTree_=r.syncPointTree_.remove(a)),h.removed);if(l=h.events,!s){var h=-1!==o.findIndex(e=>e._queryParams.loadsAllData()),c=r.syncPointTree_.findOnPath(a,(e,t)=>Ep(t));if(h&&!c){a=r.syncPointTree_.subtree(a);if(!a.isEmpty()){var u=a.fold((e,t,n)=>{if(t&&Ep(t))return[Cp(t)];{let r=[];return t&&(r=wp(t)),Ic(n,(e,t)=>{r=r.concat(t)}),r}});for(let e=0;e<u.length;++e){var d=u[e],p=d.query,d=qp(r,d);r.listenProvider_.startListening(Hp(p),Bp(r,p),d.hashFn,d.onComplete)}}}!c&&0<o.length&&!i&&(h?r.listenProvider_.stopListening(Hp(t),null):o.forEach(e=>{var t=r.queryToTagMap.get(jp(e));r.listenProvider_.stopListening(Hp(e),t)}))}var f=r,g=o;for(let e=0;e<g.length;++e){var m,v=g[e];v._queryParams.loadsAllData()||(v=jp(v),m=f.queryToTagMap.get(v),f.queryToTagMap.delete(v),f.tagToQueryMap.delete(m))}}return l}function Op(e,t,r,n){var i,s,a=zp(e,n);return null!=a?(i=(a=Kp(a)).path,a=a.queryId,s=su(i,t),Wp(e,i,new vd(fd(a),s,r))):[]}function Mp(e,t,r,n=!1){let i=t._path,s=null,a=!1,o=(e.syncPointTree_.foreachOnPath(i,(e,t)=>{var r=su(e,i);s=s||bp(t,r),a=a||Ep(t)}),e.syncPointTree_.get(i));o?(a=a||Ep(o),s=s||bp(o,v())):(o=new gp,e.syncPointTree_=e.syncPointTree_.set(i,o));let l;null!=s?l=!0:(l=!1,s=T.EMPTY_NODE,e.syncPointTree_.subtree(i).foreachChild((e,t)=>{var r=bp(t,v());r&&(s=s.updateImmediateChild(e,r))}));var h,c=Tp(o,t),u=(c||t._queryParams.loadsAllData()||(h=jp(t),g(!e.queryToTagMap.has(h),"View does not exist, but we have a tag"),u=kp++,e.queryToTagMap.set(h,u),e.tagToQueryMap.set(u,h)),qd(e.pendingWriteTree_,i));let d=_p(o,t,r,u,s,l);return c||a||n||(h=Ip(o,t),d=d.concat(((t,e,r)=>{var n=e._path,i=Bp(t,e),s=qp(t,r),s=t.listenProvider_.startListening(Hp(e),i,s.hashFn,s.onComplete),n=t.syncPointTree_.subtree(n);if(i)g(!Ep(n.value),"If we're adding a query, it shouldn't be shadowed");else{var a=n.fold((e,t,n)=>{if(!b(e)&&t&&Ep(t))return[Cp(t).query];{let r=[];return t&&(r=r.concat(wp(t).map(e=>e.query))),Ic(n,(e,t)=>{r=r.concat(t)}),r}});for(let e=0;e<a.length;++e){var o=a[e];t.listenProvider_.stopListening(Hp(o),Bp(t,o))}}return s})(e,t,h))),d}function Lp(e,n,t){var r=e.pendingWriteTree_,i=e.syncPointTree_.findOnPath(n,(e,t)=>{var r=bp(t,su(e,n));if(r)return r});return Kd(r,n,i,t,!0)}function Fp(e,t){let n=t._path,i=null,r=(e.syncPointTree_.foreachOnPath(n,(e,t)=>{var r=su(e,n);i=i||bp(t,r)}),e.syncPointTree_.get(n));r?i=i||bp(r,v()):(r=new gp,e.syncPointTree_=e.syncPointTree_.set(n,r));var s=null!=i,a=s?new yd(i,!0,!1):null,o=qd(e.pendingWriteTree_,t._path);return Sd(vp(r,t,o,s?a.getNode():T.EMPTY_NODE,s).viewCache_)}function Up(e,t){return function a(t,o,l,h){{if(b(t.path))return Vp(t,o,l,h);{let e=o.get(v()),r=(null==l&&null!=e&&(l=bp(e,v())),[]),n=_(t.path),i=t.operationForChild(n),s=o.children.get(n);if(s&&i){let e=l?l.getImmediateChild(n):null,t=Jd(h,n);r=r.concat(a(i,s,e,t))}return r=e?r.concat(mp(e,t,h,l)):r}}}(t,e.syncPointTree_,null,qd(e.pendingWriteTree_,v()))}function Vp(s,e,a,o){var t=e.get(v());null==a&&null!=t&&(a=bp(t,v()));let l=[];return e.children.inorderTraversal((e,t)=>{var r=a?a.getImmediateChild(e):null,n=Jd(o,e),i=s.operationForChild(e);i&&(l=l.concat(Vp(i,t,r,n)))}),l=t?l.concat(mp(t,s,o,a)):l}function qp(o,e){let l=e.query,h=Bp(o,l);return{hashFn:()=>(e.viewCache_.serverCache.getNode()||T.EMPTY_NODE).hash(),onComplete:e=>{var t,r,n,i,s,a;return"ok"===e?h?(t=o,r=l._path,n=h,(a=zp(t,n))?(i=(a=Kp(a)).path,a=a.queryId,s=su(i,r),Wp(t,i,new md(fd(a),s))):[]):(n=o,r=l._path,Up(n,new md(pd(),r))):(i=((e,t)=>{let r="Unknown Error";"too_big"===e?r="The data requested exceeds the maximum size that can be accessed with a single request.":"permission_denied"===e?r="Client doesn't have permission to access the desired data.":"unavailable"===e&&(r="The service is unavailable");var n=new Error(e+" at "+t._path.toString()+": "+r);return n.code=e.toUpperCase(),n})(e,l),xp(o,l,null,i))}}}function Bp(e,t){var r=jp(t);return e.queryToTagMap.get(r)}function jp(e){return e._path.toString()+"$"+e._queryIdentifier}function zp(e,t){return e.tagToQueryMap.get(t)}function Kp(e){var t=e.indexOf("$");return g(-1!==t&&t<e.length-1,"Bad queryKey."),{queryId:e.substr(t+1),path:new f(e.substr(0,t))}}function Wp(e,t,r){var n=e.syncPointTree_.get(t),i=(g(n,"Missing sync point for query tag that we're tracking"),qd(e.pendingWriteTree_,t));return mp(n,r,i,null)}function Hp(e){return e._queryParams.loadsAllData()&&!e._queryParams.isDefault()?(g(Sp,"Reference.ts has not been loaded"),new Sp(e._repo,e._path)):e}class Gp{constructor(e){this.node_=e}getImmediateChild(e){var t=this.node_.getImmediateChild(e);return new Gp(t)}node(){return this.node_}}class $p{constructor(e,t){this.syncTree_=e,this.path_=t}getImmediateChild(e){var t=iu(this.path_,e);return new $p(this.syncTree_,t)}node(){return Lp(this.syncTree_,this.path_)}}let Qp=function(e){return(e=e||{}).timestamp=e.timestamp||(new Date).getTime(),e},Yp=function(e,t,r){return e&&"object"==typeof e?(g(".sv"in e,"Unexpected leaf node or priority contents"),"string"==typeof e[".sv"]?Jp(e[".sv"],t,r):"object"==typeof e[".sv"]?Xp(e[".sv"],t):void g(!1,"Unexpected server value: "+JSON.stringify(e,null,2))):e},Jp=function(e,t,r){if("timestamp"===e)return r.timestamp;g(!1,"Unexpected server value: "+e)},Xp=function(e,t,r){e.hasOwnProperty("increment")||g(!1,"Unexpected server value: "+JSON.stringify(e,null,2));var n=e.increment,i=("number"!=typeof n&&g(!1,"Unexpected increment value: "+n),t.node());return g(null!=i,"Expected ChildrenNode.EMPTY_NODE for nulls"),!i.isLeafNode()||"number"!=typeof(i=i.getValue())?n:i+n},Zp=function(e,t,r,n){return tf(t,new $p(r,e),n)},ef=function(e,t,r){return tf(e,new Gp(t),r)};function tf(e,n,i){var t,r,s=e.getPriority().val(),s=Yp(s,n.getImmediateChild(".priority"),i);let a;return e.isLeafNode()?(r=e,(t=Yp(r.getValue(),n,i))!==r.getValue()||s!==r.getPriority().val()?new Au(t,ju(s)):e):(r=e,s!==(a=r).getPriority().val()&&(a=a.updatePriority(new Au(s))),r.forEachChild(I,(e,t)=>{var r=tf(t,n.getImmediateChild(e),i);r!==t&&(a=a.updateImmediateChild(e,r))}),a)}class rf{constructor(e="",t=null,r={children:{},childCount:0}){this.name=e,this.parent=t,this.node=r}}function nf(e,t){let r=t instanceof f?t:new f(t),n=e,i=_(r);for(;null!==i;){var s=be(n.node.children,i)||{children:{},childCount:0};n=new rf(i,n,s),r=y(r),i=_(r)}return n}function sf(e){return e.node.value}function af(e,t){e.node.value=t,cf(e)}function of(e){return 0<e.node.childCount}function lf(r,n){Ic(r.node.children,(e,t)=>{n(new rf(e,r,t))})}function hf(e){return new f(null===e.parent?e.name:hf(e.parent)+"/"+e.name)}function cf(e){var t,r,n,i;null!==e.parent&&(t=e.parent,r=e.name,n=(e=>void 0===sf(e)&&!of(e))(e=e),i=we(t.node.children,r),n&&i?(delete t.node.children[r],t.node.childCount--,cf(t)):n||i||(t.node.children[r]=e.node,t.node.childCount++,cf(t)))}function uf(e,t,r,n){n&&void 0===t||Ef(xe(e,"value"),t,r)}function df(e,t,s,r){if(!r||void 0!==t){let n=xe(e,"values");if(!t||"object"!=typeof t||Array.isArray(t))throw new Error(n+" must be an object containing the children to replace.");let i=[];Ic(t,(e,t)=>{var r=new f(e);if(Ef(n,t,iu(s,r)),".priority"===tu(r)&&!Tf(t))throw new Error(n+"contains an invalid value for '"+r.toString()+"', which must be a valid Firebase priority (a string, finite number, server value, or null).");i.push(r)});{var a=n;var o=i;let t,r;for(t=0;t<o.length;t++){var l=ru(r=o[t]);for(let e=0;e<l.length;e++)if((".priority"!==l[e]||e!==l.length-1)&&!wf(l[e]))throw new Error(a+"contains an invalid key ("+l[e]+") in path "+r.toString()+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"')}o.sort(au);let e=null;for(t=0;t<o.length;t++){if(r=o[t],null!==e&&lu(e,r))throw new Error(a+"contains a path "+e.toString()+" that is ancestor of another path "+r.toString());e=r}}}}function pf(e,t,r){if(!r||void 0!==t){if(_c(t))throw new Error(xe(e,"priority")+"is "+t.toString()+", but must be a valid Firebase priority (a string, finite number, server value, or null).");if(!Tf(t))throw new Error(xe(e,"priority")+"must be a valid Firebase priority (a string, finite number, server value, or null).")}}function ff(e,t,r,n){if(!(n&&void 0===r||wf(r)))throw new Error(xe(e,t)+'was an invalid key = "'+r+'". Firebase keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]").')}function gf(e,t,r,n){r=r&&r.replace(/^\/*\.info(\/|$)/,"/"),Cf(e,t,r,n)}function mf(e,t){if(".info"===_(t))throw new Error(e+" failed = Can't modify data under /.info/")}let vf=/[\[\].#$\/\u0000-\u001F\u007F]/,_f=/[\[\].#$\u0000-\u001F\u007F]/,yf=10485760,wf=function(e){return"string"==typeof e&&0!==e.length&&!vf.test(e)},bf=function(e){return"string"==typeof e&&0!==e.length&&!_f.test(e)},If=function(e){return e=e&&e.replace(/^\/*\.info(\/|$)/,"/"),bf(e)},Tf=function(e){return null===e||"string"==typeof e||"number"==typeof e&&!_c(e)||e&&"object"==typeof e&&we(e,".sv")},Ef=function(a,e,t){let o=t instanceof f?new hu(t,a):t;if(void 0===e)throw new Error(a+"contains undefined "+uu(o));if("function"==typeof e)throw new Error(a+"contains a function "+uu(o)+" with contents = "+e.toString());if(_c(e))throw new Error(a+"contains "+e.toString()+" "+uu(o));if("string"==typeof e&&e.length>yf/3&&Le(e)>yf)throw new Error(a+"contains a string greater than "+yf+" utf8 bytes "+uu(o)+" ('"+e.substring(0,50)+"...')");if(e&&"object"==typeof e){let i=!1,s=!1;if(Ic(e,(e,t)=>{if(".value"===e)i=!0;else if(".priority"!==e&&".sv"!==e&&(s=!0,!wf(e)))throw new Error(a+" contains an invalid key ("+e+") "+uu(o)+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');var r,n;r=o,e=e,0<r.parts_.length&&(r.byteLength_+=1),r.parts_.push(e),r.byteLength_+=Le(e),cu(r),Ef(a,t,o),e=o,n=e.parts_.pop(),e.byteLength_-=Le(n),0<e.parts_.length&&--e.byteLength_}),i&&s)throw new Error(a+' contains ".value" child '+uu(o)+" in addition to actual children.")}},Cf=function(e,t,r,n){if(!(n&&void 0===r||bf(r)))throw new Error(xe(e,t)+'was an invalid path = "'+r+'". Paths must be non-empty strings and can\'t contain ".", "#", "$", "[", or "]"')},Sf=function(e,t){var r=t.path.toString();if("string"!=typeof t.repoInfo.host||0===t.repoInfo.host.length||!wf(t.repoInfo.namespace)&&"localhost"!==t.repoInfo.host.split(":")[0]||0!==r.length&&!If(r))throw new Error(xe(e,"url")+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')};class kf{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function Af(e,t){let r=null;for(let s=0;s<t.length;s++){var n=t[s],i=n.getPath();null===r||ou(i,r.path)||(e.eventLists_.push(r),r=null),(r=null===r?{events:[],path:i}:r).events.push(n)}r&&e.eventLists_.push(r)}function Nf(e,t,r){Af(e,r),Pf(e,e=>ou(e,t))}function Rf(e,t,r){Af(e,r),Pf(e,e=>lu(e,t)||lu(t,e))}function Pf(t,e){t.recursionDepth_++;let r=!0;for(let o=0;o<t.eventLists_.length;o++){var n=t.eventLists_[o];if(n)if(e(n.path)){s=a=i=void 0;var i=t.eventLists_[o];for(let e=0;e<i.events.length;e++){var s,a=i.events[e];null!==a&&(i.events[e]=null,s=a.getEventRunner(),uc&&fc("event: "+a.toString()),Nc(s))}t.eventLists_[o]=null}else r=!1}r&&(t.eventLists_=[]),t.recursionDepth_--}let Df="repo_interrupt",xf=25;class Of{constructor(e,t,r,n){this.repoInfo_=e,this.forceRestClient_=t,this.authTokenProvider_=r,this.appCheckProvider_=n,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new kf,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=od(),this.transactionQueueTree_=new rf,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function Mf(a,e,t){if(a.stats_=Bc(a.repoInfo_),a.forceRestClient_||0<=("object"==typeof window&&window.navigator&&window.navigator.userAgent||"").search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i))a.server_=new sd(a.repoInfo_,(e,t,r,n)=>{Uf(a,e,t,r,n)},a.authTokenProvider_,a.appCheckProvider_),setTimeout(()=>Vf(a,!0),0);else{if(null!=t){if("object"!=typeof t)throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{_e(t)}catch(e){throw new Error("Invalid authOverride provided: "+e)}}a.persistentConnection_=new pu(a.repoInfo_,e,(e,t,r,n)=>{Uf(a,e,t,r,n)},e=>{Vf(a,e)},e=>{var r;r=a,Ic(e,(e,t)=>{qf(r,e,t)})},a.authTokenProvider_,a.appCheckProvider_,t),a.server_=a.persistentConnection_}var r;a.authTokenProvider_.addTokenChangeListener(e=>{a.server_.refreshAuthToken(e)}),a.appCheckProvider_.addTokenChangeListener(e=>{a.server_.refreshAppCheckToken(e.token)}),a.statsReporter_=(e=()=>new ud(a.stats_,a.server_),r=a.repoInfo_.toString(),qc[r]||(qc[r]=e()),qc[r]),a.infoData_=new ad,a.infoSyncTree_=new Ap({startListening:(e,t,r,n)=>{let i=[];var s=a.infoData_.getNode(e._path);return s.isEmpty()||(i=Dp(a.infoSyncTree_,e._path,s),setTimeout(()=>{n("ok")},0)),i},stopListening:()=>{}}),qf(a,"connected",!1),a.serverSyncTree_=new Ap({startListening:(n,e,t,i)=>(a.server_.listen(n,t,e,(e,t)=>{var r=i(e,t);Rf(a.eventQueue_,n._path,r)}),[]),stopListening:(e,t)=>{a.server_.unlisten(e,t)}})}function Lf(e){var t=e.infoData_.getNode(new f(".info/serverTimeOffset")).val()||0;return(new Date).getTime()+t}function Ff(e){return Qp({timestamp:Lf(e)})}function Uf(e,t,r,n,i){e.dataUpdateCount++;var s,a,o,l,h,c,u=new f(t);r=e.interceptServerDataCallback_?e.interceptServerDataCallback_(t,r):r;let d=[],p=u;0<(d=i?n?(c=Te(r,e=>ju(e)),t=e.serverSyncTree_,s=u,a=c,(c=zp(t,i))?(o=(c=Kp(c)).path,c=c.queryId,l=su(o,s),h=Nd.fromObject(a),Wp(t,o,new _d(fd(c),l,h))):[]):(o=ju(r),Op(e.serverSyncTree_,u,o,i)):n?(c=Te(r,e=>ju(e)),s=e.serverSyncTree_,a=u,t=c,l=Nd.fromObject(t),Up(s,new _d(pd(),a,l))):(h=ju(r),Dp(e.serverSyncTree_,u,h))).length&&(p=Jf(e,u)),Rf(e.eventQueue_,p,d)}function Vf(e,t){if(qf(e,"connected",t),!1===t){var a=e;Gf(a,"onDisconnectEvents");let n=Ff(a),i=od(),s=(hd(a.onDisconnect_,v(),(e,t)=>{var r=Zp(e,t,a.serverSyncTree_,n);ld(i,e,r)}),[]);hd(i,v(),(e,t)=>{s=s.concat(Dp(a.serverSyncTree_,e,t));var r=tg(a,e);Jf(a,r)}),a.onDisconnect_=od(),Rf(a.eventQueue_,v(),s)}}function qf(e,t,r){var n=new f("/.info/"+t),i=ju(r),i=(e.infoData_.updateSnapshot(n,i),Dp(e.infoSyncTree_,n,i));Rf(e.eventQueue_,n,i)}function Bf(e){return e.nextWriteId_++}function jf(n,i,e,t,s){Gf(n,"set",{path:i.toString(),value:e,priority:t});var r=Ff(n),a=ju(e,t),o=Lp(n.serverSyncTree_,i),o=ef(a,o,r);let l=Bf(n);r=Np(n.serverSyncTree_,i,o,l,!0),Af(n.eventQueue_,r),n.server_.put(i.toString(),a.val(!0),(e,t)=>{var r="ok"===e,r=(r||mc("set at "+i+" failed: "+e),Pp(n.serverSyncTree_,l,!r));Rf(n.eventQueue_,i,r),$f(0,s,e,t)}),o=tg(n,i);Jf(n,o),Rf(n.eventQueue_,o,[])}function zf(r,n,i){r.server_.onDisconnectCancel(n.toString(),(e,t)=>{"ok"===e&&!function e(r,t){var n;return b(t)?(r.value=null,r.children.clear(),!0):null!==r.value?!r.value.isLeafNode()&&(n=r.value,r.value=null,n.forEachChild(I,(e,t)=>{ld(r,new f(e),t)}),e(r,t)):!(0<r.children.size)||(n=_(t),t=y(t),r.children.has(n)&&e(r.children.get(n),t)&&r.children.delete(n),0===r.children.size)}(r.onDisconnect_,n),$f(0,i,e,t)})}function Kf(r,n,e,i){let s=ju(e);r.server_.onDisconnectPut(n.toString(),s.val(!0),(e,t)=>{"ok"===e&&ld(r.onDisconnect_,n,s),$f(0,i,e,t)})}function Wf(e,t,r){let n;n=".info"===_(t._path)?xp(e.infoSyncTree_,t,r):xp(e.serverSyncTree_,t,r),Nf(e.eventQueue_,t._path,n)}function Hf(e){e.persistentConnection_&&e.persistentConnection_.interrupt(Df)}function Gf(e,...t){let r="";e.persistentConnection_&&(r=e.persistentConnection_.id+":"),fc(r,...t)}function $f(e,n,i,s){n&&Nc(()=>{if("ok"===i)n(null);else{var t=(i||"error").toUpperCase();let e=t;s&&(e+=": "+s);var r=new Error(e);r.code=t,n(r)}})}function Qf(e,t,r){return Lp(e.serverSyncTree_,t,r)||T.EMPTY_NODE}function Yf(o,l=o.transactionQueueTree_){if(l||eg(o,l),sf(l)){var h=Zf(o,l),e=(g(0<h.length,"Sending zero length transaction queue"),h.every(e=>0===e.status));if(e){var c=o;var u=hf(l);var d=h;let e=d.map(e=>e.currentWriteId),t=Qf(c,u,e),r=t,n=t.hash();for(let a=0;a<d.length;a++){var p=d[a],f=(g(0===p.status,"tryToSendTransactionQueue_: items in queue should all be run."),p.status=1,p.retryCount++,su(u,p.path));r=r.updateChild(f,p.currentOutputSnapshotRaw)}let i=r.val(!0),s=u;c.server_.put(s.toString(),i,t=>{Gf(c,"transaction put response",{path:s.toString(),status:t});let r=[];if("ok"===t){var n=[];for(let e=0;e<d.length;e++)d[e].status=2,r=r.concat(Pp(c.serverSyncTree_,d[e].currentWriteId)),d[e].onComplete&&n.push(()=>d[e].onComplete(null,!0,d[e].currentOutputSnapshotResolved)),d[e].unwatcher();eg(c,nf(c.transactionQueueTree_,u)),Yf(c,c.transactionQueueTree_),Rf(c.eventQueue_,u,r);for(let t=0;t<n.length;t++)Nc(n[t])}else{if("datastale"===t)for(let e=0;e<d.length;e++)3===d[e].status?d[e].status=4:d[e].status=0;else{mc("transaction at "+s.toString()+" failed: "+t);for(let e=0;e<d.length;e++)d[e].status=4,d[e].abortReason=t}Jf(c,u)}},n)}}else of(l)&&lf(l,e=>{Yf(o,e)})}function Jf(e,t){var r=Xf(e,t),n=hf(r),r=Zf(e,r),i=e,s=r,a=n;if(0!==s.length){var o=[];let r=[];var l=s.filter(e=>0===e.status).map(e=>e.currentWriteId);for(let n=0;n<s.length;n++){var h=s[n],c=su(a,h.path);let e=!1,t;if(g(null!==c,"rerunTransactionsUnderNode_: relativePath should not be null."),4===h.status)e=!0,t=h.abortReason,r=r.concat(Pp(i.serverSyncTree_,h.currentWriteId,!0));else if(0===h.status)if(h.retryCount>=xf)e=!0,t="maxretry",r=r.concat(Pp(i.serverSyncTree_,h.currentWriteId,!0));else{var c=Qf(i,h.path,l),u=(h.currentInputSnapshot=c,s[n].update(c.val()));if(void 0!==u){Ef("transaction failed: Data returned ",u,h.path);let e=ju(u);"object"==typeof u&&null!=u&&we(u,".priority")||(e=e.updatePriority(c.getPriority()));var u=h.currentWriteId,d=Ff(i),c=ef(e,c,d);h.currentOutputSnapshotRaw=e,h.currentOutputSnapshotResolved=c,h.currentWriteId=Bf(i),l.splice(l.indexOf(u),1),r=(r=r.concat(Np(i.serverSyncTree_,h.path,c,h.currentWriteId,h.applyLocally))).concat(Pp(i.serverSyncTree_,u,!0))}else e=!0,t="nodata",r=r.concat(Pp(i.serverSyncTree_,h.currentWriteId,!0))}Rf(i.eventQueue_,a,r),r=[],e&&(s[n].status=2,(e=>{setTimeout(e,Math.floor(0))})(s[n].unwatcher),s[n].onComplete)&&("nodata"===t?o.push(()=>s[n].onComplete(null,!1,s[n].currentInputSnapshot)):o.push(()=>s[n].onComplete(new Error(t),!1,null)))}eg(i,i.transactionQueueTree_);for(let e=0;e<o.length;e++)Nc(o[e]);Yf(i,i.transactionQueueTree_)}return n}function Xf(e,t){let r,n=e.transactionQueueTree_;for(r=_(t);null!==r&&void 0===sf(n);)n=nf(n,r),t=y(t),r=_(t);return n}function Zf(e,t){var r=[];return function t(r,e,n){let i=sf(e);if(i)for(let e=0;e<i.length;e++)n.push(i[e]);lf(e,e=>{t(r,e,n)})}(e,t,r),r.sort((e,t)=>e.order-t.order),r}function eg(t,r){var n=sf(r);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,af(r,0<n.length?n:void 0)}lf(r,e=>{eg(t,e)})}function tg(t,e){var r=hf(Xf(t,e)),n=nf(t.transactionQueueTree_,e);return((e,t,r)=>{let n=r?e:e.parent;for(;null!==n;){if(t(n))return;n=n.parent}})(n,e=>{rg(t,e)}),rg(t,n),function t(e,r,n,i){n&&!i&&r(e),lf(e,e=>{t(e,r,!0,i)}),n&&i&&r(e)}(n,e=>{rg(t,e)}),r}function rg(i,s){var a=sf(s);if(a){var o=[];let e=[],t=-1;for(let r=0;r<a.length;r++)3!==a[r].status&&(1===a[r].status?(g(t===r-1,"All SENT items should be at beginning of queue."),a[t=r].status=3,a[r].abortReason="set"):(g(0===a[r].status,"Unexpected transaction status in abort"),a[r].unwatcher(),e=e.concat(Pp(i.serverSyncTree_,a[r].currentWriteId,!0)),a[r].onComplete&&o.push(a[r].onComplete.bind(null,new Error("set"),!1,null))));-1===t?af(s,void 0):a.length=t+1,Rf(i.eventQueue_,hf(s),e);for(let n=0;n<o.length;n++)Nc(o[n])}}let ng=function(e,t){var r=ig(e),n=r.namespace,i=("firebase.com"===r.domain&&gc(r.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),n&&"undefined"!==n||"localhost"===r.domain||gc("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),r.secure||vc(),"ws"===r.scheme||"wss"===r.scheme);return{repoInfo:new Lc(r.host,r.secure,n,i,t,"",n!==r.subdomain),path:new f(r.pathString)}},ig=function(n){let i="",s="",a="",o="",l="",h=!0,c="https",u=443;if("string"==typeof n){let e=n.indexOf("//"),t=(0<=e&&(c=n.substring(0,e-1),n=n.substring(e+2)),n.indexOf("/")),r=(-1===t&&(t=n.length),n.indexOf("?"));-1===r&&(r=n.length),i=n.substring(0,Math.min(t,r)),t<r&&(o=(e=>{let t="";var r=e.split("/");for(let n=0;n<r.length;n++)if(0<r[n].length){let e=r[n];try{e=decodeURIComponent(e.replace(/\+/g," "))}catch(e){}t+="/"+e}return t})(n.substring(t,r)));var d=(e=>{var t,r,n={};for(t of(e="?"===e.charAt(0)?e.substring(1):e).split("&"))0!==t.length&&(2===(r=t.split("=")).length?n[decodeURIComponent(r[0])]=decodeURIComponent(r[1]):mc(`Invalid query segment '${t}' in query '${e}'`));return n})(n.substring(Math.min(n.length,r))),p=(0<=(e=i.indexOf(":"))?(h="https"===c||"wss"===c,u=parseInt(i.substring(e+1),10)):e=i.length,i.slice(0,e));"localhost"===p.toLowerCase()?s="localhost":p.split(".").length<=2?s=p:(p=i.indexOf("."),a=i.substring(0,p).toLowerCase(),s=i.substring(p+1),l=a),"ns"in d&&(l=d.ns)}return{host:i,port:u,domain:s,subdomain:a,secure:h,scheme:c,pathString:o,namespace:l}},sg="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",ag=(()=>{let s=0,a=[];return function(e){var t=e===s;s=e;let r;var n=new Array(8);for(r=7;0<=r;r--)n[r]=sg.charAt(e%64),e=Math.floor(e/64);g(0===e,"Cannot push at time == 0");let i=n.join("");if(t){for(r=11;0<=r&&63===a[r];r--)a[r]=0;a[r]++}else for(r=0;r<12;r++)a[r]=Math.floor(64*Math.random());for(r=0;r<12;r++)i+=sg.charAt(a[r]);return g(20===i.length,"nextPushId: Length should be 20."),i}})();class og{constructor(e,t,r,n){this.eventType=e,this.eventRegistration=t,this.snapshot=r,this.prevName=n}getPath(){var e=this.snapshot.ref;return("value"===this.eventType?e:e.parent)._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+_e(this.snapshot.exportVal())}}class lg{constructor(e,t,r){this.eventRegistration=e,this.error=t,this.path=r}getPath(){return this.path}getEventType(){return"cancel"}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.path.toString()+":cancel"}}class hg{constructor(e,t){this.snapshotCallback=e,this.cancelCallback=t}onValue(e,t){this.snapshotCallback.call(null,e,t)}onCancel(e){return g(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 cg{constructor(e,t){this._repo=e,this._path=t}cancel(){var e=new Z;return zf(this._repo,this._path,e.wrapCallback(()=>{})),e.promise}remove(){mf("OnDisconnect.remove",this._path);var e=new Z;return Kf(this._repo,this._path,null,e.wrapCallback(()=>{})),e.promise}set(e){mf("OnDisconnect.set",this._path),uf("OnDisconnect.set",e,this._path,!1);var t=new Z;return Kf(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}setWithPriority(e,t){mf("OnDisconnect.setWithPriority",this._path),uf("OnDisconnect.setWithPriority",e,this._path,!1),pf("OnDisconnect.setWithPriority",t,!1);var n=new Z;{var i=this._repo,s=this._path,a=n.wrapCallback(()=>{});let r=ju(e,t);i.server_.onDisconnectPut(s.toString(),r.val(!0),(e,t)=>{"ok"===e&&ld(i.onDisconnect_,s,r),$f(0,a,e,t)})}return n.promise}update(e){mf("OnDisconnect.update",this._path),df("OnDisconnect.update",e,this._path,!1);var n,i,r,s,t=new Z;return n=this._repo,i=this._path,r=e,s=t.wrapCallback(()=>{}),Ie(r)?(fc("onDisconnect().update() called with empty data. Don't do anything."),$f(0,s,"ok",void 0)):n.server_.onDisconnectMerge(i.toString(),r,(e,t)=>{"ok"===e&&Ic(r,(e,t)=>{var r=ju(t);ld(n.onDisconnect_,iu(i,e),r)}),$f(0,s,e,t)}),t.promise}}class ug{constructor(e,t,r,n){this._repo=e,this._path=t,this._queryParams=r,this._orderByCalled=n}get key(){return b(this._path)?null:tu(this._path)}get ref(){return new gg(this._repo,this._path)}get _queryIdentifier(){var e=id(this._queryParams),e=ic(e);return"{}"===e?"default":e}get _queryObject(){return id(this._queryParams)}isEqual(e){var t,r,n;return(e=w(e))instanceof ug&&(t=this._repo===e._repo,r=ou(this._path,e._path),n=this._queryIdentifier===e._queryIdentifier,t)&&r&&n}toJSON(){return this.toString()}toString(){return this._repo.toString()+(e=>{let t="";for(let r=e.pieceNum_;r<e.pieces_.length;r++)""!==e.pieces_[r]&&(t+="/"+encodeURIComponent(String(e.pieces_[r])));return t||"/"})(this._path)}}function dg(e,t){if(!0===e._orderByCalled)throw new Error(t+": You can't combine multiple orderBy calls.")}function pg(e){let t=null,r=null;if(e.hasStart()&&(t=e.getIndexStartValue()),e.hasEnd()&&(r=e.getIndexEndValue()),e.getIndex()===vu){var n="Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().",i="Query: When ordering by key, the argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() must be a string.";if(e.hasStart()){if(e.getIndexStartName()!==yc)throw new Error(n);if("string"!=typeof t)throw new Error(i)}if(e.hasEnd()){if(e.getIndexEndName()!==wc)throw new Error(n);if("string"!=typeof r)throw new Error(i)}}else if(e.getIndex()===I){if(null!=t&&!Tf(t)||null!=r&&!Tf(r))throw new Error("Query: When ordering by priority, the first argument passed to startAt(), startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value (null, a number, or a string).")}else if(g(e.getIndex()instanceof zu||e.getIndex()===Wu,"unknown index type."),null!=t&&"object"==typeof t||null!=r&&"object"==typeof r)throw new Error("Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() cannot be an object.")}function fg(e){if(e.hasStart()&&e.hasEnd()&&e.hasLimit()&&!e.hasAnchoredLimit())throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use limitToFirst() or limitToLast() instead.")}class gg extends ug{constructor(e,t){super(e,t,new Zu,!1)}get parent(){var e=nu(this._path);return null===e?null:new gg(this._repo,e)}get root(){let e=this;for(;null!==e.parent;)e=e.parent;return e}}class mg{constructor(e,t,r){this._node=e,this.ref=t,this._index=r}get priority(){return this._node.getPriority().val()}get key(){return this.ref.key}get size(){return this._node.numChildren()}child(e){var t=new f(e),r=yg(this.ref,e);return new mg(this._node.getChild(t),r,I)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(r){return!this._node.isLeafNode()&&!!this._node.forEachChild(this._index,(e,t)=>r(new mg(t,yg(this.ref,e),I)))}hasChild(e){var t=new f(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 vg(e,t){return(e=w(e))._checkNotDeleted("ref"),void 0!==t?yg(e._root,t):e._root}function _g(e,t){(e=w(e))._checkNotDeleted("refFromURL");var r=ng(t,e._repo.repoInfo_.nodeAdmin),n=(Sf("refFromURL",r),r.repoInfo);return e._repo.repoInfo_.isCustomHost()||n.host===e._repo.repoInfo_.host||gc("refFromURL: Host name does not match the current database: (found "+n.host+" but expected "+e._repo.repoInfo_.host+")"),vg(e,r.path.toString())}function yg(e,t){return(null===_((e=w(e))._path)?gf:Cf)("child","path",t,!1),new gg(e._repo,iu(e._path,t))}function wg(e,t){e=w(e),mf("set",e._path),uf("set",t,e._path,!1);var r=new Z;return jf(e._repo,e._path,t,null,r.wrapCallback(()=>{})),r.promise}function bg(e,t){df("update",t,e._path,!1);var i=new Z;{var a=e._repo,o=e._path,l=(e=t,i.wrapCallback(()=>{}));Gf(a,"update",{path:o.toString(),value:e});let r=!0,n=Ff(a),s={};if(Ic(e,(e,t)=>{r=!1,s[e]=Zp(iu(o,e),ju(t),a.serverSyncTree_,n)}),r)fc("update() called with empty data. Don't do anything."),$f(0,l,"ok",void 0);else{let i=Bf(a);var h=Rp(a.serverSyncTree_,o,s,i);Af(a.eventQueue_,h),a.server_.merge(o.toString(),e,(e,t)=>{var r="ok"===e,r=(r||mc("update at "+o+" failed: "+e),Pp(a.serverSyncTree_,i,!r)),n=0<r.length?Jf(a,o):o;Rf(a.eventQueue_,n,r),$f(0,l,e,t)}),Ic(e,e=>{var t=tg(a,iu(o,e));Jf(a,t)}),Rf(a.eventQueue_,o,[])}}return i.promise}function Ig(t){t=w(t);var i,s,a,e=new hg(()=>{}),e=new Tg(e);return i=t._repo,s=t,a=e,(null!=(e=Fp(i.serverSyncTree_,s))?Promise.resolve(e):i.server_.get(s).then(e=>{var t,r=ju(e).withIndex(s._queryParams.getIndex());Mp(i.serverSyncTree_,s,a,!0);let n;return n=s._queryParams.loadsAllData()?Dp(i.serverSyncTree_,s._path,r):(t=Bp(i.serverSyncTree_,s),Op(i.serverSyncTree_,s._path,r,t)),Rf(i.eventQueue_,s._path,n),xp(i.serverSyncTree_,s,a,null,!0),r},e=>(Gf(i,"get for query "+_e(s)+" failed: "+e),Promise.reject(new Error(e))))).then(e=>new mg(e,new gg(t._repo,t._path),t._queryParams.getIndex()))}class Tg{constructor(e){this.callbackContext=e}respondsTo(e){return"value"===e}createEvent(e,t){var r=t._queryParams.getIndex();return new og("value",this,new mg(e.snapshotNode,new gg(t._repo,t._path),r))}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 lg(this,e,t):null}matches(e){return e instanceof Tg&&(!e.callbackContext||!this.callbackContext||e.callbackContext.matches(this.callbackContext))}hasAnyCallback(){return null!==this.callbackContext}}class Eg{constructor(e,t){this.eventType=e,this.callbackContext=t}respondsTo(e){var t="children_added"===e?"child_added":e;return this.eventType===("children_removed"===t?"child_removed":t)}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new lg(this,e,t):null}createEvent(e,t){g(null!=e.childName,"Child events should have a childName.");var r=yg(new gg(t._repo,t._path),e.childName),n=t._queryParams.getIndex();return new og(e.type,this,new mg(e.snapshotNode,r,n),e.prevName)}getEventRunner(e){return"cancel"===e.getEventType()?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,e.prevName)}matches(e){return e instanceof Eg&&this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext))}hasAnyCallback(){return!!this.callbackContext}}function Cg(n,e,t,r,i){let s;if("object"==typeof r&&(s=void 0,i=r),"function"==typeof r&&(s=r),i&&i.onlyOnce){let r=t;var a=(e,t)=>{Wf(n._repo,n,o),r(e,t)};a.userCallback=t.userCallback,a.context=t.context,t=a}a=new hg(t,s||void 0);let o="value"===e?new Tg(a):new Eg(e,a);{r=n._repo,i=n,t=o;let e;e=".info"===_(i._path)?Mp(r.infoSyncTree_,i,t):Mp(r.serverSyncTree_,i,t),Nf(r.eventQueue_,i._path,e)}return()=>Wf(n._repo,n,o)}function Sg(e,t,r,n){return Cg(e,"value",t,r,n)}function kg(e,t,r,n){Cg(e,"child_added",t,r,n)}function Ag(e,t,r,n){Cg(e,"child_changed",t,r,n)}function Ng(e,t,r,n){Cg(e,"child_moved",t,r,n)}function Rg(e,t,r,n){Cg(e,"child_removed",t,r,n)}function Pg(e,t,r){let n=null;var i=r?new hg(r):null;"value"===t?n=new Tg(i):t&&(n=new Eg(t,i)),Wf(e._repo,e,n)}class Dg{}class xg extends Dg{constructor(e,t){super(),this._value=e,this._key=t,this.type="endAt"}_apply(e){uf("endAt",this._value,e._path,!0);var t=td(e._queryParams,this._value,this._key);if(fg(t),pg(t),e._queryParams.hasEnd())throw new Error("endAt: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new ug(e._repo,e._path,t,e._orderByCalled)}}class Og extends Dg{constructor(e,t){super(),this._value=e,this._key=t,this.type="endBefore"}_apply(e){uf("endBefore",this._value,e._path,!1);var t=((e,t,r)=>{let n;return(n=e.index_===vu||r?td(e,t,r):td(e,t,yc)).endBeforeSet_=!0,n})(e._queryParams,this._value,this._key);if(fg(t),pg(t),e._queryParams.hasEnd())throw new Error("endBefore: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new ug(e._repo,e._path,t,e._orderByCalled)}}class Mg extends Dg{constructor(e,t){super(),this._value=e,this._key=t,this.type="startAt"}_apply(e){uf("startAt",this._value,e._path,!0);var t=ed(e._queryParams,this._value,this._key);if(fg(t),pg(t),e._queryParams.hasStart())throw new Error("startAt: Starting point was already set (by another call to startAt, startBefore or equalTo).");return new ug(e._repo,e._path,t,e._orderByCalled)}}class Lg extends Dg{constructor(e,t){super(),this._value=e,this._key=t,this.type="startAfter"}_apply(e){uf("startAfter",this._value,e._path,!1);var t=((e,t,r)=>{let n;return(n=e.index_===vu||r?ed(e,t,r):ed(e,t,wc)).startAfterSet_=!0,n})(e._queryParams,this._value,this._key);if(fg(t),pg(t),e._queryParams.hasStart())throw new Error("startAfter: Starting point was already set (by another call to startAt, startAfter, or equalTo).");return new ug(e._repo,e._path,t,e._orderByCalled)}}class Fg extends Dg{constructor(e){super(),this._limit=e,this.type="limitToFirst"}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToFirst: Limit was already set (by another call to limitToFirst or limitToLast).");return new ug(e._repo,e._path,(t=e._queryParams,r=this._limit,(n=t.copy()).limitSet_=!0,n.limit_=r,n.viewFrom_="l",n),e._orderByCalled);var t,r,n}}class Ug extends Dg{constructor(e){super(),this._limit=e,this.type="limitToLast"}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToLast: Limit was already set (by another call to limitToFirst or limitToLast).");return new ug(e._repo,e._path,(t=e._queryParams,r=this._limit,(n=t.copy()).limitSet_=!0,n.limit_=r,n.viewFrom_="r",n),e._orderByCalled);var t,r,n}}class Vg extends Dg{constructor(e){super(),this._path=e,this.type="orderByChild"}_apply(e){dg(e,"orderByChild");var t=new f(this._path);if(b(t))throw new Error("orderByChild: cannot pass in empty path. Use orderByValue() instead.");t=new zu(t),t=rd(e._queryParams,t);return pg(t),new ug(e._repo,e._path,t,!0)}}class qg extends Dg{constructor(){super(...arguments),this.type="orderByKey"}_apply(e){dg(e,"orderByKey");var t=rd(e._queryParams,vu);return pg(t),new ug(e._repo,e._path,t,!0)}}class Bg extends Dg{constructor(){super(...arguments),this.type="orderByPriority"}_apply(e){dg(e,"orderByPriority");var t=rd(e._queryParams,I);return pg(t),new ug(e._repo,e._path,t,!0)}}class jg extends Dg{constructor(){super(...arguments),this.type="orderByValue"}_apply(e){dg(e,"orderByValue");var t=rd(e._queryParams,Wu);return pg(t),new ug(e._repo,e._path,t,!0)}}class zg extends Dg{constructor(e,t){super(),this._value=e,this._key=t,this.type="equalTo"}_apply(e){if(uf("equalTo",this._value,e._path,!1),e._queryParams.hasStart())throw new Error("equalTo: Starting point was already set (by another call to startAt/startAfter or equalTo).");if(e._queryParams.hasEnd())throw new Error("equalTo: Ending point was already set (by another call to endAt/endBefore or equalTo).");return new xg(this._value,this._key)._apply(new Mg(this._value,this._key)._apply(e))}}function Kg(e,...t){let r=w(e);for(var n of t)r=n._apply(r);return r}t=gg,g(!fp,"__referenceConstructor has already been defined"),fp=t,t=gg,g(!Sp,"__referenceConstructor has already been defined"),Sp=t;let Wg="FIREBASE_DATABASE_EMULATOR_HOST",Hg={},Gg=!1;function $g(e,t,r,n,i){let s=n||e.options.databaseURL,a=(void 0===s&&(e.options.projectId||gc("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),fc("Using default host for project ",e.options.projectId),s=e.options.projectId+"-default-rtdb.firebaseio.com"),ng(s,i)),o=a.repoInfo,l,h=void 0;(h="undefined"!=typeof process&&process.env?process.env[Wg]:h)?(l=!0,s=`http://${h}?ns=`+o.namespace,a=ng(s,i),o=a.repoInfo):l=!a.repoInfo.secure;var c=i&&l?new Dc(Dc.OWNER):new Pc(e.name,e.options,t),c=(Sf("Invalid Firebase Database URL",a),b(a.path)||gc("Database URL must point to the root of a Firebase Database (not including a child path)."),((e,t,r,n)=>{let i=Hg[t.name];var s;return i||(i={},Hg[t.name]=i),(s=i[e.toURLString()])&&gc("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call."),s=new Of(e,Gg,r,n),i[e.toURLString()]=s})(o,e,c,new Rc(e,r)));return new Qg(c,e)}class Qg{constructor(e,t){this._repoInternal=e,this.app=t,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(Mf(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new gg(this._repo,v())),this._rootInternal}_delete(){var e,t,r;return null!==this._rootInternal&&(e=this._repo,t=this.app.name,(r=Hg[t])&&r[e.key]===e||gc(`Database ${t}(${e.repoInfo_}) has already been deleted.`),Hf(e),delete r[e.key],this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){null===this._rootInternal&&gc("Cannot call "+e+" on a deleted database.")}}function Yg(){Gc.IS_TRANSPORT_INITIALIZED&&mc("Transport has already been initialized. Please call this function before calling ref or setting up a listener")}function Jg(){Yg(),zc.forceDisallow()}function Xg(){Yg(),Hc.forceDisallow(),zc.forceAllow()}function Zg(e,t,r,n={}){(e=w(e))._checkNotDeleted("useEmulator");var i,s=t+":"+r,a=e._repoInternal;if(e._instanceStarted){if(s===e._repoInternal.repoInfo_.host&&Ee(n,a.repoInfo_.emulatorOptions))return;gc("connectDatabaseEmulator() cannot initialize or alter the emulator configuration after the database instance has started.")}let o=void 0;a.repoInfo_.nodeAdmin?(n.mockUserToken&&gc('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),o=new Dc(Dc.OWNER)):n.mockUserToken&&(i="string"==typeof n.mockUserToken?n.mockUserToken:ee(n.mockUserToken,e.app.options.projectId),o=new Dc(i)),je(t)&&ze(t),r=a,e=s,t=n,n=o,i=e.lastIndexOf(":"),i=je(e.substring(0,i)),r.repoInfo_=new Lc(e,i,r.repoInfo_.namespace,r.repoInfo_.webSocketOnly,r.repoInfo_.nodeAdmin,r.repoInfo_.persistenceKey,r.repoInfo_.includeNamespaceInQueryParams,!0,t),n&&(r.authTokenProvider_=n)}function em(e){(e=w(e))._checkNotDeleted("goOnline"),(e=e._repo).persistentConnection_&&e.persistentConnection_.resume(Df)}function tm(e,t){pc(e,t)}let rm={".sv":"timestamp"};class nm{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}}function im(i,e,t){if(i=w(i),mf("Reference.transaction",i._path),".length"===i.key||".keys"===i.key)throw"Reference.transaction failed: "+i.key+" is a read-only object.";var r=t?.applyLocally??!0;let s=new Z;var n=Sg(i,()=>{}),t=i._repo,a=i._path,o=(e,t,r)=>{var n;e?s.reject(e):(n=new mg(r,new gg(i._repo,i._path),I),s.resolve(new nm(t,n)))},l=n,h=r;Gf(t,"transaction on "+a);var c,n={path:a,update:e,onComplete:o,status:null,order:hc(),applyLocally:h,retryCount:0,unwatcher:l,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},r=Qf(t,a,void 0);if(n.currentInputSnapshot=r,void 0===(c=n.update(r.val())))n.unwatcher(),n.currentOutputSnapshotRaw=null,n.currentOutputSnapshotResolved=null,n.onComplete&&n.onComplete(null,!1,n.currentInputSnapshot);else{Ef("transaction failed: Data returned ",c,n.path),n.status=0;var u=nf(t.transactionQueueTree_,a),d=sf(u)||[];d.push(n),af(u,d);let e;"object"==typeof c&&null!==c&&we(c,".priority")?(e=be(c,".priority"),g(Tf(e),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.")):(u=Lp(t.serverSyncTree_,a)||T.EMPTY_NODE,e=u.getPriority().val());d=Ff(t),u=ju(c,e),c=ef(u,r,d),r=(n.currentOutputSnapshotRaw=u,n.currentOutputSnapshotResolved=c,n.currentWriteId=Bf(t),Np(t.serverSyncTree_,a,c,n.currentWriteId,n.applyLocally));Rf(t.eventQueue_,a,r),Yf(t,t.transactionQueueTree_)}return s.promise}pu.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)},pu.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)},$h(Ft),Nt(new c("database",(e,{instanceIdentifier:t})=>$g(e.getProvider("app").getImmediate(),e.getProvider("auth-internal"),e.getProvider("app-check-internal"),t),"PUBLIC").setMultipleInstances(!0)),u(Hh,"1.1.2",hD),u(Hh,"1.1.2","esm2020");function sm(e){var t="FIREBASE WARNING: "+e;am.warn(t)}let am=new Xe("@firebase/database-compat");class om{constructor(e){this._delegate=e}cancel(t){l("OnDisconnect.cancel",0,1,arguments.length),Oe("OnDisconnect.cancel","onComplete",t,!0);var e=this._delegate.cancel();return t&&e.then(()=>t(null),e=>t(e)),e}remove(t){l("OnDisconnect.remove",0,1,arguments.length),Oe("OnDisconnect.remove","onComplete",t,!0);var e=this._delegate.remove();return t&&e.then(()=>t(null),e=>t(e)),e}set(e,t){l("OnDisconnect.set",1,2,arguments.length),Oe("OnDisconnect.set","onComplete",t,!0);var r=this._delegate.set(e);return t&&r.then(()=>t(null),e=>t(e)),r}setWithPriority(e,t,r){l("OnDisconnect.setWithPriority",2,3,arguments.length),Oe("OnDisconnect.setWithPriority","onComplete",r,!0);var n=this._delegate.setWithPriority(e,t);return r&&n.then(()=>r(null),e=>r(e)),n}update(t,r){if(l("OnDisconnect.update",1,2,arguments.length),Array.isArray(t)){var n={};for(let e=0;e<t.length;++e)n[""+e]=t[e];t=n,sm("Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.")}Oe("OnDisconnect.update","onComplete",r,!0);var e=this._delegate.update(t);return r&&e.then(()=>r(null),e=>r(e)),e}}class lm{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return l("TransactionResult.toJSON",0,1,arguments.length),{committed:this.committed,snapshot:this.snapshot.toJSON()}}}class hm{constructor(e,t){this._database=e,this._delegate=t}val(){return l("DataSnapshot.val",0,0,arguments.length),this._delegate.val()}exportVal(){return l("DataSnapshot.exportVal",0,0,arguments.length),this._delegate.exportVal()}toJSON(){return l("DataSnapshot.toJSON",0,1,arguments.length),this._delegate.toJSON()}exists(){return l("DataSnapshot.exists",0,0,arguments.length),this._delegate.exists()}child(e){return l("DataSnapshot.child",0,1,arguments.length),e=String(e),Cf("DataSnapshot.child","path",e,!1),new hm(this._database,this._delegate.child(e))}hasChild(e){return l("DataSnapshot.hasChild",1,1,arguments.length),Cf("DataSnapshot.hasChild","path",e,!1),this._delegate.hasChild(e)}getPriority(){return l("DataSnapshot.getPriority",0,0,arguments.length),this._delegate.priority}forEach(t){return l("DataSnapshot.forEach",1,1,arguments.length),Oe("DataSnapshot.forEach","action",t,!1),this._delegate.forEach(e=>t(new hm(this._database,e)))}hasChildren(){return l("DataSnapshot.hasChildren",0,0,arguments.length),this._delegate.hasChildren()}get key(){return this._delegate.key}numChildren(){return l("DataSnapshot.numChildren",0,0,arguments.length),this._delegate.size}getRef(){return l("DataSnapshot.ref",0,0,arguments.length),new um(this._database,this._delegate.ref)}get ref(){return this.getRef()}}class cm{constructor(e,t){this.database=e,this._delegate=t}on(e,r,t,n){l("Query.on",2,4,arguments.length),Oe("Query.on","callback",r,!1);let i=cm.getCancelAndContextArgs_("Query.on",t,n);var s=(e,t)=>{r.call(i.context,new hm(this.database,e),t)},a=(s.userCallback=r,s.context=i.context,i.cancel?.bind(i.context));switch(e){case"value":return Sg(this._delegate,s,a),r;case"child_added":return kg(this._delegate,s,a),r;case"child_removed":return Rg(this._delegate,s,a),r;case"child_changed":return Ag(this._delegate,s,a),r;case"child_moved":return Ng(this._delegate,s,a),r;default:throw new Error(xe("Query.on","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}}off(e,t,r){l("Query.off",0,3,arguments.length);var n,i="Query.off",s=e,a=!0;if(!a||void 0!==s)switch(s){case"value":case"child_added":case"child_removed":case"child_changed":case"child_moved":break;default:throw new Error(xe(i,"eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}Oe("Query.off","callback",t,!0),Me("Query.off","context",r,!0),t?((n=()=>{}).userCallback=t,n.context=r,Pg(this._delegate,e,n)):Pg(this._delegate,e)}get(){return Ig(this._delegate).then(e=>new hm(this.database,e))}once(e,n,t,r){l("Query.once",1,4,arguments.length),Oe("Query.once","callback",n,!0);let i=cm.getCancelAndContextArgs_("Query.once",t,r),s=new Z;var a=(e,t)=>{var r=new hm(this.database,e);n&&n.call(i.context,r,t),s.resolve(r)},o=(a.userCallback=n,a.context=i.context,e=>{i.cancel&&i.cancel.call(i.context,e),s.reject(e)});switch(e){case"value":Sg(this._delegate,a,o,{onlyOnce:!0});break;case"child_added":kg(this._delegate,a,o,{onlyOnce:!0});break;case"child_removed":Rg(this._delegate,a,o,{onlyOnce:!0});break;case"child_changed":Ag(this._delegate,a,o,{onlyOnce:!0});break;case"child_moved":Ng(this._delegate,a,o,{onlyOnce:!0});break;default:throw new Error(xe("Query.once","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}return s.promise}limitToFirst(e){return l("Query.limitToFirst",1,1,arguments.length),new cm(this.database,Kg(this._delegate,(e=>{if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToFirst: First argument must be a positive integer.");return new Fg(e)})(e)))}limitToLast(e){return l("Query.limitToLast",1,1,arguments.length),new cm(this.database,Kg(this._delegate,(e=>{if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToLast: First argument must be a positive integer.");return new Ug(e)})(e)))}orderByChild(e){return l("Query.orderByChild",1,1,arguments.length),new cm(this.database,Kg(this._delegate,(e=>{if("$key"===e)throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');if("$priority"===e)throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');if("$value"===e)throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');return Cf("orderByChild","path",e,!1),new Vg(e)})(e)))}orderByKey(){return l("Query.orderByKey",0,0,arguments.length),new cm(this.database,Kg(this._delegate,new qg))}orderByPriority(){return l("Query.orderByPriority",0,0,arguments.length),new cm(this.database,Kg(this._delegate,new Bg))}orderByValue(){return l("Query.orderByValue",0,0,arguments.length),new cm(this.database,Kg(this._delegate,new jg))}startAt(e=null,t){return l("Query.startAt",0,2,arguments.length),new cm(this.database,Kg(this._delegate,([e=null,t]=[e,t],ff("startAt","key",t,!0),new Mg(e,t))))}startAfter(e=null,t){return l("Query.startAfter",0,2,arguments.length),new cm(this.database,Kg(this._delegate,(e=e,t=t,ff("startAfter","key",t,!0),new Lg(e,t))))}endAt(e=null,t){return l("Query.endAt",0,2,arguments.length),new cm(this.database,Kg(this._delegate,(e=e,t=t,ff("endAt","key",t,!0),new xg(e,t))))}endBefore(e=null,t){return l("Query.endBefore",0,2,arguments.length),new cm(this.database,Kg(this._delegate,(e=e,t=t,ff("endBefore","key",t,!0),new Og(e,t))))}equalTo(e,t){return l("Query.equalTo",1,2,arguments.length),new cm(this.database,Kg(this._delegate,(e=e,t=t,ff("equalTo","key",t,!0),new zg(e,t))))}toString(){return l("Query.toString",0,0,arguments.length),this._delegate.toString()}toJSON(){return l("Query.toJSON",0,1,arguments.length),this._delegate.toJSON()}isEqual(e){if(l("Query.isEqual",1,1,arguments.length),e instanceof cm)return this._delegate.isEqual(e._delegate);throw new Error("Query.isEqual failed: First argument must be an instance of firebase.database.Query.")}static getCancelAndContextArgs_(e,t,r){var n={cancel:void 0,context:void 0};if(t&&r)n.cancel=t,Oe(e,"cancel",n.cancel,!0),n.context=r,Me(e,"context",n.context,!0);else if(t)if("object"==typeof t&&null!==t)n.context=t;else{if("function"!=typeof t)throw new Error(xe(e,"cancelOrContext")+" must either be a cancel callback or a context object.");n.cancel=t}return n}get ref(){return new um(this.database,new gg(this._delegate._repo,this._delegate._path))}}class um extends cm{constructor(e,t){super(e,new ug(t._repo,t._path,new Zu,!1)),this.database=e,this._delegate=t}getKey(){return l("Reference.key",0,0,arguments.length),this._delegate.key}child(e){return l("Reference.child",1,1,arguments.length),"number"==typeof e&&(e=String(e)),new um(this.database,yg(this._delegate,e))}getParent(){l("Reference.parent",0,0,arguments.length);var e=this._delegate.parent;return e?new um(this.database,e):null}getRoot(){return l("Reference.root",0,0,arguments.length),new um(this.database,this._delegate.root)}set(e,t){l("Reference.set",1,2,arguments.length),Oe("Reference.set","onComplete",t,!0);var r=wg(this._delegate,e);return t&&r.then(()=>t(null),e=>t(e)),r}update(t,r){if(l("Reference.update",1,2,arguments.length),Array.isArray(t)){var n={};for(let e=0;e<t.length;++e)n[""+e]=t[e];t=n,sm("Passing an Array to Firebase.update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.")}mf("Reference.update",this._delegate._path),Oe("Reference.update","onComplete",r,!0);var e=bg(this._delegate,t);return r&&e.then(()=>r(null),e=>r(e)),e}setWithPriority(e,t,r){l("Reference.setWithPriority",2,3,arguments.length),Oe("Reference.setWithPriority","onComplete",r,!0);var n=((e,t,r)=>{if(mf("setWithPriority",e._path),uf("setWithPriority",t,e._path,!1),pf("setWithPriority",r,!1),".length"===e.key||".keys"===e.key)throw"setWithPriority failed: "+e.key+" is a read-only object.";var n=new Z;return jf(e._repo,e._path,t,r,n.wrapCallback(()=>{})),n.promise})(this._delegate,e,t);return r&&n.then(()=>r(null),e=>r(e)),n}remove(t){l("Reference.remove",0,1,arguments.length),Oe("Reference.remove","onComplete",t,!0);e=this._delegate,mf("remove",e._path);var e,r=wg(e,null);return t&&r.then(()=>t(null),e=>t(e)),r}transaction(e,t,r){l("Reference.transaction",1,3,arguments.length),Oe("Reference.transaction","transactionUpdate",e,!1),Oe("Reference.transaction","onComplete",t,!0);var n,i="Reference.transaction",s="applyLocally",a=r,o=!0;if(o&&void 0===a||"boolean"==typeof a)return n=im(this._delegate,e,{applyLocally:r}).then(e=>new lm(e.committed,new hm(this.database,e.snapshot))),t&&n.then(e=>t(null,e.committed,e.snapshot),e=>t(e,!1,null)),n;throw new Error(xe(i,s)+"must be a boolean.")}setPriority(e,t){l("Reference.setPriority",1,2,arguments.length),Oe("Reference.setPriority","onComplete",t,!0);r=this._delegate,e=e,r=w(r),mf("setPriority",r._path),pf("setPriority",e,!1),n=new Z,jf(r._repo,iu(r._path,".priority"),e,null,n.wrapCallback(()=>{}));var r,n=n.promise;return t&&n.then(()=>t(null),e=>t(e)),n}push(e,t){l("Reference.push",0,2,arguments.length),Oe("Reference.push","onComplete",t,!0);var r=((e,t)=>{e=w(e),mf("push",e._path),uf("push",t,e._path,!0);var r=Lf(e._repo),r=ag(r),n=yg(e,r);let i=yg(e,r),s;return s=null!=t?wg(i,t).then(()=>i):Promise.resolve(i),n.then=s.then.bind(s),n.catch=s.then.bind(s,void 0),n})(this._delegate,e),n=r.then(e=>new um(this.database,e)),r=(t&&n.then(()=>t(null),e=>t(e)),new um(this.database,r));return r.then=n.then.bind(n),r.catch=n.catch.bind(n,void 0),r}onDisconnect(){return mf("Reference.onDisconnect",this._delegate._path),new om(new cg(this._delegate._repo,this._delegate._path))}get key(){return this.getKey()}get parent(){return this.getParent()}get root(){return this.getRoot()}}class dm{constructor(e,t){this._delegate=e,this.app=t,this.INTERNAL={delete:()=>this._delegate._delete(),forceWebSockets:Jg,forceLongPolling:Xg}}useEmulator(e,t,r={}){Zg(this._delegate,e,t,r)}ref(e){var t;return l("database.ref",0,1,arguments.length),e instanceof um?(t=_g(this._delegate,e.toString()),new um(this,t)):(t=vg(this._delegate,e),new um(this,t))}refFromURL(e){l("database.refFromURL",1,1,arguments.length);var t=_g(this._delegate,e);return new um(this,t)}goOffline(){var e;l("database.goOffline",0,0,arguments.length),(e=w(e=this._delegate))._checkNotDeleted("goOffline"),Hf(e._repo)}goOnline(){return l("database.goOnline",0,0,arguments.length),em(this._delegate)}}dm.ServerValue={TIMESTAMP:rm,increment:e=>({".sv":{increment:e}})};ar=Object.freeze({__proto__:null,initStandalone:function({app:e,url:t,version:r,customAuthImpl:n,customAppCheckImpl:i,namespace:s,nodeAdmin:a=!1}){$h(r);var o=new He("database-standalone"),l=new We("auth-internal",o);l.setComponent(new c("auth-internal",()=>n,"PRIVATE"));let h=void 0;return i&&(h=new We("app-check-internal",o)).setComponent(new c("app-check-internal",()=>i,"PRIVATE")),{instance:new dm($g(e,l,h,t,a),e),namespace:s}}});let pm=dm.ServerValue;(t=or).INTERNAL.registerComponent(new c("database-compat",(e,{instanceIdentifier:t})=>{var r=e.getProvider("app-compat").getImmediate(),n=e.getProvider("database").getImmediate({identifier:t});return new dm(n,r)},"PUBLIC").setServiceProps({Reference:um,Query:cm,Database:dm,DataSnapshot:hm,enableLogging:tm,INTERNAL:ar,ServerValue:pm}).setMultipleInstances(!0)),t.registerVersion("@firebase/database-compat","2.1.3");var fm,gm,mm,vm,_m,ym,wm,bm,Im,Tm,Em,e,Cm,lr="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},Sm=(!(function(){var e,t,s;function r(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.C=Array(this.blockSize),this.o=this.h=0,this.u()}function n(){}function a(e,t,r){r=r||0;var n=Array(16);if("string"==typeof t)for(var i=0;i<16;++i)n[i]=t.charCodeAt(r++)|t.charCodeAt(r++)<<8|t.charCodeAt(r++)<<16|t.charCodeAt(r++)<<24;else for(i=0;i<16;++i)n[i]=t[r++]|t[r++]<<8|t[r++]<<16|t[r++]<<24;t=e.g[0],r=e.g[1];var i=e.g[2],s=e.g[3],a=t+(s^r&(i^s))+n[0]+3614090360&4294967295;a=(r=(i=(s=(t=(r=(i=(s=(t=(r=(i=(s=(t=(r=(i=(s=(t=(r=(i=(s=(t=(r=(i=(s=(t=(r=(i=(s=(t=(r=(i=(s=(t=(r=(i=(s=(t=(r=(i=(s=(t=(r=(i=(s=(t=(r=(i=(s=(t=(r=(i=(s=(t=(r=(i=(s=(t=(r=(i=(s=(t=r+(a<<7&4294967295|a>>>25))+((a=s+(i^t&(r^i))+n[1]+3905402710&4294967295)<<12&4294967295|a>>>20))+((a=i+(r^s&(t^r))+n[2]+606105819&4294967295)<<17&4294967295|a>>>15))+((a=r+(t^i&(s^t))+n[3]+3250441966&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^r&(i^s))+n[4]+4118548399&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(r^i))+n[5]+1200080426&4294967295)<<12&4294967295|a>>>20))+((a=i+(r^s&(t^r))+n[6]+2821735955&4294967295)<<17&4294967295|a>>>15))+((a=r+(t^i&(s^t))+n[7]+4249261313&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^r&(i^s))+n[8]+1770035416&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(r^i))+n[9]+2336552879&4294967295)<<12&4294967295|a>>>20))+((a=i+(r^s&(t^r))+n[10]+4294925233&4294967295)<<17&4294967295|a>>>15))+((a=r+(t^i&(s^t))+n[11]+2304563134&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^r&(i^s))+n[12]+1804603682&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(r^i))+n[13]+4254626195&4294967295)<<12&4294967295|a>>>20))+((a=i+(r^s&(t^r))+n[14]+2792965006&4294967295)<<17&4294967295|a>>>15))+((a=r+(t^i&(s^t))+n[15]+1236535329&4294967295)<<22&4294967295|a>>>10))+((a=t+(i^s&(r^i))+n[1]+4129170786&4294967295)<<5&4294967295|a>>>27))+((a=s+(r^i&(t^r))+n[6]+3225465664&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^r&(s^t))+n[11]+643717713&4294967295)<<14&4294967295|a>>>18))+((a=r+(s^t&(i^s))+n[0]+3921069994&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(r^i))+n[5]+3593408605&4294967295)<<5&4294967295|a>>>27))+((a=s+(r^i&(t^r))+n[10]+38016083&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^r&(s^t))+n[15]+3634488961&4294967295)<<14&4294967295|a>>>18))+((a=r+(s^t&(i^s))+n[4]+3889429448&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(r^i))+n[9]+568446438&4294967295)<<5&4294967295|a>>>27))+((a=s+(r^i&(t^r))+n[14]+3275163606&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^r&(s^t))+n[3]+4107603335&4294967295)<<14&4294967295|a>>>18))+((a=r+(s^t&(i^s))+n[8]+1163531501&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(r^i))+n[13]+2850285829&4294967295)<<5&4294967295|a>>>27))+((a=s+(r^i&(t^r))+n[2]+4243563512&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^r&(s^t))+n[7]+1735328473&4294967295)<<14&4294967295|a>>>18))+((a=r+(s^t&(i^s))+n[12]+2368359562&4294967295)<<20&4294967295|a>>>12))+((a=t+(r^i^s)+n[5]+4294588738&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^r^i)+n[8]+2272392833&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^r)+n[11]+1839030562&4294967295)<<16&4294967295|a>>>16))+((a=r+(i^s^t)+n[14]+4259657740&4294967295)<<23&4294967295|a>>>9))+((a=t+(r^i^s)+n[1]+2763975236&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^r^i)+n[4]+1272893353&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^r)+n[7]+4139469664&4294967295)<<16&4294967295|a>>>16))+((a=r+(i^s^t)+n[10]+3200236656&4294967295)<<23&4294967295|a>>>9))+((a=t+(r^i^s)+n[13]+681279174&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^r^i)+n[0]+3936430074&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^r)+n[3]+3572445317&4294967295)<<16&4294967295|a>>>16))+((a=r+(i^s^t)+n[6]+76029189&4294967295)<<23&4294967295|a>>>9))+((a=t+(r^i^s)+n[9]+3654602809&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^r^i)+n[12]+3873151461&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^r)+n[15]+530742520&4294967295)<<16&4294967295|a>>>16))+((a=r+(i^s^t)+n[2]+3299628645&4294967295)<<23&4294967295|a>>>9))+((a=t+(i^(r|~s))+n[0]+4096336452&4294967295)<<6&4294967295|a>>>26))+((a=s+(r^(t|~i))+n[7]+1126891415&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~r))+n[14]+2878612391&4294967295)<<15&4294967295|a>>>17))+((a=r+(s^(i|~t))+n[5]+4237533241&4294967295)<<21&4294967295|a>>>11))+((a=t+(i^(r|~s))+n[12]+1700485571&4294967295)<<6&4294967295|a>>>26))+((a=s+(r^(t|~i))+n[3]+2399980690&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~r))+n[10]+4293915773&4294967295)<<15&4294967295|a>>>17))+((a=r+(s^(i|~t))+n[1]+2240044497&4294967295)<<21&4294967295|a>>>11))+((a=t+(i^(r|~s))+n[8]+1873313359&4294967295)<<6&4294967295|a>>>26))+((a=s+(r^(t|~i))+n[15]+4264355552&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~r))+n[6]+2734768916&4294967295)<<15&4294967295|a>>>17))+((a=r+(s^(i|~t))+n[13]+1309151649&4294967295)<<21&4294967295|a>>>11))+((s=(t=r+((a=t+(i^(r|~s))+n[4]+4149444226&4294967295)<<6&4294967295|a>>>26))+((a=s+(r^(t|~i))+n[11]+3174756917&4294967295)<<10&4294967295|a>>>22))^((i=s+((a=i+(t^(s|~r))+n[2]+718787259&4294967295)<<15&4294967295|a>>>17))|~t))+n[9]+3951481745&4294967295,e.g[0]=e.g[0]+t&4294967295,e.g[1]=e.g[1]+(i+(a<<21&4294967295|a>>>11))&4294967295,e.g[2]=e.g[2]+i&4294967295,e.g[3]=e.g[3]+s&4294967295}function l(e,t){this.h=t;var r=[];let n=!0;for(let s=e.length-1;0<=s;s--){var i=0|e[s];n&&i==t||(r[s]=i,n=!1)}this.g=r}t=r,s=function(){this.blockSize=-1},n.prototype=s.prototype,t.F=s.prototype,t.prototype=new n,(t.prototype.constructor=t).D=function(e,t,r){for(var n=Array(arguments.length-2),i=2;i<arguments.length;i++)n[i-2]=arguments[i];return s.prototype[t].apply(e,n)},r.prototype.u=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.o=this.h=0},r.prototype.v=function(e,t){var r=(t=void 0===t?e.length:t)-this.blockSize,n=this.C;let i=this.h,s=0;for(;s<t;){if(0==i)for(;s<=r;)a(this,e,s),s+=this.blockSize;if("string"==typeof e){for(;s<t;)if(n[i++]=e.charCodeAt(s++),i==this.blockSize){a(this,n),i=0;break}}else for(;s<t;)if(n[i++]=e[s++],i==this.blockSize){a(this,n),i=0;break}}this.h=i,this.o+=t},r.prototype.A=function(){var t=Array((this.h<56?this.blockSize:2*this.blockSize)-this.h);t[0]=128;for(var r=1;r<t.length-8;++r)t[r]=0;for(var r=8*this.o,n=t.length-8;n<t.length;++n)t[n]=255&r,r/=256;for(this.v(t),t=Array(16),n=r=0;n<4;++n)for(let e=0;e<32;e+=8)t[r++]=this.g[n]>>>e&255;return t};var i={};function o(e){return-128<=e&&e<128?(t=e,r=function(e){return new l([0|e],e<0?-1:0)},n=i,Object.prototype.hasOwnProperty.call(n,t)?n[t]:n[t]=r(t)):new l([0|e],e<0?-1:0);var t,r,n}function h(e){if(isNaN(e)||!isFinite(e))return c;if(e<0)return g(h(-e));var t=[];let r=1;for(let n=0;e>=r;n++)t[n]=e/r|0,r*=4294967296;return new l(t,0)}var c=o(0),u=o(1),d=o(16777216);function p(t){if(0==t.h){for(let e=0;e<t.g.length;e++)if(0!=t.g[e])return;return 1}}function f(e){return-1==e.h}function g(e){var t=e.g.length,r=[];for(let n=0;n<t;n++)r[n]=~e.g[n];return new l(r,~e.h).add(u)}function m(e,t){return e.add(g(t))}function v(e,t){for(;(65535&e[t])!=e[t];)e[t+1]+=e[t]>>>16,e[t]&=65535,t++}function _(e,t){this.g=e,this.h=t}function y(e,t){if(p(t))throw Error("division by zero");if(p(e))return new _(c,c);if(f(e))return t=y(g(e),t),new _(g(t.g),g(t.h));if(f(t))return t=y(e,g(t)),new _(g(t.g),t.h);if(30<e.g.length){if(f(e)||f(t))throw Error("slowDivide_ only works with positive integers.");for(var r=u,n=t;n.l(e)<=0;)r=w(r),n=w(n);for(var i=b(r,1),s=b(n,1),n=b(n,2),r=b(r,2);!p(n);){var a=s.add(n);a.l(e)<=0&&(i=i.add(r),s=a),n=b(n,1),r=b(r,1)}return t=m(e,i.j(t)),new _(i,t)}for(i=c;0<=e.l(t);){for(r=Math.max(1,Math.floor(e.m()/t.m())),n=(n=Math.ceil(Math.log(r)/Math.LN2))<=48?1:Math.pow(2,n-48),a=(s=h(r)).j(t);f(a)||0<a.l(e);)a=(s=h(r-=n)).j(t);p(s)&&(s=u),i=i.add(s),e=m(e,a)}return new _(i,e)}function w(e){var t=e.g.length+1,r=[];for(let n=0;n<t;n++)r[n]=e.i(n)<<1|e.i(n-1)>>>31;return new l(r,e.h)}function b(e,t){var r=t>>5,n=(t%=32,e.g.length-r),i=[];for(let s=0;s<n;s++)i[s]=0<t?e.i(s+r)>>>t|e.i(s+r+1)<<32-t:e.i(s+r);return new l(i,e.h)}(e=l.prototype).m=function(){if(f(this))return-g(this).m();let e=0,t=1;for(let n=0;n<this.g.length;n++){var r=this.i(n);e+=(0<=r?r:4294967296+r)*t,t*=4294967296}return e},e.toString=function(t){if((t=t||10)<2||36<t)throw Error("radix out of range: "+t);if(p(this))return"0";if(f(this))return"-"+g(this).toString(t);var r=h(Math.pow(t,6)),n=this;let i="";for(;;){var s=y(n,r).g;let e=((0<(n=m(n,s.j(r))).g.length?n.g[0]:n.h)>>>0).toString(t);if(p(n=s))return e+i;for(;e.length<6;)e="0"+e;i=e+i}},e.i=function(e){return e<0?0:e<this.g.length?this.g[e]:this.h},e.l=function(e){return f(e=m(this,e))?-1:p(e)?0:1},e.abs=function(){return f(this)?g(this):this},e.add=function(e){var t=Math.max(this.g.length,e.g.length),r=[];let n=0;for(let a=0;a<=t;a++){var i=n+(65535&this.i(a))+(65535&e.i(a)),s=(i>>>16)+(this.i(a)>>>16)+(e.i(a)>>>16);n=s>>>16,i&=65535,s&=65535,r[a]=s<<16|i}return new l(r,-2147483648&r[r.length-1]?-1:0)},e.j=function(t){if(p(this)||p(t))return c;if(f(this))return f(t)?g(this).j(g(t)):g(g(this).j(t));if(f(t))return g(this.j(g(t)));if(this.l(d)<0&&t.l(d)<0)return h(this.m()*t.m());for(var e=this.g.length+t.g.length,r=[],n=0;n<2*e;n++)r[n]=0;for(n=0;n<this.g.length;n++)for(let e=0;e<t.g.length;e++){var i=this.i(n)>>>16,s=65535&this.i(n),a=t.i(e)>>>16,o=65535&t.i(e);r[2*n+2*e]+=s*o,v(r,2*n+2*e),r[2*n+2*e+1]+=i*o,v(r,2*n+2*e+1),r[2*n+2*e+1]+=s*a,v(r,2*n+2*e+1),r[2*n+2*e+2]+=i*a,v(r,2*n+2*e+2)}for(t=0;t<e;t++)r[t]=r[2*t+1]<<16|r[2*t];for(t=e;t<2*e;t++)r[t]=0;return new l(r,0)},e.B=function(e){return y(this,e).h},e.and=function(e){var t=Math.max(this.g.length,e.g.length),r=[];for(let n=0;n<t;n++)r[n]=this.i(n)&e.i(n);return new l(r,this.h&e.h)},e.or=function(e){var t=Math.max(this.g.length,e.g.length),r=[];for(let n=0;n<t;n++)r[n]=this.i(n)|e.i(n);return new l(r,this.h|e.h)},e.xor=function(e){var t=Math.max(this.g.length,e.g.length),r=[];for(let n=0;n<t;n++)r[n]=this.i(n)^e.i(n);return new l(r,this.h^e.h)},r.prototype.digest=r.prototype.A,r.prototype.reset=r.prototype.u,r.prototype.update=r.prototype.v,gm=r,l.prototype.multiply=l.prototype.j,l.prototype.modulo=l.prototype.B,l.prototype.compare=l.prototype.l,l.prototype.toNumber=l.prototype.m,l.prototype.getBits=l.prototype.i,l.fromNumber=h,l.fromString=function e(t,r){if(0==t.length)throw Error("number format error: empty string");if((r=r||10)<2||36<r)throw Error("radix out of range: "+r);if("-"==t.charAt(0))return g(e(t.substring(1),r));if(0<=t.indexOf("-"))throw Error('number format error: interior "-" character');var n=h(Math.pow(r,8));let i=c;for(let o=0;o<t.length;o+=8){var s=Math.min(8,t.length-o),a=parseInt(t.substring(o,o+s),r);i=(s<8?(s=h(Math.pow(r,s)),i.j(s)):i=i.j(n)).add(h(a))}return i},fm=l}).apply(void 0!==lr?lr:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{}),"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{});!(function(){var e,L=Object.defineProperty;var F=(e=>{e=["object"==typeof globalThis&&globalThis,e,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof Sm&&Sm];for(var t=0;t<e.length;++t){var r=e[t];if(r&&r.Math==Math)return r}throw Error("Cannot find global object")})(this);function U(e,t){if(t)e:{var r=F;e=e.split(".");for(var n=0;n<e.length-1;n++){var i=e[n];if(!(i in r))break e;r=r[i]}(t=t(n=r[e=e[e.length-1]]))!=n&&null!=t&&L(r,e,{configurable:!0,writable:!0,value:t})}}U("Symbol.dispose",function(e){return e||Symbol("Symbol.dispose")}),U("Array.prototype.values",function(e){return e||function(){return this[Symbol.iterator]()}}),U("Object.entries",function(e){return e||function(e){var t,r=[];for(t in e)Object.prototype.hasOwnProperty.call(e,t)&&r.push([t,e[t]]);return r}});var V=V||{},N=this||self;function d(e){var t=typeof e;return"object"==t&&null!=e||"function"==t}function q(e,t,r){return e.call.apply(e.bind,arguments)}function v(e,t,r){return(v=q).apply(null,arguments)}function B(t){var r=Array.prototype.slice.call(arguments,1);return function(){var e=r.slice();return e.push.apply(e,arguments),t.apply(this,e)}}function t(e,s){function t(){}t.prototype=s.prototype,e.Z=s.prototype,e.prototype=new t,(e.prototype.constructor=e).Ob=function(e,t,r){for(var n=Array(arguments.length-2),i=2;i<arguments.length;i++)n[i-2]=arguments[i];return s.prototype[t].apply(e,n)}}var j="undefined"!=typeof AsyncContext&&"function"==typeof AsyncContext.Snapshot?e=>e&&AsyncContext.Snapshot.wrap(e):e=>e;function z(t){var r=t.length;if(0<r){var n=Array(r);for(let e=0;e<r;e++)n[e]=t[e];return n}return[]}function K(t){for(let e=1;e<arguments.length;e++){var r=arguments[e];if("array"==(n="object"!=(n=typeof r)?n:r?Array.isArray(r)?"array":n:"null")||"object"==n&&"number"==typeof r.length){var n=t.length||0,i=r.length||0;t.length=n+i;for(let e=0;e<i;e++)t[n+e]=r[e]}else t.push(r)}}var W=new class{constructor(e,t){this.i=e,this.j=t,this.h=0,this.g=null}get(){let e;return 0<this.h?(this.h--,e=this.g,this.g=e.next,e.next=null):e=this.i(),e}}(()=>new H,e=>e.reset());class H{constructor(){this.next=this.g=this.h=null}set(e,t){this.h=e,this.g=t,this.next=null}reset(){this.next=this.g=this.h=null}}let r,n=!1,G=new class{constructor(){this.h=this.g=null}add(e,t){var r=W.get();r.set(e,t),this.h?this.h.next=r:this.g=r,this.h=r}},$=()=>{let e=Promise.resolve(void 0);r=()=>{e.then(Q)}};function Q(){for(var e;e=(()=>{let e=G,t=null;return e.g&&(t=e.g,e.g=e.g.next,e.g||(e.h=null),t.next=null),t})();){try{e.h.call(e.g)}catch(e){(e=>{N.setTimeout(()=>{throw e},0)})(e)}var t=W;t.j(e),t.h<100&&(t.h++,e.next=t.g,t.g=e)}n=!1}function i(){this.u=this.u,this.C=this.C}function o(e,t){this.type=e,this.g=this.target=t,this.defaultPrevented=!1}i.prototype.u=!1,i.prototype.dispose=function(){this.u||(this.u=!0,this.N())},i.prototype[Symbol.dispose]=function(){this.dispose()},i.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()},o.prototype.h=function(){this.defaultPrevented=!0};var Y=(()=>{if(!N.addEventListener||!Object.defineProperty)return!1;var e=!1,t=Object.defineProperty({},"passive",{get:function(){e=!0}});try{var r=()=>{};N.addEventListener("test",r,t),N.removeEventListener("test",r,t)}catch(e){}return e})();function R(e){return/^[\s\xa0]*$/.test(e)}function s(e,t){o.call(this,e?e.type:""),this.relatedTarget=this.g=this.target=null,this.button=this.screenY=this.screenX=this.clientY=this.clientX=0,this.key="",this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1,this.state=null,this.pointerId=0,this.pointerType="",this.i=null,e&&this.init(e,t)}t(s,o),s.prototype.init=function(e,t){var r=this.type=e.type,n=e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:null;this.target=e.target||e.srcElement,this.g=t,(t=e.relatedTarget)||("mouseover"==r?t=e.fromElement:"mouseout"==r&&(t=e.toElement)),this.relatedTarget=t,n?(this.clientX=void 0!==n.clientX?n.clientX:n.pageX,this.clientY=void 0!==n.clientY?n.clientY:n.pageY,this.screenX=n.screenX||0,this.screenY=n.screenY||0):(this.clientX=void 0!==e.clientX?e.clientX:e.pageX,this.clientY=void 0!==e.clientY?e.clientY:e.pageY,this.screenX=e.screenX||0,this.screenY=e.screenY||0),this.button=e.button,this.key=e.key||"",this.ctrlKey=e.ctrlKey,this.altKey=e.altKey,this.shiftKey=e.shiftKey,this.metaKey=e.metaKey,this.pointerId=e.pointerId||0,this.pointerType=e.pointerType,this.state=e.state,(this.i=e).defaultPrevented&&s.Z.h.call(this)},s.prototype.h=function(){s.Z.h.call(this);var e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1};var l="closure_listenable_"+(1e6*Math.random()|0),J=0;function X(e,t,r,n,i){this.listener=e,this.proxy=null,this.src=t,this.type=r,this.capture=!!n,this.ha=i,this.key=++J,this.da=this.fa=!1}function Z(e){e.da=!0,e.listener=null,e.proxy=null,e.src=null,e.ha=null}function ee(e,t,r){for(var n in e)t.call(r,e[n],n,e)}function te(e){var t,r={};for(t in e)r[t]=e[t];return r}let re="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function ne(t){let r,n;for(let i=1;i<arguments.length;i++){for(r in n=arguments[i])t[r]=n[r];for(let e=0;e<re.length;e++)r=re[e],Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}}function ie(e){this.src=e,this.g={},this.h=0}function se(e,t){var r,n,i,s=t.type;s in e.g&&(r=e.g[s],(i=0<=(n=Array.prototype.indexOf.call(r,t,void 0)))&&Array.prototype.splice.call(r,n,1),i)&&(Z(t),0==e.g[s].length)&&(delete e.g[s],e.h--)}function ae(e,t,r,n){for(let s=0;s<e.length;++s){var i=e[s];if(!i.da&&i.listener==t&&i.capture==!!r&&i.ha==n)return s}return-1}ie.prototype.add=function(e,t,r,n,i){var s=e.toString(),a=((e=this.g[s])||(e=this.g[s]=[],this.h++),ae(e,t,n,i));return-1<a?(t=e[a],r||(t.fa=!1)):((t=new X(t,this.src,s,!!n,i)).fa=r,e.push(t)),t};var oe="closure_lm_"+(1e6*Math.random()|0),le={};function he(t,r,n,i,s){if(i&&i.once)return function t(r,n,i,s,a){if(Array.isArray(n)){for(let e=0;e<n.length;e++)t(r,n[e],i,s,a);return null}i=me(i);return r&&r[l]?r.K(n,i,d(s)?!!s.capture:!!s,a):ce(r,n,i,!0,s,a)}(t,r,n,i,s);if(Array.isArray(r)){for(let e=0;e<r.length;e++)he(t,r[e],n,i,s);return null}return n=me(n),t&&t[l]?t.J(r,n,d(i)?!!i.capture:!!i,s):ce(t,r,n,!1,i,s)}function ce(e,t,r,n,i,s){if(!t)throw Error("Invalid event type");var a=d(i)?!!i.capture:!!i;let o=fe(e);if(o||(e[oe]=o=new ie(e)),!(r=o.add(t,r,n,a,s)).proxy)if(n=(()=>{let r=pe;return function e(t){return r.call(e.src,e.listener,t)}})(),(r.proxy=n).src=e,n.listener=r,e.addEventListener)void 0===(i=Y?i:a)&&(i=!1),e.addEventListener(t.toString(),n,i);else if(e.attachEvent)e.attachEvent(de(t.toString()),n);else{if(!e.addListener||!e.removeListener)throw Error("addEventListener and attachEvent are unavailable.");e.addListener(n)}return r}function ue(e){var t,r,n;"number"!=typeof e&&e&&!e.da&&((t=e.src)&&t[l]?se(t.i,e):(r=e.type,n=e.proxy,t.removeEventListener?t.removeEventListener(r,n,e.capture):t.detachEvent?t.detachEvent(de(r),n):t.addListener&&t.removeListener&&t.removeListener(n),(r=fe(t))?(se(r,e),0==r.h&&(r.src=null,t[oe]=null)):Z(e)))}function de(e){return e in le?le[e]:le[e]="on"+e}function pe(e,t){var r,n;return e=!!e.da||(t=new s(t,this),r=e.listener,n=e.ha||e.src,e.fa&&ue(e),r.call(n,t))}function fe(e){return(e=e[oe])instanceof ie?e:null}var ge="__closure_events_fn_"+(1e9*Math.random()>>>0);function me(t){return"function"==typeof t?t:(t[ge]||(t[ge]=function(e){return t.handleEvent(e)}),t[ge])}function a(){i.call(this),this.i=new ie(this),(this.M=this).G=null}function h(e,t){var r,n,i=e.G;if(i)for(r=[];i;i=i.G)r.push(i);e=e.M,i=t.type||t,"string"==typeof t?t=new o(t,e):t instanceof o?t.target=t.target||e:(n=t,ne(t=new o(i,e),n)),n=!0;let s,a;if(r)for(a=r.length-1;0<=a;a--)n=ve(s=t.g=r[a],i,!0,t)&&n;if(n=ve(s=t.g=e,i,!0,t)&&n,n=ve(s,i,!1,t)&&n,r)for(a=0;a<r.length;a++)n=ve(s=t.g=r[a],i,!1,t)&&n}function ve(e,t,r,n){if(!(t=e.i.g[String(t)]))return!0;t=t.concat();let i=!0;for(let l=0;l<t.length;++l){var s,a,o=t[l];o&&!o.da&&o.capture==r&&(s=o.listener,a=o.ha||o.src,o.fa&&se(e.i,o),i=!1!==s.call(a,n)&&i)}return i&&!n.defaultPrevented}function _e(e){e.g=((e,t)=>{if("function"!=typeof e){if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=v(e.handleEvent,e)}return 2147483647<Number(t)?-1:N.setTimeout(e,t||0)})(()=>{e.g=null,e.i&&(e.i=!1,_e(e))},e.l);var t=e.h;e.h=null,e.m.apply(null,t)}t(a,i),a.prototype[l]=!0,a.prototype.removeEventListener=function(e,t,r,n){!function e(t,r,n,i,s){if(Array.isArray(r))for(var a=0;a<r.length;a++)e(t,r[a],n,i,s);else i=d(i)?!!i.capture:!!i,n=me(n),t&&t[l]?(t=t.i,(a=String(r).toString())in t.g&&-1<(n=ae(r=t.g[a],n,i,s))&&(Z(r[n]),Array.prototype.splice.call(r,n,1),0==r.length)&&(delete t.g[a],t.h--)):(t=t&&fe(t))&&(r=t.g[r.toString()],n=(t=-1)<(t=r?ae(r,n,i,s):t)?r[t]:null)&&ue(n)}(this,e,t,r,n)},a.prototype.N=function(){if(a.Z.N.call(this),this.i){var t,r=this.i;for(t in r.g){var n=r.g[t];for(let e=0;e<n.length;e++)Z(n[e]);delete r.g[t],r.h--}}this.G=null},a.prototype.J=function(e,t,r,n){return this.i.add(String(e),t,!1,r,n)},a.prototype.K=function(e,t,r,n){return this.i.add(String(e),t,!0,r,n)};class ye extends i{constructor(e,t){super(),this.m=e,this.l=t,this.h=null,this.i=!1,this.g=null}j(e){this.h=arguments,this.g?this.i=!0:_e(this)}N(){super.N(),this.g&&(N.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function c(e){i.call(this),this.h=e,this.g={}}t(c,i);var we=[];function be(e){ee(e.g,function(e,t){this.g.hasOwnProperty(t)&&ue(e)},e),e.g={}}c.prototype.N=function(){c.Z.N.call(this),be(this)},c.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var Ie=N.JSON.stringify,Te=N.JSON.parse,Ee=class{stringify(e){return N.JSON.stringify(e,void 0)}parse(e){return N.JSON.parse(e,void 0)}};function Ce(){}function Se(){}var ke={OPEN:"a",hb:"b",ERROR:"c",tb:"d"};function Ae(){o.call(this,"d")}function Ne(){o.call(this,"c")}t(Ae,o),t(Ne,o);var u={},Re=null;function Pe(){return Re=Re||new a}function De(e){o.call(this,u.Ia,e)}function xe(){var e=Pe();h(e,new De(e))}function Oe(e,t){o.call(this,u.STAT_EVENT,e),this.stat=t}function P(e){var t=Pe();h(t,new Oe(t,e))}function Me(e,t){o.call(this,u.Ja,e),this.size=t}function _(e,t){if("function"!=typeof e)throw Error("Fn must not be null and must be a function");return N.setTimeout(function(){e()},t)}function p(){this.g=!0}function D(e,t,r,n){e.info(function(){return"XMLHTTP TEXT ("+t+"): "+((e,t)=>{if(!e.g)return t;if(!t)return null;try{var r=JSON.parse(t);if(r)for(e=0;e<r.length;e++)if(Array.isArray(r[e])){var n=r[e];if(!(n.length<2)){var i=n[1];if(Array.isArray(i)&&!(i.length<1)){var s=i[0];if("noop"!=s&&"stop"!=s&&"close"!=s)for(let e=1;e<i.length;e++)i[e]=""}}}return Ie(r)}catch(e){return t}})(e,r)+(n?" "+n:"")})}u.Ia="serverreachability",t(De,o),u.STAT_EVENT="statevent",t(Oe,o),u.Ja="timingevent",t(Me,o),p.prototype.ua=function(){this.g=!1},p.prototype.info=function(){};var Le={NO_ERROR:0,cb:1,qb:2,pb:3,kb:4,ob:5,rb:6,Ga:7,TIMEOUT:8,ub:9},Fe={ib:"complete",Fb:"success",ERROR:"error",Ga:"abort",xb:"ready",yb:"readystatechange",TIMEOUT:"timeout",sb:"incrementaldata",wb:"progress",lb:"downloadprogress",Nb:"uploadprogress"};function Ue(){}function f(e){return encodeURIComponent(String(e))}function g(e,t,r,n){this.j=e,this.i=t,this.l=r,this.S=n||1,this.V=new c(this),this.H=45e3,this.J=null,this.o=!1,this.u=this.B=this.A=this.M=this.F=this.T=this.D=null,this.G=[],this.g=null,this.C=0,this.m=this.v=null,this.X=-1,this.K=!1,this.P=0,this.O=null,this.W=this.L=this.U=this.R=!1,this.h=new Ve}function Ve(){this.i=null,this.g="",this.h=!1}t(Ue,Ce),Ue.prototype.g=function(){return new XMLHttpRequest};var qe=new Ue,Be={},je={};function ze(e,t,r){e.M=1,e.A=ot(y(t)),e.u=r,e.R=!0,Ke(e,null)}function Ke(e,t){e.F=Date.now(),He(e),e.B=y(e.A);var a,o,l,h,c,u,r=e.B,n=e.S,i=(Array.isArray(n)||(n=[String(n)]),wt(r.i,"t",n),e.C=0,r=e.j.L,e.h=new Ve,e.g=tr(e.j,r?t:null,!e.u),0<e.P&&(e.O=new ye(v(e.Y,e,e.g),e.P)),t=e.V,r=e.g,n=e.ba,"readystatechange");Array.isArray(i)||(i&&(we[0]=i.toString()),i=we);for(let d=0;d<i.length;d++){var s=he(r,i[d],n||t.handleEvent,!1,t.h||t);if(!s)break;t.g[s.key]=s}t=e.J?te(e.J):{},e.u?(e.v||(e.v="POST"),t["Content-Type"]="application/x-www-form-urlencoded",e.g.ea(e.B,e.v,e.u,t)):(e.v="GET",e.g.ea(e.B,e.v,null,t)),xe(),a=e.i,o=e.v,l=e.B,h=e.l,c=e.S,u=e.u,a.info(function(){if(a.g)if(u){var t="",r=u.split("&");for(let e=0;e<r.length;e++){var n,i,s=r[e].split("=");1<s.length&&(n=s[0],s=s[1],t=2<=(i=n.split("_")).length&&"type"==i[1]?t+(n+"=")+s+"&":t+(n+"=redacted&"))}}else t=null;else t=u;return"XMLHTTP REQ ("+h+") [attempt "+c+"]: "+o+"\n"+l+"\n"+t})}function We(e){return e.g&&"GET"==e.v&&2!=e.M&&e.j.Aa}function He(e){e.T=Date.now()+e.H,Ge(e,e.H)}function Ge(e,t){if(null!=e.D)throw Error("WatchDog timer not null");e.D=_(v(e.aa,e),t)}function $e(e){e.D&&(N.clearTimeout(e.D),e.D=null)}function x(e){0==e.j.I||e.K||Jt(e.j,e)}function O(e){$e(e);var t=e.O;t&&"function"==typeof t.dispose&&t.dispose(),e.O=null,be(e.V),e.g&&(t=e.g,e.g=null,t.abort(),t.dispose())}function Qe(e,t){try{var r=e.j;if(0!=r.I&&(r.g==e||et(r.h,e)))if(!e.L&&et(r.h,e)&&3==r.I){try{var n=r.Ba.g.parse(t)}catch(e){n=null}if(Array.isArray(n)&&3==n.length){var i=n;if(0==i[0]){e:if(!r.v){if(r.g){if(!(r.g.F+3e3<e.F))break e;Yt(r),qt(r)}Gt(r),P(18)}}else r.xa=i[1],0<r.xa-r.K&&i[2]<37500&&r.F&&0==r.A&&!r.C&&(r.C=_(v(r.Va,r),6e3));Ze(r.h)<=1&&r.ta&&(r.ta=void 0)}else S(r,11)}else if(!e.L&&r.g!=e||Yt(r),!R(t))for(i=r.Ba.g.parse(t),t=0;t<i.length;t++){var s,a,o,l,h,c,u,d,p,f,g=i[t],m=g[0];m<=r.K||(r.K=m,g=g[1],2==r.I?"c"==g[0]?(r.M=g[1],r.ba=g[2],null!=(s=g[3])&&(r.ka=s,r.j.info("VER="+r.ka)),null!=(a=g[4])&&(r.za=a,r.j.info("SVER="+r.za)),null!=(o=g[5])&&"number"==typeof o&&0<o&&(n=1.5*o,r.O=n,r.j.info("backChannelRequestTimeoutMs_="+n)),n=r,(l=e.g)&&(!(h=l.g?l.g.getResponseHeader("X-Client-Wire-Protocol"):null)||(c=n.h).g||-1==h.indexOf("spdy")&&-1==h.indexOf("quic")&&-1==h.indexOf("h2")||(c.j=c.l,c.g=new Set,c.h&&(tt(c,c.h),c.h=null)),n.G)&&(u=l.g?l.g.getResponseHeader("X-HTTP-Session-Id"):null)&&(n.wa=u,b(n.J,n.G,u)),r.I=3,r.l&&r.l.ra(),r.aa&&(r.T=Date.now()-e.F,r.j.info("Handshake RTT: "+r.T+"ms")),d=e,(n=r).na=er(n,n.L?n.ba:null,n.W),d.L?(rt(n.h,d),p=d,(f=n.O)&&(p.H=f),p.D&&($e(p),He(p)),n.g=d):Ht(n),0<r.i.length&&jt(r)):"stop"!=g[0]&&"close"!=g[0]||S(r,7):3==r.I&&("stop"==g[0]||"close"==g[0]?"stop"==g[0]?S(r,7):Vt(r):"noop"!=g[0]&&r.l&&r.l.qa(g),r.A=0))}xe()}catch(e){}}g.prototype.ba=function(e){e=e.target;var t=this.O;t&&3==M(e)?t.j():this.Y(e)},g.prototype.Y=function(e){try{if(e==this.g)e:{var t=M(this.g),r=this.g.ya();this.g.ca();if(!(t<3)&&(3!=t||this.g&&(this.h.h||this.g.la()||Lt(this.g)))){this.K||4!=t||7==r||xe(),$e(this);var n,i,s=this.g.ca(),a=(this.X=s,(e=>{if(!We(e))return e.g.la();var t=Lt(e.g);if(""===t)return"";let r="",n=t.length,i=4==M(e.g);if(!e.h.i){if("undefined"==typeof TextDecoder)return O(e),x(e),"";e.h.i=new N.TextDecoder}for(let s=0;s<n;s++)e.h.h=!0,r+=e.h.i.decode(t[s],{stream:!(i&&s==n-1)});return t.length=0,e.h.g+=r,e.C=0,e.h.g})(this));if(this.o=200==s,I=this.i,T=this.v,E=this.B,C=this.l,S=this.S,k=t,A=s,I.info(function(){return"XMLHTTP RESP ("+C+") [ attempt "+S+"]: "+T+"\n"+E+"\n"+k+" "+A}),this.o){if(this.U&&!this.L){t:{if(this.g){var o,l=this.g;if((o=l.g?l.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!R(o)){var h=o;break t}}h=null}if(!(e=h)){this.o=!1,this.m=3,P(12),O(this),x(this);break e}D(this.i,this.l,e,"Initial handshake response via X-HTTP-Initial-Response"),this.L=!0,Qe(this,e)}if(this.R){for(e=!0;!this.K&&this.C<a.length;){if(y=a,b=w=void 0,w=(_=this).C,(n=-1==(b=y.indexOf("\n",w))?je:(w=Number(y.substring(w,b)),isNaN(w)?Be:(b+=1)+w>y.length?je:(y=y.slice(b,b+w),_.C=b+w,y)))==je){4==t&&(this.m=4,P(14),e=!1),D(this.i,this.l,null,"[Incomplete Response]");break}if(n==Be){this.m=4,P(15),D(this.i,this.l,a,"[Invalid Chunk]"),e=!1;break}D(this.i,this.l,n,null),Qe(this,n)}We(this)&&0!=this.C&&(this.h.g=this.h.g.slice(this.C),this.C=0),4!=t||0!=a.length||this.h.h||(this.m=1,P(16),e=!1),this.o=this.o&&e,e?0<a.length&&!this.W&&(this.W=!0,(i=this.j).g==this)&&i.aa&&!i.P&&(i.j.info("Great, no buffering proxy detected. Bytes received: "+a.length),$t(i),i.P=!0,P(11)):(D(this.i,this.l,a,"[Invalid Chunked Response]"),O(this),x(this))}else D(this.i,this.l,a,null),Qe(this,a);4==t&&O(this),this.o&&!this.K&&(4==t?Jt(this.j,this):(this.o=!1,He(this)))}else{{var c=this.g;var u,d,p,f={};c=(c.g&&2<=M(c)&&c.g.getAllResponseHeaders()||"").split("\r\n");for(let e=0;e<c.length;e++)R(c[e])||(u=(e=>{for(var t=1,r=(e=e.split(":"),[]);0<t&&e.length;)r.push(e.shift()),t--;return e.length&&r.push(e.join(":")),r})(c[e]),d=u[0],"string"==typeof(u=u[1])&&(u=u.trim(),p=f[d]||[],(f[d]=p).push(u)));var g,m=f,v=function(e){return e.join(", ")};for(g in m)v.call(void 0,m[g],g,m)}400==s&&0<a.indexOf("Unknown SID")?(this.m=3,P(12)):(this.m=0,P(13)),O(this),x(this)}}}}catch(e){}var _,y,w,b,I,T,E,C,S,k,A},g.prototype.cancel=function(){this.K=!0,O(this)},g.prototype.aa=function(){this.D=null;var e,t,r=Date.now();0<=r-this.T?(e=this.i,t=this.B,e.info(function(){return"TIMEOUT: "+t}),2!=this.M&&(xe(),P(17)),O(this),this.m=2,x(this)):Ge(this,this.T-r)};var Ye=class{constructor(e,t){this.g=e,this.map=t}};function Je(e){this.l=e||10,e=N.PerformanceNavigationTiming?0<(e=N.performance.getEntriesByType("navigation")).length&&("hq"==e[0].nextHopProtocol||"h2"==e[0].nextHopProtocol):!!(N.chrome&&N.chrome.loadTimes&&N.chrome.loadTimes()&&N.chrome.loadTimes().wasFetchedViaSpdy),this.j=e?this.l:1,this.g=null,1<this.j&&(this.g=new Set),this.h=null,this.i=[]}function Xe(e){return e.h||e.g&&e.g.size>=e.j}function Ze(e){return e.h?1:e.g?e.g.size:0}function et(e,t){return e.h?e.h==t:e.g&&e.g.has(t)}function tt(e,t){e.g?e.g.add(t):e.h=t}function rt(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function nt(t){if(null!=t.h)return t.i.concat(t.h.G);if(null==t.g||0===t.g.size)return z(t.i);{let e=t.i;for(var r of t.g.values())e=e.concat(r.G);return e}}Je.prototype.cancel=function(){if(this.i=nt(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&0!==this.g.size){for(var e of this.g.values())e.cancel();this.g.clear()}};var it=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function m(e){this.g=this.o=this.j="",this.u=null,this.m=this.h="",this.l=!1;let t;e instanceof m?(this.l=e.l,w(this,e.j),this.o=e.o,this.g=e.g,st(this,e.u),this.h=e.h,at(this,bt(e.i)),this.m=e.m):e&&(t=String(e).match(it))?(this.l=!1,w(this,t[1]||"",!0),this.o=lt(t[2]||""),this.g=lt(t[3]||"",!0),st(this,t[4]),this.h=lt(t[5]||"",!0),at(this,t[6]||"",!0),this.m=lt(t[7]||"")):(this.l=!1,this.i=new mt(null,this.l))}function y(e){return new m(e)}function w(e,t,r){e.j=r?lt(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function st(e,t){if(t){if(t=Number(t),isNaN(t)||t<0)throw Error("Bad port number "+t);e.u=t}else e.u=null}function at(e,t,r){var n,i;t instanceof mt?(e.i=t,n=e.i,(i=e.l)&&!n.j&&(I(n),n.i=null,n.g.forEach(function(e,t){var r=t.toLowerCase();t!=r&&(vt(this,t),wt(this,r,e))},n)),n.j=i):(r||(t=ht(t,ft)),e.i=new mt(t,e.l))}function b(e,t,r){e.i.set(t,r)}function ot(e){return b(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function lt(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function ht(e,t,r){return"string"==typeof e?(e=encodeURI(e).replace(t,ct),e=r?e.replace(/%25([0-9a-fA-F]{2})/g,"%$1"):e):null}function ct(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}m.prototype.toString=function(){var e=[],t=this.j,r=(t&&e.push(ht(t,ut,!0),":"),this.g);return!r&&"file"!=t||(e.push("//"),(t=this.o)&&e.push(ht(t,ut,!0),"@"),e.push(f(r).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null==(r=this.u))||e.push(":",String(r)),(r=this.h)&&(this.g&&"/"!=r.charAt(0)&&e.push("/"),e.push(ht(r,"/"==r.charAt(0)?pt:dt,!0))),(r=this.i.toString())&&e.push("?",r),(r=this.m)&&e.push("#",ht(r,gt)),e.join("")},m.prototype.resolve=function(e){var t=y(this);let r=!!e.j;r?w(t,e.j):r=!!e.o,r?t.o=e.o:r=!!e.g,r?t.g=e.g:r=null!=e.u;var n=e.h;if(r)st(t,e.u);else if(r=!!e.h)if("/"!=n.charAt(0)&&(this.g&&!this.h?n="/"+n:-1!=(i=t.h.lastIndexOf("/"))&&(n=t.h.slice(0,i+1)+n)),".."==(i=n)||"."==i)n="";else if(-1!=i.indexOf("./")||-1!=i.indexOf("/.")){var n=0==i.lastIndexOf("/",0),i=i.split("/"),s=[];for(let e=0;e<i.length;){var a=i[e++];"."==a?n&&e==i.length&&s.push(""):".."==a?((1<s.length||1==s.length&&""!=s[0])&&s.pop(),n&&e==i.length&&s.push("")):(s.push(a),n=!0)}n=s.join("/")}else n=i;return r?t.h=n:r=""!==e.i.toString(),r?at(t,bt(e.i)):r=!!e.m,r&&(t.m=e.m),t};var ut=/[#\/\?@]/g,dt=/[#\?:]/g,pt=/[#\?]/g,ft=/[#\?@]/g,gt=/#/g;function mt(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function I(r){if(!r.g&&(r.g=new Map,r.h=0,r.i)){var n=r.i,i=function(e,t){r.add(decodeURIComponent(e.replace(/\+/g," ")),t)};if(n){n=n.split("&");for(let r=0;r<n.length;r++){var s=n[r].indexOf("=");let e,t=null;0<=s?(e=n[r].substring(0,s),t=n[r].substring(s+1)):e=n[r],i(e,t?decodeURIComponent(t.replace(/\+/g," ")):"")}}}}function vt(e,t){I(e),t=T(e,t),e.g.has(t)&&(e.i=null,e.h-=e.g.get(t).length,e.g.delete(t))}function _t(e,t){return I(e),t=T(e,t),e.g.has(t)}function yt(e,t){I(e);let r=[];if("string"==typeof t)_t(e,t)&&(r=r.concat(e.g.get(T(e,t))));else for(e=Array.from(e.g.values()),t=0;t<e.length;t++)r=r.concat(e[t]);return r}function wt(e,t,r){vt(e,t),0<r.length&&(e.i=null,e.g.set(T(e,t),z(r)),e.h+=r.length)}function bt(e){var t=new mt;return t.i=e.i,e.g&&(t.g=new Map(e.g),t.h=e.h),t}function T(e,t){return t=String(t),t=e.j?t.toLowerCase():t}function E(e,t,r,n,i){try{i&&(i.onload=null,i.onerror=null,i.onabort=null,i.ontimeout=null),n(r)}catch(e){}}function It(){this.g=new Ee}function Tt(e){this.i=e.Sb||null,this.h=e.ab||!1}function Et(e,t){a.call(this),this.H=e,this.o=t,this.m=void 0,this.status=this.readyState=0,this.responseType=this.responseText=this.response=this.statusText="",this.onreadystatechange=null,this.A=new Headers,this.h=null,this.F="GET",this.D="",this.g=!1,this.B=this.j=this.l=null,this.v=new AbortController}function Ct(e){e.j.read().then(e.Ma.bind(e)).catch(e.ga.bind(e))}function St(e){e.readyState=4,e.l=null,e.j=null,e.B=null,kt(e)}function kt(e){e.onreadystatechange&&e.onreadystatechange.call(e)}function At(e){let r="";return ee(e,function(e,t){r=(r=r+t+":")+e+"\r\n"}),r}function Nt(e,t,r){e:{for(n in r){var n=!1;break e}n=!0}n||(r=At(r),"string"==typeof e?null!=r&&f(r):b(e,t,r))}function C(e){a.call(this),this.headers=new Map,this.L=e||null,this.h=!1,this.g=null,this.D="",this.o=0,this.l="",this.j=this.B=this.v=this.A=!1,this.m=null,this.F="",this.H=!1}(e=mt.prototype).add=function(e,t){I(this),this.i=null,e=T(this,e);let r=this.g.get(e);return r||this.g.set(e,r=[]),r.push(t),this.h+=1,this},e.forEach=function(r,n){I(this),this.g.forEach(function(e,t){e.forEach(function(e){r.call(n,e,t,this)},this)},this)},e.set=function(e,t){return I(this),this.i=null,_t(this,e=T(this,e))&&(this.h-=this.g.get(e).length),this.g.set(e,[t]),this.h+=1,this},e.get=function(e,t){return e&&0<(e=yt(this,e)).length?String(e[0]):t},e.toString=function(){if(this.i)return this.i;if(!this.g)return"";var r=[],e=Array.from(this.g.keys());for(let s=0;s<e.length;s++){var n=f(i=e[s]),i=yt(this,i);for(let t=0;t<i.length;t++){let e=n;""!==i[t]&&(e+="="+f(i[t])),r.push(e)}}return this.i=r.join("&")},t(Tt,Ce),Tt.prototype.g=function(){return new Et(this.i,this.h)},t(Et,a),(e=Et.prototype).open=function(e,t){if(0!=this.readyState)throw this.abort(),Error("Error reopening a connection");this.F=e,this.D=t,this.readyState=1,kt(this)},e.send=function(e){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");if(this.v.signal.aborted)throw this.abort(),Error("Request was aborted.");this.g=!0;var t={headers:this.A,method:this.F,credentials:this.m,cache:void 0,signal:this.v.signal};e&&(t.body=e),(this.H||N).fetch(new Request(this.D,t)).then(this.Pa.bind(this),this.ga.bind(this))},e.abort=function(){this.response=this.responseText="",this.A=new Headers,this.status=0,this.v.abort(),this.j&&this.j.cancel("Request was aborted.").catch(()=>{}),1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,St(this)),this.readyState=0},e.Pa=function(e){if(this.g&&(this.l=e,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=e.headers,this.readyState=2,kt(this)),this.g)&&(this.readyState=3,kt(this),this.g))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Na.bind(this),this.ga.bind(this));else if(void 0!==N.ReadableStream&&"body"in e){if(this.j=e.body.getReader(),this.o){if(this.responseType)throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');this.response=[]}else this.response=this.responseText="",this.B=new TextDecoder;Ct(this)}else e.text().then(this.Oa.bind(this),this.ga.bind(this))},e.Ma=function(e){var t;this.g&&(this.o&&e.value?this.response.push(e.value):!this.o&&(t=e.value||new Uint8Array(0),t=this.B.decode(t,{stream:!e.done}))&&(this.response=this.responseText+=t),(e.done?St:kt)(this),3==this.readyState)&&Ct(this)},e.Oa=function(e){this.g&&(this.response=this.responseText=e,St(this))},e.Na=function(e){this.g&&(this.response=e,St(this))},e.ga=function(){this.g&&St(this)},e.setRequestHeader=function(e,t){this.A.append(e,t)},e.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},e.getAllResponseHeaders=function(){if(!this.h)return"";for(var e=[],t=this.h.entries(),r=t.next();!r.done;)r=r.value,e.push(r[0]+": "+r[1]),r=t.next();return e.join("\r\n")},Object.defineProperty(Et.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}}),t(C,a);var Rt=/^https?$/i,Pt=["POST","PUT"];function Dt(e,t){e.h=!1,e.g&&(e.j=!0,e.g.abort(),e.j=!1),e.l=t,e.o=5,xt(e),Mt(e)}function xt(e){e.A||(e.A=!0,h(e,"complete"),h(e,"error"))}function Ot(t){if(t.h&&void 0!==V)if(t.v&&4==M(t))setTimeout(t.Ca.bind(t),0);else if(h(t,"readystatechange"),4==M(t)){t.h=!1;try{var e,r,n=t.ca();switch(n){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var i=!0;break;default:i=!1}if(!(e=i)){if(r=0===n){let e=String(t.D).match(it)[1]||null;!e&&N.self&&N.self.location&&(e=N.self.location.protocol.slice(0,-1)),r=!Rt.test(e?e.toLowerCase():"")}e=r}if(e)h(t,"complete"),h(t,"success");else{t.o=6;try{var s=2<M(t)?t.g.statusText:""}catch(e){s=""}t.l=s+" ["+t.ca()+"]",xt(t)}}finally{Mt(t)}}}function Mt(e,t){if(e.g){e.m&&(clearTimeout(e.m),e.m=null);var r=e.g;e.g=null,t||h(e,"ready");try{r.onreadystatechange=null}catch(e){}}}function M(e){return e.g?e.g.readyState:0}function Lt(e){try{if(e.g){if("response"in e.g)return e.g.response;switch(e.F){case"":case"text":return e.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in e.g)return e.g.mozResponseArrayBuffer}}return null}catch(e){return null}}function Ft(e,t,r){return r&&r.internalChannelParams&&r.internalChannelParams[e]||t}function Ut(e){this.za=0,this.i=[],this.j=new p,this.ba=this.na=this.J=this.W=this.g=this.wa=this.G=this.H=this.u=this.U=this.o=null,this.Ya=this.V=0,this.Sa=Ft("failFast",!1,e),this.F=this.C=this.v=this.m=this.l=null,this.X=!0,this.xa=this.K=-1,this.Y=this.A=this.D=0,this.Qa=Ft("baseRetryDelayMs",5e3,e),this.Za=Ft("retryDelaySeedMs",1e4,e),this.Ta=Ft("forwardChannelMaxRetries",2,e),this.va=Ft("forwardChannelRequestTimeoutMs",2e4,e),this.ma=e&&e.xmlHttpFactory||void 0,this.Ua=e&&e.Rb||void 0,this.Aa=e&&e.useFetchStreams||!1,this.O=void 0,this.L=e&&e.supportsCrossDomainXhr||!1,this.M="",this.h=new Je(e&&e.concurrentRequestLimit),this.Ba=new It,this.S=e&&e.fastHandshake||!1,this.R=e&&e.encodeInitMessageHeaders||!1,this.S&&this.R&&(this.R=!1),this.Ra=e&&e.Pb||!1,e&&e.ua&&this.j.ua(),e&&e.forceLongPolling&&(this.X=!1),this.aa=!this.S&&this.X&&e&&e.detectBufferingProxy||!1,this.ia=void 0,e&&e.longPollingTimeout&&0<e.longPollingTimeout&&(this.ia=e.longPollingTimeout),this.ta=void 0,this.T=0,this.P=!1,this.ja=this.B=null}function Vt(e){if(Bt(e),3==e.I){var t=e.V++,r=y(e.J);if(b(r,"SID",e.M),b(r,"RID",t),b(r,"TYPE","terminate"),Kt(e,r),(t=new g(e,e.j,t)).M=2,t.A=ot(y(r)),r=!1,N.navigator&&N.navigator.sendBeacon)try{r=N.navigator.sendBeacon(t.A.toString(),"")}catch(e){}!r&&N.Image&&((new Image).src=t.A,r=!0),r||(t.g=tr(t.j,null),t.g.ea(t.A)),t.F=Date.now(),He(t)}Zt(e)}function qt(e){e.g&&($t(e),e.g.cancel(),e.g=null)}function Bt(e){qt(e),e.v&&(N.clearTimeout(e.v),e.v=null),Yt(e),e.h.cancel(),e.m&&("number"==typeof e.m&&N.clearTimeout(e.m),e.m=null)}function jt(e){var t;Xe(e.h)||e.m||(e.m=!0,t=e.Ea,r||$(),n||(r(),n=!0),G.add(t,e),e.D=0)}function zt(e,t){var r=t?t.l:e.V++,n=y(e.J);b(n,"SID",e.M),b(n,"RID",r),b(n,"AID",e.K),Kt(e,n),e.u&&e.o&&Nt(n,e.u,e.o),r=new g(e,e.j,r,e.D+1),null===e.u&&(r.J=e.o),t&&(e.i=t.G.concat(e.i)),t=Wt(e,r,1e3),r.H=Math.round(.5*e.va)+Math.round(.5*e.va*Math.random()),tt(e.h,r),ze(r,n,t)}function Kt(e,r){e.H&&ee(e.H,function(e,t){b(r,t,e)}),e.l&&ee({},function(e,t){b(r,t,e)})}function Wt(e,t,i){i=Math.min(e.i.length,i);var s=e.l?v(e.l.Ka,e.l,e):null;e:{let r=e.i,n=-1;for(;;){var a=["count="+i];-1==n?0<i?(n=r[0].g,a.push("ofs="+n)):n=0:a.push("ofs="+n);let e=!0;for(let t=0;t<i;t++){var o=r[t].g,l=r[t].map;if((o-=n)<0)n=Math.max(0,r[t].g-100),e=!1;else try{o="req"+o+"_"||"";try{var h,c,u=l instanceof Map?l:Object.entries(l);for([h,c]of u){let e=c;d(c)&&(e=Ie(c)),a.push(o+h+"="+encodeURIComponent(e))}}catch(e){throw a.push(o+"type="+encodeURIComponent("_badmap")),e}}catch(e){s&&s(l)}}if(e){u=a.join("&");break e}}u=void 0}return e=e.i.splice(0,i),t.G=e,u}function Ht(e){var t;e.g||e.v||(e.Y=1,t=e.Da,r||$(),n||(r(),n=!0),G.add(t,e),e.A=0)}function Gt(e){return!(e.g||e.v||3<=e.A)&&(e.Y++,e.v=_(v(e.Da,e),Xt(e,e.A)),e.A++,1)}function $t(e){null!=e.B&&(N.clearTimeout(e.B),e.B=null)}function Qt(e){e.g=new g(e,e.j,"rpc",e.Y),null===e.u&&(e.g.J=e.o),e.g.P=0;var t=y(e.na),r=(b(t,"RID","rpc"),b(t,"SID",e.M),b(t,"AID",e.K),b(t,"CI",e.F?"0":"1"),!e.F&&e.ia&&b(t,"TO",e.ia),b(t,"TYPE","xmlhttp"),Kt(e,t),e.u&&e.o&&Nt(t,e.u,e.o),e.O&&(e.g.H=e.O),e.g);e=e.ba,r.M=1,r.A=ot(y(t)),r.u=null,r.R=!0,Ke(r,e)}function Yt(e){null!=e.C&&(N.clearTimeout(e.C),e.C=null)}function Jt(e,t){var r,n,i,s=null;if(e.g==t){Yt(e),$t(e),e.g=null;var a=2}else{if(!et(e.h,t))return;s=t.G,rt(e.h,t),a=1}if(0!=e.I)if(t.o)(1==a?(s=t.u?t.u.length:0,t=Date.now()-t.F,r=e.D,h(a=Pe(),new Me(a,s)),jt):Ht)(e);else if(3==(r=t.m)||0==r&&0<t.X||(1!=a||(i=t,Ze((n=e).h)>=n.h.j-(n.m?1:0))||(n.m?(n.i=i.G.concat(n.i),0):1==n.I||2==n.I||n.D>=(n.Sa?0:n.Ta)||(n.m=_(v(n.Ea,n,i),Xt(n,n.D)),n.D++,0)))&&(2!=a||!Gt(e)))switch(s&&0<s.length&&(t=e.h,t.i=t.i.concat(s)),r){case 1:S(e,5);break;case 4:S(e,10);break;case 3:S(e,6);break;default:S(e,2)}}function Xt(e,t){let r=e.Qa+Math.floor(Math.random()*e.Za);return e.isActive()||(r*=2),r*t}function S(e,t){var r,n,i;e.j.info("Error code "+t),2==t?(r=v(e.bb,e),n=!(i=e.Ua),i=new m(i||"//www.google.com/images/cleardot.gif"),N.location&&"http"==N.location.protocol||w(i,"https"),ot(i),(n?(t,r)=>{var n=new p;if(N.Image){let e=new Image;e.onload=B(E,n,"TestLoadImage: loaded",!0,r,e),e.onerror=B(E,n,"TestLoadImage: error",!1,r,e),e.onabort=B(E,n,"TestLoadImage: abort",!1,r,e),e.ontimeout=B(E,n,"TestLoadImage: timeout",!1,r,e),N.setTimeout(function(){e.ontimeout&&e.ontimeout()},1e4),e.src=t}else r(!1)}:(e,t)=>{let r=new p,n=new AbortController,i=setTimeout(()=>{n.abort(),E(r,0,!1,t)},1e4);fetch(e,{signal:n.signal}).then(e=>{clearTimeout(i),e.ok?E(r,0,!0,t):E(r,0,!1,t)}).catch(()=>{clearTimeout(i),E(r,0,!1,t)})})(i.toString(),r)):P(2),e.I=0,e.l&&e.l.pa(t),Zt(e),Bt(e)}function Zt(e){var t;e.I=0,e.ja=[],e.l&&(0==(t=nt(e.h)).length&&0==e.i.length||(K(e.ja,t),K(e.ja,e.i),e.h.i.length=0,z(e.i),e.i.length=0),e.l.oa())}function er(e,t,r){var n,i,s=r instanceof m?y(r):new m(r);return""!=s.g?(t&&(s.g=t+"."+s.g),st(s,s.u)):(s=(n=N.location).protocol,t=t?t+"."+n.hostname:n.hostname,n=+n.port,i=new m(null),s&&w(i,s),t&&(i.g=t),n&&st(i,n),r&&(i.h=r),s=i),r=e.G,t=e.wa,r&&t&&b(s,r,t),b(s,"VER",e.ka),Kt(e,s),s}function tr(e,t,r){if(t&&!e.L)throw Error("Can't create secondary domain capable XhrIo object.");return(t=e.Aa&&!e.ma?new C(new Tt({ab:r})):new C(e.ma)).Fa(e.L),t}function rr(){}function nr(){}function k(e,t){a.call(this),this.g=new Ut(t),this.l=e,this.h=t&&t.messageUrlParams||null,e=t&&t.messageHeaders||null,t&&t.clientProtocolHeaderRequired&&(e?e["X-Client-Protocol"]="webchannel":e={"X-Client-Protocol":"webchannel"}),this.g.o=e,e=t&&t.initMessageHeaders||null,t&&t.messageContentType&&(e?e["X-WebChannel-Content-Type"]=t.messageContentType:e={"X-WebChannel-Content-Type":t.messageContentType}),t&&t.sa&&(e?e["X-WebChannel-Client-Profile"]=t.sa:e={"X-WebChannel-Client-Profile":t.sa}),this.g.U=e,(e=t&&t.Qb)&&!R(e)&&(this.g.u=e),this.A=t&&t.supportsCrossDomainXhr||!1,this.v=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!R(t)&&(this.g.G=t,null!==(e=this.h))&&t in e&&t in(e=this.h)&&delete e[t],this.j=new A(this)}function ir(e){Ae.call(this),e.__headers__&&(this.headers=e.__headers__,this.statusCode=e.__status__,delete e.__headers__,delete e.__status__);var t=e.__sm__;if(t){e:{for(var r in t){e=r;break e}e=void 0}(this.i=e)&&(e=this.i,t=null!==t&&e in t?t[e]:void 0),this.data=t}else this.data=e}function sr(){Ne.call(this),this.status=1}function A(e){this.g=e}(e=C.prototype).Fa=function(e){this.H=e},e.ea=function(e,t,r,n){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.D+"; newUri="+e);t=t?t.toUpperCase():"GET",this.D=e,this.l="",this.o=0,this.A=!1,this.h=!0,this.g=(this.L||qe).g(),this.g.onreadystatechange=j(v(this.Ca,this));try{this.B=!0,this.g.open(t,String(e),!0),this.B=!1}catch(e){return void Dt(this,e)}if(e=r||"",r=new Map(this.headers),n)if(Object.getPrototypeOf(n)===Object.prototype)for(var i in n)r.set(i,n[i]);else{if("function"!=typeof n.keys||"function"!=typeof n.get)throw Error("Unknown input type for opt_headers: "+String(n));for(var s of n.keys())r.set(s,n.get(s))}n=Array.from(r.keys()).find(e=>"content-type"==e.toLowerCase()),i=N.FormData&&e instanceof N.FormData,0<=Array.prototype.indexOf.call(Pt,t,void 0)&&!n&&!i&&r.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8");for(var[a,o]of r)this.g.setRequestHeader(a,o);this.F&&(this.g.responseType=this.F),"withCredentials"in this.g&&this.g.withCredentials!==this.H&&(this.g.withCredentials=this.H);try{this.m&&(clearTimeout(this.m),this.m=null),this.v=!0,this.g.send(e),this.v=!1}catch(e){Dt(this,e)}},e.abort=function(e){this.g&&this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1,this.o=e||7,h(this,"complete"),h(this,"abort"),Mt(this))},e.N=function(){this.g&&(this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1),Mt(this,!0)),C.Z.N.call(this)},e.Ca=function(){this.u||(this.B||this.v||this.j?Ot(this):this.Xa())},e.Xa=function(){Ot(this)},e.isActive=function(){return!!this.g},e.ca=function(){try{return 2<M(this)?this.g.status:-1}catch(e){return-1}},e.la=function(){try{return this.g?this.g.responseText:""}catch(e){return""}},e.La=function(e){var t;if(this.g)return t=this.g.responseText,e&&0==t.indexOf(e)&&(t=t.substring(e.length)),Te(t)},e.ya=function(){return this.o},e.Ha=function(){return"string"==typeof this.l?this.l:String(this.l)},(e=Ut.prototype).ka=8,e.I=1,e.connect=function(e,t,r,n){P(0),this.W=e,this.H=t||{},r&&void 0!==n&&(this.H.OSID=r,this.H.OAID=n),this.F=this.X,this.J=er(this,null,this.W),jt(this)},e.Ea=function(t){if(this.m)if(this.m=null,1==this.I){if(!t){this.V=Math.floor(1e5*Math.random()),t=this.V++;var r=new g(this,this.j,t);let e=this.o;if(this.U&&(e?ne(e=te(e),this.U):e=this.U),null!==this.u||this.R||(r.J=e,e=null),this.S)e:{for(var n=0,i=0;i<this.i.length;i++){var s=this.i[i];if("__data__"in s.map&&"string"==typeof(s=s.map.__data__)?s=s.length:s=void 0,void 0===s)break;if(4096<(n+=s)){n=i;break e}if(4096===n||i===this.i.length-1){n=i+1;break e}}n=1e3}else n=1e3;n=Wt(this,r,n),b(i=y(this.J),"RID",t),b(i,"CVER",22),this.G&&b(i,"X-HTTP-Session-Id",this.G),Kt(this,i),e&&(this.R?n="headers="+f(At(e))+"&"+n:this.u&&Nt(i,this.u,e)),tt(this.h,r),this.Ra&&b(i,"TYPE","init"),this.S?(b(i,"$req",n),b(i,"SID","null"),r.U=!0,ze(r,i,null)):ze(r,i,n),this.I=2}}else 3==this.I&&(t?zt(this,t):0==this.i.length||Xe(this.h)||zt(this))},e.Da=function(){var e;this.v=null,Qt(this),this.aa&&!(this.P||null==this.g||this.T<=0)&&(e=4*this.T,this.j.info("BP detection timer enabled: "+e),this.B=_(v(this.Wa,this),e))},e.Wa=function(){this.B&&(this.B=null,this.j.info("BP detection timeout reached."),this.j.info("Buffering proxy detected and switch to long-polling!"),this.F=!1,this.P=!0,P(10),qt(this),Qt(this))},e.Va=function(){null!=this.C&&(this.C=null,qt(this),Gt(this),P(19))},e.bb=function(e){e?(this.j.info("Successfully pinged google.com"),P(2)):(this.j.info("Failed to ping google.com"),P(1))},e.isActive=function(){return!!this.l&&this.l.isActive(this)},(e=rr.prototype).ra=function(){},e.qa=function(){},e.pa=function(){},e.oa=function(){},e.isActive=function(){return!0},e.Ka=function(){},nr.prototype.g=function(e,t){return new k(e,t)},t(k,a),k.prototype.m=function(){this.g.l=this.j,this.A&&(this.g.L=!0),this.g.connect(this.l,this.h||void 0)},k.prototype.close=function(){Vt(this.g)},k.prototype.o=function(e){var t,r=this.g;"string"==typeof e?((t={}).__data__=e,e=t):this.v&&((t={}).__data__=Ie(e),e=t),r.i.push(new Ye(r.Ya++,e)),3==r.I&&jt(r)},k.prototype.N=function(){this.g.l=null,delete this.j,Vt(this.g),delete this.g,k.Z.N.call(this)},t(ir,Ae),t(sr,Ne),t(A,rr),A.prototype.ra=function(){h(this.g,"a")},A.prototype.qa=function(e){h(this.g,new ir(e))},A.prototype.pa=function(e){h(this.g,new sr)},A.prototype.oa=function(){h(this.g,"b")},nr.prototype.createWebChannel=nr.prototype.g,k.prototype.send=k.prototype.o,k.prototype.open=k.prototype.m,Tm=function(){return new nr},Im=Pe,bm=u,wm={jb:0,mb:1,nb:2,Hb:3,Mb:4,Jb:5,Kb:6,Ib:7,Gb:8,Lb:9,PROXY:10,NOPROXY:11,Eb:12,Ab:13,Bb:14,zb:15,Cb:16,Db:17,fb:18,eb:19,gb:20},Le.NO_ERROR=0,Le.TIMEOUT=8,Le.HTTP_ERROR=6,ym=Le,Fe.COMPLETE="complete",_m=Fe,(Se.EventType=ke).OPEN="a",ke.CLOSE="b",ke.ERROR="c",ke.MESSAGE="d",a.prototype.listen=a.prototype.J,vm=Se,C.prototype.listenOnce=C.prototype.K,C.prototype.getLastError=C.prototype.Ha,C.prototype.getLastErrorCode=C.prototype.ya,C.prototype.getStatus=C.prototype.ca,C.prototype.getResponseJson=C.prototype.La,C.prototype.getResponseText=C.prototype.la,C.prototype.send=C.prototype.ea,C.prototype.setWithCredentials=C.prototype.Fa,mm=C}).apply(void 0!==Sm?Sm:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});class km{constructor(e){this.uid=e}isAuthenticated(){return null!=this.uid}toKey(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"}isEqual(e){return e.uid===this.uid}}km.UNAUTHENTICATED=new km(null),km.GOOGLE_CREDENTIALS=new km("google-credentials-uid"),km.FIRST_PARTY=new km("first-party-uid"),km.MOCK_USER=new km("mock-user");let Am="12.12.1";let Nm=new Xe("@firebase/firestore");function Rm(){return Nm.logLevel}function E(e,...t){var r;Nm.logLevel<=p.DEBUG&&(r=t.map(xm),Nm.debug(`Firestore (${Am}): `+e,...r))}function Pm(e,...t){var r;Nm.logLevel<=p.ERROR&&(r=t.map(xm),Nm.error(`Firestore (${Am}): `+e,...r))}function Dm(e,...t){var r;Nm.logLevel<=p.WARN&&(r=t.map(xm),Nm.warn(`Firestore (${Am}): `+e,...r))}function xm(t){if("string"==typeof t)return t;try{return JSON.stringify(t)}catch(e){return t}}function C(e,t,r){let n="Unexpected state";"string"==typeof t?n=t:r=t,Om(e,n,r)}function Om(e,t,r){let n=`FIRESTORE (${Am}) INTERNAL ASSERTION FAILED: ${t} (ID: ${e.toString(16)})`;if(void 0!==r)try{n+=" CONTEXT: "+JSON.stringify(r)}catch(e){n+=" CONTEXT: "+r}throw Pm(n),new Error(n)}function S(e,t,r,n){let i="Unexpected state";"string"==typeof r?i=r:n=r,e||Om(t,i,n)}let k={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class A extends fe{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: `+this.message}}class Mm{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class Lm{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization","Bearer "+e)}}class Fm{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(km.UNAUTHENTICATED))}shutdown(){}}class Um{constructor(e){this.token=e,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(e,t){this.changeListener=t,e.enqueueRetryable(()=>t(this.token.user))}shutdown(){this.changeListener=null}}class Vm{constructor(e){this.t=e,this.currentUser=km.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(t,r){S(void 0===this.o,42304);let n=this.i,i=e=>this.i!==n?(n=this.i,r(e)):Promise.resolve(),s=new Mm,a=(this.o=()=>{this.i++,this.currentUser=this.u(),s.resolve(),s=new Mm,t.enqueueRetryable(()=>i(this.currentUser))},()=>{let e=s;t.enqueueRetryable(async()=>{await e.promise,await i(this.currentUser)})}),o=e=>{E("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.o&&(this.auth.addAuthTokenListener(this.o),a())};this.t.onInit(e=>o(e)),setTimeout(()=>{var e;this.auth||((e=this.t.getImmediate({optional:!0}))?o(e):(E("FirebaseAuthCredentialsProvider","Auth not yet detected"),s.resolve(),s=new Mm))},0),a()}getToken(){let t=this.i,e=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(e).then(e=>this.i!==t?(E("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):e?(S("string"==typeof e.accessToken,31837,{l:e}),new Lm(e.accessToken,this.currentUser)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.o&&this.auth.removeAuthTokenListener(this.o),this.o=void 0}u(){var e=this.auth&&this.auth.getUid();return S(null===e||"string"==typeof e,2055,{h:e}),new km(e)}}class qm{constructor(e,t,r){this.P=e,this.T=t,this.I=r,this.type="FirstParty",this.user=km.FIRST_PARTY,this.R=new Map}A(){return this.I?this.I():null}get headers(){this.R.set("X-Goog-AuthUser",this.P);var e=this.A();return e&&this.R.set("Authorization",e),this.T&&this.R.set("X-Goog-Iam-Authorization-Token",this.T),this.R}}class Bm{constructor(e,t,r){this.P=e,this.T=t,this.I=r}getToken(){return Promise.resolve(new qm(this.P,this.T,this.I))}start(e,t){e.enqueueRetryable(()=>t(km.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class jm{constructor(e){this.value=e,this.type="AppCheck",this.headers=new Map,e&&0<e.length&&this.headers.set("x-firebase-appcheck",this.value)}}class zm{constructor(e,t){this.V=t,this.forceRefresh=!1,this.appCheck=null,this.m=null,this.p=null,h(e)&&e.settings.appCheckToken&&(this.p=e.settings.appCheckToken)}start(t,r){S(void 0===this.o,3512);let n=e=>{null!=e.error&&E("FirebaseAppCheckTokenProvider","Error getting App Check token; using placeholder token instead. Error: "+e.error.message);var t=e.token!==this.m;return this.m=e.token,E("FirebaseAppCheckTokenProvider",`Received ${t?"new":"existing"} token.`),t?r(e.token):Promise.resolve()},i=(this.o=e=>{t.enqueueRetryable(()=>n(e))},e=>{E("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.o&&this.appCheck.addTokenListener(this.o)});this.V.onInit(e=>i(e)),setTimeout(()=>{var e;this.appCheck||((e=this.V.getImmediate({optional:!0}))?i(e):E("FirebaseAppCheckTokenProvider","AppCheck not yet detected"))},0)}getToken(){var e;return this.p?Promise.resolve(new jm(this.p)):(e=this.forceRefresh,this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>e?(S("string"==typeof e.token,44558,{tokenResult:e}),this.m=e.token,new jm(e.token)):null):Promise.resolve(null))}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.o&&this.appCheck.removeTokenListener(this.o),this.o=void 0}}class Km{static newId(){var t=62*Math.floor(256/62);let r="";for(;r.length<20;){var n=(t=>{var r="undefined"!=typeof self&&(self.crypto||self.msCrypto),n=new Uint8Array(t);if(r&&"function"==typeof r.getRandomValues)r.getRandomValues(n);else for(let e=0;e<t;e++)n[e]=Math.floor(256*Math.random());return n})(40);for(let e=0;e<n.length;++e)r.length<20&&n[e]<t&&(r+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(n[e]%62))}return r}}function N(e,t){return e<t?-1:t<e?1:0}function Wm(r,n){let e=Math.min(r.length,n.length);for(let i=0;i<e;i++){let e=r.charAt(i),t=n.charAt(i);if(e!==t)return $m(e)===$m(t)?N(e,t):$m(e)?1:-1}return N(r.length,n.length)}let Hm=55296,Gm=57343;function $m(e){var t=e.charCodeAt(0);return t>=Hm&&t<=Gm}function Qm(e,r,n){return e.length===r.length&&e.every((e,t)=>n(e,r[t]))}function Ym(e){return e+"\0"}let Jm="__name__";class Xm{constructor(e,t,r){void 0===t?t=0:t>e.length&&C(637,{offset:t,range:e.length}),void 0===r?r=e.length-t:r>e.length-t&&C(1746,{length:r,range:e.length-t}),this.segments=e,this.offset=t,this.len=r}get length(){return this.len}isEqual(e){return 0===Xm.comparator(this,e)}child(e){let t=this.segments.slice(this.offset,this.limit());return e instanceof Xm?e.forEach(e=>{t.push(e)}):t.push(e),this.construct(t)}limit(){return this.offset+this.length}popFirst(e){return this.construct(this.segments,this.offset+(e=void 0===e?1:e),this.length-e)}popLast(){return this.construct(this.segments,this.offset,this.length-1)}firstSegment(){return this.segments[this.offset]}lastSegment(){return this.get(this.length-1)}get(e){return this.segments[this.offset+e]}isEmpty(){return 0===this.length}isPrefixOf(e){if(e.length<this.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}isImmediateParentOf(e){if(this.length+1!==e.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}forEach(e){for(let t=this.offset,r=this.limit();t<r;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(t,r){let e=Math.min(t.length,r.length);for(let n=0;n<e;n++){let e=Xm.compareSegments(t.get(n),r.get(n));if(0!==e)return e}return N(t.length,r.length)}static compareSegments(e,t){var r=Xm.isNumericId(e),n=Xm.isNumericId(t);return r&&!n?-1:!r&&n?1:r&&n?Xm.extractNumericId(e).compare(Xm.extractNumericId(t)):Wm(e,t)}static isNumericId(e){return e.startsWith("__id")&&e.endsWith("__")}static extractNumericId(e){return fm.fromString(e.substring(4,e.length-2))}}class R extends Xm{construct(e,t,r){return new R(e,t,r)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}toUriEncodedString(){return this.toArray().map(encodeURIComponent).join("/")}static fromString(...e){var t,r=[];for(t of e){if(0<=t.indexOf("//"))throw new A(k.INVALID_ARGUMENT,`Invalid segment (${t}). Paths must not contain // in them.`);r.push(...t.split("/").filter(e=>0<e.length))}return new R(r)}static emptyPath(){return new R([])}}let Zm=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class ev extends Xm{construct(e,t,r){return new ev(e,t,r)}static isValidIdentifier(e){return Zm.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),e=ev.isValidIdentifier(e)?e:"`"+e+"`")).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&this.get(0)===Jm}static keyField(){return new ev([Jm])}static fromServerFormat(t){let e=[],r="",n=0;var i=()=>{if(0===r.length)throw new A(k.INVALID_ARGUMENT,`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);e.push(r),r=""};let s=!1;for(;n<t.length;){let e=t[n];if("\\"===e){if(n+1===t.length)throw new A(k.INVALID_ARGUMENT,"Path has trailing escape character: "+t);let e=t[n+1];if("\\"!==e&&"."!==e&&"`"!==e)throw new A(k.INVALID_ARGUMENT,"Path has invalid escape sequence: "+t);r+=e,n+=2}else"`"===e?s=!s:"."!==e||s?r+=e:i(),n++}if(i(),s)throw new A(k.INVALID_ARGUMENT,"Unterminated ` in path: "+t);return new ev(e)}static emptyPath(){return new ev([])}}class P{constructor(e){this.path=e}static fromPath(e){return new P(R.fromString(e))}static fromName(e){return new P(R.fromString(e).popFirst(5))}static empty(){return new P(R.emptyPath())}get collectionGroup(){return this.path.popLast().lastSegment()}hasCollectionId(e){return 2<=this.path.length&&this.path.get(this.path.length-2)===e}getCollectionGroup(){return this.path.get(this.path.length-2)}getCollectionPath(){return this.path.popLast()}isEqual(e){return null!==e&&0===R.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return R.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new P(new R(e.slice()))}}function tv(e,t,r){if(!r)throw new A(k.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function rv(e,t,r,n){if(!0===t&&!0===n)throw new A(k.INVALID_ARGUMENT,e+` and ${r} cannot be used together.`)}function nv(e){if(!P.isDocumentKey(e))throw new A(k.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function iv(e){if(P.isDocumentKey(e))throw new A(k.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function sv(e){return"object"==typeof e&&null!==e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}function av(e){var t,r;return void 0===e?"undefined":null===e?"null":"string"==typeof e?(20<e.length&&(e=e.substring(0,20)+"..."),JSON.stringify(e)):"number"==typeof e||"boolean"==typeof e?""+e:"object"==typeof e?e instanceof Array?"an array":(t=(r=e).constructor?r.constructor.name:null)?`a custom ${t} object`:"an object":"function"==typeof e?"a function":C(12329,{type:typeof e})}function D(e,t){if((e="_delegate"in e?e._delegate:e)instanceof t)return e;if(t.name===e.constructor.name)throw new A(k.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");var r=av(e);throw new A(k.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: `+r)}function ov(e,t){if(t<=0)throw new A(k.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}function lv(e,t){var r={typeString:e};return t&&(r.value=t),r}function hv(e,t){if(!sv(e))throw new A(k.INVALID_ARGUMENT,"JSON must be an object");let r;for(var n in t)if(t[n]){var i=t[n].typeString,s="value"in t[n]?{value:t[n].value}:void 0;if(!(n in e)){r=`JSON missing required field: '${n}'`;break}var a=e[n];if(i&&typeof a!==i){r=`JSON field '${n}' must be a ${i}.`;break}if(void 0!==s&&a!==s.value){r=`Expected '${n}' field to equal '${s.value}'`;break}}if(r)throw new A(k.INVALID_ARGUMENT,r);return 1}let cv=-62135596800;class x{static now(){return x.fromMillis(Date.now())}static fromDate(e){return x.fromMillis(e.getTime())}static fromMillis(e){var t=Math.floor(e/1e3),r=Math.floor(1e6*(e-1e3*t));return new x(t,r)}constructor(e,t){if(this.seconds=e,(this.nanoseconds=t)<0)throw new A(k.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(1e9<=t)throw new A(k.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<cv)throw new A(k.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(253402300800<=e)throw new A(k.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?N(this.nanoseconds,e.nanoseconds):N(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{type:x._jsonSchemaVersion,seconds:this.seconds,nanoseconds:this.nanoseconds}}static fromJSON(e){if(hv(e,x._jsonSchema))return new x(e.seconds,e.nanoseconds)}valueOf(){var e=this.seconds-cv;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}x._jsonSchemaVersion="firestore/timestamp/1.0",x._jsonSchema={type:lv("string",x._jsonSchemaVersion),seconds:lv("number"),nanoseconds:lv("number")};class O{static fromTimestamp(e){return new O(e)}static min(){return new O(new x(0,0))}static max(){return new O(new x(253402300799,999999999))}constructor(e){this.timestamp=e}compareTo(e){return this.timestamp._compareTo(e.timestamp)}isEqual(e){return this.timestamp.isEqual(e.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}}let uv=-1;class dv{constructor(e,t,r,n){this.indexId=e,this.collectionGroup=t,this.fields=r,this.indexState=n}}function pv(e){return e.fields.find(e=>2===e.kind)}function fv(e){return e.fields.filter(e=>2!==e.kind)}dv.UNKNOWN_ID=-1;class gv{constructor(e,t){this.fieldPath=e,this.kind=t}}class mv{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new mv(0,yv.min())}}function vv(e,t){var r=e.toTimestamp().seconds,n=e.toTimestamp().nanoseconds+1,r=O.fromTimestamp(1e9===n?new x(r+1,0):new x(r,n));return new yv(r,P.empty(),t)}function _v(e){return new yv(e.readTime,e.key,uv)}class yv{constructor(e,t,r){this.readTime=e,this.documentKey=t,this.largestBatchId=r}static min(){return new yv(O.min(),P.empty(),uv)}static max(){return new yv(O.max(),P.empty(),uv)}}function wv(e,t){var r=e.readTime.compareTo(t.readTime);return 0!==r||0!==(r=P.comparator(e.documentKey,t.documentKey))?r:N(e.largestBatchId,t.largestBatchId)}let bv="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class Iv{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}async function Tv(e){if(e.code!==k.FAILED_PRECONDITION||e.message!==bv)throw e;E("LocalStore","Unexpectedly lost primary lease")}class M{constructor(e){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,e(e=>{this.isDone=!0,this.result=e,this.nextCallback&&this.nextCallback(e)},e=>{this.isDone=!0,this.error=e,this.catchCallback&&this.catchCallback(e)})}catch(e){return this.next(void 0,e)}next(n,i){return this.callbackAttached&&C(59440),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(i,this.error):this.wrapSuccess(n,this.result):new M((t,r)=>{this.nextCallback=e=>{this.wrapSuccess(n,e).next(t,r)},this.catchCallback=e=>{this.wrapFailure(i,e).next(t,r)}})}toPromise(){return new Promise((e,t)=>{this.next(e,t)})}wrapUserFunction(e){try{var t=e();return t instanceof M?t:M.resolve(t)}catch(e){return M.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):M.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):M.reject(t)}static resolve(r){return new M((e,t)=>{e(r)})}static reject(r){return new M((e,t)=>{t(r)})}static waitFor(e){return new M((t,r)=>{let n=0,i=0,s=!1;e.forEach(e=>{++n,e.next(()=>{++i,s&&i===n&&t()},e=>r(e))}),s=!0,i===n&&t()})}static or(e){let t=M.resolve(!1);for(let r of e)t=t.next(e=>e?M.resolve(e):r());return t}static forEach(e,r){let n=[];return e.forEach((e,t)=>{n.push(r.call(this,e,t))}),this.waitFor(n)}static mapArray(o,l){return new M((r,n)=>{let i=o.length,s=new Array(i),a=0;for(let e=0;e<i;e++){let t=e;l(o[t]).next(e=>{s[t]=e,++a===i&&r(s)},e=>n(e))}})}static doWhile(n,i){return new M((e,t)=>{let r=()=>{!0===n()?i().next(()=>{r()},t):e()};r()})}}let Ev="SimpleDb";class Cv{static open(e,t,r,n){try{return new Cv(t,e.transaction(n,r))}catch(e){throw new Nv(t,e)}}constructor(r,e){this.action=r,this.transaction=e,this.aborted=!1,this.S=new Mm,this.transaction.oncomplete=()=>{this.S.resolve()},this.transaction.onabort=()=>{e.error?this.S.reject(new Nv(r,e.error)):this.S.resolve()},this.transaction.onerror=e=>{var t=Ov(e.target.error);this.S.reject(new Nv(r,t))}}get D(){return this.S.promise}abort(e){e&&this.S.reject(e),this.aborted||(E(Ev,"Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}C(){var e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}store(e){var t=this.transaction.objectStore(e);return new Pv(t)}}class Sv{static delete(e){return E(Ev,"Removing database:",e),Dv(H().indexedDB.deleteDatabase(e)).toPromise()}static v(){var e,t,r;return!(!ue()||!Sv.F()&&(e=te(),t=0<(t=Sv.M(e))&&t<10,r=0<(r=kv(e))&&r<4.5,0<e.indexOf("MSIE ")||0<e.indexOf("Trident/")||0<e.indexOf("Edge/")||t||r))}static F(){return"undefined"!=typeof process&&"YES"===process.__PRIVATE_env?.__PRIVATE_USE_MOCK_PERSISTENCE}static O(e,t){return e.store(t)}static M(e){var t=e.match(/i(?:phone|pad|pod) os ([\d_]+)/i),t=t?t[1].split("_").slice(0,2).join("."):"-1";return Number(t)}constructor(e,t,r){this.name=e,this.version=t,this.N=r,this.B=null,12.2===Sv.M(te())&&Pm("Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.")}async L(s){return this.db||(E(Ev,"Opening database:",this.name),this.db=await new Promise((r,n)=>{let i=indexedDB.open(this.name,this.version);i.onsuccess=e=>{var t=e.target.result;r(t)},i.onblocked=()=>{n(new Nv(s,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},i.onerror=e=>{var t=e.target.error;"VersionError"===t.name?n(new A(k.FAILED_PRECONDITION,"A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")):"InvalidStateError"===t.name?n(new A(k.FAILED_PRECONDITION,"Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: "+t)):n(new Nv(s,t))},i.onupgradeneeded=e=>{E(Ev,'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);var t=e.target.result;this.N.k(t,i.transaction,e.oldVersion,this.version).next(()=>{E(Ev,"Database upgrade to version "+this.version+" complete")})}})),this.q&&(this.db.onversionchange=e=>this.q(e)),this.db}K(t){this.q=t,this.db&&(this.db.onversionchange=e=>t(e))}async runTransaction(r,e,n,i){var s="readonly"===e;let a=0;for(;;){++a;try{this.db=await this.L(r);let t=Cv.open(this.db,r,s?"readonly":"readwrite",n),e=i(t).next(e=>(t.C(),e)).catch(e=>(t.abort(e),M.reject(e))).toPromise();return e.catch(()=>{}),await t.D,e}catch(r){let e=r,t="FirebaseError"!==e.name&&a<3;if(E(Ev,"Transaction failed with error:",e.message,"Retrying:",t),this.close(),!t)return Promise.reject(e)}}}close(){this.db&&this.db.close(),this.db=void 0}}function kv(e){var t=e.match(/Android ([\d.]+)/i),t=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(t)}class Av{constructor(e){this.U=e,this.$=!1,this.W=null}get isDone(){return this.$}get G(){return this.W}set cursor(e){this.U=e}done(){this.$=!0}j(e){this.W=e}delete(){return Dv(this.U.delete())}}class Nv extends A{constructor(e,t){super(k.UNAVAILABLE,`IndexedDB transaction '${e}' failed: `+t),this.name="IndexedDbTransactionError"}}function Rv(e){return"IndexedDbTransactionError"===e.name}class Pv{constructor(e){this.store=e}put(e,t){let r;return Dv(r=void 0!==t?(E(Ev,"PUT",this.store.name,e,t),this.store.put(t,e)):(E(Ev,"PUT",this.store.name,"<auto-key>",e),this.store.put(e)))}add(e){return E(Ev,"ADD",this.store.name,e,e),Dv(this.store.add(e))}get(t){return Dv(this.store.get(t)).next(e=>(void 0===e&&(e=null),E(Ev,"GET",this.store.name,t,e),e))}delete(e){return E(Ev,"DELETE",this.store.name,e),Dv(this.store.delete(e))}count(){return E(Ev,"COUNT",this.store.name),Dv(this.store.count())}J(e,t){var n=this.options(e,t),r=n.index?this.store.index(n.index):this.store;if("function"==typeof r.getAll){let e=r.getAll(n.range);return new M((t,r)=>{e.onerror=e=>{r(e.target.error)},e.onsuccess=e=>{t(e.target.result)}})}{let e=this.cursor(n),r=[];return this.H(e,(e,t)=>{r.push(t)}).next(()=>r)}}Z(e,t){let n=this.store.getAll(e,null===t?void 0:t);return new M((t,r)=>{n.onerror=e=>{r(e.target.error)},n.onsuccess=e=>{t(e.target.result)}})}X(e,t){E(Ev,"DELETE ALL",this.store.name);var r=this.options(e,t),r=(r.Y=!1,this.cursor(r));return this.H(r,(e,t,r)=>r.delete())}ee(e,t){let r;t?r=e:(r={},t=e);var n=this.cursor(r);return this.H(n,t)}te(i){let e=this.cursor({});return new M((r,n)=>{e.onerror=e=>{var t=Ov(e.target.error);n(t)},e.onsuccess=e=>{let t=e.target.result;t?i(t.primaryKey,t.value).next(e=>{e?t.continue():r()}):r()}})}H(e,s){let a=[];return new M((i,t)=>{e.onerror=e=>{t(e.target.error)},e.onsuccess=e=>{var n=e.target.result;if(n){let t=new Av(n),r=s(n.primaryKey,n.value,t);if(r instanceof M){let e=r.catch(e=>(t.done(),M.reject(e)));a.push(e)}t.isDone?i():null===t.G?n.continue():n.continue(t.G)}else i()}}).next(()=>M.waitFor(a))}options(e,t){let r;return void 0!==e&&("string"==typeof e?r=e:t=e),{index:r,range:t}}cursor(e){let t="next";var r;return e.reverse&&(t="prev"),e.index?(r=this.store.index(e.index),e.Y?r.openKeyCursor(e.range,t):r.openCursor(e.range,t)):this.store.openCursor(e.range,t)}}function Dv(e){return new M((r,n)=>{e.onsuccess=e=>{var t=e.target.result;r(t)},e.onerror=e=>{var t=Ov(e.target.error);n(t)}})}let xv=!1;function Ov(e){let t=Sv.M(te());if(12.2<=t&&t<13){let t="An internal error was encountered in the Indexed Database server";if(0<=e.message.indexOf(t)){let e=new A("internal",`IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${t}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);return xv||(xv=!0,setTimeout(()=>{throw e},0)),e}}return e}let Mv="IndexBackfiller";class Lv{constructor(e,t){this.asyncQueue=e,this.ne=t,this.task=null}start(){this.re(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return null!==this.task}re(e){E(Mv,`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,async()=>{this.task=null;try{var e=await this.ne.ie();E(Mv,"Documents written: "+e)}catch(e){Rv(e)?E(Mv,"Ignoring IndexedDB error during index backfill: ",e):await Tv(e)}await this.re(6e4)})}}class Fv{constructor(e,t){this.localStore=e,this.persistence=t}async ie(t=50){return this.persistence.runTransaction("Backfill Indexes","readwrite-primary",e=>this.se(e,t))}se(e,t){let r=new Set,n=t,i=!0;return M.doWhile(()=>!0===i&&0<n,()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next(t=>{if(null!==t&&!r.has(t))return E(Mv,"Processing collection: "+t),this.oe(e,t,n).next(e=>{n-=e,r.add(t)});i=!1})).next(()=>t-n)}oe(n,i,e){return this.localStore.indexManager.getMinOffsetFromCollectionGroup(n,i).next(r=>this.localStore.localDocuments.getNextDocuments(n,i,r,e).next(e=>{let t=e.changes;return this.localStore.indexManager.updateIndexEntries(n,t).next(()=>this._e(r,e)).next(e=>(E(Mv,"Updating offset: "+e),this.localStore.indexManager.updateCollectionGroup(n,i,e))).next(()=>t.size)}))}_e(e,t){let n=e;return t.changes.forEach((e,t)=>{var r=_v(t);0<wv(r,n)&&(n=r)}),new yv(n.readTime,n.documentKey,Math.max(t.batchId,e.largestBatchId))}}class Uv{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.ae(e),this.ue=e=>t.writeSequenceNumber(e))}ae(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){var e=++this.previousValue;return this.ue&&this.ue(e),e}}let Vv=Uv.ce=-1;function qv(e){return null==e}function Bv(e){return 0===e&&1/e==-1/0}function jv(e){return"number"==typeof e&&Number.isInteger(e)&&!Bv(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}let zv="";function Kv(e){let t="";for(let r=0;r<e.length;r++)0<t.length&&(t=Wv(t)),t=((t,e)=>{let r=e,n=t.length;for(let i=0;i<n;i++){let e=t.charAt(i);switch(e){case"\0":r+="";break;case zv:r+="";break;default:r+=e}}return r})(e.get(r),t);return Wv(t)}function Wv(e){return e+zv+""}function Hv(r){let e=r.length;if(S(2<=e,64408,{path:r}),2===e)return S(r.charAt(0)===zv&&""===r.charAt(1),56145,{path:r}),R.emptyPath();var __PRIVATE_lastReasonableEscapeIndex=e-2,n=[];let i="";for(let a=0;a<e;){let t=r.indexOf(zv,a);switch((t<0||t>__PRIVATE_lastReasonableEscapeIndex)&&C(50515,{path:r}),r.charAt(t+1)){case"":var s=r.substring(a,t);let e;0===i.length?e=s:(i+=s,e=i,i=""),n.push(e);break;case"":i=i+r.substring(a,t)+"\0";break;case"":i+=r.substring(a,t+1);break;default:C(61167,{path:r})}a=t+2}return new R(n)}let Gv="remoteDocuments",$v="owner",Qv="owner",Yv="mutationQueues",Jv="mutations",Xv="batchId",Zv="userMutationsIndex",e_=["userId","batchId"];function t_(e,t){return[e,Kv(t)]}function r_(e,t,r){return[e,Kv(t),r]}let n_={},i_="documentMutations",s_="remoteDocumentsV14",a_=["prefixPath","collectionGroup","readTime","documentId"],o_="documentKeyIndex",l_=["prefixPath","collectionGroup","documentId"],h_="collectionGroupIndex",c_=["collectionGroup","readTime","prefixPath","documentId"],u_="remoteDocumentGlobal",d_="remoteDocumentGlobalKey",p_="targets",f_="queryTargetsIndex",g_=["canonicalId","targetId"],m_="targetDocuments",v_=["targetId","path"],__="documentTargetsIndex",y_=["path","targetId"],w_="targetGlobalKey",b_="targetGlobal",I_="collectionParents",T_=["collectionId","parent"],E_="clientMetadata",C_="bundles",S_="namedQueries",k_="indexConfiguration",A_="collectionGroupIndex",N_="indexState",R_=["indexId","uid"],P_="sequenceNumberIndex",D_=["uid","sequenceNumber"],x_="indexEntries",O_=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],M_="documentKeyIndex",L_=["indexId","uid","orderedDocumentKey"],F_="documentOverlays",U_=["userId","collectionPath","documentId"],V_="collectionPathOverlayIndex",q_=["userId","collectionPath","largestBatchId"],B_="collectionGroupOverlayIndex",j_=["userId","collectionGroup","largestBatchId"],z_="globals",K_=[Yv,Jv,i_,Gv,p_,$v,b_,m_,E_,u_,I_,C_,S_],W_=[...K_,F_],H_=[Yv,Jv,i_,s_,p_,$v,b_,m_,E_,u_,I_,C_,S_,F_],G_=H_,$_=[...G_,k_,N_,x_],Q_=$_,Y_=[...$_,z_],J_=Y_;class X_ extends Iv{constructor(e,t){super(),this.le=e,this.currentSequenceNumber=t}}function Z_(e,t){var r=e;return Sv.O(r.le,t)}function ey(e){let t=0;for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}function ty(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t(r,e[r])}function ry(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class ny{constructor(e,t){this.comparator=e,this.root=t||sy.EMPTY}insert(e,t){return new ny(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,sy.BLACK,null,null))}remove(e){return new ny(this.comparator,this.root.remove(e,this.comparator).copy(null,null,sy.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){var r=this.comparator(e,t.key);if(0===r)return t.value;r<0?t=t.left:0<r&&(t=t.right)}return null}indexOf(e){let t=0,r=this.root;for(;!r.isEmpty();){var n=this.comparator(e,r.key);if(0===n)return t+r.left.size;r=n<0?r.left:(t+=r.left.size+1,r.right)}return-1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(e){return this.root.inorderTraversal(e)}forEach(r){this.inorderTraversal((e,t)=>(r(e,t),!1))}toString(){let r=[];return this.inorderTraversal((e,t)=>(r.push(e+":"+t),!1)),`{${r.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new iy(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new iy(this.root,e,this.comparator,!1)}getReverseIterator(){return new iy(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new iy(this.root,e,this.comparator,!0)}}class iy{constructor(e,t,r,n){this.isReverse=n,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?r(e.key,t):1,t&&n&&(i*=-1),i<0)e=this.isReverse?e.left:e.right;else{if(0===i){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop();var t={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t}hasNext(){return 0<this.nodeStack.length}peek(){var e;return 0===this.nodeStack.length?null:{key:(e=this.nodeStack[this.nodeStack.length-1]).key,value:e.value}}}class sy{constructor(e,t,r,n,i){this.key=e,this.value=t,this.color=null!=r?r:sy.RED,this.left=null!=n?n:sy.EMPTY,this.right=null!=i?i:sy.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,r,n,i){return new sy(null!=e?e:this.key,null!=t?t:this.value,null!=r?r:this.color,null!=n?n:this.left,null!=i?i:this.right)}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,r){var n=this,i=r(e,n.key);return(n=i<0?n.copy(null,null,null,n.left.insert(e,t,r),null):0===i?n.copy(null,t,null,null,null):n.copy(null,null,null,null,n.right.insert(e,t,r))).fixUp()}removeMin(){if(this.left.isEmpty())return sy.EMPTY;let e=this;return(e=(e=e.left.isRed()||e.left.left.isRed()?e:e.moveRedLeft()).copy(null,null,null,e.left.removeMin(),null)).fixUp()}remove(e,t){let r,n=this;if(t(e,n.key)<0)n=(n=n.left.isEmpty()||n.left.isRed()||n.left.left.isRed()?n:n.moveRedLeft()).copy(null,null,null,n.left.remove(e,t),null);else{if(0===t(e,(n=(n=n.left.isRed()?n.rotateRight():n).right.isEmpty()||n.right.isRed()||n.right.left.isRed()?n:n.moveRedRight()).key)){if(n.right.isEmpty())return sy.EMPTY;r=n.right.min(),n=n.copy(r.key,r.value,null,null,n.right.removeMin())}n=n.copy(null,null,null,null,n.right.remove(e,t))}return n.fixUp()}isRed(){return this.color}fixUp(){let e=this;return e=(e=(e=e.right.isRed()&&!e.left.isRed()?e.rotateLeft():e).left.isRed()&&e.left.left.isRed()?e.rotateRight():e).left.isRed()&&e.right.isRed()?e.colorFlip():e}moveRedLeft(){let e=this.colorFlip();return e=e.right.left.isRed()?(e=(e=e.copy(null,null,null,null,e.right.rotateRight())).rotateLeft()).colorFlip():e}moveRedRight(){let e=this.colorFlip();return e=e.left.left.isRed()?(e=e.rotateRight()).colorFlip():e}rotateLeft(){var e=this.copy(null,null,sy.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){var e=this.copy(null,null,sy.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){var e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth(){var e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw C(43730,{key:this.key,value:this.value});if(this.right.isRed())throw C(14113,{key:this.key,value:this.value});var e=this.left.check();if(e!==this.right.check())throw C(27949);return e+(this.isRed()?0:1)}}sy.EMPTY=null,sy.RED=!0,sy.BLACK=!1,sy.EMPTY=new class{constructor(){this.size=0}get key(){throw C(57766)}get value(){throw C(16141)}get color(){throw C(16727)}get left(){throw C(29726)}get right(){throw C(36894)}copy(e,t,r,n,i){return this}insert(e,t,r){return new sy(e,t)}remove(e,t){return this}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}isRed(){return!1}checkMaxDepth(){return!0}check(){return 0}};class L{constructor(e){this.comparator=e,this.data=new ny(this.comparator)}has(e){return null!==this.data.get(e)}first(){return this.data.minKey()}last(){return this.data.maxKey()}get size(){return this.data.size}indexOf(e){return this.data.indexOf(e)}forEach(r){this.data.inorderTraversal((e,t)=>(r(e),!1))}forEachInRange(e,t){for(var r=this.data.getIteratorFrom(e[0]);r.hasNext();){var n=r.getNext();if(0<=this.comparator(n.key,e[1]))return;t(n.key)}}forEachWhile(e,t){for(var r=void 0!==t?this.data.getIteratorFrom(t):this.data.getIterator();r.hasNext();)if(!e(r.getNext().key))return}firstAfterOrEqual(e){var t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new ay(this.data.getIterator())}getIteratorFrom(e){return new ay(this.data.getIteratorFrom(e))}add(e){return this.copy(this.data.remove(e).insert(e,!0))}delete(e){return this.has(e)?this.copy(this.data.remove(e)):this}isEmpty(){return this.data.isEmpty()}unionWith(e){let t=this;return t.size<e.size&&(t=e,e=this),e.forEach(e=>{t=t.add(e)}),t}isEqual(e){if(!(e instanceof L))return!1;if(this.size!==e.size)return!1;for(var r=this.data.getIterator(),n=e.data.getIterator();r.hasNext();){let e=r.getNext().key,t=n.getNext().key;if(0!==this.comparator(e,t))return!1}return!0}toArray(){let t=[];return this.forEach(e=>{t.push(e)}),t}toString(){let t=[];return this.forEach(e=>t.push(e)),"SortedSet("+t.toString()+")"}copy(e){var t=new L(this.comparator);return t.data=e,t}}class ay{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function oy(e){return e.hasNext()?e.getNext():void 0}class ly{constructor(e){(this.fields=e).sort(ev.comparator)}static empty(){return new ly([])}unionWith(e){let t=new L(ev.comparator);for(let e of this.fields)t=t.add(e);for(var r of e)t=t.add(r);return new ly(t.toArray())}covers(e){for(var t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return Qm(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class hy extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class cy{constructor(e){this.binaryString=e}static fromBase64String(e){var t=(e=>{try{return atob(e)}catch(e){throw"undefined"!=typeof DOMException&&e instanceof DOMException?new hy("Invalid base64 string: "+e):e}})(e);return new cy(t)}static fromUint8Array(e){var t=(e=>{let t="";for(let r=0;r<e.length;++r)t+=String.fromCharCode(e[r]);return t})(e);return new cy(t)}[Symbol.iterator](){let e=0;return{next:()=>e<this.binaryString.length?{value:this.binaryString.charCodeAt(e++),done:!1}:{value:void 0,done:!0}}}toBase64(){return e=this.binaryString,btoa(e);var e}toUint8Array(){var e=this.binaryString,t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return N(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}cy.EMPTY_BYTE_STRING=new cy("");let uy=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function dy(t){if(S(!!t,39018),"string"!=typeof t)return{seconds:py(t.seconds),nanos:py(t.nanos)};{let e=0;var r=uy.exec(t),r=(S(!!r,46558,{timestamp:t}),r[1]&&(r=((r=r[1])+"000000000").substr(0,9),e=Number(r)),new Date(t));return{seconds:Math.floor(r.getTime()/1e3),nanos:e}}}function py(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function fy(e){return"string"==typeof e?cy.fromBase64String(e):cy.fromUint8Array(e)}let gy="server_timestamp",my="__type__",vy="__previous_value__",_y="__local_write_time__";function yy(e){return(e?.mapValue?.fields||{})[my]?.stringValue===gy}function wy(e){var t=e.mapValue.fields[vy];return yy(t)?wy(t):t}function by(e){var t=dy(e.mapValue.fields[_y].timestampValue);return new x(t.seconds,t.nanos)}class Iy{constructor(e,t,r,n,i,s,a,o,l,h,c){this.databaseId=e,this.appId=t,this.persistenceKey=r,this.host=n,this.ssl=i,this.forceLongPolling=s,this.autoDetectLongPolling=a,this.longPollingOptions=o,this.useFetchStreams=l,this.isUsingEmulator=h,this.apiKey=c}}let Ty="(default)";class Ey{constructor(e,t){this.projectId=e,this.database=t||Ty}static empty(){return new Ey("","")}get isDefaultDatabase(){return this.database===Ty}isEqual(e){return e instanceof Ey&&e.projectId===this.projectId&&e.database===this.database}}let Cy="__type__",Sy="__max__",ky={mapValue:{fields:{__type__:{stringValue:Sy}}}},Ay="__vector__",Ny="value",Ry={nullValue:"NULL_VALUE"};function Py(e){return"nullValue"in e?0:"booleanValue"in e?1:"integerValue"in e||"doubleValue"in e?2:"timestampValue"in e?3:"stringValue"in e?5:"bytesValue"in e?6:"referenceValue"in e?7:"geoPointValue"in e?8:"arrayValue"in e?9:"mapValue"in e?yy(e)?4:Hy(e)?9007199254740991:Ky(e)?10:11:C(28295,{value:e})}function Dy(t,r){if(t===r)return!0;var n,i,s,a,o,e=Py(t);if(e!==Py(r))return!1;switch(e){case 0:case 9007199254740991:return!0;case 1:return t.booleanValue===r.booleanValue;case 4:return by(t).isEqual(by(r));case 3:return s=r,"string"==typeof(i=t).timestampValue&&"string"==typeof s.timestampValue&&i.timestampValue.length===s.timestampValue.length?i.timestampValue===s.timestampValue:(a=dy(i.timestampValue),o=dy(s.timestampValue),a.seconds===o.seconds&&a.nanos===o.nanos);case 5:return t.stringValue===r.stringValue;case 6:return i=r,fy(t.bytesValue).isEqual(fy(i.bytesValue));case 7:return t.referenceValue===r.referenceValue;case 8:return s=r,py((n=t).geoPointValue.latitude)===py(s.geoPointValue.latitude)&&py(n.geoPointValue.longitude)===py(s.geoPointValue.longitude);case 2:return n=r,"integerValue"in(h=t)&&"integerValue"in n?py(h.integerValue)===py(n.integerValue):"doubleValue"in h&&"doubleValue"in n&&((a=py(h.doubleValue))===(o=py(n.doubleValue))?Bv(a)===Bv(o):isNaN(a)&&isNaN(o));case 9:return Qm(t.arrayValue.values||[],r.arrayValue.values||[],Dy);case 10:case 11:var l=t,h=r,c=l.mapValue.fields||{},u=h.mapValue.fields||{};if(ey(c)!==ey(u))return!1;for(let e in c)if(c.hasOwnProperty(e)&&(void 0===u[e]||!Dy(c[e],u[e])))return!1;return!0;default:return C(52216,{left:t})}}function xy(e,t){return void 0!==(e.values||[]).find(e=>Dy(e,t))}function Oy(e,n){if(e===n)return 0;var i,s,a,o,l,h,c,u,d=Py(e),t=Py(n);if(d!==t)return N(d,t);switch(d){case 0:case 9007199254740991:return 0;case 1:return N(e.booleanValue,n.booleanValue);case 2:return h=n,c=py((l=e).integerValue||l.doubleValue),u=py(h.integerValue||h.doubleValue),c<u?-1:u<c?1:c===u?0:isNaN(c)?isNaN(u)?0:-1:1;case 3:return My(e.timestampValue,n.timestampValue);case 4:return My(by(e),by(n));case 5:return Wm(e.stringValue,n.stringValue);case 6:return l=e.bytesValue,h=n.bytesValue,c=fy(l),u=fy(h),c.compareTo(u);case 7:var p=e.referenceValue,f=n.referenceValue,g=p.split("/"),m=f.split("/");for(let t=0;t<g.length&&t<m.length;t++){let e=N(g[t],m[t]);if(0!==e)return e}return N(g.length,m.length);case 8:return p=e.geoPointValue,f=n.geoPointValue,0!==(o=N(py(p.latitude),py(f.latitude)))?o:N(py(p.longitude),py(f.longitude));case 9:return Ly(e.arrayValue,n.arrayValue);case 10:return v=e.mapValue,i=n.mapValue,o=v.fields||{},s=i.fields||{},o=o[Ny]?.arrayValue,s=s[Ny]?.arrayValue,0!==(a=N(o?.values?.length||0,s?.values?.length||0))?a:Ly(o,s);case 11:var v=e.mapValue,_=n.mapValue;if(v===ky.mapValue&&_===ky.mapValue)return 0;if(v===ky.mapValue)return 1;if(_===ky.mapValue)return-1;var y=v.fields||{},w=Object.keys(y),b=_.fields||{},I=Object.keys(b);w.sort(),I.sort();for(let r=0;r<w.length&&r<I.length;++r){let e=Wm(w[r],I[r]);if(0!==e)return e;var T=Oy(y[w[r]],b[I[r]]);if(0!==T)return T}return N(w.length,I.length);default:throw C(23264,{he:d})}}function My(e,t){var r,n,i;return"string"==typeof e&&"string"==typeof t&&e.length===t.length?N(e,t):(r=dy(e),n=dy(t),0!==(i=N(r.seconds,n.seconds))?i:N(r.nanos,n.nanos))}function Ly(e,t){var r=e.values||[],n=t.values||[];for(let i=0;i<r.length&&i<n.length;++i){let e=Oy(r[i],n[i]);if(e)return e}return N(r.length,n.length)}function Fy(e){return function s(e){return"nullValue"in e?"null":"booleanValue"in e?""+e.booleanValue:"integerValue"in e?""+e.integerValue:"doubleValue"in e?""+e.doubleValue:"timestampValue"in e?(e=>{let t=dy(e);return`time(${t.seconds},${t.nanos})`})(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?(e=>fy(e).toBase64())(e.bytesValue):"referenceValue"in e?(e=>P.fromName(e).toString())(e.referenceValue):"geoPointValue"in e?(e=>`geo(${e.latitude},${e.longitude})`)(e.geoPointValue):"arrayValue"in e?(e=>{let t="[",r=!0;for(var n of e.values||[])r?r=!1:t+=",",t+=s(n);return t+"]"})(e.arrayValue):"mapValue"in e?(e=>{let t=Object.keys(e.fields||{}).sort(),r="{",n=!0;for(var i of t)n?n=!1:r+=",",r+=i+":"+s(e.fields[i]);return r+"}"})(e.mapValue):C(61005,{value:e})}(e)}function Uy(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/`+t.path.canonicalString()}}function Vy(e){return!!e&&"integerValue"in e}function qy(e){return!!e&&"arrayValue"in e}function By(e){return e&&"nullValue"in e}function jy(e){return e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function zy(e){return e&&"mapValue"in e}function Ky(e){return(e?.mapValue?.fields||{})[Cy]?.stringValue===Ay}function Wy(t){if(t.geoPointValue)return{geoPointValue:{...t.geoPointValue}};if(t.timestampValue&&"object"==typeof t.timestampValue)return{timestampValue:{...t.timestampValue}};if(t.mapValue){let r={mapValue:{fields:{}}};return ty(t.mapValue.fields,(e,t)=>r.mapValue.fields[e]=Wy(t)),r}if(t.arrayValue){var r={arrayValue:{values:[]}};for(let e=0;e<(t.arrayValue.values||[]).length;++e)r.arrayValue.values[e]=Wy(t.arrayValue.values[e]);return r}return{...t}}function Hy(e){return(((e.mapValue||{}).fields||{}).__type__||{}).stringValue===Sy}let Gy={mapValue:{fields:{[Cy]:{stringValue:Ay},[Ny]:{arrayValue:{}}}}};function $y(e,t){var r=Oy(e.value,t.value);return 0!==r?r:e.inclusive&&!t.inclusive?-1:!e.inclusive&&t.inclusive?1:0}function Qy(e,t){var r=Oy(e.value,t.value);return 0!==r?r:e.inclusive&&!t.inclusive?1:!e.inclusive&&t.inclusive?-1:0}class Yy{constructor(e){this.value=e}static empty(){return new Yy({mapValue:{}})}field(r){if(r.isEmpty())return this.value;{let e=this.value;for(let t=0;t<r.length-1;++t)if(!zy(e=(e.mapValue.fields||{})[r.get(t)]))return null;return(e=(e.mapValue.fields||{})[r.lastSegment()])||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=Wy(t)}setAll(e){let r=ev.emptyPath(),n={},i=[];e.forEach((e,t)=>{if(!r.isImmediateParentOf(t)){let e=this.getFieldsMap(r);this.applyChanges(e,n,i),n={},i=[],r=t.popLast()}e?n[t.lastSegment()]=Wy(e):i.push(t.lastSegment())});var t=this.getFieldsMap(r);this.applyChanges(t,n,i)}delete(e){var t=this.field(e.popLast());zy(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return Dy(this.value,e.value)}getFieldsMap(t){let r=this.value;r.mapValue.fields||(r.mapValue={fields:{}});for(let n=0;n<t.length;++n){let e=r.mapValue.fields[t.get(n)];zy(e)&&e.mapValue.fields||(e={mapValue:{fields:{}}},r.mapValue.fields[t.get(n)]=e),r=e}return r.mapValue.fields}applyChanges(r,e,t){ty(e,(e,t)=>r[e]=t);for(let e of t)delete r[e]}clone(){return new Yy(Wy(this.value))}}class Jy{constructor(e,t,r,n,i,s,a){this.key=e,this.documentType=t,this.version=r,this.readTime=n,this.createTime=i,this.data=s,this.documentState=a}static newInvalidDocument(e){return new Jy(e,0,O.min(),O.min(),O.min(),Yy.empty(),0)}static newFoundDocument(e,t,r,n){return new Jy(e,1,t,O.min(),r,n,0)}static newNoDocument(e,t){return new Jy(e,2,t,O.min(),O.min(),Yy.empty(),0)}static newUnknownDocument(e,t){return new Jy(e,3,t,O.min(),O.min(),Yy.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(O.min())||2!==this.documentType&&0!==this.documentType||(this.createTime=e),this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=Yy.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=Yy.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=O.min(),this}setReadTime(e){return this.readTime=e,this}get hasLocalMutations(){return 1===this.documentState}get hasCommittedMutations(){return 2===this.documentState}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return 0!==this.documentType}isFoundDocument(){return 1===this.documentType}isNoDocument(){return 2===this.documentType}isUnknownDocument(){return 3===this.documentType}isEqual(e){return e instanceof Jy&&this.key.isEqual(e.key)&&this.version.isEqual(e.version)&&this.documentType===e.documentType&&this.documentState===e.documentState&&this.data.isEqual(e.data)}mutableCopy(){return new Jy(this.key,this.documentType,this.version,this.readTime,this.createTime,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class Xy{constructor(e,t){this.position=e,this.inclusive=t}}function Zy(e,t,r){let n=0;for(let a=0;a<e.position.length;a++){var i=t[a],s=e.position[a];if(n=i.field.isKeyField()?P.comparator(P.fromName(s.referenceValue),r.key):Oy(s,r.data.field(i.field)),"desc"===i.dir&&(n*=-1),0!==n)break}return n}function ew(e,t){if(null===e)return null===t;if(null===t)return!1;if(e.inclusive!==t.inclusive||e.position.length!==t.position.length)return!1;for(let r=0;r<e.position.length;r++)if(!Dy(e.position[r],t.position[r]))return!1;return!0}class tw{constructor(e,t="asc"){this.field=e,this.dir=t}}class rw{}class F extends rw{constructor(e,t,r){super(),this.field=e,this.op=t,this.value=r}static create(e,t,r){return e.isKeyField()?"in"===t||"not-in"===t?this.createKeyFieldInFilter(e,t,r):new hw(e,t,r):"array-contains"===t?new pw(e,r):"in"===t?new fw(e,r):"not-in"===t?new gw(e,r):"array-contains-any"===t?new mw(e,r):new F(e,t,r)}static createKeyFieldInFilter(e,t,r){return new("in"===t?cw:uw)(e,r)}matches(e){var t=e.data.field(this.field);return"!="===this.op?null!==t&&void 0===t.nullValue&&this.matchesComparison(Oy(t,this.value)):null!==t&&Py(this.value)===Py(t)&&this.matchesComparison(Oy(t,this.value))}matchesComparison(e){switch(this.op){case"<":return e<0;case"<=":return e<=0;case"==":return 0===e;case"!=":return 0!==e;case">":return 0<e;case">=":return 0<=e;default:return C(47266,{operator:this.op})}}isInequality(){return 0<=["<","<=",">",">=","!=","not-in"].indexOf(this.op)}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class U extends rw{constructor(e,t){super(),this.filters=e,this.op=t,this.Pe=null}static create(e,t){return new U(e,t)}matches(t){return nw(this)?void 0===this.filters.find(e=>!e.matches(t)):void 0!==this.filters.find(e=>e.matches(t))}getFlattenedFilters(){return null===this.Pe&&(this.Pe=this.filters.reduce((e,t)=>e.concat(t.getFlattenedFilters()),[])),this.Pe}getFilters(){return Object.assign([],this.filters)}}function nw(e){return"and"===e.op}function iw(e){return"or"===e.op}function sw(e){return aw(e)&&nw(e)}function aw(e){for(var t of e.filters)if(t instanceof U)return!1;return!0}function ow(e,t){var r=e.filters.concat(t);return U.create(r,e.op)}function lw(e){return e instanceof F?`${(t=e).field.canonicalString()} ${t.op} `+Fy(t.value):e instanceof U?(t=e).op.toString()+" {"+t.getFilters().map(lw).join(" ,")+"}":"Filter";var t}class hw extends F{constructor(e,t,r){super(e,t,r),this.key=P.fromName(r.referenceValue)}matches(e){var t=P.comparator(e.key,this.key);return this.matchesComparison(t)}}class cw extends F{constructor(e,t){super(e,"in",t),this.keys=dw(0,t)}matches(t){return this.keys.some(e=>e.isEqual(t.key))}}class uw extends F{constructor(e,t){super(e,"not-in",t),this.keys=dw(0,t)}matches(t){return!this.keys.some(e=>e.isEqual(t.key))}}function dw(e,t){return(t.arrayValue?.values||[]).map(e=>P.fromName(e.referenceValue))}class pw extends F{constructor(e,t){super(e,"array-contains",t)}matches(e){var t=e.data.field(this.field);return qy(t)&&xy(t.arrayValue,this.value)}}class fw extends F{constructor(e,t){super(e,"in",t)}matches(e){var t=e.data.field(this.field);return null!==t&&xy(this.value.arrayValue,t)}}class gw extends F{constructor(e,t){super(e,"not-in",t)}matches(e){var t;return!xy(this.value.arrayValue,{nullValue:"NULL_VALUE"})&&null!==(t=e.data.field(this.field))&&void 0===t.nullValue&&!xy(this.value.arrayValue,t)}}class mw extends F{constructor(e,t){super(e,"array-contains-any",t)}matches(e){var t=e.data.field(this.field);return!(!qy(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>xy(this.value.arrayValue,e))}}class vw{constructor(e,t=null,r=[],n=[],i=null,s=null,a=null){this.path=e,this.collectionGroup=t,this.orderBy=r,this.filters=n,this.limit=i,this.startAt=s,this.endAt=a,this.Te=null}}function _w(e,t=null,r=[],n=[],i=null,s=null,a=null){return new vw(e,t,r,n,i,s,a)}function yw(e){var t=e;if(null===t.Te){let e=t.path.canonicalString();null!==t.collectionGroup&&(e+="|cg:"+t.collectionGroup),e=(e=(e+="|f:")+t.filters.map(e=>function t(e){var r;return e instanceof F?e.field.canonicalString()+e.op.toString()+Fy(e.value):sw(e)?e.filters.map(e=>t(e)).join(","):(r=e.filters.map(e=>t(e)).join(","),e.op+`(${r})`)}(e)).join(",")+"|ob:")+t.orderBy.map(e=>(e=e).field.canonicalString()+e.dir).join(","),qv(t.limit)||(e=(e+="|l:")+t.limit),t.startAt&&(e=(e=(e+="|lb:")+(t.startAt.inclusive?"b:":"a:"))+t.startAt.position.map(e=>Fy(e)).join(",")),t.endAt&&(e=(e=(e+="|ub:")+(t.endAt.inclusive?"a:":"b:"))+t.endAt.position.map(e=>Fy(e)).join(",")),t.Te=e}return t.Te}function ww(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let i=0;i<e.orderBy.length;i++)if(r=e.orderBy[i],n=t.orderBy[i],r.dir!==n.dir||!r.field.isEqual(n.field))return!1;var r,n;if(e.filters.length!==t.filters.length)return!1;for(let s=0;s<e.filters.length;s++)if(!function n(e,t){return e instanceof F?(r=e,(s=t)instanceof F&&r.op===s.op&&r.field.isEqual(s.field)&&Dy(r.value,s.value)):e instanceof U?(r=e,(i=t)instanceof U&&r.op===i.op&&r.filters.length===i.filters.length&&r.filters.reduce((e,t,r)=>e&&n(t,i.filters[r]),!0)):void C(19439);var i,r,s}(e.filters[s],t.filters[s]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!ew(e.startAt,t.startAt)&&ew(e.endAt,t.endAt)}function bw(e){return P.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function Iw(e,t){return e.filters.filter(e=>e instanceof F&&e.field.isEqual(t))}function Tw(e,r,n){let i=Ry,s=!0;for(let n of Iw(e,r)){let e=Ry,t=!0;switch(n.op){case"<":case"<=":e="nullValue"in(a=n.value)?Ry:"booleanValue"in a?{booleanValue:!1}:"integerValue"in a||"doubleValue"in a?{doubleValue:NaN}:"timestampValue"in a?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"stringValue"in a?{stringValue:""}:"bytesValue"in a?{bytesValue:""}:"referenceValue"in a?Uy(Ey.empty(),P.empty()):"geoPointValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in a?{arrayValue:{}}:"mapValue"in a?Ky(a)?Gy:{mapValue:{}}:C(35942,{value:a});break;case"==":case"in":case">=":e=n.value;break;case">":e=n.value,t=!1;break;case"!=":case"not-in":e=Ry}$y({value:i,inclusive:s},{value:e,inclusive:t})<0&&(i=e,s=t)}var a;if(null!==n)for(let t=0;t<e.orderBy.length;++t)if(e.orderBy[t].field.isEqual(r)){let e=n.position[t];$y({value:i,inclusive:s},{value:e,inclusive:n.inclusive})<0&&(i=e,s=n.inclusive);break}return{value:i,inclusive:s}}function Ew(e,r,n){let i=ky,s=!0;for(let n of Iw(e,r)){let e=ky,t=!0;switch(n.op){case">=":case">":e="nullValue"in(a=n.value)?{booleanValue:!1}:"booleanValue"in a?{doubleValue:NaN}:"integerValue"in a||"doubleValue"in a?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"timestampValue"in a?{stringValue:""}:"stringValue"in a?{bytesValue:""}:"bytesValue"in a?Uy(Ey.empty(),P.empty()):"referenceValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in a?{arrayValue:{}}:"arrayValue"in a?Gy:"mapValue"in a?Ky(a)?{mapValue:{}}:ky:C(61959,{value:a}),t=!1;break;case"==":case"in":case"<=":e=n.value;break;case"<":e=n.value,t=!1;break;case"!=":case"not-in":e=ky}0<Qy({value:i,inclusive:s},{value:e,inclusive:t})&&(i=e,s=t)}var a;if(null!==n)for(let t=0;t<e.orderBy.length;++t)if(e.orderBy[t].field.isEqual(r)){let e=n.position[t];0<Qy({value:i,inclusive:s},{value:e,inclusive:n.inclusive})&&(i=e,s=n.inclusive);break}return{value:i,inclusive:s}}class Cw{constructor(e,t=null,r=[],n=[],i=null,s="F",a=null,o=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=r,this.filters=n,this.limit=i,this.limitType=s,this.startAt=a,this.endAt=o,this.Ee=null,this.Ie=null,this.Re=null,this.startAt,this.endAt}}function Sw(e,t,r,n,i,s,a,o){return new Cw(e,t,r,n,i,s,a,o)}function kw(e){return new Cw(e)}function Aw(e){return 0===e.filters.length&&null===e.limit&&null==e.startAt&&null==e.endAt&&(0===e.explicitOrderBy.length||1===e.explicitOrderBy.length&&e.explicitOrderBy[0].field.isKeyField())}function Nw(e){return null!==e.collectionGroup}function Rw(e){let n=e;if(null===n.Ee){n.Ee=[];let t=new Set;for(var i of n.explicitOrderBy)n.Ee.push(i),t.add(i.field.canonicalString());let r=0<n.explicitOrderBy.length?n.explicitOrderBy[n.explicitOrderBy.length-1].dir:"asc",e=(e=>{let t=new L(ev.comparator);return e.filters.forEach(e=>{e.getFlattenedFilters().forEach(e=>{e.isInequality()&&(t=t.add(e.field))})}),t})(n);e.forEach(e=>{t.has(e.canonicalString())||e.isKeyField()||n.Ee.push(new tw(e,r))}),t.has(ev.keyField().canonicalString())||n.Ee.push(new tw(ev.keyField(),r))}return n.Ee}function Pw(e){var t=e;return t.Ie||(t.Ie=((e,t)=>{if("F"===e.limitType)return _w(e.path,e.collectionGroup,t,e.filters,e.limit,e.startAt,e.endAt);t=t.map(e=>{var t="desc"===e.dir?"asc":"desc";return new tw(e.field,t)});var r=e.endAt?new Xy(e.endAt.position,e.endAt.inclusive):null,n=e.startAt?new Xy(e.startAt.position,e.startAt.inclusive):null;return _w(e.path,e.collectionGroup,t,e.filters,e.limit,r,n)})(t,Rw(e))),t.Ie}function Dw(e,t){var r=e.filters.concat([t]);return new Cw(e.path,e.collectionGroup,e.explicitOrderBy.slice(),r,e.limit,e.limitType,e.startAt,e.endAt)}function xw(e,t,r){return new Cw(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,r,e.startAt,e.endAt)}function Ow(e,t){return ww(Pw(e),Pw(t))&&e.limitType===t.limitType}function Mw(e){return yw(Pw(e))+"|lt:"+e.limitType}function Lw(e){return`Query(target=${(e=>{let t=e.path.canonicalString();return null!==e.collectionGroup&&(t+=" collectionGroup="+e.collectionGroup),0<e.filters.length&&(t+=`, filters: [${e.filters.map(e=>lw(e)).join(", ")}]`),qv(e.limit)||(t+=", limit: "+e.limit),0<e.orderBy.length&&(t+=`, orderBy: [${e.orderBy.map(e=>`${(e=e).field.canonicalString()} (${e.dir})`).join(", ")}]`),e.startAt&&(t=(t=(t+=", startAt: ")+(e.startAt.inclusive?"b:":"a:"))+e.startAt.position.map(e=>Fy(e)).join(",")),`Target(${t=e.endAt?(t=(t+=", endAt: ")+(e.endAt.inclusive?"a:":"b:"))+e.endAt.position.map(e=>Fy(e)).join(","):t})`})(Pw(e))}; limitType=${e.limitType})`}function Fw(e,t){return t.isFoundDocument()&&(s=e,o=(a=t).key.path,null!==s.collectionGroup?a.key.hasCollectionId(s.collectionGroup)&&s.path.isPrefixOf(o):P.isDocumentKey(s.path)?s.path.isEqual(o):s.path.isImmediateParentOf(o))&&((e,t)=>{for(var r of Rw(e))if(!r.field.isKeyField()&&null===t.data.field(r.field))return;return 1})(e,t)&&((e,t)=>{for(var r of e.filters)if(!r.matches(t))return;return 1})(e,t)&&(a=t,!(s=e).startAt||(n=s.startAt,r=Rw(s),i=Zy(n,r,a),n.inclusive?i<=0:i<0))&&(!s.endAt||(r=s.endAt,n=Rw(s),i=Zy(r,n,a),r.inclusive?0<=i:0<i));var r,n,i,s,a,o}function Uw(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function Vw(e){return(t,r)=>{let n=!1;for(var i of Rw(e)){let e=((e,t,r)=>{var n=e.field.isKeyField()?P.comparator(t.key,r.key):((e,t,r)=>{var n=t.data.field(e),i=r.data.field(e);return null!==n&&null!==i?Oy(n,i):C(42886)})(e.field,t,r);switch(e.dir){case"asc":return n;case"desc":return-1*n;default:return C(19790,{direction:e.dir})}})(i,t,r);if(0!==e)return e;n=n||i.field.isKeyField()}return 0}}class qw{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(r){let e=this.mapKeyFn(r),n=this.inner[e];if(void 0!==n)for(let[e,t]of n)if(this.equalsFn(e,r))return t}has(e){return void 0!==this.get(e)}set(t,r){var e=this.mapKeyFn(t),n=this.inner[e];if(void 0===n)this.inner[e]=[[t,r]];else{for(let e=0;e<n.length;e++)if(this.equalsFn(n[e][0],t))return void(n[e]=[t,r]);n.push([t,r])}this.innerSize++}delete(t){var r=this.mapKeyFn(t),n=this.inner[r];if(void 0!==n)for(let e=0;e<n.length;e++)if(this.equalsFn(n[e][0],t))return 1===n.length?delete this.inner[r]:n.splice(e,1),this.innerSize--,!0;return!1}forEach(n){ty(this.inner,(e,t)=>{for(let[e,r]of t)n(e,r)})}isEmpty(){return ry(this.inner)}size(){return this.innerSize}}let Bw=new ny(P.comparator);let jw=new ny(P.comparator);function zw(...e){let t=jw;for(var r of e)t=t.insert(r.key,r);return t}function Kw(e){let r=jw;return e.forEach((e,t)=>r=r.insert(e,t.overlayedDocument)),r}function Ww(){return new qw(e=>e.toString(),(e,t)=>e.isEqual(t))}let Hw=new ny(P.comparator),Gw=new L(P.comparator);function V(...e){let t=Gw;for(var r of e)t=t.add(r);return t}let $w=new L(N);function Qw(e,t){if(e.useProto3Json){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:Bv(t)?"-0":t}}function Yw(e){return{integerValue:""+e}}function Jw(e,t){return jv(t)?Yw(t):Qw(e,t)}class Xw{constructor(){this._=void 0}}function Zw(e,t){return e instanceof sb?Vy(e=t)||(e=e)&&"doubleValue"in e?t:{integerValue:0}:null}class eb extends Xw{}class tb extends Xw{constructor(e){super(),this.elements=e}}function rb(e,t){var r=ob(t);for(let t of e.elements)r.some(e=>Dy(e,t))||r.push(t);return{arrayValue:{values:r}}}class nb extends Xw{constructor(e){super(),this.elements=e}}function ib(e,t){let r=ob(t);for(let t of e.elements)r=r.filter(e=>!Dy(e,t));return{arrayValue:{values:r}}}class sb extends Xw{constructor(e,t){super(),this.serializer=e,this.Ae=t}}function ab(e){return py(e.integerValue||e.doubleValue)}function ob(e){return qy(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class lb{constructor(e,t){this.field=e,this.transform=t}}class hb{constructor(e,t){this.version=e,this.transformResults=t}}class cb{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new cb}static exists(e){return new cb(void 0,e)}static updateTime(e){return new cb(e)}get isNone(){return void 0===this.updateTime&&void 0===this.exists}isEqual(e){return this.exists===e.exists&&(this.updateTime?!!e.updateTime&&this.updateTime.isEqual(e.updateTime):!e.updateTime)}}function ub(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class db{}function pb(e,r){if(!e.hasLocalMutations||r&&0===r.fields.length)return null;if(null===r)return e.isNoDocument()?new bb(e.key,cb.none()):new mb(e.key,e.data,cb.none());{var n,i=e.data,s=Yy.empty();let t=new L(ev.comparator);for(n of r.fields)if(!t.has(n)){let e=i.field(n);null===e&&1<n.length&&(n=n.popLast(),e=i.field(n)),null===e?s.delete(n):s.set(n,e),t=t.add(n)}return new vb(e.key,s,new ly(t.toArray()),cb.none())}}function fb(e,t,r,n){return e instanceof mb?(s=t,a=r,o=n,ub((i=e).precondition,s)?(l=i.value.clone(),h=wb(i.fieldTransforms,o,s),l.setAll(h),s.convertToFoundDocument(s.version,l).setHasLocalMutations(),null):a):e instanceof vb?(i=t,o=r,s=n,ub((a=e).precondition,i)?(h=wb(a.fieldTransforms,s,i),(l=i.data).setAll(_b(a)),l.setAll(h),i.convertToFoundDocument(i.version,l).setHasLocalMutations(),null===o?null:o.unionWith(a.fieldMask.fields).unionWith(a.fieldTransforms.map(e=>e.field))):o):(n=t,t=r,ub(e.precondition,n)?(n.convertToNoDocument(n.version).setHasLocalMutations(),null):t);var i,s,a,o,l,h}function gb(e,t){return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&(r=e.fieldTransforms,n=t.fieldTransforms,!!(void 0===r&&void 0===n||r&&n&&Qm(r,n,(e,t)=>(t=t,(e=e).field.isEqual(t.field)&&(e=e.transform,t=t.transform,e instanceof tb&&t instanceof tb||e instanceof nb&&t instanceof nb?Qm(e.elements,t.elements,Dy):e instanceof sb&&t instanceof sb?Dy(e.Ae,t.Ae):e instanceof eb&&t instanceof eb)))))&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask));var r,n}class mb extends db{constructor(e,t,r,n=[]){super(),this.key=e,this.value=t,this.precondition=r,this.fieldTransforms=n,this.type=0}getFieldMask(){return null}}class vb extends db{constructor(e,t,r,n,i=[]){super(),this.key=e,this.data=t,this.fieldMask=r,this.precondition=n,this.fieldTransforms=i,this.type=1}getFieldMask(){return this.fieldMask}}function _b(r){let n=new Map;return r.fieldMask.fields.forEach(e=>{var t;e.isEmpty()||(t=r.data.field(e),n.set(e,t))}),n}function yb(e,t,r){var n,i,s,a=new Map;S(e.length===r.length,32656,{Ve:r.length,de:e.length});for(let c=0;c<r.length;c++){var o=e[c],l=o.transform,h=t.data.field(o.field);a.set(o.field,(n=l,i=h,s=r[c],n instanceof tb?rb(n,i):n instanceof nb?ib(n,i):s))}return a}function wb(e,r,n){var i,s,a,o,l,h,c,u=new Map;for(i of e){let e=i.transform,t=n.data.field(i.field);u.set(i.field,(s=e,a=t,o=r,c=h=l=void 0,s instanceof eb?(o=o,h=a,c={fields:{[my]:{stringValue:gy},[_y]:{timestampValue:{seconds:o.seconds,nanos:o.nanoseconds}}}},(h=h&&yy(h)?wy(h):h)&&(c.fields[vy]=h),{mapValue:c}):s instanceof tb?rb(s,a):s instanceof nb?ib(s,a):(c=Zw(o=s,a),l=ab(c)+ab(o.Ae),Vy(c)&&Vy(o.Ae)?Yw(l):Qw(o.serializer,l))))}return u}class bb extends db{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class Ib extends db{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class Tb{constructor(e,t,r,n){this.batchId=e,this.localWriteTime=t,this.baseMutations=r,this.mutations=n}applyToRemoteDocument(e,t){var r,n,i,s,a,o,l,h=t.mutationResults;for(let u=0;u<this.mutations.length;u++){var c=this.mutations[u];c.key.isEqual(e.key)&&(r=c,n=e,i=h[u],l=c=o=a=s=void 0,r instanceof mb?(a=n,o=i,c=(s=r).value.clone(),l=yb(s.fieldTransforms,a,o.transformResults),c.setAll(l),a.convertToFoundDocument(o.version,c).setHasCommittedMutations()):r instanceof vb?(s=n,a=i,ub((o=r).precondition,s)?(l=yb(o.fieldTransforms,s,a.transformResults),(c=s.data).setAll(_b(o)),c.setAll(l),s.convertToFoundDocument(a.version,c).setHasCommittedMutations()):s.convertToUnknownDocument(a.version)):n.convertToNoDocument(i.version).setHasCommittedMutations())}}applyToLocalView(e,t){for(var r of this.baseMutations)r.key.isEqual(e.key)&&(t=fb(r,e,t,this.localWriteTime));for(var n of this.mutations)n.key.isEqual(e.key)&&(t=fb(n,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(n,i){let s=Ww();return this.mutations.forEach(e=>{var t=n.get(e.key),r=t.overlayedDocument,t=this.applyToLocalView(r,t.mutatedFields),t=pb(r,i.has(e.key)?null:t);null!==t&&s.set(e.key,t),r.isValidDocument()||r.convertToNoDocument(O.min())}),s}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),V())}isEqual(e){return this.batchId===e.batchId&&Qm(this.mutations,e.mutations,(e,t)=>gb(e,t))&&Qm(this.baseMutations,e.baseMutations,(e,t)=>gb(e,t))}}class Eb{constructor(e,t,r,n){this.batch=e,this.commitVersion=t,this.mutationResults=r,this.docVersions=n}static from(e,t,r){S(e.mutations.length===r.length,58842,{me:e.mutations.length,fe:r.length});let n=Hw;var i=e.mutations;for(let s=0;s<i.length;s++)n=n.insert(i[s].key,r[s].version);return new Eb(e,t,r,n)}}class Cb{constructor(e,t){this.largestBatchId=e,this.mutation=t}getKey(){return this.mutation.key}isEqual(e){return null!==e&&this.mutation===e.mutation}toString(){return`Overlay{
|
|
10
10
|
largestBatchId: ${this.largestBatchId},
|
|
11
11
|
mutation: ${this.mutation.toString()}
|
|
12
12
|
}`}}class Sb{constructor(e,t){this.count=e,this.unchangedNames=t}}function kb(e){switch(e){case k.OK:return C(64938);case k.CANCELLED:case k.UNKNOWN:case k.DEADLINE_EXCEEDED:case k.RESOURCE_EXHAUSTED:case k.INTERNAL:case k.UNAVAILABLE:case k.UNAUTHENTICATED:return!1;case k.INVALID_ARGUMENT:case k.NOT_FOUND:case k.ALREADY_EXISTS:case k.PERMISSION_DENIED:case k.FAILED_PRECONDITION:case k.ABORTED:case k.OUT_OF_RANGE:case k.UNIMPLEMENTED:case k.DATA_LOSS:return!0;default:return C(15467,{code:e})}}function Ab(e){if(void 0===e)return Pm("GRPC error has no .code"),k.UNKNOWN;switch(e){case Em.OK:return k.OK;case Em.CANCELLED:return k.CANCELLED;case Em.UNKNOWN:return k.UNKNOWN;case Em.DEADLINE_EXCEEDED:return k.DEADLINE_EXCEEDED;case Em.RESOURCE_EXHAUSTED:return k.RESOURCE_EXHAUSTED;case Em.INTERNAL:return k.INTERNAL;case Em.UNAVAILABLE:return k.UNAVAILABLE;case Em.UNAUTHENTICATED:return k.UNAUTHENTICATED;case Em.INVALID_ARGUMENT:return k.INVALID_ARGUMENT;case Em.NOT_FOUND:return k.NOT_FOUND;case Em.ALREADY_EXISTS:return k.ALREADY_EXISTS;case Em.PERMISSION_DENIED:return k.PERMISSION_DENIED;case Em.FAILED_PRECONDITION:return k.FAILED_PRECONDITION;case Em.ABORTED:return k.ABORTED;case Em.OUT_OF_RANGE:return k.OUT_OF_RANGE;case Em.UNIMPLEMENTED:return k.UNIMPLEMENTED;case Em.DATA_LOSS:return k.DATA_LOSS;default:return C(39323,{code:e})}}(e=Em=Em||{})[e.OK=0]="OK",e[e.CANCELLED=1]="CANCELLED",e[e.UNKNOWN=2]="UNKNOWN",e[e.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",e[e.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",e[e.NOT_FOUND=5]="NOT_FOUND",e[e.ALREADY_EXISTS=6]="ALREADY_EXISTS",e[e.PERMISSION_DENIED=7]="PERMISSION_DENIED",e[e.UNAUTHENTICATED=16]="UNAUTHENTICATED",e[e.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",e[e.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",e[e.ABORTED=10]="ABORTED",e[e.OUT_OF_RANGE=11]="OUT_OF_RANGE",e[e.UNIMPLEMENTED=12]="UNIMPLEMENTED",e[e.INTERNAL=13]="INTERNAL",e[e.UNAVAILABLE=14]="UNAVAILABLE",e[e.DATA_LOSS=15]="DATA_LOSS";function Nb(){return new TextEncoder}let Rb=new fm([4294967295,4294967295],0);function Pb(e){var t=Nb().encode(e),r=new gm;return r.update(t),new Uint8Array(r.digest())}function Db(e){var t=new DataView(e.buffer),r=t.getUint32(0,!0),n=t.getUint32(4,!0),i=t.getUint32(8,!0),t=t.getUint32(12,!0);return[new fm([r,n],0),new fm([i,t],0)]}class xb{constructor(e,t,r){if(this.bitmap=e,this.padding=t,this.hashCount=r,t<0||8<=t)throw new Ob("Invalid padding: "+t);if(r<0)throw new Ob("Invalid hash count: "+r);if(0<e.length&&0===this.hashCount)throw new Ob("Invalid hash count: "+r);if(0===e.length&&0!==t)throw new Ob("Invalid padding when bitmap length is 0: "+t);this.ge=8*e.length-t,this.pe=fm.fromNumber(this.ge)}ye(e,t,r){let n=e.add(t.multiply(fm.fromNumber(r)));return(n=1===n.compare(Rb)?new fm([n.getBits(0),n.getBits(1)],0):n).modulo(this.pe).toNumber()}we(e){return!!(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(0===this.ge)return!1;let t=Pb(e),[r,n]=Db(t);for(let i=0;i<this.hashCount;i++){let e=this.ye(r,n,i);if(!this.we(e))return!1}return!0}static create(e,t,r){let n=e%8==0?0:8-e%8,i=new Uint8Array(Math.ceil(e/8)),s=new xb(i,n,t);return r.forEach(e=>s.insert(e)),s}insert(i){if(0!==this.ge){let e=Pb(i),[t,r]=Db(e);for(let n=0;n<this.hashCount;n++){let e=this.ye(t,r,n);this.Se(e)}}}Se(e){var t=Math.floor(e/8);this.bitmap[t]|=1<<e%8}}class Ob extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}class Mb{constructor(e,t,r,n,i){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=r,this.documentUpdates=n,this.resolvedLimboDocuments=i}static createSynthesizedRemoteEventForCurrentChange(e,t,r){var n=new Map;return n.set(e,Lb.createSynthesizedTargetChangeForCurrentChange(e,t,r)),new Mb(O.min(),n,new ny(N),Bw,V())}}class Lb{constructor(e,t,r,n,i){this.resumeToken=e,this.current=t,this.addedDocuments=r,this.modifiedDocuments=n,this.removedDocuments=i}static createSynthesizedTargetChangeForCurrentChange(e,t,r){return new Lb(r,t,V(),V(),V())}}class Fb{constructor(e,t,r,n){this.be=e,this.removedTargetIds=t,this.key=r,this.De=n}}class Ub{constructor(e,t){this.targetId=e,this.Ce=t}}class Vb{constructor(e,t,r=cy.EMPTY_BYTE_STRING,n=null){this.state=e,this.targetIds=t,this.resumeToken=r,this.cause=n}}class qb{constructor(){this.ve=0,this.Fe=zb(),this.Me=cy.EMPTY_BYTE_STRING,this.xe=!1,this.Oe=!0}get current(){return this.xe}get resumeToken(){return this.Me}get Ne(){return 0!==this.ve}get Be(){return this.Oe}Le(e){0<e.approximateByteSize()&&(this.Oe=!0,this.Me=e)}ke(){let r=V(),n=V(),i=V();return this.Fe.forEach((e,t)=>{switch(t){case 0:r=r.add(e);break;case 2:n=n.add(e);break;case 1:i=i.add(e);break;default:C(38017,{changeType:t})}}),new Lb(this.Me,this.xe,r,n,i)}qe(){this.Oe=!1,this.Fe=zb()}Ke(e,t){this.Oe=!0,this.Fe=this.Fe.insert(e,t)}Ue(e){this.Oe=!0,this.Fe=this.Fe.remove(e)}$e(){this.ve+=1}We(){--this.ve,S(0<=this.ve,3241,{ve:this.ve})}Qe(){this.Oe=!0,this.xe=!0}}class Bb{constructor(e){this.Ge=e,this.ze=new Map,this.je=Bw,this.Je=jb(),this.He=jb(),this.Ze=new ny(N)}Xe(e){for(var t of e.be)e.De&&e.De.isFoundDocument()?this.Ye(t,e.De):this.et(t,e.key,e.De);for(var r of e.removedTargetIds)this.et(r,e.key,e.De)}tt(r){this.forEachTarget(r,e=>{var t=this.nt(e);switch(r.state){case 0:this.rt(e)&&t.Le(r.resumeToken);break;case 1:t.We(),t.Ne||t.qe(),t.Le(r.resumeToken);break;case 2:t.We(),t.Ne||this.removeTarget(e);break;case 3:this.rt(e)&&(t.Qe(),t.Le(r.resumeToken));break;case 4:this.rt(e)&&(this.it(e),t.Le(r.resumeToken));break;default:C(56790,{state:r.state})}})}forEachTarget(e,r){0<e.targetIds.length?e.targetIds.forEach(r):this.ze.forEach((e,t)=>{this.rt(t)&&r(t)})}st(n){let i=n.targetId,e=n.Ce.count,t=this.ot(i);if(t){var r=t.target;if(bw(r))if(0===e){let e=new P(r.path);this.et(i,e,Jy.newNoDocument(e,O.min()))}else S(1===e,20013,{expectedCount:e});else{let r=this._t(i);if(r!==e){let e=this.ut(n),t=e?this.ct(e,n,r):1;if(0!==t){this.it(i);let e=2===t?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch";this.Ze=this.Ze.insert(i,e)}}}}}ut(e){var t=e.Ce.unchangedNames;if(!t||!t.bits)return null;var{bits:{bitmap:t="",padding:r=0},hashCount:n=0}=t;let i,s;try{i=fy(t).toUint8Array()}catch(e){if(e instanceof hy)return Dm("Decoding the base64 bloom filter in existence filter failed ("+e.message+"); ignoring the bloom filter and falling back to full re-query."),null;throw e}try{s=new xb(i,r,n)}catch(e){return Dm(e instanceof Ob?"BloomFilter error: ":"Applying bloom filter failed: ",e),null}return 0===s.ge?null:s}ct(e,t,r){return t.Ce.count===r-this.Pt(e,t.targetId)?0:2}Pt(r,n){var e=this.Ge.getRemoteKeysForTarget(n);let i=0;return e.forEach(e=>{var t=this.Ge.ht(),t=`projects/${t.projectId}/databases/${t.database}/documents/`+e.path.canonicalString();r.mightContain(t)||(this.et(n,e,null),i++)}),i}Tt(n){let i=new Map,s=(this.ze.forEach((e,t)=>{var r=this.ot(t);if(r){if(e.current&&bw(r.target)){let e=new P(r.target.path);this.Et(e).has(t)||this.It(t,e)||this.et(t,e,Jy.newNoDocument(e,n))}e.Be&&(i.set(t,e.ke()),e.qe())}}),V());this.He.forEach((e,t)=>{let r=!0;t.forEachWhile(e=>{var t=this.ot(e);return!t||"TargetPurposeLimboResolution"===t.purpose||(r=!1)}),r&&(s=s.add(e))}),this.je.forEach((e,t)=>t.setReadTime(n));var e=new Mb(n,i,this.Ze,this.je,s);return this.je=Bw,this.Je=jb(),this.He=jb(),this.Ze=new ny(N),e}Ye(e,t){var r;this.rt(e)&&(r=this.It(e,t.key)?2:0,this.nt(e).Ke(t.key,r),this.je=this.je.insert(t.key,t),this.Je=this.Je.insert(t.key,this.Et(t.key).add(e)),this.He=this.He.insert(t.key,this.Rt(t.key).add(e)))}et(e,t,r){var n;this.rt(e)&&(n=this.nt(e),this.It(e,t)?n.Ke(t,1):n.Ue(t),this.He=this.He.insert(t,this.Rt(t).delete(e)),this.He=this.He.insert(t,this.Rt(t).add(e)),r)&&(this.je=this.je.insert(t,r))}removeTarget(e){this.ze.delete(e)}_t(e){var t=this.nt(e).ke();return this.Ge.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}$e(e){this.nt(e).$e()}nt(e){let t=this.ze.get(e);return t||(t=new qb,this.ze.set(e,t)),t}Rt(e){let t=this.He.get(e);return t||(t=new L(N),this.He=this.He.insert(e,t)),t}Et(e){let t=this.Je.get(e);return t||(t=new L(N),this.Je=this.Je.insert(e,t)),t}rt(e){var t=null!==this.ot(e);return t||E("WatchChangeAggregator","Detected inactive target",e),t}ot(e){var t=this.ze.get(e);return t&&t.Ne?null:this.Ge.At(e)}it(t){this.ze.set(t,new qb),this.Ge.getRemoteKeysForTarget(t).forEach(e=>{this.et(t,e,null)})}It(e,t){return this.Ge.getRemoteKeysForTarget(e).has(t)}}function jb(){return new ny(P.comparator)}function zb(){return new ny(P.comparator)}let Kb={asc:"ASCENDING",desc:"DESCENDING"},Wb={"<":"LESS_THAN","<=":"LESS_THAN_OR_EQUAL",">":"GREATER_THAN",">=":"GREATER_THAN_OR_EQUAL","==":"EQUAL","!=":"NOT_EQUAL","array-contains":"ARRAY_CONTAINS",in:"IN","not-in":"NOT_IN","array-contains-any":"ARRAY_CONTAINS_ANY"},Hb={and:"AND",or:"OR"};class Gb{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function $b(e,t){return e.useProto3Json||qv(t)?t:{value:t}}function Qb(e,t){return e.useProto3Json?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function Yb(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function Jb(e){return S(!!e,49232),O.fromTimestamp((t=dy(e),new x(t.seconds,t.nanos)));var t}function Xb(e,t){return Zb(e,t).canonicalString()}function Zb(e,t){e=e;var r=new R(["projects",e.projectId,"databases",e.database]).child("documents");return void 0===t?r:r.child(t)}function eI(e){var t=R.fromString(e);return S(wI(t),10190,{key:t.toString()}),t}function tI(e,t){return Xb(e.databaseId,t.path)}function rI(e,t){var r=eI(t);if(r.get(1)!==e.databaseId.projectId)throw new A(k.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+r.get(1)+" vs "+e.databaseId.projectId);if(r.get(3)!==e.databaseId.database)throw new A(k.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+r.get(3)+" vs "+e.databaseId.database);return new P(aI(r))}function nI(e,t){return Xb(e.databaseId,t)}function iI(e){var t=eI(e);return 4===t.length?R.emptyPath():aI(t)}function sI(e){return new R(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function aI(e){return S(4<e.length&&"documents"===e.get(4),29091,{key:e.toString()}),e.popFirst(5)}function oI(e,t,r){return{name:tI(e,t),fields:r.value.mapValue.fields}}function lI(e,t,r){var n=rI(e,t.name),i=Jb(t.updateTime),s=t.createTime?Jb(t.createTime):O.min(),a=new Yy({mapValue:{fields:t.fields}}),n=Jy.newFoundDocument(n,i,s,a);return r&&n.setHasCommittedMutations(),r?n.setHasCommittedMutations():n}function hI(e,t){let r;if(t instanceof mb)r={update:oI(e,t.key,t.value)};else if(t instanceof bb)r={delete:tI(e,t.key)};else if(t instanceof vb)r={update:oI(e,t.key,t.data),updateMask:(e=>{let t=[];return e.fields.forEach(e=>t.push(e.canonicalString())),{fieldPaths:t}})(t.fieldMask)};else{if(!(t instanceof Ib))return C(16599,{dt:t.type});r={verify:tI(e,t.key)}}return 0<t.fieldTransforms.length&&(r.updateTransforms=t.fieldTransforms.map(e=>{var t=e.transform;if(t instanceof eb)return{fieldPath:e.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(t instanceof tb)return{fieldPath:e.field.canonicalString(),appendMissingElements:{values:t.elements}};if(t instanceof nb)return{fieldPath:e.field.canonicalString(),removeAllFromArray:{values:t.elements}};if(t instanceof sb)return{fieldPath:e.field.canonicalString(),increment:t.Ae};throw C(20930,{transform:e.transform})})),t.precondition.isNone||(r.currentDocument=(e=e,void 0!==(t=t.precondition).updateTime?{updateTime:(n=t.updateTime,Qb(e,n.toTimestamp()))}:void 0!==t.exists?{exists:t.exists}:C(27497))),r;var n}function cI(i,t){let r=t.currentDocument?void 0!==(s=t.currentDocument).updateTime?cb.updateTime(Jb(s.updateTime)):void 0!==s.exists?cb.exists(s.exists):cb.none():cb.none(),n=t.updateTransforms?t.updateTransforms.map(r=>{{var e=i;let t=null;if("setToServerValue"in r)S("REQUEST_TIME"===r.setToServerValue,16630,{proto:r}),t=new eb;else if("appendMissingElements"in r){let e=r.appendMissingElements.values||[];t=new tb(e)}else if("removeAllFromArray"in r){let e=r.removeAllFromArray.values||[];t=new nb(e)}else"increment"in r?t=new sb(e,r.increment):C(16584,{proto:r});var n=ev.fromServerFormat(r.fieldPath);return new lb(n,t)}}):[];var s,a;if(t.update){t.update.name;var o=rI(i,t.update.name),l=new Yy({mapValue:{fields:t.update.fields}});if(t.updateMask){s=t.updateMask,a=s.fieldPaths||[];let e=new ly(a.map(e=>ev.fromServerFormat(e)));return new vb(o,l,e,r,n)}return new mb(o,l,r,n)}if(t.delete){let e=rI(i,t.delete);return new bb(e,r)}if(t.verify){let e=rI(i,t.verify);return new Ib(e,r)}return C(1463,{proto:t})}function uI(e,n){return e&&0<e.length?(S(void 0!==n,14353),e.map(t=>{{var r=n;let e=t.updateTime?Jb(t.updateTime):Jb(r);return e.isEqual(O.min())&&(e=Jb(r)),new hb(e,t.transformResults||[])}})):[]}function dI(e,t){return{documents:[nI(e,t.path)]}}function pI(e,t){var r={structuredQuery:{}},n=t.path;let i;null!==t.collectionGroup?(i=n,r.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(i=n.popLast(),r.structuredQuery.from=[{collectionId:n.lastSegment()}]),r.parent=nI(e,i);n=(e=>{if(0!==e.length)return function r(e){return e instanceof F?(e=>{if("=="===e.op){if(jy(e.value))return{unaryFilter:{field:_I(e.field),op:"IS_NAN"}};if(By(e.value))return{unaryFilter:{field:_I(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(jy(e.value))return{unaryFilter:{field:_I(e.field),op:"IS_NOT_NAN"}};if(By(e.value))return{unaryFilter:{field:_I(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:_I(e.field),op:mI(e.op),value:e.value}}})(e):e instanceof U?(e=>{let t=e.getFilters().map(e=>r(e));return 1===t.length?t[0]:{compositeFilter:{op:vI(e.op),filters:t}}})(e):C(54877,{filter:e})}(U.create(e,"and"))})(t.filters),n&&(r.structuredQuery.where=n),n=(e=>{if(0!==e.length)return e.map(e=>({field:_I((e=e).field),direction:(e=e.dir,Kb[e])}))})(t.orderBy),n&&(r.structuredQuery.orderBy=n),n=$b(e,t.limit);return null!==n&&(r.structuredQuery.limit=n),t.startAt&&(r.structuredQuery.startAt={before:(e=t.startAt).inclusive,values:e.position}),t.endAt&&(r.structuredQuery.endAt={before:!(e=t.endAt).inclusive,values:e.position}),{ft:r,parent:i}}function fI(e){let t=iI(e.parent);var r,n=e.structuredQuery,i=n.from?n.from.length:0;let s=null;if(0<i){S(1===i,65062);let e=n.from[0];e.allDescendants?s=e.collectionId:t=t.child(e.collectionId)}let a=[],o=(n.where&&(a=(e=n.where,(i=function t(e){return void 0!==e.unaryFilter?(i=>{switch(i.unaryFilter.op){case"IS_NAN":let e=yI(i.unaryFilter.field);return F.create(e,"==",{doubleValue:NaN});case"IS_NULL":let t=yI(i.unaryFilter.field);return F.create(t,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":let r=yI(i.unaryFilter.field);return F.create(r,"!=",{doubleValue:NaN});case"IS_NOT_NULL":let n=yI(i.unaryFilter.field);return F.create(n,"!=",{nullValue:"NULL_VALUE"});case"OPERATOR_UNSPECIFIED":return C(61313);default:return C(60726)}})(e):void 0!==e.fieldFilter?(e=>F.create(yI(e.fieldFilter.field),(e=>{switch(e){case"EQUAL":return"==";case"NOT_EQUAL":return"!=";case"GREATER_THAN":return">";case"GREATER_THAN_OR_EQUAL":return">=";case"LESS_THAN":return"<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";case"OPERATOR_UNSPECIFIED":return C(58110);default:return C(50506)}})(e.fieldFilter.op),e.fieldFilter.value))(e):void 0!==e.compositeFilter?(e=>U.create(e.compositeFilter.filters.map(e=>t(e)),(e=>{switch(e){case"AND":return"and";case"OR":return"or";default:return C(1026)}})(e.compositeFilter.op)))(e):C(30097,{filter:e})}(e))instanceof U&&sw(i)?i.getFilters():[i])),[]),l=(n.orderBy&&(o=n.orderBy.map(e=>(e=e,new tw(yI(e.field),(e=>{switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}})(e.direction))))),null),h=(n.limit&&(l=(e=n.limit,qv(i="object"==typeof e?e.value:e)?null:i)),null),c=(n.startAt&&(h=(e=n.startAt,i=!!e.before,r=e.values||[],new Xy(r,i))),null);return n.endAt&&(c=(e=n.endAt,r=!e.before,i=e.values||[],new Xy(i,r))),Sw(t,s,o,a,l,"F",h,c)}function gI(e,t){var r=(e=>{switch(e){case"TargetPurposeListen":return null;case"TargetPurposeExistenceFilterMismatch":return"existence-filter-mismatch";case"TargetPurposeExistenceFilterMismatchBloom":return"existence-filter-mismatch-bloom";case"TargetPurposeLimboResolution":return"limbo-document";default:return C(28987,{purpose:e})}})(t.purpose);return null==r?null:{"goog-listen-tags":r}}function mI(e){return Wb[e]}function vI(e){return Hb[e]}function _I(e){return{fieldPath:e.canonicalString()}}function yI(e){return ev.fromServerFormat(e.fieldPath)}function wI(e){return 4<=e.length&&"projects"===e.get(0)&&"databases"===e.get(2)}function bI(e){return e&&"function"==typeof e._toProto&&"ProtoValue"===e._protoValueType}class II{constructor(e,t,r,n,i=O.min(),s=O.min(),a=cy.EMPTY_BYTE_STRING,o=null){this.target=e,this.targetId=t,this.purpose=r,this.sequenceNumber=n,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=s,this.resumeToken=a,this.expectedCount=o}withSequenceNumber(e){return new II(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new II(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new II(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new II(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class TI{constructor(e){this.yt=e}}function EI(e,t){var r,n=t.key,i={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:CI(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument())i.document={name:tI(e=e.yt,(r=t).key),fields:r.data.value.mapValue.fields,updateTime:Qb(e,r.version.toTimestamp()),createTime:Qb(e,r.createTime.toTimestamp())};else if(t.isNoDocument())i.noDocument={path:n.path.toArray(),readTime:SI(t.version)};else{if(!t.isUnknownDocument())return C(57904,{document:t});i.unknownDocument={path:n.path.toArray(),version:SI(t.version)}}return i}function CI(e){var t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function SI(e){var t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function kI(e){var t=new x(e.seconds,e.nanoseconds);return O.fromTimestamp(t)}function AI(t,r){let e=(r.baseMutations||[]).map(e=>cI(t.yt,e));for(let s=0;s<r.mutations.length-1;++s){let t=r.mutations[s];if(s+1<r.mutations.length&&void 0!==r.mutations[s+1].transform){let e=r.mutations[s+1];t.updateTransforms=e.transform.fieldTransforms,r.mutations.splice(s+1,1),++s}}let n=r.mutations.map(e=>cI(t.yt,e)),i=x.fromMillis(r.localWriteTimeMs);return new Tb(r.batchId,i,e,n)}function NI(e){var t,r=kI(e.readTime),n=void 0!==e.lastLimboFreeSnapshotVersion?kI(e.lastLimboFreeSnapshotVersion):O.min(),i=void 0!==e.query.documents?(t=e.query,S(1===(i=t.documents.length),1966,{count:i}),Pw(kw(iI(t.documents[0])))):Pw(fI(e.query));return new II(i,e.targetId,"TargetPurposeListen",e.lastListenSequenceNumber,r,n,cy.fromBase64String(e.resumeToken))}function RI(e,t){var r=SI(t.snapshotVersion),n=SI(t.lastLimboFreeSnapshotVersion),i=bw(t.target)?dI(e.yt,t.target):pI(e.yt,t.target).ft,s=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:yw(t.target),readTime:r,resumeToken:s,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:n,query:i}}function PI(e){var t=fI({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?xw(t,t.limit,"L"):t}function DI(e,t){return new Cb(t.largestBatchId,cI(e.yt,t.overlayMutation))}function xI(e,t){var r=t.path.lastSegment();return[e,Kv(t.path.popLast()),r]}function OI(e,t,r,n){return{indexId:e,uid:t,sequenceNumber:r,readTime:SI(n.readTime),documentKey:Kv(n.documentKey.path),largestBatchId:n.largestBatchId}}class MI{getBundleMetadata(e,t){return LI(e).get(t).next(e=>{if(e)return{id:(e=e).bundleId,createTime:kI(e.createTime),version:e.version}})}saveBundleMetadata(e,t){return LI(e).put({bundleId:(e=t).id,createTime:SI(Jb(e.createTime)),version:e.version})}getNamedQuery(e,t){return FI(e).get(t).next(e=>{if(e)return{name:(e=e).name,query:PI(e.bundledQuery),readTime:kI(e.readTime)}})}saveNamedQuery(e,t){return FI(e).put({name:(e=t).name,readTime:SI(Jb(e.readTime)),bundledQuery:e.bundledQuery})}}function LI(e){return Z_(e,C_)}function FI(e){return Z_(e,S_)}class UI{constructor(e,t){this.serializer=e,this.userId=t}static wt(e,t){var r=t.uid||"";return new UI(e,r)}getOverlay(e,t){return VI(e).get(xI(this.userId,t)).next(e=>e?DI(this.serializer,e):null)}getOverlays(e,t){let r=Ww();return M.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&r.set(t,e)})).next(()=>r)}saveOverlays(n,i,e){let s=[];return e.forEach((e,t)=>{var r=new Cb(i,t);s.push(this.St(n,r))}),M.waitFor(s)}removeOverlaysForBatchId(r,e,n){let t=new Set,i=(e.forEach(e=>t.add(Kv(e.getCollectionPath()))),[]);return t.forEach(e=>{var t=IDBKeyRange.bound([this.userId,e,n],[this.userId,e,n+1],!1,!0);i.push(VI(r).X(V_,t))}),M.waitFor(i)}getOverlaysForCollection(e,t,r){let n=Ww(),i=Kv(t),s=IDBKeyRange.bound([this.userId,i,r],[this.userId,i,Number.POSITIVE_INFINITY],!0);return VI(e).J(V_,s).next(e=>{for(var t of e){let e=DI(this.serializer,t);n.set(e.getKey(),e)}return n})}getOverlaysForCollectionGroup(e,t,r,i){let s=Ww(),a;var n=IDBKeyRange.bound([this.userId,t,r],[this.userId,t,Number.POSITIVE_INFINITY],!0);return VI(e).ee({index:B_,range:n},(e,t,r)=>{var n=DI(this.serializer,t);s.size()<i||n.largestBatchId===a?(s.set(n.getKey(),n),a=n.largestBatchId):r.done()}).next(()=>s)}St(e,t){return VI(e).put(((e,t,r)=>{var[,n,i]=xI(t,r.mutation.key);return{userId:t,collectionPath:n,documentId:i,collectionGroup:r.mutation.key.getCollectionGroup(),largestBatchId:r.largestBatchId,overlayMutation:hI(e.yt,r.mutation)}})(this.serializer,this.userId,t))}}function VI(e){return Z_(e,F_)}class qI{bt(e){return Z_(e,z_)}getSessionToken(e){return this.bt(e).get("sessionToken").next(e=>{var t=e?.value;return t?cy.fromUint8Array(t):cy.EMPTY_BYTE_STRING})}setSessionToken(e,t){return this.bt(e).put({name:"sessionToken",value:t.toUint8Array()})}}class BI{constructor(){}Dt(e,t){this.Ct(e,t),t.vt()}Ct(t,r){if("nullValue"in t)this.Ft(r,5);else if("booleanValue"in t)this.Ft(r,10),r.Mt(t.booleanValue?1:0);else if("integerValue"in t)this.Ft(r,15),r.Mt(py(t.integerValue));else if("doubleValue"in t){var e=py(t.doubleValue);isNaN(e)?this.Ft(r,13):(this.Ft(r,15),Bv(e)?r.Mt(0):r.Mt(e))}else if("timestampValue"in t){let e=t.timestampValue;this.Ft(r,20),"string"==typeof e&&(e=dy(e)),r.xt(""+(e.seconds||"")),r.Mt(e.nanos||0)}else"stringValue"in t?(this.Ot(t.stringValue,r),this.Nt(r)):"bytesValue"in t?(this.Ft(r,30),r.Bt(fy(t.bytesValue)),this.Nt(r)):"referenceValue"in t?this.Lt(t.referenceValue,r):"geoPointValue"in t?(e=t.geoPointValue,this.Ft(r,45),r.Mt(e.latitude||0),r.Mt(e.longitude||0)):"mapValue"in t?Hy(t)?this.Ft(r,Number.MAX_SAFE_INTEGER):Ky(t)?this.kt(t.mapValue,r):(this.qt(t.mapValue,r),this.Nt(r)):"arrayValue"in t?(this.Kt(t.arrayValue,r),this.Nt(r)):C(19022,{Ut:t})}Ot(e,t){this.Ft(t,25),this.$t(e,t)}$t(e,t){t.xt(e)}qt(e,t){var r=e.fields||{};this.Ft(t,55);for(let e of Object.keys(r))this.Ot(e,t),this.Ct(r[e],t)}kt(e,t){var r=e.fields||{},n=(this.Ft(t,53),Ny),i=r[n].arrayValue?.values?.length||0;this.Ft(t,15),t.Mt(py(i)),this.Ot(n,t),this.Ct(r[n],t)}Kt(e,t){var r=e.values||[];this.Ft(t,50);for(let e of r)this.Ct(e,t)}Lt(e,t){this.Ft(t,37),P.fromName(e).path.forEach(e=>{this.Ft(t,60),this.$t(e,t)})}Ft(e,t){e.Mt(t)}Nt(e){e.Mt(2)}}BI.Wt=new BI;function jI(e){var t=64-(e=>{let t=0;for(let n=0;n<8;++n){var r=(e=>{if(0===e)return 8;let t=0;return e>>4||(t+=4,e<<=4),e>>6||(t+=2,e<<=2),e>>7||(t+=1),t})(255&e[n]);if(t+=r,8!==r)break}return t})(e);return Math.ceil(t/8)}class zI{constructor(){this.buffer=new Uint8Array(1024),this.position=0}Qt(e){var t=e[Symbol.iterator]();let r=t.next();for(;!r.done;)this.Gt(r.value),r=t.next();this.zt()}jt(e){var t=e[Symbol.iterator]();let r=t.next();for(;!r.done;)this.Jt(r.value),r=t.next();this.Ht()}Zt(e){for(var t of e){let e=t.charCodeAt(0);if(e<128)this.Gt(e);else if(e<2048)this.Gt(960|e>>>6),this.Gt(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Gt(480|e>>>12),this.Gt(128|63&e>>>6),this.Gt(128|63&e);else{let e=t.codePointAt(0);this.Gt(240|e>>>18),this.Gt(128|63&e>>>12),this.Gt(128|63&e>>>6),this.Gt(128|63&e)}}this.zt()}Xt(e){for(var t of e){let e=t.charCodeAt(0);if(e<128)this.Jt(e);else if(e<2048)this.Jt(960|e>>>6),this.Jt(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Jt(480|e>>>12),this.Jt(128|63&e>>>6),this.Jt(128|63&e);else{let e=t.codePointAt(0);this.Jt(240|e>>>18),this.Jt(128|63&e>>>12),this.Jt(128|63&e>>>6),this.Jt(128|63&e)}}this.Ht()}Yt(e){var t=this.en(e),r=jI(t);this.tn(1+r),this.buffer[this.position++]=255&r;for(let n=t.length-r;n<t.length;++n)this.buffer[this.position++]=255&t[n]}nn(e){var t=this.en(e),r=jI(t);this.tn(1+r),this.buffer[this.position++]=~(255&r);for(let n=t.length-r;n<t.length;++n)this.buffer[this.position++]=~(255&t[n])}rn(){this.sn(255),this.sn(255)}_n(){this.an(255),this.an(255)}reset(){this.position=0}seed(e){this.tn(e.length),this.buffer.set(e,this.position),this.position+=e.length}un(){return this.buffer.slice(0,this.position)}en(e){e=e,(t=new DataView(new ArrayBuffer(8))).setFloat64(0,e,!1);var t,r=new Uint8Array(t.buffer),n=!!(128&r[0]);r[0]^=n?255:128;for(let i=1;i<r.length;++i)r[i]^=n?255:0;return r}Gt(e){var t=255&e;0==t?(this.sn(0),this.sn(255)):255==t?(this.sn(255),this.sn(0)):this.sn(t)}Jt(e){var t=255&e;0==t?(this.an(0),this.an(255)):255==t?(this.an(255),this.an(0)):this.an(e)}zt(){this.sn(0),this.sn(1)}Ht(){this.an(0),this.an(1)}sn(e){this.tn(1),this.buffer[this.position++]=e}an(e){this.tn(1),this.buffer[this.position++]=~e}tn(e){var t=e+this.position;if(!(t<=this.buffer.length)){let e=2*this.buffer.length;e<t&&(e=t);t=new Uint8Array(e);t.set(this.buffer),this.buffer=t}}}class KI{constructor(e){this.cn=e}Bt(e){this.cn.Qt(e)}xt(e){this.cn.Zt(e)}Mt(e){this.cn.Yt(e)}vt(){this.cn.rn()}}class WI{constructor(e){this.cn=e}Bt(e){this.cn.jt(e)}xt(e){this.cn.Xt(e)}Mt(e){this.cn.nn(e)}vt(){this.cn._n()}}class HI{constructor(){this.cn=new zI,this.ascending=new KI(this.cn),this.descending=new WI(this.cn)}seed(e){this.cn.seed(e)}ln(e){return 0===e?this.ascending:this.descending}un(){return this.cn.un()}reset(){this.cn.reset()}}class GI{constructor(e,t,r,n){this.hn=e,this.Pn=t,this.Tn=r,this.En=n}In(){var e=this.En.length,t=0===e||255===this.En[e-1]?e+1:e,r=new Uint8Array(t);return r.set(this.En,0),t!==e?r.set([0],this.En.length):++r[r.length-1],new GI(this.hn,this.Pn,this.Tn,r)}Rn(e,t,r){return{indexId:this.hn,uid:e,arrayValue:YI(this.Tn),directionalValue:YI(this.En),orderedDocumentKey:YI(t),documentKey:r.path.toArray()}}An(e,t,r){var n=this.Rn(e,t,r);return[n.indexId,n.uid,n.arrayValue,n.directionalValue,n.orderedDocumentKey,n.documentKey]}}function $I(e,t){var r=e.hn-t.hn;return 0!=r||0!==(r=QI(e.Tn,t.Tn))||0!==(r=QI(e.En,t.En))?r:P.comparator(e.Pn,t.Pn)}function QI(e,t){for(let n=0;n<e.length&&n<t.length;++n){var r=e[n]-t[n];if(0!=r)return r}return e.length-t.length}function YI(r){if(ce()){var n=r;let e="";for(let t=0;t<n.length;t++)e+=String.fromCharCode(n[t]);return e}return r}function JI(e){if("string"!=typeof e)return e;var t=e,r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}class XI{constructor(e){this.Vn=new L((e,t)=>ev.comparator(e.field,t.field)),this.collectionId=null!=e.collectionGroup?e.collectionGroup:e.path.lastSegment(),this.dn=e.orderBy,this.mn=[];for(var t of e.filters){let e=t;e.isInequality()?this.Vn=this.Vn.add(e):this.mn.push(e)}}get fn(){return 1<this.Vn.size}gn(e){if(S(e.collectionGroup===this.collectionId,49279),this.fn)return!1;let t=pv(e);if(void 0!==t&&!this.pn(t))return!1;var r=fv(e);let n=new Set,i=0,s=0;for(;i<r.length&&this.pn(r[i]);++i)n=n.add(r[i].fieldPath.canonicalString());if(i!==r.length){if(0<this.Vn.size){let t=this.Vn.getIterator().getNext();if(!n.has(t.field.canonicalString())){let e=r[i];if(!this.yn(t,e)||!this.wn(this.dn[s++],e))return!1}++i}for(;i<r.length;++i){let e=r[i];if(s>=this.dn.length||!this.wn(this.dn[s++],e))return!1}}return!0}Sn(){if(this.fn)return null;let e=new L(ev.comparator);var t,r,n=[];for(t of this.mn)t.field.isKeyField()||("array-contains"===t.op||"array-contains-any"===t.op?n.push(new gv(t.field,2)):e.has(t.field)||(e=e.add(t.field),n.push(new gv(t.field,0))));for(r of this.dn)r.field.isKeyField()||e.has(r.field)||(e=e.add(r.field),n.push(new gv(r.field,"asc"===r.dir?0:1)));return new dv(dv.UNKNOWN_ID,this.collectionId,n,mv.empty())}pn(e){for(var t of this.mn)if(this.yn(t,e))return!0;return!1}yn(e,t){var r;return!(void 0===e||!e.field.isEqual(t.fieldPath))&&(r="array-contains"===e.op||"array-contains-any"===e.op,2===t.kind==r)}wn(e,t){return!!e.field.isEqual(t.fieldPath)&&(0===t.kind&&"asc"===e.dir||1===t.kind&&"desc"===e.dir)}}function ZI(e){var t;return 0===e.getFilters().length?[]:(t=function t(e){if(S(e instanceof F||e instanceof U,34018),e instanceof F)return e;if(1===e.filters.length)return t(e.filters[0]);let r=e.filters.map(e=>t(e));let n=U.create(r,e.op);return n=sT(n),rT(n)?n:(S(n instanceof U,64498),S(nw(n),40251),S(1<n.filters.length,57927),n.filters.reduce((e,t)=>nT(e,t)))}(function t(r){if(S(r instanceof F||r instanceof U,20012),r instanceof F){if(r instanceof fw){let e=r.value.arrayValue?.values?.map(e=>F.create(r.field,"==",e))||[];return U.create(e,"or")}return r}let e=r.filters.map(e=>t(e));return U.create(e,r.op)}(e)),S(rT(t),7391),eT(t)||tT(t)?[t]:t.getFilters())}function eT(e){return e instanceof F}function tT(e){return e instanceof U&&sw(e)}function rT(e){return eT(e)||tT(e)||(e=>{if(e instanceof U&&iw(e)){for(var t of e.getFilters())if(!eT(t)&&!tT(t))return!1;return!0}return!1})(e)}function nT(e,t){var r,n;return S(e instanceof F||e instanceof U,38388),S(t instanceof F||t instanceof U,25473),sT(e instanceof F?t instanceof F?(r=e,n=t,U.create([r,n],"and")):iT(e,t):t instanceof F?iT(t,e):((e,t)=>{if(S(0<e.filters.length&&0<t.filters.length,48005),nw(e)&&nw(t))return ow(e,t.getFilters());let r=iw(e)?e:t,n=iw(e)?t:e,i=r.filters.map(e=>nT(e,n));return U.create(i,"or")})(e,t))}function iT(t,e){var r;return nw(e)?ow(e,t.getFilters()):(r=e.filters.map(e=>nT(t,e)),U.create(r,"or"))}function sT(t){if(S(t instanceof F||t instanceof U,11850),t instanceof F)return t;var e=t.getFilters();if(1===e.length)return sT(e[0]);if(aw(t))return t;let r=e.map(e=>sT(e)),n=[];return r.forEach(e=>{e instanceof F?n.push(e):e instanceof U&&(e.op===t.op?n.push(...e.filters):n.push(e))}),1===n.length?n[0]:U.create(n,t.op)}class aT{constructor(){this.bn=new oT}addToCollectionParentIndex(e,t){return this.bn.add(t),M.resolve()}getCollectionParents(e,t){return M.resolve(this.bn.getEntries(t))}addFieldIndex(e,t){return M.resolve()}deleteFieldIndex(e,t){return M.resolve()}deleteAllFieldIndexes(e){return M.resolve()}createTargetIndexes(e,t){return M.resolve()}getDocumentsMatchingTarget(e,t){return M.resolve(null)}getIndexType(e,t){return M.resolve(0)}getFieldIndexes(e,t){return M.resolve([])}getNextCollectionGroupToUpdate(e){return M.resolve(null)}getMinOffset(e,t){return M.resolve(yv.min())}getMinOffsetFromCollectionGroup(e,t){return M.resolve(yv.min())}updateCollectionGroup(e,t,r){return M.resolve()}updateIndexEntries(e,t){return M.resolve()}}class oT{constructor(){this.index={}}add(e){var t=e.lastSegment(),r=e.popLast(),n=this.index[t]||new L(R.comparator),i=!n.has(r);return this.index[t]=n.add(r),i}has(e){var t=e.lastSegment(),r=e.popLast(),t=this.index[t];return t&&t.has(r)}getEntries(e){return(this.index[e]||new L(R.comparator)).toArray()}}let lT="IndexedDbIndexManager",hT=new Uint8Array(0);class cT{constructor(e,t){this.databaseId=t,this.Dn=new oT,this.Cn=new qw(e=>yw(e),(e,t)=>ww(e,t)),this.uid=e.uid||""}addToCollectionParentIndex(e,t){var r,n;return this.Dn.has(t)?M.resolve():(n=t.lastSegment(),r=t.popLast(),e.addOnCommittedListener(()=>{this.Dn.add(t)}),n={collectionId:n,parent:Kv(r)},uT(e).put(n))}getCollectionParents(e,r){let n=[],t=IDBKeyRange.bound([r,""],[Ym(r),""],!1,!0);return uT(e).J(t).next(e=>{for(var t of e){if(t.collectionId!==r)break;n.push(Hv(t.parent))}return n})}addFieldIndex(e,r){let t=pT(e),n={indexId:r.indexId,collectionGroup:r.collectionGroup,fields:r.fields.map(e=>[e.fieldPath.canonicalString(),e.kind])};delete n.indexId;var i=t.add(n);if(r.indexState){let t=fT(e);return i.next(e=>{t.put(OI(e,this.uid,r.indexState.sequenceNumber,r.indexState.offset))})}return i.next()}deleteFieldIndex(e,t){let r=pT(e),n=fT(e),i=dT(e);return r.delete(t.indexId).next(()=>n.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0))).next(()=>i.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0)))}deleteAllFieldIndexes(e){let t=pT(e),r=dT(e),n=fT(e);return t.X().next(()=>r.X()).next(()=>n.X())}createTargetIndexes(r,e){return M.forEach(this.vn(e),t=>this.getIndexType(r,t).next(e=>{if(0===e||1===e){let e=new XI(t).Sn();if(null!=e)return this.addFieldIndex(r,e)}}))}getDocumentsMatchingTarget(e,u){let d=dT(e),r=!0,n=new Map;return M.forEach(this.vn(u),t=>this.Fn(e,t).next(e=>{r=r&&!!e,n.set(t,e)})).next(()=>{if(r){let h=V(),c=[];return M.forEach(n,(e,t)=>{E(lT,`Using index ${r=e,`id=${r.indexId}|cg=${r.collectionGroup}|f=`+r.fields.map(e=>e.fieldPath+":"+e.kind).join(",")} to execute `+yw(u));var r,n=((t,e)=>{var r=pv(e);if(void 0!==r)for(let e of Iw(t,r.fieldPath))switch(e.op){case"array-contains-any":return e.value.arrayValue.values||[];case"array-contains":return[e.value]}return null})(t,e),i=((t,r)=>{var n,i=new Map;for(n of fv(r))for(let e of Iw(t,n.fieldPath))switch(e.op){case"==":case"in":i.set(n.fieldPath.canonicalString(),e.value);break;case"not-in":case"!=":return i.set(n.fieldPath.canonicalString(),e.value),Array.from(i.values())}return null})(t,e),s=((t,e)=>{var r,n=[];let i=!0;for(r of fv(e)){let e=(0===r.kind?Tw:Ew)(t,r.fieldPath,t.startAt);n.push(e.value),i=i&&e.inclusive}return new Xy(n,i)})(t,e),a=((t,e)=>{var r,n=[];let i=!0;for(r of fv(e)){let e=(0===r.kind?Ew:Tw)(t,r.fieldPath,t.endAt);n.push(e.value),i=i&&e.inclusive}return new Xy(n,i)})(t,e),o=this.Mn(e,t,s),l=this.Mn(e,t,a),i=this.xn(e,t,i),n=this.On(e.indexId,n,o,s.inclusive,l,a.inclusive,i);return M.forEach(n,e=>d.Z(e,u.limit).next(e=>{e.forEach(e=>{var t=P.fromSegments(e.documentKey);h.has(t)||(h=h.add(t),c.push(t))})}))}).next(()=>c)}return M.resolve(null)})}vn(t){let e=this.Cn.get(t);return e||(e=0===t.filters.length?[t]:ZI(U.create(t.filters,"and")).map(e=>_w(t.path,t.collectionGroup,t.orderBy,e.getFilters(),t.limit,t.startAt,t.endAt)),this.Cn.set(t,e)),e}On(i,s,a,o,l,h,c){let e=(null!=s?s.length:1)*Math.max(a.length,l.length),u=e/(null!=s?s.length:1),d=[];for(let p=0;p<e;++p){let t=s?this.Nn(s[p/u]):hT,e=this.Bn(i,t,a[p%u],o),r=this.Ln(i,t,l[p%u],h),n=c.map(e=>this.Bn(i,t,e,!0));d.push(...this.createRange(e,r,n))}return d}Bn(e,t,r,n){var i=new GI(e,P.empty(),t,r);return n?i:i.In()}Ln(e,t,r,n){var i=new GI(e,P.empty(),t,r);return n?i.In():i}Fn(e,t){let n=new XI(t),r=null!=t.collectionGroup?t.collectionGroup:t.path.lastSegment();return this.getFieldIndexes(e,r).next(e=>{let t=null;for(var r of e)n.gn(r)&&(!t||r.fields.length>t.fields.length)&&(t=r);return t})}getIndexType(e,t){let r=2,n=this.vn(t);return M.forEach(n,t=>this.Fn(e,t).next(e=>{e?0!==r&&e.fields.length<(t=>{let r=new L(ev.comparator),n=!1;for(var i of t.filters)for(let e of i.getFlattenedFilters())e.field.isKeyField()||("array-contains"===e.op||"array-contains-any"===e.op?n=!0:r=r.add(e.field));for(let n of t.orderBy)n.field.isKeyField()||(r=r.add(n.field));return r.size+(n?1:0)})(t)&&(r=1):r=0})).next(()=>null!==t.limit&&1<n.length&&2===r?1:r)}kn(e,t){var r,n=new HI;for(r of fv(e)){let e=t.data.field(r.fieldPath);if(null==e)return null;var i=n.ln(r.kind);BI.Wt.Dt(e,i)}return n.un()}Nn(e){var t=new HI;return BI.Wt.Dt(e,t.ln(0)),t.un()}qn(e,t){var r,n=new HI;return BI.Wt.Dt(Uy(this.databaseId,t),n.ln(0===(r=fv(e)).length?0:r[r.length-1].kind)),n.un()}xn(e,n,i){if(null===i)return[];let s=[],a=(s.push(new HI),0);for(var o of fv(e)){let t=i[a++];for(let r of s)if(this.Kn(n,o.fieldPath)&&qy(t))s=this.Un(s,o,t);else{let e=r.ln(o.kind);BI.Wt.Dt(t,e)}}return this.$n(s)}Mn(e,t,r){return this.xn(e,t,r.position)}$n(e){var t=[];for(let r=0;r<e.length;++r)t[r]=e[r].un();return t}Un(r,n,e){let i=[...r],s=[];for(let r of e.arrayValue.values||[])for(let t of i){let e=new HI;e.seed(t.un()),BI.Wt.Dt(r,e.ln(n.kind)),s.push(e)}return s}Kn(e,t){return!!e.filters.find(e=>e instanceof F&&e.field.isEqual(t)&&("in"===e.op||"not-in"===e.op))}getFieldIndexes(e,t){let r=pT(e),n=fT(e);return(t?r.J(A_,IDBKeyRange.bound(t,t)):r.J()).next(e=>{let s=[];return M.forEach(e,i=>n.get([i.indexId,this.uid]).next(e=>{var t,r,n;s.push((t=i,r=(e=e)?new mv(e.sequenceNumber,new yv(kI(e.readTime),new P(Hv(e.documentKey)),e.largestBatchId)):mv.empty(),n=t.fields.map(([e,t])=>new gv(ev.fromServerFormat(e),t)),new dv(t.indexId,t.collectionGroup,n,r)))})).next(()=>s)})}getNextCollectionGroupToUpdate(e){return this.getFieldIndexes(e).next(e=>0===e.length?null:(e.sort((e,t)=>{var r=e.indexState.sequenceNumber-t.indexState.sequenceNumber;return 0!=r?r:N(e.collectionGroup,t.collectionGroup)}),e[0].collectionGroup))}updateCollectionGroup(e,r,n){let i=pT(e),s=fT(e);return this.Wn(e).next(t=>i.J(A_,IDBKeyRange.bound(r,r)).next(e=>M.forEach(e,e=>s.put(OI(e.indexId,this.uid,t,n)))))}updateIndexEntries(i,e){let r=new Map;return M.forEach(e,(t,n)=>{var e=r.get(t.collectionGroup);return(e?M.resolve(e):this.getFieldIndexes(i,t.collectionGroup)).next(e=>(r.set(t.collectionGroup,e),M.forEach(e,r=>this.Qn(i,t,r).next(e=>{var t=this.Gn(n,r);return e.isEqual(t)?M.resolve():this.zn(i,n,r,e,t)}))))})}jn(e,t,r,n){return dT(e).put(n.Rn(this.uid,this.qn(r,t.key),t.key))}Jn(e,t,r,n){return dT(e).delete(n.An(this.uid,this.qn(r,t.key),t.key))}Qn(e,r,n){var t=dT(e);let i=new L($I);return t.ee({index:M_,range:IDBKeyRange.only([n.indexId,this.uid,YI(this.qn(n,r))])},(e,t)=>{i=i.add(new GI(n.indexId,r,JI(t.arrayValue),JI(t.directionalValue)))}).next(()=>i)}Gn(t,r){let n=new L($I);var i=this.kn(r,t);if(null!=i){let e=pv(r);if(null!=e){var s=t.data.field(e.fieldPath);if(qy(s))for(let e of s.arrayValue.values||[])n=n.add(new GI(r.indexId,t.key,this.Nn(e),i))}else n=n.add(new GI(r.indexId,t.key,hT,i))}return n}zn(t,r,s,e,a){E(lT,"Updating index entries for document '%s'",r.key);let o=[];{var l=$I,h=e=>{o.push(this.jn(t,r,s,e))},c=e=>{o.push(this.Jn(t,r,s,e))},u=e.getIterator(),d=a.getIterator();let n=oy(u),i=oy(d);for(;n||i;){let t=!1,r=!1;if(n&&i){let e=l(n,i);e<0?r=!0:0<e&&(t=!0)}else null!=n?r=!0:t=!0;t?(h(i),i=oy(d)):r?(c(n),n=oy(u)):(n=oy(u),i=oy(d))}}return M.waitFor(o)}Wn(e){let n=1;return fT(e).ee({index:P_,reverse:!0,range:IDBKeyRange.upperBound([this.uid,Number.MAX_SAFE_INTEGER])},(e,t,r)=>{r.done(),n=t.sequenceNumber+1}).next(()=>n)}createRange(r,n,e){e=e.sort((e,t)=>$I(e,t)).filter((e,t,r)=>!t||0!==$I(e,r[t-1]));var i=[];i.push(r);for(let s of e){let e=$I(s,r),t=$I(s,n);if(0===e)i[0]=r.In();else if(0<e&&t<0)i.push(s),i.push(s.In());else if(0<t)break}i.push(n);let s=[];for(let a=0;a<i.length;a+=2){if(this.Hn(i[a],i[a+1]))return[];let e=i[a].An(this.uid,hT,P.empty()),t=i[a+1].An(this.uid,hT,P.empty());s.push(IDBKeyRange.bound(e,t))}return s}Hn(e,t){return 0<$I(e,t)}getMinOffsetFromCollectionGroup(e,t){return this.getFieldIndexes(e,t).next(gT)}getMinOffset(t,e){return M.mapArray(this.vn(e),e=>this.Fn(t,e).next(e=>e||C(44426))).next(gT)}}function uT(e){return Z_(e,I_)}function dT(e){return Z_(e,x_)}function pT(e){return Z_(e,k_)}function fT(e){return Z_(e,N_)}function gT(e){S(0!==e.length,28825);let t=e[0].indexState.offset,r=t.largestBatchId;for(let i=1;i<e.length;i++){var n=e[i].indexState.offset;wv(n,t)<0&&(t=n),r<n.largestBatchId&&(r=n.largestBatchId)}return new yv(t.readTime,t.documentKey,r)}let mT={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class vT{static withCacheSize(e){return new vT(e,vT.DEFAULT_COLLECTION_PERCENTILE,vT.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}constructor(e,t,r){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=r}}function _T(t,r,n){let e=t.store(Jv),i=t.store(i_),s=[],a=IDBKeyRange.only(n.batchId),o=0;var l=e.ee({range:a},(e,t,r)=>(o++,r.delete()));s.push(l.next(()=>{S(1===o,47070,{batchId:n.batchId})}));let h=[];for(let t of n.mutations){let e=r_(r,t.key.path,n.batchId);s.push(i.delete(e)),h.push(t.key)}return M.waitFor(s).next(()=>h)}function yT(e){if(!e)return 0;let t;if(e.document)t=e.document;else if(e.unknownDocument)t=e.unknownDocument;else{if(!e.noDocument)throw C(14731);t=e.noDocument}return JSON.stringify(t).length}vT.DEFAULT_COLLECTION_PERCENTILE=10,vT.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,vT.DEFAULT=new vT(41943040,vT.DEFAULT_COLLECTION_PERCENTILE,vT.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),vT.DISABLED=new vT(-1,0,0);class wT{constructor(e,t,r,n){this.userId=e,this.serializer=t,this.indexManager=r,this.referenceDelegate=n,this.Zn={}}static wt(e,t,r,n){S(""!==e.uid,64387);var i=e.isAuthenticated()?e.uid:"";return new wT(i,t,r,n)}checkEmpty(e){let n=!0;var t=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return IT(e).ee({index:Zv,range:t},(e,t,r)=>{n=!1,r.done()}).next(()=>n)}addMutationBatch(u,d,p,f){let g=TT(u),m=IT(u);return m.add({}).next(t=>{S("number"==typeof t,49019);let e=new Tb(t,d,p,f),r=(i=this.serializer,s=this.userId,a=e,o=a.baseMutations.map(e=>hI(i.yt,e)),l=a.mutations.map(e=>hI(i.yt,e)),{userId:s,batchId:a.batchId,localWriteTimeMs:a.localWriteTime.toMillis(),baseMutations:o,mutations:l}),n=[];var i,s,a,o,l;let h=new L((e,t)=>N(e.canonicalString(),t.canonicalString()));for(let c of f){let e=r_(this.userId,c.key.path,t);h=h.add(c.key.path.popLast()),n.push(m.put(r)),n.push(g.put(e,n_))}return h.forEach(e=>{n.push(this.indexManager.addToCollectionParentIndex(u,e))}),u.addOnCommittedListener(()=>{this.Zn[t]=e.keys()}),M.waitFor(n).next(()=>e)})}lookupMutationBatch(e,t){return IT(e).get(t).next(e=>e?(S(e.userId===this.userId,48,"Unexpected user for mutation batch",{userId:e.userId,batchId:t}),AI(this.serializer,e)):null)}Xn(e,r){return this.Zn[r]?M.resolve(this.Zn[r]):this.lookupMutationBatch(e,r).next(e=>{var t;return e?(t=e.keys(),this.Zn[r]=t):null})}getNextMutationBatchAfterBatchId(e,t){let n=t+1,r=IDBKeyRange.lowerBound([this.userId,n]),i=null;return IT(e).ee({index:Zv,range:r},(e,t,r)=>{t.userId===this.userId&&(S(t.batchId>=n,47524,{Yn:n}),i=AI(this.serializer,t)),r.done()}).next(()=>i)}getHighestUnacknowledgedBatchId(e){var t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let n=Vv;return IT(e).ee({index:Zv,range:t,reverse:!0},(e,t,r)=>{n=t.batchId,r.done()}).next(()=>n)}getAllMutationBatches(e){var t=IDBKeyRange.bound([this.userId,Vv],[this.userId,Number.POSITIVE_INFINITY]);return IT(e).J(Zv,t).next(e=>e.map(e=>AI(this.serializer,e)))}getAllMutationBatchesAffectingDocumentKey(o,l){let e=t_(this.userId,l.path),t=IDBKeyRange.lowerBound(e),h=[];return TT(o).ee({range:t},(t,e,r)=>{let[n,i,s]=t,a=Hv(i);if(n===this.userId&&l.path.isEqual(a))return IT(o).get(s).next(e=>{if(!e)throw C(61480,{er:t,batchId:s});S(e.userId===this.userId,10503,"Unexpected user for mutation batch",{userId:e.userId,batchId:s}),h.push(AI(this.serializer,e))});r.done()}).next(()=>h)}getAllMutationBatchesAffectingDocumentKeys(t,e){let o=new L(N),r=[];return e.forEach(a=>{var e=t_(this.userId,a.path),e=IDBKeyRange.lowerBound(e),e=TT(t).ee({range:e},(e,t,r)=>{var[n,i,s]=e,i=Hv(i);n===this.userId&&a.path.isEqual(i)?o=o.add(s):r.done()});r.push(e)}),M.waitFor(r).next(()=>this.tr(t,o))}getAllMutationBatchesAffectingQuery(e,t){let a=t.path,o=a.length+1,r=t_(this.userId,a),n=IDBKeyRange.lowerBound(r),l=new L(N);return TT(e).ee({range:n},(e,t,r)=>{var[n,i,s]=e,i=Hv(i);n===this.userId&&a.isPrefixOf(i)?i.length===o&&(l=l.add(s)):r.done()}).next(()=>this.tr(e,l))}tr(e,t){let r=[],n=[];return t.forEach(t=>{n.push(IT(e).get(t).next(e=>{if(null===e)throw C(35274,{batchId:t});S(e.userId===this.userId,9748,"Unexpected user for mutation batch",{userId:e.userId,batchId:t}),r.push(AI(this.serializer,e))}))}),M.waitFor(n).next(()=>r)}removeMutationBatch(t,r){return _T(t.le,this.userId,r).next(e=>(t.addOnCommittedListener(()=>{this.nr(r.batchId)}),M.forEach(e,e=>this.referenceDelegate.markPotentiallyOrphaned(t,e))))}nr(e){delete this.Zn[e]}performConsistencyCheck(r){return this.checkEmpty(r).next(e=>{if(!e)return M.resolve();let t=IDBKeyRange.lowerBound([this.userId]),n=[];return TT(r).ee({range:t},(t,e,r)=>{if(t[0]===this.userId){let e=Hv(t[1]);n.push(e)}else r.done()}).next(()=>{S(0===n.length,56720,{rr:n.map(e=>e.canonicalString())})})})}containsKey(e,t){return bT(e,this.userId,t)}ir(e){return ET(e).get(this.userId).next(e=>e||{userId:this.userId,lastAcknowledgedBatchId:Vv,lastStreamToken:""})}}function bT(e,s,t){let r=t_(s,t.path),a=r[1],n=IDBKeyRange.lowerBound(r),o=!1;return TT(e).ee({range:n,Y:!0},(e,t,r)=>{var[n,i,,]=e;n===s&&i===a&&(o=!0),r.done()}).next(()=>o)}function IT(e){return Z_(e,Jv)}function TT(e){return Z_(e,i_)}function ET(e){return Z_(e,Yv)}class CT{constructor(e){this.sr=e}next(){return this.sr+=2,this.sr}static _r(){return new CT(0)}static ar(){return new CT(-1)}}class ST{constructor(e,t){this.referenceDelegate=e,this.serializer=t}allocateTargetId(r){return this.ur(r).next(e=>{var t=new CT(e.highestTargetId);return e.highestTargetId=t.next(),this.cr(r,e).next(()=>e.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.ur(e).next(e=>O.fromTimestamp(new x(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.ur(e).next(e=>e.highestListenSequenceNumber)}setTargetsMetadata(t,r,n){return this.ur(t).next(e=>(e.highestListenSequenceNumber=r,n&&(e.lastRemoteSnapshotVersion=n.toTimestamp()),e.highestListenSequenceNumber<r&&(e.highestListenSequenceNumber=r),this.cr(t,e)))}addTargetData(t,r){return this.lr(t,r).next(()=>this.ur(t).next(e=>(e.targetCount+=1,this.hr(r,e),this.cr(t,e))))}updateTargetData(e,t){return this.lr(e,t)}removeTargetData(t,e){return this.removeMatchingKeysForTargetId(t,e.targetId).next(()=>kT(t).delete(e.targetId)).next(()=>this.ur(t)).next(e=>(S(0<e.targetCount,8065),--e.targetCount,this.cr(t,e)))}removeTargets(n,i,s){let a=0,o=[];return kT(n).ee((e,t)=>{var r=NI(t);r.sequenceNumber<=i&&null===s.get(r.targetId)&&(a++,o.push(this.removeTargetData(n,r)))}).next(()=>M.waitFor(o)).next(()=>a)}forEachTarget(e,n){return kT(e).ee((e,t)=>{var r=NI(t);n(r)})}ur(e){return AT(e).get(w_).next(e=>(S(null!==e,2888),e))}cr(e,t){return AT(e).put(w_,t)}lr(e,t){return kT(e).put(RI(this.serializer,t))}hr(e,t){let r=!1;return e.targetId>t.highestTargetId&&(t.highestTargetId=e.targetId,r=!0),t.highestListenSequenceNumber<e.sequenceNumber&&(t.highestListenSequenceNumber=e.sequenceNumber,r=!0),r}getTargetCount(e){return this.ur(e).next(e=>e.targetCount)}getTargetData(e,i){var t=yw(i),t=IDBKeyRange.bound([t,Number.NEGATIVE_INFINITY],[t,Number.POSITIVE_INFINITY]);let s=null;return kT(e).ee({range:t,index:f_},(e,t,r)=>{var n=NI(t);ww(i,n.target)&&(s=n,r.done())}).next(()=>s)}addMatchingKeys(r,e,n){let i=[],s=NT(r);return e.forEach(e=>{var t=Kv(e.path);i.push(s.put({targetId:n,path:t})),i.push(this.referenceDelegate.addReference(r,n,e))}),M.waitFor(i)}removeMatchingKeys(r,e,n){let i=NT(r);return M.forEach(e,e=>{var t=Kv(e.path);return M.waitFor([i.delete([n,t]),this.referenceDelegate.removeReference(r,n,e)])})}removeMatchingKeysForTargetId(e,t){var r=NT(e),n=IDBKeyRange.bound([t],[t+1],!1,!0);return r.delete(n)}getMatchingKeysForTargetId(e,t){var r=IDBKeyRange.bound([t],[t+1],!1,!0),n=NT(e);let i=V();return n.ee({range:r,Y:!0},(e,t,r)=>{var n=Hv(e[1]),n=new P(n);i=i.add(n)}).next(()=>i)}containsKey(e,t){var r=Kv(t.path),r=IDBKeyRange.bound([r],[Ym(r)],!1,!0);let n=0;return NT(e).ee({index:__,Y:!0,range:r},([e],t,r)=>{0!==e&&(n++,r.done())}).next(()=>0<n)}At(e,t){return kT(e).get(t).next(e=>e?NI(e):null)}}function kT(e){return Z_(e,p_)}function AT(e){return Z_(e,b_)}function NT(e){return Z_(e,m_)}let RT="LruGarbageCollector";function PT([e,t],[r,n]){var i=N(e,r);return 0===i?N(t,n):i}class DT{constructor(e){this.Pr=e,this.buffer=new L(PT),this.Tr=0}Er(){return++this.Tr}Ir(e){var t=[e,this.Er()];if(this.buffer.size<this.Pr)this.buffer=this.buffer.add(t);else{let e=this.buffer.last();PT(t,e)<0&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class xT{constructor(e,t,r){this.garbageCollector=e,this.asyncQueue=t,this.localStore=r,this.Rr=null}start(){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.Ar(6e4)}stop(){this.Rr&&(this.Rr.cancel(),this.Rr=null)}get started(){return null!==this.Rr}Ar(e){E(RT,`Garbage collection scheduled in ${e}ms`),this.Rr=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,async()=>{this.Rr=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){Rv(e)?E(RT,"Ignoring IndexedDB error during garbage collection: ",e):await Tv(e)}await this.Ar(3e5)})}}class OT{constructor(e,t){this.Vr=e,this.params=t}calculateTargetCount(e,t){return this.Vr.dr(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return M.resolve(Uv.ce);let r=new DT(t);return this.Vr.forEachTarget(e,e=>r.Ir(e.sequenceNumber)).next(()=>this.Vr.mr(e,e=>r.Ir(e))).next(()=>r.maxValue)}removeTargets(e,t,r){return this.Vr.removeTargets(e,t,r)}removeOrphanedDocuments(e,t){return this.Vr.removeOrphanedDocuments(e,t)}collect(t,r){return-1===this.params.cacheSizeCollectionThreshold?(E("LruGarbageCollector","Garbage collection skipped; disabled"),M.resolve(mT)):this.getCacheSize(t).next(e=>e<this.params.cacheSizeCollectionThreshold?(E("LruGarbageCollector",`Garbage collection skipped; Cache size ${e} is lower than threshold `+this.params.cacheSizeCollectionThreshold),mT):this.gr(t,r))}getCacheSize(e){return this.Vr.getCacheSize(e)}gr(t,r){let n,i,s,a,o,l,h,c=Date.now();return this.calculateTargetCount(t,this.params.percentileToCollect).next(e=>(i=e>this.params.maximumSequenceNumbersToCollect?(E("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from `+e),this.params.maximumSequenceNumbersToCollect):e,a=Date.now(),this.nthSequenceNumber(t,i))).next(e=>(n=e,o=Date.now(),this.removeTargets(t,n,r))).next(e=>(s=e,l=Date.now(),this.removeOrphanedDocuments(t,n))).next(e=>(h=Date.now(),Rm()<=p.DEBUG&&E("LruGarbageCollector",`LRU Garbage Collection
|
|
@@ -23,5 +23,5 @@ For the CDN builds, these are available in the following manner
|
|
|
23
23
|
(replace <PACKAGE> with the name of a component - i.e. auth, database, etc):
|
|
24
24
|
|
|
25
25
|
https://www.gstatic.com/firebasejs/5.0.0/firebase-<PACKAGE>.js
|
|
26
|
-
`),or.registerVersion("firebase","12.12.
|
|
26
|
+
`),or.registerVersion("firebase","12.12.1","compat-cdn"),or});
|
|
27
27
|
//# sourceMappingURL=firebase-compat.js.map
|