firebase 11.3.0 → 11.3.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-analytics.js +1 -1
- package/firebase-app-check.js +1 -1
- package/firebase-app-compat.js +2 -2
- package/firebase-app.js +5 -5
- 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 +9 -9
- package/firebase-compat.js.map +1 -1
- package/firebase-data-connect.js +1 -1
- package/firebase-database.js +1 -1
- package/firebase-firestore-compat.js +5 -5
- package/firebase-firestore-compat.js.map +1 -1
- package/firebase-firestore-lite.js +1 -1
- package/firebase-firestore-lite.js.map +1 -1
- package/firebase-firestore.js +1 -1
- package/firebase-firestore.js.map +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 +5 -5
- package/firebase-performance.js +1 -1
- package/firebase-remote-config-compat.js.map +1 -1
- package/firebase-remote-config.js +1 -1
- package/firebase-remote-config.js.map +1 -1
- package/firebase-storage.js +1 -1
- package/firebase-vertexai.js +1 -1
- package/package.json +5 -5
package/firebase-compat.js
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
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={NODE_CLIENT:!1,NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"},g=function(e,t){if(!e)throw j(t)},j=function(e){return new Error("Firebase Database ("+n.SDK_VERSION+") INTERNAL ASSERT FAILED: "+e)},i=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},s={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 u=0;u<r.length;u+=3){var s=r[u],a=u+1<r.length,o=a?r[u+1]:0,l=u+2<r.length,h=l?r[u+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(i(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 B;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 B extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}function a(e){var t=i(e);return s.encodeByteArray(t,!0)}let o=function(e){return a(e).replace(/\./g,"")},z=function(e){try{return s.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function K(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]=K(e[r],t[r]));return e}function W(){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 H=()=>W().__FIREBASE_DEFAULTS__,G=()=>{var e;return"undefined"!=typeof process&&void 0!==process.env&&(e=process.env.__FIREBASE_DEFAULTS__)?JSON.parse(e):void 0},$=()=>{if("undefined"!=typeof document){let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}var t=e&&z(e[1]);return t&&JSON.parse(t)}},Q=()=>{try{return H()||G()||$()}catch(e){console.info("Unable to get __FIREBASE_DEFAULTS__ due to: "+e)}},Y=()=>{var e;return null==(e=Q())?void 0:e.config};var c,J;class X{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 Z(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=Object.assign({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),[o(JSON.stringify({alg:"none",type:"JWT"})),o(JSON.stringify(r)),""].join(".");throw new Error("mockUserToken must contain 'sub' or 'user_id' field!")}function ee(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function te(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(ee())}function re(){var e=null==(e=Q())?void 0:e.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 ne(){return"undefined"!=typeof WorkerGlobalScope&&"undefined"!=typeof self&&self instanceof WorkerGlobalScope}function ie(){var e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}function se(){return"object"==typeof navigator&&"ReactNative"===navigator.product}function ae(){var e=ee();return 0<=e.indexOf("MSIE ")||0<=e.indexOf("Trident/")}function oe(){return!0===n.NODE_ADMIN}function le(){return!re()&&navigator.userAgent&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}function he(){try{return"object"==typeof indexedDB}catch(e){return!1}}function ue(){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=()=>{var e;i((null==(e=r.error)?void 0:e.message)||"")}}catch(e){i(e)}})}function ce(){return!("undefined"==typeof navigator||!navigator.cookieEnabled)}class de extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name="FirebaseError",Object.setPrototypeOf(this,de.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,pe.prototype.create)}}class pe{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(fe,(e,t)=>{var r=n[t];return null!=r?String(r):`<${t}?>`})):"Error",s=this.serviceName+`: ${s} (${i}).`;return new de(i,s,r)}}let fe=/\{\$([^}]+)}/g;function ge(e){return JSON.parse(e)}function me(e){return JSON.stringify(e)}function ve(e){let t={},r={},n={},i="";try{var s=e.split(".");t=ge(z(s[0])||""),r=ge(z(s[1])||""),i=s[2],n=r.d||{},delete r.d}catch(e){}return{header:t,claims:r,data:n,signature:i}}function _e(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ye(e,t){if(Object.prototype.hasOwnProperty.call(e,t))return e[t]}function we(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function be(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 Ie(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(Te(a)&&Te(o)){if(!Ie(a,o))return!1}else if(a!==o)return!1}for(n of s)if(!i.includes(n))return!1}return!0}function Te(e){return null!==e&&"object"==typeof e}function Ee(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 Ce(e){let n={};return e.replace(/^\?/,"").split("&").forEach(e=>{var t,r;e&&([t,r]=e.split("="),n[decodeURIComponent(t)]=decodeURIComponent(r))}),n}function ke(e){var t,r=e.indexOf("?");return r?(t=e.indexOf("#",r),e.substring(r,0<t?t:void 0)):""}class Se{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,u;for(let p=0;p<80;p++){u=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 c=(t<<5|t>>>27)+h+l+u+i[p]&4294967295;l=o,o=a,a=4294967295&(s<<30|s>>>2),s=t,t=c}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 Ae(e,t){var r=new Ne(e,t);return r.subscribe.bind(r)}class Ne{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=Re),void 0===n.error&&(n.error=Re),void 0===n.complete&&(n.complete=Re);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 Re(){}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 Pe(e,t){return e+` failed: ${t} argument `}function De(e,t,r,n){if((!n||r)&&"function"!=typeof r)throw new Error(Pe(e,t)+"must be a valid function.")}function xe(e,t,r,n){if((!n||r)&&("object"!=typeof r||null===r))throw new Error(Pe(e,t)+"must be a valid context object.")}let Oe=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},Le=1e3,Me=2,Fe=144e5,Ue=.5;function Ve(e,t=Le,r=Me){var n=t*Math.pow(r,e),i=Math.round(Ue*n*(Math.random()-.5)*2);return Math.min(Fe,n+i)}function w(e){return e&&e._delegate?e._delegate:e}class u{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 qe="[DEFAULT]";class je{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 X;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(null==e?void 0:e.identifier),r=null!=(r=null==e?void 0:e.optional)&&r;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:qe})}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=qe){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=qe){return this.instances.has(e)}getOptions(e=qe){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=null!=(i=this.onInitCallbacks.get(r))?i: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(e){}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let r=this.instances.get(e);if(!r&&this.component&&(r=this.component.instanceFactory(this.container,{instanceIdentifier:(n=e)===qe?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(e){}var n;return r||null}normalizeInstanceIdentifier(e=qe){return!this.component||this.component.multipleInstances?e:qe}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class Be{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 je(e,this),this.providers.set(e,t),t)}getProviders(){return Array.from(this.providers.values())}}let ze=[],Ke=((t=c=c||{})[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:c.DEBUG,verbose:c.VERBOSE,info:c.INFO,warn:c.WARN,error:c.ERROR,silent:c.SILENT}),We=c.INFO,He={[c.DEBUG]:"log",[c.VERBOSE]:"log",[c.INFO]:"info",[c.WARN]:"warn",[c.ERROR]:"error"},Ge=(e,t,...r)=>{if(!(t<e.logLevel)){var n=(new Date).toISOString(),i=He[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${n}] ${e.name}:`,...r)}};class $e{constructor(e){this.name=e,this._logLevel=We,this._logHandler=Ge,this._userLogHandler=null,ze.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in c))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?Ke[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,c.DEBUG,...e),this._logHandler(this,c.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,c.VERBOSE,...e),this._logHandler(this,c.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,c.INFO,...e),this._logHandler(this,c.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,c.WARN,...e),this._logHandler(this,c.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,c.ERROR,...e),this._logHandler(this,c.ERROR,...e)}}let Qe=(t,e)=>e.some(e=>t instanceof e),Ye,Je;let Xe=new WeakMap,Ze=new WeakMap,et=new WeakMap,tt=new WeakMap,rt=new WeakMap;let nt={get(e,t,r){if(e instanceof IDBTransaction){if("done"===t)return Ze.get(e);if("objectStoreNames"===t)return e.objectStoreNames||et.get(e);if("store"===t)return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return at(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 it(n){return n!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(Je=Je||[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey]).includes(n)?function(...e){return n.apply(ot(this),e),at(Xe.get(this))}:function(...e){return at(n.apply(ot(this),e))}:function(e,...t){var r=n.call(ot(this),e,...t);return et.set(r,e.sort?e.sort():[e]),at(r)}}function st(e){var s,t;return"function"==typeof e?it(e):(e instanceof IDBTransaction&&(s=e,Ze.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)}),Ze.set(s,t))),Qe(e,Ye=Ye||[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])?new Proxy(e,nt):e)}function at(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(at(s.result)),r()},i=()=>{t(s.error),r()};s.addEventListener("success",n),s.addEventListener("error",i)})).then(e=>{e instanceof IDBCursor&&Xe.set(e,s)}).catch(()=>{}),rt.set(t,s),t):tt.has(e)?tt.get(e):((t=st(e))!==e&&(tt.set(e,t),rt.set(t,e)),t)}let ot=e=>rt.get(e);function lt(e,t,{blocked:r,upgrade:n,blocking:i,terminated:s}={}){let a=indexedDB.open(e,t);var o=at(a);return n&&a.addEventListener("upgradeneeded",e=>{n(at(a.result),e.oldVersion,e.newVersion,at(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 ht(e,{blocked:t}={}){var r=indexedDB.deleteDatabase(e);return t&&r.addEventListener("blocked",e=>t(e.oldVersion,e)),at(r).then(()=>{})}let ut=["get","getKey","getAll","getAllKeys","count"],ct=["put","add","delete","clear"],dt=new Map;function pt(e,t){if(e instanceof IDBDatabase&&!(t in e)&&"string"==typeof t){if(dt.get(t))return dt.get(t);let i=t.replace(/FromIndex$/,""),s=t!==i,a=ct.includes(i);var r;return i in(s?IDBIndex:IDBObjectStore).prototype&&(a||ut.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]},dt.set(t,r),r):void 0}}nt={...J=nt,get:(e,t,r)=>pt(e,t)||J.get(e,t,r),has:(e,t)=>!!pt(e,t)||J.has(e,t)};class ft{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(e=>{var t;return"VERSION"===(null==(t=e.getComponent())?void 0:t.type)?(t=e.getImmediate()).library+"/"+t.version:null}).filter(e=>e).join(" ")}}let gt="@firebase/app",mt="0.11.0",vt=new $e("@firebase/app");let _t="[DEFAULT]",yt={"@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/vertexai":"fire-vertex","fire-js":"fire-js",firebase:"fire-js-all"},wt=new Map,bt=new Map,It=new Map;function Tt(t,r){try{t.container.addComponent(r)}catch(e){vt.debug(`Component ${r.name} failed to register with FirebaseApp `+t.name,e)}}function Et(e,t){e.container.addOrOverwriteComponent(t)}function Ct(e){var t,r,n=e.name;if(It.has(n))return vt.debug(`There were multiple attempts to register component ${n}.`),!1;It.set(n,e);for(t of wt.values())Tt(t,e);for(r of bt.values())Tt(r,e);return!0}function kt(e,t){var r=e.container.getProvider("heartbeat").getImmediate({optional:!0});return r&&r.triggerHeartbeat(),e.container.getProvider(t)}function St(e){return void 0!==e.options}function h(e){return null!=e&&void 0!==e.settings}let At=new pe("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 Nt{constructor(e,t,r){this._isDeleted=!1,this._options=Object.assign({},e),this._config=Object.assign({},t),this._name=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled,this._container=r,this.container.addComponent(new u("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 At.create("app-deleted",{appName:this._name})}}function Rt(e,t){var r=z(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 Pt extends Nt{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=Object.assign({automaticDataCollectionEnabled:i},t),this._serverConfig.authIdToken&&Rt(this._serverConfig.authIdToken,"authIdToken"),this._serverConfig.appCheckToken&&Rt(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,d(gt,mt,"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(){Lt(this)}get settings(){return this.checkDestroyed(),this._serverConfig}checkDestroyed(){if(this.isDeleted)throw At.create("server-app-deleted")}}let Dt="11.3.0";function xt(e,t={}){let r=e;if("object"!=typeof t){let e=t;t={name:e}}var n=Object.assign({name:_t,automaticDataCollectionEnabled:!1},t);let i=n.name;if("string"!=typeof i||!i)throw At.create("bad-app-name",{appName:String(i)});if(!(r=r||Y()))throw At.create("no-options");var s=wt.get(i);if(s){if(Ie(r,s.options)&&Ie(n,s.config))return s;throw At.create("duplicate-app",{appName:i})}var a,o=new Be(i);for(a of It.values())o.addComponent(a);s=new Nt(r,n,o);return wt.set(i,s),s}function Ot(e=_t){var t=wt.get(e);if(!t&&e===_t&&Y())return xt();if(t)return t;throw At.create("no-app",{appName:e})}async function Lt(e){let t=!1;var r=e.name;wt.has(r)?(t=!0,wt.delete(r)):bt.has(r)&&e.decRefCount()<=0&&(bt.delete(r),t=!0),t&&(await Promise.all(e.container.getProviders().map(e=>e.delete())),e.isDeleted=!0)}function d(e,t,r){let n,i=null!=(n=yt[e])?n:e;r&&(i+="-"+r);var s,a=i.match(/\s|\//),o=t.match(/\s|\//);a||o?(s=[`Unable to register library "${i}" with version "${t}":`],a&&s.push(`library name "${i}" contains illegal characters (whitespace or "/")`),a&&o&&s.push("and"),o&&s.push(`version name "${t}" contains illegal characters (whitespace or "/")`),vt.warn(s.join(" "))):Ct(new u(i+"-version",()=>({library:i,version:t}),"VERSION"))}function Mt(e,t){if(null!==e&&"function"!=typeof e)throw At.create("invalid-log-argument");var r,s=e,n=t;for(r of ze){let i=null;n&&n.level&&(i=Ke[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>=(null!=i?i:e.logLevel)&&s({level:c[t].toLowerCase(),message:n,args:r,type:e.name})}}}function Ft(e){var t;t=e,ze.forEach(e=>{e.setLogLevel(t)})}let Ut="firebase-heartbeat-database",Vt=1,qt="firebase-heartbeat-store",jt=null;function Bt(){return jt=jt||lt(Ut,Vt,{upgrade:(e,t)=>{if(0===t)try{e.createObjectStore(qt)}catch(e){console.warn(e)}}}).catch(e=>{throw At.create("idb-open",{originalErrorMessage:e.message})})}async function zt(e,t){try{var r=(await Bt()).transaction(qt,"readwrite");await r.objectStore(qt).put(t,Kt(e)),await r.done}catch(e){e instanceof de?vt.warn(e.message):(r=At.create("idb-set",{originalErrorMessage:null==e?void 0:e.message}),vt.warn(r.message))}}function Kt(e){return e.name+"!"+e.options.appId}class Wt{constructor(e){this.container=e,this._heartbeatsCache=null;var t=this.container.getProvider("app").getImmediate();this._storage=new Gt(t),this._heartbeatsCachePromise=this._storage.read().then(e=>this._heartbeatsCache=e)}async triggerHeartbeat(){var e,r;try{var n,i=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString();let t=Ht();if(null!=(null==(e=this._heartbeatsCache)?void 0:e.heartbeats)||(this._heartbeatsCache=await this._heartbeatsCachePromise,null!=(null==(r=this._heartbeatsCache)?void 0:r.heartbeats)))if(this._heartbeatsCache.lastSentHeartbeatDate!==t&&!this._heartbeatsCache.heartbeats.some(e=>e.date===t))return this._heartbeatsCache.heartbeats.push({date:t,agent:i}),30<this._heartbeatsCache.heartbeats.length&&(n=(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(n,1)),this._storage.overwrite(this._heartbeatsCache)}catch(e){vt.warn(e)}}async getHeartbeatsHeader(){var e,t,r,n,i;try{return(null===this._heartbeatsCache&&await this._heartbeatsCachePromise,null==(null==(e=this._heartbeatsCache)?void 0:e.heartbeats)||0===this._heartbeatsCache.heartbeats.length)?"":(t=Ht(),{heartbeatsToSend:r,unsentEntries:n}=((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),$t(r)>t){i.dates.pop();break}}else if(r.push({agent:s.agent,dates:[s.date]}),$t(r)>t){r.pop();break}n=n.slice(1)}return{heartbeatsToSend:r,unsentEntries:n}})(this._heartbeatsCache.heartbeats),i=o(JSON.stringify({version:2,heartbeats:r})),this._heartbeatsCache.lastSentHeartbeatDate=t,0<n.length?(this._heartbeatsCache.heartbeats=n,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),i)}catch(e){return vt.warn(e),""}}}function Ht(){return(new Date).toISOString().substring(0,10)}class Gt{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!he()&&ue().then(()=>!0).catch(()=>!1)}async read(){var e;return await this._canUseIndexedDBPromise&&null!=(e=await(async e=>{try{var t=(await Bt()).transaction(qt),r=await t.objectStore(qt).get(Kt(e));return await t.done,r}catch(e){e instanceof de?vt.warn(e.message):(t=At.create("idb-get",{originalErrorMessage:null==e?void 0:e.message}),vt.warn(t.message))}})(this.app))&&e.heartbeats?e:{heartbeats:[]}}async overwrite(e){var t,r;if(await this._canUseIndexedDBPromise)return r=await this.read(),zt(this.app,{lastSentHeartbeatDate:null!=(t=e.lastSentHeartbeatDate)?t:r.lastSentHeartbeatDate,heartbeats:e.heartbeats})}async add(e){var t,r;if(await this._canUseIndexedDBPromise)return r=await this.read(),zt(this.app,{lastSentHeartbeatDate:null!=(t=e.lastSentHeartbeatDate)?t:r.lastSentHeartbeatDate,heartbeats:[...r.heartbeats,...e.heartbeats]})}}function $t(e){return o(JSON.stringify({version:2,heartbeats:e})).length}t="",Ct(new u("platform-logger",e=>new ft(e),"PRIVATE")),Ct(new u("heartbeat",e=>new Wt(e),"PRIVATE")),d(gt,mt,t),d(gt,mt,"esm2017"),d("fire-js","");var Qt=Object.freeze({__proto__:null,SDK_VERSION:Dt,_DEFAULT_ENTRY_NAME:_t,_addComponent:Tt,_addOrOverwriteComponent:Et,_apps:wt,_clearComponents:function(){It.clear()},_components:It,_getProvider:kt,_isFirebaseApp:St,_isFirebaseServerApp:h,_registerComponent:Ct,_removeServiceInstance:function(e,t,r=_t){kt(e,t).clearInstance(r)},_serverApps:bt,deleteApp:Lt,getApp:Ot,getApps:function(){return Array.from(wt.values())},initializeApp:xt,initializeServerApp:function(e,t){if(("undefined"!=typeof window||ne())&&!ne())throw At.create("invalid-server-app-environment");void 0===t.automaticDataCollectionEnabled&&(t.automaticDataCollectionEnabled=!1);let r;r=St(e)?e.options:e;var n=Object.assign(Object.assign({},t),r);if(void 0!==n.releaseOnDeref&&delete n.releaseOnDeref,void 0!==t.releaseOnDeref&&"undefined"==typeof FinalizationRegistry)throw At.create("finalization-registry-not-supported",{});var n=""+[...JSON.stringify(n)].reduce((e,t)=>Math.imul(31,e)+t.charCodeAt(0)|0,0),i=bt.get(n);if(i)i.incRefCount(t.releaseOnDeref);else{var s,a=new Be(n);for(s of It.values())a.addComponent(s);i=new Pt(r,t,n,a),bt.set(n,i)}return i},onLog:Mt,registerVersion:d,setLogLevel:Ft,FirebaseError:de});class Yt{constructor(e,t){this._delegate=e,this.firebase=t,Tt(e,new u("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),Lt(this._delegate)))}_getService(e,t=_t){this._delegate.checkDestroyed();var r,n=this._delegate.container.getProvider(e);return n.isInitialized()||"EXPLICIT"!==(null==(r=n.getComponent())?void 0:r.instantiationMode)||n.initialize(),n.getImmediate({identifier:t})}_removeServiceInstance(e,t=_t){this._delegate.container.getProvider(e).clearInstance(t)}_addComponent(e){Tt(this._delegate,e)}_addOrOverwriteComponent(e){Et(this._delegate,e)}toJSON(){return{name:this.name,automaticDataCollectionEnabled:this.automaticDataCollectionEnabled,options:this.options}}}let Jt=new pe("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 Xt(i){let s={},a={__esModule:!0,initializeApp:function(e,t={}){var r=xt(e,t);if(_e(s,r.name))return s[r.name];var n=new i(r,a);return s[r.name]=n},app:o,registerVersion:d,setLogLevel:Ft,onLog:Mt,apps:null,SDK_VERSION:Dt,INTERNAL:{registerComponent:function(t){let r=t.name,n=r.replace("-compat","");{var e;Ct(t)&&"PUBLIC"===t.type&&(e=(e=o())=>{if("function"!=typeof e[n])throw Jt.create("invalid-app-argument",{appName:r});return e[n]()},void 0!==t.serviceProps&&K(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:Qt}};function o(e){if(e=e||_t,_e(s,e))return s[e];throw Jt.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 Zt=function e(){let t=Xt(Yt);return t.INTERNAL=Object.assign(Object.assign({},t.INTERNAL),{createFirebaseNamespace:e,extendNamespace:function(e){K(t,e)},createSubscribe:Ae,ErrorFactory:pe,deepExtend:K}),t}(),e=new $e("@firebase/app-compat");try{var er=W();void 0!==er.firebase&&(e.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={NODE_CLIENT:!1,NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"},g=function(e,t){if(!e)throw j(t)},j=function(e){return new Error("Firebase Database ("+n.SDK_VERSION+") INTERNAL ASSERT FAILED: "+e)},i=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},s={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 u=0;u<r.length;u+=3){var s=r[u],a=u+1<r.length,o=a?r[u+1]:0,l=u+2<r.length,h=l?r[u+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(i(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 B;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 B extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}function a(e){var t=i(e);return s.encodeByteArray(t,!0)}let o=function(e){return a(e).replace(/\./g,"")},z=function(e){try{return s.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function K(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]=K(e[r],t[r]));return e}function W(){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 H=()=>W().__FIREBASE_DEFAULTS__,G=()=>{var e;return"undefined"!=typeof process&&void 0!==process.env&&(e=process.env.__FIREBASE_DEFAULTS__)?JSON.parse(e):void 0},$=()=>{if("undefined"!=typeof document){let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}var t=e&&z(e[1]);return t&&JSON.parse(t)}},Q=()=>{try{return H()||G()||$()}catch(e){console.info("Unable to get __FIREBASE_DEFAULTS__ due to: "+e)}},Y=()=>{var e;return null==(e=Q())?void 0:e.config};var c,J;class X{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 Z(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=Object.assign({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),[o(JSON.stringify({alg:"none",type:"JWT"})),o(JSON.stringify(r)),""].join(".");throw new Error("mockUserToken must contain 'sub' or 'user_id' field!")}function ee(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function te(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(ee())}function re(){var e=null==(e=Q())?void 0:e.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 ne(){return"undefined"!=typeof WorkerGlobalScope&&"undefined"!=typeof self&&self instanceof WorkerGlobalScope}function ie(){var e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}function se(){return"object"==typeof navigator&&"ReactNative"===navigator.product}function ae(){var e=ee();return 0<=e.indexOf("MSIE ")||0<=e.indexOf("Trident/")}function oe(){return!0===n.NODE_ADMIN}function le(){return!re()&&navigator.userAgent&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}function he(){try{return"object"==typeof indexedDB}catch(e){return!1}}function ue(){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=()=>{var e;i((null==(e=r.error)?void 0:e.message)||"")}}catch(e){i(e)}})}function ce(){return!("undefined"==typeof navigator||!navigator.cookieEnabled)}class de extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name="FirebaseError",Object.setPrototypeOf(this,de.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,pe.prototype.create)}}class pe{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(fe,(e,t)=>{var r=n[t];return null!=r?String(r):`<${t}?>`})):"Error",s=this.serviceName+`: ${s} (${i}).`;return new de(i,s,r)}}let fe=/\{\$([^}]+)}/g;function ge(e){return JSON.parse(e)}function me(e){return JSON.stringify(e)}function ve(e){let t={},r={},n={},i="";try{var s=e.split(".");t=ge(z(s[0])||""),r=ge(z(s[1])||""),i=s[2],n=r.d||{},delete r.d}catch(e){}return{header:t,claims:r,data:n,signature:i}}function _e(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ye(e,t){if(Object.prototype.hasOwnProperty.call(e,t))return e[t]}function we(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function be(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 Ie(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(Te(a)&&Te(o)){if(!Ie(a,o))return!1}else if(a!==o)return!1}for(n of s)if(!i.includes(n))return!1}return!0}function Te(e){return null!==e&&"object"==typeof e}function Ee(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 Ce(e){let n={};return e.replace(/^\?/,"").split("&").forEach(e=>{var t,r;e&&([t,r]=e.split("="),n[decodeURIComponent(t)]=decodeURIComponent(r))}),n}function ke(e){var t,r=e.indexOf("?");return r?(t=e.indexOf("#",r),e.substring(r,0<t?t:void 0)):""}class Se{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,u;for(let p=0;p<80;p++){u=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 c=(t<<5|t>>>27)+h+l+u+i[p]&4294967295;l=o,o=a,a=4294967295&(s<<30|s>>>2),s=t,t=c}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 Ae(e,t){var r=new Ne(e,t);return r.subscribe.bind(r)}class Ne{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=Re),void 0===n.error&&(n.error=Re),void 0===n.complete&&(n.complete=Re);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 Re(){}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 Pe(e,t){return e+` failed: ${t} argument `}function De(e,t,r,n){if((!n||r)&&"function"!=typeof r)throw new Error(Pe(e,t)+"must be a valid function.")}function xe(e,t,r,n){if((!n||r)&&("object"!=typeof r||null===r))throw new Error(Pe(e,t)+"must be a valid context object.")}let Oe=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},Le=1e3,Me=2,Fe=144e5,Ue=.5;function Ve(e,t=Le,r=Me){var n=t*Math.pow(r,e),i=Math.round(Ue*n*(Math.random()-.5)*2);return Math.min(Fe,n+i)}function w(e){return e&&e._delegate?e._delegate:e}class u{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 qe="[DEFAULT]";class je{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 X;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(null==e?void 0:e.identifier),r=null!=(r=null==e?void 0:e.optional)&&r;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:qe})}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=qe){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=qe){return this.instances.has(e)}getOptions(e=qe){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=null!=(i=this.onInitCallbacks.get(r))?i: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(e){}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let r=this.instances.get(e);if(!r&&this.component&&(r=this.component.instanceFactory(this.container,{instanceIdentifier:(n=e)===qe?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(e){}var n;return r||null}normalizeInstanceIdentifier(e=qe){return!this.component||this.component.multipleInstances?e:qe}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class Be{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 je(e,this),this.providers.set(e,t),t)}getProviders(){return Array.from(this.providers.values())}}let ze=[],Ke=((t=c=c||{})[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:c.DEBUG,verbose:c.VERBOSE,info:c.INFO,warn:c.WARN,error:c.ERROR,silent:c.SILENT}),We=c.INFO,He={[c.DEBUG]:"log",[c.VERBOSE]:"log",[c.INFO]:"info",[c.WARN]:"warn",[c.ERROR]:"error"},Ge=(e,t,...r)=>{if(!(t<e.logLevel)){var n=(new Date).toISOString(),i=He[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${n}] ${e.name}:`,...r)}};class $e{constructor(e){this.name=e,this._logLevel=We,this._logHandler=Ge,this._userLogHandler=null,ze.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in c))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?Ke[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,c.DEBUG,...e),this._logHandler(this,c.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,c.VERBOSE,...e),this._logHandler(this,c.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,c.INFO,...e),this._logHandler(this,c.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,c.WARN,...e),this._logHandler(this,c.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,c.ERROR,...e),this._logHandler(this,c.ERROR,...e)}}let Qe=(t,e)=>e.some(e=>t instanceof e),Ye,Je;let Xe=new WeakMap,Ze=new WeakMap,et=new WeakMap,tt=new WeakMap,rt=new WeakMap;let nt={get(e,t,r){if(e instanceof IDBTransaction){if("done"===t)return Ze.get(e);if("objectStoreNames"===t)return e.objectStoreNames||et.get(e);if("store"===t)return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return at(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 it(n){return n!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(Je=Je||[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey]).includes(n)?function(...e){return n.apply(ot(this),e),at(Xe.get(this))}:function(...e){return at(n.apply(ot(this),e))}:function(e,...t){var r=n.call(ot(this),e,...t);return et.set(r,e.sort?e.sort():[e]),at(r)}}function st(e){var s,t;return"function"==typeof e?it(e):(e instanceof IDBTransaction&&(s=e,Ze.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)}),Ze.set(s,t))),Qe(e,Ye=Ye||[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])?new Proxy(e,nt):e)}function at(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(at(s.result)),r()},i=()=>{t(s.error),r()};s.addEventListener("success",n),s.addEventListener("error",i)})).then(e=>{e instanceof IDBCursor&&Xe.set(e,s)}).catch(()=>{}),rt.set(t,s),t):tt.has(e)?tt.get(e):((t=st(e))!==e&&(tt.set(e,t),rt.set(t,e)),t)}let ot=e=>rt.get(e);function lt(e,t,{blocked:r,upgrade:n,blocking:i,terminated:s}={}){let a=indexedDB.open(e,t);var o=at(a);return n&&a.addEventListener("upgradeneeded",e=>{n(at(a.result),e.oldVersion,e.newVersion,at(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 ht(e,{blocked:t}={}){var r=indexedDB.deleteDatabase(e);return t&&r.addEventListener("blocked",e=>t(e.oldVersion,e)),at(r).then(()=>{})}let ut=["get","getKey","getAll","getAllKeys","count"],ct=["put","add","delete","clear"],dt=new Map;function pt(e,t){if(e instanceof IDBDatabase&&!(t in e)&&"string"==typeof t){if(dt.get(t))return dt.get(t);let i=t.replace(/FromIndex$/,""),s=t!==i,a=ct.includes(i);var r;return i in(s?IDBIndex:IDBObjectStore).prototype&&(a||ut.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]},dt.set(t,r),r):void 0}}nt={...J=nt,get:(e,t,r)=>pt(e,t)||J.get(e,t,r),has:(e,t)=>!!pt(e,t)||J.has(e,t)};class ft{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(e=>{var t;return"VERSION"===(null==(t=e.getComponent())?void 0:t.type)?(t=e.getImmediate()).library+"/"+t.version:null}).filter(e=>e).join(" ")}}let gt="@firebase/app",mt="0.11.1",vt=new $e("@firebase/app");let _t="[DEFAULT]",yt={"@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/vertexai":"fire-vertex","fire-js":"fire-js",firebase:"fire-js-all"},wt=new Map,bt=new Map,It=new Map;function Tt(t,r){try{t.container.addComponent(r)}catch(e){vt.debug(`Component ${r.name} failed to register with FirebaseApp `+t.name,e)}}function Et(e,t){e.container.addOrOverwriteComponent(t)}function Ct(e){var t,r,n=e.name;if(It.has(n))return vt.debug(`There were multiple attempts to register component ${n}.`),!1;It.set(n,e);for(t of wt.values())Tt(t,e);for(r of bt.values())Tt(r,e);return!0}function kt(e,t){var r=e.container.getProvider("heartbeat").getImmediate({optional:!0});return r&&r.triggerHeartbeat(),e.container.getProvider(t)}function St(e){return void 0!==e.options}function h(e){return null!=e&&void 0!==e.settings}let At=new pe("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 Nt{constructor(e,t,r){this._isDeleted=!1,this._options=Object.assign({},e),this._config=Object.assign({},t),this._name=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled,this._container=r,this.container.addComponent(new u("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 At.create("app-deleted",{appName:this._name})}}function Rt(e,t){var r=z(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 Pt extends Nt{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=Object.assign({automaticDataCollectionEnabled:i},t),this._serverConfig.authIdToken&&Rt(this._serverConfig.authIdToken,"authIdToken"),this._serverConfig.appCheckToken&&Rt(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,d(gt,mt,"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(){Lt(this)}get settings(){return this.checkDestroyed(),this._serverConfig}checkDestroyed(){if(this.isDeleted)throw At.create("server-app-deleted")}}let Dt="11.3.1";function xt(e,t={}){let r=e;if("object"!=typeof t){let e=t;t={name:e}}var n=Object.assign({name:_t,automaticDataCollectionEnabled:!1},t);let i=n.name;if("string"!=typeof i||!i)throw At.create("bad-app-name",{appName:String(i)});if(!(r=r||Y()))throw At.create("no-options");var s=wt.get(i);if(s){if(Ie(r,s.options)&&Ie(n,s.config))return s;throw At.create("duplicate-app",{appName:i})}var a,o=new Be(i);for(a of It.values())o.addComponent(a);s=new Nt(r,n,o);return wt.set(i,s),s}function Ot(e=_t){var t=wt.get(e);if(!t&&e===_t&&Y())return xt();if(t)return t;throw At.create("no-app",{appName:e})}async function Lt(e){let t=!1;var r=e.name;wt.has(r)?(t=!0,wt.delete(r)):bt.has(r)&&e.decRefCount()<=0&&(bt.delete(r),t=!0),t&&(await Promise.all(e.container.getProviders().map(e=>e.delete())),e.isDeleted=!0)}function d(e,t,r){let n,i=null!=(n=yt[e])?n:e;r&&(i+="-"+r);var s,a=i.match(/\s|\//),o=t.match(/\s|\//);a||o?(s=[`Unable to register library "${i}" with version "${t}":`],a&&s.push(`library name "${i}" contains illegal characters (whitespace or "/")`),a&&o&&s.push("and"),o&&s.push(`version name "${t}" contains illegal characters (whitespace or "/")`),vt.warn(s.join(" "))):Ct(new u(i+"-version",()=>({library:i,version:t}),"VERSION"))}function Mt(e,t){if(null!==e&&"function"!=typeof e)throw At.create("invalid-log-argument");var r,s=e,n=t;for(r of ze){let i=null;n&&n.level&&(i=Ke[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>=(null!=i?i:e.logLevel)&&s({level:c[t].toLowerCase(),message:n,args:r,type:e.name})}}}function Ft(e){var t;t=e,ze.forEach(e=>{e.setLogLevel(t)})}let Ut="firebase-heartbeat-database",Vt=1,qt="firebase-heartbeat-store",jt=null;function Bt(){return jt=jt||lt(Ut,Vt,{upgrade:(e,t)=>{if(0===t)try{e.createObjectStore(qt)}catch(e){console.warn(e)}}}).catch(e=>{throw At.create("idb-open",{originalErrorMessage:e.message})})}async function zt(e,t){try{var r=(await Bt()).transaction(qt,"readwrite");await r.objectStore(qt).put(t,Kt(e)),await r.done}catch(e){e instanceof de?vt.warn(e.message):(r=At.create("idb-set",{originalErrorMessage:null==e?void 0:e.message}),vt.warn(r.message))}}function Kt(e){return e.name+"!"+e.options.appId}class Wt{constructor(e){this.container=e,this._heartbeatsCache=null;var t=this.container.getProvider("app").getImmediate();this._storage=new Gt(t),this._heartbeatsCachePromise=this._storage.read().then(e=>this._heartbeatsCache=e)}async triggerHeartbeat(){var e,r;try{var n,i=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString();let t=Ht();if(null!=(null==(e=this._heartbeatsCache)?void 0:e.heartbeats)||(this._heartbeatsCache=await this._heartbeatsCachePromise,null!=(null==(r=this._heartbeatsCache)?void 0:r.heartbeats)))if(this._heartbeatsCache.lastSentHeartbeatDate!==t&&!this._heartbeatsCache.heartbeats.some(e=>e.date===t))return this._heartbeatsCache.heartbeats.push({date:t,agent:i}),30<this._heartbeatsCache.heartbeats.length&&(n=(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(n,1)),this._storage.overwrite(this._heartbeatsCache)}catch(e){vt.warn(e)}}async getHeartbeatsHeader(){var e,t,r,n,i;try{return(null===this._heartbeatsCache&&await this._heartbeatsCachePromise,null==(null==(e=this._heartbeatsCache)?void 0:e.heartbeats)||0===this._heartbeatsCache.heartbeats.length)?"":(t=Ht(),{heartbeatsToSend:r,unsentEntries:n}=((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),$t(r)>t){i.dates.pop();break}}else if(r.push({agent:s.agent,dates:[s.date]}),$t(r)>t){r.pop();break}n=n.slice(1)}return{heartbeatsToSend:r,unsentEntries:n}})(this._heartbeatsCache.heartbeats),i=o(JSON.stringify({version:2,heartbeats:r})),this._heartbeatsCache.lastSentHeartbeatDate=t,0<n.length?(this._heartbeatsCache.heartbeats=n,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),i)}catch(e){return vt.warn(e),""}}}function Ht(){return(new Date).toISOString().substring(0,10)}class Gt{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!he()&&ue().then(()=>!0).catch(()=>!1)}async read(){var e;return await this._canUseIndexedDBPromise&&null!=(e=await(async e=>{try{var t=(await Bt()).transaction(qt),r=await t.objectStore(qt).get(Kt(e));return await t.done,r}catch(e){e instanceof de?vt.warn(e.message):(t=At.create("idb-get",{originalErrorMessage:null==e?void 0:e.message}),vt.warn(t.message))}})(this.app))&&e.heartbeats?e:{heartbeats:[]}}async overwrite(e){var t,r;if(await this._canUseIndexedDBPromise)return r=await this.read(),zt(this.app,{lastSentHeartbeatDate:null!=(t=e.lastSentHeartbeatDate)?t:r.lastSentHeartbeatDate,heartbeats:e.heartbeats})}async add(e){var t,r;if(await this._canUseIndexedDBPromise)return r=await this.read(),zt(this.app,{lastSentHeartbeatDate:null!=(t=e.lastSentHeartbeatDate)?t:r.lastSentHeartbeatDate,heartbeats:[...r.heartbeats,...e.heartbeats]})}}function $t(e){return o(JSON.stringify({version:2,heartbeats:e})).length}t="",Ct(new u("platform-logger",e=>new ft(e),"PRIVATE")),Ct(new u("heartbeat",e=>new Wt(e),"PRIVATE")),d(gt,mt,t),d(gt,mt,"esm2017"),d("fire-js","");var Qt=Object.freeze({__proto__:null,SDK_VERSION:Dt,_DEFAULT_ENTRY_NAME:_t,_addComponent:Tt,_addOrOverwriteComponent:Et,_apps:wt,_clearComponents:function(){It.clear()},_components:It,_getProvider:kt,_isFirebaseApp:St,_isFirebaseServerApp:h,_registerComponent:Ct,_removeServiceInstance:function(e,t,r=_t){kt(e,t).clearInstance(r)},_serverApps:bt,deleteApp:Lt,getApp:Ot,getApps:function(){return Array.from(wt.values())},initializeApp:xt,initializeServerApp:function(e,t){if(("undefined"!=typeof window||ne())&&!ne())throw At.create("invalid-server-app-environment");void 0===t.automaticDataCollectionEnabled&&(t.automaticDataCollectionEnabled=!1);let r;r=St(e)?e.options:e;var n=Object.assign(Object.assign({},t),r);if(void 0!==n.releaseOnDeref&&delete n.releaseOnDeref,void 0!==t.releaseOnDeref&&"undefined"==typeof FinalizationRegistry)throw At.create("finalization-registry-not-supported",{});var n=""+[...JSON.stringify(n)].reduce((e,t)=>Math.imul(31,e)+t.charCodeAt(0)|0,0),i=bt.get(n);if(i)i.incRefCount(t.releaseOnDeref);else{var s,a=new Be(n);for(s of It.values())a.addComponent(s);i=new Pt(r,t,n,a),bt.set(n,i)}return i},onLog:Mt,registerVersion:d,setLogLevel:Ft,FirebaseError:de});class Yt{constructor(e,t){this._delegate=e,this.firebase=t,Tt(e,new u("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),Lt(this._delegate)))}_getService(e,t=_t){this._delegate.checkDestroyed();var r,n=this._delegate.container.getProvider(e);return n.isInitialized()||"EXPLICIT"!==(null==(r=n.getComponent())?void 0:r.instantiationMode)||n.initialize(),n.getImmediate({identifier:t})}_removeServiceInstance(e,t=_t){this._delegate.container.getProvider(e).clearInstance(t)}_addComponent(e){Tt(this._delegate,e)}_addOrOverwriteComponent(e){Et(this._delegate,e)}toJSON(){return{name:this.name,automaticDataCollectionEnabled:this.automaticDataCollectionEnabled,options:this.options}}}let Jt=new pe("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 Xt(i){let s={},a={__esModule:!0,initializeApp:function(e,t={}){var r=xt(e,t);if(_e(s,r.name))return s[r.name];var n=new i(r,a);return s[r.name]=n},app:o,registerVersion:d,setLogLevel:Ft,onLog:Mt,apps:null,SDK_VERSION:Dt,INTERNAL:{registerComponent:function(t){let r=t.name,n=r.replace("-compat","");{var e;Ct(t)&&"PUBLIC"===t.type&&(e=(e=o())=>{if("function"!=typeof e[n])throw Jt.create("invalid-app-argument",{appName:r});return e[n]()},void 0!==t.serviceProps&&K(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:Qt}};function o(e){if(e=e||_t,_e(s,e))return s[e];throw Jt.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 Zt=function e(){let t=Xt(Yt);return t.INTERNAL=Object.assign(Object.assign({},t.INTERNAL),{createFirebaseNamespace:e,extendNamespace:function(e){K(t,e)},createSubscribe:Ae,ErrorFactory:pe,deepExtend:K}),t}(),e=new $e("@firebase/app-compat");try{var er=W();void 0!==er.firebase&&(e.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
|
`),rr=er.firebase.SDK_VERSION)&&0<=rr.indexOf("LITE")&&e.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(e){}let tr=Zt;d("@firebase/app-compat","0.2.49",void 0);tr.registerVersion("firebase","11.3.0","app-compat");var er="@firebase/installations",rr="0.6.12";let nr=1e4,ir="w:"+rr,sr="FIS_v2",ar="https://firebaseinstallations.googleapis.com/v1",or=36e5;let lr=new pe("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 hr(e){return e instanceof de&&e.code.includes("request-failed")}function ur({projectId:e}){return ar+`/projects/${e}/installations`}function cr(e){return{token:e.token,requestStatus:2,expiresIn:Number(e.expiresIn.replace("s","000")),creationTime:Date.now()}}async function dr(e,t){var r=(await t.json()).error;return lr.create("request-failed",{requestName:e,serverCode:r.code,serverMessage:r.message,serverStatus:r.status})}function pr({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function fr(e,{refreshToken:t}){var r=pr(e);return r.append("Authorization",(e=t,sr+" "+e)),r}async function gr(e){var t=await e();return 500<=t.status&&t.status<600?e():t}function mr(t){return new Promise(e=>{setTimeout(e,t)})}let vr=/^[cdef][\w-]{21}$/,_r="";function yr(){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 vr.test(t)?t:_r}catch(e){return _r}}function wr(e){return e.appName+"!"+e.appId}let br=new Map;function Ir(e,t){var r=wr(e),e=(Tr(r,t),r),r=(()=>(!Er&&"BroadcastChannel"in self&&((Er=new BroadcastChannel("[Firebase] FID Change")).onmessage=e=>{Tr(e.data.key,e.data.fid)}),Er))();r&&r.postMessage({key:e,fid:t}),0===br.size&&Er&&(Er.close(),Er=null)}function Tr(e,t){var r=br.get(e);if(r)for(var n of r)n(t)}let Er=null;let Cr="firebase-installations-database",kr=1,Sr="firebase-installations-store",Ar=null;function Nr(){return Ar=Ar||lt(Cr,kr,{upgrade:(e,t)=>{0===t&&e.createObjectStore(Sr)}})}async function Rr(e,t){var r=wr(e),n=(await Nr()).transaction(Sr,"readwrite"),i=n.objectStore(Sr),s=await i.get(r);return await i.put(t,r),await n.done,s&&s.fid===t.fid||Ir(e,t.fid),t}async function Pr(e){var t=wr(e),r=(await Nr()).transaction(Sr,"readwrite");await r.objectStore(Sr).delete(t),await r.done}async function Dr(e,t){var r=wr(e),n=(await Nr()).transaction(Sr,"readwrite"),i=n.objectStore(Sr),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||Ir(e,a.fid),a}async function xr(r){let n;var e=await Dr(r.appConfig,e=>{var t=Lr(e||{fid:yr(),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=ur(e);var i=pr(e),s=((s=t.getImmediate({optional:!0}))&&(s=await s.getHeartbeatsHeader())&&i.append("x-firebase-client",s),{fid:r,authVersion:sr,appId:e.appId,sdkVersion:ir});let a={method:"POST",headers:i,body:JSON.stringify(s)};if((i=await gr(()=>fetch(n,a))).ok)return{fid:(s=await i.json()).fid||r,registrationStatus:2,refreshToken:s.refreshToken,authToken:cr(s.authToken)};throw await dr("Create Installation",i)})(t,r);return Rr(t.appConfig,e)}catch(e){throw hr(e)&&409===e.customData.serverCode?await Pr(t.appConfig):await Rr(t.appConfig,{fid:r.fid,registrationStatus:0}),e}})(e,r),{installationEntry:r,registrationPromise:n}):(r=Promise.reject(lr.create("app-offline")),{installationEntry:t,registrationPromise:r}):1===t.registrationStatus?{installationEntry:t,registrationPromise:(async e=>{let t=await Or(e.appConfig);for(;1===t.registrationStatus;)await mr(100),t=await Or(e.appConfig);var r,n;return 0!==t.registrationStatus?t:({installationEntry:r,registrationPromise:n}=await xr(e),n||r)})(e)}:{installationEntry:t}})(r,t);return n=t.registrationPromise,t.installationEntry});return e.fid===_r?{installationEntry:await n}:{installationEntry:e,registrationPromise:n}}function Or(e){return Dr(e,e=>{if(e)return Lr(e);throw lr.create("installation-not-found")})}function Lr(e){var t;return 1===(t=e).registrationStatus&&t.registrationTime+nr<Date.now()?{fid:e.fid,registrationStatus:0}:e}async function Mr({appConfig:e,heartbeatServiceProvider:t},r){[i,s]=[e,r.fid];let n=ur(i)+`/${s}/authTokens:generate`;var i,s,a=fr(e,r),o=t.getImmediate({optional:!0}),o=(o&&(o=await o.getHeartbeatsHeader())&&a.append("x-firebase-client",o),{installation:{sdkVersion:ir,appId:e.appId}});let l={method:"POST",headers:a,body:JSON.stringify(o)};a=await gr(()=>fetch(n,l));if(a.ok)return cr(await a.json());throw await dr("Generate Auth Token",a)}async function Fr(n,i=!1){let s;var e=await Dr(n.appConfig,e=>{if(!Vr(e))throw lr.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+or})(t)){if(1===r.requestStatus)return s=(async(e,t)=>{let r=await Ur(e.appConfig);for(;1===r.authToken.requestStatus;)await mr(100),r=await Ur(e.appConfig);var n=r.authToken;return 0===n.requestStatus?Fr(e,t):n})(n,i),e;if(navigator.onLine)return t=e,r={requestStatus:1,requestTime:Date.now()},r=Object.assign(Object.assign({},t),{authToken:r}),s=(async(t,r)=>{try{var e=await Mr(t,r),n=Object.assign(Object.assign({},r),{authToken:e});return await Rr(t.appConfig,n),e}catch(e){var i;throw!hr(e)||401!==e.customData.serverCode&&404!==e.customData.serverCode?(i=Object.assign(Object.assign({},r),{authToken:{requestStatus:0}}),await Rr(t.appConfig,i)):await Pr(t.appConfig),e}})(n,r),r;throw lr.create("app-offline")}return e});return s?await s:e.authToken}function Ur(e){return Dr(e,e=>{var t,r;if(Vr(e))return t=e.authToken,1===(r=t).requestStatus&&r.requestTime+nr<Date.now()?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e;throw lr.create("not-registered")})}function Vr(e){return void 0!==e&&2===e.registrationStatus}async function qr(e,t=!1){var r=e,n=(await(!(n=(await xr(r)).registrationPromise)||!await n),await Fr(r,t));return n.token}function jr(e){return lr.create("missing-app-config-values",{valueName:e})}let Br="installations",zr=e=>{var t=e.getProvider("app").getImmediate();return{app:t,appConfig:(e=>{if(!e||!e.options)throw jr("App Configuration");if(!e.name)throw jr("App Name");var t;for(t of["projectId","apiKey","appId"])if(!e.options[t])throw jr(t);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}})(t),heartbeatServiceProvider:kt(t,"heartbeat"),_delete:()=>Promise.resolve()}},Kr=e=>{let t=kt(e.getProvider("app").getImmediate(),Br).getImmediate();return{getId:()=>(async e=>{var t=e,{installationEntry:r,registrationPromise:n}=await xr(t);return(n||Fr(t)).catch(console.error),r.fid})(t),getToken:e=>qr(t,e)}};Ct(new u(Br,zr,"PUBLIC")),Ct(new u("installations-internal",Kr,"PRIVATE")),d(er,rr),d(er,rr,"esm2017");let Wr="analytics",Hr="firebase_id",Gr="origin",$r=6e4,Qr="https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig",Yr="https://www.googletagmanager.com/gtag/js",Jr=new $e("@firebase/analytics"),Xr=new pe("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 Zr(e){var t;return e.startsWith(Yr)?e:(t=Xr.create("invalid-gtag-resource",{gtagURL:e}),Jr.warn(t.message),"")}function en(e){return Promise.all(e.map(e=>e.catch(e=>e)))}function tn(e,t){var r=((e,t)=>{let r;return r=window.trustedTypes?window.trustedTypes.createPolicy(e,t):r})("firebase-js-sdk-policy",{createScriptURL:Zr}),n=document.createElement("script"),i=Yr+`?l=${e}&id=`+t;n.src=r?null==r?void 0:r.createScriptURL(i):i,n.async=!0,document.head.appendChild(n)}function rn(S,A,N,R){return async function(e,...t){try{if("event"===e){var[r,n]=t,i=S,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 en(a);for(let t of e){var u=h.find(e=>e.measurementId===t),c=u&&s[u.appId];if(!c){r=[];break}r.push(c)}}0===r.length&&(r=Object.values(s)),await Promise.all(r),i("event",o,l||{})}catch(e){Jr.error(e)}}else if("config"===e){var d,[p,f]=t,g=S,m=A,v=N,_=p,y=f,w=R[_];try{w?await m[w]:(d=(await en(v)).find(e=>e.measurementId===_))&&await m[d.appId]}catch(e){Jr.error(e)}g("config",_,y)}else{var b,I,T,E,C,k;"consent"===e?([b,I]=t,S("consent",b,I)):"get"===e?([T,E,C]=t,S("get",T,E,C)):"set"===e?([k]=t,S("set",k)):S(e,...t)}}catch(e){Jr.error(e)}}}let nn=30;let sn=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 an(e){var t,{appId:r,apiKey:n}=e,n={method:"GET",headers:new Headers({Accept:"application/json","x-goog-api-key":n})},r=Qr.replace("{app-id}",r),r=await fetch(r,n);if(200===r.status||304===r.status)return r.json();{let e="";try{var i=await r.json();null!=(t=i.error)&&t.message&&(e=i.error.message)}catch(e){}throw Xr.create("config-fetch-failed",{httpStatus:r.status,responseMessage:e})}}async function on(e,t=sn,r){var{appId:n,apiKey:i,measurementId:s}=e.options;if(!n)throw Xr.create("no-app-id");if(!i){if(s)return{measurementId:s,appId:n};throw Xr.create("no-api-key")}var a=t.getThrottleMetadata(n)||{backoffCount:0,throttleEndTimeMillis:Date.now()};let o=new un;return setTimeout(async()=>{o.abort()},void 0!==r?r:$r),async function i(s,{throttleEndTimeMillis:e,backoffCount:a},o,l=sn){var h;let{appId:u,measurementId:c}=s;try{await ln(o,e)}catch(e){if(c)return Jr.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. [${null==e?void 0:e.message}]`),{appId:u,measurementId:c};throw e}try{let e=await an(s);return l.deleteThrottleMetadata(u),e}catch(e){let t=e;if(!hn(t)){if(l.deleteThrottleMetadata(u),c)return Jr.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. [${null==t?void 0:t.message}]`),{appId:u,measurementId:c};throw e}let r=503===Number(null==(h=null==t?void 0:t.customData)?void 0:h.httpStatus)?Ve(a,l.intervalMillis,nn):Ve(a,l.intervalMillis),n={throttleEndTimeMillis:Date.now()+r,backoffCount:a+1};return l.setThrottleMetadata(u,n),Jr.debug(`Calling attemptFetch again in ${r} millis`),i(s,n,o,l)}}({appId:n,apiKey:i,measurementId:s},a,o,t)}function ln(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(Xr.create("fetch-throttle",{throttleEndTimeMillis:s}))})})}function hn(e){var t;return!!(e instanceof de&&e.customData)&&(429===(t=Number(e.customData.httpStatus))||500===t||503===t||504===t)}class un{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach(e=>e())}}async function cn(t,e,r,n,i,s,a){var o=on(t),l=(o.then(e=>{r[e.measurementId]=e.appId,t.options.measurementId&&e.measurementId!==t.options.measurementId&&Jr.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=>Jr.error(e)),e.push(o),(async()=>{if(!he())return Jr.warn(Xr.create("indexeddb-unavailable",{errorInfo:"IndexedDB is not available in this environment."}).message),!1;try{await ue()}catch(e){return Jr.warn(Xr.create("indexeddb-unavailable",{errorInfo:null==e?void 0: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(Yr)&&t.src.includes(e))return t})(s)||tn(s,o.measurementId),i("js",new Date),null!=(h=null==a?void 0:a.config)?h:{});return h[Gr]="firebase",h.update=!0,null!=l&&(h[Hr]=l),i("config",o.measurementId,h),o.measurementId}class dn{constructor(e){this.app=e}_delete(){return delete pn[this.app.options.appId],Promise.resolve()}}let pn={},fn=[],gn={},mn="dataLayer",vn="gtag",_n,yn,wn=!1;function bn(e){if(wn)throw Xr.create("already-initialized");e.dataLayerName&&(mn=e.dataLayerName),e.gtagName&&(vn=e.gtagName)}function In(e,t,r){n=[],ie()&&n.push("This is a browser extension environment."),ce()||n.push("Cookies are not available."),0<n.length&&(n=n.map((e,t)=>`(${t+1}) `+e).join(" "),n=Xr.create("invalid-analytics-context",{errorInfo:n}),Jr.warn(n.message));var n=e.options.appId;if(!n)throw Xr.create("no-app-id");if(!e.options.apiKey){if(!e.options.measurementId)throw Xr.create("no-api-key");Jr.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!=pn[n])throw Xr.create("already-exists",{id:n});if(!wn){{var i=mn;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]=rn(s,e,t,r),{gtagCore:s,wrappedGtag:window[i]}})(pn,fn,gn,mn,vn);yn=s,_n=a,wn=!0}return pn[n]=cn(e,fn,gn,t,_n,mn,r),new dn(e)}async function Tn(){if(ie())return!1;if(!ce())return!1;if(!he())return!1;try{return await ue()}catch(e){return!1}}function En(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})})(yn,pn[e.app.options.appId],t,r).catch(e=>Jr.error(e))}function Cn(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})})(yn,pn[e.app.options.appId],t,r).catch(e=>Jr.error(e))}function kn(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})})(yn,pn[e.app.options.appId],t,r).catch(e=>Jr.error(e))}function Sn(e,t){e=w(e),(async(e,t)=>{var r=await e;window["ga-disable-"+r]=!t})(pn[e.app.options.appId],t).catch(e=>Jr.error(e))}function An(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,Object.assign(Object.assign({},n),{send_to:s})))})(yn,pn[e.app.options.appId],t,r,n).catch(e=>Jr.error(e))}let Nn="@firebase/analytics",Rn="0.10.11";Ct(new u(Wr,(e,{options:t})=>In(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),t),"PUBLIC")),Ct(new u("analytics-internal",function(e){try{let n=e.getProvider(Wr).getImmediate();return{logEvent:(e,t,r)=>An(n,e,t,r)}}catch(e){throw Xr.create("interop-component-reg-failed",{reason:e})}},"PRIVATE")),d(Nn,Rn),d(Nn,Rn,"esm2017");class Pn{constructor(e,t){this.app=e,this._delegate=t}logEvent(e,t,r){An(this._delegate,e,t,r)}setCurrentScreen(e,t){En(this._delegate,e,t)}setUserId(e,t){Cn(this._delegate,e,t)}setUserProperties(e,t){kn(this._delegate,e,t)}setAnalyticsCollectionEnabled(e){Sn(this._delegate,e)}}(t=ym=ym||{}).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 Dn=e=>{var t=e.getProvider("app-compat").getImmediate(),r=e.getProvider("analytics").getImmediate();return new Pn(t,r)};e={Analytics:Pn,settings:bn,isSupported:Tn,EventName:ym},tr.INTERNAL.registerComponent(new u("analytics-compat",Dn,"PUBLIC").setServiceProps(e).setMultipleInstances(!0)),tr.registerVersion("@firebase/analytics-compat","0.2.17");let xn=new Map,On={activated:!1,tokenObservers:[]},Ln={initialized:!1,enabled:!1};function Mn(e){return xn.get(e)||Object.assign({},On)}let Fn="https://content-firebaseappcheck.googleapis.com/v1",Un="exchangeDebugToken",Vn={OFFSET_DURATION:3e5,RETRIAL_MIN_WAIT:3e4,RETRIAL_MAX_WAIT:96e4};class qn{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 X,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 X,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 jn=new pe("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.",throttled:"Requests throttled due to {$httpStatus} error. Attempts allowed again after {$time}"});function Bn(e=!1){var t;return e?null==(t=self.grecaptcha)?void 0:t.enterprise:self.grecaptcha}function zn(e){if(!Mn(e).activated)throw jn.create("use-before-activation",{appName:e.name})}function Kn(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+=Wn(r)+"d:"),n&&(s+=Wn(n)+"h:"),s+=Wn(i)+"m:"+Wn(t)+"s"}function Wn(e){return 0===e?"00":10<=e?e.toString():"0"+e}async function Hn({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 jn.create("fetch-network-error",{originalErrorMessage:null==e?void 0:e.message})}if(200!==s.status)throw jn.create("fetch-status-error",{httpStatus:s.status});let a;try{a=await s.json()}catch(e){throw jn.create("fetch-parse-error",{originalErrorMessage:null==e?void 0: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 jn.create("fetch-parse-error",{originalErrorMessage:"ttl field (timeToLive) is not in standard Protobuf Duration format: "+a.ttl})}function Gn(e,t){var{projectId:r,appId:n,apiKey:i}=e.options;return{url:`${Fn}/projects/${r}/apps/${n}:${Un}?key=`+i,body:{debug_token:t}}}let $n="firebase-app-check-database",Qn=1,Yn="firebase-app-check-store",Jn="debug-token",Xn=null;function Zn(){return Xn=Xn||new Promise((t,r)=>{try{var e=indexedDB.open($n,Qn);e.onsuccess=e=>{t(e.target.result)},e.onerror=e=>{var t;r(jn.create("storage-open",{originalErrorMessage:null==(t=e.target.error)?void 0:t.message}))},e.onupgradeneeded=e=>{var t=e.target.result;0===e.oldVersion&&t.createObjectStore(Yn,{keyPath:"compositeKey"})}}catch(e){r(jn.create("storage-open",{originalErrorMessage:null==e?void 0:e.message}))}})}async function ei(e,t){let n=(await Zn()).transaction(Yn,"readwrite"),i=n.objectStore(Yn).put({compositeKey:e,value:t});return new Promise((t,r)=>{i.onsuccess=e=>{t()},n.onerror=e=>{var t;r(jn.create("storage-set",{originalErrorMessage:null==(t=e.target.error)?void 0:t.message}))}})}async function ti(e){let t=(await Zn()).transaction(Yn,"readonly"),i=t.objectStore(Yn).get(e);return new Promise((r,n)=>{i.onsuccess=e=>{var t=e.target.result;r(t?t.value:void 0)},t.onerror=e=>{var t;n(jn.create("storage-get",{originalErrorMessage:null==(t=e.target.error)?void 0:t.message}))}})}function ri(e){return e.options.appId+"-"+e.name}let ni=new $e("@firebase/app-check");async function ii(t){if(he()){let e=void 0;try{e=await ti(ri(t))}catch(e){ni.warn("Failed to read token from IndexedDB. Error: "+e)}return e}}function si(e,t){return he()?ei(ri(e),t).catch(e=>{ni.warn("Failed to write token to IndexedDB. Error: "+e)}):Promise.resolve()}async function ai(){let e=void 0;try{e=await ti(Jn)}catch(e){}var t,r;return e||(t=crypto.randomUUID(),r=t,ei(Jn,r).catch(e=>ni.warn("Failed to persist debug token to IndexedDB. Error: "+e)),t)}function oi(){return Ln.enabled}async function li(){var e=Ln;if(e.enabled&&e.token)return e.token.promise;throw Error(`
|
|
7
|
+
`)}catch(e){}let tr=Zt;d("@firebase/app-compat","0.2.50",void 0);tr.registerVersion("firebase","11.3.1","app-compat");var er="@firebase/installations",rr="0.6.12";let nr=1e4,ir="w:"+rr,sr="FIS_v2",ar="https://firebaseinstallations.googleapis.com/v1",or=36e5;let lr=new pe("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 hr(e){return e instanceof de&&e.code.includes("request-failed")}function ur({projectId:e}){return ar+`/projects/${e}/installations`}function cr(e){return{token:e.token,requestStatus:2,expiresIn:Number(e.expiresIn.replace("s","000")),creationTime:Date.now()}}async function dr(e,t){var r=(await t.json()).error;return lr.create("request-failed",{requestName:e,serverCode:r.code,serverMessage:r.message,serverStatus:r.status})}function pr({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function fr(e,{refreshToken:t}){var r=pr(e);return r.append("Authorization",(e=t,sr+" "+e)),r}async function gr(e){var t=await e();return 500<=t.status&&t.status<600?e():t}function mr(t){return new Promise(e=>{setTimeout(e,t)})}let vr=/^[cdef][\w-]{21}$/,_r="";function yr(){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 vr.test(t)?t:_r}catch(e){return _r}}function wr(e){return e.appName+"!"+e.appId}let br=new Map;function Ir(e,t){var r=wr(e),e=(Tr(r,t),r),r=(()=>(!Er&&"BroadcastChannel"in self&&((Er=new BroadcastChannel("[Firebase] FID Change")).onmessage=e=>{Tr(e.data.key,e.data.fid)}),Er))();r&&r.postMessage({key:e,fid:t}),0===br.size&&Er&&(Er.close(),Er=null)}function Tr(e,t){var r=br.get(e);if(r)for(var n of r)n(t)}let Er=null;let Cr="firebase-installations-database",kr=1,Sr="firebase-installations-store",Ar=null;function Nr(){return Ar=Ar||lt(Cr,kr,{upgrade:(e,t)=>{0===t&&e.createObjectStore(Sr)}})}async function Rr(e,t){var r=wr(e),n=(await Nr()).transaction(Sr,"readwrite"),i=n.objectStore(Sr),s=await i.get(r);return await i.put(t,r),await n.done,s&&s.fid===t.fid||Ir(e,t.fid),t}async function Pr(e){var t=wr(e),r=(await Nr()).transaction(Sr,"readwrite");await r.objectStore(Sr).delete(t),await r.done}async function Dr(e,t){var r=wr(e),n=(await Nr()).transaction(Sr,"readwrite"),i=n.objectStore(Sr),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||Ir(e,a.fid),a}async function xr(r){let n;var e=await Dr(r.appConfig,e=>{var t=Lr(e||{fid:yr(),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=ur(e);var i=pr(e),s=((s=t.getImmediate({optional:!0}))&&(s=await s.getHeartbeatsHeader())&&i.append("x-firebase-client",s),{fid:r,authVersion:sr,appId:e.appId,sdkVersion:ir});let a={method:"POST",headers:i,body:JSON.stringify(s)};if((i=await gr(()=>fetch(n,a))).ok)return{fid:(s=await i.json()).fid||r,registrationStatus:2,refreshToken:s.refreshToken,authToken:cr(s.authToken)};throw await dr("Create Installation",i)})(t,r);return Rr(t.appConfig,e)}catch(e){throw hr(e)&&409===e.customData.serverCode?await Pr(t.appConfig):await Rr(t.appConfig,{fid:r.fid,registrationStatus:0}),e}})(e,r),{installationEntry:r,registrationPromise:n}):(r=Promise.reject(lr.create("app-offline")),{installationEntry:t,registrationPromise:r}):1===t.registrationStatus?{installationEntry:t,registrationPromise:(async e=>{let t=await Or(e.appConfig);for(;1===t.registrationStatus;)await mr(100),t=await Or(e.appConfig);var r,n;return 0!==t.registrationStatus?t:({installationEntry:r,registrationPromise:n}=await xr(e),n||r)})(e)}:{installationEntry:t}})(r,t);return n=t.registrationPromise,t.installationEntry});return e.fid===_r?{installationEntry:await n}:{installationEntry:e,registrationPromise:n}}function Or(e){return Dr(e,e=>{if(e)return Lr(e);throw lr.create("installation-not-found")})}function Lr(e){var t;return 1===(t=e).registrationStatus&&t.registrationTime+nr<Date.now()?{fid:e.fid,registrationStatus:0}:e}async function Mr({appConfig:e,heartbeatServiceProvider:t},r){[i,s]=[e,r.fid];let n=ur(i)+`/${s}/authTokens:generate`;var i,s,a=fr(e,r),o=t.getImmediate({optional:!0}),o=(o&&(o=await o.getHeartbeatsHeader())&&a.append("x-firebase-client",o),{installation:{sdkVersion:ir,appId:e.appId}});let l={method:"POST",headers:a,body:JSON.stringify(o)};a=await gr(()=>fetch(n,l));if(a.ok)return cr(await a.json());throw await dr("Generate Auth Token",a)}async function Fr(n,i=!1){let s;var e=await Dr(n.appConfig,e=>{if(!Vr(e))throw lr.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+or})(t)){if(1===r.requestStatus)return s=(async(e,t)=>{let r=await Ur(e.appConfig);for(;1===r.authToken.requestStatus;)await mr(100),r=await Ur(e.appConfig);var n=r.authToken;return 0===n.requestStatus?Fr(e,t):n})(n,i),e;if(navigator.onLine)return t=e,r={requestStatus:1,requestTime:Date.now()},r=Object.assign(Object.assign({},t),{authToken:r}),s=(async(t,r)=>{try{var e=await Mr(t,r),n=Object.assign(Object.assign({},r),{authToken:e});return await Rr(t.appConfig,n),e}catch(e){var i;throw!hr(e)||401!==e.customData.serverCode&&404!==e.customData.serverCode?(i=Object.assign(Object.assign({},r),{authToken:{requestStatus:0}}),await Rr(t.appConfig,i)):await Pr(t.appConfig),e}})(n,r),r;throw lr.create("app-offline")}return e});return s?await s:e.authToken}function Ur(e){return Dr(e,e=>{var t,r;if(Vr(e))return t=e.authToken,1===(r=t).requestStatus&&r.requestTime+nr<Date.now()?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e;throw lr.create("not-registered")})}function Vr(e){return void 0!==e&&2===e.registrationStatus}async function qr(e,t=!1){var r=e,n=(await(!(n=(await xr(r)).registrationPromise)||!await n),await Fr(r,t));return n.token}function jr(e){return lr.create("missing-app-config-values",{valueName:e})}let Br="installations",zr=e=>{var t=e.getProvider("app").getImmediate();return{app:t,appConfig:(e=>{if(!e||!e.options)throw jr("App Configuration");if(!e.name)throw jr("App Name");var t;for(t of["projectId","apiKey","appId"])if(!e.options[t])throw jr(t);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}})(t),heartbeatServiceProvider:kt(t,"heartbeat"),_delete:()=>Promise.resolve()}},Kr=e=>{let t=kt(e.getProvider("app").getImmediate(),Br).getImmediate();return{getId:()=>(async e=>{var t=e,{installationEntry:r,registrationPromise:n}=await xr(t);return(n||Fr(t)).catch(console.error),r.fid})(t),getToken:e=>qr(t,e)}};Ct(new u(Br,zr,"PUBLIC")),Ct(new u("installations-internal",Kr,"PRIVATE")),d(er,rr),d(er,rr,"esm2017");let Wr="analytics",Hr="firebase_id",Gr="origin",$r=6e4,Qr="https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig",Yr="https://www.googletagmanager.com/gtag/js",Jr=new $e("@firebase/analytics"),Xr=new pe("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 Zr(e){var t;return e.startsWith(Yr)?e:(t=Xr.create("invalid-gtag-resource",{gtagURL:e}),Jr.warn(t.message),"")}function en(e){return Promise.all(e.map(e=>e.catch(e=>e)))}function tn(e,t){var r=((e,t)=>{let r;return r=window.trustedTypes?window.trustedTypes.createPolicy(e,t):r})("firebase-js-sdk-policy",{createScriptURL:Zr}),n=document.createElement("script"),i=Yr+`?l=${e}&id=`+t;n.src=r?null==r?void 0:r.createScriptURL(i):i,n.async=!0,document.head.appendChild(n)}function rn(S,A,N,R){return async function(e,...t){try{if("event"===e){var[r,n]=t,i=S,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 en(a);for(let t of e){var u=h.find(e=>e.measurementId===t),c=u&&s[u.appId];if(!c){r=[];break}r.push(c)}}0===r.length&&(r=Object.values(s)),await Promise.all(r),i("event",o,l||{})}catch(e){Jr.error(e)}}else if("config"===e){var d,[p,f]=t,g=S,m=A,v=N,_=p,y=f,w=R[_];try{w?await m[w]:(d=(await en(v)).find(e=>e.measurementId===_))&&await m[d.appId]}catch(e){Jr.error(e)}g("config",_,y)}else{var b,I,T,E,C,k;"consent"===e?([b,I]=t,S("consent",b,I)):"get"===e?([T,E,C]=t,S("get",T,E,C)):"set"===e?([k]=t,S("set",k)):S(e,...t)}}catch(e){Jr.error(e)}}}let nn=30;let sn=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 an(e){var t,{appId:r,apiKey:n}=e,n={method:"GET",headers:new Headers({Accept:"application/json","x-goog-api-key":n})},r=Qr.replace("{app-id}",r),r=await fetch(r,n);if(200===r.status||304===r.status)return r.json();{let e="";try{var i=await r.json();null!=(t=i.error)&&t.message&&(e=i.error.message)}catch(e){}throw Xr.create("config-fetch-failed",{httpStatus:r.status,responseMessage:e})}}async function on(e,t=sn,r){var{appId:n,apiKey:i,measurementId:s}=e.options;if(!n)throw Xr.create("no-app-id");if(!i){if(s)return{measurementId:s,appId:n};throw Xr.create("no-api-key")}var a=t.getThrottleMetadata(n)||{backoffCount:0,throttleEndTimeMillis:Date.now()};let o=new un;return setTimeout(async()=>{o.abort()},void 0!==r?r:$r),async function i(s,{throttleEndTimeMillis:e,backoffCount:a},o,l=sn){var h;let{appId:u,measurementId:c}=s;try{await ln(o,e)}catch(e){if(c)return Jr.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. [${null==e?void 0:e.message}]`),{appId:u,measurementId:c};throw e}try{let e=await an(s);return l.deleteThrottleMetadata(u),e}catch(e){let t=e;if(!hn(t)){if(l.deleteThrottleMetadata(u),c)return Jr.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. [${null==t?void 0:t.message}]`),{appId:u,measurementId:c};throw e}let r=503===Number(null==(h=null==t?void 0:t.customData)?void 0:h.httpStatus)?Ve(a,l.intervalMillis,nn):Ve(a,l.intervalMillis),n={throttleEndTimeMillis:Date.now()+r,backoffCount:a+1};return l.setThrottleMetadata(u,n),Jr.debug(`Calling attemptFetch again in ${r} millis`),i(s,n,o,l)}}({appId:n,apiKey:i,measurementId:s},a,o,t)}function ln(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(Xr.create("fetch-throttle",{throttleEndTimeMillis:s}))})})}function hn(e){var t;return!!(e instanceof de&&e.customData)&&(429===(t=Number(e.customData.httpStatus))||500===t||503===t||504===t)}class un{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach(e=>e())}}async function cn(t,e,r,n,i,s,a){var o=on(t),l=(o.then(e=>{r[e.measurementId]=e.appId,t.options.measurementId&&e.measurementId!==t.options.measurementId&&Jr.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=>Jr.error(e)),e.push(o),(async()=>{if(!he())return Jr.warn(Xr.create("indexeddb-unavailable",{errorInfo:"IndexedDB is not available in this environment."}).message),!1;try{await ue()}catch(e){return Jr.warn(Xr.create("indexeddb-unavailable",{errorInfo:null==e?void 0: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(Yr)&&t.src.includes(e))return t})(s)||tn(s,o.measurementId),i("js",new Date),null!=(h=null==a?void 0:a.config)?h:{});return h[Gr]="firebase",h.update=!0,null!=l&&(h[Hr]=l),i("config",o.measurementId,h),o.measurementId}class dn{constructor(e){this.app=e}_delete(){return delete pn[this.app.options.appId],Promise.resolve()}}let pn={},fn=[],gn={},mn="dataLayer",vn="gtag",_n,yn,wn=!1;function bn(e){if(wn)throw Xr.create("already-initialized");e.dataLayerName&&(mn=e.dataLayerName),e.gtagName&&(vn=e.gtagName)}function In(e,t,r){n=[],ie()&&n.push("This is a browser extension environment."),ce()||n.push("Cookies are not available."),0<n.length&&(n=n.map((e,t)=>`(${t+1}) `+e).join(" "),n=Xr.create("invalid-analytics-context",{errorInfo:n}),Jr.warn(n.message));var n=e.options.appId;if(!n)throw Xr.create("no-app-id");if(!e.options.apiKey){if(!e.options.measurementId)throw Xr.create("no-api-key");Jr.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!=pn[n])throw Xr.create("already-exists",{id:n});if(!wn){{var i=mn;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]=rn(s,e,t,r),{gtagCore:s,wrappedGtag:window[i]}})(pn,fn,gn,mn,vn);yn=s,_n=a,wn=!0}return pn[n]=cn(e,fn,gn,t,_n,mn,r),new dn(e)}async function Tn(){if(ie())return!1;if(!ce())return!1;if(!he())return!1;try{return await ue()}catch(e){return!1}}function En(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})})(yn,pn[e.app.options.appId],t,r).catch(e=>Jr.error(e))}function Cn(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})})(yn,pn[e.app.options.appId],t,r).catch(e=>Jr.error(e))}function kn(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})})(yn,pn[e.app.options.appId],t,r).catch(e=>Jr.error(e))}function Sn(e,t){e=w(e),(async(e,t)=>{var r=await e;window["ga-disable-"+r]=!t})(pn[e.app.options.appId],t).catch(e=>Jr.error(e))}function An(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,Object.assign(Object.assign({},n),{send_to:s})))})(yn,pn[e.app.options.appId],t,r,n).catch(e=>Jr.error(e))}let Nn="@firebase/analytics",Rn="0.10.11";Ct(new u(Wr,(e,{options:t})=>In(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),t),"PUBLIC")),Ct(new u("analytics-internal",function(e){try{let n=e.getProvider(Wr).getImmediate();return{logEvent:(e,t,r)=>An(n,e,t,r)}}catch(e){throw Xr.create("interop-component-reg-failed",{reason:e})}},"PRIVATE")),d(Nn,Rn),d(Nn,Rn,"esm2017");class Pn{constructor(e,t){this.app=e,this._delegate=t}logEvent(e,t,r){An(this._delegate,e,t,r)}setCurrentScreen(e,t){En(this._delegate,e,t)}setUserId(e,t){Cn(this._delegate,e,t)}setUserProperties(e,t){kn(this._delegate,e,t)}setAnalyticsCollectionEnabled(e){Sn(this._delegate,e)}}(t=ym=ym||{}).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 Dn=e=>{var t=e.getProvider("app-compat").getImmediate(),r=e.getProvider("analytics").getImmediate();return new Pn(t,r)};e={Analytics:Pn,settings:bn,isSupported:Tn,EventName:ym},tr.INTERNAL.registerComponent(new u("analytics-compat",Dn,"PUBLIC").setServiceProps(e).setMultipleInstances(!0)),tr.registerVersion("@firebase/analytics-compat","0.2.17");let xn=new Map,On={activated:!1,tokenObservers:[]},Ln={initialized:!1,enabled:!1};function Mn(e){return xn.get(e)||Object.assign({},On)}let Fn="https://content-firebaseappcheck.googleapis.com/v1",Un="exchangeDebugToken",Vn={OFFSET_DURATION:3e5,RETRIAL_MIN_WAIT:3e4,RETRIAL_MAX_WAIT:96e4};class qn{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 X,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 X,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 jn=new pe("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.",throttled:"Requests throttled due to {$httpStatus} error. Attempts allowed again after {$time}"});function Bn(e=!1){var t;return e?null==(t=self.grecaptcha)?void 0:t.enterprise:self.grecaptcha}function zn(e){if(!Mn(e).activated)throw jn.create("use-before-activation",{appName:e.name})}function Kn(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+=Wn(r)+"d:"),n&&(s+=Wn(n)+"h:"),s+=Wn(i)+"m:"+Wn(t)+"s"}function Wn(e){return 0===e?"00":10<=e?e.toString():"0"+e}async function Hn({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 jn.create("fetch-network-error",{originalErrorMessage:null==e?void 0:e.message})}if(200!==s.status)throw jn.create("fetch-status-error",{httpStatus:s.status});let a;try{a=await s.json()}catch(e){throw jn.create("fetch-parse-error",{originalErrorMessage:null==e?void 0: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 jn.create("fetch-parse-error",{originalErrorMessage:"ttl field (timeToLive) is not in standard Protobuf Duration format: "+a.ttl})}function Gn(e,t){var{projectId:r,appId:n,apiKey:i}=e.options;return{url:`${Fn}/projects/${r}/apps/${n}:${Un}?key=`+i,body:{debug_token:t}}}let $n="firebase-app-check-database",Qn=1,Yn="firebase-app-check-store",Jn="debug-token",Xn=null;function Zn(){return Xn=Xn||new Promise((t,r)=>{try{var e=indexedDB.open($n,Qn);e.onsuccess=e=>{t(e.target.result)},e.onerror=e=>{var t;r(jn.create("storage-open",{originalErrorMessage:null==(t=e.target.error)?void 0:t.message}))},e.onupgradeneeded=e=>{var t=e.target.result;0===e.oldVersion&&t.createObjectStore(Yn,{keyPath:"compositeKey"})}}catch(e){r(jn.create("storage-open",{originalErrorMessage:null==e?void 0:e.message}))}})}async function ei(e,t){let n=(await Zn()).transaction(Yn,"readwrite"),i=n.objectStore(Yn).put({compositeKey:e,value:t});return new Promise((t,r)=>{i.onsuccess=e=>{t()},n.onerror=e=>{var t;r(jn.create("storage-set",{originalErrorMessage:null==(t=e.target.error)?void 0:t.message}))}})}async function ti(e){let t=(await Zn()).transaction(Yn,"readonly"),i=t.objectStore(Yn).get(e);return new Promise((r,n)=>{i.onsuccess=e=>{var t=e.target.result;r(t?t.value:void 0)},t.onerror=e=>{var t;n(jn.create("storage-get",{originalErrorMessage:null==(t=e.target.error)?void 0:t.message}))}})}function ri(e){return e.options.appId+"-"+e.name}let ni=new $e("@firebase/app-check");async function ii(t){if(he()){let e=void 0;try{e=await ti(ri(t))}catch(e){ni.warn("Failed to read token from IndexedDB. Error: "+e)}return e}}function si(e,t){return he()?ei(ri(e),t).catch(e=>{ni.warn("Failed to write token to IndexedDB. Error: "+e)}):Promise.resolve()}async function ai(){let e=void 0;try{e=await ti(Jn)}catch(e){}var t,r;return e||(t=crypto.randomUUID(),r=t,ei(Jn,r).catch(e=>ni.warn("Failed to persist debug token to IndexedDB. Error: "+e)),t)}function oi(){return Ln.enabled}async function li(){var e=Ln;if(e.enabled&&e.token)return e.token.promise;throw Error(`
|
|
8
8
|
Can't get debug token in production mode.
|
|
9
|
-
`)}let hi={error:"UNKNOWN_ERROR"};async function ui(e,t=!1){var r,n=e.app;zn(n);let i=Mn(n),s=i.token,a=void 0;if(s&&!gi(s)&&(i.token=void 0,s=void 0),s||(r=await i.cachedTokenPromise)&&(gi(r)?s=r:await si(n,void 0)),!t&&s&&gi(s))return{token:s.token};let o=!1;if(oi())return i.exchangeTokenPromise||(i.exchangeTokenPromise=Hn(Gn(n,await li()),e.heartbeatServiceProvider).finally(()=>{i.exchangeTokenPromise=void 0}),o=!0),await si(n,r=await i.exchangeTokenPromise),{token:(i.token=r).token};try{i.exchangeTokenPromise||(i.exchangeTokenPromise=i.provider.getToken().finally(()=>{i.exchangeTokenPromise=void 0}),o=!0),s=await Mn(n).exchangeTokenPromise}catch(e){"appCheck/throttled"===e.code?ni.warn(e.message):ni.error(e),a=e}let l;return s?a?l=gi(s)?{token:s.token,internalError:a}:mi(a):(l={token:s.token},await si(n,i.token=s)):l=mi(a),o&&fi(n,l),l}function ci(t,e,r,n){var i=t.app,i=Mn(i),s={next:r,error:n,type:e};if(i.tokenObservers=[...i.tokenObservers,s],i.token&&gi(i.token)){let e=i.token;Promise.resolve().then(()=>{r({token:e.token}),pi(t)}).catch(()=>{})}i.cachedTokenPromise.then(()=>pi(t))}function di(e,t){var r=Mn(e),n=r.tokenObservers.filter(e=>e.next!==t);0===n.length&&r.tokenRefresher&&r.tokenRefresher.isRunning()&&r.tokenRefresher.stop(),r.tokenObservers=n}function pi(e){var t=e.app,t=Mn(t);let r=t.tokenRefresher;r||(r=(r=>{let n=r.app;return new qn(async()=>{var e=Mn(n);let t;if((t=e.token?await ui(r,!0):await ui(r)).error)throw t.error;if(t.internalError)throw t.internalError},()=>!0,()=>{var e,t=Mn(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},Vn.RETRIAL_MIN_WAIT,Vn.RETRIAL_MAX_WAIT)})(e),t.tokenRefresher=r),!r.isRunning()&&t.isTokenAutoRefreshEnabled&&r.start()}function fi(e,t){var r;for(r of Mn(e).tokenObservers)try{"EXTERNAL"===r.type&&null!=t.error?r.error(t.error):r.next(t)}catch(e){}}function gi(e){return 0<e.expireTimeMillis-Date.now()}function mi(e){return{token:(t=hi,s.encodeString(JSON.stringify(t),!1)),error:e};var t}class vi{constructor(e,t){this.app=e,this.heartbeatServiceProvider=t}_delete(){var e,t=Mn(this.app).tokenObservers;for(e of t)di(this.app,e.next);return Promise.resolve()}}function _i(t){return{getToken:e=>ui(t,e),getLimitedUseToken:()=>(async e=>{var t=e.app,r=(zn(t),Mn(t)).provider;return oi()?{token:t=(await Hn(Gn(t,await li()),e.heartbeatServiceProvider)).token}:{token:t=(await r.getToken()).token}})(t),addTokenListener:e=>ci(t,"INTERNAL",e),removeTokenListener:e=>di(t.app,e)}}let yi="https://www.google.com/recaptcha/api.js",wi="https://www.google.com/recaptcha/enterprise.js";function bi(t,r){let n=new X;Mn(t).reCAPTCHAState={initialized:n};let i=Ei(t);var e,s=Bn(!1);return s?Ti(t,r,s,i,n):(e=()=>{var e=Bn(!1);if(!e)throw new Error("no recaptcha");Ti(t,r,e,i,n)},(s=document.createElement("script")).src=yi,s.onload=e,document.head.appendChild(s)),n.promise}function Ii(t,r){let n=new X;Mn(t).reCAPTCHAState={initialized:n};let i=Ei(t);var e,s=Bn(!0);return s?Ti(t,r,s,i,n):(e=()=>{var e=Bn(!0);if(!e)throw new Error("no recaptcha");Ti(t,r,e,i,n)},(s=document.createElement("script")).src=wi,s.onload=e,document.head.appendChild(s)),n.promise}function Ti(n,i,s,a,o){s.ready(()=>{var e,t,r;e=n,t=s.render(a,{sitekey:i,size:"invisible",callback:()=>{Mn(e).reCAPTCHAState.succeeded=!0},"error-callback":()=>{Mn(e).reCAPTCHAState.succeeded=!1}}),(r=Mn(e)).reCAPTCHAState=Object.assign(Object.assign({},r.reCAPTCHAState),{widgetId:t}),o.resolve(s)})}function Ei(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 Ci(n){zn(n);let i=await Mn(n).reCAPTCHAState.initialized.promise;return new Promise((e,t)=>{let r=Mn(n).reCAPTCHAState;i.ready(()=>{e(i.execute(r.widgetId,{action:"fire_app_check"}))})})}class ki{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){Ri(this._throttleData);var t,r=await Ci(this._app).catch(e=>{throw jn.create("recaptcha-error")});if(null==(t=Mn(this._app).reCAPTCHAState)||!t.succeeded)throw jn.create("recaptcha-error");let e;try{e=await Hn(((e,t)=>{var{projectId:r,appId:n,apiKey:i}=e.options;return{url:Fn+`/projects/${r}/apps/${n}:exchangeRecaptchaV3Token?key=`+i,body:{recaptcha_v3_token:t}}})(this._app,r),this._heartbeatServiceProvider)}catch(e){throw null!=(t=e.code)&&t.includes("fetch-status-error")?(this._throttleData=Ni(Number(null==(r=e.customData)?void 0:r.httpStatus),this._throttleData),jn.create("throttled",{time:Kn(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,e}initialize(e){this._app=e,this._heartbeatServiceProvider=kt(e,"heartbeat"),bi(e,this._siteKey).catch(()=>{})}isEqual(e){return e instanceof ki&&this._siteKey===e._siteKey}}class Si{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){Ri(this._throttleData);var t,r=await Ci(this._app).catch(e=>{throw jn.create("recaptcha-error")});if(null==(t=Mn(this._app).reCAPTCHAState)||!t.succeeded)throw jn.create("recaptcha-error");let e;try{e=await Hn(((e,t)=>{var{projectId:r,appId:n,apiKey:i}=e.options;return{url:Fn+`/projects/${r}/apps/${n}:exchangeRecaptchaEnterpriseToken?key=`+i,body:{recaptcha_enterprise_token:t}}})(this._app,r),this._heartbeatServiceProvider)}catch(e){throw null!=(t=e.code)&&t.includes("fetch-status-error")?(this._throttleData=Ni(Number(null==(r=e.customData)?void 0:r.httpStatus),this._throttleData),jn.create("throttled",{time:Kn(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,e}initialize(e){this._app=e,this._heartbeatServiceProvider=kt(e,"heartbeat"),Ii(e,this._siteKey).catch(()=>{})}isEqual(e){return e instanceof Si&&this._siteKey===e._siteKey}}class Ai{constructor(e){this._customProviderOptions=e}async getToken(){var e,t=await this._customProviderOptions.getToken(),r=(e=t.token,"object"==typeof(r=ve(e).claims)&&r.hasOwnProperty("iat")?r.iat:null),r=null!==r&&r<Date.now()&&0<r?1e3*r:Date.now();return Object.assign(Object.assign({},t),{issuedAtTimeMillis:r})}initialize(e){this._app=e}isEqual(e){return e instanceof Ai&&this._customProviderOptions.getToken.toString()===e._customProviderOptions.getToken.toString()}}function Ni(e,t){var r,n;return 404===e||403===e?{backoffCount:1,allowRequestsAfter:Date.now()+864e5,httpStatus:e}:(n=Ve(r=t?t.backoffCount:0,1e3,2),{backoffCount:r+1,allowRequestsAfter:Date.now()+n,httpStatus:e})}function Ri(e){if(e&&Date.now()-e.allowRequestsAfter<=0)throw jn.create("throttled",{time:Kn(e.allowRequestsAfter-Date.now()),httpStatus:e.httpStatus})}function Pi(e=Ot(),r){var t=kt(e=w(e),"app-check");if(Ln.initialized||(i=W(),(n=Ln).initialized=!0,"string"!=typeof i.FIREBASE_APPCHECK_DEBUG_TOKEN&&!0!==i.FIREBASE_APPCHECK_DEBUG_TOKEN)||(n.enabled=!0,s=new X,n.token=s,"string"==typeof i.FIREBASE_APPCHECK_DEBUG_TOKEN?s.resolve(i.FIREBASE_APPCHECK_DEBUG_TOKEN):s.resolve(ai())),oi()&&li().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 jn.create("already-initialized",{appName:e.name})}var s=t.initialize({options:r});{var a=e,o=r.provider;r=r.isTokenAutoRefreshEnabled;let t=((e,t)=>(xn.set(e,t),xn.get(e)))(a,Object.assign({},On));t.activated=!0,t.provider=o,t.cachedTokenPromise=ii(a).then(e=>(e&&gi(e)&&(t.token=e,fi(a,{token:e.token})),e)),t.isTokenAutoRefreshEnabled=void 0===r?a.automaticDataCollectionEnabled:r,t.provider.initialize(a)}return Mn(e).isTokenAutoRefreshEnabled&&ci(s,"INTERNAL",()=>{}),s}let Di="app-check-internal";Ct(new u("app-check",e=>{var t,r=e.getProvider("app").getImmediate(),n=e.getProvider("heartbeat");return e=r,t=n,new vi(e,t)},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,r)=>{e.getProvider(Di).initialize()})),Ct(new u(Di,e=>_i(e.getProvider("app-check").getImmediate()),"PUBLIC").setInstantiationMode("EXPLICIT")),d("@firebase/app-check","0.8.11");let xi=new pe("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 Oi{constructor(e){this.app=e}activate(e,t){let r;r="string"==typeof e?new ki(e):e instanceof Si||e instanceof ki||e instanceof Ai?e:new Ai({getToken:e.getToken}),this._delegate=Pi(this.app,{provider:r,isTokenAutoRefreshEnabled:t})}setTokenAutoRefreshEnabled(e){if(!this._delegate)throw xi.create("use-before-activation",{appName:this.app.name});var t,r;t=this._delegate,e=e,(r=Mn(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 ui(e,t);if(r.error)throw r.error;return{token:r.token}})(this._delegate,e);throw xi.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),ci(i,"EXTERNAL",e,t),()=>di(i.app,e)}throw xi.create("use-before-activation",{appName:this.app.name})}}let Li=e=>{var t=e.getProvider("app-compat").getImmediate();return new Oi(t)};function Mi(e,t){var r={};for(i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(r[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var n=0,i=Object.getOwnPropertySymbols(e);n<i.length;n++)t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(r[i[n]]=e[i[n]]);return r}tr.INTERNAL.registerComponent(new u("appCheck-compat",Li,"PUBLIC").setServiceProps({ReCaptchaEnterpriseProvider:Si,ReCaptchaV3Provider:ki,CustomProvider:Ai})),tr.registerVersion("@firebase/app-check-compat","0.3.18");let Fi={FACEBOOK:"facebook.com",GITHUB:"github.com",GOOGLE:"google.com",PASSWORD:"password",PHONE:"phone",TWITTER:"twitter.com"},Ui={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 Vi(){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 qi(){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 ji=Vi,Bi=new pe("auth","Firebase",Vi()),zi=new $e("@firebase/auth");function Ki(e,...t){zi.logLevel<=c.ERROR&&zi.error(`Auth (${Dt}): `+e,...t)}function Wi(e,...t){throw Yi(e,...t)}function Hi(e,...t){return Yi(e,...t)}function Gi(e,t,r){var n=Object.assign(Object.assign({},ji()),{[t]:r});return new pe("auth","Firebase",n).create(t,{appName:e.name})}function $i(e){return Gi(e,"operation-not-supported-in-this-environment","Operations that alter the current user are not supported in conjunction with FirebaseServerApp")}function Qi(e,t,r){var n=r;if(!(t instanceof n))throw n.name!==t.constructor.name&&Wi(e,"argument-error"),Gi(e,"argument-error",`Type of ${t.constructor.name} does not match expected instance.`+"Did you pass a reference from a different Auth SDK?")}function Yi(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)):Bi.create(e,...t)}function m(e,t,...r){if(!e)throw Yi(t,...r)}function Ji(e){var t="INTERNAL ASSERTION FAILED: "+e;throw Ki(t),new Error(t)}function Xi(e,t){e||Ji(t)}function Zi(){var e;return"undefined"!=typeof self&&(null==(e=self.location)?void 0:e.href)||""}function es(){return"http:"===ts()||"https:"===ts()}function ts(){var e;return"undefined"!=typeof self&&(null==(e=self.location)?void 0:e.protocol)||null}class rs{constructor(e,t){Xi((this.shortDelay=e)<(this.longDelay=t),"Short delay should be less than long delay!"),this.isMobile=te()||se()}get(){return"undefined"!=typeof navigator&&navigator&&"onLine"in navigator&&"boolean"==typeof navigator.onLine&&(es()||ie()||"connection"in navigator)&&!navigator.onLine?Math.min(5e3,this.shortDelay):this.isMobile?this.longDelay:this.shortDelay}}function ns(e,t){Xi(e.emulator,"Emulator should always be set here");var r=e.emulator.url;return t?""+r+(t.startsWith("/")?t.slice(1):t):r}class is{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 Ji("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 Ji("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 Ji("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"))}}let ss={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"},as=new rs(3e4,6e4);function os(e,t){return e.tenantId&&!t.tenantId?Object.assign(Object.assign({},t),{tenantId:e.tenantId}):t}async function ls(i,s,a,o,e={}){return hs(i,e,async()=>{let e={},t={};o&&("GET"===s?t=o:e={body:JSON.stringify(o)});var r=Ee(Object.assign({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),Object.assign({method:s,headers:n},e));return"undefined"!=typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||(n.referrerPolicy="no-referrer"),is.fetch()(cs(i,i.config.apiHost,a,r),n)})}async function hs(t,e,r){t._canInitEmulator=!1;var n=Object.assign(Object.assign({},ss),e);try{var i=new ds(t),s=await Promise.race([r(),i.promise]),a=(i.clearNetworkTimeout(),await s.json());if("needConfirmation"in a)throw ps(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 ps(t,"credential-already-in-use",a);if("EMAIL_EXISTS"===o)throw ps(t,"email-already-in-use",a);if("USER_DISABLED"===o)throw ps(t,"user-disabled",a);var h=n[o]||o.toLowerCase().replace(/[_\s]+/g,"-");if(l)throw Gi(t,h,l);Wi(t,h)}catch(e){if(e instanceof de)throw e;Wi(t,"network-request-failed",{message:String(e)})}}async function us(e,t,r,n,i={}){var s=await ls(e,t,r,n,i);return"mfaPendingCredential"in s&&Wi(e,"multi-factor-auth-required",{_serverResponse:s}),s}function cs(e,t,r,n){var i=""+t+r+"?"+n;return e.config.emulator?ns(e.config,i):e.config.apiScheme+"://"+i}class ds{clearNetworkTimeout(){clearTimeout(this.timer)}constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((e,t)=>{this.timer=setTimeout(()=>t(Hi(this.auth,"network-request-failed")),as.get())})}}function ps(e,t,r){var n={appName:e.name},n=(r.email&&(n.email=r.email),r.phoneNumber&&(n.phoneNumber=r.phoneNumber),Hi(e,t,n));return n.customData._tokenResponse=r,n}function fs(e){return void 0!==e&&void 0!==e.getResponse}function gs(e){return void 0!==e&&void 0!==e.enterprise}class ms{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 vs(e,t){return ls(e,"GET","/v2/recaptchaConfig",os(e,t))}async function _s(e,t){return ls(e,"POST","/v1/accounts:lookup",t)}function ys(e){if(e)try{var t=new Date(Number(e));if(!isNaN(t.getTime()))return t.toUTCString()}catch(e){}}function ws(e){return 1e3*Number(e)}function bs(e){var[t,r,n]=e.split(".");if(void 0===t||void 0===r||void 0===n)return Ki("JWT malformed, contained fewer than 3 sections"),null;try{var i=z(r);return i?JSON.parse(i):(Ki("Failed to decode base64 JWT payload"),null)}catch(e){return Ki("Caught error parsing JWT payload as JSON",null==e?void 0:e.toString()),null}}function Is(e){var t=bs(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 Ts(t,e,r=!1){if(r)return e;try{return await e}catch(e){throw e instanceof de&&(r=[e.code][0],"auth/user-disabled"===r||"auth/user-token-expired"===r)&&(t.auth.currentUser===t&&await t.auth.signOut()),e}}class Es{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=(null!=(t=this.user.stsTokenManager.expirationTime)?t: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"===(null==e?void 0:e.code)&&this.schedule(!0))}this.schedule()}}class Cs{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=ys(this.lastLoginAt),this.creationTime=ys(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function ks(e){var t,r,n=e.auth,i=await e.getIdToken(),i=await Ts(e,_s(n,{idToken:i})),n=(m(null==i?void 0:i.users.length,n,"internal-error"),i.users[0]),i=(e._notifyReloadListener(n),null!=(i=n.providerUserInfo)&&i.length?Ss(n.providerUserInfo):[]),i=(t=e.providerData,r=i,[...t.filter(t=>!r.some(e=>e.providerId===t.providerId)),...r]),s=!(e.email&&n.passwordHash||null!==i&&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 Cs(n.createdAt,n.lastLoginAt),isAnonymous:s};Object.assign(e,i)}function Ss(e){return e.map(e=>{var t=e.providerId,r=Mi(e,["providerId"]);return{providerId:t,uid:r.rawId||"",displayName:r.displayName||null,email:r.email||null,phoneNumber:r.phoneNumber||null,photoURL:r.photoUrl||null}})}class As{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):Is(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,t)}updateFromIdToken(e){m(0!==e.length,"internal-error");var t=Is(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 hs(n=e,{},async()=>{var e=Ee({grant_type:"refresh_token",refresh_token:i}).slice(1),{tokenApiHost:t,apiKey:r}=n.config,t=cs(n,t,"/v1/token","key="+r),r=await n._getAdditionalHeaders();return r["Content-Type"]="application/x-www-form-urlencoded",is.fetch()(t,{method:"POST",headers:r,body:e})})).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 As;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 As,this.toJSON())}_performRefresh(){return Ji("not implemented")}}function Ns(e,t){m("string"==typeof e||void 0===e,"internal-error",{appName:t})}class Rs{constructor(e){var{uid:t,auth:r,stsTokenManager:n}=e,i=Mi(e,["uid","auth","stsTokenManager"]);this.providerId="firebase",this.proactiveRefresh=new Es(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=t,this.auth=r,this.stsTokenManager=n,this.accessToken=n.accessToken,this.displayName=i.displayName||null,this.email=i.email||null,this.emailVerified=i.emailVerified||!1,this.phoneNumber=i.phoneNumber||null,this.photoURL=i.photoURL||null,this.isAnonymous=i.isAnonymous||!1,this.tenantId=i.tenantId||null,this.providerData=i.providerData?[...i.providerData]:[],this.metadata=new Cs(i.createdAt||void 0,i.lastLoginAt||void 0)}async getIdToken(e){var t=await Ts(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=bs(n),s=(m(i&&i.exp&&i.auth_time&&i.iat,r.auth,"internal-error"),null==(r="object"==typeof i.firebase?i.firebase:void 0)?void 0:r.sign_in_provider);return{claims:i,token:n,authTime:ys(ws(i.auth_time)),issuedAtTime:ys(ws(i.iat)),expirationTime:ys(ws(i.exp)),signInProvider:s||null,signInSecondFactor:(null==r?void 0:r.sign_in_second_factor)||null}})(this,e)}reload(){return(async e=>{var t=w(e);await ks(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=>Object.assign({},e)),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){var t=new Rs(Object.assign(Object.assign({},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 ks(this),await this.auth._persistUserIfCurrent(this),r&&this.auth._notifyListenersIfCurrent(this)}async delete(){var e;return h(this.auth.app)?Promise.reject($i(this.auth)):(e=await this.getIdToken(),await Ts(this,(async(e,t)=>ls(e,"POST","/v1/accounts:delete",t))(this.auth,{idToken:e})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut())}toJSON(){return Object.assign(Object.assign({uid:this.uid,email:this.email||void 0,emailVerified:this.emailVerified,displayName:this.displayName||void 0,isAnonymous:this.isAnonymous,photoURL:this.photoURL||void 0,phoneNumber:this.phoneNumber||void 0,tenantId:this.tenantId||void 0,providerData:this.providerData.map(e=>Object.assign({},e)),stsTokenManager:this.stsTokenManager.toJSON(),_redirectEventId:this._redirectEventId},this.metadata.toJSON()),{apiKey:this.auth.config.apiKey,appName:this.auth.name})}get refreshToken(){return this.stsTokenManager.refreshToken||""}static _fromJSON(e,t){var r=null!=(r=t.displayName)?r:void 0,n=null!=(n=t.email)?n:void 0,i=null!=(i=t.phoneNumber)?i:void 0,s=null!=(s=t.photoURL)?s:void 0,a=null!=(a=t.tenantId)?a:void 0,o=null!=(o=t._redirectEventId)?o:void 0,l=null!=(l=t.createdAt)?l:void 0,h=null!=(h=t.lastLoginAt)?h:void 0,{uid:u,emailVerified:c,isAnonymous:d,providerData:p,stsTokenManager:f}=t,f=(m(u&&f,e,"internal-error"),As.fromJSON(this.name,f)),u=(m("string"==typeof u,e,"internal-error"),Ns(r,e.name),Ns(n,e.name),m("boolean"==typeof c,e,"internal-error"),m("boolean"==typeof d,e,"internal-error"),Ns(i,e.name),Ns(s,e.name),Ns(a,e.name),Ns(o,e.name),Ns(l,e.name),Ns(h,e.name),new Rs({uid:u,auth:e,email:n,emailVerified:c,displayName:r,isAnonymous:d,photoURL:s,phoneNumber:i,tenantId:a,stsTokenManager:f,createdAt:l,lastLoginAt:h}));return p&&Array.isArray(p)&&(u.providerData=p.map(e=>Object.assign({},e))),o&&(u._redirectEventId=o),u}static async _fromIdTokenResponse(e,t,r=!1){var n=new As,n=(n.updateFromServerResponse(t),new Rs({uid:t.localId,auth:e,stsTokenManager:n,isAnonymous:r}));return await ks(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?Ss(n.providerUserInfo):[]),s=!(n.email&&n.passwordHash||null!=i&&i.length),a=new As,a=(a.updateFromIdToken(r),new Rs({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 Cs(n.createdAt,n.lastLoginAt),isAnonymous:!(n.email&&n.passwordHash||null!=i&&i.length)};return Object.assign(a,s),a}}let Ps=new Map;function Ds(e){Xi(e instanceof Function,"Expected a class definition");var t=Ps.get(e);return t?Xi(t instanceof e,"Instance stored in cache mismatched with class"):(t=new e,Ps.set(e,t)),t}class xs{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){}}xs.type="NONE";let Os=xs;function Ls(e,t,r){return`firebase:${e}:${t}:`+r}class Ms{constructor(e,t,r){this.persistence=e,this.auth=t,this.userKey=r;var{config:n,name:i}=this.auth;this.fullUserKey=Ls(this.userKey,n.apiKey,i),this.fullPersistenceKey=Ls("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=await this.persistence._get(this.fullUserKey);return e?Rs._fromJSON(this.auth,e):null}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(e){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(e,t,r="authUser"){if(!t.length)return new Ms(Ds(Os),e,r);var n,i=(await Promise.all(t.map(async e=>{if(await e._isAvailable())return e}))).filter(e=>e);let s=i[0]||Ds(Os),a=Ls(r,e.config.apiKey,e.name),o=null;for(n of t)try{var l=await n._get(a);if(l){var h=Rs._fromJSON(e,l);n!==s&&(o=h),s=n;break}}catch(e){}i=i.filter(e=>e._shouldAllowMigration);return s._shouldAllowMigration&&i.length&&(s=i[0],o&&await s._set(a,o.toJSON()),await Promise.all(t.map(async e=>{if(e!==s)try{await e._remove(a)}catch(e){}}))),new Ms(s,e,r)}}function Fs(e){var t=e.toLowerCase();return t.includes("opera/")||t.includes("opr/")||t.includes("opios/")?"Opera":js(t)?"IEMobile":t.includes("msie")||t.includes("trident/")?"IE":t.includes("edge/")?"Edge":Us(t)?"Firefox":t.includes("silk/")?"Silk":zs(t)?"Blackberry":Ks(t)?"Webos":Vs(t)?"Safari":!t.includes("chrome/")&&!qs(t)||t.includes("edge/")?Bs(t)?"Android":2===(null==(t=e.match(/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/))?void 0:t.length)?t[1]:"Other":"Chrome"}function Us(e=ee()){return/firefox\//i.test(e)}function Vs(e=ee()){var t=e.toLowerCase();return t.includes("safari/")&&!t.includes("chrome/")&&!t.includes("crios/")&&!t.includes("android")}function qs(e=ee()){return/crios\//i.test(e)}function js(e=ee()){return/iemobile/i.test(e)}function Bs(e=ee()){return/android/i.test(e)}function zs(e=ee()){return/blackberry/i.test(e)}function Ks(e=ee()){return/webos/i.test(e)}function Ws(e=ee()){return/iphone|ipad|ipod/i.test(e)||/macintosh/i.test(e)&&/mobile/i.test(e)}function Hs(e=ee()){return Ws(e)||Bs(e)||Ks(e)||zs(e)||/windows phone/i.test(e)||js(e)}function Gs(e,t=[]){let r;switch(e){case"Browser":r=Fs(ee());break;case"Worker":r=Fs(ee())+"-"+e;break;default:r=e}var n=t.length?t.join(","):"FirebaseCore-web";return`${r}/JsCore/${Dt}/`+n}class $s{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:null==e?void 0:e.message})}}}}class Qs{constructor(e){var t,r=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=null!=(t=r.minPasswordLength)?t:6,r.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=r.maxPasswordLength),void 0!==r.containsLowercaseCharacter&&(this.customStrengthOptions.containsLowercaseLetter=r.containsLowercaseCharacter),void 0!==r.containsUppercaseCharacter&&(this.customStrengthOptions.containsUppercaseLetter=r.containsUppercaseCharacter),void 0!==r.containsNumericCharacter&&(this.customStrengthOptions.containsNumericCharacter=r.containsNumericCharacter),void 0!==r.containsNonAlphanumericCharacter&&(this.customStrengthOptions.containsNonAlphanumericCharacter=r.containsNonAlphanumericCharacter),this.enforcementState=e.enforcementState,"ENFORCEMENT_STATE_UNSPECIFIED"===this.enforcementState&&(this.enforcementState="OFF"),this.allowedNonAlphanumericCharacters=null!=(r=null==(t=e.allowedNonAlphanumericCharacters)?void 0:t.join(""))?r:"",this.forceUpgradeOnSignin=null!=(t=e.forceUpgradeOnSignin)&&t,this.schemaVersion=e.schemaVersion}validatePassword(e){var t,r={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,r),this.validatePasswordCharacterOptions(e,r),r.isValid&&(r.isValid=null==(t=r.meetsMinPasswordLength)||t),r.isValid&&(r.isValid=null==(t=r.meetsMaxPasswordLength)||t),r.isValid&&(r.isValid=null==(t=r.containsLowercaseLetter)||t),r.isValid&&(r.isValid=null==(t=r.containsUppercaseLetter)||t),r.isValid&&(r.isValid=null==(t=r.containsNumericCharacter)||t),r.isValid&&(r.isValid=null==(t=r.containsNonAlphanumericCharacter)||t),r}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 Ys{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 Xs(this),this.idTokenSubscription=new Xs(this),this.beforeStateQueue=new $s(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=Bi,this._agentRecaptchaConfig=null,this._tenantRecaptchaConfigs={},this._projectPasswordPolicy=null,this._tenantPasswordPolicies={},this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=n.sdkClientVersion}_initializeWithPersistence(t,r){return r&&(this._popupRedirectResolver=Ds(r)),this._initializationPromise=this.queue(async()=>{var e;if(!this._deleted&&(this.persistenceManager=await Ms.create(this,t),!this._deleted)){if(null!=(e=this._popupRedirectResolver)&&e._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch(e){}await this.initializeCurrentUser(r),this.lastNotifiedUid=(null==(e=this.currentUser)?void 0:e.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 _s(this,{idToken:e}),r=await Rs._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=null==(t=this.redirectUser)?void 0:t._redirectEventId,r=null==s?void 0:s._redirectEventId,n=await this.tryRedirectSignIn(e),t&&t!==r||null==n||!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 ks(e)}catch(e){if("auth/network-request-failed"!==(null==e?void 0: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($i(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($i(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($i(this)):this.queue(async()=>{await this.assertedPersistence.setPersistence(Ds(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 ls(e=this,"GET","/v2/passwordPolicy",os(e,{})),t=new Qs(t);null===this.tenantId?this._projectPasswordPolicy=t:this._tenantPasswordPolicies[this.tenantId]=t}_getPersistence(){return this.assertedPersistence.persistence.type}_updateErrorMap(e){this._errorFactory=new pe("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 ls(e=this,"POST","/v2/accounts:revokeToken",os(e,t)))}toJSON(){var e;return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:null==(e=this._currentUser)?void 0:e.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&&Ds(e)||this._popupRedirectResolver,this,"argument-error"),this.redirectPersistenceManager=await Ms.create(this,[Ds(t._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()),this.redirectPersistenceManager}async _redirectUserForId(e){var t;return this._isInitialized&&await this.queue(async()=>{}),(null==(t=this._currentUser)?void 0:t._redirectEventId)===e?this._currentUser:(null==(t=this.redirectUser)?void 0:t._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=null!=(e=null==(e=this.currentUser)?void 0:e.uid)?e: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=Gs(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(null==(t=this.heartbeatServiceProvider.getImmediate({optional:!0}))?void 0:t.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:(null!=(e=await(null==(e=this.appCheckServiceProvider.getImmediate({optional:!0}))?void 0:e.getToken()))&&e.error&&(t="Error while retrieving App Check token: "+e.error,r=[],zi.logLevel<=c.WARN)&&zi.warn(`Auth (${Dt}): `+t,...r),null==e?void 0:e.token)}}function Js(e){return w(e)}class Xs{constructor(e){this.auth=e,this.observer=null,this.addObserver=Ae(e=>this.observer=e)}get next(){return m(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}let Zs={async loadJS(){throw new Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};function ea(e){return Zs.loadJS(e)}function ta(e){return"__"+e+Math.floor(1e6*Math.random())}class ra{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 sa(e,this.auth.name,t||{})),this.counter++,r}reset(e){var t,r=e||1e12;null!=(t=this._widgets.get(r))&&t.delete(),this._widgets.delete(r)}getResponse(e){var t;return(null==(t=this._widgets.get(e||1e12))?void 0:t.getResponse())||""}async execute(e){var t;return null!=(t=this._widgets.get(e||1e12))&&t.execute(),""}}class na{constructor(){this.enterprise=new ia}ready(e){e()}execute(e,t){return Promise.resolve("token")}render(e,t){return""}}class ia{ready(e){e()}execute(e,t){return Promise.resolve("token")}render(e,t){return""}}class sa{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 aa="NO_RECAPTCHA";class oa{constructor(e){this.type="recaptcha-enterprise",this.auth=Js(e)}async verify(i="verify",e=!1){function s(e,t,r){let n=window.grecaptcha;gs(n)?n.enterprise.ready(()=>{n.enterprise.execute(e,{action:i}).then(e=>{t(e)}).catch(()=>{t(aa)})}):r(Error("No reCAPTCHA enterprise script loaded."))}return this.auth.settings.appVerificationDisabledForTesting?(new na).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)=>{vs(i,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then(e=>{var t;if(void 0!==e.recaptchaKey)return t=new ms(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&&gs(window.grecaptcha))s(t,r,n);else if("undefined"==typeof window)n(new Error("RecaptchaVerifier is only supported in browser"));else{let e=Zs.recaptchaEnterpriseScript;0!==e.length&&(e+=t),ea(e).then(()=>{s(t,r,n)}).catch(e=>{n(e)})}}).catch(e=>{n(e)})})}}async function la(e,t,r,n=!1,i=!1){var s=new oa(e);let a;if(i)a=aa;else try{a=await s.verify(r)}catch(e){a=await s.verify(r,!0)}var o,l,s=Object.assign({},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 ha(r,n,i,s,e){var t;return"EMAIL_PASSWORD_PROVIDER"===e?null!=(t=r._getRecaptchaConfig())&&t.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")?(t=await la(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 la(r,n,i,"getOobCode"===i),s(r,t)):Promise.reject(e)}):"PHONE_PROVIDER"===e?null!=(t=r._getRecaptchaConfig())&&t.isProviderEnabled("PHONE_PROVIDER")?(t=await la(r,n,i),s(r,t).catch(async e=>{var t;if("AUDIT"===(null==(t=r._getRecaptchaConfig())?void 0:t.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 la(r,n,i,!1,!0),s(r,t);return Promise.reject(e)})):(t=await la(r,n,i,!1,!0),s(r,t)):Promise.reject(e+" provider is not supported.")}function ua(e,t,r){var n=Js(e),i=(m(n._canInitEmulator,n,"emulator-config-failed"),m(/^https?:\/\//.test(t),n,"invalid-emulator-scheme"),!(null==r||!r.disableWarnings)),s=ca(t),{host:a,port:o}=(e=>{var t,r=ca(e);return(r=/(\/\/)?([^?#/]+)/.exec(e.substr(r.length)))?(r=r[2].split("@").pop()||"",(t=/^(\[[^\]]+\])(:|$)/.exec(r))?{host:t=t[1],port:da(r.substr(t.length+1))}:([t,r]=r.split(":"),{host:t,port:da(r)})):{host:"",port:null}})(t);function l(){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.config.emulator={url:s+`//${a}${null===o?"":":"+o}/`},n.settings.appVerificationDisabledForTesting=!0,n.emulatorConfig=Object.freeze({host:a,port:o,protocol:s.replace(":",""),options:Object.freeze({disableWarnings:i})}),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",l):l()))}function ca(e){var t=e.indexOf(":");return t<0?"":e.substr(0,t+1)}function da(e){var t;return!e||(t=Number(e),isNaN(t))?null:t}class pa{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return Ji("not implemented")}_getIdTokenResponse(e){return Ji("not implemented")}_linkToIdToken(e,t){return Ji("not implemented")}_getReauthenticationResolver(e){return Ji("not implemented")}}async function fa(e,t){return ls(e,"POST","/v1/accounts:resetPassword",os(e,t))}async function ga(e,t){return ls(e,"POST","/v1/accounts:signUp",t)}async function ma(e,t){return us(e,"POST","/v1/accounts:signInWithPassword",os(e,t))}async function va(e,t){return ls(e,"POST","/v1/accounts:sendOobCode",os(e,t))}async function _a(e,t){return va(e,t)}async function ya(e,t){return va(e,t)}class wa extends pa{constructor(e,t,r,n=null){super("password",r),this._email=e,this._password=t,this._tenantId=n}static _fromEmailAndPassword(e,t){return new wa(e,t,"password")}static _fromEmailAndCode(e,t,r=null){return new wa(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(null!=t&&t.email&&null!=t&&t.password){if("password"===t.signInMethod)return this._fromEmailAndPassword(t.email,t.password);if("emailLink"===t.signInMethod)return this._fromEmailAndCode(t.email,t.password,t.tenantId)}return null}async _getIdTokenResponse(e){switch(this.signInMethod){case"password":return ha(e,{returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signInWithPassword",ma,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return(async(e,t)=>us(e,"POST","/v1/accounts:signInWithEmailLink",os(e,t)))(e,{email:this._email,oobCode:this._password});default:Wi(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":return ha(e,{idToken:t,returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",ga,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return(async(e,t)=>us(e,"POST","/v1/accounts:signInWithEmailLink",os(e,t)))(e,{idToken:t,email:this._email,oobCode:this._password});default:Wi(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function ba(e,t){return us(e,"POST","/v1/accounts:signInWithIdp",os(e,t))}class Ia extends pa{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){var t=new Ia(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):Wi("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="string"==typeof e?JSON.parse(e):e,{providerId:r,signInMethod:n}=t,t=Mi(t,["providerId","signInMethod"]);return r&&n?((r=new Ia(r,n)).idToken=t.idToken||void 0,r.accessToken=t.accessToken||void 0,r.secret=t.secret,r.nonce=t.nonce,r.pendingToken=t.pendingToken||null,r):null}_getIdTokenResponse(e){return ba(e,this.buildRequest())}_linkToIdToken(e,t){var r=this.buildRequest();return r.idToken=t,ba(e,r)}_getReauthenticationResolver(e){var t=this.buildRequest();return t.autoCreate=!1,ba(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=Ee(e)),t}}async function Ta(e,t){return ls(e,"POST","/v1/accounts:sendVerificationCode",os(e,t))}let Ea={USER_NOT_FOUND:"user-not-found"};class Ca extends pa{constructor(e){super("phone","phone"),this.params=e}static _fromVerification(e,t){return new Ca({verificationId:e,verificationCode:t})}static _fromTokenResponse(e,t){return new Ca({phoneNumber:e,temporaryProof:t})}_getIdTokenResponse(e){return(async(e,t)=>us(e,"POST","/v1/accounts:signInWithPhoneNumber",os(e,t)))(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return(async(e,t)=>{var r=await us(e,"POST","/v1/accounts:signInWithPhoneNumber",os(e,t));if(r.temporaryProof)throw ps(e,"account-exists-with-different-credential",r);return r})(e,Object.assign({idToken:t},this._makeVerificationRequest()))}_getReauthenticationResolver(e){return(async(e,t)=>us(e,"POST","/v1/accounts:signInWithPhoneNumber",os(e,Object.assign(Object.assign({},t),{operation:"REAUTH"})),Ea))(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 Ca({verificationId:t,verificationCode:r,phoneNumber:n,temporaryProof:i}):null}}class ka{constructor(e){var t=Ce(ke(e)),r=null!=(r=t.apiKey)?r:null,n=null!=(n=t.oobCode)?n: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}})(null!=(i=t.mode)?i:null);m(r&&n&&i,"argument-error"),this.apiKey=r,this.operation=i,this.code=n,this.continueUrl=null!=(r=t.continueUrl)?r:null,this.languageCode=null!=(i=t.languageCode)?i:null,this.tenantId=null!=(n=t.tenantId)?n:null}static parseLink(e){t=Ce(ke(e=e)).link,r=t?Ce(ke(t)).deep_link_id:null;var t,r,n=((n=Ce(ke(e)).deep_link_id)?Ce(ke(n)).link:null)||n||r||t||e;try{return new ka(n)}catch(e){return null}}}class Sa{constructor(){this.providerId=Sa.PROVIDER_ID}static credential(e,t){return wa._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){var r=ka.parseLink(t);return m(r,"argument-error"),wa._fromEmailAndCode(e,r.code,r.tenantId)}}Sa.PROVIDER_ID="password",Sa.EMAIL_PASSWORD_SIGN_IN_METHOD="password",Sa.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class Aa{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 Na extends Aa{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class Ra extends Na{static credentialFromJSON(e){var t="string"==typeof e?JSON.parse(e):e;return m("providerId"in t&&"signInMethod"in t,"argument-error"),Ia._fromParams(t)}credential(e){return this._credential(Object.assign(Object.assign({},e),{nonce:e.rawNonce}))}_credential(e){return m(e.idToken||e.accessToken,"argument-error"),Ia._fromParams(Object.assign(Object.assign({},e),{providerId:this.providerId,signInMethod:this.providerId}))}static credentialFromResult(e){return Ra.oauthCredentialFromTaggedObject(e)}static credentialFromError(e){return Ra.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 Ra(a)._credential({idToken:t,accessToken:r,nonce:s,pendingToken:i})}catch(e){return null}}}class Pa extends Na{constructor(){super("facebook.com")}static credential(e){return Ia._fromParams({providerId:Pa.PROVIDER_ID,signInMethod:Pa.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return Pa.credentialFromTaggedObject(e)}static credentialFromError(e){return Pa.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return Pa.credential(e.oauthAccessToken)}catch(e){return null}}}Pa.FACEBOOK_SIGN_IN_METHOD="facebook.com",Pa.PROVIDER_ID="facebook.com";class Da extends Na{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return Ia._fromParams({providerId:Da.PROVIDER_ID,signInMethod:Da.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return Da.credentialFromTaggedObject(e)}static credentialFromError(e){return Da.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthIdToken:t,oauthAccessToken:r}=e;if(!t&&!r)return null;try{return Da.credential(t,r)}catch(e){return null}}}Da.GOOGLE_SIGN_IN_METHOD="google.com",Da.PROVIDER_ID="google.com";class xa extends Na{constructor(){super("github.com")}static credential(e){return Ia._fromParams({providerId:xa.PROVIDER_ID,signInMethod:xa.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return xa.credentialFromTaggedObject(e)}static credentialFromError(e){return xa.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return xa.credential(e.oauthAccessToken)}catch(e){return null}}}xa.GITHUB_SIGN_IN_METHOD="github.com",xa.PROVIDER_ID="github.com";class Oa extends pa{constructor(e,t){super(e,e),this.pendingToken=t}_getIdTokenResponse(e){return ba(e,this.buildRequest())}_linkToIdToken(e,t){var r=this.buildRequest();return r.idToken=t,ba(e,r)}_getReauthenticationResolver(e){var t=this.buildRequest();return t.autoCreate=!1,ba(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 Oa(t,n):null}static _create(e,t){return new Oa(e,t)}buildRequest(){return{requestUri:"http://localhost",returnSecureToken:!0,pendingToken:this.pendingToken}}}class La extends Aa{constructor(e){m(e.startsWith("saml."),"argument-error"),super(e)}static credentialFromResult(e){return La.samlCredentialFromTaggedObject(e)}static credentialFromError(e){return La.samlCredentialFromTaggedObject(e.customData||{})}static credentialFromJSON(e){var t=Oa.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 Oa._create(r,t)}catch(e){return null}}}class Ma extends Na{constructor(){super("twitter.com")}static credential(e,t){return Ia._fromParams({providerId:Ma.PROVIDER_ID,signInMethod:Ma.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return Ma.credentialFromTaggedObject(e)}static credentialFromError(e){return Ma.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthAccessToken:t,oauthTokenSecret:r}=e;if(!t||!r)return null;try{return Ma.credential(t,r)}catch(e){return null}}}async function Fa(e,t){return us(e,"POST","/v1/accounts:signUp",os(e,t))}Ma.TWITTER_SIGN_IN_METHOD="twitter.com",Ma.PROVIDER_ID="twitter.com";class Ua{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 Rs._fromIdTokenResponse(e,r,n),s=Va(r);return new Ua({user:i,providerId:s,_tokenResponse:r,operationType:t})}static async _forOperation(e,t,r){await e._updateTokensIfNecessary(r,!0);var n=Va(r);return new Ua({user:e,providerId:n,_tokenResponse:r,operationType:t})}}function Va(e){return e.providerId||("phoneNumber"in e?"phone":null)}class qa extends de{constructor(e,t,r,n){var i;super(t.code,t.message),this.operationType=r,this.user=n,Object.setPrototypeOf(this,qa.prototype),this.customData={appName:e.name,tenantId:null!=(i=e.tenantId)?i:void 0,_serverResponse:t.customData._serverResponse,operationType:r}}static _fromErrorAndOperation(e,t,r,n){return new qa(e,t,r,n)}}function ja(t,r,e,n){return("reauthenticate"===r?e._getReauthenticationResolver(t):e._getIdTokenResponse(t)).catch(e=>{if("auth/multi-factor-auth-required"===e.code)throw qa._fromErrorAndOperation(t,e,r,n);throw e})}function Ba(e){return new Set(e.map(({providerId:e})=>e).filter(e=>!!e))}async function za(e,t){var r=w(e),n=(await Wa(!0,r,t),e=r.auth,t={idToken:await r.getIdToken(),deleteProvider:[t]},await ls(e,"POST","/v1/accounts:update",t)).providerUserInfo;let i=Ba(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 Ka(e,t,r=!1){var n=await Ts(e,t._linkToIdToken(e.auth,await e.getIdToken()),r);return Ua._forOperation(e,"link",n)}async function Wa(e,t,r){await ks(t);var n=!1===e?"provider-already-linked":"no-such-provider";m(Ba(t.providerData).has(r)===e,t.auth,n)}async function Ha(e,t,r=!1){var n=e.auth;if(h(n.app))return Promise.reject($i(n));var i="reauthenticate";try{var s=await Ts(e,ja(n,i,t,e),r),a=(m(s.idToken,n,"internal-error"),bs(s.idToken)),o=(m(a,n,"internal-error"),a).sub;return m(e.uid===o,n,"user-mismatch"),Ua._forOperation(e,i,s)}catch(e){throw"auth/user-not-found"===(null==e?void 0:e.code)&&Wi(n,"user-mismatch"),e}}async function Ga(e,t,r=!1){var n;return h(e.app)?Promise.reject($i(e)):(n=await ja(e,"signIn",t),n=await Ua._fromIdTokenResponse(e,"signIn",n),r||await e._updateCurrentUser(n.user),n)}async function $a(e,t){return Ga(Js(e),t)}async function Qa(e,t){var r=w(e);return await Wa(!1,r,t.providerId),Ka(r,t)}async function Ya(e,t){return Ha(w(e),t)}async function Ja(e,t){var r,n;return h(e.app)?Promise.reject($i(e)):(n=await us(r=Js(e),"POST","/v1/accounts:signInWithCustomToken",os(r,{token:t,returnSecureToken:!0})),n=await Ua._fromIdTokenResponse(r,"signIn",n),await r._updateCurrentUser(n.user),n)}class Xa{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?Za._fromServerResponse(e,t):"totpInfo"in t?eo._fromServerResponse(e,t):Wi(e,"internal-error")}}class Za extends Xa{constructor(e){super("phone",e),this.phoneNumber=e.phoneInfo}static _fromServerResponse(e,t){return new Za(t)}}class eo extends Xa{constructor(e){super("totp",e)}static _fromServerResponse(e,t){return new eo(t)}}function to(e,t,r){var n;m(0<(null==(n=r.url)?void 0:n.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 ro(e){var t=Js(e);t._getPasswordPolicyInternal()&&await t._updatePasswordPolicy()}async function no(e,t){await ls(e=w(e),"POST","/v1/accounts:update",os(e,{oobCode:t}))}async function io(e,t){var r=w(e),n=await fa(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=Xa._fromServerResponse(Js(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 so(e,t){var r=es()?Zi():"http://localhost",r=(await ls(e=w(e),"POST","/v1/accounts:createAuthUri",os(e,{identifier:t,continueUri:r}))).signinMethods;return r||[]}async function ao(e,t){var r=w(e),n={requestType:"VERIFY_EMAIL",idToken:await e.getIdToken()},r=(t&&to(r.auth,n,t),await va(r.auth,n)).email;r!==e.email&&await e.reload()}async function oo(e,t,r){var n=w(e),i={requestType:"VERIFY_AND_CHANGE_EMAIL",idToken:await e.getIdToken(),newEmail:t},n=(r&&to(n.auth,i,r),await va(n.auth,i)).email;n!==e.email&&await e.reload()}async function lo(e,{displayName:t,photoURL:r}){var n,i,s;void 0===t&&void 0===r||(i=await(n=w(e)).getIdToken(),i=await Ts(n,(async(e,t)=>ls(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 ho(e,t,r){var n=e.auth,i={idToken:await e.getIdToken(),returnSecureToken:!0},n=(t&&(i.email=t),r&&(i.password=r),await Ts(e,(async(e,t)=>ls(e,"POST","/v1/accounts:update",t))(n,i)));await e._updateTokensIfNecessary(n,!0)}class uo{constructor(e,t,r={}){this.isNewUser=e,this.providerId=t,this.profile=r}}class co extends uo{constructor(e,t,r,n){super(e,t,r),this.username=n}}class po extends uo{constructor(e,t){super(e,"facebook.com",t)}}class fo extends co{constructor(e,t){super(e,"github.com",t,"string"==typeof(null==t?void 0:t.login)?null==t?void 0:t.login:null)}}class go extends uo{constructor(e,t){super(e,"google.com",t)}}class mo extends co{constructor(e,t,r){super(e,"twitter.com",t,r)}}function vo(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&&null!=n&&n.idToken){t=null==(t=null==(t=bs(n.idToken))?void 0:t.firebase)?void 0:t.sign_in_provider;if(t)return t="anonymous"!==t&&"custom"!==t?t:null,new uo(a,t)}if(!i)return null;switch(i){case"facebook.com":return new po(a,s);case"github.com":return new fo(a,s);case"google.com":return new go(a,s);case"twitter.com":return new mo(a,s,n.screenName||null);case"custom":case"anonymous":return new uo(a,null);default:return new uo(a,i,s)}}class _o{constructor(e,t,r){this.type=e,this.credential=t,this.user=r}static _fromIdtoken(e,t){return new _o("enroll",e,t)}static _fromMfaPendingCredential(e){return new _o("signin",e)}toJSON(){return{multiFactorSession:{["enroll"===this.type?"idToken":"pendingCredential"]:this.credential}}}static fromJSON(e){var t;if(null!=e&&e.multiFactorSession){if(null!=(t=e.multiFactorSession)&&t.pendingCredential)return _o._fromMfaPendingCredential(e.multiFactorSession.pendingCredential);if(null!=(t=e.multiFactorSession)&&t.idToken)return _o._fromIdtoken(e.multiFactorSession.idToken)}return null}}class yo{constructor(e,t,r){this.session=e,this.hints=t,this.signInResolver=r}static _fromError(e,i){let s=Js(e),a=i.customData._serverResponse;var t=(a.mfaInfo||[]).map(e=>Xa._fromServerResponse(s,e));m(a.mfaPendingCredential,s,"internal-error");let o=_o._fromMfaPendingCredential(a.mfaPendingCredential);return new yo(o,t,async e=>{var t=await e._process(s,o),r=(delete a.mfaInfo,delete a.mfaPendingCredential,Object.assign(Object.assign({},a),{idToken:t.idToken,refreshToken:t.refreshToken}));switch(i.operationType){case"signIn":var n=await Ua._fromIdTokenResponse(s,i.operationType,r);return await s._updateCurrentUser(n.user),n;case"reauthenticate":return m(i.user,s,"internal-error"),Ua._forOperation(i.user,i.operationType,r);default:Wi(s,"internal-error")}})}async resolveSignIn(e){return this.signInResolver(e)}}function wo(e,t){return ls(e,"POST","/v2/accounts/mfaEnrollment:start",os(e,t))}class bo{constructor(t){this.user=t,this.enrolledFactors=[],t._onReload(e=>{e.mfaInfo&&(this.enrolledFactors=e.mfaInfo.map(e=>Xa._fromServerResponse(t.auth,e)))})}static _fromUser(e){return new bo(e)}async getSession(){return _o._fromIdtoken(await this.user.getIdToken(),this.user)}async enroll(e,t){var r=e,n=await this.getSession(),r=await Ts(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 Ts(this.user,(r=this.user.auth,n={idToken:i,mfaEnrollmentId:t},ls(r,"POST","/v2/accounts/mfaEnrollment:withdraw",os(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 Io=new WeakMap;let To="__sak";class Eo{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(To,"1"),this.storage.removeItem(To),Promise.resolve(!0)):Promise.resolve(!1)}catch(e){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 Co extends Eo{constructor(){super(()=>window.localStorage,"LOCAL"),this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t),this.listeners={},this.localCache={},this.pollTimer=null,this.fallbackToPolling=Hs(),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);ae()&&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]}}Co.type="LOCAL";let ko=Co;class So extends Eo{constructor(){super(()=>window.sessionStorage,"SESSION")}_addListener(e,t){}_removeListener(e,t){}}So.type="SESSION";let Ao=So;class No{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 No(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];null!=s&&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 Ro(e="",t=10){let r="";for(let n=0;n<t;n++)r+=Math.floor(10*Math.random());return e+r}No.receivers=[];class Po{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=Ro("",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 Do(){return window}function xo(){return void 0!==Do().WorkerGlobalScope&&"function"==typeof Do().importScripts}let Oo="firebaseLocalStorageDb",Lo="firebaseLocalStorage",Mo="fbase_key";class Fo{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 Uo(e,t){return e.transaction([Lo],t?"readwrite":"readonly").objectStore(Lo)}function Vo(){let n=indexedDB.open(Oo,1);return new Promise((t,r)=>{n.addEventListener("error",()=>{r(n.error)}),n.addEventListener("upgradeneeded",()=>{var e=n.result;try{e.createObjectStore(Lo,{keyPath:Mo})}catch(e){r(e)}}),n.addEventListener("success",async()=>{var e=n.result;e.objectStoreNames.contains(Lo)?t(e):(e.close(),e=indexedDB.deleteDatabase(Oo),await new Fo(e).toPromise(),t(await Vo()))})})}async function qo(e,t,r){var n=Uo(e,!0).put({fbase_key:t,value:r});return new Fo(n).toPromise()}function jo(e,t){var r=Uo(e,!0).delete(t);return new Fo(r).toPromise()}class Bo{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 Vo()),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 xo()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=No._getInstance(xo()?self:null),this.receiver._subscribe("keyChanged",async(e,t)=>({keyProcessed:(await this._poll()).includes(t.key)})),this.receiver._subscribe("ping",async(e,t)=>["keyChanged"])}async initializeSender(){var e,t;this.activeServiceWorker=await(async()=>{if(null==navigator||!navigator.serviceWorker)return null;try{return(await navigator.serviceWorker.ready).active}catch(e){return null}})(),this.activeServiceWorker&&(this.sender=new Po(this.activeServiceWorker),t=await this.sender._send("ping",{},800))&&null!=(e=t[0])&&e.fulfilled&&null!=(e=t[0])&&e.value.includes("keyChanged")&&(this.serviceWorkerReceiverAvailable=!0)}async notifyServiceWorker(e){var t;if(this.sender&&this.activeServiceWorker&&((null==(t=null==navigator?void 0:navigator.serviceWorker)?void 0:t.controller)||null)===this.activeServiceWorker)try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch(e){}}async _isAvailable(){try{var e;return indexedDB?(await qo(e=await Vo(),To,"1"),await jo(e,To),!0):!1}catch(e){}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=>qo(e,t,r)),this.localCache[t]=r,this.notifyServiceWorker(t)))}async _get(t){var e=await this._withRetries(e=>(async(e,t)=>{var r=Uo(e,!1).get(t);return void 0===(r=await new Fo(r).toPromise())?null:r.value})(e,t));return this.localCache[t]=e}async _remove(t){return this._withPendingWrite(async()=>(await this._withRetries(e=>jo(e,t)),delete this.localCache[t],this.notifyServiceWorker(t)))}async _poll(){var e=await this._withRetries(e=>{var t=Uo(e,!1).getAll();return new Fo(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()}}Bo.type="LOCAL";let zo=Bo;function Ko(e,t){return ls(e,"POST","/v2/accounts/mfaSignIn:start",os(e,t))}let Wo=ta("rcb"),Ho=new rs(3e4,6e4);class Go{constructor(){var e;this.hostLanguage="",this.counter=0,this.librarySeparatelyLoaded=!(null==(e=Do().grecaptcha)||!e.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)&&fs(Do().grecaptcha)?Promise.resolve(Do().grecaptcha):new Promise((t,r)=>{let n=Do().setTimeout(()=>{r(Hi(i,"network-request-failed"))},Ho.get());Do()[Wo]=()=>{Do().clearTimeout(n),delete Do()[Wo];var e=Do().grecaptcha;if(e&&fs(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(Hi(i,"internal-error"))},ea(Zs.recaptchaV2Script+"?"+Ee({onload:Wo,render:"explicit",hl:s})).catch(()=>{clearTimeout(n),r(Hi(i,"internal-error"))})})}clearedOneInstance(){this.counter--}shouldResolveImmediately(e){var t;return!(null==(t=Do().grecaptcha)||!t.render)&&(e===this.hostLanguage||0<this.counter||this.librarySeparatelyLoaded)}}class $o{async load(e){return new ra(e)}clearedOneInstance(){}}let Qo="recaptcha",Yo={theme:"light",type:"image"};class Jo{constructor(e,t,r=Object.assign({},Yo)){this.parameters=r,this.type=Qo,this.destroyed=!1,this.widgetId=null,this.tokenChangeListeners=new Set,this.renderPromise=null,this.recaptcha=null,this.auth=Js(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?$o:Go),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=Do()[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(es()&&!xo(),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 ls(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 Xo{constructor(e,t){this.verificationId=e,this.onConfirmation=t}confirm(e){var t=Ca._fromVerification(this.verificationId,e);return this.onConfirmation(t)}}async function Zo(t,r,n){var i,e,s,a,o,l,h,u;if(!t._getRecaptchaConfig())try{e=Js(t),s=await vs(e,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}),s=new ms(s),null==e.tenantId?e._agentRecaptchaConfig=s:e._tenantRecaptchaConfigs[e.tenantId]=s,await(!s.isAnyProviderEnabled()||!new oa(e).verify())}catch(e){console.log("Failed to initialize reCAPTCHA Enterprise config. Triggering the reCAPTCHA v2 verification.")}try{let e;return("session"in(e="string"==typeof r?{phoneNumber:r}:r)?(a=e.session,"phoneNumber"in e?(m("enroll"===a.type,t,"internal-error"),o={idToken:a.credential,phoneEnrollmentInfo:{phoneNumber:e.phoneNumber,clientType:"CLIENT_TYPE_WEB"}},(await ha(t,o,"mfaSmsEnrollment",async(e,t)=>t.phoneEnrollmentInfo.captchaResponse===aa?(m((null==n?void 0:n.type)===Qo,e,"argument-error"),wo(e,await el(e,t,n))):wo(e,t),"PHONE_PROVIDER").catch(e=>Promise.reject(e))).phoneSessionInfo):(m("signin"===a.type,t,"internal-error"),m(l=(null==(i=e.multiFactorHint)?void 0:i.uid)||e.multiFactorUid,t,"missing-multi-factor-info"),h={mfaPendingCredential:a.credential,mfaEnrollmentId:l,phoneSignInInfo:{clientType:"CLIENT_TYPE_WEB"}},(await ha(t,h,"mfaSmsSignIn",async(e,t)=>t.phoneSignInInfo.captchaResponse===aa?(m((null==n?void 0:n.type)===Qo,e,"argument-error"),Ko(e,await el(e,t,n))):Ko(e,t),"PHONE_PROVIDER").catch(e=>Promise.reject(e))).phoneResponseInfo)):(u={phoneNumber:e.phoneNumber,clientType:"CLIENT_TYPE_WEB"},await ha(t,u,"sendVerificationCode",async(e,t)=>t.captchaResponse===aa?(m((null==n?void 0:n.type)===Qo,e,"argument-error"),Ta(e,await el(e,t,n))):Ta(e,t),"PHONE_PROVIDER").catch(e=>Promise.reject(e)))).sessionInfo}finally{null!=n&&n._reset()}}async function el(e,t,r){m(r.type===Qo,e,"argument-error");var n,i,s,a,o=await r.verify(),l=(m("string"==typeof o,e,"argument-error"),Object.assign({},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 tl{constructor(e){this.providerId=tl.PROVIDER_ID,this.auth=Js(e)}verifyPhoneNumber(e,t){return Zo(this.auth,e,w(t))}static credential(e,t){return Ca._fromVerification(e,t)}static credentialFromResult(e){var t=e;return tl.credentialFromTaggedObject(t)}static credentialFromError(e){return tl.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){var t,r;return e&&({phoneNumber:t,temporaryProof:r}=e,t)&&r?Ca._fromTokenResponse(t,r):null}}function rl(e,t){return t?Ds(t):(m(e._popupRedirectResolver,e,"argument-error"),e._popupRedirectResolver)}tl.PROVIDER_ID="phone",tl.PHONE_SIGN_IN_METHOD="phone";class nl extends pa{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return ba(e,this._buildIdpRequest())}_linkToIdToken(e,t){return ba(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return ba(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 il(e){return Ga(e.auth,new nl(e),e.bypassAuthState)}function sl(e){var{auth:t,user:r}=e;return m(r,t,"internal-error"),Ha(r,new nl(e),e.bypassAuthState)}async function al(e){var{auth:t,user:r}=e;return m(r,t,"internal-error"),Ka(r,new nl(e),e.bypassAuthState)}class ol{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 il;case"linkViaPopup":case"linkViaRedirect":return al;case"reauthViaPopup":case"reauthViaRedirect":return sl;default:Wi(this.auth,"internal-error")}}resolve(e){Xi(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){Xi(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 ll=new rs(2e3,1e4);class hl extends ol{constructor(e,t,r,n,i){super(e,t,n,i),this.provider=r,this.authWindow=null,this.pollId=null,hl.currentPopupAction&&hl.currentPopupAction.cancel(),hl.currentPopupAction=this}async executeNotNull(){var e=await this.execute();return m(e,this.auth,"internal-error"),e}async onExecution(){Xi(1===this.filter.length,"Popup operations only handle one event");var e=Ro();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(Hi(this.auth,"web-storage-unsupported"))}),this.pollUserCancellation()}get eventId(){var e;return(null==(e=this.authWindow)?void 0:e.associatedEvent)||null}cancel(){this.reject(Hi(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,hl.currentPopupAction=null}pollUserCancellation(){let t=()=>{var e;null!=(e=null==(e=this.authWindow)?void 0:e.window)&&e.closed?this.pollId=window.setTimeout(()=>{this.pollId=null,this.reject(Hi(this.auth,"popup-closed-by-user"))},8e3):this.pollId=window.setTimeout(t,ll.get())};t()}}hl.currentPopupAction=null;let ul="pendingRedirect",cl=new Map;class dl extends ol{constructor(e,t,r=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,r),this.eventId=null}async execute(){let t=cl.get(this.auth._key());if(!t){try{let e=await(async(e,t)=>{var r,n=ml(t),i=gl(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)}cl.set(this.auth._key(),t)}return this.bypassAuthState||cl.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 pl(e,t){return gl(e)._set(ml(t),"true")}function fl(e,t){cl.set(e._key(),t)}function gl(e){return Ds(e._redirectPersistence)}function ml(e){return Ls(ul,e.config.apiKey,e.name)}function vl(e,t,r){return(async(e,t,r)=>{var n,i;return h(e.app)?Promise.reject($i(e)):(n=Js(e),Qi(e,t,Aa),await n._initializationPromise,await pl(i=rl(n,r),n),i._openRedirect(n,t,"signInViaRedirect"))})(e,t,r)}function _l(e,t,r){return(async(e,t,r)=>{var n=w(e);if(Qi(n.auth,t,Aa),h(n.auth.app))return Promise.reject($i(n.auth));await n.auth._initializationPromise;var i=rl(n.auth,r),s=(await pl(i,n.auth),await bl(n));return i._openRedirect(n.auth,t,"reauthViaRedirect",s)})(e,t,r)}function yl(e,t,r){return(async(e,t,r)=>{var n=w(e),i=(Qi(n.auth,t,Aa),await n.auth._initializationPromise,rl(n.auth,r)),s=(await Wa(!1,n,t.providerId),await pl(i,n.auth),await bl(n));return i._openRedirect(n.auth,t,"linkViaRedirect",s)})(e,t,r)}async function wl(e,t,r=!1){var n,i;return h(e.app)?Promise.reject($i(e)):(i=rl(n=Js(e),t),(i=await new dl(n,i,r).execute())&&!r&&(delete i.user._redirectEventId,await n._persistUserIfCurrent(i.user),await n._setRedirectUser(null,t)),i)}async function bl(e){var t=Ro(e.uid+":::");return e._redirectEventId=t,await e.auth._setRedirectUser(e),await e.auth._persistUserIfCurrent(e),t}class Il{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 El(e);default:return}})(t)||(this.hasHandledPotentialRedirect=!0,r)||(this.queuedRedirectEvent=t,r=!0),r}sendToConsumer(e,t){var r;e.error&&!El(e)?(r=(null==(r=e.error.code)?void 0:r.split("auth/")[1])||"internal-error",t.onError(Hi(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(Tl(e))}saveEventToCache(e){this.cachedEventUids.add(Tl(e)),this.lastProcessedEventTime=Date.now()}}function Tl(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter(e=>e).join("-")}function El({type:e,error:t}){return"unknown"===e&&"auth/no-auth-event"===(null==t?void 0:t.code)}async function Cl(e,t={}){return ls(e,"GET","/v1/projects",t)}let kl=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,Sl=/^https?/;async function Al(e){if(!e.config.emulator){var t,r=(await Cl(e)).authorizedDomains;for(t of r)try{if((e=>{var t,r=Zi(),{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:Sl.test(n)&&(kl.test(e)?i===e:(r=e.replace(/\./g,"\\."),(t=new RegExp("^(.+\\."+r+"|"+r+")$","i")).test(i)))})(t))return}catch(e){}Wi(e,"unauthorized-domain")}}let Nl=new rs(3e4,6e4);function Rl(){var t=Do().___jsl;if(null!=t&&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 Pl(i){return new Promise((e,t)=>{var r;function n(){Rl(),gapi.load("gapi.iframes",{callback:()=>{e(gapi.iframes.getContext())},ontimeout:()=>{Rl(),t(Hi(i,"network-request-failed"))},timeout:Nl.get()})}if(null!=(r=null==(r=Do().gapi)?void 0:r.iframes)&&r.Iframe)e(gapi.iframes.getContext());else{if(null==(r=Do().gapi)||!r.load)return r=ta("iframefcb"),Do()[r]=()=>{gapi.load?n():t(Hi(i,"network-request-failed"))},ea(Zs.gapiScript+"?onload="+r).catch(e=>t(e));n()}}).catch(e=>{throw Dl=null,e})}let Dl=null;let xl=new rs(5e3,15e3),Ol="__/auth/iframe",Ll="emulator/auth/iframe",Ml={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},Fl=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);async function Ul(a){e=a;var e,t,r,n=await(Dl=Dl||Pl(e)),i=Do().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?ns(n,Ll):`https://${e.config.authDomain}/`+Ol,n={apiKey:n.apiKey,appName:e.name,v:Dt},(r=Fl.get(e.config.apiHost))&&(n.eid=r),(r=e._getFrameworks()).length&&(n.fw=r.join(",")),t+"?"+Ee(n).slice(1)),messageHandlersFilter:i.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:Ml,dontclear:!0},s=>new Promise(async(e,t)=>{await s.restyle({setHideOnLeave:!1});let r=Hi(a,"network-request-failed"),n=Do().setTimeout(()=>{t(r)},xl.get());function i(){Do().clearTimeout(n),e(s)}s.ping(i).then(i,()=>{t(r)})}))}let Vl={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"};class ql{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch(e){}}}function jl(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=Object.assign(Object.assign({},Vl),{width:n.toString(),height:i.toString(),top:s,left:a}),a=ee().toLowerCase(),s=(r&&(o=qs(a)?"_blank":r),Us(a)&&(t=t||"http://localhost",s.scrollbars="yes"),Object.entries(s).reduce((e,[t,r])=>""+e+t+`=${r},`,""));if([n=ee()]=[a],Ws(n)&&null!=(a=window.navigator)&&a.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 ql(null);a=window.open(t||"",o,s);m(a,e,"popup-blocked");try{a.focus()}catch(e){}return new ql(a)}let Bl="__/auth/handler",zl="emulator/auth/handler",Kl=encodeURIComponent("fac");async function Wl(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:Dt,eventId:i};if(t instanceof Aa){t.setDefaultLanguage(e.languageCode),a.providerId=t.providerId||"",we(t.getCustomParameters())||(a.customParameters=JSON.stringify(t.getCustomParameters()));for(var[o,l]of Object.entries(s||{}))a[o]=l}t instanceof Na&&0<(c=t.getScopes().filter(e=>""!==e)).length&&(a.scopes=c.join(",")),e.tenantId&&(a.tid=e.tenantId);var h,u=a;for(h of Object.keys(u))void 0===u[h]&&delete u[h];var c=await e._getAppCheckToken(),c=c?`#${Kl}=`+encodeURIComponent(c):"";return`${r=[e.config][0],r.emulator?ns(r,zl):`https://${r.authDomain}/`+Bl}?`+Ee(u).slice(1)+c}let Hl="webStorageSupport";class Gl{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=Ao,this._completeRedirectFn=wl,this._overrideRedirectResult=fl}async _openPopup(e,t,r,n){Xi(null==(i=this.eventManagers[e._key()])?void 0:i.manager,"_initialize() not called before _openPopup()");var i=await Wl(e,t,r,Zi(),n);return jl(e,i,Ro())}async _openRedirect(e,t,r,n){await this._originValidation(e);var i=await Wl(e,t,r,Zi(),n);return Do().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):(Xi(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 Ul(t);let r=new Il(t);return e.register("authEvent",e=>(m(null==e?void 0: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(Hl,{type:Hl},e=>{var t=null==(t=null==e?void 0:e[0])?void 0:t[Hl];void 0!==t&&n(!!t),Wi(r,"internal-error")},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){var t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=Al(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return Hs()||Vs()||Ws()}}let $l=Gl;class Ql 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 Ji("unexpected MultiFactorSessionType")}}}{constructor(e){super("phone"),this.credential=e}static _fromCredential(e){return new Ql(e)}_finalizeEnroll(e,t,r){return e=e,t={idToken:t,displayName:r,phoneVerificationInfo:this.credential._makeVerificationRequest()},ls(e,"POST","/v2/accounts/mfaEnrollment:finalize",os(e,t))}_finalizeSignIn(e,t){return e=e,t={mfaPendingCredential:t,phoneVerificationInfo:this.credential._makeVerificationRequest()},ls(e,"POST","/v2/accounts/mfaSignIn:finalize",os(e,t))}}class Yl{constructor(){}static assertion(e){return Ql._fromCredential(e)}}Yl.FACTOR_ID="phone";Zt="@firebase/auth";class Jl{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){var e;return this.assertAuthConfigured(),(null==(e=this.auth.currentUser)?void 0:e.uid)||null}async getToken(e){return this.assertAuthConfigured(),await this.auth._initializationPromise,this.auth.currentUser?{accessToken:await this.auth.currentUser.getIdToken(e)}:null}addAuthTokenListener(t){var e;this.assertAuthConfigured(),this.internalListeners.has(t)||(e=this.auth.onIdTokenChanged(e=>{t((null==e?void 0: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 Xl;function Zl(){return window}t="authIdTokenMaxAge",null!=(er=Q())&&er["_"+t],Zs={loadJS(i){return new Promise((e,r)=>{var t,n=document.createElement("script");n.setAttribute("src",i),n.onload=e,n.onerror=e=>{var t=Hi("internal-error");t.customData=e,r(t)},n.type="text/javascript",n.charset="UTF-8",(null!=(t=null==(t=document.getElementsByTagName("head"))?void 0:t[0])?t:document).appendChild(n)})},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="},Xl="Browser",Ct(new u("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:Xl,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:Gs(Xl)}),a=new Ys(r,n,i,s);return e=a,r=(null==(t=t)?void 0:t.persistence)||[],r=(Array.isArray(r)?r:[r]).map(Ds),null!=t&&t.errorMap&&e._updateErrorMap(t.errorMap),e._initializeWithPersistence(r,null==t?void 0:t.popupRedirectResolver),a},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,r)=>{e.getProvider("auth-internal").initialize()})),Ct(new u("auth-internal",e=>{var t=Js(e.getProvider("auth").getImmediate());return e=t,new Jl(e)},"PRIVATE").setInstantiationMode("EXPLICIT")),d(Zt,"1.9.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}})(Xl)),d(Zt,"1.9.0","esm2017");async function eh(e,t,r){var n=Zl().BuildInfo,i=(Xi(t.sessionId,"AuthEvent did not contain a session ID"),i=(e=>{if(Xi(/[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 Ws()?s.ibi=n.packageName:Bs()?s.apn=n.packageName:Wi(e,"operation-not-supported-in-this-environment"),n.displayName&&(s.appDisplayName=n.displayName),s.sessionId=i,Wl(e,r,t.type,void 0,null!=(n=t.eventId)?n:void 0,s)}function th(n){let i=Zl().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=ee(),/(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 rh=20;class nh extends Il{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 ih(e,t,r=null){return{type:t,eventId:r,urlResponse:null,sessionId:(()=>{var e=[],t="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let n=0;n<rh;n++){var r=Math.floor(Math.random()*t.length);e.push(t.charAt(r))}return e.join("")})(),postBody:null,tenantId:e.tenantId,error:Hi(e,"no-auth-event")}}async function sh(e){var t=await oh()._get(lh(e));return t&&await oh()._remove(lh(e)),t}function ah(e,t){i=hh(t=t),n=i.link?decodeURIComponent(i.link):void 0,r=hh(n).link,i=i.deep_link_id?decodeURIComponent(i.deep_link_id):void 0;var r,n,i=hh(i).link||i||r||n||t;return i.includes("/__/auth/callback")?(n=(r=null==(n=null==(r=null==(n=(r=hh(i)).firebaseError?(e=>{try{return JSON.parse(e)}catch(e){return null}})(decodeURIComponent(r.firebaseError)):null)?void 0:n.code)?void 0:r.split("auth/"))?void 0:n[1])?Hi(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 oh(){return Ds(ko)}function lh(e){return Ls("authEvent",e.config.apiKey,e.name)}function hh(e){var t,r;return null!=e&&e.includes("?")?([t,...r]=e.split("?"),Ce(r.join("?"))):{}}class uh{constructor(){this._redirectPersistence=Ao,this._shouldInitProactively=!0,this.eventManagers=new Map,this.originValidationPromises={},this._completeRedirectFn=wl,this._overrideRedirectResult=fl}async _initialize(e){var t=e._key();let r=this.eventManagers.get(t);return r||(r=new nh(e),this.eventManagers.set(t,r),this.attachCallbackListeners(e,r)),r}_openPopup(e){Wi(e,"operation-not-supported-in-this-environment")}async _openRedirect(e,t,r,n){i=e,a=Zl(),m("function"==typeof(null==(s=null==a?void 0:a.universalLinks)?void 0:s.subscribe),i,"invalid-cordova-configuration",{missingPlugin:"cordova-universal-links-plugin-fix"}),m(void 0!==(null==(s=null==a?void 0:a.BuildInfo)?void 0:s.packageName),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-buildInfo"}),m("function"==typeof(null==(s=null==(s=null==(s=null==a?void 0:a.cordova)?void 0:s.plugins)?void 0:s.browsertab)?void 0:s.openUrl),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"}),m("function"==typeof(null==(s=null==(s=null==(s=null==a?void 0:a.cordova)?void 0:s.plugins)?void 0:s.browsertab)?void 0:s.isAvailable),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"}),m("function"==typeof(null==(a=null==(s=null==a?void 0:a.cordova)?void 0:s.InAppBrowser)?void 0:a.open),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-inappbrowser"});var i,s=await this._initialize(e),a=(await s.initialized(),s.resetRedirect(),cl.clear(),await this._originValidation(e),ih(e,r,n)),a=(i=e,r=a,await oh()._set(lh(i),r),await eh(e,a,t));return(async(a,o,l)=>{let h=Zl().cordova,u=()=>{};try{await new Promise((t,e)=>{let r=null;function n(){t();var e=null==(e=h.plugins.browsertab)?void 0:e.close;"function"==typeof e&&e(),"function"==typeof(null==l?void 0:l.close)&&l.close()}function i(){r=r||window.setTimeout(()=>{e(Hi(a,"redirect-cancelled-by-user"))},2e3)}function s(){"visible"===(null==document?void 0:document.visibilityState)&&i()}o.addPassiveListener(n),document.addEventListener("resume",i,!1),Bs()&&document.addEventListener("visibilitychange",s,!1),u=()=>{o.removePassiveListener(n),document.removeEventListener("resume",i,!1),document.removeEventListener("visibilitychange",s,!1),r&&window.clearTimeout(r)}})}finally{u()}})(e,s,await th(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=Zl().BuildInfo,r={};Ws()?r.iosBundleId=t.packageName:Bs()?r.androidPackageName=t.packageName:Wi(e,"operation-not-supported-in-this-environment"),await Cl(e,r)})(e)),this.originValidationPromises[t]}attachCallbackListeners(n,i){var{universalLinks:e,handleOpenURL:t,BuildInfo:r}=Zl();let s=setTimeout(async()=>{await sh(n),i.onEvent(dh())},500),a=async e=>{clearTimeout(s);var t=await sh(n);let r=null;t&&null!=e&&e.url&&(r=ah(t,e.url)),i.onEvent(r||dh())},o=(void 0!==e&&"function"==typeof e.subscribe&&e.subscribe(null,a),t),l=r.packageName.toLowerCase()+"://";Zl().handleOpenURL=async e=>{if(e.toLowerCase().startsWith(l)&&a({url:e}),"function"==typeof o)try{o(e)}catch(e){console.error(e)}}}}let ch=uh;function dh(){return{type:"unknown",eventId:null,sessionId:null,urlResponse:null,postBody:null,tenantId:null,error:Hi("no-auth-event")}}function ph(){var e;return(null==(e=null==self?void 0:self.location)?void 0:e.protocol)||null}function fh(e=ee()){return!("file:"!==ph()&&"ionic:"!==ph()&&"capacitor:"!==ph()||!e.toLowerCase().match(/iphone|ipad|ipod|android/))}function gh(e=ee()){return ae()&&11===(null==document?void 0:document.documentMode)||([e=ee()]=[e],/Edge\/\d+/.test(e))}function mh(){try{var e=self.localStorage,t=Ro();if(e)return e.setItem(t,"1"),e.removeItem(t),!gh()||he()}catch(e){return vh()&&he()}return!1}function vh(){return"undefined"!=typeof global&&"WorkerGlobalScope"in global&&"importScripts"in global}function _h(){return("http:"===ph()||"https:"===ph()||ie()||fh())&&!(se()||re())&&mh()&&!vh()}function yh(){return fh()&&"undefined"!=typeof document}let wh={LOCAL:"local",NONE:"none",SESSION:"session"},bh=m,Ih="persistence";async function Th(e){await e._initializationPromise;var t=Eh(),r=Ls(Ih,e.config.apiKey,e.name);t&&t.setItem(r,e._getPersistence())}function Eh(){var e;try{return(null===(e="undefined"!=typeof window?window:null)?void 0:e.sessionStorage)||null}catch(e){return null}}let Ch=m;class kh{constructor(){this.browserResolver=Ds($l),this.cordovaResolver=Ds(ch),this.underlyingResolver=null,this._redirectPersistence=Ao,this._completeRedirectFn=wl,this._overrideRedirectResult=fl}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 yh()||this.browserResolver._shouldInitProactively}get assertedUnderlyingResolver(){return Ch(this.underlyingResolver,"internal-error"),this.underlyingResolver}async selectUnderlyingResolver(){var e;this.underlyingResolver||(e=await(!!yh()&&new Promise(e=>{let t=setTimeout(()=>{e(!1)},1e3);document.addEventListener("deviceready",()=>{clearTimeout(t),e(!0)})})),this.underlyingResolver=e?this.cordovaResolver:this.browserResolver)}}function Sh(e){return e.unwrap()}function Ah(e,t){var r,n,i,s,a=null==(a=t.customData)?void 0:a._tokenResponse;"auth/multi-factor-auth-required"===(null==t?void 0:t.code)?t.resolver=new Dh(e,(r=t,i=w(e),m((s=r).customData.operationType,i,"argument-error"),m(null==(n=s.customData._serverResponse)?void 0:n.mfaPendingCredential,i,"argument-error"),yo._fromError(i,s))):a&&(i=Nh(n=t))&&(n.credential=i,n.tenantId=a.tenantId||void 0,n.email=a.email||void 0,n.phoneNumber=a.phoneNumber||void 0)}function Nh(e){var t=(e instanceof de?e.customData:e)._tokenResponse;if(!t)return null;if(!(e instanceof de)&&"temporaryProof"in t&&"phoneNumber"in t)return tl.credentialFromResult(e);var r=t.providerId;if(!r||r===Fi.PASSWORD)return null;let n;switch(r){case Fi.GOOGLE:n=Da;break;case Fi.FACEBOOK:n=Pa;break;case Fi.GITHUB:n=xa;break;case Fi.TWITTER:n=Ma;break;default:var{oauthIdToken:i,oauthAccessToken:s,oauthTokenSecret:a,pendingToken:o,nonce:l}=t;return s||a||i||o?o?r.startsWith("saml.")?Oa._create(r,o):Ia._fromParams({providerId:r,signInMethod:r,pendingToken:o,idToken:i,accessToken:s}):new Ra(r).credential({idToken:i,accessToken:s,rawNonce:l}):null}return e instanceof de?n.credentialFromError(e):n.credentialFromResult(e)}function Rh(t,e){return e.catch(e=>{throw e instanceof de&&Ah(t,e),e}).then(e=>{var t=e.operationType,r=e.user;return{operationType:t,credential:Nh(e),additionalUserInfo:vo(e),user:xh.getOrCreate(r)}})}async function Ph(t,e){let r=await e;return{verificationId:r.verificationId,confirm:e=>Rh(t,r.confirm(e))}}class Dh{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 Rh(Sh(this.auth),this.resolver.resolveSignIn(e))}}class xh{constructor(e){var t;this._delegate=e,this.multiFactor=(t=w(e),Io.has(t)||Io.set(t,bo._fromUser(t)),Io.get(t))}static getOrCreate(e){return xh.USER_MAP.has(e)||xh.USER_MAP.set(e,new xh(e)),xh.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 Rh(this.auth,Qa(this._delegate,e))}async linkWithPhoneNumber(e,t){return Ph(this.auth,(async(e,t,r)=>{let n=w(e);await Wa(!1,n,"phone");var i=await Zo(n.auth,t,w(r));return new Xo(i,e=>Qa(n,e))})(this._delegate,e,t))}async linkWithPopup(e){return Rh(this.auth,(async(e,t,r)=>{var n=w(e),i=(Qi(n.auth,t,Aa),rl(n.auth,r));return new hl(n.auth,"linkViaPopup",t,i,n).executeNotNull()})(this._delegate,e,kh))}async linkWithRedirect(e){return await Th(Js(this.auth)),yl(this._delegate,e,kh)}reauthenticateAndRetrieveDataWithCredential(e){return this.reauthenticateWithCredential(e)}async reauthenticateWithCredential(e){return Rh(this.auth,Ya(this._delegate,e))}reauthenticateWithPhoneNumber(e,t){return Ph(this.auth,(async(e,t,r)=>{let n=w(e);var i;return h(n.auth.app)?Promise.reject($i(n.auth)):(i=await Zo(n.auth,t,w(r)),new Xo(i,e=>Ya(n,e)))})(this._delegate,e,t))}reauthenticateWithPopup(e){return Rh(this.auth,(async(e,t,r)=>{var n=w(e);if(h(n.auth.app))return Promise.reject(Hi(n.auth,"operation-not-supported-in-this-environment"));Qi(n.auth,t,Aa);var i=rl(n.auth,r);return new hl(n.auth,"reauthViaPopup",t,i,n).executeNotNull()})(this._delegate,e,kh))}async reauthenticateWithRedirect(e){return await Th(Js(this.auth)),_l(this._delegate,e,kh)}sendEmailVerification(e){return ao(this._delegate,e)}async unlink(e){return await za(this._delegate,e),this}updateEmail(e){return t=this._delegate,e=e,h((r=w(t)).auth.app)?Promise.reject($i(r.auth)):ho(r,e,null);var t,r}updatePassword(e){return ho(w(this._delegate),null,e)}updatePhoneNumber(e){return(async(e,t)=>{var r=w(e);if(h(r.auth.app))return Promise.reject($i(r.auth));await Ka(r,t)})(this._delegate,e)}updateProfile(e){return lo(this._delegate,e)}verifyBeforeUpdateEmail(e,t){return oo(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}}xh.USER_MAP=new WeakMap;let Oh=m;class Lh{constructor(e,t){var r,n;this.app=e,t.isInitialized()?this._delegate=t.getImmediate():(r=e.options.apiKey,Oh(r,"invalid-api-key",{appName:e.name}),Oh(r,"invalid-api-key",{appName:e.name}),n="undefined"!=typeof window?kh:void 0,this._delegate=t.initialize({options:{persistence:((e,t)=>{var r=((e,t)=>{var r=Eh();if(!r)return[];var n=Ls(Ih,e,t);switch(r.getItem(n)){case wh.NONE:return[Os];case wh.LOCAL:return[zo,Ao];case wh.SESSION:return[Ao];default:return[]}})(e,t);if("undefined"==typeof self||r.includes(zo)||r.push(zo),"undefined"!=typeof window)for(var n of[ko,Ao])r.includes(n)||r.push(n);return r.includes(Os)||r.push(Os),r})(r,e.name),popupRedirectResolver:n}}),this._delegate._updateErrorMap(qi)),this.linkUnderlyingAuth()}get emulatorConfig(){return this._delegate.emulatorConfig}get currentUser(){return this._delegate.currentUser?xh.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){ua(this._delegate,e,t)}applyActionCode(e){return no(this._delegate,e)}checkActionCode(e){return io(this._delegate,e)}confirmPasswordReset(e,t){return(async(t,e,r)=>{await fa(w(t),{oobCode:e,newPassword:r}).catch(async e=>{throw"auth/password-does-not-meet-requirements"===e.code&&ro(t),e})})(this._delegate,e,t)}async createUserWithEmailAndPassword(e,t){return Rh(this._delegate,(async(t,e,r)=>{var n,i;return h(t.app)?Promise.reject($i(t)):(i=await ha(n=Js(t),{returnSecureToken:!0,email:e,password:r,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",Fa,"EMAIL_PASSWORD_PROVIDER").catch(e=>{throw"auth/password-does-not-meet-requirements"===e.code&&ro(t),e}),i=await Ua._fromIdTokenResponse(n,"signIn",i),await n._updateCurrentUser(i.user),i)})(this._delegate,e,t))}fetchProvidersForEmail(e){return this.fetchSignInMethodsForEmail(e)}fetchSignInMethodsForEmail(e){return so(this._delegate,e)}isSignInWithEmailLink(e){return this._delegate,e=e,"EMAIL_SIGNIN"===(null==(t=ka.parseLink(e))?void 0:t.operation);var t}async getRedirectResult(){Oh(_h(),this._delegate,"operation-not-supported-in-this-environment");e=this._delegate,t=kh,await Js(e)._initializationPromise;var e,t,r=await wl(e,t,!1);return r?Rh(this._delegate,Promise.resolve(r)):{credential:null,user:null}}addFrameworkForLogging(e){Js(this._delegate)._logFramework(e)}onAuthStateChanged(e,t,r){var{next:n,error:i,complete:s}=Mh(e,t,r);return this._delegate.onAuthStateChanged(n,i,s)}onIdTokenChanged(e,t,r){var{next:n,error:i,complete:s}=Mh(e,t,r);return this._delegate.onIdTokenChanged(n,i,s)}sendSignInLinkToEmail(e,t){return(async(e,t,r)=>{let n=Js(e);var i={requestType:"EMAIL_SIGNIN",email:t,clientType:"CLIENT_TYPE_WEB"};e=i,m((t=r).handleCodeInApp,n,"argument-error"),t&&to(n,e,t),await ha(n,i,"getOobCode",ya,"EMAIL_PASSWORD_PROVIDER")})(this._delegate,e,t)}sendPasswordResetEmail(e,t){return(async(e,t,r)=>{var n=Js(e),i={requestType:"PASSWORD_RESET",email:t,clientType:"CLIENT_TYPE_WEB"};r&&to(n,i,r),await ha(n,i,"getOobCode",_a,"EMAIL_PASSWORD_PROVIDER")})(this._delegate,e,t||void 0)}async setPersistence(e){var t,r;t=this._delegate,r=e,bh(Object.values(wh).includes(r),t,"invalid-persistence-type"),se()?bh(r!==wh.SESSION,t,"unsupported-persistence-type"):re()?bh(r===wh.NONE,t,"unsupported-persistence-type"):vh()?bh(r===wh.NONE||r===wh.LOCAL&&he(),t,"unsupported-persistence-type"):bh(r===wh.NONE||mh(),t,"unsupported-persistence-type");let n;switch(e){case wh.SESSION:n=Ao;break;case wh.LOCAL:var i=await Ds(zo)._isAvailable();n=i?zo:ko;break;case wh.NONE:n=Os;break;default:return Wi("argument-error",{appName:this._delegate.name})}return this._delegate.setPersistence(n)}signInAndRetrieveDataWithCredential(e){return this.signInWithCredential(e)}signInAnonymously(){return Rh(this._delegate,(async e=>{var t,r;return h(e.app)?Promise.reject($i(e)):(await(t=Js(e))._initializationPromise,null!=(r=t.currentUser)&&r.isAnonymous?new Ua({user:t.currentUser,providerId:null,operationType:"signIn"}):(r=await Fa(t,{returnSecureToken:!0}),r=await Ua._fromIdTokenResponse(t,"signIn",r,!0),await t._updateCurrentUser(r.user),r))})(this._delegate))}signInWithCredential(e){return Rh(this._delegate,$a(this._delegate,e))}signInWithCustomToken(e){return Rh(this._delegate,Ja(this._delegate,e))}signInWithEmailAndPassword(e,t){return Rh(this._delegate,(r=this._delegate,e=e,t=t,h(r.app)?Promise.reject($i(r)):$a(w(r),Sa.credential(e,t)).catch(async e=>{throw"auth/password-does-not-meet-requirements"===e.code&&ro(r),e})));var r}signInWithEmailLink(e,t){return Rh(this._delegate,(async(e,t,r)=>{var n,i;return h(e.app)?Promise.reject($i(e)):(n=w(e),m((i=Sa.credentialWithLink(t,r||Zi()))._tenantId===(n.tenantId||null),n,"tenant-id-mismatch"),$a(n,i))})(this._delegate,e,t))}signInWithPhoneNumber(e,t){return Ph(this._delegate,(async(e,t,r)=>{if(h(e.app))return Promise.reject($i(e));let n=Js(e);var i=await Zo(n,t,w(r));return new Xo(i,e=>$a(n,e))})(this._delegate,e,t))}async signInWithPopup(e){return Oh(_h(),this._delegate,"operation-not-supported-in-this-environment"),Rh(this._delegate,(async(e,t,r)=>{var n,i;return h(e.app)?Promise.reject(Hi(e,"operation-not-supported-in-this-environment")):(n=Js(e),Qi(e,t,Aa),i=rl(n,r),new hl(n,"signInViaPopup",t,i).executeNotNull())})(this._delegate,e,kh))}async signInWithRedirect(e){return Oh(_h(),this._delegate,"operation-not-supported-in-this-environment"),await Th(this._delegate),vl(this._delegate,e,kh)}updateCurrentUser(e){return this._delegate.updateCurrentUser(e)}verifyPasswordResetCode(e){return(async(e,t)=>{var r=(await io(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 Mh(e,t,r){let n=e,i=("function"!=typeof e&&({next:n,error:t,complete:r}=e),n);return{next:e=>i(e&&xh.getOrCreate(e)),error:t,complete:r}}Lh.Persistence=wh;class Fh{static credential(e,t){return tl.credential(e,t)}constructor(){this.providerId="phone",this._delegate=new tl(Sh(tr.auth()))}verifyPhoneNumber(e,t){return this._delegate.verifyPhoneNumber(e,t)}unwrap(){return this._delegate}}Fh.PHONE_SIGN_IN_METHOD=tl.PHONE_SIGN_IN_METHOD,Fh.PROVIDER_ID=tl.PROVIDER_ID;let Uh=m;class Vh{constructor(e,t,r=tr.app()){var n;Uh(null==(n=r.options)?void 0:n.apiKey,"invalid-api-key",{appName:r.name}),this._delegate=new Jo(r.auth(),e,t),this.type=this._delegate.type}clear(){this._delegate.clear()}render(){return this._delegate.render()}verify(){return this._delegate.verify()}}(t=tr).INTERNAL.registerComponent(new u("auth-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),r=e.getProvider("auth");return new Lh(t,r)},"PUBLIC").setServiceProps({ActionCodeInfo:{Operation:{EMAIL_SIGNIN:Ui.EMAIL_SIGNIN,PASSWORD_RESET:Ui.PASSWORD_RESET,RECOVER_EMAIL:Ui.RECOVER_EMAIL,REVERT_SECOND_FACTOR_ADDITION:Ui.REVERT_SECOND_FACTOR_ADDITION,VERIFY_AND_CHANGE_EMAIL:Ui.VERIFY_AND_CHANGE_EMAIL,VERIFY_EMAIL:Ui.VERIFY_EMAIL}},EmailAuthProvider:Sa,FacebookAuthProvider:Pa,GithubAuthProvider:xa,GoogleAuthProvider:Da,OAuthProvider:Ra,SAMLAuthProvider:La,PhoneAuthProvider:Fh,PhoneMultiFactorGenerator:Yl,RecaptchaVerifier:Vh,TwitterAuthProvider:Ma,Auth:Lh,AuthCredential:pa,Error:de}).setInstantiationMode("LAZY").setMultipleInstances(!1)),t.registerVersion("@firebase/auth-compat","0.5.18");let qh="@firebase/database",jh="";function Bh(e){jh=e}class zh{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),me(t))}get(e){var t=this.domStorage_.getItem(this.prefixedName_(e));return null==t?null:ge(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}class Kh{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){null==t?delete this.cache_[e]:this.cache_[e]=t}get(e){return _e(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}function Wh(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 zh(t)}catch(e){}return new Kh}var Hh;function Gh(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 Se,t=(r.update(t),r.digest());return s.encodeByteArray(t)}function $h(t){return function(...e){lu(t,...e)}}function Qh(...e){var t="FIREBASE INTERNAL ERROR: "+iu(...e);ru.error(t)}function Yh(e,t){return e===t?0:e<t?-1:1}function Jh(e,t){if(t&&e in t)return t[e];throw new Error("Missing required key ("+e+") in object: "+me(t))}function Xh(e){if("object"!=typeof e||null===e)return me(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+me(r[i])+":")+Xh(e[r[i]]);return n+="}"}function Zh(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 eu=Wh("localStorage"),tu=Wh("sessionStorage"),ru=new $e("@firebase/database"),nu=(()=>{let e=1;return function(){return e++}})(),iu=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+=iu.apply(null,r):t+="object"==typeof r?me(r):r,t+=" "}return t},su=null,au=!0,ou=function(e,t){g(!t||!0===e||!1===e,"Can't turn on custom loggers persistently."),!0===e?(ru.logLevel=c.VERBOSE,su=ru.log.bind(ru),t&&tu.set("logging_enabled",!0)):"function"==typeof e?su=e:(su=null,tu.remove("logging_enabled"))},lu=function(...e){var t;!0===au&&(au=!1,null===su)&&!0===tu.get("logging_enabled")&&ou(!0),su&&(t=iu.apply(null,e),su(t))},hu=function(...e){var t="FIREBASE FATAL ERROR: "+iu(...e);throw ru.error(t),new Error(t)},uu=function(...e){var t="FIREBASE WARNING: "+iu(...e);ru.warn(t)},cu=function(){"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&uu("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().")},du=function(e){return"number"==typeof e&&(e!=e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY)},pu="[MIN_NAME]",fu="[MAX_NAME]",gu=function(e,t){var r,n;return e===t?0:e===pu||t===fu?-1:t===pu||e===fu?1:(r=_u(e),n=_u(t),null!==r?null!==n?r-n==0?e.length-t.length:r-n:-1:null===n&&e<t?-1:1)};function mu(e,t){for(var r in e)e.hasOwnProperty(r)&&t(r,e[r])}function vu(e){g(!du(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 _u(e){if(wu.test(e)){var t=Number(e);if(t>=bu&&t<=Iu)return t}return null}function yu(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 wu=new RegExp("^-?(0*)\\d{1,10}$"),bu=-2147483648,Iu=2147483647,Tu=function(e){try{e()}catch(t){setTimeout(()=>{var e=t.stack||"";throw uu("Exception was thrown by user callback.",e),t},Math.floor(0))}};class Eu{constructor(e,t){this.appCheckProvider=t,this.appName=e.name,h(e)&&e.settings.appCheckToken&&(this.serverAppAppCheckToken=e.settings.appCheckToken),this.appCheck=null==t?void 0:t.getImmediate({optional:!0}),this.appCheck||null!=t&&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){var e;null!=(e=this.appCheckProvider)&&e.get().then(e=>e.addTokenListener(t))}notifyForInvalidToken(){uu(`Provided AppCheck credentials for the app named "${this.appName}" `+"are invalid. This usually indicates your app was not initialized correctly.")}}class Cu{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?(lu("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/.',uu(e)}}class ku{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}ku.OWNER="owner";let Su=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,Au="websocket",Nu="long_polling";class Ru{constructor(e,t,r,n,i=!1,s="",a=!1,o=!1){this.secure=t,this.namespace=r,this.webSocketOnly=n,this.nodeAdmin=i,this.persistenceKey=s,this.includeNamespaceInQueryParams=a,this.isUsingEmulator=o,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=eu.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())&&eu.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 Pu(e,t,r){g("string"==typeof t,"typeof type must == string"),g("object"==typeof r,"typeof params must == object");let n;if(t===Au)n=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?";else{if(t!==Nu)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 mu(r,(e,t)=>{i.push(e+"="+t)}),n+i.join("&")}class Du{constructor(){this.counters_={}}incrementCounter(e,t=1){_e(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return K(void 0,this.counters_)}}let xu={},Ou={};function Lu(e){var t=e.toString();return xu[t]||(xu[t]=new Du),xu[t]}class Mu{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]&&Tu(()=>{this.onMessage_(e[t])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}class Fu{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_=$h(e),this.stats_=Lu(t),this.urlFn=e=>(this.appCheckToken&&(e.ac=this.appCheckToken),Pu(t,Nu,e))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new Mu(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 Uu((...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&&Su.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(){Fu.forceAllow_=!0}static forceDisallow(){Fu.forceDisallow_=!0}static isAvailable(){return!!Fu.forceAllow_||!(Fu.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=me(e),t=(this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length),a(t)),r=Zh(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=me(e).length;this.bytesReceived+=t,this.stats_.incrementCounter("bytes_received",t)}}class Uu{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=nu(),window["pLPCommand"+this.uniqueCallbackIdentifier]=t,window["pRTLPCB"+this.uniqueCallbackIdentifier]=r,this.myIFrame=Uu.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){lu("frame writing exception"),e.stack&&lu(e.stack),lu(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||lu("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=()=>{lu("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(t)}}catch(e){}},Math.floor(1))}}let Vu=null;"undefined"!=typeof MozWebSocket?Vu=MozWebSocket:"undefined"!=typeof WebSocket&&(Vu=WebSocket);class qu{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_=$h(this.connId),this.stats_=Lu(t),this.connURL=qu.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&&Su.test(location.hostname)&&(s.r="f"),t&&(s.s=t),r&&(s.ls=r),n&&(s.ac=n),i&&(s.p=i),Pu(e,Au,s)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,eu.set("previous_websocket_failure",!0);try{oe(),this.mySock=new Vu(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(){qu.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!==Vu&&!qu.forceDisallow_}static previouslyFailed(){return eu.isInMemoryStorage||!0===eu.get("previous_websocket_failure")}markConnectionHealthy(){eu.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=ge(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=me(e),r=(this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length),Zh(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)}}}qu.responsesRequiredToBeHealthy=2,qu.healthyTimeout=3e4;class ju{static get ALL_TRANSPORTS(){return[Fu,qu]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}constructor(e){this.initTransports_(e)}initTransports_(e){var t=qu&&qu.isAvailable();let r=t&&!qu.previouslyFailed();if(e.webSocketOnly&&(t||uu("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),r=!0),r)this.transports_=[qu];else{var n,i=this.transports_=[];for(n of ju.ALL_TRANSPORTS)n&&n.isAvailable()&&i.push(n);ju.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}}ju.globalTransportInitialized_=!1;class Bu{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_=$h("c:"+this.id+":"),this.transportManager_=new ju(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_=yu(()=>{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=Jh("t",e),r=Jh("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=Jh("t",e),r=Jh("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=Jh("t",e);if("d"in e){var r=e.d;if("h"===t){var n=Object.assign({},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?Qh("Server Error: "+r):"o"===t?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):Qh("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&&uu("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),yu(()=>{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):yu(()=>{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()&&(eu.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 zu{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 Ku{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 Wu extends Ku{static getInstance(){return new Wu}constructor(){super(["online"]),this.online_=!0,"undefined"==typeof window||void 0===window.addEventListener||te()||(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 Hu=32,Gu=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 $u(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 Qu(e){return e.pieceNum_<e.pieces_.length?e.pieces_[e.pieces_.length-1]:null}function Yu(e,t=0){return e.pieces_.slice(e.pieceNum_+t)}function Ju(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 Xu(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 Zu(e,t){var r=_(e),n=_(t);if(null===r)return t;if(r===n)return Zu(y(e),y(t));throw new Error("INTERNAL ERROR: innerPath ("+t+") is not within outerPath ("+e+")")}function ec(e,t){var r=Yu(e,0),n=Yu(t,0);for(let s=0;s<r.length&&s<n.length;s++){var i=gu(r[s],n[s]);if(0!==i)return i}return r.length===n.length?0:r.length<n.length?-1:1}function tc(e,t){if($u(e)!==$u(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 rc(e,t){let r=e.pieceNum_,n=t.pieceNum_;if($u(e)>$u(t))return!1;for(;r<e.pieces_.length;){if(e.pieces_[r]!==t.pieces_[n])return!1;++r,++n}return!0}class nc{constructor(e,t){this.errorPrefix_=t,this.parts_=Yu(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let r=0;r<this.parts_.length;r++)this.byteLength_+=Oe(this.parts_[r]);ic(this)}}function ic(e){if(e.byteLength_>Gu)throw new Error(e.errorPrefix_+"has a key path longer than "+Gu+" bytes ("+e.byteLength_+").");if(e.parts_.length>Hu)throw new Error(e.errorPrefix_+"path specified exceeds the maximum depth that can be written ("+Hu+") or object contains a cycle "+sc(e))}function sc(e){return 0===e.parts_.length?"":"in property '"+e.parts_.join(".")+"'"}class ac extends Ku{static getInstance(){return new ac}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 oc extends zu{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=oc.nextPersistentConnectionId_++,this.log_=$h("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&&!oe())throw new Error("Auth override specified in options, but not supported on non Node.js platforms");ac.getInstance().on("visible",this.onVisible_,this),-1===e.host.indexOf("fblocal")&&Wu.getInstance().on("online",this.onOnline_,this)}sendRequest(e,t,r){var n=++this.requestNumber_,i={r:n,a:e,b:t};this.log_(me(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 X;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=(oc.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&&_e(e,"w")&&(r=ye(e,"w"),Array.isArray(r))&&~r.indexOf("no_index")&&(r='".indexOn": "'+t._queryParams.getIndex().toString()+'"',n=t._path.toString(),uu("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=ve(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=ve(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: "+me(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):Qh("Unrecognized action received from server: "+me(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+":"+oc.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,u]=await Promise.all([this.authTokenProvider_.getToken(l),this.appCheckTokenProvider_.getToken(l)]);t?lu("getToken() completed but was canceled"):(lu("getToken() completed. Creating connection."),this.authToken_=h&&h.accessToken,this.appCheckToken_=u&&u.token,r=new Bu(s,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,n,i,e,e=>{uu(e+" ("+this.repoInfo_.toString()+")"),this.interrupt("server_kill")},a))}catch(e){this.log_("Failed to get token: "+e),t||(this.repoInfo_.nodeAdmin&&uu(e),o())}}}interrupt(e){lu("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){lu("Resuming connection for reason: "+e),delete this.interruptReasons_[e],we(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=>Xh(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){lu("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){lu("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."+jh.replace(/\./g,"-")]=1,te()?e["framework.cordova"]=1:se()&&(e["framework.reactnative"]=1),this.reportStats(e)}shouldReconnect_(){var e=Wu.getInstance().currentlyOnline();return we(this.interruptReasons_)&&e}}oc.nextPersistentConnectionId_=0,oc.nextConnectionId_=0;class p{constructor(e,t){this.name=e,this.node=t}static Wrap(e,t){return new p(e,t)}}class lc{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,t){var r=new p(pu,e),n=new p(pu,t);return 0!==this.compare(r,n)}minPost(){return p.MIN}}let hc;class uc extends lc{static get __EMPTY_NODE(){return hc}static set __EMPTY_NODE(e){hc=e}compare(e,t){return gu(e.name,t.name)}isDefinedOn(e){throw j("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,t){return!1}minPost(){return p.MIN}maxPost(){return new p(fu,hc)}makePost(e,t){return g("string"==typeof e,"KeyIndex indexValue must always be a string."),new p(e,hc)}toString(){return".key"}}let cc=new uc;class dc{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 pc{constructor(e,t,r,n,i){this.key=e,this.value=t,this.color=null!=r?r:pc.RED,this.left=null!=n?n:gc.EMPTY_NODE,this.right=null!=i?i:gc.EMPTY_NODE}copy(e,t,r,n,i){return new pc(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 gc.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 gc.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,pc.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){var e=this.copy(null,null,pc.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)}}pc.RED=!0,pc.BLACK=!1;class fc{copy(e,t,r,n,i){return this}insert(e,t,r){return new pc(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 gc{constructor(e,t=gc.EMPTY_NODE){this.comparator_=e,this.root_=t}insert(e,t){return new gc(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,pc.BLACK,null,null))}remove(e){return new gc(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,pc.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 dc(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new dc(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new dc(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new dc(this.root_,null,this.comparator_,!0,e)}}function mc(e,t){return gu(e.name,t.name)}function vc(e,t){return gu(e,t)}gc.EMPTY_NODE=new fc;let _c;function yc(e){return"number"==typeof e?"number:"+vu(e):"string:"+e}function wc(e){var t;e.isLeafNode()?(t=e.val(),g("string"==typeof t||"number"==typeof t||"object"==typeof t&&_e(t,".sv"),"Priority must be a string or number.")):g(e===_c||e.isEmpty(),"priority of unexpected type."),g(e===_c||e.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")}let bc;class Ic{static set __childrenNodeConstructor(e){bc=e}static get __childrenNodeConstructor(){return bc}constructor(e,t=Ic.__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."),wc(this.priorityNode_)}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new Ic(this.value_,e)}getImmediateChild(e){return".priority"===e?this.priorityNode_:Ic.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return b(e)?this:".priority"===_(e)?this.priorityNode_:Ic.__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:Ic.__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===$u(e),".priority must be the last token in a path"),this.updateImmediateChild(r,Ic.__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:"+yc(this.priorityNode_.val())+":");var t=typeof this.value_;e=(e+=t+":")+("number"==t?vu(this.value_):this.value_),this.lazyHash_=Gh(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===Ic.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof Ic.__childrenNodeConstructor?-1:(g(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){var t=typeof e.value_,r=typeof this.value_,n=Ic.VALUE_TYPE_ORDER.indexOf(t),i=Ic.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_)}}Ic.VALUE_TYPE_ORDER=["object","boolean","number","string"];let Tc,Ec;class Cc extends lc{compare(e,t){var r=e.node.getPriority(),n=t.node.getPriority(),r=r.compareTo(n);return 0===r?gu(e.name,t.name):r}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return p.MIN}maxPost(){return new p(fu,new Ic("[PRIORITY-POST]",Ec))}makePost(e,t){var r=Tc(e);return new p(t,new Ic("[PRIORITY-POST]",r))}toString(){return".priority"}}let I=new Cc,kc=Math.log(2);class Sc{constructor(e){this.count=(t=e+1,parseInt(Math.log(t)/kc,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 Ac(l,e,h,t){l.sort(e);let u=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 pc(a,s.node,pc.BLACK,null,null)):(i=parseInt(i/2,10)+e,r=u(e,i),n=u(i+1,t),s=l[i],a=h?h(s):s,new pc(a,s.node,pc.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,u(1+r,n)),r=l[r],i=h?h(r):r,e=new pc(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,pc.BLACK):(t(n,pc.BLACK),t(n,pc.RED))}return a})(new Sc(l.length));return new gc(t||e,r)}let Nc,Rc={};class Pc{static get Default(){return g((Rc,I),"ChildrenNode.ts has not been loaded"),Nc=Nc||new Pc({".priority":Rc},{".priority":I})}constructor(e,t){this.indexes_=e,this.indexSet_=t}get(e){var t=ye(this.indexes_,e);if(t)return t instanceof gc?t:null;throw new Error("No index defined for "+e)}hasIndex(e){return _e(this.indexSet_,e.toString())}addIndex(e,t){g(e!==cc,"KeyIndex always exists and isn't meant to be added to the IndexMap.");var r=[];let n=!1;var i=t.getIterator(p.Wrap);let s=i.getNext();for(;s;)n=n||e.isDefinedOn(s.node),r.push(s),s=i.getNext();let a;a=n?Ac(r,e.getCompare()):Rc;var o=e.toString(),l=Object.assign({},this.indexSet_),h=(l[o]=e,Object.assign({},this.indexes_));return h[o]=a,new Pc(h,l)}addToIndexes(s,a){var e=be(this.indexes_,(t,e)=>{var r=ye(this.indexSet_,e);if(g(r,"Missing index implementation for "+e),t===Rc){if(r.isDefinedOn(s.node)){var n=[],i=a.getIterator(p.Wrap);let e=i.getNext();for(;e;)e.name!==s.name&&n.push(e),e=i.getNext();return n.push(s),Ac(n,r.getCompare())}return Rc}{r=a.get(s.name);let e=t;return(e=r?e.remove(new p(s.name,r)):e).insert(s,s.node)}});return new Pc(e,this.indexSet_)}removeFromIndexes(r,n){var e=be(this.indexes_,e=>{var t;return e!==Rc&&(t=n.get(r.name))?e.remove(new p(r.name,t)):e});return new Pc(e,this.indexSet_)}}let Dc;class T{static get EMPTY_NODE(){return Dc=Dc||new T(new gc(vc),null,Pc.Default)}constructor(e,t,r){this.children_=e,this.priorityNode_=t,this.indexMap_=r,this.lazyHash_=null,this.priorityNode_&&wc(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_||Dc}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))?Dc: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 p(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()?Dc:this.priorityNode_;return new T(e,i,t)}}updateChild(e,t){var r,n=_(e);return null===n?t:(g(".priority"!==_(e)||1===$u(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:"+yc(this.getPriority().val())+":"),this.forEachChild(I,(e,t)=>{var r=t.hash();""!==r&&(n+=":"+e+":"+r)}),this.lazyHash_=""===n?"":Gh(n)}return this.lazyHash_}getPredecessorChildName(e,t,r){var n=this.resolveIndex_(r);return n?(n=n.getPredecessorKey(new p(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 p(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 p(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,p.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,p.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===Oc?-1:0}withIndex(e){var t;return e===cc||this.indexMap_.hasIndex(e)?this:(t=this.indexMap_.addIndex(e,this.children_),new T(this.children_,this.priorityNode_,t))}isIndexed(e){return e===cc||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===cc?null:this.indexMap_.get(e.toString())}}T.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;class xc extends T{constructor(){super(new gc(vc),T.EMPTY_NODE,Pc.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 Oc=new xc,Lc=(Object.defineProperties(p,{MIN:{value:new p(pu,T.EMPTY_NODE)},MAX:{value:new p(fu,Oc)}}),uc.__EMPTY_NODE=T.EMPTY_NODE,Ic.__childrenNodeConstructor=T,t=Oc,_c=t,t=Oc,Ec=t,!0);function Mc(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 Ic(t,Mc(e));if(s instanceof Array||!Lc){let n=T.EMPTY_NODE;return mu(s,(e,t)=>{var r;!_e(s,e)||"."===e.substring(0,1)||!(r=Mc(t)).isLeafNode()&&r.isEmpty()||(n=n.updateImmediateChild(e,r))}),n.updatePriority(Mc(e))}{let n=[],i=!1;return mu(s,(e,t)=>{var r;"."===e.substring(0,1)||(r=Mc(t)).isEmpty()||(i=i||!r.getPriority().isEmpty(),n.push(new p(e,r)))}),0===n.length?T.EMPTY_NODE:(t=Ac(n,mc,e=>e.name,vc),i?(r=Ac(n,I.getCompare()),new T(t,Mc(e),new Pc({".priority":r},{".priority":I}))):new T(t,Mc(e),Pc.Default))}}Tc=Mc;class Fc extends lc{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?gu(e.name,t.name):r}makePost(e,t){var r=Mc(e),r=T.EMPTY_NODE.updateChild(this.indexPath_,r);return new p(t,r)}maxPost(){var e=T.EMPTY_NODE.updateChild(this.indexPath_,Oc);return new p(fu,e)}toString(){return Yu(this.indexPath_,0).join("/")}}class Uc extends lc{compare(e,t){var r=e.node.compareTo(t.node);return 0===r?gu(e.name,t.name):r}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return p.MIN}maxPost(){return p.MAX}makePost(e,t){var r=Mc(e);return new p(t,r)}toString(){return".value"}}let Vc=new Uc;function qc(e){return{type:"value",snapshotNode:e}}function jc(e,t){return{type:"child_added",snapshotNode:t,childName:e}}function Bc(e,t){return{type:"child_removed",snapshotNode:t,childName:e}}function zc(e,t,r){return{type:"child_changed",snapshotNode:t,childName:e,oldSnap:r}}class Kc{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(Bc(t,a)):g(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):a.isEmpty()?s.trackChildChange(jc(t,r)):s.trackChildChange(zc(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(Bc(e,t))}),r.isLeafNode()||r.forEachChild(I,(e,t)=>{var r;n.hasChild(e)?(r=n.getImmediateChild(e)).equals(t)||i.trackChildChange(zc(e,t,r)):i.trackChildChange(jc(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 Wc{constructor(e){this.indexedFilter_=new Kc(e.getIndex()),this.index_=e.getIndex(),this.startPost_=Wc.getStartPost_(e),this.endPost_=Wc.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 p(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 p(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 Hc{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 Wc(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 p(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 p(t,r)),l=this.reverse_?a.getFirstChild(this.index_):a.getLastChild(this.index_),h=this.rangedFilter_.matches(o);if(a.hasChild(t)){var u=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 c=null==e?1:s(e,o);return h&&!r.isEmpty()&&0<=c?(null!=i&&i.trackChildChange(zc(t,r,u)),a.updateImmediateChild(t,r)):(null!=i&&i.trackChildChange(Bc(t,u)),c=a.updateImmediateChild(t,T.EMPTY_NODE),null!=e&&this.rangedFilter_.matches(e)?(null!=i&&i.trackChildChange(jc(e.name,e.node)),c.updateImmediateChild(e.name,e.node)):c)}return!r.isEmpty()&&h&&0<=s(l,o)?(null!=i&&(i.trackChildChange(Bc(l.name,l.node)),i.trackChildChange(jc(t,r))),a.updateImmediateChild(t,r).updateImmediateChild(l.name,T.EMPTY_NODE)):e}}class Gc{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_:pu}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_:fu}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 Gc;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 $c(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 Qc(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 Yc(e,t){var r=e.copy();return r.index_=t,r}function Jc(t){var r,n={};if(!t.isDefault()){let e;e=t.index_===I?"$priority":t.index_===Vc?"$value":t.index_===cc?"$key":(g(t.index_ instanceof Fc,"Unrecognized index type!"),t.index_.toString()),n.orderBy=me(e),t.startSet_&&(n[r=t.startAfterSet_?"startAfter":"startAt"]=me(t.indexStartValue_),t.startNameSet_)&&(n[r]+=","+me(t.indexStartName_)),t.endSet_&&(n[r=t.endBeforeSet_?"endBefore":"endAt"]=me(t.indexEndValue_),t.endNameSet_)&&(n[r]+=","+me(t.indexEndName_)),t.limitSet_&&(t.isViewFromLeft()?n.limitToFirst=t.limit_:n.limitToLast=t.limit_)}return n}function Xc(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 Zc extends zu{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_=$h("p:rest:"),this.listens_={}}listen(e,t,n,i){let s=e._path.toString(),a=(this.log_("Listen called for "+s+" "+e._queryIdentifier),Zc.getListenId_(e,n)),o={};this.listens_[a]=o;var r=Jc(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),ye(this.listens_,a)===o){let e;e=t?401===t?"permission_denied":"rest_error:"+t:"ok",i(e,null)}})}unlisten(e,t){var r=Zc.getListenId_(e,t);delete this.listens_[r]}get(e){var t=Jc(e._queryParams);let n=e._path.toString(),i=new X;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+Ee(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=ge(n.responseText)}catch(e){uu("Failed to parse JSON response for "+r+": "+n.responseText)}a(null,e)}else 401!==n.status&&404!==n.status&&uu("Got unsuccessful REST response for "+r+" Status: "+n.status),a(n.status);a=null}},n.open("GET",r,!0),n.send()})}}class ed{constructor(){this.rootNode_=T.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}function td(){return{value:null,children:new Map}}function rd(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,td()),rd(e.children.get(n),t=y(t),r))}function nd(e,r,n){var i;null!==e.value?n(r,e.value):(i=(e,t)=>{nd(t,new f(r.toString()+"/"+e),n)},e.children.forEach((e,t)=>{i(t,e)}))}class id{constructor(e){this.collection_=e,this.last_=null}get(){var e=this.collection_.get();let r=Object.assign({},e);return this.last_&&mu(this.last_,(e,t)=>{r[e]=r[e]-t}),this.last_=e,r}}class sd{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new id(e);var r=1e4+2e4*Math.random();yu(this.reportStats_.bind(this),Math.floor(r))}reportStats_(){var e=this.statsListener_.get();let r={},n=!1;mu(e,(e,t)=>{0<t&&_e(this.statsToReport_,e)&&(r[e]=t,n=!0)}),n&&this.server_.reportStats(r),yu(this.reportStats_.bind(this),Math.floor(2*Math.random()*3e5))}}function ad(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function od(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function ld(e){return{fromUser:!1,fromServer:!0,queryId:e,tagged:!0}}(t=Hh=Hh||{})[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 hd{constructor(e,t,r){this.path=e,this.affectedTree=t,this.revert=r,this.type=Hh.ACK_USER_WRITE,this.source=ad()}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 hd(v(),t,this.revert)):(g(_(this.path)===e,"operationForChild called for unrelated child."),new hd(y(this.path),this.affectedTree,this.revert))}}class ud{constructor(e,t){this.source=e,this.path=t,this.type=Hh.LISTEN_COMPLETE}operationForChild(e){return b(this.path)?new ud(this.source,v()):new ud(this.source,y(this.path))}}class cd{constructor(e,t,r){this.source=e,this.path=t,this.snap=r,this.type=Hh.OVERWRITE}operationForChild(e){return b(this.path)?new cd(this.source,v(),this.snap.getImmediateChild(e)):new cd(this.source,y(this.path),this.snap)}}class dd{constructor(e,t,r){this.source=e,this.path=t,this.children=r,this.type=Hh.MERGE}operationForChild(e){var t;return b(this.path)?(t=this.children.subtree(new f(e))).isEmpty()?null:t.value?new cd(this.source,v(),t.value):new dd(this.source,v(),t):(g(_(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new dd(this.source,y(this.path),this.children))}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}class pd{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 fd{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function gd(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}))}),md(r,i,"child_removed",e,n,t),md(r,i,"child_added",e,n,t),md(r,i,"child_moved",s,n,t),md(r,i,"child_changed",e,n,t),md(r,i,"value",e,n,t),i}function md(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 j("Should only compare child_ events.");var n=new p(e.childName,e.snapshotNode),i=new p(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 vd(e,t){return{eventCache:e,serverCache:t}}function _d(e,t,r,n){return vd(new pd(t,r,n),e.serverCache)}function yd(e,t,r,n){return vd(e.eventCache,new pd(t,r,n))}function wd(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function bd(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}let Id;class E{static fromObject(e){let r=new E(null);return mu(e,(e,t)=>{r=r.set(new f(e),t)}),r}constructor(e,t=Id=Id||new gc(Yh)){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:Xu(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 E(null))}set(e,t){var r,n;return b(e)?new E(t,this.children):(n=_(e),r=(this.children.get(n)||new E(null)).set(y(e),t),n=this.children.insert(n,r),new E(this.value,n))}remove(t){if(b(t))return this.children.isEmpty()?new E(null):new E(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 E(null):new E(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 E(null)).setTree(y(t),r);let e;return e=i.isEmpty()?this.children.remove(n):this.children.insert(n,i),new E(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_(Xu(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),Xu(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),Xu(t,n),r):new E(null))}foreach(e){this.foreach_(v(),e)}foreach_(r,n){this.children.inorderTraversal((e,t)=>{t.foreach_(Xu(r,e),n)}),this.value&&n(r,this.value)}foreachChild(r){this.children.inorderTraversal((e,t)=>{t.value&&r(e,t.value)})}}class Td{constructor(e){this.writeTree_=e}static empty(){return new Td(new E(null))}}function Ed(t,r,n){if(b(r))return new Td(new E(n));var i=t.writeTree_.findRootMostValueAndPath(r);if(null==i)return s=new E(n),s=t.writeTree_.setTree(r,s),new Td(s);{var s=i.path;let e=i.value;i=Zu(s,r);return e=e.updateChild(i,n),new Td(t.writeTree_.set(s,e))}}function Cd(e,r,t){let n=e;return mu(t,(e,t)=>{n=Ed(n,Xu(r,e),t)}),n}function kd(e,t){var r;return b(t)?Td.empty():(r=e.writeTree_.setTree(t,new E(null)),new Td(r))}function Sd(e,t){return null!=Ad(e,t)}function Ad(e,t){var r=e.writeTree_.findRootMostValueAndPath(t);return null!=r?e.writeTree_.get(r.path).getChild(Zu(r.path,t)):null}function Nd(e){let r=[];var t=e.writeTree_.value;return null!=t?t.isLeafNode()||t.forEachChild(I,(e,t)=>{r.push(new p(e,t))}):e.writeTree_.children.inorderTraversal((e,t)=>{null!=t.value&&r.push(new p(e,t.value))}),r}function Rd(e,t){var r;return b(t)?e:null!=(r=Ad(e,t))?new Td(new E(r)):new Td(e.writeTree_.subtree(t))}function Pd(e){return e.writeTree_.isEmpty()}function Dd(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(Xu(i,e),t,s)}),s=s.getChild(i).isEmpty()||null===r?s:s.updateChild(Xu(i,".priority"),r)}}}(v(),e.writeTree_,t)}function xd(e,t){return Wd(t,e)}function Od(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 rc(e.path,t);for(var r in e.children)if(e.children.hasOwnProperty(r)&&rc(Xu(e.path,r),t))return 1})(l,i.path)?s=!1:rc(i.path,l.path)&&(a=!0)),o--}return!!s&&(a?((e=t).visibleWrites=Md(e.allWrites,Ld,v()),0<e.allWrites.length?e.lastWriteId=e.allWrites[e.allWrites.length-1].writeId:e.lastWriteId=-1):i.snap?t.visibleWrites=kd(t.visibleWrites,i.path):mu(i.children,e=>{t.visibleWrites=kd(t.visibleWrites,Xu(i.path,e))}),!0)}function Ld(e){return e.visible}function Md(e,t,r){let n=Td.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)rc(r,s)?(e=Zu(r,s),n=Ed(n,e,i.snap)):rc(s,r)&&(e=Zu(s,r),n=Ed(n,v(),i.snap.getChild(e)));else{if(!i.children)throw j("WriteRecord should have .snap or .children");rc(r,s)?(e=Zu(r,s),n=Cd(n,e,i.children)):rc(s,r)&&(b(e=Zu(s,r))?n=Cd(n,v(),i.children):(s=ye(i.children,_(e)))&&(i=s.getChild(y(e)),n=Ed(n,v(),i)))}}}return n}function Fd(e,t,r,n,i){var s;return n||i?(s=Rd(e.visibleWrites,t),!i&&Pd(s)?r:i||null!=r||Sd(s,v())?Dd(Md(e.allWrites,function(e){return(e.visible||i)&&(!n||!~n.indexOf(e.writeId))&&(rc(e.path,t)||rc(t,e.path))},t),r||T.EMPTY_NODE):null):null!=(s=Ad(e.visibleWrites,t))?s:Pd(s=Rd(e.visibleWrites,t))?r:null!=r||Sd(s,v())?Dd(s,r||T.EMPTY_NODE):null}function Ud(e,t,r,n){return Fd(e.writeTree,e.treePath,t,r,n)}function Vd(e,t){{var r=e.writeTree;e=e.treePath;let i=T.EMPTY_NODE;var n=Ad(r.visibleWrites,e);if(n)n.isLeafNode()||n.forEachChild(I,(e,t)=>{i=i.updateImmediateChild(e,t)});else if(t){let n=Rd(r.visibleWrites,e);t.forEachChild(I,(e,t)=>{var r=Dd(Rd(n,new f(e)),t);i=i.updateImmediateChild(e,r)}),Nd(n).forEach(e=>{i=i.updateImmediateChild(e.name,e.node)})}else Nd(Rd(r.visibleWrites,e)).forEach(e=>{i=i.updateImmediateChild(e.name,e.node)});return i}}function qd(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=Xu(e,t),Sd(i.visibleWrites,s)?null:Pd(s=Rd(i.visibleWrites,s))?n.getChild(t):Dd(s,n.getChild(t));var i,s}function jd(e,t){return r=e.writeTree,e=Xu(e.treePath,t),Ad(r.visibleWrites,e);var r}function Bd(e,r,n,i,s,a){{var o=e.writeTree,l=(e=e.treePath,n),h=i;n=s,i=a;let t;var u=Rd(o.visibleWrites,e),c=Ad(u,v());if(null!=c)t=c;else{if(null==r)return[];t=Dd(u,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 zd(e,t,r){return n=e.writeTree,r=r,i=Xu(e.treePath,e=t),null!=(s=Ad(n.visibleWrites,i))?s:r.isCompleteForChild(e)?Dd(Rd(n.visibleWrites,i),r.getNode().getImmediateChild(e)):null;var n,i,s}function Kd(e,t){return Wd(Xu(e.treePath,t),e.writeTree)}function Wd(e,t){return{treePath:e,writeTree:t}}class Hd{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,zc(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,Bc(r,n.oldSnap));else if("child_changed"===t&&"child_added"===i)this.changeMap.set(r,jc(r,e.snapshotNode));else{if("child_changed"!==t||"child_changed"!==i)throw j("Illegal combination of changes: "+e+" occurred after "+n);this.changeMap.set(r,zc(r,e.snapshotNode,n.oldSnap))}}else this.changeMap.set(r,e)}getChanges(){return Array.from(this.changeMap.values())}}let Gd=new class{getCompleteChild(e){return null}getChildAfterChild(e,t,r){return null}};class $d{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 pd(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache,zd(this.writes_,e,t))}getChildAfterChild(e,t,r){var n=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:bd(this.viewCache_),n=Bd(this.writes_,n,t,1,r,e);return 0===n.length?null:n[0]}}function Qd(e,t,r,n,i){var s=new Hd;let a,o;if(r.type===Hh.OVERWRITE){var l=r;a=l.source.fromUser?Xd(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),Jd(e,t,l.path,l.snap,n,i,o,s))}else if(r.type===Hh.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=Xu(s,e);Zd(i,_(r))&&(h=Xd(n,h,r,t,a,o,l))}),e.foreach((e,t)=>{var r=Xu(s,e);Zd(i,_(r))||(h=Xd(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(),tp(e,t,l.path,l.children,n,i,o,s))}else if(r.type===Hh.ACK_USER_WRITE){l=r;a=l.revert?((r,n,i,s,e,a)=>{let o;if(null!=jd(s,i))return n;{var l=new $d(s,n,e),h=n.eventCache.getNode();let t;if(b(i)||".priority"===_(i)){let e;e=e=n.serverCache.isFullyInitialized()?Ud(s,bd(n)):(u=n.serverCache.getNode(),g(u instanceof T,"serverChildren would be complete if leaf node"),Vd(s,u)),t=r.filter.updateFullNode(h,e,a)}else{var u=_(i);let e=zd(s,u,n.serverCache);null==e&&n.serverCache.isCompleteForChild(u)&&(e=h.getImmediateChild(u)),(t=null!=e?r.filter.updateChild(h,u,e,y(i),l,a):n.eventCache.getNode().hasChild(u)?r.filter.updateChild(h,u,T.EMPTY_NODE,y(i),l,a):h).isEmpty()&&n.serverCache.isFullyInitialized()&&(o=Ud(s,bd(n))).isLeafNode()&&(t=r.filter.updateFullNode(t,o,a))}return o=n.serverCache.isFullyInitialized()||null!=jd(s,v()),_d(n,t,o,r.filter.filtersNodes())}})(e,t,l.path,n,i,s):((e,t,i,r,s,a,o)=>{if(null!=jd(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 Jd(e,t,i,h.getNode().getChild(i),s,a,l,o);if(b(i)){let r=new E(null);return h.getNode().forEachChild(cc,(e,t)=>{r=r.set(new f(e),t)}),tp(e,t,i,r,s,a,l,o)}return t}{let n=new E(null);return r.foreach((e,t)=>{var r=Xu(i,e);h.isCompleteForPath(r)&&(n=n.set(e,h.getNode().getChild(r)))}),tp(e,t,i,n,s,a,l,o)}})(e,t,l.path,l.affectedTree,n,i,s)}else{if(r.type!==Hh.LISTEN_COMPLETE)throw j("Unknown operation type: "+r.type);a=(i=e,e=r.path,r=n,n=s,l=t.serverCache,l=yd(t,l.getNode(),l.isFullyInitialized()||b(e),l.isFiltered()),Yd(i,l,e,r,Gd,n))}var h,u,s=s.getChanges(),i=t,e=a,r=s,c=e.eventCache;return c.isFullyInitialized()&&(h=c.getNode().isLeafNode()||c.getNode().isEmpty(),u=wd(i),0<r.length||!i.eventCache.isFullyInitialized()||h&&!c.getNode().equals(u)||!c.getNode().getPriority().equals(u.getPriority()))&&r.push(qc(wd(e))),{viewCache:a,changes:s}}function Yd(n,i,s,a,o,l){var h=i.eventCache;if(null!=jd(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()?(u=Vd(a,(u=bd(i))instanceof T?u:T.EMPTY_NODE),n.filter.updateFullNode(i.eventCache.getNode(),u,l)):(u=Ud(a,bd(i)),n.filter.updateFullNode(i.eventCache.getNode(),u,l));else{var u=_(s);if(".priority"===u){g(1===$u(s),"Can't have a priority with additional path components");var c=h.getNode(),d=qd(a,s,c,r=i.serverCache.getNode());t=null!=d?n.filter.updatePriority(c,d):h.getNode()}else{c=y(s);let e;e=h.isCompleteForChild(u)?(r=i.serverCache.getNode(),null!=(d=qd(a,s,h.getNode(),r))?h.getNode().getImmediateChild(u).updateChild(c,d):h.getNode().getImmediateChild(u)):zd(a,u,i.serverCache),t=null!=e?n.filter.updateChild(h.getNode(),u,e,c,o,l):h.getNode()}}return _d(i,t,h.isFullyInitialized()||b(s),n.filter.filtersNodes())}}function Jd(e,t,r,n,i,s,a,o){var l=t.serverCache;let h;var u=a?e.filter:e.filter.getIndexedFilter();if(b(r))h=u.updateFullNode(l.getNode(),n,null);else if(u.filtersNodes()&&!l.isFiltered()){var c=l.getNode().updateChild(r,n);h=u.updateFullNode(l.getNode(),c,null)}else{c=_(r);if(!l.isCompleteForPath(r)&&1<$u(r))return t;var d=y(r),p=l.getNode().getImmediateChild(c).updateChild(d,n);h=".priority"===c?u.updatePriority(l.getNode(),p):u.updateChild(l.getNode(),c,p,d,Gd,null)}c=yd(t,h,l.isFullyInitialized()||b(r),u.filtersNodes());return Yd(e,c,r,i,new $d(i,c,s),o)}function Xd(t,r,n,i,e,s,a){var o=r.eventCache;let l,h;var u=new $d(e,r,s);if(b(n))h=t.filter.updateFullNode(r.eventCache.getNode(),i,a),l=_d(r,h,!0,t.filter.filtersNodes());else{var c=_(n);if(".priority"===c)h=t.filter.updatePriority(r.eventCache.getNode(),i),l=_d(r,h,o.isFullyInitialized(),o.isFiltered());else{var d,p=y(n),f=o.getNode().getImmediateChild(c);let e;e=b(p)?i:null!=(d=u.getCompleteChild(c))?".priority"===Qu(p)&&d.getChild(Ju(p)).isEmpty()?d:d.updateChild(p,i):T.EMPTY_NODE,l=f.equals(e)?r:_d(r,t.filter.updateChild(o.getNode(),c,e,p,u,a),o.isFullyInitialized(),t.filter.filtersNodes())}}return l}function Zd(e,t){return e.eventCache.isCompleteForChild(t)}function ep(e,r,t){return t.foreach((e,t)=>{r=r.updateChild(e,t)}),r}function tp(n,i,e,t,s,a,o,l){if(i.serverCache.getNode().isEmpty()&&!i.serverCache.isFullyInitialized())return i;let h=i,r,u=(r=b(e)?t:new E(null).setTree(e,t),i.serverCache.getNode());return r.children.inorderTraversal((e,t)=>{var r;u.hasChild(e)&&(r=ep(0,i.serverCache.getNode().getImmediateChild(e),t),h=Jd(n,h,new f(e),r,s,a,o,l))}),r.children.inorderTraversal((e,t)=>{var r=!i.serverCache.isCompleteForChild(e)&&null===t.value;u.hasChild(e)||r||(r=ep(0,i.serverCache.getNode().getImmediateChild(e),t),h=Jd(n,h,new f(e),r,s,a,o,l))}),h}class rp{constructor(e,t){this.query_=e,this.eventRegistrations_=[];var r=this.query_._queryParams,n=new Kc(r.getIndex()),r=(e=r).loadsAllData()?new Kc(e.getIndex()):new(e.hasLimit()?Hc:Wc)(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 pd(a,i.isFullyInitialized(),n.filtersNodes()),i=new pd(o,s.isFullyInitialized(),r.filtersNodes());this.viewCache_=vd(i,a),this.eventGenerator_=new fd(this.query_)}get query(){return this.query_}}function np(e){return 0===e.eventRegistrations_.length}function ip(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 sp(e,t,r,n){t.type===Hh.MERGE&&null!==t.source.queryId&&(g(bd(e.viewCache_),"We should always have a full cache before handling merges"),g(wd(e.viewCache_),"Missing event cache, even though we have a server cache"));var i=e.viewCache_,s=Qd(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,ap(e,s.changes,s.viewCache.eventCache.getNode(),null)}function ap(e,t,r,n){var i=n?[n]:e.eventRegistrations_;return gd(e.eventGenerator_,t,r,i)}let op;class lp{constructor(){this.views=new Map}}function hp(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."),sp(e,r,n,i);{let e=[];for(var s of t.views.values())e=e.concat(sp(s,r,n,i));return e}}function up(e,r,n,i,s){var a=r._queryIdentifier,a=e.views.get(a);if(a)return a;{let e=Ud(n,s?i:null),t=!1;t=!!e||(e=i instanceof T?Vd(n,i):T.EMPTY_NODE,!1);a=vd(new pd(e,t,!1),new pd(i,s,!1));return new rp(r,a)}}function cp(e,t,n,i,s,r){var a=up(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(jc(e,t))}),a.isFullyInitialized()&&r.push(qc(a.getNode())),ap(i,r,a.getNode(),s)}}function dp(e,t,r,n){var i=t._queryIdentifier,s=[];let a=[];var o=vp(e);if("default"===i)for(var[l,h]of e.views.entries())a=a.concat(ip(h,r,n)),np(h)&&(e.views.delete(l),h.query._queryParams.loadsAllData()||s.push(h.query));else{var u=e.views.get(i);u&&(a=a.concat(ip(u,r,n)),np(u))&&(e.views.delete(i),u.query._queryParams.loadsAllData()||s.push(u.query))}return o&&!vp(e)&&s.push((g(op,"Reference.ts has not been loaded"),new op(t._repo,t._path))),{removed:s,events:a}}function pp(e){var t,r=[];for(t of e.views.values())t.query._queryParams.loadsAllData()||r.push(t);return r}function fp(e,t){let r=null;for(var n of e.views.values())r=r||(i=n,s=t,n=void 0,(n=bd(i.viewCache_))&&(i.query._queryParams.loadsAllData()||!b(s)&&!n.getImmediateChild(_(s)).isEmpty())?n.getChild(s):null);var i,s;return r}function gp(e,t){var r;return t._queryParams.loadsAllData()?_p(e):(r=t._queryIdentifier,e.views.get(r))}function mp(e,t){return null!=gp(e,t)}function vp(e){return null!=_p(e)}function _p(e){for(var t of e.views.values())if(t.query._queryParams.loadsAllData())return t;return null}let yp;let wp=1;class bp{constructor(e){this.listenProvider_=e,this.syncPointTree_=new E(null),this.pendingWriteTree_={visibleWrites:Td.empty(),allWrites:[],lastWriteId:-1},this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function Ip(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=Ed(s.visibleWrites,a,o)),s.lastWriteId=n,i?Pp(e,new cd(ad(),t,r)):[]}function Tp(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=Cd(i.visibleWrites,s,a),i.lastWriteId=n;var i,s,a,o=E.fromObject(r);return Pp(e,new dd(ad(),t,o))}function Ep(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(Od(e.pendingWriteTree_,t)){let t=new E(null);return null!=n.snap?t=t.set(v(),!0):mu(n.children,e=>{t=t.set(new f(e),!0)}),Pp(e,new hd(n.path,t,r))}return[]}function Cp(e,t,r){return Pp(e,new cd(od(),t,r))}function kp(r,t,n,i,s=!1){var a=t._path,o=r.syncPointTree_.get(a);let l=[];if(o&&("default"===t._queryIdentifier||mp(o,t))){var h=dp(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()),u=r.syncPointTree_.findOnPath(a,(e,t)=>vp(t));if(h&&!u){a=r.syncPointTree_.subtree(a);if(!a.isEmpty()){var c=a.fold((e,t,n)=>{if(t&&vp(t))return[_p(t)];{let r=[];return t&&(r=pp(t)),mu(n,(e,t)=>{r=r.concat(t)}),r}});for(let e=0;e<c.length;++e){var d=c[e],p=d.query,d=xp(r,d);r.listenProvider_.startListening(Vp(p),Op(r,p),d.hashFn,d.onComplete)}}}!u&&0<o.length&&!i&&(h?r.listenProvider_.stopListening(Vp(t),null):o.forEach(e=>{var t=r.queryToTagMap.get(Lp(e));r.listenProvider_.stopListening(Vp(e),t)}))}var f=r,g=o;for(let e=0;e<g.length;++e){var m,v=g[e];v._queryParams.loadsAllData()||(v=Lp(v),m=f.queryToTagMap.get(v),f.queryToTagMap.delete(v),f.tagToQueryMap.delete(m))}}return l}function Sp(e,t,r,n){var i,s,a=Mp(e,n);return null!=a?(i=(a=Fp(a)).path,a=a.queryId,s=Zu(i,t),Up(e,i,new cd(ld(a),s,r))):[]}function Ap(e,t,r,n=!1){let i=t._path,s=null,a=!1,o=(e.syncPointTree_.foreachOnPath(i,(e,t)=>{var r=Zu(e,i);s=s||fp(t,r),a=a||vp(t)}),e.syncPointTree_.get(i));o?(a=a||vp(o),s=s||fp(o,v())):(o=new lp,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=fp(t,v());r&&(s=s.updateImmediateChild(e,r))}));var h,u=mp(o,t),c=(u||t._queryParams.loadsAllData()||(h=Lp(t),g(!e.queryToTagMap.has(h),"View does not exist, but we have a tag"),c=wp++,e.queryToTagMap.set(h,c),e.tagToQueryMap.set(c,h)),xd(e.pendingWriteTree_,i));let d=cp(o,t,r,c,s,l);return u||a||n||(h=gp(o,t),d=d.concat(((t,e,r)=>{var n=e._path,i=Op(t,e),s=xp(t,r),s=t.listenProvider_.startListening(Vp(e),i,s.hashFn,s.onComplete),n=t.syncPointTree_.subtree(n);if(i)g(!vp(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&&vp(t))return[_p(t).query];{let r=[];return t&&(r=r.concat(pp(t).map(e=>e.query))),mu(n,(e,t)=>{r=r.concat(t)}),r}});for(let e=0;e<a.length;++e){var o=a[e];t.listenProvider_.stopListening(Vp(o),Op(t,o))}}return s})(e,t,h))),d}function Np(e,n,t){var r=e.pendingWriteTree_,i=e.syncPointTree_.findOnPath(n,(e,t)=>{var r=fp(t,Zu(e,n));if(r)return r});return Fd(r,n,i,t,!0)}function Rp(e,t){let n=t._path,i=null,r=(e.syncPointTree_.foreachOnPath(n,(e,t)=>{var r=Zu(e,n);i=i||fp(t,r)}),e.syncPointTree_.get(n));r?i=i||fp(r,v()):(r=new lp,e.syncPointTree_=e.syncPointTree_.set(n,r));var s=null!=i,a=s?new pd(i,!0,!1):null,o=xd(e.pendingWriteTree_,t._path);return wd(up(r,t,o,s?a.getNode():T.EMPTY_NODE,s).viewCache_)}function Pp(e,t){return function a(t,o,l,h){{if(b(t.path))return Dp(t,o,l,h);{let e=o.get(v()),r=(null==l&&null!=e&&(l=fp(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=Kd(h,n);r=r.concat(a(i,s,e,t))}return r=e?r.concat(hp(e,t,h,l)):r}}}(t,e.syncPointTree_,null,xd(e.pendingWriteTree_,v()))}function Dp(s,e,a,o){var t=e.get(v());null==a&&null!=t&&(a=fp(t,v()));let l=[];return e.children.inorderTraversal((e,t)=>{var r=a?a.getImmediateChild(e):null,n=Kd(o,e),i=s.operationForChild(e);i&&(l=l.concat(Dp(i,t,r,n)))}),l=t?l.concat(hp(t,s,o,a)):l}function xp(o,e){let l=e.query,h=Op(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=Mp(t,n))?(i=(a=Fp(a)).path,a=a.queryId,s=Zu(i,r),Up(t,i,new ud(ld(a),s))):[]):(n=o,r=l._path,Pp(n,new ud(od(),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),kp(o,l,null,i))}}}function Op(e,t){var r=Lp(t);return e.queryToTagMap.get(r)}function Lp(e){return e._path.toString()+"$"+e._queryIdentifier}function Mp(e,t){return e.tagToQueryMap.get(t)}function Fp(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 Up(e,t,r){var n=e.syncPointTree_.get(t),i=(g(n,"Missing sync point for query tag that we're tracking"),xd(e.pendingWriteTree_,t));return hp(n,r,i,null)}function Vp(e){return e._queryParams.loadsAllData()&&!e._queryParams.isDefault()?(g(yp,"Reference.ts has not been loaded"),new yp(e._repo,e._path)):e}class qp{constructor(e){this.node_=e}getImmediateChild(e){var t=this.node_.getImmediateChild(e);return new qp(t)}node(){return this.node_}}class jp{constructor(e,t){this.syncTree_=e,this.path_=t}getImmediateChild(e){var t=Xu(this.path_,e);return new jp(this.syncTree_,t)}node(){return Np(this.syncTree_,this.path_)}}let Bp=function(e){return(e=e||{}).timestamp=e.timestamp||(new Date).getTime(),e},zp=function(e,t,r){return e&&"object"==typeof e?(g(".sv"in e,"Unexpected leaf node or priority contents"),"string"==typeof e[".sv"]?Kp(e[".sv"],t,r):"object"==typeof e[".sv"]?Wp(e[".sv"],t):void g(!1,"Unexpected server value: "+JSON.stringify(e,null,2))):e},Kp=function(e,t,r){if("timestamp"===e)return r.timestamp;g(!1,"Unexpected server value: "+e)},Wp=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},Hp=function(e,t,r,n){return $p(t,new jp(r,e),n)},Gp=function(e,t,r){return $p(e,new qp(t),r)};function $p(e,n,i){var t,r,s=e.getPriority().val(),s=zp(s,n.getImmediateChild(".priority"),i);let a;return e.isLeafNode()?(r=e,(t=zp(r.getValue(),n,i))!==r.getValue()||s!==r.getPriority().val()?new Ic(t,Mc(s)):e):(r=e,s!==(a=r).getPriority().val()&&(a=a.updatePriority(new Ic(s))),r.forEachChild(I,(e,t)=>{var r=$p(t,n.getImmediateChild(e),i);r!==t&&(a=a.updateImmediateChild(e,r))}),a)}class Qp{constructor(e="",t=null,r={children:{},childCount:0}){this.name=e,this.parent=t,this.node=r}}function Yp(e,t){let r=t instanceof f?t:new f(t),n=e,i=_(r);for(;null!==i;){var s=ye(n.node.children,i)||{children:{},childCount:0};n=new Qp(i,n,s),r=y(r),i=_(r)}return n}function Jp(e){return e.node.value}function Xp(e,t){e.node.value=t,rf(e)}function Zp(e){return 0<e.node.childCount}function ef(r,n){mu(r.node.children,(e,t)=>{n(new Qp(e,r,t))})}function tf(e){return new f(null===e.parent?e.name:tf(e.parent)+"/"+e.name)}function rf(e){var t,r,n,i;null!==e.parent&&(t=e.parent,r=e.name,n=(e=>void 0===Jp(e)&&!Zp(e))(e=e),i=_e(t.node.children,r),n&&i?(delete t.node.children[r],t.node.childCount--,rf(t)):n||i||(t.node.children[r]=e.node,t.node.childCount++,rf(t)))}function nf(e,t,r,n){n&&void 0===t||vf(Pe(e,"value"),t,r)}function sf(e,t,s,r){if(!r||void 0!==t){let n=Pe(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=[];mu(t,(e,t)=>{var r=new f(e);if(vf(n,t,Xu(s,r)),".priority"===Qu(r)&&!mf(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=Yu(r=o[t]);for(let e=0;e<l.length;e++)if((".priority"!==l[e]||e!==l.length-1)&&!pf(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(ec);let e=null;for(t=0;t<o.length;t++){if(r=o[t],null!==e&&rc(e,r))throw new Error(a+"contains a path "+e.toString()+" that is ancestor of another path "+r.toString());e=r}}}}function af(e,t,r){if(!r||void 0!==t){if(du(t))throw new Error(Pe(e,"priority")+"is "+t.toString()+", but must be a valid Firebase priority (a string, finite number, server value, or null).");if(!mf(t))throw new Error(Pe(e,"priority")+"must be a valid Firebase priority (a string, finite number, server value, or null).")}}function of(e,t,r,n){if(!(n&&void 0===r||pf(r)))throw new Error(Pe(e,t)+'was an invalid key = "'+r+'". Firebase keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]").')}function lf(e,t,r,n){r=r&&r.replace(/^\/*\.info(\/|$)/,"/"),_f(e,t,r,n)}function hf(e,t){if(".info"===_(t))throw new Error(e+" failed = Can't modify data under /.info/")}let uf=/[\[\].#$\/\u0000-\u001F\u007F]/,cf=/[\[\].#$\u0000-\u001F\u007F]/,df=10485760,pf=function(e){return"string"==typeof e&&0!==e.length&&!uf.test(e)},ff=function(e){return"string"==typeof e&&0!==e.length&&!cf.test(e)},gf=function(e){return e=e&&e.replace(/^\/*\.info(\/|$)/,"/"),ff(e)},mf=function(e){return null===e||"string"==typeof e||"number"==typeof e&&!du(e)||e&&"object"==typeof e&&_e(e,".sv")},vf=function(a,e,t){let o=t instanceof f?new nc(t,a):t;if(void 0===e)throw new Error(a+"contains undefined "+sc(o));if("function"==typeof e)throw new Error(a+"contains a function "+sc(o)+" with contents = "+e.toString());if(du(e))throw new Error(a+"contains "+e.toString()+" "+sc(o));if("string"==typeof e&&e.length>df/3&&Oe(e)>df)throw new Error(a+"contains a string greater than "+df+" utf8 bytes "+sc(o)+" ('"+e.substring(0,50)+"...')");if(e&&"object"==typeof e){let i=!1,s=!1;if(mu(e,(e,t)=>{if(".value"===e)i=!0;else if(".priority"!==e&&".sv"!==e&&(s=!0,!pf(e)))throw new Error(a+" contains an invalid key ("+e+") "+sc(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_+=Oe(e),ic(r),vf(a,t,o),e=o,n=e.parts_.pop(),e.byteLength_-=Oe(n),0<e.parts_.length&&--e.byteLength_}),i&&s)throw new Error(a+' contains ".value" child '+sc(o)+" in addition to actual children.")}},_f=function(e,t,r,n){if(!(n&&void 0===r||ff(r)))throw new Error(Pe(e,t)+'was an invalid path = "'+r+'". Paths must be non-empty strings and can\'t contain ".", "#", "$", "[", or "]"')},yf=function(e,t){var r=t.path.toString();if("string"!=typeof t.repoInfo.host||0===t.repoInfo.host.length||!pf(t.repoInfo.namespace)&&"localhost"!==t.repoInfo.host.split(":")[0]||0!==r.length&&!gf(r))throw new Error(Pe(e,"url")+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')};class wf{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function bf(e,t){let r=null;for(let s=0;s<t.length;s++){var n=t[s],i=n.getPath();null===r||tc(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 If(e,t,r){bf(e,r),Ef(e,e=>tc(e,t))}function Tf(e,t,r){bf(e,r),Ef(e,e=>rc(e,t)||rc(t,e))}function Ef(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(),su&&lu("event: "+a.toString()),Tu(s))}t.eventLists_[o]=null}else r=!1}r&&(t.eventLists_=[]),t.recursionDepth_--}let Cf="repo_interrupt",kf=25;class Sf{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 wf,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=td(),this.transactionQueueTree_=new Qp,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function Af(a,e,t){if(a.stats_=Lu(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 Zc(a.repoInfo_,(e,t,r,n)=>{Pf(a,e,t,r,n)},a.authTokenProvider_,a.appCheckProvider_),setTimeout(()=>Df(a,!0),0);else{if(null!=t){if("object"!=typeof t)throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{me(t)}catch(e){throw new Error("Invalid authOverride provided: "+e)}}a.persistentConnection_=new oc(a.repoInfo_,e,(e,t,r,n)=>{Pf(a,e,t,r,n)},e=>{Df(a,e)},e=>{var r;r=a,mu(e,(e,t)=>{xf(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 sd(a.stats_,a.server_),r=a.repoInfo_.toString(),Ou[r]||(Ou[r]=e()),Ou[r]),a.infoData_=new ed,a.infoSyncTree_=new bp({startListening:(e,t,r,n)=>{let i=[];var s=a.infoData_.getNode(e._path);return s.isEmpty()||(i=Cp(a.infoSyncTree_,e._path,s),setTimeout(()=>{n("ok")},0)),i},stopListening:()=>{}}),xf(a,"connected",!1),a.serverSyncTree_=new bp({startListening:(n,e,t,i)=>(a.server_.listen(n,t,e,(e,t)=>{var r=i(e,t);Tf(a.eventQueue_,n._path,r)}),[]),stopListening:(e,t)=>{a.server_.unlisten(e,t)}})}function Nf(e){var t=e.infoData_.getNode(new f(".info/serverTimeOffset")).val()||0;return(new Date).getTime()+t}function Rf(e){return Bp({timestamp:Nf(e)})}function Pf(e,t,r,n,i){e.dataUpdateCount++;var s,a,o,l,h,u,c=new f(t);r=e.interceptServerDataCallback_?e.interceptServerDataCallback_(t,r):r;let d=[],p=c;0<(d=i?n?(u=be(r,e=>Mc(e)),t=e.serverSyncTree_,s=c,a=u,(u=Mp(t,i))?(o=(u=Fp(u)).path,u=u.queryId,l=Zu(o,s),h=E.fromObject(a),Up(t,o,new dd(ld(u),l,h))):[]):(o=Mc(r),Sp(e.serverSyncTree_,c,o,i)):n?(u=be(r,e=>Mc(e)),s=e.serverSyncTree_,a=c,t=u,l=E.fromObject(t),Pp(s,new dd(od(),a,l))):(h=Mc(r),Cp(e.serverSyncTree_,c,h))).length&&(p=Kf(e,c)),Tf(e.eventQueue_,p,d)}function Df(e,t){if(xf(e,"connected",t),!1===t){var a=e;qf(a,"onDisconnectEvents");let n=Rf(a),i=td(),s=(nd(a.onDisconnect_,v(),(e,t)=>{var r=Hp(e,t,a.serverSyncTree_,n);rd(i,e,r)}),[]);nd(i,v(),(e,t)=>{s=s.concat(Cp(a.serverSyncTree_,e,t));var r=$f(a,e);Kf(a,r)}),a.onDisconnect_=td(),Tf(a.eventQueue_,v(),s)}}function xf(e,t,r){var n=new f("/.info/"+t),i=Mc(r),i=(e.infoData_.updateSnapshot(n,i),Cp(e.infoSyncTree_,n,i));Tf(e.eventQueue_,n,i)}function Of(e){return e.nextWriteId_++}function Lf(n,i,e,t,s){qf(n,"set",{path:i.toString(),value:e,priority:t});var r=Rf(n),a=Mc(e,t),o=Np(n.serverSyncTree_,i),o=Gp(a,o,r);let l=Of(n);r=Ip(n.serverSyncTree_,i,o,l,!0),bf(n.eventQueue_,r),n.server_.put(i.toString(),a.val(!0),(e,t)=>{var r="ok"===e,r=(r||uu("set at "+i+" failed: "+e),Ep(n.serverSyncTree_,l,!r));Tf(n.eventQueue_,i,r),jf(0,s,e,t)}),o=$f(n,i);Kf(n,o),Tf(n.eventQueue_,o,[])}function Mf(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)=>{rd(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),jf(0,i,e,t)})}function Ff(r,n,e,i){let s=Mc(e);r.server_.onDisconnectPut(n.toString(),s.val(!0),(e,t)=>{"ok"===e&&rd(r.onDisconnect_,n,s),jf(0,i,e,t)})}function Uf(e,t,r){let n;n=".info"===_(t._path)?kp(e.infoSyncTree_,t,r):kp(e.serverSyncTree_,t,r),If(e.eventQueue_,t._path,n)}function Vf(e){e.persistentConnection_&&e.persistentConnection_.interrupt(Cf)}function qf(e,...t){let r="";e.persistentConnection_&&(r=e.persistentConnection_.id+":"),lu(r,...t)}function jf(e,n,i,s){n&&Tu(()=>{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 Bf(e,t,r){return Np(e.serverSyncTree_,t,r)||T.EMPTY_NODE}function zf(o,l=o.transactionQueueTree_){if(l||Gf(o,l),Jp(l)){var h=Hf(o,l),e=(g(0<h.length,"Sending zero length transaction queue"),h.every(e=>0===e.status));if(e){var u=o;var c=tf(l);var d=h;let e=d.map(e=>e.currentWriteId),t=Bf(u,c,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++,Zu(c,p.path));r=r.updateChild(f,p.currentOutputSnapshotRaw)}let i=r.val(!0),s=c;u.server_.put(s.toString(),i,t=>{qf(u,"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(Ep(u.serverSyncTree_,d[e].currentWriteId)),d[e].onComplete&&n.push(()=>d[e].onComplete(null,!0,d[e].currentOutputSnapshotResolved)),d[e].unwatcher();Gf(u,Yp(u.transactionQueueTree_,c)),zf(u,u.transactionQueueTree_),Tf(u.eventQueue_,c,r);for(let t=0;t<n.length;t++)Tu(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{uu("transaction at "+s.toString()+" failed: "+t);for(let e=0;e<d.length;e++)d[e].status=4,d[e].abortReason=t}Kf(u,c)}},n)}}else Zp(l)&&ef(l,e=>{zf(o,e)})}function Kf(e,t){var r=Wf(e,t),n=tf(r),r=Hf(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],u=Zu(a,h.path);let e=!1,t;if(g(null!==u,"rerunTransactionsUnderNode_: relativePath should not be null."),4===h.status)e=!0,t=h.abortReason,r=r.concat(Ep(i.serverSyncTree_,h.currentWriteId,!0));else if(0===h.status)if(h.retryCount>=kf)e=!0,t="maxretry",r=r.concat(Ep(i.serverSyncTree_,h.currentWriteId,!0));else{var u=Bf(i,h.path,l),c=(h.currentInputSnapshot=u,s[n].update(u.val()));if(void 0!==c){vf("transaction failed: Data returned ",c,h.path);let e=Mc(c);"object"==typeof c&&null!=c&&_e(c,".priority")||(e=e.updatePriority(u.getPriority()));var c=h.currentWriteId,d=Rf(i),u=Gp(e,u,d);h.currentOutputSnapshotRaw=e,h.currentOutputSnapshotResolved=u,h.currentWriteId=Of(i),l.splice(l.indexOf(c),1),r=(r=r.concat(Ip(i.serverSyncTree_,h.path,u,h.currentWriteId,h.applyLocally))).concat(Ep(i.serverSyncTree_,c,!0))}else e=!0,t="nodata",r=r.concat(Ep(i.serverSyncTree_,h.currentWriteId,!0))}Tf(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)))}Gf(i,i.transactionQueueTree_);for(let e=0;e<o.length;e++)Tu(o[e]);zf(i,i.transactionQueueTree_)}return n}function Wf(e,t){let r,n=e.transactionQueueTree_;for(r=_(t);null!==r&&void 0===Jp(n);)n=Yp(n,r),t=y(t),r=_(t);return n}function Hf(e,t){var r=[];return function t(r,e,n){let i=Jp(e);if(i)for(let e=0;e<i.length;e++)n.push(i[e]);ef(e,e=>{t(r,e,n)})}(e,t,r),r.sort((e,t)=>e.order-t.order),r}function Gf(t,r){var n=Jp(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,Xp(r,0<n.length?n:void 0)}ef(r,e=>{Gf(t,e)})}function $f(t,e){var r=tf(Wf(t,e)),n=Yp(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=>{Qf(t,e)}),Qf(t,n),function t(e,r,n,i){n&&!i&&r(e),ef(e,e=>{t(e,r,!0,i)}),n&&i&&r(e)}(n,e=>{Qf(t,e)}),r}function Qf(i,s){var a=Jp(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(Ep(i.serverSyncTree_,a[r].currentWriteId,!0)),a[r].onComplete&&o.push(a[r].onComplete.bind(null,new Error("set"),!1,null))));-1===t?Xp(s,void 0):a.length=t+1,Tf(i.eventQueue_,tf(s),e);for(let n=0;n<o.length;n++)Tu(o[n])}}let Yf=function(e,t){var r=Jf(e),n=r.namespace,i=("firebase.com"===r.domain&&hu(r.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),n&&"undefined"!==n||"localhost"===r.domain||hu("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),r.secure||cu(),"ws"===r.scheme||"wss"===r.scheme);return{repoInfo:new Ru(r.host,r.secure,n,i,t,"",n!==r.subdomain),path:new f(r.pathString)}},Jf=function(n){let i="",s="",a="",o="",l="",h=!0,u="https",c=443;if("string"==typeof n){let e=n.indexOf("//"),t=(0<=e&&(u=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]):uu(`Invalid query segment '${t}' in query '${e}'`));return n})(n.substring(Math.min(n.length,r))),p=(0<=(e=i.indexOf(":"))?(h="https"===u||"wss"===u,c=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:c,domain:s,subdomain:a,secure:h,scheme:u,pathString:o,namespace:l}},Xf="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",Zf=(()=>{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]=Xf.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+=Xf.charAt(a[r]);return g(20===i.length,"nextPushId: Length should be 20."),i}})();class eg{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+":"+me(this.snapshot.exportVal())}}class tg{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 rg{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 ng{constructor(e,t){this._repo=e,this._path=t}cancel(){var e=new X;return Mf(this._repo,this._path,e.wrapCallback(()=>{})),e.promise}remove(){hf("OnDisconnect.remove",this._path);var e=new X;return Ff(this._repo,this._path,null,e.wrapCallback(()=>{})),e.promise}set(e){hf("OnDisconnect.set",this._path),nf("OnDisconnect.set",e,this._path,!1);var t=new X;return Ff(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}setWithPriority(e,t){hf("OnDisconnect.setWithPriority",this._path),nf("OnDisconnect.setWithPriority",e,this._path,!1),af("OnDisconnect.setWithPriority",t,!1);var n=new X;{var i=this._repo,s=this._path,a=n.wrapCallback(()=>{});let r=Mc(e,t);i.server_.onDisconnectPut(s.toString(),r.val(!0),(e,t)=>{"ok"===e&&rd(i.onDisconnect_,s,r),jf(0,a,e,t)})}return n.promise}update(e){hf("OnDisconnect.update",this._path),sf("OnDisconnect.update",e,this._path,!1);var n,i,r,s,t=new X;return n=this._repo,i=this._path,r=e,s=t.wrapCallback(()=>{}),we(r)?(lu("onDisconnect().update() called with empty data. Don't do anything."),jf(0,s,"ok",void 0)):n.server_.onDisconnectMerge(i.toString(),r,(e,t)=>{"ok"===e&&mu(r,(e,t)=>{var r=Mc(t);rd(n.onDisconnect_,Xu(i,e),r)}),jf(0,s,e,t)}),t.promise}}class ig{constructor(e,t,r,n){this._repo=e,this._path=t,this._queryParams=r,this._orderByCalled=n}get key(){return b(this._path)?null:Qu(this._path)}get ref(){return new lg(this._repo,this._path)}get _queryIdentifier(){var e=Xc(this._queryParams),e=Xh(e);return"{}"===e?"default":e}get _queryObject(){return Xc(this._queryParams)}isEqual(e){var t,r,n;return(e=w(e))instanceof ig&&(t=this._repo===e._repo,r=tc(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 sg(e,t){if(!0===e._orderByCalled)throw new Error(t+": You can't combine multiple orderBy calls.")}function ag(e){let t=null,r=null;if(e.hasStart()&&(t=e.getIndexStartValue()),e.hasEnd()&&(r=e.getIndexEndValue()),e.getIndex()===cc){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()!==pu)throw new Error(n);if("string"!=typeof t)throw new Error(i)}if(e.hasEnd()){if(e.getIndexEndName()!==fu)throw new Error(n);if("string"!=typeof r)throw new Error(i)}}else if(e.getIndex()===I){if(null!=t&&!mf(t)||null!=r&&!mf(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 Fc||e.getIndex()===Vc,"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 og(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 lg extends ig{constructor(e,t){super(e,t,new Gc,!1)}get parent(){var e=Ju(this._path);return null===e?null:new lg(this._repo,e)}get root(){let e=this;for(;null!==e.parent;)e=e.parent;return e}}class hg{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=dg(this.ref,e);return new hg(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 hg(t,dg(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 ug(e,t){return(e=w(e))._checkNotDeleted("ref"),void 0!==t?dg(e._root,t):e._root}function cg(e,t){(e=w(e))._checkNotDeleted("refFromURL");var r=Yf(t,e._repo.repoInfo_.nodeAdmin),n=(yf("refFromURL",r),r.repoInfo);return e._repo.repoInfo_.isCustomHost()||n.host===e._repo.repoInfo_.host||hu("refFromURL: Host name does not match the current database: (found "+n.host+" but expected "+e._repo.repoInfo_.host+")"),ug(e,r.path.toString())}function dg(e,t){return(null===_((e=w(e))._path)?lf:_f)("child","path",t,!1),new lg(e._repo,Xu(e._path,t))}function pg(e,t){e=w(e),hf("set",e._path),nf("set",t,e._path,!1);var r=new X;return Lf(e._repo,e._path,t,null,r.wrapCallback(()=>{})),r.promise}function fg(e,t){sf("update",t,e._path,!1);var i=new X;{var a=e._repo,o=e._path,l=(e=t,i.wrapCallback(()=>{}));qf(a,"update",{path:o.toString(),value:e});let r=!0,n=Rf(a),s={};if(mu(e,(e,t)=>{r=!1,s[e]=Hp(Xu(o,e),Mc(t),a.serverSyncTree_,n)}),r)lu("update() called with empty data. Don't do anything."),jf(0,l,"ok",void 0);else{let i=Of(a);var h=Tp(a.serverSyncTree_,o,s,i);bf(a.eventQueue_,h),a.server_.merge(o.toString(),e,(e,t)=>{var r="ok"===e,r=(r||uu("update at "+o+" failed: "+e),Ep(a.serverSyncTree_,i,!r)),n=0<r.length?Kf(a,o):o;Tf(a.eventQueue_,n,r),jf(0,l,e,t)}),mu(e,e=>{var t=$f(a,Xu(o,e));Kf(a,t)}),Tf(a.eventQueue_,o,[])}}return i.promise}function gg(t){t=w(t);var i,s,a,e=new rg(()=>{}),e=new mg(e);return i=t._repo,s=t,a=e,(null!=(e=Rp(i.serverSyncTree_,s))?Promise.resolve(e):i.server_.get(s).then(e=>{var t,r=Mc(e).withIndex(s._queryParams.getIndex());Ap(i.serverSyncTree_,s,a,!0);let n;return n=s._queryParams.loadsAllData()?Cp(i.serverSyncTree_,s._path,r):(t=Op(i.serverSyncTree_,s),Sp(i.serverSyncTree_,s._path,r,t)),Tf(i.eventQueue_,s._path,n),kp(i.serverSyncTree_,s,a,null,!0),r},e=>(qf(i,"get for query "+me(s)+" failed: "+e),Promise.reject(new Error(e))))).then(e=>new hg(e,new lg(t._repo,t._path),t._queryParams.getIndex()))}class mg{constructor(e){this.callbackContext=e}respondsTo(e){return"value"===e}createEvent(e,t){var r=t._queryParams.getIndex();return new eg("value",this,new hg(e.snapshotNode,new lg(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 tg(this,e,t):null}matches(e){return e instanceof mg&&(!e.callbackContext||!this.callbackContext||e.callbackContext.matches(this.callbackContext))}hasAnyCallback(){return null!==this.callbackContext}}class vg{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 tg(this,e,t):null}createEvent(e,t){g(null!=e.childName,"Child events should have a childName.");var r=dg(new lg(t._repo,t._path),e.childName),n=t._queryParams.getIndex();return new eg(e.type,this,new hg(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 vg&&this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext))}hasAnyCallback(){return!!this.callbackContext}}function _g(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)=>{Uf(n._repo,n,o),r(e,t)};a.userCallback=t.userCallback,a.context=t.context,t=a}a=new rg(t,s||void 0);let o="value"===e?new mg(a):new vg(e,a);{r=n._repo,i=n,t=o;let e;e=".info"===_(i._path)?Ap(r.infoSyncTree_,i,t):Ap(r.serverSyncTree_,i,t),If(r.eventQueue_,i._path,e)}return()=>Uf(n._repo,n,o)}function yg(e,t,r,n){return _g(e,"value",t,r,n)}function wg(e,t,r,n){_g(e,"child_added",t,r,n)}function bg(e,t,r,n){_g(e,"child_changed",t,r,n)}function Ig(e,t,r,n){_g(e,"child_moved",t,r,n)}function Tg(e,t,r,n){_g(e,"child_removed",t,r,n)}function Eg(e,t,r){let n=null;var i=r?new rg(r):null;"value"===t?n=new mg(i):t&&(n=new vg(t,i)),Uf(e._repo,e,n)}class Cg{}class kg extends Cg{constructor(e,t){super(),this._value=e,this._key=t,this.type="endAt"}_apply(e){nf("endAt",this._value,e._path,!0);var t=Qc(e._queryParams,this._value,this._key);if(og(t),ag(t),e._queryParams.hasEnd())throw new Error("endAt: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new ig(e._repo,e._path,t,e._orderByCalled)}}class Sg extends Cg{constructor(e,t){super(),this._value=e,this._key=t,this.type="endBefore"}_apply(e){nf("endBefore",this._value,e._path,!1);var t=((e,t,r)=>{let n;return(n=e.index_===cc||r?Qc(e,t,r):Qc(e,t,pu)).endBeforeSet_=!0,n})(e._queryParams,this._value,this._key);if(og(t),ag(t),e._queryParams.hasEnd())throw new Error("endBefore: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new ig(e._repo,e._path,t,e._orderByCalled)}}class Ag extends Cg{constructor(e,t){super(),this._value=e,this._key=t,this.type="startAt"}_apply(e){nf("startAt",this._value,e._path,!0);var t=$c(e._queryParams,this._value,this._key);if(og(t),ag(t),e._queryParams.hasStart())throw new Error("startAt: Starting point was already set (by another call to startAt, startBefore or equalTo).");return new ig(e._repo,e._path,t,e._orderByCalled)}}class Ng extends Cg{constructor(e,t){super(),this._value=e,this._key=t,this.type="startAfter"}_apply(e){nf("startAfter",this._value,e._path,!1);var t=((e,t,r)=>{let n;return(n=e.index_===cc||r?$c(e,t,r):$c(e,t,fu)).startAfterSet_=!0,n})(e._queryParams,this._value,this._key);if(og(t),ag(t),e._queryParams.hasStart())throw new Error("startAfter: Starting point was already set (by another call to startAt, startAfter, or equalTo).");return new ig(e._repo,e._path,t,e._orderByCalled)}}class Rg extends Cg{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 ig(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 Pg extends Cg{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 ig(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 Dg extends Cg{constructor(e){super(),this._path=e,this.type="orderByChild"}_apply(e){sg(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 Fc(t),t=Yc(e._queryParams,t);return ag(t),new ig(e._repo,e._path,t,!0)}}class xg extends Cg{constructor(){super(...arguments),this.type="orderByKey"}_apply(e){sg(e,"orderByKey");var t=Yc(e._queryParams,cc);return ag(t),new ig(e._repo,e._path,t,!0)}}class Og extends Cg{constructor(){super(...arguments),this.type="orderByPriority"}_apply(e){sg(e,"orderByPriority");var t=Yc(e._queryParams,I);return ag(t),new ig(e._repo,e._path,t,!0)}}class Lg extends Cg{constructor(){super(...arguments),this.type="orderByValue"}_apply(e){sg(e,"orderByValue");var t=Yc(e._queryParams,Vc);return ag(t),new ig(e._repo,e._path,t,!0)}}class Mg extends Cg{constructor(e,t){super(),this._value=e,this._key=t,this.type="equalTo"}_apply(e){if(nf("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 kg(this._value,this._key)._apply(new Ag(this._value,this._key)._apply(e))}}function Fg(e,...t){let r=w(e);for(var n of t)r=n._apply(r);return r}t=lg,g(!op,"__referenceConstructor has already been defined"),op=t,t=lg,g(!yp,"__referenceConstructor has already been defined"),yp=t;let Ug="FIREBASE_DATABASE_EMULATOR_HOST",Vg={},qg=!1;function jg(e,t,r,n,i){let s=n||e.options.databaseURL,a=(void 0===s&&(e.options.projectId||hu("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),lu("Using default host for project ",e.options.projectId),s=e.options.projectId+"-default-rtdb.firebaseio.com"),Yf(s,i)),o=a.repoInfo,l,h=void 0;(h="undefined"!=typeof process&&process.env?process.env[Ug]:h)?(l=!0,s=`http://${h}?ns=`+o.namespace,a=Yf(s,i),o=a.repoInfo):l=!a.repoInfo.secure;var u=i&&l?new ku(ku.OWNER):new Cu(e.name,e.options,t),u=(yf("Invalid Firebase Database URL",a),b(a.path)||hu("Database URL must point to the root of a Firebase Database (not including a child path)."),((e,t,r,n)=>{let i=Vg[t.name];var s;return i||(i={},Vg[t.name]=i),(s=i[e.toURLString()])&&hu("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call."),s=new Sf(e,qg,r,n),i[e.toURLString()]=s})(o,e,u,new Eu(e,r)));return new Bg(u,e)}class Bg{constructor(e,t){this._repoInternal=e,this.app=t,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(Af(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new lg(this._repo,v())),this._rootInternal}_delete(){var e,t,r;return null!==this._rootInternal&&(e=this._repo,t=this.app.name,(r=Vg[t])&&r[e.key]===e||hu(`Database ${t}(${e.repoInfo_}) has already been deleted.`),Vf(e),delete r[e.key],this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){null===this._rootInternal&&hu("Cannot call "+e+" on a deleted database.")}}function zg(){ju.IS_TRANSPORT_INITIALIZED&&uu("Transport has already been initialized. Please call this function before calling ref or setting up a listener")}function Kg(){zg(),Fu.forceDisallow()}function Wg(){zg(),qu.forceDisallow(),Fu.forceAllow()}function Hg(e,t,r,n={}){(e=w(e))._checkNotDeleted("useEmulator"),e._instanceStarted&&hu("Cannot call useEmulator() after instance has already been initialized.");var i,s=e._repoInternal;let a=void 0;s.repoInfo_.nodeAdmin?(n.mockUserToken&&hu('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),a=new ku(ku.OWNER)):n.mockUserToken&&(i="string"==typeof n.mockUserToken?n.mockUserToken:Z(n.mockUserToken,e.app.options.projectId),a=new ku(i)),n=s,e=t,t=r,r=a,n.repoInfo_=new Ru(e+":"+t,!1,n.repoInfo_.namespace,n.repoInfo_.webSocketOnly,n.repoInfo_.nodeAdmin,n.repoInfo_.persistenceKey,n.repoInfo_.includeNamespaceInQueryParams,!0),r&&(n.authTokenProvider_=r)}function Gg(e){(e=w(e))._checkNotDeleted("goOnline"),(e=e._repo).persistentConnection_&&e.persistentConnection_.resume(Cf)}function $g(e,t){ou(e,t)}let Qg={".sv":"timestamp"};class Yg{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}}function Jg(i,e,t){if(i=w(i),hf("Reference.transaction",i._path),".length"===i.key||".keys"===i.key)throw"Reference.transaction failed: "+i.key+" is a read-only object.";var r=null==(r=null==t?void 0:t.applyLocally)||r;let s=new X;var n=yg(i,()=>{}),t=i._repo,a=i._path,o=(e,t,r)=>{var n;e?s.reject(e):(n=new hg(r,new lg(i._repo,i._path),I),s.resolve(new Yg(t,n)))},l=n,h=r;qf(t,"transaction on "+a);var u,n={path:a,update:e,onComplete:o,status:null,order:nu(),applyLocally:h,retryCount:0,unwatcher:l,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},r=Bf(t,a,void 0);if(n.currentInputSnapshot=r,void 0===(u=n.update(r.val())))n.unwatcher(),n.currentOutputSnapshotRaw=null,n.currentOutputSnapshotResolved=null,n.onComplete&&n.onComplete(null,!1,n.currentInputSnapshot);else{vf("transaction failed: Data returned ",u,n.path),n.status=0;var c=Yp(t.transactionQueueTree_,a),d=Jp(c)||[];d.push(n),Xp(c,d);let e;"object"==typeof u&&null!==u&&_e(u,".priority")?(e=ye(u,".priority"),g(mf(e),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.")):(c=Np(t.serverSyncTree_,a)||T.EMPTY_NODE,e=c.getPriority().val());d=Rf(t),c=Mc(u,e),u=Gp(c,r,d),r=(n.currentOutputSnapshotRaw=c,n.currentOutputSnapshotResolved=u,n.currentWriteId=Of(t),Ip(t.serverSyncTree_,a,u,n.currentWriteId,n.applyLocally));Tf(t.eventQueue_,a,r),zf(t,t.transactionQueueTree_)}return s.promise}oc.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)},oc.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)},Bh(Dt),Ct(new u("database",(e,{instanceIdentifier:t})=>jg(e.getProvider("app").getImmediate(),e.getProvider("auth-internal"),e.getProvider("app-check-internal"),t),"PUBLIC").setMultipleInstances(!0)),d(qh,"1.0.12",WD),d(qh,"1.0.12","esm2017");function Xg(e){var t="FIREBASE WARNING: "+e;Zg.warn(t)}let Zg=new $e("@firebase/database-compat");class em{constructor(e){this._delegate=e}cancel(t){l("OnDisconnect.cancel",0,1,arguments.length),De("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),De("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),De("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),De("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,Xg("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.")}De("OnDisconnect.update","onComplete",r,!0);var e=this._delegate.update(t);return r&&e.then(()=>r(null),e=>r(e)),e}}class tm{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 rm{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),_f("DataSnapshot.child","path",e,!1),new rm(this._database,this._delegate.child(e))}hasChild(e){return l("DataSnapshot.hasChild",1,1,arguments.length),_f("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),De("DataSnapshot.forEach","action",t,!1),this._delegate.forEach(e=>t(new rm(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 im(this._database,this._delegate.ref)}get ref(){return this.getRef()}}class nm{constructor(e,t){this.database=e,this._delegate=t}on(e,r,t,n){var i;l("Query.on",2,4,arguments.length),De("Query.on","callback",r,!1);let s=nm.getCancelAndContextArgs_("Query.on",t,n);var a=(e,t)=>{r.call(s.context,new rm(this.database,e),t)},o=(a.userCallback=r,a.context=s.context,null==(i=s.cancel)?void 0:i.bind(s.context));switch(e){case"value":return yg(this._delegate,a,o),r;case"child_added":return wg(this._delegate,a,o),r;case"child_removed":return Tg(this._delegate,a,o),r;case"child_changed":return bg(this._delegate,a,o),r;case"child_moved":return Ig(this._delegate,a,o),r;default:throw new Error(Pe("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(Pe(i,"eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}De("Query.off","callback",t,!0),xe("Query.off","context",r,!0),t?((n=()=>{}).userCallback=t,n.context=r,Eg(this._delegate,e,n)):Eg(this._delegate,e)}get(){return gg(this._delegate).then(e=>new rm(this.database,e))}once(e,n,t,r){l("Query.once",1,4,arguments.length),De("Query.once","callback",n,!0);let i=nm.getCancelAndContextArgs_("Query.once",t,r),s=new X;var a=(e,t)=>{var r=new rm(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":yg(this._delegate,a,o,{onlyOnce:!0});break;case"child_added":wg(this._delegate,a,o,{onlyOnce:!0});break;case"child_removed":Tg(this._delegate,a,o,{onlyOnce:!0});break;case"child_changed":bg(this._delegate,a,o,{onlyOnce:!0});break;case"child_moved":Ig(this._delegate,a,o,{onlyOnce:!0});break;default:throw new Error(Pe("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 nm(this.database,Fg(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 Rg(e)})(e)))}limitToLast(e){return l("Query.limitToLast",1,1,arguments.length),new nm(this.database,Fg(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 Pg(e)})(e)))}orderByChild(e){return l("Query.orderByChild",1,1,arguments.length),new nm(this.database,Fg(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 _f("orderByChild","path",e,!1),new Dg(e)})(e)))}orderByKey(){return l("Query.orderByKey",0,0,arguments.length),new nm(this.database,Fg(this._delegate,new xg))}orderByPriority(){return l("Query.orderByPriority",0,0,arguments.length),new nm(this.database,Fg(this._delegate,new Og))}orderByValue(){return l("Query.orderByValue",0,0,arguments.length),new nm(this.database,Fg(this._delegate,new Lg))}startAt(e=null,t){return l("Query.startAt",0,2,arguments.length),new nm(this.database,Fg(this._delegate,([e=null,t]=[e,t],of("startAt","key",t,!0),new Ag(e,t))))}startAfter(e=null,t){return l("Query.startAfter",0,2,arguments.length),new nm(this.database,Fg(this._delegate,(e=e,t=t,of("startAfter","key",t,!0),new Ng(e,t))))}endAt(e=null,t){return l("Query.endAt",0,2,arguments.length),new nm(this.database,Fg(this._delegate,(e=e,t=t,of("endAt","key",t,!0),new kg(e,t))))}endBefore(e=null,t){return l("Query.endBefore",0,2,arguments.length),new nm(this.database,Fg(this._delegate,(e=e,t=t,of("endBefore","key",t,!0),new Sg(e,t))))}equalTo(e,t){return l("Query.equalTo",1,2,arguments.length),new nm(this.database,Fg(this._delegate,(e=e,t=t,of("equalTo","key",t,!0),new Mg(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 nm)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,De(e,"cancel",n.cancel,!0),n.context=r,xe(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(Pe(e,"cancelOrContext")+" must either be a cancel callback or a context object.");n.cancel=t}return n}get ref(){return new im(this.database,new lg(this._delegate._repo,this._delegate._path))}}class im extends nm{constructor(e,t){super(e,new ig(t._repo,t._path,new Gc,!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 im(this.database,dg(this._delegate,e))}getParent(){l("Reference.parent",0,0,arguments.length);var e=this._delegate.parent;return e?new im(this.database,e):null}getRoot(){return l("Reference.root",0,0,arguments.length),new im(this.database,this._delegate.root)}set(e,t){l("Reference.set",1,2,arguments.length),De("Reference.set","onComplete",t,!0);var r=pg(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,Xg("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.")}hf("Reference.update",this._delegate._path),De("Reference.update","onComplete",r,!0);var e=fg(this._delegate,t);return r&&e.then(()=>r(null),e=>r(e)),e}setWithPriority(e,t,r){l("Reference.setWithPriority",2,3,arguments.length),De("Reference.setWithPriority","onComplete",r,!0);var n=((e,t,r)=>{if(hf("setWithPriority",e._path),nf("setWithPriority",t,e._path,!1),af("setWithPriority",r,!1),".length"===e.key||".keys"===e.key)throw"setWithPriority failed: "+e.key+" is a read-only object.";var n=new X;return Lf(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),De("Reference.remove","onComplete",t,!0);e=this._delegate,hf("remove",e._path);var e,r=pg(e,null);return t&&r.then(()=>t(null),e=>t(e)),r}transaction(e,t,r){l("Reference.transaction",1,3,arguments.length),De("Reference.transaction","transactionUpdate",e,!1),De("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=Jg(this._delegate,e,{applyLocally:r}).then(e=>new tm(e.committed,new rm(this.database,e.snapshot))),t&&n.then(e=>t(null,e.committed,e.snapshot),e=>t(e,!1,null)),n;throw new Error(Pe(i,s)+"must be a boolean.")}setPriority(e,t){l("Reference.setPriority",1,2,arguments.length),De("Reference.setPriority","onComplete",t,!0);r=this._delegate,e=e,r=w(r),hf("setPriority",r._path),af("setPriority",e,!1),n=new X,Lf(r._repo,Xu(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),De("Reference.push","onComplete",t,!0);var r=((e,t)=>{e=w(e),hf("push",e._path),nf("push",t,e._path,!0);var r=Nf(e._repo),r=Zf(r),n=dg(e,r);let i=dg(e,r),s;return s=null!=t?pg(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 im(this.database,e)),r=(t&&n.then(()=>t(null),e=>t(e)),new im(this.database,r));return r.then=n.then.bind(n),r.catch=n.catch.bind(n,void 0),r}onDisconnect(){return hf("Reference.onDisconnect",this._delegate._path),new em(new ng(this._delegate._repo,this._delegate._path))}get key(){return this.getKey()}get parent(){return this.getParent()}get root(){return this.getRoot()}}class sm{constructor(e,t){this._delegate=e,this.app=t,this.INTERNAL={delete:()=>this._delegate._delete(),forceWebSockets:Kg,forceLongPolling:Wg}}useEmulator(e,t,r={}){Hg(this._delegate,e,t,r)}ref(e){var t;return l("database.ref",0,1,arguments.length),e instanceof im?(t=cg(this._delegate,e.toString()),new im(this,t)):(t=ug(this._delegate,e),new im(this,t))}refFromURL(e){l("database.refFromURL",1,1,arguments.length);var t=cg(this._delegate,e);return new im(this,t)}goOffline(){var e;l("database.goOffline",0,0,arguments.length),(e=w(e=this._delegate))._checkNotDeleted("goOffline"),Vf(e._repo)}goOnline(){return l("database.goOnline",0,0,arguments.length),Gg(this._delegate)}}sm.ServerValue={TIMESTAMP:Qg,increment:e=>({".sv":{increment:e}})};rr=Object.freeze({__proto__:null,initStandalone:function({app:e,url:t,version:r,customAuthImpl:n,customAppCheckImpl:i,namespace:s,nodeAdmin:a=!1}){Bh(r);var o=new Be("database-standalone"),l=new je("auth-internal",o);l.setComponent(new u("auth-internal",()=>n,"PRIVATE"));let h=void 0;return i&&(h=new je("app-check-internal",o)).setComponent(new u("app-check-internal",()=>i,"PRIVATE")),{instance:new sm(jg(e,l,h,t,a),e),namespace:s}}});let am=sm.ServerValue;(t=tr).INTERNAL.registerComponent(new u("database-compat",(e,{instanceIdentifier:t})=>{var r=e.getProvider("app-compat").getImmediate(),n=e.getProvider("database").getImmediate({identifier:t});return new sm(n,r)},"PUBLIC").setServiceProps({Reference:im,Query:nm,Database:sm,DataSnapshot:rm,enableLogging:$g,INTERNAL:rr,ServerValue:am}).setMultipleInstances(!0)),t.registerVersion("@firebase/database-compat","2.0.3");var om,lm,hm,um,cm,dm,pm,fm,gm,mm,vm,_m,ym="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},wm=(!(function(){var e,t,s;function r(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.B=Array(this.blockSize),this.o=this.h=0,this.s()}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=(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=t+(s^r&(i^s))+n[0]+3614090360&4294967295)<<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 h(e,t){this.h=t;for(var r=[],n=!0,i=e.length-1;0<=i;i--){var s=0|e[i];n&&s==t||(r[i]=s,n=!1)}this.g=r}t=r,s=function(){this.blockSize=-1},n.prototype=s.prototype,t.D=s.prototype,t.prototype=new n,(t.prototype.constructor=t).C=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.s=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.o=this.h=0},r.prototype.u=function(e,t){for(var r=(t=void 0===t?e.length:t)-this.blockSize,n=this.B,i=this.h,s=0;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.v=function(){var e=Array((this.h<56?this.blockSize:2*this.blockSize)-this.h);e[0]=128;for(var t=1;t<e.length-8;++t)e[t]=0;for(var r=8*this.o,t=e.length-8;t<e.length;++t)e[t]=255&r,r/=256;for(this.u(e),e=Array(16),t=r=0;t<4;++t)for(var n=0;n<32;n+=8)e[r++]=this.g[t]>>>n&255;return e};var i={};function o(e){return-128<=e&&e<128?(t=e,r=function(e){return new h([0|e],e<0?-1:0)},n=i,Object.prototype.hasOwnProperty.call(n,t)?n[t]:n[t]=r(t)):new h([0|e],e<0?-1:0);var t,r,n}function u(e){if(isNaN(e)||!isFinite(e))return c;if(e<0)return g(u(-e));for(var t=[],r=1,n=0;r<=e;n++)t[n]=e/r|0,r*=4294967296;return new h(t,0)}var c=o(0),l=o(1),d=o(16777216);function p(e){if(0==e.h){for(var t=0;t<e.g.length;t++)if(0!=e.g[t])return;return 1}}function f(e){return-1==e.h}function g(e){for(var t=e.g.length,r=[],n=0;n<t;n++)r[n]=~e.g[n];return new h(r,~e.h).add(l)}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=l,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=u(r)).j(t);f(a)||0<a.l(e);)a=(s=u(r-=n)).j(t);p(s)&&(s=l),i=i.add(s),e=m(e,a)}return new _(i,e)}function w(e){for(var t=e.g.length+1,r=[],n=0;n<t;n++)r[n]=e.i(n)<<1|e.i(n-1)>>>31;return new h(r,e.h)}function b(e,t){var r=t>>5;t%=32;for(var n=e.g.length-r,i=[],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 h(i,e.h)}(e=h.prototype).m=function(){if(f(this))return-g(this).m();for(var e=0,t=1,r=0;r<this.g.length;r++){var n=this.i(r);e+=(0<=n?n:4294967296+n)*t,t*=4294967296}return e},e.toString=function(e){if((e=e||10)<2||36<e)throw Error("radix out of range: "+e);if(p(this))return"0";if(f(this))return"-"+g(this).toString(e);for(var t=u(Math.pow(e,6)),r=this,n="";;){var i=y(r,t).g,s=((0<(r=m(r,i.j(t))).g.length?r.g[0]:r.h)>>>0).toString(e);if(p(r=i))return s+n;for(;s.length<6;)s="0"+s;n=s+n}},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){for(var t=Math.max(this.g.length,e.g.length),r=[],n=0,i=0;i<=t;i++){var s=n+(65535&this.i(i))+(65535&e.i(i)),a=(s>>>16)+(this.i(i)>>>16)+(e.i(i)>>>16),n=a>>>16;r[i]=(a&=65535)<<16|(s&=65535)}return new h(r,-2147483648&r[r.length-1]?-1:0)},e.j=function(e){if(p(this)||p(e))return c;if(f(this))return f(e)?g(this).j(g(e)):g(g(this).j(e));if(f(e))return g(this.j(g(e)));if(this.l(d)<0&&e.l(d)<0)return u(this.m()*e.m());for(var t=this.g.length+e.g.length,r=[],n=0;n<2*t;n++)r[n]=0;for(n=0;n<this.g.length;n++)for(var i=0;i<e.g.length;i++){var s=this.i(n)>>>16,a=65535&this.i(n),o=e.i(i)>>>16,l=65535&e.i(i);r[2*n+2*i]+=a*l,v(r,2*n+2*i),r[2*n+2*i+1]+=s*l,v(r,2*n+2*i+1),r[2*n+2*i+1]+=a*o,v(r,2*n+2*i+1),r[2*n+2*i+2]+=s*o,v(r,2*n+2*i+2)}for(n=0;n<t;n++)r[n]=r[2*n+1]<<16|r[2*n];for(n=t;n<2*t;n++)r[n]=0;return new h(r,0)},e.A=function(e){return y(this,e).h},e.and=function(e){for(var t=Math.max(this.g.length,e.g.length),r=[],n=0;n<t;n++)r[n]=this.i(n)&e.i(n);return new h(r,this.h&e.h)},e.or=function(e){for(var t=Math.max(this.g.length,e.g.length),r=[],n=0;n<t;n++)r[n]=this.i(n)|e.i(n);return new h(r,this.h|e.h)},e.xor=function(e){for(var t=Math.max(this.g.length,e.g.length),r=[],n=0;n<t;n++)r[n]=this.i(n)^e.i(n);return new h(r,this.h^e.h)},r.prototype.digest=r.prototype.v,r.prototype.reset=r.prototype.s,r.prototype.update=r.prototype.u,lm=r,h.prototype.multiply=h.prototype.j,h.prototype.modulo=h.prototype.A,h.prototype.compare=h.prototype.l,h.prototype.toNumber=h.prototype.m,h.prototype.getBits=h.prototype.i,h.fromNumber=u,h.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');for(var n=u(Math.pow(r,8)),i=c,s=0;s<t.length;s+=8)var a=Math.min(8,t.length-s),o=parseInt(t.substring(s,s+a),r),i=(a<8?(a=u(Math.pow(r,a)),i.j(a)):i=i.j(n)).add(u(o));return i},om=h}).apply(void 0!==ym?ym:"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,R="function"==typeof Object.defineProperties?Object.defineProperty:function(e,t,r){return e!=Array.prototype&&e!=Object.prototype&&(e[t]=r.value),e};var P=(e=>{e=["object"==typeof globalThis&&globalThis,e,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof wm&&wm];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);var t="Array.prototype.values",r=function(e){return e||function(){return r=function(e,t){return t},(t=this)instanceof String&&(t+=""),n=0,i=!1,(e={next:function(){var e;return!i&&n<t.length?(e=n++,{value:r(e,t[e]),done:!1}):{done:i=!0,value:void 0}}})[Symbol.iterator]=function(){return e},e;var t,r,n,i,e}};if(r)e:{var n=P;t=t.split(".");for(var i=0;i<t.length-1;i++){var U=t[i];if(!(U in n))break e;n=n[U]}(r=r(i=n[t=t[t.length-1]]))!=i&&null!=r&&R(n,t,{configurable:!0,writable:!0,value:r})}var V=V||{},D=this||self;function q(e){var t=typeof e;return"array"==(t="object"!=t?t:e?Array.isArray(e)?"array":t:"null")||"object"==t&&"number"==typeof e.length}function h(e){var t=typeof e;return"object"==t&&null!=e||"function"==t}function j(e,t,r){return e.call.apply(e.bind,arguments)}function B(t,r,e){var n;if(t)return 2<arguments.length?(n=Array.prototype.slice.call(arguments,2),function(){var e=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(e,n),t.apply(r,e)}):function(){return t.apply(r,arguments)};throw Error()}function m(e,t,r){return(m=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?j:B).apply(null,arguments)}function z(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 s(e,s){function t(){}t.prototype=s.prototype,e.aa=s.prototype,e.prototype=new t,(e.prototype.constructor=e).Qb=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)}}function K(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 W(t){for(let e=1;e<arguments.length;e++){var r=arguments[e];if(q(r)){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)}}function x(e){return/^[\s\xa0]*$/.test(e)}function a(){var e=D.navigator;return(e=e&&e.userAgent)||""}function H(e){return H[" "](e),e}H[" "]=function(){};var G=!(-1==a().indexOf("Gecko")||-1!=a().toLowerCase().indexOf("webkit")&&-1==a().indexOf("Edge")||-1!=a().indexOf("Trident")||-1!=a().indexOf("MSIE")||-1!=a().indexOf("Edge"));function $(e,t,r){for(var n in e)t.call(r,e[n],n,e)}function Q(e){var t,r={};for(t in e)r[t]=e[t];return r}let Y="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function J(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<Y.length;e++)r=Y[e],Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}}var X=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 Z,e=>e.reset());class Z{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 o,l=!1,ee=new class{constructor(){this.h=this.g=null}add(e,t){var r=X.get();r.set(e,t),this.h?this.h.next=r:this.g=r,this.h=r}},te=()=>{let e=D.Promise.resolve(void 0);o=()=>{e.then(re)}};var re=()=>{for(var e;e=(()=>{let e=ee,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=>{D.setTimeout(()=>{throw e},0)})(e)}var t=X;t.j(e),t.h<100&&(t.h++,e.next=t.g,t.g=e)}l=!1};function u(){this.s=this.s,this.C=this.C}function c(e,t){this.type=e,this.g=this.target=t,this.defaultPrevented=!1}u.prototype.s=!1,u.prototype.ma=function(){this.s||(this.s=!0,this.N())},u.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()},c.prototype.h=function(){this.defaultPrevented=!0};var ne=(()=>{if(!D.addEventListener||!Object.defineProperty)return!1;var e=!1,t=Object.defineProperty({},"passive",{get:function(){e=!0}});try{var r=()=>{};D.addEventListener("test",r,t),D.removeEventListener("test",r,t)}catch(e){}return e})();function d(e,t){if(c.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){var r=this.type=e.type,n=e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:null;if(this.target=e.target||e.srcElement,this.g=t,t=e.relatedTarget){if(G){e:{try{H(t.nodeName);var i=!0;break e}catch(e){}i=!1}i||(t=null)}}else"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="string"==typeof e.pointerType?e.pointerType:ie[e.pointerType]||"",this.state=e.state,(this.i=e).defaultPrevented&&d.aa.h.call(this)}}s(d,c);var ie={2:"touch",3:"pen",4:"mouse"},p=(d.prototype.h=function(){d.aa.h.call(this);var e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1},"closure_listenable_"+(1e6*Math.random()|0)),se=0;function ae(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=++se,this.da=this.fa=!1}function oe(e){e.da=!0,e.listener=null,e.proxy=null,e.src=null,e.ha=null}function le(e){this.src=e,this.g={},this.h=0}function he(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)&&(oe(t),0==e.g[s].length)&&(delete e.g[s],e.h--)}function ue(e,t,r,n){for(var i=0;i<e.length;++i){var s=e[i];if(!s.da&&s.listener==t&&s.capture==!!r&&s.ha==n)return i}return-1}le.prototype.add=function(e,t,r,n,i){var s=e.toString(),a=((e=this.g[s])||(e=this.g[s]=[],this.h++),ue(e,t,n,i));return-1<a?(t=e[a],r||(t.fa=!1)):((t=new ae(t,this.src,s,!!n,i)).fa=r,e.push(t)),t};var ce="closure_lm_"+(1e6*Math.random()|0),de={};function pe(e,t,r,n,i){if(n&&n.once)return 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);return null}n=we(n);return t&&t[p]?t.L(r,n,h(i)?!!i.capture:!!i,s):fe(t,r,n,!0,i,s)}(e,t,r,n,i);if(Array.isArray(t)){for(var s=0;s<t.length;s++)pe(e,t[s],r,n,i);return null}return r=we(r),e&&e[p]?e.K(t,r,h(n)?!!n.capture:!!n,i):fe(e,t,r,!1,n,i)}function fe(e,t,r,n,i,s){if(!t)throw Error("Invalid event type");var a=h(i)?!!i.capture:!!i,o=_e(e);if(o||(e[ce]=o=new le(e)),!(r=o.add(t,r,n,a,s)).proxy)if(n=(()=>{let r=ve;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=ne?i:a)&&(i=!1),e.addEventListener(t.toString(),n,i);else if(e.attachEvent)e.attachEvent(me(t.toString()),n);else{if(!e.addListener||!e.removeListener)throw Error("addEventListener and attachEvent are unavailable.");e.addListener(n)}return r}function ge(e){var t,r,n;"number"!=typeof e&&e&&!e.da&&((t=e.src)&&t[p]?he(t.i,e):(r=e.type,n=e.proxy,t.removeEventListener?t.removeEventListener(r,n,e.capture):t.detachEvent?t.detachEvent(me(r),n):t.addListener&&t.removeListener&&t.removeListener(n),(r=_e(t))?(he(r,e),0==r.h&&(r.src=null,t[ce]=null)):oe(e)))}function me(e){return e in de?de[e]:de[e]="on"+e}function ve(e,t){var r,n;return e=!!e.da||(t=new d(t,this),r=e.listener,n=e.ha||e.src,e.fa&&ge(e),r.call(n,t))}function _e(e){return(e=e[ce])instanceof le?e:null}var ye="__closure_events_fn_"+(1e9*Math.random()>>>0);function we(t){return"function"==typeof t?t:(t[ye]||(t[ye]=function(e){return t.handleEvent(e)}),t[ye])}function f(){u.call(this),this.i=new le(this),(this.M=this).F=null}function g(e,t){var r,n=e.F;if(n)for(r=[];n;n=n.F)r.push(n);if(e=e.M,n=t.type||t,"string"==typeof t?t=new c(t,e):t instanceof c?t.target=t.target||e:(a=t,J(t=new c(n,e),a)),a=!0,r)for(var i=r.length-1;0<=i;i--)var s=t.g=r[i],a=be(s,n,!0,t)&&a;if(a=be(s=t.g=e,n,!0,t)&&a,a=be(s,n,!1,t)&&a,r)for(i=0;i<r.length;i++)a=be(s=t.g=r[i],n,!1,t)&&a}function be(e,t,r,n){if(!(t=e.i.g[String(t)]))return!0;t=t.concat();for(var i=!0,s=0;s<t.length;++s){var a,o,l=t[s];l&&!l.da&&l.capture==r&&(a=l.listener,o=l.ha||l.src,l.fa&&he(e.i,l),i=!1!==a.call(o,n)&&i)}return i&&!n.defaultPrevented}function Ie(e,t,r){if("function"==typeof e)r&&(e=m(e,r));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=m(e.handleEvent,e)}return 2147483647<Number(t)?-1:D.setTimeout(e,t||0)}s(f,u),f.prototype[p]=!0,f.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=h(i)?!!i.capture:!!i,n=we(n),t&&t[p]?(t=t.i,(r=String(r).toString())in t.g&&-1<(n=ue(a=t.g[r],n,i,s))&&(oe(a[n]),Array.prototype.splice.call(a,n,1),0==a.length)&&(delete t.g[r],t.h--)):(t=t&&_e(t))&&(r=t.g[r.toString()],n=(t=-1)<(t=r?ue(r,n,i,s):t)?r[t]:null)&&ge(n)}(this,e,t,r,n)},f.prototype.N=function(){if(f.aa.N.call(this),this.i){var e,t=this.i;for(e in t.g){for(var r=t.g[e],n=0;n<r.length;n++)oe(r[n]);delete t.g[e],t.h--}}this.F=null},f.prototype.K=function(e,t,r,n){return this.i.add(String(e),t,!1,r,n)},f.prototype.L=function(e,t,r,n){return this.i.add(String(e),t,!0,r,n)};class Te extends u{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:function e(t){t.g=Ie(()=>{t.g=null,t.i&&(t.i=!1,e(t))},t.l);var r=t.h;t.h=null,t.m.apply(null,r)}(this)}N(){super.N(),this.g&&(D.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function v(e){u.call(this),this.h=e,this.g={}}s(v,u);var Ee=[];function Ce(e){$(e.g,function(e,t){this.g.hasOwnProperty(t)&&ge(e)},e),e.g={}}v.prototype.N=function(){v.aa.N.call(this),Ce(this)},v.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var ke=D.JSON.stringify,Se=D.JSON.parse,Ae=class{stringify(e){return D.JSON.stringify(e,void 0)}parse(e){return D.JSON.parse(e,void 0)}};function Ne(){}function Re(e){return e.h||(e.h=e.i())}function Pe(){}Ne.prototype.h=null;var De={OPEN:"a",kb:"b",Ja:"c",wb:"d"};function xe(){c.call(this,"d")}function Oe(){c.call(this,"c")}s(xe,c),s(Oe,c);var _={},Le=null;function Me(){return Le=Le||new f}function Fe(e){c.call(this,_.La,e)}function Ue(){var e=Me();g(e,new Fe(e))}function Ve(e,t){c.call(this,_.STAT_EVENT,e),this.stat=t}function O(e){var t=Me();g(t,new Ve(t,e))}function qe(e,t){c.call(this,_.Ma,e),this.size=t}function je(e,t){if("function"!=typeof e)throw Error("Fn must not be null and must be a function");return D.setTimeout(function(){e()},t)}function Be(){this.g=!0}function L(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(var a=1;a<i.length;a++)i[a]=""}}}return ke(r)}catch(e){return t}})(e,r)+(n?" "+n:"")})}_.La="serverreachability",s(Fe,c),_.STAT_EVENT="statevent",s(Ve,c),_.Ma="timingevent",s(qe,c),Be.prototype.xa=function(){this.g=!1},Be.prototype.info=function(){};var ze={NO_ERROR:0,gb:1,tb:2,sb:3,nb:4,rb:5,ub:6,Ia:7,TIMEOUT:8,xb:9},Ke={lb:"complete",Hb:"success",Ja:"error",Ia:"abort",zb:"ready",Ab:"readystatechange",TIMEOUT:"timeout",vb:"incrementaldata",yb:"progress",ob:"downloadprogress",Pb:"uploadprogress"};function We(){}function y(e,t,r,n){this.j=e,this.i=t,this.l=r,this.R=n||1,this.U=new v(this),this.I=45e3,this.H=null,this.o=!1,this.m=this.A=this.v=this.L=this.F=this.S=this.B=null,this.D=[],this.g=null,this.C=0,this.s=this.u=null,this.X=-1,this.J=!1,this.O=0,this.M=null,this.W=this.K=this.T=this.P=!1,this.h=new He}function He(){this.i=null,this.g="",this.h=!1}s(We,Ne),We.prototype.g=function(){return new XMLHttpRequest},We.prototype.i=function(){return{}};var Ge=new We,$e={},Qe={};function Ye(e,t,r){e.L=1,e.v=vt(b(t)),e.m=r,e.P=!0,Je(e,null)}function Je(e,t){e.F=Date.now(),Ze(e),e.A=b(e.v);var r=e.A,n=e.R,i=(Array.isArray(n)||(n=[String(n)]),Rt(r.i,"t",n),e.C=0,r=e.j.J,e.h=new He,e.g=cr(e.j,r?t:null,!e.m),0<e.O&&(e.M=new Te(m(e.Y,e,e.g),e.O)),t=e.U,r=e.g,n=e.ca,"readystatechange");Array.isArray(i)||(i&&(Ee[0]=i.toString()),i=Ee);for(var a,o,l,h,u,c,s=0;s<i.length;s++){var d=pe(r,i[s],n||t.handleEvent,!1,t.h||t);if(!d)break;t.g[d.key]=d}t=e.H?Q(e.H):{},e.m?(e.u||(e.u="POST"),t["Content-Type"]="application/x-www-form-urlencoded",e.g.ea(e.A,e.u,e.m,t)):(e.u="GET",e.g.ea(e.A,e.u,null,t)),Ue(),a=e.i,o=e.u,l=e.A,h=e.l,u=e.R,c=e.m,a.info(function(){if(a.g)if(c)for(var e="",t=c.split("&"),r=0;r<t.length;r++){var n,i,s=t[r].split("=");1<s.length&&(n=s[0],s=s[1],e=2<=(i=n.split("_")).length&&"type"==i[1]?e+(n+"=")+s+"&":e+(n+"=redacted&"))}else e=null;else e=c;return"XMLHTTP REQ ("+h+") [attempt "+u+"]: "+o+"\n"+l+"\n"+e})}function Xe(e){return e.g&&"GET"==e.u&&2!=e.L&&e.j.Ca}function Ze(e){e.S=Date.now()+e.I,et(e,e.I)}function et(e,t){if(null!=e.B)throw Error("WatchDog timer not null");e.B=je(m(e.ba,e),t)}function tt(e){e.B&&(D.clearTimeout(e.B),e.B=null)}function rt(e){0==e.j.G||e.J||or(e.j,e)}function M(e){tt(e);var t=e.M;t&&"function"==typeof t.ma&&t.ma(),e.M=null,Ce(e.U),e.g&&(t=e.g,e.g=null,t.abort(),t.ma())}function nt(e,t){try{var r=e.j;if(0!=r.G&&(r.g==e||lt(r.h,e)))if(!e.K&<(r.h,e)&&3==r.G){try{var n=r.Da.g.parse(t)}catch(e){n=null}if(Array.isArray(n)&&3==n.length){var i=n;if(0==i[0]){e:if(!r.u){if(r.g){if(!(r.g.F+3e3<e.F))break e;ar(r),Yt(r)}nr(r),O(18)}}else r.za=i[1],0<r.za-r.T&&i[2]<37500&&r.F&&0==r.v&&!r.C&&(r.C=je(m(r.Za,r),6e3));if(ot(r.h)<=1&&r.ca){try{r.ca()}catch(e){}r.ca=void 0}}else S(r,11)}else if(!e.K&&r.g!=e||ar(r),!x(t))for(i=r.Da.g.parse(t),t=0;t<i.length;t++){var s,a,o,l,h,u,c,d,p,f,g=i[t];r.T=g[0],g=g[1],2==r.G?"c"==g[0]?(r.K=g[1],r.ia=g[2],null!=(s=g[3])&&(r.la=s,r.j.info("VER="+r.la)),null!=(a=g[4])&&(r.Aa=a,r.j.info("SVER="+r.Aa)),null!=(o=g[5])&&"number"==typeof o&&0<o&&(n=1.5*o,r.L=n,r.j.info("backChannelRequestTimeoutMs_="+n)),n=r,(l=e.g)&&(!(h=l.g?l.g.getResponseHeader("X-Client-Wire-Protocol"):null)||(u=n.h).g||-1==h.indexOf("spdy")&&-1==h.indexOf("quic")&&-1==h.indexOf("h2")||(u.j=u.l,u.g=new Set,u.h&&(ht(u,u.h),u.h=null)),n.D)&&(c=l.g?l.g.getResponseHeader("X-HTTP-Session-Id"):null)&&(n.ya=c,I(n.I,n.D,c)),r.G=3,r.l&&r.l.ua(),r.ba&&(r.R=Date.now()-e.F,r.j.info("Handshake RTT: "+r.R+"ms")),d=e,(n=r).qa=ur(n,n.J?n.ia:null,n.W),d.K?(ut(n.h,d),p=d,(f=n.L)&&(p.I=f),p.B&&(tt(p),Ze(p)),n.g=d):rr(n),0<r.i.length&&Xt(r)):"stop"!=g[0]&&"close"!=g[0]||S(r,7):3==r.G&&("stop"==g[0]||"close"==g[0]?"stop"==g[0]?S(r,7):Qt(r):"noop"!=g[0]&&r.l&&r.l.ta(g),r.v=0)}Ue()}catch(e){}}y.prototype.ca=function(e){e=e.target;var t=this.M;t&&3==F(e)?t.j():this.Y(e)},y.prototype.Y=function(e){try{if(e==this.g)e:{var t=F(this.g),r=this.g.Ba();this.g.Z();if(!(t<3)&&(3!=t||this.g&&(this.h.h||this.g.oa()||Ht(this.g)))){this.J||4!=t||7==r||Ue(),tt(this);var n=this.g.Z();this.X=n;t:if(Xe(this)){var i=Ht(this.g),s=(e="",i.length),a=4==F(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){M(this),rt(this);var o="";break t}this.h.i=new D.TextDecoder}for(r=0;r<s;r++)this.h.h=!0,e+=this.h.i.decode(i[r],{stream:!(a&&r==s-1)});i.length=0,this.h.g+=e,this.C=0,o=this.h.g}else o=this.g.oa();if(this.o=200==n,C=this.i,k=this.u,S=this.A,A=this.l,N=this.R,R=t,P=n,C.info(function(){return"XMLHTTP RESP ("+A+") [ attempt "+N+"]: "+k+"\n"+S+"\n"+R+" "+P}),this.o){if(this.T&&!this.K){t:{if(this.g){var l,h=this.g;if((l=h.g?h.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!x(l)){var u=l;break t}}u=null}if(!(n=u)){this.o=!1,this.s=3,O(12),M(this),rt(this);break e}L(this.i,this.l,n,"Initial handshake response via X-HTTP-Initial-Response"),this.K=!0,nt(this,n)}if(this.P){for(var c,d,n=!0;!this.J&&this.C<o.length;){if(I=o,E=T=void 0,T=(b=this).C,(c=-1==(E=I.indexOf("\n",T))?Qe:(T=Number(I.substring(T,E)),isNaN(T)?$e:(E+=1)+T>I.length?Qe:(I=I.slice(E,E+T),b.C=E+T,I)))==Qe){4==t&&(this.s=4,O(14),n=!1),L(this.i,this.l,null,"[Incomplete Response]");break}if(c==$e){this.s=4,O(15),L(this.i,this.l,o,"[Invalid Chunk]"),n=!1;break}L(this.i,this.l,c,null),nt(this,c)}Xe(this)&&0!=this.C&&(this.h.g=this.h.g.slice(this.C),this.C=0),4!=t||0!=o.length||this.h.h||(this.s=1,O(16),n=!1),this.o=this.o&&n,n?0<o.length&&!this.W&&(this.W=!0,(d=this.j).g==this)&&d.ba&&!d.M&&(d.j.info("Great, no buffering proxy detected. Bytes received: "+o.length),ir(d),d.M=!0,O(11)):(L(this.i,this.l,o,"[Invalid Chunked Response]"),M(this),rt(this))}else L(this.i,this.l,o,null),nt(this,o);4==t&&M(this),this.o&&!this.J&&(4==t?or(this.j,this):(this.o=!1,Ze(this)))}else{{var p=this.g;var f,g,m,v={};p=(p.g&&2<=F(p)&&p.g.getAllResponseHeaders()||"").split("\r\n");for(let e=0;e<p.length;e++)x(p[e])||(f=(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})(p[e]),g=f[0],"string"==typeof(f=f[1])&&(f=f.trim(),m=v[g]||[],(v[g]=m).push(f)));var _,y=v,w=function(e){return e.join(", ")};for(_ in y)w.call(void 0,y[_],_,y)}400==n&&0<o.indexOf("Unknown SID")?(this.s=3,O(12)):(this.s=0,O(13)),M(this),rt(this)}}}}catch(e){}var b,I,T,E,C,k,S,A,N,R,P},y.prototype.cancel=function(){this.J=!0,M(this)},y.prototype.ba=function(){this.B=null;var e,t,r=Date.now();0<=r-this.S?(e=this.i,t=this.A,e.info(function(){return"TIMEOUT: "+t}),2!=this.L&&(Ue(),O(17)),M(this),this.s=2,rt(this)):et(this,this.S-r)};var it=class{constructor(e,t){this.g=e,this.map=t}};function st(e){this.l=e||10,e=D.PerformanceNavigationTiming?0<(e=D.performance.getEntriesByType("navigation")).length&&("hq"==e[0].nextHopProtocol||"h2"==e[0].nextHopProtocol):!!(D.chrome&&D.chrome.loadTimes&&D.chrome.loadTimes()&&D.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 at(e){return e.h||e.g&&e.g.size>=e.j}function ot(e){return e.h?1:e.g?e.g.size:0}function lt(e,t){return e.h?e.h==t:e.g&&e.g.has(t)}function ht(e,t){e.g?e.g.add(t):e.h=t}function ut(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function ct(t){if(null!=t.h)return t.i.concat(t.h.D);if(null==t.g||0===t.g.size)return K(t.i);{let e=t.i;for(var r of t.g.values())e=e.concat(r.D);return e}}function dt(e,t){if(e.forEach&&"function"==typeof e.forEach)e.forEach(t,void 0);else if(q(e)||"string"==typeof e)Array.prototype.forEach.call(e,t,void 0);else for(var r=(e=>{if(e.na&&"function"==typeof e.na)return e.na();if(!e.V||"function"!=typeof e.V){if("undefined"!=typeof Map&&e instanceof Map)return Array.from(e.keys());if(!("undefined"!=typeof Set&&e instanceof Set)){if(q(e)||"string"==typeof e){var t=[];e=e.length;for(var r=0;r<e;r++)t.push(r)}else for(var n in t=[],r=0,e)t[r++]=n;return t}}})(e),n=(e=>{if(e.V&&"function"==typeof e.V)return e.V();if("undefined"!=typeof Map&&e instanceof Map||"undefined"!=typeof Set&&e instanceof Set)return Array.from(e.values());if("string"==typeof e)return e.split("");if(q(e))for(var t=[],r=e.length,n=0;n<r;n++)t.push(e[n]);else for(n in t=[],r=0,e)t[r++]=e[n];return t})(e),i=n.length,s=0;s<i;s++)t.call(void 0,n[s],r&&r[s],e)}st.prototype.cancel=function(){if(this.i=ct(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 pt=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function w(e){var t,r;this.g=this.o=this.j="",this.s=null,this.m=this.l="",this.h=!1,e instanceof w?(this.h=e.h,ft(this,e.j),this.o=e.o,this.g=e.g,gt(this,e.s),this.l=e.l,t=e.i,(r=new St).i=t.i,t.g&&(r.g=new Map(t.g),r.h=t.h),mt(this,r),this.m=e.m):e&&(t=String(e).match(pt))?(this.h=!1,ft(this,t[1]||"",!0),this.o=_t(t[2]||""),this.g=_t(t[3]||"",!0),gt(this,t[4]),this.l=_t(t[5]||"",!0),mt(this,t[6]||"",!0),this.m=_t(t[7]||"")):(this.h=!1,this.i=new St(null,this.h))}function b(e){return new w(e)}function ft(e,t,r){e.j=r?_t(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function gt(e,t){if(t){if(t=Number(t),isNaN(t)||t<0)throw Error("Bad port number "+t);e.s=t}else e.s=null}function mt(e,t,r){var n,i;t instanceof St?(e.i=t,n=e.i,(i=e.h)&&!n.j&&(T(n),n.i=null,n.g.forEach(function(e,t){var r=t.toLowerCase();t!=r&&(At(this,t),Rt(this,r,e))},n)),n.j=i):(r||(t=yt(t,Ct)),e.i=new St(t,e.h))}function I(e,t,r){e.i.set(t,r)}function vt(e){return I(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function _t(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function yt(e,t,r){return"string"==typeof e?(e=encodeURI(e).replace(t,wt),e=r?e.replace(/%25([0-9a-fA-F]{2})/g,"%$1"):e):null}function wt(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}w.prototype.toString=function(){var e=[],t=this.j,r=(t&&e.push(yt(t,It,!0),":"),this.g);return!r&&"file"!=t||(e.push("//"),(t=this.o)&&e.push(yt(t,It,!0),"@"),e.push(encodeURIComponent(String(r)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null==(r=this.s))||e.push(":",String(r)),(r=this.l)&&(this.g&&"/"!=r.charAt(0)&&e.push("/"),e.push(yt(r,"/"==r.charAt(0)?Et:Tt,!0))),(r=this.i.toString())&&e.push("?",r),(r=this.m)&&e.push("#",yt(r,kt)),e.join("")};var bt,It=/[#\/\?@]/g,Tt=/[#\?:]/g,Et=/[#\?]/g,Ct=/[#\?@]/g,kt=/#/g;function St(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function T(r){if(!r.g&&(r.g=new Map,r.h=0,r.i)){var e=r.i,t=function(e,t){r.add(decodeURIComponent(e.replace(/\+/g," ")),t)};if(e){e=e.split("&");for(var n=0;n<e.length;n++){var i,s=e[n].indexOf("="),a=null;0<=s?(i=e[n].substring(0,s),a=e[n].substring(s+1)):i=e[n],t(i,a?decodeURIComponent(a.replace(/\+/g," ")):"")}}}}function At(e,t){T(e),t=E(e,t),e.g.has(t)&&(e.i=null,e.h-=e.g.get(t).length,e.g.delete(t))}function Nt(e,t){return T(e),t=E(e,t),e.g.has(t)}function Rt(e,t,r){At(e,t),0<r.length&&(e.i=null,e.g.set(E(e,t),K(r)),e.h+=r.length)}function E(e,t){return t=String(t),t=e.j?t.toLowerCase():t}function C(e,t,r,n,i){try{i&&(i.onload=null,i.onerror=null,i.onabort=null,i.ontimeout=null),n(r)}catch(e){}}function Pt(){this.g=new Ae}function Dt(e){this.l=e.Ub||null,this.j=e.eb||!1}function xt(e,t){f.call(this),this.D=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.u=new Headers,this.h=null,this.B="GET",this.A="",this.g=!1,this.v=this.j=this.l=null}function Ot(e){e.j.read().then(e.Pa.bind(e)).catch(e.ga.bind(e))}function Lt(e){e.readyState=4,e.l=null,e.j=null,e.v=null,Mt(e)}function Mt(e){e.onreadystatechange&&e.onreadystatechange.call(e)}function Ft(e){let r="";return $(e,function(e,t){r=(r=r+t+":")+e+"\r\n"}),r}function Ut(e,t,r){e:{for(n in r){var n=!1;break e}n=!0}n||(r=Ft(r),"string"==typeof e?null!=r&&encodeURIComponent(String(r)):I(e,t,r))}function k(e){f.call(this),this.headers=new Map,this.o=e||null,this.h=!1,this.v=this.g=null,this.D="",this.m=0,this.l="",this.j=this.B=this.u=this.A=!1,this.I=null,this.H="",this.J=!1}(e=St.prototype).add=function(e,t){T(this),this.i=null,e=E(this,e);var r=this.g.get(e);return r||this.g.set(e,r=[]),r.push(t),this.h+=1,this},e.forEach=function(r,n){T(this),this.g.forEach(function(e,t){e.forEach(function(e){r.call(n,e,t,this)},this)},this)},e.na=function(){T(this);var t=Array.from(this.g.values()),r=Array.from(this.g.keys()),n=[];for(let s=0;s<r.length;s++){var i=t[s];for(let e=0;e<i.length;e++)n.push(r[s])}return n},e.V=function(t){T(this);let r=[];if("string"==typeof t)Nt(this,t)&&(r=r.concat(this.g.get(E(this,t))));else{t=Array.from(this.g.values());for(let e=0;e<t.length;e++)r=r.concat(t[e])}return r},e.set=function(e,t){return T(this),this.i=null,Nt(this,e=E(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=this.V(e)).length?String(e[0]):t},e.toString=function(){if(this.i)return this.i;if(!this.g)return"";for(var e=[],t=Array.from(this.g.keys()),r=0;r<t.length;r++)for(var n=t[r],i=encodeURIComponent(String(n)),s=this.V(n),n=0;n<s.length;n++){var a=i;""!==s[n]&&(a+="="+encodeURIComponent(String(s[n]))),e.push(a)}return this.i=e.join("&")},s(Dt,Ne),Dt.prototype.g=function(){return new xt(this.l,this.j)},Dt.prototype.i=(bt={},function(){return bt}),s(xt,f),(e=xt.prototype).open=function(e,t){if(0!=this.readyState)throw this.abort(),Error("Error reopening a connection");this.B=e,this.A=t,this.readyState=1,Mt(this)},e.send=function(e){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.g=!0;var t={headers:this.u,method:this.B,credentials:this.m,cache:void 0};e&&(t.body=e),(this.D||D).fetch(new Request(this.A,t)).then(this.Sa.bind(this),this.ga.bind(this))},e.abort=function(){this.response=this.responseText="",this.u=new Headers,this.status=0,this.j&&this.j.cancel("Request was aborted.").catch(()=>{}),1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,Lt(this)),this.readyState=0},e.Sa=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,Mt(this)),this.g)&&(this.readyState=3,Mt(this),this.g))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Qa.bind(this),this.ga.bind(this));else if(void 0!==D.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.v=new TextDecoder;Ot(this)}else e.text().then(this.Ra.bind(this),this.ga.bind(this))},e.Pa=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.v.decode(t,{stream:!e.done}))&&(this.response=this.responseText+=t),(e.done?Lt:Mt)(this),3==this.readyState)&&Ot(this)},e.Ra=function(e){this.g&&(this.response=this.responseText=e,Lt(this))},e.Qa=function(e){this.g&&(this.response=e,Lt(this))},e.ga=function(){this.g&&Lt(this)},e.setRequestHeader=function(e,t){this.u.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(xt.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}}),s(k,f);var Vt=/^https?$/i,qt=["POST","PUT"];function jt(e,t){e.h=!1,e.g&&(e.j=!0,e.g.abort(),e.j=!1),e.l=t,e.m=5,Bt(e),Kt(e)}function Bt(e){e.A||(e.A=!0,g(e,"complete"),g(e,"error"))}function zt(e){if(e.h&&void 0!==V&&(!e.v[1]||4!=F(e)||2!=e.Z()))if(e.u&&4==F(e))Ie(e.Ea,0,e);else if(g(e,"readystatechange"),4==F(e)){e.h=!1;try{var t,r,n,i=e.Z();switch(i){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var s=!0;break;default:s=!1}if((t=s)||((r=0===i)&&(!(n=String(e.D).match(pt)[1]||null)&&D.self&&D.self.location&&(n=D.self.location.protocol.slice(0,-1)),r=!Vt.test(n?n.toLowerCase():"")),t=r),t)g(e,"complete"),g(e,"success");else{e.m=6;try{var a=2<F(e)?e.g.statusText:""}catch(e){a=""}e.l=a+" ["+e.Z()+"]",Bt(e)}}finally{Kt(e)}}}function Kt(e,t){if(e.g){Wt(e);var r=e.g,n=e.v[0]?()=>{}:null;e.g=null,e.v=null,t||g(e,"ready");try{r.onreadystatechange=n}catch(e){}}}function Wt(e){e.I&&(D.clearTimeout(e.I),e.I=null)}function F(e){return e.g?e.g.readyState:0}function Ht(e){try{if(e.g){if("response"in e.g)return e.g.response;switch(e.H){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 Gt(e,t,r){return r&&r.internalChannelParams&&r.internalChannelParams[e]||t}function $t(e){this.Aa=0,this.i=[],this.j=new Be,this.ia=this.qa=this.I=this.W=this.g=this.ya=this.D=this.H=this.m=this.S=this.o=null,this.Ya=this.U=0,this.Va=Gt("failFast",!1,e),this.F=this.C=this.u=this.s=this.l=null,this.X=!0,this.za=this.T=-1,this.Y=this.v=this.B=0,this.Ta=Gt("baseRetryDelayMs",5e3,e),this.cb=Gt("retryDelaySeedMs",1e4,e),this.Wa=Gt("forwardChannelMaxRetries",2,e),this.wa=Gt("forwardChannelRequestTimeoutMs",2e4,e),this.pa=e&&e.xmlHttpFactory||void 0,this.Xa=e&&e.Tb||void 0,this.Ca=e&&e.useFetchStreams||!1,this.L=void 0,this.J=e&&e.supportsCrossDomainXhr||!1,this.K="",this.h=new st(e&&e.concurrentRequestLimit),this.Da=new Pt,this.P=e&&e.fastHandshake||!1,this.O=e&&e.encodeInitMessageHeaders||!1,this.P&&this.O&&(this.O=!1),this.Ua=e&&e.Rb||!1,e&&e.xa&&this.j.xa(),e&&e.forceLongPolling&&(this.X=!1),this.ba=!this.P&&this.X&&e&&e.detectBufferingProxy||!1,this.ja=void 0,e&&e.longPollingTimeout&&0<e.longPollingTimeout&&(this.ja=e.longPollingTimeout),this.ca=void 0,this.R=0,this.M=!1,this.ka=this.A=null}function Qt(e){if(Jt(e),3==e.G){var t=e.U++,r=b(e.I);if(I(r,"SID",e.K),I(r,"RID",t),I(r,"TYPE","terminate"),er(e,r),(t=new y(e,e.j,t)).L=2,t.v=vt(b(r)),r=!1,D.navigator&&D.navigator.sendBeacon)try{r=D.navigator.sendBeacon(t.v.toString(),"")}catch(e){}!r&&D.Image&&((new Image).src=t.v,r=!0),r||(t.g=cr(t.j,null),t.g.ea(t.v)),t.F=Date.now(),Ze(t)}hr(e)}function Yt(e){e.g&&(ir(e),e.g.cancel(),e.g=null)}function Jt(e){Yt(e),e.u&&(D.clearTimeout(e.u),e.u=null),ar(e),e.h.cancel(),e.s&&("number"==typeof e.s&&D.clearTimeout(e.s),e.s=null)}function Xt(e){var t;at(e.h)||e.s||(e.s=!0,t=e.Ga,o||te(),l||(o(),l=!0),ee.add(t,e),e.B=0)}function Zt(e,t){var r=t?t.l:e.U++,n=b(e.I);I(n,"SID",e.K),I(n,"RID",r),I(n,"AID",e.T),er(e,n),e.m&&e.o&&Ut(n,e.m,e.o),r=new y(e,e.j,r,e.B+1),null===e.m&&(r.H=e.o),t&&(e.i=t.D.concat(e.i)),t=tr(e,r,1e3),r.I=Math.round(.5*e.wa)+Math.round(.5*e.wa*Math.random()),ht(e.h,r),Ye(r,n,t)}function er(e,r){e.H&&$(e.H,function(e,t){I(r,t,e)}),e.l&&dt({},function(e,t){I(r,t,e)})}function tr(e,t,i){i=Math.min(e.i.length,i);var s=e.l?m(e.l.Na,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{((e,n,t)=>{let i=t||"";try{dt(e,function(e,t){let r=e;h(e)&&(r=ke(e)),n.push(i+t+"="+encodeURIComponent(r))})}catch(e){throw n.push(i+"type="+encodeURIComponent("_badmap")),e}})(l,a,"req"+o+"_")}catch(e){s&&s(l)}}if(e){s=a.join("&");break e}}}return e=e.i.splice(0,i),t.D=e,s}function rr(e){var t;e.g||e.u||(e.Y=1,t=e.Fa,o||te(),l||(o(),l=!0),ee.add(t,e),e.v=0)}function nr(e){return!(e.g||e.u||3<=e.v)&&(e.Y++,e.u=je(m(e.Fa,e),lr(e,e.v)),e.v++,1)}function ir(e){null!=e.A&&(D.clearTimeout(e.A),e.A=null)}function sr(e){e.g=new y(e,e.j,"rpc",e.Y),null===e.m&&(e.g.H=e.o),e.g.O=0;var t=b(e.qa),r=(I(t,"RID","rpc"),I(t,"SID",e.K),I(t,"AID",e.T),I(t,"CI",e.F?"0":"1"),!e.F&&e.ja&&I(t,"TO",e.ja),I(t,"TYPE","xmlhttp"),er(e,t),e.m&&e.o&&Ut(t,e.m,e.o),e.L&&(e.g.I=e.L),e.g);e=e.ia,r.L=1,r.v=vt(b(t)),r.m=null,r.P=!0,Je(r,e)}function ar(e){null!=e.C&&(D.clearTimeout(e.C),e.C=null)}function or(e,t){var r,n,i,s=null;if(e.g==t){ar(e),ir(e),e.g=null;var a=2}else{if(!lt(e.h,t))return;s=t.D,ut(e.h,t),a=1}if(0!=e.G)if(t.o)(1==a?(s=t.m?t.m.length:0,t=Date.now()-t.F,r=e.B,g(a=Me(),new qe(a,s)),Xt):rr)(e);else if(3==(r=t.s)||0==r&&0<t.X||(1!=a||(i=t,ot((n=e).h)>=n.h.j-(n.s?1:0))||(n.s?(n.i=i.D.concat(n.i),0):1==n.G||2==n.G||n.B>=(n.Va?0:n.Wa)||(n.s=je(m(n.Ga,n,i),lr(n,n.B)),n.B++,0)))&&(2!=a||!nr(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 lr(e,t){let r=e.Ta+Math.floor(Math.random()*e.cb);return e.isActive()||(r*=2),r*t}function S(e,t){var r,n,i;e.j.info("Error code "+t),2==t?(r=m(e.fb,e),n=!(i=e.Xa),i=new w(i||"//www.google.com/images/cleardot.gif"),D.location&&"http"==D.location.protocol||ft(i,"https"),vt(i),(n?(t,r)=>{var n=new Be;if(D.Image){let e=new Image;e.onload=z(C,n,"TestLoadImage: loaded",!0,r,e),e.onerror=z(C,n,"TestLoadImage: error",!1,r,e),e.onabort=z(C,n,"TestLoadImage: abort",!1,r,e),e.ontimeout=z(C,n,"TestLoadImage: timeout",!1,r,e),D.setTimeout(function(){e.ontimeout&&e.ontimeout()},1e4),e.src=t}else r(!1)}:(e,t)=>{let r=new Be,n=new AbortController,i=setTimeout(()=>{n.abort(),C(r,0,!1,t)},1e4);fetch(e,{signal:n.signal}).then(e=>{clearTimeout(i),e.ok?C(r,0,!0,t):C(r,0,!1,t)}).catch(()=>{clearTimeout(i),C(r,0,!1,t)})})(i.toString(),r)):O(2),e.G=0,e.l&&e.l.sa(t),hr(e),Jt(e)}function hr(e){var t;e.G=0,e.ka=[],e.l&&(0==(t=ct(e.h)).length&&0==e.i.length||(W(e.ka,t),W(e.ka,e.i),e.h.i.length=0,K(e.i),e.i.length=0),e.l.ra())}function ur(e,t,r){var n,i,s=r instanceof w?b(r):new w(r);return""!=s.g?(t&&(s.g=t+"."+s.g),gt(s,s.s)):(s=(n=D.location).protocol,t=t?t+"."+n.hostname:n.hostname,n=+n.port,i=new w(null),s&&ft(i,s),t&&(i.g=t),n&>(i,n),r&&(i.l=r),s=i),r=e.D,t=e.ya,r&&t&&I(s,r,t),I(s,"VER",e.la),er(e,s),s}function cr(e,t,r){if(t&&!e.J)throw Error("Can't create secondary domain capable XhrIo object.");return(t=e.Ca&&!e.pa?new k(new Dt({eb:r})):new k(e.pa)).Ha(e.J),t}function dr(){}function pr(){}function A(e,t){f.call(this),this.g=new $t(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.va&&(e?e["X-WebChannel-Client-Profile"]=t.va:e={"X-WebChannel-Client-Profile":t.va}),this.g.S=e,(e=t&&t.Sb)&&!x(e)&&(this.g.m=e),this.v=t&&t.supportsCrossDomainXhr||!1,this.u=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!x(t)&&(this.g.D=t,null!==(e=this.h))&&t in e&&t in(e=this.h)&&delete e[t],this.j=new N(this)}function fr(e){xe.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 gr(){Oe.call(this),this.status=1}function N(e){this.g=e}(e=k.prototype).Ha=function(e){this.J=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.m=0,this.A=!1,this.h=!0,this.g=(this.o||Ge).g(),this.v=this.o?Re(this.o):Re(Ge),this.g.onreadystatechange=m(this.Ea,this);try{this.B=!0,this.g.open(t,String(e),!0),this.B=!1}catch(e){return void jt(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=D.FormData&&e instanceof D.FormData,0<=Array.prototype.indexOf.call(qt,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.H&&(this.g.responseType=this.H),"withCredentials"in this.g&&this.g.withCredentials!==this.J&&(this.g.withCredentials=this.J);try{Wt(this),this.u=!0,this.g.send(e),this.u=!1}catch(e){jt(this,e)}},e.abort=function(e){this.g&&this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1,this.m=e||7,g(this,"complete"),g(this,"abort"),Kt(this))},e.N=function(){this.g&&(this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1),Kt(this,!0)),k.aa.N.call(this)},e.Ea=function(){this.s||(this.B||this.u||this.j?zt(this):this.bb())},e.bb=function(){zt(this)},e.isActive=function(){return!!this.g},e.Z=function(){try{return 2<F(this)?this.g.status:-1}catch(e){return-1}},e.oa=function(){try{return this.g?this.g.responseText:""}catch(e){return""}},e.Oa=function(e){var t;if(this.g)return t=this.g.responseText,e&&0==t.indexOf(e)&&(t=t.substring(e.length)),Se(t)},e.Ba=function(){return this.m},e.Ka=function(){return"string"==typeof this.l?this.l:String(this.l)},(e=$t.prototype).la=8,e.G=1,e.connect=function(e,t,r,n){O(0),this.W=e,this.H=t||{},r&&void 0!==n&&(this.H.OSID=r,this.H.OAID=n),this.F=this.X,this.I=ur(this,null,this.W),Xt(this)},e.Ga=function(t){if(this.s)if(this.s=null,1==this.G){if(!t){this.U=Math.floor(1e5*Math.random()),t=this.U++;var r=new y(this,this.j,t);let e=this.o;if(this.S&&(e?J(e=Q(e),this.S):e=this.S),null!==this.m||this.O||(r.H=e,e=null),this.P)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=tr(this,r,n),I(i=b(this.I),"RID",t),I(i,"CVER",22),this.D&&I(i,"X-HTTP-Session-Id",this.D),er(this,i),e&&(this.O?n="headers="+encodeURIComponent(String(Ft(e)))+"&"+n:this.m&&Ut(i,this.m,e)),ht(this.h,r),this.Ua&&I(i,"TYPE","init"),this.P?(I(i,"$req",n),I(i,"SID","null"),r.T=!0,Ye(r,i,null)):Ye(r,i,n),this.G=2}}else 3==this.G&&(t?Zt(this,t):0==this.i.length||at(this.h)||Zt(this))},e.Fa=function(){var e;this.u=null,sr(this),this.ba&&!(this.M||null==this.g||this.R<=0)&&(e=2*this.R,this.j.info("BP detection timer enabled: "+e),this.A=je(m(this.ab,this),e))},e.ab=function(){this.A&&(this.A=null,this.j.info("BP detection timeout reached."),this.j.info("Buffering proxy detected and switch to long-polling!"),this.F=!1,this.M=!0,O(10),Yt(this),sr(this))},e.Za=function(){null!=this.C&&(this.C=null,Yt(this),nr(this),O(19))},e.fb=function(e){e?(this.j.info("Successfully pinged google.com"),O(2)):(this.j.info("Failed to ping google.com"),O(1))},e.isActive=function(){return!!this.l&&this.l.isActive(this)},(e=dr.prototype).ua=function(){},e.ta=function(){},e.sa=function(){},e.ra=function(){},e.isActive=function(){return!0},e.Na=function(){},pr.prototype.g=function(e,t){return new A(e,t)},s(A,f),A.prototype.m=function(){this.g.l=this.j,this.v&&(this.g.J=!0),this.g.connect(this.l,this.h||void 0)},A.prototype.close=function(){Qt(this.g)},A.prototype.o=function(e){var t,r=this.g;"string"==typeof e?((t={}).__data__=e,e=t):this.u&&((t={}).__data__=ke(e),e=t),r.i.push(new it(r.Ya++,e)),3==r.G&&Xt(r)},A.prototype.N=function(){this.g.l=null,delete this.j,Qt(this.g),delete this.g,A.aa.N.call(this)},s(fr,xe),s(gr,Oe),s(N,dr),N.prototype.ua=function(){g(this.g,"a")},N.prototype.ta=function(e){g(this.g,new fr(e))},N.prototype.sa=function(e){g(this.g,new gr)},N.prototype.ra=function(){g(this.g,"b")},pr.prototype.createWebChannel=pr.prototype.g,A.prototype.send=A.prototype.o,A.prototype.open=A.prototype.m,mm=function(){return new pr},gm=Me,fm=_,pm={mb:0,pb:1,qb:2,Jb:3,Ob:4,Lb:5,Mb:6,Kb:7,Ib:8,Nb:9,PROXY:10,NOPROXY:11,Gb:12,Cb:13,Db:14,Bb:15,Eb:16,Fb:17,ib:18,hb:19,jb:20},ze.NO_ERROR=0,ze.TIMEOUT=8,ze.HTTP_ERROR=6,dm=ze,Ke.COMPLETE="complete",cm=Ke,(Pe.EventType=De).OPEN="a",De.CLOSE="b",De.ERROR="c",De.MESSAGE="d",f.prototype.listen=f.prototype.K,um=Pe,k.prototype.listenOnce=k.prototype.L,k.prototype.getLastError=k.prototype.Ka,k.prototype.getLastErrorCode=k.prototype.Ba,k.prototype.getStatus=k.prototype.Z,k.prototype.getResponseJson=k.prototype.Oa,k.prototype.getResponseText=k.prototype.oa,k.prototype.send=k.prototype.ea,k.prototype.setWithCredentials=k.prototype.Ha,hm=k}).apply(void 0!==wm?wm:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});let bm="@firebase/firestore";class Im{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}}Im.UNAUTHENTICATED=new Im(null),Im.GOOGLE_CREDENTIALS=new Im("google-credentials-uid"),Im.FIRST_PARTY=new Im("first-party-uid"),Im.MOCK_USER=new Im("mock-user");let Tm="11.3.0",Em=new $e("@firebase/firestore");function Cm(){return Em.logLevel}function C(e,...t){var r;Em.logLevel<=c.DEBUG&&(r=t.map(Am),Em.debug(`Firestore (${Tm}): `+e,...r))}function km(e,...t){var r;Em.logLevel<=c.ERROR&&(r=t.map(Am),Em.error(`Firestore (${Tm}): `+e,...r))}function Sm(e,...t){var r;Em.logLevel<=c.WARN&&(r=t.map(Am),Em.warn(`Firestore (${Tm}): `+e,...r))}function Am(t){if("string"==typeof t)return t;try{return JSON.stringify(t)}catch(e){return t}}function k(e="Unexpected state"){var t=`FIRESTORE (${Tm}) INTERNAL ASSERTION FAILED: `+e;throw km(t),new Error(t)}function S(e){e||k()}let A={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 N extends de{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: `+this.message}}class Nm{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class Rm{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization","Bearer "+e)}}class Pm{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(Im.UNAUTHENTICATED))}shutdown(){}}class Dm{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 xm{constructor(e){this.t=e,this.currentUser=Im.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(t,r){S(void 0===this.o);let n=this.i,i=e=>this.i!==n?(n=this.i,r(e)):Promise.resolve(),s=new Nm,a=(this.o=()=>{this.i++,this.currentUser=this.u(),s.resolve(),s=new Nm,t.enqueueRetryable(()=>i(this.currentUser))},()=>{let e=s;t.enqueueRetryable(async()=>{await e.promise,await i(this.currentUser)})}),o=e=>{C("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):(C("FirebaseAuthCredentialsProvider","Auth not yet detected"),s.resolve(),s=new Nm))},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?(C("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):e?(S("string"==typeof e.accessToken),new Rm(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),new Im(e)}}class Om{constructor(e,t,r){this.l=e,this.h=t,this.P=r,this.type="FirstParty",this.user=Im.FIRST_PARTY,this.T=new Map}I(){return this.P?this.P():null}get headers(){this.T.set("X-Goog-AuthUser",this.l);var e=this.I();return e&&this.T.set("Authorization",e),this.h&&this.T.set("X-Goog-Iam-Authorization-Token",this.h),this.T}}class Lm{constructor(e,t,r){this.l=e,this.h=t,this.P=r}getToken(){return Promise.resolve(new Om(this.l,this.h,this.P))}start(e,t){e.enqueueRetryable(()=>t(Im.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class Mm{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 Fm{constructor(e,t){this.A=t,this.forceRefresh=!1,this.appCheck=null,this.R=null,this.V=null,h(e)&&e.settings.appCheckToken&&(this.V=e.settings.appCheckToken)}start(t,r){S(void 0===this.o);let n=e=>{null!=e.error&&C("FirebaseAppCheckTokenProvider","Error getting App Check token; using placeholder token instead. Error: "+e.error.message);var t=e.token!==this.R;return this.R=e.token,C("FirebaseAppCheckTokenProvider",`Received ${t?"new":"existing"} token.`),t?r(e.token):Promise.resolve()},i=(this.o=e=>{t.enqueueRetryable(()=>n(e))},e=>{C("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.o&&this.appCheck.addTokenListener(this.o)});this.A.onInit(e=>i(e)),setTimeout(()=>{var e;this.appCheck||((e=this.A.getImmediate({optional:!0}))?i(e):C("FirebaseAppCheckTokenProvider","AppCheck not yet detected"))},0)}getToken(){var e;return this.V?Promise.resolve(new Mm(this.V)):(e=this.forceRefresh,this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>e?(S("string"==typeof e.token),this.R=e.token,new Mm(e.token)):null):Promise.resolve(null))}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.o&&this.appCheck.removeTokenListener(this.o),this.o=void 0}}function Um(){return new TextEncoder}class Vm{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 R(e,t){return e<t?-1:t<e?1:0}function qm(e,t){var r=Um().encode(e),n=Um().encode(t);for(let i=0;i<Math.min(r.length,n.length);i++){let e=R(r[i],n[i]);if(0!==e)return e}return R(r.length,n.length)}function jm(e,r,n){return e.length===r.length&&e.every((e,t)=>n(e,r[t]))}function Bm(e){return e+"\0"}let zm=-62135596800;class Km{static now(){return Km.fromMillis(Date.now())}static fromDate(e){return Km.fromMillis(e.getTime())}static fromMillis(e){var t=Math.floor(e/1e3),r=Math.floor(1e6*(e-1e3*t));return new Km(t,r)}constructor(e,t){if(this.seconds=e,(this.nanoseconds=t)<0)throw new N(A.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(1e9<=t)throw new N(A.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<zm)throw new N(A.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(253402300800<=e)throw new N(A.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?R(this.nanoseconds,e.nanoseconds):R(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{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){var e=this.seconds-zm;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}class P{static fromTimestamp(e){return new P(e)}static min(){return new P(new Km(0,0))}static max(){return new P(new Km(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 Wm="__name__";class Hm{constructor(e,t,r){void 0===t?t=0:t>e.length&&k(),void 0===r?r=e.length-t:r>e.length-t&&k(),this.segments=e,this.offset=t,this.len=r}get length(){return this.len}isEqual(e){return 0===Hm.comparator(this,e)}child(e){let t=this.segments.slice(this.offset,this.limit());return e instanceof Hm?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=Hm.compareSegments(t.get(n),r.get(n));if(0!==e)return e}return R(t.length,r.length)}static compareSegments(e,t){var r=Hm.isNumericId(e),n=Hm.isNumericId(t);return r&&!n?-1:!r&&n?1:r&&n?Hm.extractNumericId(e).compare(Hm.extractNumericId(t)):qm(e,t)}static isNumericId(e){return e.startsWith("__id")&&e.endsWith("__")}static extractNumericId(e){return om.fromString(e.substring(4,e.length-2))}}class D extends Hm{construct(e,t,r){return new D(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 N(A.INVALID_ARGUMENT,`Invalid segment (${t}). Paths must not contain // in them.`);r.push(...t.split("/").filter(e=>0<e.length))}return new D(r)}static emptyPath(){return new D([])}}let Gm=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class $m extends Hm{construct(e,t,r){return new $m(e,t,r)}static isValidIdentifier(e){return Gm.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),e=$m.isValidIdentifier(e)?e:"`"+e+"`")).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&this.get(0)===Wm}static keyField(){return new $m([Wm])}static fromServerFormat(t){let e=[],r="",n=0;var i=()=>{if(0===r.length)throw new N(A.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 N(A.INVALID_ARGUMENT,"Path has trailing escape character: "+t);let e=t[n+1];if("\\"!==e&&"."!==e&&"`"!==e)throw new N(A.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 N(A.INVALID_ARGUMENT,"Unterminated ` in path: "+t);return new $m(e)}static emptyPath(){return new $m([])}}class x{constructor(e){this.path=e}static fromPath(e){return new x(D.fromString(e))}static fromName(e){return new x(D.fromString(e).popFirst(5))}static empty(){return new x(D.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===D.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return D.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new x(new D(e.slice()))}}let Qm=-1;class Ym{constructor(e,t,r,n){this.indexId=e,this.collectionGroup=t,this.fields=r,this.indexState=n}}function Jm(e){return e.fields.find(e=>2===e.kind)}function Xm(e){return e.fields.filter(e=>2!==e.kind)}Ym.UNKNOWN_ID=-1;class Zm{constructor(e,t){this.fieldPath=e,this.kind=t}}class ev{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new ev(0,nv.min())}}function tv(e,t){var r=e.toTimestamp().seconds,n=e.toTimestamp().nanoseconds+1,r=P.fromTimestamp(1e9===n?new Km(r+1,0):new Km(r,n));return new nv(r,x.empty(),t)}function rv(e){return new nv(e.readTime,e.key,Qm)}class nv{constructor(e,t,r){this.readTime=e,this.documentKey=t,this.largestBatchId=r}static min(){return new nv(P.min(),x.empty(),Qm)}static max(){return new nv(P.max(),x.empty(),Qm)}}function iv(e,t){var r=e.readTime.compareTo(t.readTime);return 0!==r||0!==(r=x.comparator(e.documentKey,t.documentKey))?r:R(e.largestBatchId,t.largestBatchId)}let sv="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class av{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}async function ov(e){if(e.code!==A.FAILED_PRECONDITION||e.message!==sv)throw e;C("LocalStore","Unexpectedly lost primary lease")}class O{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&&k(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(i,this.error):this.wrapSuccess(n,this.result):new O((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 O?t:O.resolve(t)}catch(e){return O.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):O.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):O.reject(t)}static resolve(r){return new O((e,t)=>{e(r)})}static reject(r){return new O((e,t)=>{t(r)})}static waitFor(e){return new O((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=O.resolve(!1);for(let r of e)t=t.next(e=>e?O.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 O((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 O((e,t)=>{let r=()=>{!0===n()?i().next(()=>{r()},t):e()};r()})}}let lv="SimpleDb";class hv{static open(e,t,r,n){try{return new hv(t,e.transaction(n,r))}catch(e){throw new pv(t,e)}}constructor(r,e){this.action=r,this.transaction=e,this.aborted=!1,this.m=new Nm,this.transaction.oncomplete=()=>{this.m.resolve()},this.transaction.onabort=()=>{e.error?this.m.reject(new pv(r,e.error)):this.m.resolve()},this.transaction.onerror=e=>{var t=_v(e.target.error);this.m.reject(new pv(r,t))}}get p(){return this.m.promise}abort(e){e&&this.m.reject(e),this.aborted||(C(lv,"Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}S(){var e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}store(e){var t=this.transaction.objectStore(e);return new gv(t)}}class uv{static delete(e){return C(lv,"Removing database:",e),mv(window.indexedDB.deleteDatabase(e)).toPromise()}static D(){var e,t,r;return!(!he()||!uv.v()&&(e=ee(),t=0<(t=uv.C(e))&&t<10,r=0<(r=cv(e))&&r<4.5,0<e.indexOf("MSIE ")||0<e.indexOf("Trident/")||0<e.indexOf("Edge/")||t||r))}static v(){var e;return"undefined"!=typeof process&&"YES"===(null==(e=process.__PRIVATE_env)?void 0:e.F)}static M(e,t){return e.store(t)}static C(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.O=r,12.2===uv.C(ee())&&km("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 N(s){return this.db||(C(lv,"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 pv(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 N(A.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 N(A.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 pv(s,t))},i.onupgradeneeded=e=>{C(lv,'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);var t=e.target.result;this.O.B(t,i.transaction,e.oldVersion,this.version).next(()=>{C(lv,"Database upgrade to version "+this.version+" complete")})}})),this.L&&(this.db.onversionchange=e=>this.L(e)),this.db}k(t){this.L=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.N(r);let t=hv.open(this.db,r,s?"readonly":"readwrite",n),e=i(t).next(e=>(t.S(),e)).catch(e=>(t.abort(e),O.reject(e))).toPromise();return e.catch(()=>{}),await t.p,e}catch(r){let e=r,t="FirebaseError"!==e.name&&a<3;if(C(lv,"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 cv(e){var t=e.match(/Android ([\d.]+)/i),t=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(t)}class dv{constructor(e){this.q=e,this.$=!1,this.U=null}get isDone(){return this.$}get K(){return this.U}set cursor(e){this.q=e}done(){this.$=!0}W(e){this.U=e}delete(){return mv(this.q.delete())}}class pv extends N{constructor(e,t){super(A.UNAVAILABLE,`IndexedDB transaction '${e}' failed: `+t),this.name="IndexedDbTransactionError"}}function fv(e){return"IndexedDbTransactionError"===e.name}class gv{constructor(e){this.store=e}put(e,t){let r;return mv(r=void 0!==t?(C(lv,"PUT",this.store.name,e,t),this.store.put(t,e)):(C(lv,"PUT",this.store.name,"<auto-key>",e),this.store.put(e)))}add(e){return C(lv,"ADD",this.store.name,e,e),mv(this.store.add(e))}get(t){return mv(this.store.get(t)).next(e=>(void 0===e&&(e=null),C(lv,"GET",this.store.name,t,e),e))}delete(e){return C(lv,"DELETE",this.store.name,e),mv(this.store.delete(e))}count(){return C(lv,"COUNT",this.store.name),mv(this.store.count())}G(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 O((t,r)=>{e.onerror=e=>{r(e.target.error)},e.onsuccess=e=>{t(e.target.result)}})}{let e=this.cursor(n),r=[];return this.j(e,(e,t)=>{r.push(t)}).next(()=>r)}}H(e,t){let n=this.store.getAll(e,null===t?void 0:t);return new O((t,r)=>{n.onerror=e=>{r(e.target.error)},n.onsuccess=e=>{t(e.target.result)}})}J(e,t){C(lv,"DELETE ALL",this.store.name);var r=this.options(e,t),r=(r.Y=!1,this.cursor(r));return this.j(r,(e,t,r)=>r.delete())}Z(e,t){let r;t?r=e:(r={},t=e);var n=this.cursor(r);return this.j(n,t)}X(i){let e=this.cursor({});return new O((r,n)=>{e.onerror=e=>{var t=_v(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()}})}j(e,s){let a=[];return new O((i,t)=>{e.onerror=e=>{t(e.target.error)},e.onsuccess=e=>{var n=e.target.result;if(n){let t=new dv(n),r=s(n.primaryKey,n.value,t);if(r instanceof O){let e=r.catch(e=>(t.done(),O.reject(e)));a.push(e)}t.isDone?i():null===t.K?n.continue():n.continue(t.K)}else i()}}).next(()=>O.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 mv(e){return new O((r,n)=>{e.onsuccess=e=>{var t=e.target.result;r(t)},e.onerror=e=>{var t=_v(e.target.error);n(t)}})}let vv=!1;function _v(e){let t=uv.C(ee());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 N("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 vv||(vv=!0,setTimeout(()=>{throw e},0)),e}}return e}let yv="IndexBackfiller";class wv{constructor(e,t){this.asyncQueue=e,this.ee=t,this.task=null}start(){this.te(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return null!==this.task}te(e){C(yv,`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,async()=>{this.task=null;try{var e=await this.ee.ne();C(yv,"Documents written: "+e)}catch(e){fv(e)?C(yv,"Ignoring IndexedDB error during index backfill: ",e):await ov(e)}await this.te(6e4)})}}class bv{constructor(e,t){this.localStore=e,this.persistence=t}async ne(t=50){return this.persistence.runTransaction("Backfill Indexes","readwrite-primary",e=>this.re(e,t))}re(e,t){let r=new Set,n=t,i=!0;return O.doWhile(()=>!0===i&&0<n,()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next(t=>{if(null!==t&&!r.has(t))return C(yv,"Processing collection: "+t),this.ie(e,t,n).next(e=>{n-=e,r.add(t)});i=!1})).next(()=>t-n)}ie(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.se(r,e)).next(e=>(C(yv,"Updating offset: "+e),this.localStore.indexManager.updateCollectionGroup(n,i,e))).next(()=>t.size)}))}se(e,t){let n=e;return t.changes.forEach((e,t)=>{var r=rv(t);0<iv(r,n)&&(n=r)}),new nv(n.readTime,n.documentKey,Math.max(t.batchId,e.largestBatchId))}}class Iv{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.oe(e),this._e=e=>t.writeSequenceNumber(e))}oe(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){var e=++this.previousValue;return this._e&&this._e(e),e}}let Tv=Iv.ae=-1;function Ev(e){return null==e}function Cv(e){return 0===e&&1/e==-1/0}function kv(e){return"number"==typeof e&&Number.isInteger(e)&&!Cv(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}let Sv="";function Av(e){let t="";for(let r=0;r<e.length;r++)0<t.length&&(t=Nv(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 Sv:r+="";break;default:r+=e}}return r})(e.get(r),t);return Nv(t)}function Nv(e){return e+Sv+""}function Rv(r){let e=r.length;if(S(2<=e),2===e)return S(r.charAt(0)===Sv&&""===r.charAt(1)),D.emptyPath();var __PRIVATE_lastReasonableEscapeIndex=e-2,n=[];let i="";for(let a=0;a<e;){let t=r.indexOf(Sv,a);switch((t<0||t>__PRIVATE_lastReasonableEscapeIndex)&&k(),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:k()}a=t+2}return new D(n)}let Pv="remoteDocuments",Dv="owner",xv="owner",Ov="mutationQueues",Lv="mutations",Mv="batchId",Fv="userMutationsIndex",Uv=["userId","batchId"];function Vv(e,t){return[e,Av(t)]}function qv(e,t,r){return[e,Av(t),r]}let jv={},Bv="documentMutations",zv="remoteDocumentsV14",Kv=["prefixPath","collectionGroup","readTime","documentId"],Wv="documentKeyIndex",Hv=["prefixPath","collectionGroup","documentId"],Gv="collectionGroupIndex",$v=["collectionGroup","readTime","prefixPath","documentId"],Qv="remoteDocumentGlobal",Yv="remoteDocumentGlobalKey",Jv="targets",Xv="queryTargetsIndex",Zv=["canonicalId","targetId"],e_="targetDocuments",t_=["targetId","path"],r_="documentTargetsIndex",n_=["path","targetId"],i_="targetGlobalKey",s_="targetGlobal",a_="collectionParents",o_=["collectionId","parent"],l_="clientMetadata",h_="bundles",u_="namedQueries",c_="indexConfiguration",d_="collectionGroupIndex",p_="indexState",f_=["indexId","uid"],g_="sequenceNumberIndex",m_=["uid","sequenceNumber"],v_="indexEntries",__=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],y_="documentKeyIndex",w_=["indexId","uid","orderedDocumentKey"],b_="documentOverlays",I_=["userId","collectionPath","documentId"],T_="collectionPathOverlayIndex",E_=["userId","collectionPath","largestBatchId"],C_="collectionGroupOverlayIndex",k_=["userId","collectionGroup","largestBatchId"],S_="globals",A_=[Ov,Lv,Bv,Pv,Jv,Dv,s_,e_,l_,Qv,a_,h_,u_],N_=[...A_,b_],R_=[Ov,Lv,Bv,zv,Jv,Dv,s_,e_,l_,Qv,a_,h_,u_,b_],P_=R_,D_=[...P_,c_,p_,v_],x_=D_,O_=[...D_,S_];class L_ extends av{constructor(e,t){super(),this.ue=e,this.currentSequenceNumber=t}}function M_(e,t){var r=e;return uv.M(r.ue,t)}function F_(e){let t=0;for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}function U_(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t(r,e[r])}function V_(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class L{constructor(e,t){this.comparator=e,this.root=t||j_.EMPTY}insert(e,t){return new L(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,j_.BLACK,null,null))}remove(e){return new L(this.comparator,this.root.remove(e,this.comparator).copy(null,null,j_.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 q_(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new q_(this.root,e,this.comparator,!1)}getReverseIterator(){return new q_(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new q_(this.root,e,this.comparator,!0)}}class q_{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 j_{constructor(e,t,r,n,i){this.key=e,this.value=t,this.color=null!=r?r:j_.RED,this.left=null!=n?n:j_.EMPTY,this.right=null!=i?i:j_.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,r,n,i){return new j_(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 j_.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 j_.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,j_.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){var e=this.copy(null,null,j_.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 k();if(this.right.isRed())throw k();var e=this.left.check();if(e!==this.right.check())throw k();return e+(this.isRed()?0:1)}}j_.EMPTY=null,j_.RED=!0,j_.BLACK=!1,j_.EMPTY=new class{constructor(){this.size=0}get key(){throw k()}get value(){throw k()}get color(){throw k()}get left(){throw k()}get right(){throw k()}copy(e,t,r,n,i){return this}insert(e,t,r){return new j_(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 M{constructor(e){this.comparator=e,this.data=new L(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 B_(this.data.getIterator())}getIteratorFrom(e){return new B_(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 M))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 M(this.comparator);return t.data=e,t}}class B_{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function z_(e){return e.hasNext()?e.getNext():void 0}class K_{constructor(e){(this.fields=e).sort($m.comparator)}static empty(){return new K_([])}unionWith(e){let t=new M($m.comparator);for(let e of this.fields)t=t.add(e);for(var r of e)t=t.add(r);return new K_(t.toArray())}covers(e){for(var t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return jm(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class W_ extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class H_{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 W_("Invalid base64 string: "+e):e}})(e);return new H_(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 H_(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 R(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}H_.EMPTY_BYTE_STRING=new H_("");let G_=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function $_(t){if(S(!!t),"string"!=typeof t)return{seconds:Q_(t.seconds),nanos:Q_(t.nanos)};{let e=0;var r=G_.exec(t),r=(S(!!r),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 Q_(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function Y_(e){return"string"==typeof e?H_.fromBase64String(e):H_.fromUint8Array(e)}let J_="server_timestamp",X_="__type__",Z_="__previous_value__",ey="__local_write_time__";function ty(e){var t;return(null==(t=((null==(t=null==e?void 0:e.mapValue)?void 0:t.fields)||{})[X_])?void 0:t.stringValue)===J_}function ry(e){var t=e.mapValue.fields[Z_];return ty(t)?ry(t):t}function ny(e){var t=$_(e.mapValue.fields[ey].timestampValue);return new Km(t.seconds,t.nanos)}class iy{constructor(e,t,r,n,i,s,a,o,l){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}}let sy="(default)";class ay{constructor(e,t){this.projectId=e,this.database=t||sy}static empty(){return new ay("","")}get isDefaultDatabase(){return this.database===sy}isEqual(e){return e instanceof ay&&e.projectId===this.projectId&&e.database===this.database}}let oy="__type__",ly="__max__",hy={mapValue:{fields:{__type__:{stringValue:ly}}}},uy="__vector__",cy="value",dy={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?ty(e)?4:Ay(e)?9007199254740991:ky(e)?10:11:k()}function fy(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 ny(t).isEqual(ny(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=$_(i.timestampValue),o=$_(s.timestampValue),a.seconds===o.seconds&&a.nanos===o.nanos);case 5:return t.stringValue===r.stringValue;case 6:return i=r,Y_(t.bytesValue).isEqual(Y_(i.bytesValue));case 7:return t.referenceValue===r.referenceValue;case 8:return s=r,Q_((n=t).geoPointValue.latitude)===Q_(s.geoPointValue.latitude)&&Q_(n.geoPointValue.longitude)===Q_(s.geoPointValue.longitude);case 2:return n=r,"integerValue"in(h=t)&&"integerValue"in n?Q_(h.integerValue)===Q_(n.integerValue):"doubleValue"in h&&"doubleValue"in n&&((a=Q_(h.doubleValue))===(o=Q_(n.doubleValue))?Cv(a)===Cv(o):isNaN(a)&&isNaN(o));case 9:return jm(t.arrayValue.values||[],r.arrayValue.values||[],fy);case 10:case 11:var l=t,h=r,u=l.mapValue.fields||{},c=h.mapValue.fields||{};if(F_(u)!==F_(c))return!1;for(let e in u)if(u.hasOwnProperty(e)&&(void 0===c[e]||!fy(u[e],c[e])))return!1;return!0;default:return k()}}function gy(e,t){return void 0!==(e.values||[]).find(e=>fy(e,t))}function my(e,n){if(e===n)return 0;var i,s,a,o,l,h,u,c,t=py(e),r=py(n);if(t!==r)return R(t,r);switch(t){case 0:case 9007199254740991:return 0;case 1:return R(e.booleanValue,n.booleanValue);case 2:return h=n,u=Q_((l=e).integerValue||l.doubleValue),c=Q_(h.integerValue||h.doubleValue),u<c?-1:c<u?1:u===c?0:isNaN(u)?isNaN(c)?0:-1:1;case 3:return vy(e.timestampValue,n.timestampValue);case 4:return vy(ny(e),ny(n));case 5:return qm(e.stringValue,n.stringValue);case 6:return l=e.bytesValue,h=n.bytesValue,u=Y_(l),c=Y_(h),u.compareTo(c);case 7:var d=e.referenceValue,p=n.referenceValue,f=d.split("/"),g=p.split("/");for(let t=0;t<f.length&&t<g.length;t++){let e=R(f[t],g[t]);if(0!==e)return e}return R(f.length,g.length);case 8:return d=e.geoPointValue,p=n.geoPointValue,0!==(o=R(Q_(d.latitude),Q_(p.latitude)))?o:R(Q_(d.longitude),Q_(p.longitude));case 9:return _y(e.arrayValue,n.arrayValue);case 10:return m=e.mapValue,i=n.mapValue,o=m.fields||{},s=i.fields||{},o=null==(o=o[cy])?void 0:o.arrayValue,s=null==(s=s[cy])?void 0:s.arrayValue,0!==(a=R((null==(a=null==o?void 0:o.values)?void 0:a.length)||0,(null==(a=null==s?void 0:s.values)?void 0:a.length)||0))?a:_y(o,s);case 11:var m=e.mapValue,v=n.mapValue;if(m===hy.mapValue&&v===hy.mapValue)return 0;if(m===hy.mapValue)return 1;if(v===hy.mapValue)return-1;var _=m.fields||{},y=Object.keys(_),w=v.fields||{},b=Object.keys(w);y.sort(),b.sort();for(let r=0;r<y.length&&r<b.length;++r){let e=qm(y[r],b[r]);if(0!==e)return e;var I=my(_[y[r]],w[b[r]]);if(0!==I)return I}return R(y.length,b.length);default:throw k()}}function vy(e,t){var r,n,i;return"string"==typeof e&&"string"==typeof t&&e.length===t.length?R(e,t):(r=$_(e),n=$_(t),0!==(i=R(r.seconds,n.seconds))?i:R(r.nanos,n.nanos))}function _y(e,t){var r=e.values||[],n=t.values||[];for(let i=0;i<r.length&&i<n.length;++i){let e=my(r[i],n[i]);if(e)return e}return R(r.length,n.length)}function yy(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=$_(e);return`time(${t.seconds},${t.nanos})`})(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?(e=>Y_(e).toBase64())(e.bytesValue):"referenceValue"in e?(e=>x.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):k()}(e)}function wy(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/`+t.path.canonicalString()}}function by(e){return!!e&&"integerValue"in e}function Iy(e){return!!e&&"arrayValue"in e}function Ty(e){return e&&"nullValue"in e}function Ey(e){return e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function Cy(e){return e&&"mapValue"in e}function ky(e){var t;return(null==(t=((null==(t=null==e?void 0:e.mapValue)?void 0:t.fields)||{})[oy])?void 0:t.stringValue)===uy}function Sy(t){if(t.geoPointValue)return{geoPointValue:Object.assign({},t.geoPointValue)};if(t.timestampValue&&"object"==typeof t.timestampValue)return{timestampValue:Object.assign({},t.timestampValue)};if(t.mapValue){let r={mapValue:{fields:{}}};return U_(t.mapValue.fields,(e,t)=>r.mapValue.fields[e]=Sy(t)),r}if(t.arrayValue){var r={arrayValue:{values:[]}};for(let e=0;e<(t.arrayValue.values||[]).length;++e)r.arrayValue.values[e]=Sy(t.arrayValue.values[e]);return r}return Object.assign({},t)}function Ay(e){return(((e.mapValue||{}).fields||{}).__type__||{}).stringValue===ly}let Ny={mapValue:{fields:{[oy]:{stringValue:uy},[cy]:{arrayValue:{}}}}};function Ry(e,t){var r=my(e.value,t.value);return 0!==r?r:e.inclusive&&!t.inclusive?-1:!e.inclusive&&t.inclusive?1:0}function Py(e,t){var r=my(e.value,t.value);return 0!==r?r:e.inclusive&&!t.inclusive?1:!e.inclusive&&t.inclusive?-1:0}class Dy{constructor(e){this.value=e}static empty(){return new Dy({mapValue:{}})}field(r){if(r.isEmpty())return this.value;{let e=this.value;for(let t=0;t<r.length-1;++t)if(!Cy(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()]=Sy(t)}setAll(e){let r=$m.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()]=Sy(e):i.push(t.lastSegment())});var t=this.getFieldsMap(r);this.applyChanges(t,n,i)}delete(e){var t=this.field(e.popLast());Cy(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return fy(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)];Cy(e)&&e.mapValue.fields||(e={mapValue:{fields:{}}},r.mapValue.fields[t.get(n)]=e),r=e}return r.mapValue.fields}applyChanges(r,e,t){U_(e,(e,t)=>r[e]=t);for(let e of t)delete r[e]}clone(){return new Dy(Sy(this.value))}}class xy{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 xy(e,0,P.min(),P.min(),P.min(),Dy.empty(),0)}static newFoundDocument(e,t,r,n){return new xy(e,1,t,P.min(),r,n,0)}static newNoDocument(e,t){return new xy(e,2,t,P.min(),P.min(),Dy.empty(),0)}static newUnknownDocument(e,t){return new xy(e,3,t,P.min(),P.min(),Dy.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(P.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=Dy.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=Dy.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=P.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 xy&&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 xy(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 Oy{constructor(e,t){this.position=e,this.inclusive=t}}function Ly(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()?x.comparator(x.fromName(s.referenceValue),r.key):my(s,r.data.field(i.field)),"desc"===i.dir&&(n*=-1),0!==n)break}return n}function My(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(!fy(e.position[r],t.position[r]))return!1;return!0}class Fy{constructor(e,t="asc"){this.field=e,this.dir=t}}class Uy{}class F extends Uy{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 Wy(e,t,r):"array-contains"===t?new Qy(e,r):"in"===t?new Yy(e,r):"not-in"===t?new Jy(e,r):"array-contains-any"===t?new Xy(e,r):new F(e,t,r)}static createKeyFieldInFilter(e,t,r){return new("in"===t?Hy:Gy)(e,r)}matches(e){var t=e.data.field(this.field);return"!="===this.op?null!==t&&this.matchesComparison(my(t,this.value)):null!==t&&py(this.value)===py(t)&&this.matchesComparison(my(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 k()}}isInequality(){return 0<=["<","<=",">",">=","!=","not-in"].indexOf(this.op)}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class U extends Uy{constructor(e,t){super(),this.filters=e,this.op=t,this.ce=null}static create(e,t){return new U(e,t)}matches(t){return Vy(this)?void 0===this.filters.find(e=>!e.matches(t)):void 0!==this.filters.find(e=>e.matches(t))}getFlattenedFilters(){return null===this.ce&&(this.ce=this.filters.reduce((e,t)=>e.concat(t.getFlattenedFilters()),[])),this.ce}getFilters(){return Object.assign([],this.filters)}}function Vy(e){return"and"===e.op}function qy(e){return"or"===e.op}function jy(e){return By(e)&&Vy(e)}function By(e){for(var t of e.filters)if(t instanceof U)return!1;return!0}function zy(e,t){var r=e.filters.concat(t);return U.create(r,e.op)}function Ky(e){return e instanceof F?`${(t=e).field.canonicalString()} ${t.op} `+yy(t.value):e instanceof U?(t=e).op.toString()+" {"+t.getFilters().map(Ky).join(" ,")+"}":"Filter";var t}class Wy extends F{constructor(e,t,r){super(e,t,r),this.key=x.fromName(r.referenceValue)}matches(e){var t=x.comparator(e.key,this.key);return this.matchesComparison(t)}}class Hy extends F{constructor(e,t){super(e,"in",t),this.keys=$y(0,t)}matches(t){return this.keys.some(e=>e.isEqual(t.key))}}class Gy extends F{constructor(e,t){super(e,"not-in",t),this.keys=$y(0,t)}matches(t){return!this.keys.some(e=>e.isEqual(t.key))}}function $y(e,t){var r;return((null==(r=t.arrayValue)?void 0:r.values)||[]).map(e=>x.fromName(e.referenceValue))}class Qy extends F{constructor(e,t){super(e,"array-contains",t)}matches(e){var t=e.data.field(this.field);return Iy(t)&&gy(t.arrayValue,this.value)}}class Yy extends F{constructor(e,t){super(e,"in",t)}matches(e){var t=e.data.field(this.field);return null!==t&&gy(this.value.arrayValue,t)}}class Jy extends F{constructor(e,t){super(e,"not-in",t)}matches(e){var t;return!gy(this.value.arrayValue,{nullValue:"NULL_VALUE"})&&null!==(t=e.data.field(this.field))&&!gy(this.value.arrayValue,t)}}class Xy extends F{constructor(e,t){super(e,"array-contains-any",t)}matches(e){var t=e.data.field(this.field);return!(!Iy(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>gy(this.value.arrayValue,e))}}class Zy{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.le=null}}function ew(e,t=null,r=[],n=[],i=null,s=null,a=null){return new Zy(e,t,r,n,i,s,a)}function tw(e){var t=e;if(null===t.le){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()+yy(e.value):jy(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(","),Ev(t.limit)||(e=(e+="|l:")+t.limit),t.startAt&&(e=(e=(e+="|lb:")+(t.startAt.inclusive?"b:":"a:"))+t.startAt.position.map(e=>yy(e)).join(",")),t.endAt&&(e=(e=(e+="|ub:")+(t.endAt.inclusive?"a:":"b:"))+t.endAt.position.map(e=>yy(e)).join(",")),t.le=e}return t.le}function rw(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)&&fy(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 k();var i,r,s}(e.filters[s],t.filters[s]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!My(e.startAt,t.startAt)&&My(e.endAt,t.endAt)}function nw(e){return x.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 sw(e,r,n){let i=dy,s=!0;for(let n of iw(e,r)){let e=dy,t=!0;switch(n.op){case"<":case"<=":e="nullValue"in(a=n.value)?dy:"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?wy(ay.empty(),x.empty()):"geoPointValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in a?{arrayValue:{}}:"mapValue"in a?ky(a)?Ny:{mapValue:{}}:k();break;case"==":case"in":case">=":e=n.value;break;case">":e=n.value,t=!1;break;case"!=":case"not-in":e=dy}Ry({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];Ry({value:i,inclusive:s},{value:e,inclusive:n.inclusive})<0&&(i=e,s=n.inclusive);break}return{value:i,inclusive:s}}function aw(e,r,n){let i=hy,s=!0;for(let n of iw(e,r)){let e=hy,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?wy(ay.empty(),x.empty()):"referenceValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in a?{arrayValue:{}}:"arrayValue"in a?Ny:"mapValue"in a?ky(a)?{mapValue:{}}:hy:k(),t=!1;break;case"==":case"in":case"<=":e=n.value;break;case"<":e=n.value,t=!1;break;case"!=":case"not-in":e=hy}0<Py({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<Py({value:i,inclusive:s},{value:e,inclusive:n.inclusive})&&(i=e,s=n.inclusive);break}return{value:i,inclusive:s}}class ow{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.he=null,this.Pe=null,this.Te=null,this.startAt,this.endAt}}function lw(e,t,r,n,i,s,a,o){return new ow(e,t,r,n,i,s,a,o)}function hw(e){return new ow(e)}function uw(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 cw(e){return null!==e.collectionGroup}function dw(e){let n=e;if(null===n.he){n.he=[];let t=new Set;for(var i of n.explicitOrderBy)n.he.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 M($m.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.he.push(new Fy(e,r))}),t.has($m.keyField().canonicalString())||n.he.push(new Fy($m.keyField(),r))}return n.he}function pw(e){var t=e;return t.Pe||(t.Pe=((e,t)=>{if("F"===e.limitType)return ew(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 Fy(e.field,t)});var r=e.endAt?new Oy(e.endAt.position,e.endAt.inclusive):null,n=e.startAt?new Oy(e.startAt.position,e.startAt.inclusive):null;return ew(e.path,e.collectionGroup,t,e.filters,e.limit,r,n)})(t,dw(e))),t.Pe}function fw(e,t){var r=e.filters.concat([t]);return new ow(e.path,e.collectionGroup,e.explicitOrderBy.slice(),r,e.limit,e.limitType,e.startAt,e.endAt)}function gw(e,t,r){return new ow(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,r,e.startAt,e.endAt)}function mw(e,t){return rw(pw(e),pw(t))&&e.limitType===t.limitType}function vw(e){return tw(pw(e))+"|lt:"+e.limitType}function _w(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=>Ky(e)).join(", ")}]`),Ev(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=>yy(e)).join(",")),`Target(${t=e.endAt?(t=(t+=", endAt: ")+(e.endAt.inclusive?"a:":"b:"))+e.endAt.position.map(e=>yy(e)).join(","):t})`})(pw(e))}; limitType=${e.limitType})`}function yw(e,t){return t.isFoundDocument()&&(s=e,o=(a=t).key.path,null!==s.collectionGroup?a.key.hasCollectionId(s.collectionGroup)&&s.path.isPrefixOf(o):x.isDocumentKey(s.path)?s.path.isEqual(o):s.path.isImmediateParentOf(o))&&((e,t)=>{for(var r of dw(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=dw(s),i=Ly(n,r,a),n.inclusive?i<=0:i<0))&&(!s.endAt||(r=s.endAt,n=dw(s),i=Ly(r,n,a),r.inclusive?0<=i:0<i));var r,n,i,s,a,o}function ww(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function bw(e){return(t,r)=>{let n=!1;for(var i of dw(e)){let e=((e,t,r)=>{var n=e.field.isKeyField()?x.comparator(t.key,r.key):((e,t,r)=>{var n=t.data.field(e),i=r.data.field(e);return null!==n&&null!==i?my(n,i):k()})(e.field,t,r);switch(e.dir){case"asc":return n;case"desc":return-1*n;default:return k()}})(i,t,r);if(0!==e)return e;n=n||i.field.isKeyField()}return 0}}class Iw{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){U_(this.inner,(e,t)=>{for(let[e,r]of t)n(e,r)})}isEmpty(){return V_(this.inner)}size(){return this.innerSize}}let Tw=new L(x.comparator);let Ew=new L(x.comparator);function Cw(...e){let t=Ew;for(var r of e)t=t.insert(r.key,r);return t}function kw(e){let r=Ew;return e.forEach((e,t)=>r=r.insert(e,t.overlayedDocument)),r}function Sw(){return new Iw(e=>e.toString(),(e,t)=>e.isEqual(t))}let Aw=new L(x.comparator),Nw=new M(x.comparator);function V(...e){let t=Nw;for(var r of e)t=t.add(r);return t}let Rw=new M(R);function Pw(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:Cv(t)?"-0":t}}function Dw(e){return{integerValue:""+e}}function xw(e,t){return kv(t)?Dw(t):Pw(e,t)}class Ow{constructor(){this._=void 0}}function Lw(e,t){return e instanceof jw?by(e=t)||(e=e)&&"doubleValue"in e?t:{integerValue:0}:null}class Mw extends Ow{}class Fw extends Ow{constructor(e){super(),this.elements=e}}function Uw(e,t){var r=zw(t);for(let t of e.elements)r.some(e=>fy(e,t))||r.push(t);return{arrayValue:{values:r}}}class Vw extends Ow{constructor(e){super(),this.elements=e}}function qw(e,t){let r=zw(t);for(let t of e.elements)r=r.filter(e=>!fy(e,t));return{arrayValue:{values:r}}}class jw extends Ow{constructor(e,t){super(),this.serializer=e,this.Ie=t}}function Bw(e){return Q_(e.integerValue||e.doubleValue)}function zw(e){return Iy(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class Kw{constructor(e,t){this.field=e,this.transform=t}}class Ww{constructor(e,t){this.version=e,this.transformResults=t}}class Hw{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new Hw}static exists(e){return new Hw(void 0,e)}static updateTime(e){return new Hw(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 Gw(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class $w{}function Qw(e,r){if(!e.hasLocalMutations||r&&0===r.fields.length)return null;if(null===r)return e.isNoDocument()?new nb(e.key,Hw.none()):new Xw(e.key,e.data,Hw.none());{var n,i=e.data,s=Dy.empty();let t=new M($m.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 Zw(e.key,s,new K_(t.toArray()),Hw.none())}}function Yw(e,t,r,n){return e instanceof Xw?(s=t,a=r,o=n,Gw((i=e).precondition,s)?(l=i.value.clone(),h=rb(i.fieldTransforms,o,s),l.setAll(h),s.convertToFoundDocument(s.version,l).setHasLocalMutations(),null):a):e instanceof Zw?(i=t,o=r,s=n,Gw((a=e).precondition,i)?(h=rb(a.fieldTransforms,s,i),(l=i.data).setAll(eb(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,Gw(e.precondition,n)?(n.convertToNoDocument(n.version).setHasLocalMutations(),null):t);var i,s,a,o,l,h}function Jw(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&&jm(r,n,(e,t)=>(t=t,(e=e).field.isEqual(t.field)&&(e=e.transform,t=t.transform,e instanceof Fw&&t instanceof Fw||e instanceof Vw&&t instanceof Vw?jm(e.elements,t.elements,fy):e instanceof jw&&t instanceof jw?fy(e.Ie,t.Ie):e instanceof Mw&&t instanceof Mw)))))&&(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 Xw extends $w{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 Zw extends $w{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 eb(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 tb(e,t,r){var n,i,s,a=new Map;S(e.length===r.length);for(let u=0;u<r.length;u++){var o=e[u],l=o.transform,h=t.data.field(o.field);a.set(o.field,(n=l,i=h,s=r[u],n instanceof Fw?Uw(n,i):n instanceof Vw?qw(n,i):s))}return a}function rb(e,r,n){var i,s,a,o,l,h,u,c=new Map;for(i of e){let e=i.transform,t=n.data.field(i.field);c.set(i.field,(s=e,a=t,o=r,u=h=l=void 0,s instanceof Mw?(o=o,h=a,u={fields:{[X_]:{stringValue:J_},[ey]:{timestampValue:{seconds:o.seconds,nanos:o.nanoseconds}}}},(h=h&&ty(h)?ry(h):h)&&(u.fields[Z_]=h),{mapValue:u}):s instanceof Fw?Uw(s,a):s instanceof Vw?qw(s,a):(u=Lw(o=s,a),l=Bw(u)+Bw(o.Ie),by(u)&&by(o.Ie)?Dw(l):Pw(o.serializer,l))))}return c}class nb extends $w{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class ib extends $w{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class sb{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 c=0;c<this.mutations.length;c++){var u=this.mutations[c];u.key.isEqual(e.key)&&(r=u,n=e,i=h[c],l=u=o=a=s=void 0,r instanceof Xw?(a=n,o=i,u=(s=r).value.clone(),l=tb(s.fieldTransforms,a,o.transformResults),u.setAll(l),a.convertToFoundDocument(o.version,u).setHasCommittedMutations()):r instanceof Zw?(s=n,a=i,Gw((o=r).precondition,s)?(l=tb(o.fieldTransforms,s,a.transformResults),(u=s.data).setAll(eb(o)),u.setAll(l),s.convertToFoundDocument(a.version,u).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=Yw(r,e,t,this.localWriteTime));for(var n of this.mutations)n.key.isEqual(e.key)&&(t=Yw(n,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(n,i){let s=Sw();return this.mutations.forEach(e=>{var t=n.get(e.key),r=t.overlayedDocument,t=this.applyToLocalView(r,t.mutatedFields),t=Qw(r,i.has(e.key)?null:t);null!==t&&s.set(e.key,t),r.isValidDocument()||r.convertToNoDocument(P.min())}),s}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),V())}isEqual(e){return this.batchId===e.batchId&&jm(this.mutations,e.mutations,(e,t)=>Jw(e,t))&&jm(this.baseMutations,e.baseMutations,(e,t)=>Jw(e,t))}}class ab{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);let n=Aw;var i=e.mutations;for(let s=0;s<i.length;s++)n=n.insert(i[s].key,r[s].version);return new ab(e,t,r,n)}}class ob{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 hi={error:"UNKNOWN_ERROR"};async function ui(e,t=!1){var r,n=e.app;zn(n);let i=Mn(n),s=i.token,a=void 0;if(s&&!gi(s)&&(i.token=void 0,s=void 0),s||(r=await i.cachedTokenPromise)&&(gi(r)?s=r:await si(n,void 0)),!t&&s&&gi(s))return{token:s.token};let o=!1;if(oi())return i.exchangeTokenPromise||(i.exchangeTokenPromise=Hn(Gn(n,await li()),e.heartbeatServiceProvider).finally(()=>{i.exchangeTokenPromise=void 0}),o=!0),await si(n,r=await i.exchangeTokenPromise),{token:(i.token=r).token};try{i.exchangeTokenPromise||(i.exchangeTokenPromise=i.provider.getToken().finally(()=>{i.exchangeTokenPromise=void 0}),o=!0),s=await Mn(n).exchangeTokenPromise}catch(e){"appCheck/throttled"===e.code?ni.warn(e.message):ni.error(e),a=e}let l;return s?a?l=gi(s)?{token:s.token,internalError:a}:mi(a):(l={token:s.token},await si(n,i.token=s)):l=mi(a),o&&fi(n,l),l}function ci(t,e,r,n){var i=t.app,i=Mn(i),s={next:r,error:n,type:e};if(i.tokenObservers=[...i.tokenObservers,s],i.token&&gi(i.token)){let e=i.token;Promise.resolve().then(()=>{r({token:e.token}),pi(t)}).catch(()=>{})}i.cachedTokenPromise.then(()=>pi(t))}function di(e,t){var r=Mn(e),n=r.tokenObservers.filter(e=>e.next!==t);0===n.length&&r.tokenRefresher&&r.tokenRefresher.isRunning()&&r.tokenRefresher.stop(),r.tokenObservers=n}function pi(e){var t=e.app,t=Mn(t);let r=t.tokenRefresher;r||(r=(r=>{let n=r.app;return new qn(async()=>{var e=Mn(n);let t;if((t=e.token?await ui(r,!0):await ui(r)).error)throw t.error;if(t.internalError)throw t.internalError},()=>!0,()=>{var e,t=Mn(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},Vn.RETRIAL_MIN_WAIT,Vn.RETRIAL_MAX_WAIT)})(e),t.tokenRefresher=r),!r.isRunning()&&t.isTokenAutoRefreshEnabled&&r.start()}function fi(e,t){var r;for(r of Mn(e).tokenObservers)try{"EXTERNAL"===r.type&&null!=t.error?r.error(t.error):r.next(t)}catch(e){}}function gi(e){return 0<e.expireTimeMillis-Date.now()}function mi(e){return{token:(t=hi,s.encodeString(JSON.stringify(t),!1)),error:e};var t}class vi{constructor(e,t){this.app=e,this.heartbeatServiceProvider=t}_delete(){var e,t=Mn(this.app).tokenObservers;for(e of t)di(this.app,e.next);return Promise.resolve()}}function _i(t){return{getToken:e=>ui(t,e),getLimitedUseToken:()=>(async e=>{var t=e.app,r=(zn(t),Mn(t)).provider;return oi()?{token:t=(await Hn(Gn(t,await li()),e.heartbeatServiceProvider)).token}:{token:t=(await r.getToken()).token}})(t),addTokenListener:e=>ci(t,"INTERNAL",e),removeTokenListener:e=>di(t.app,e)}}let yi="https://www.google.com/recaptcha/api.js",wi="https://www.google.com/recaptcha/enterprise.js";function bi(t,r){let n=new X;Mn(t).reCAPTCHAState={initialized:n};let i=Ei(t);var e,s=Bn(!1);return s?Ti(t,r,s,i,n):(e=()=>{var e=Bn(!1);if(!e)throw new Error("no recaptcha");Ti(t,r,e,i,n)},(s=document.createElement("script")).src=yi,s.onload=e,document.head.appendChild(s)),n.promise}function Ii(t,r){let n=new X;Mn(t).reCAPTCHAState={initialized:n};let i=Ei(t);var e,s=Bn(!0);return s?Ti(t,r,s,i,n):(e=()=>{var e=Bn(!0);if(!e)throw new Error("no recaptcha");Ti(t,r,e,i,n)},(s=document.createElement("script")).src=wi,s.onload=e,document.head.appendChild(s)),n.promise}function Ti(n,i,s,a,o){s.ready(()=>{var e,t,r;e=n,t=s.render(a,{sitekey:i,size:"invisible",callback:()=>{Mn(e).reCAPTCHAState.succeeded=!0},"error-callback":()=>{Mn(e).reCAPTCHAState.succeeded=!1}}),(r=Mn(e)).reCAPTCHAState=Object.assign(Object.assign({},r.reCAPTCHAState),{widgetId:t}),o.resolve(s)})}function Ei(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 Ci(n){zn(n);let i=await Mn(n).reCAPTCHAState.initialized.promise;return new Promise((e,t)=>{let r=Mn(n).reCAPTCHAState;i.ready(()=>{e(i.execute(r.widgetId,{action:"fire_app_check"}))})})}class ki{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){Ri(this._throttleData);var t,r=await Ci(this._app).catch(e=>{throw jn.create("recaptcha-error")});if(null==(t=Mn(this._app).reCAPTCHAState)||!t.succeeded)throw jn.create("recaptcha-error");let e;try{e=await Hn(((e,t)=>{var{projectId:r,appId:n,apiKey:i}=e.options;return{url:Fn+`/projects/${r}/apps/${n}:exchangeRecaptchaV3Token?key=`+i,body:{recaptcha_v3_token:t}}})(this._app,r),this._heartbeatServiceProvider)}catch(e){throw null!=(t=e.code)&&t.includes("fetch-status-error")?(this._throttleData=Ni(Number(null==(r=e.customData)?void 0:r.httpStatus),this._throttleData),jn.create("throttled",{time:Kn(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,e}initialize(e){this._app=e,this._heartbeatServiceProvider=kt(e,"heartbeat"),bi(e,this._siteKey).catch(()=>{})}isEqual(e){return e instanceof ki&&this._siteKey===e._siteKey}}class Si{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){Ri(this._throttleData);var t,r=await Ci(this._app).catch(e=>{throw jn.create("recaptcha-error")});if(null==(t=Mn(this._app).reCAPTCHAState)||!t.succeeded)throw jn.create("recaptcha-error");let e;try{e=await Hn(((e,t)=>{var{projectId:r,appId:n,apiKey:i}=e.options;return{url:Fn+`/projects/${r}/apps/${n}:exchangeRecaptchaEnterpriseToken?key=`+i,body:{recaptcha_enterprise_token:t}}})(this._app,r),this._heartbeatServiceProvider)}catch(e){throw null!=(t=e.code)&&t.includes("fetch-status-error")?(this._throttleData=Ni(Number(null==(r=e.customData)?void 0:r.httpStatus),this._throttleData),jn.create("throttled",{time:Kn(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,e}initialize(e){this._app=e,this._heartbeatServiceProvider=kt(e,"heartbeat"),Ii(e,this._siteKey).catch(()=>{})}isEqual(e){return e instanceof Si&&this._siteKey===e._siteKey}}class Ai{constructor(e){this._customProviderOptions=e}async getToken(){var e,t=await this._customProviderOptions.getToken(),r=(e=t.token,"object"==typeof(r=ve(e).claims)&&r.hasOwnProperty("iat")?r.iat:null),r=null!==r&&r<Date.now()&&0<r?1e3*r:Date.now();return Object.assign(Object.assign({},t),{issuedAtTimeMillis:r})}initialize(e){this._app=e}isEqual(e){return e instanceof Ai&&this._customProviderOptions.getToken.toString()===e._customProviderOptions.getToken.toString()}}function Ni(e,t){var r,n;return 404===e||403===e?{backoffCount:1,allowRequestsAfter:Date.now()+864e5,httpStatus:e}:(n=Ve(r=t?t.backoffCount:0,1e3,2),{backoffCount:r+1,allowRequestsAfter:Date.now()+n,httpStatus:e})}function Ri(e){if(e&&Date.now()-e.allowRequestsAfter<=0)throw jn.create("throttled",{time:Kn(e.allowRequestsAfter-Date.now()),httpStatus:e.httpStatus})}function Pi(e=Ot(),r){var t=kt(e=w(e),"app-check");if(Ln.initialized||(i=W(),(n=Ln).initialized=!0,"string"!=typeof i.FIREBASE_APPCHECK_DEBUG_TOKEN&&!0!==i.FIREBASE_APPCHECK_DEBUG_TOKEN)||(n.enabled=!0,s=new X,n.token=s,"string"==typeof i.FIREBASE_APPCHECK_DEBUG_TOKEN?s.resolve(i.FIREBASE_APPCHECK_DEBUG_TOKEN):s.resolve(ai())),oi()&&li().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 jn.create("already-initialized",{appName:e.name})}var s=t.initialize({options:r});{var a=e,o=r.provider;r=r.isTokenAutoRefreshEnabled;let t=((e,t)=>(xn.set(e,t),xn.get(e)))(a,Object.assign({},On));t.activated=!0,t.provider=o,t.cachedTokenPromise=ii(a).then(e=>(e&&gi(e)&&(t.token=e,fi(a,{token:e.token})),e)),t.isTokenAutoRefreshEnabled=void 0===r?a.automaticDataCollectionEnabled:r,t.provider.initialize(a)}return Mn(e).isTokenAutoRefreshEnabled&&ci(s,"INTERNAL",()=>{}),s}let Di="app-check-internal";Ct(new u("app-check",e=>{var t,r=e.getProvider("app").getImmediate(),n=e.getProvider("heartbeat");return e=r,t=n,new vi(e,t)},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,r)=>{e.getProvider(Di).initialize()})),Ct(new u(Di,e=>_i(e.getProvider("app-check").getImmediate()),"PUBLIC").setInstantiationMode("EXPLICIT")),d("@firebase/app-check","0.8.11");let xi=new pe("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 Oi{constructor(e){this.app=e}activate(e,t){let r;r="string"==typeof e?new ki(e):e instanceof Si||e instanceof ki||e instanceof Ai?e:new Ai({getToken:e.getToken}),this._delegate=Pi(this.app,{provider:r,isTokenAutoRefreshEnabled:t})}setTokenAutoRefreshEnabled(e){if(!this._delegate)throw xi.create("use-before-activation",{appName:this.app.name});var t,r;t=this._delegate,e=e,(r=Mn(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 ui(e,t);if(r.error)throw r.error;return{token:r.token}})(this._delegate,e);throw xi.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),ci(i,"EXTERNAL",e,t),()=>di(i.app,e)}throw xi.create("use-before-activation",{appName:this.app.name})}}let Li=e=>{var t=e.getProvider("app-compat").getImmediate();return new Oi(t)};function Mi(e,t){var r={};for(i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(r[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var n=0,i=Object.getOwnPropertySymbols(e);n<i.length;n++)t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(r[i[n]]=e[i[n]]);return r}tr.INTERNAL.registerComponent(new u("appCheck-compat",Li,"PUBLIC").setServiceProps({ReCaptchaEnterpriseProvider:Si,ReCaptchaV3Provider:ki,CustomProvider:Ai})),tr.registerVersion("@firebase/app-check-compat","0.3.18");let Fi={FACEBOOK:"facebook.com",GITHUB:"github.com",GOOGLE:"google.com",PASSWORD:"password",PHONE:"phone",TWITTER:"twitter.com"},Ui={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 Vi(){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 qi(){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 ji=Vi,Bi=new pe("auth","Firebase",Vi()),zi=new $e("@firebase/auth");function Ki(e,...t){zi.logLevel<=c.ERROR&&zi.error(`Auth (${Dt}): `+e,...t)}function Wi(e,...t){throw Yi(e,...t)}function Hi(e,...t){return Yi(e,...t)}function Gi(e,t,r){var n=Object.assign(Object.assign({},ji()),{[t]:r});return new pe("auth","Firebase",n).create(t,{appName:e.name})}function $i(e){return Gi(e,"operation-not-supported-in-this-environment","Operations that alter the current user are not supported in conjunction with FirebaseServerApp")}function Qi(e,t,r){var n=r;if(!(t instanceof n))throw n.name!==t.constructor.name&&Wi(e,"argument-error"),Gi(e,"argument-error",`Type of ${t.constructor.name} does not match expected instance.`+"Did you pass a reference from a different Auth SDK?")}function Yi(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)):Bi.create(e,...t)}function m(e,t,...r){if(!e)throw Yi(t,...r)}function Ji(e){var t="INTERNAL ASSERTION FAILED: "+e;throw Ki(t),new Error(t)}function Xi(e,t){e||Ji(t)}function Zi(){var e;return"undefined"!=typeof self&&(null==(e=self.location)?void 0:e.href)||""}function es(){return"http:"===ts()||"https:"===ts()}function ts(){var e;return"undefined"!=typeof self&&(null==(e=self.location)?void 0:e.protocol)||null}class rs{constructor(e,t){Xi((this.shortDelay=e)<(this.longDelay=t),"Short delay should be less than long delay!"),this.isMobile=te()||se()}get(){return"undefined"!=typeof navigator&&navigator&&"onLine"in navigator&&"boolean"==typeof navigator.onLine&&(es()||ie()||"connection"in navigator)&&!navigator.onLine?Math.min(5e3,this.shortDelay):this.isMobile?this.longDelay:this.shortDelay}}function ns(e,t){Xi(e.emulator,"Emulator should always be set here");var r=e.emulator.url;return t?""+r+(t.startsWith("/")?t.slice(1):t):r}class is{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 Ji("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 Ji("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 Ji("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"))}}let ss={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"},as=new rs(3e4,6e4);function os(e,t){return e.tenantId&&!t.tenantId?Object.assign(Object.assign({},t),{tenantId:e.tenantId}):t}async function ls(i,s,a,o,e={}){return hs(i,e,async()=>{let e={},t={};o&&("GET"===s?t=o:e={body:JSON.stringify(o)});var r=Ee(Object.assign({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),Object.assign({method:s,headers:n},e));return"undefined"!=typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||(n.referrerPolicy="no-referrer"),is.fetch()(cs(i,i.config.apiHost,a,r),n)})}async function hs(t,e,r){t._canInitEmulator=!1;var n=Object.assign(Object.assign({},ss),e);try{var i=new ds(t),s=await Promise.race([r(),i.promise]),a=(i.clearNetworkTimeout(),await s.json());if("needConfirmation"in a)throw ps(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 ps(t,"credential-already-in-use",a);if("EMAIL_EXISTS"===o)throw ps(t,"email-already-in-use",a);if("USER_DISABLED"===o)throw ps(t,"user-disabled",a);var h=n[o]||o.toLowerCase().replace(/[_\s]+/g,"-");if(l)throw Gi(t,h,l);Wi(t,h)}catch(e){if(e instanceof de)throw e;Wi(t,"network-request-failed",{message:String(e)})}}async function us(e,t,r,n,i={}){var s=await ls(e,t,r,n,i);return"mfaPendingCredential"in s&&Wi(e,"multi-factor-auth-required",{_serverResponse:s}),s}function cs(e,t,r,n){var i=""+t+r+"?"+n;return e.config.emulator?ns(e.config,i):e.config.apiScheme+"://"+i}class ds{clearNetworkTimeout(){clearTimeout(this.timer)}constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((e,t)=>{this.timer=setTimeout(()=>t(Hi(this.auth,"network-request-failed")),as.get())})}}function ps(e,t,r){var n={appName:e.name},n=(r.email&&(n.email=r.email),r.phoneNumber&&(n.phoneNumber=r.phoneNumber),Hi(e,t,n));return n.customData._tokenResponse=r,n}function fs(e){return void 0!==e&&void 0!==e.getResponse}function gs(e){return void 0!==e&&void 0!==e.enterprise}class ms{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 vs(e,t){return ls(e,"GET","/v2/recaptchaConfig",os(e,t))}async function _s(e,t){return ls(e,"POST","/v1/accounts:lookup",t)}function ys(e){if(e)try{var t=new Date(Number(e));if(!isNaN(t.getTime()))return t.toUTCString()}catch(e){}}function ws(e){return 1e3*Number(e)}function bs(e){var[t,r,n]=e.split(".");if(void 0===t||void 0===r||void 0===n)return Ki("JWT malformed, contained fewer than 3 sections"),null;try{var i=z(r);return i?JSON.parse(i):(Ki("Failed to decode base64 JWT payload"),null)}catch(e){return Ki("Caught error parsing JWT payload as JSON",null==e?void 0:e.toString()),null}}function Is(e){var t=bs(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 Ts(t,e,r=!1){if(r)return e;try{return await e}catch(e){throw e instanceof de&&(r=[e.code][0],"auth/user-disabled"===r||"auth/user-token-expired"===r)&&(t.auth.currentUser===t&&await t.auth.signOut()),e}}class Es{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=(null!=(t=this.user.stsTokenManager.expirationTime)?t: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"===(null==e?void 0:e.code)&&this.schedule(!0))}this.schedule()}}class Cs{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=ys(this.lastLoginAt),this.creationTime=ys(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function ks(e){var t,r,n=e.auth,i=await e.getIdToken(),i=await Ts(e,_s(n,{idToken:i})),n=(m(null==i?void 0:i.users.length,n,"internal-error"),i.users[0]),i=(e._notifyReloadListener(n),null!=(i=n.providerUserInfo)&&i.length?Ss(n.providerUserInfo):[]),i=(t=e.providerData,r=i,[...t.filter(t=>!r.some(e=>e.providerId===t.providerId)),...r]),s=!(e.email&&n.passwordHash||null!==i&&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 Cs(n.createdAt,n.lastLoginAt),isAnonymous:s};Object.assign(e,i)}function Ss(e){return e.map(e=>{var t=e.providerId,r=Mi(e,["providerId"]);return{providerId:t,uid:r.rawId||"",displayName:r.displayName||null,email:r.email||null,phoneNumber:r.phoneNumber||null,photoURL:r.photoUrl||null}})}class As{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):Is(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,t)}updateFromIdToken(e){m(0!==e.length,"internal-error");var t=Is(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 hs(n=e,{},async()=>{var e=Ee({grant_type:"refresh_token",refresh_token:i}).slice(1),{tokenApiHost:t,apiKey:r}=n.config,t=cs(n,t,"/v1/token","key="+r),r=await n._getAdditionalHeaders();return r["Content-Type"]="application/x-www-form-urlencoded",is.fetch()(t,{method:"POST",headers:r,body:e})})).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 As;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 As,this.toJSON())}_performRefresh(){return Ji("not implemented")}}function Ns(e,t){m("string"==typeof e||void 0===e,"internal-error",{appName:t})}class Rs{constructor(e){var{uid:t,auth:r,stsTokenManager:n}=e,i=Mi(e,["uid","auth","stsTokenManager"]);this.providerId="firebase",this.proactiveRefresh=new Es(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=t,this.auth=r,this.stsTokenManager=n,this.accessToken=n.accessToken,this.displayName=i.displayName||null,this.email=i.email||null,this.emailVerified=i.emailVerified||!1,this.phoneNumber=i.phoneNumber||null,this.photoURL=i.photoURL||null,this.isAnonymous=i.isAnonymous||!1,this.tenantId=i.tenantId||null,this.providerData=i.providerData?[...i.providerData]:[],this.metadata=new Cs(i.createdAt||void 0,i.lastLoginAt||void 0)}async getIdToken(e){var t=await Ts(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=bs(n),s=(m(i&&i.exp&&i.auth_time&&i.iat,r.auth,"internal-error"),null==(r="object"==typeof i.firebase?i.firebase:void 0)?void 0:r.sign_in_provider);return{claims:i,token:n,authTime:ys(ws(i.auth_time)),issuedAtTime:ys(ws(i.iat)),expirationTime:ys(ws(i.exp)),signInProvider:s||null,signInSecondFactor:(null==r?void 0:r.sign_in_second_factor)||null}})(this,e)}reload(){return(async e=>{var t=w(e);await ks(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=>Object.assign({},e)),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){var t=new Rs(Object.assign(Object.assign({},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 ks(this),await this.auth._persistUserIfCurrent(this),r&&this.auth._notifyListenersIfCurrent(this)}async delete(){var e;return h(this.auth.app)?Promise.reject($i(this.auth)):(e=await this.getIdToken(),await Ts(this,(async(e,t)=>ls(e,"POST","/v1/accounts:delete",t))(this.auth,{idToken:e})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut())}toJSON(){return Object.assign(Object.assign({uid:this.uid,email:this.email||void 0,emailVerified:this.emailVerified,displayName:this.displayName||void 0,isAnonymous:this.isAnonymous,photoURL:this.photoURL||void 0,phoneNumber:this.phoneNumber||void 0,tenantId:this.tenantId||void 0,providerData:this.providerData.map(e=>Object.assign({},e)),stsTokenManager:this.stsTokenManager.toJSON(),_redirectEventId:this._redirectEventId},this.metadata.toJSON()),{apiKey:this.auth.config.apiKey,appName:this.auth.name})}get refreshToken(){return this.stsTokenManager.refreshToken||""}static _fromJSON(e,t){var r=null!=(r=t.displayName)?r:void 0,n=null!=(n=t.email)?n:void 0,i=null!=(i=t.phoneNumber)?i:void 0,s=null!=(s=t.photoURL)?s:void 0,a=null!=(a=t.tenantId)?a:void 0,o=null!=(o=t._redirectEventId)?o:void 0,l=null!=(l=t.createdAt)?l:void 0,h=null!=(h=t.lastLoginAt)?h:void 0,{uid:u,emailVerified:c,isAnonymous:d,providerData:p,stsTokenManager:f}=t,f=(m(u&&f,e,"internal-error"),As.fromJSON(this.name,f)),u=(m("string"==typeof u,e,"internal-error"),Ns(r,e.name),Ns(n,e.name),m("boolean"==typeof c,e,"internal-error"),m("boolean"==typeof d,e,"internal-error"),Ns(i,e.name),Ns(s,e.name),Ns(a,e.name),Ns(o,e.name),Ns(l,e.name),Ns(h,e.name),new Rs({uid:u,auth:e,email:n,emailVerified:c,displayName:r,isAnonymous:d,photoURL:s,phoneNumber:i,tenantId:a,stsTokenManager:f,createdAt:l,lastLoginAt:h}));return p&&Array.isArray(p)&&(u.providerData=p.map(e=>Object.assign({},e))),o&&(u._redirectEventId=o),u}static async _fromIdTokenResponse(e,t,r=!1){var n=new As,n=(n.updateFromServerResponse(t),new Rs({uid:t.localId,auth:e,stsTokenManager:n,isAnonymous:r}));return await ks(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?Ss(n.providerUserInfo):[]),s=!(n.email&&n.passwordHash||null!=i&&i.length),a=new As,a=(a.updateFromIdToken(r),new Rs({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 Cs(n.createdAt,n.lastLoginAt),isAnonymous:!(n.email&&n.passwordHash||null!=i&&i.length)};return Object.assign(a,s),a}}let Ps=new Map;function Ds(e){Xi(e instanceof Function,"Expected a class definition");var t=Ps.get(e);return t?Xi(t instanceof e,"Instance stored in cache mismatched with class"):(t=new e,Ps.set(e,t)),t}class xs{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){}}xs.type="NONE";let Os=xs;function Ls(e,t,r){return`firebase:${e}:${t}:`+r}class Ms{constructor(e,t,r){this.persistence=e,this.auth=t,this.userKey=r;var{config:n,name:i}=this.auth;this.fullUserKey=Ls(this.userKey,n.apiKey,i),this.fullPersistenceKey=Ls("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=await this.persistence._get(this.fullUserKey);return e?Rs._fromJSON(this.auth,e):null}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(e){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(e,t,r="authUser"){if(!t.length)return new Ms(Ds(Os),e,r);var n,i=(await Promise.all(t.map(async e=>{if(await e._isAvailable())return e}))).filter(e=>e);let s=i[0]||Ds(Os),a=Ls(r,e.config.apiKey,e.name),o=null;for(n of t)try{var l=await n._get(a);if(l){var h=Rs._fromJSON(e,l);n!==s&&(o=h),s=n;break}}catch(e){}i=i.filter(e=>e._shouldAllowMigration);return s._shouldAllowMigration&&i.length&&(s=i[0],o&&await s._set(a,o.toJSON()),await Promise.all(t.map(async e=>{if(e!==s)try{await e._remove(a)}catch(e){}}))),new Ms(s,e,r)}}function Fs(e){var t=e.toLowerCase();return t.includes("opera/")||t.includes("opr/")||t.includes("opios/")?"Opera":js(t)?"IEMobile":t.includes("msie")||t.includes("trident/")?"IE":t.includes("edge/")?"Edge":Us(t)?"Firefox":t.includes("silk/")?"Silk":zs(t)?"Blackberry":Ks(t)?"Webos":Vs(t)?"Safari":!t.includes("chrome/")&&!qs(t)||t.includes("edge/")?Bs(t)?"Android":2===(null==(t=e.match(/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/))?void 0:t.length)?t[1]:"Other":"Chrome"}function Us(e=ee()){return/firefox\//i.test(e)}function Vs(e=ee()){var t=e.toLowerCase();return t.includes("safari/")&&!t.includes("chrome/")&&!t.includes("crios/")&&!t.includes("android")}function qs(e=ee()){return/crios\//i.test(e)}function js(e=ee()){return/iemobile/i.test(e)}function Bs(e=ee()){return/android/i.test(e)}function zs(e=ee()){return/blackberry/i.test(e)}function Ks(e=ee()){return/webos/i.test(e)}function Ws(e=ee()){return/iphone|ipad|ipod/i.test(e)||/macintosh/i.test(e)&&/mobile/i.test(e)}function Hs(e=ee()){return Ws(e)||Bs(e)||Ks(e)||zs(e)||/windows phone/i.test(e)||js(e)}function Gs(e,t=[]){let r;switch(e){case"Browser":r=Fs(ee());break;case"Worker":r=Fs(ee())+"-"+e;break;default:r=e}var n=t.length?t.join(","):"FirebaseCore-web";return`${r}/JsCore/${Dt}/`+n}class $s{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:null==e?void 0:e.message})}}}}class Qs{constructor(e){var t,r=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=null!=(t=r.minPasswordLength)?t:6,r.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=r.maxPasswordLength),void 0!==r.containsLowercaseCharacter&&(this.customStrengthOptions.containsLowercaseLetter=r.containsLowercaseCharacter),void 0!==r.containsUppercaseCharacter&&(this.customStrengthOptions.containsUppercaseLetter=r.containsUppercaseCharacter),void 0!==r.containsNumericCharacter&&(this.customStrengthOptions.containsNumericCharacter=r.containsNumericCharacter),void 0!==r.containsNonAlphanumericCharacter&&(this.customStrengthOptions.containsNonAlphanumericCharacter=r.containsNonAlphanumericCharacter),this.enforcementState=e.enforcementState,"ENFORCEMENT_STATE_UNSPECIFIED"===this.enforcementState&&(this.enforcementState="OFF"),this.allowedNonAlphanumericCharacters=null!=(r=null==(t=e.allowedNonAlphanumericCharacters)?void 0:t.join(""))?r:"",this.forceUpgradeOnSignin=null!=(t=e.forceUpgradeOnSignin)&&t,this.schemaVersion=e.schemaVersion}validatePassword(e){var t,r={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,r),this.validatePasswordCharacterOptions(e,r),r.isValid&&(r.isValid=null==(t=r.meetsMinPasswordLength)||t),r.isValid&&(r.isValid=null==(t=r.meetsMaxPasswordLength)||t),r.isValid&&(r.isValid=null==(t=r.containsLowercaseLetter)||t),r.isValid&&(r.isValid=null==(t=r.containsUppercaseLetter)||t),r.isValid&&(r.isValid=null==(t=r.containsNumericCharacter)||t),r.isValid&&(r.isValid=null==(t=r.containsNonAlphanumericCharacter)||t),r}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 Ys{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 Xs(this),this.idTokenSubscription=new Xs(this),this.beforeStateQueue=new $s(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=Bi,this._agentRecaptchaConfig=null,this._tenantRecaptchaConfigs={},this._projectPasswordPolicy=null,this._tenantPasswordPolicies={},this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=n.sdkClientVersion}_initializeWithPersistence(t,r){return r&&(this._popupRedirectResolver=Ds(r)),this._initializationPromise=this.queue(async()=>{var e;if(!this._deleted&&(this.persistenceManager=await Ms.create(this,t),!this._deleted)){if(null!=(e=this._popupRedirectResolver)&&e._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch(e){}await this.initializeCurrentUser(r),this.lastNotifiedUid=(null==(e=this.currentUser)?void 0:e.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 _s(this,{idToken:e}),r=await Rs._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=null==(t=this.redirectUser)?void 0:t._redirectEventId,r=null==s?void 0:s._redirectEventId,n=await this.tryRedirectSignIn(e),t&&t!==r||null==n||!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 ks(e)}catch(e){if("auth/network-request-failed"!==(null==e?void 0: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($i(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($i(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($i(this)):this.queue(async()=>{await this.assertedPersistence.setPersistence(Ds(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 ls(e=this,"GET","/v2/passwordPolicy",os(e,{})),t=new Qs(t);null===this.tenantId?this._projectPasswordPolicy=t:this._tenantPasswordPolicies[this.tenantId]=t}_getPersistence(){return this.assertedPersistence.persistence.type}_updateErrorMap(e){this._errorFactory=new pe("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 ls(e=this,"POST","/v2/accounts:revokeToken",os(e,t)))}toJSON(){var e;return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:null==(e=this._currentUser)?void 0:e.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&&Ds(e)||this._popupRedirectResolver,this,"argument-error"),this.redirectPersistenceManager=await Ms.create(this,[Ds(t._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()),this.redirectPersistenceManager}async _redirectUserForId(e){var t;return this._isInitialized&&await this.queue(async()=>{}),(null==(t=this._currentUser)?void 0:t._redirectEventId)===e?this._currentUser:(null==(t=this.redirectUser)?void 0:t._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=null!=(e=null==(e=this.currentUser)?void 0:e.uid)?e: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=Gs(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(null==(t=this.heartbeatServiceProvider.getImmediate({optional:!0}))?void 0:t.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:(null!=(e=await(null==(e=this.appCheckServiceProvider.getImmediate({optional:!0}))?void 0:e.getToken()))&&e.error&&(t="Error while retrieving App Check token: "+e.error,r=[],zi.logLevel<=c.WARN)&&zi.warn(`Auth (${Dt}): `+t,...r),null==e?void 0:e.token)}}function Js(e){return w(e)}class Xs{constructor(e){this.auth=e,this.observer=null,this.addObserver=Ae(e=>this.observer=e)}get next(){return m(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}let Zs={async loadJS(){throw new Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};function ea(e){return Zs.loadJS(e)}function ta(e){return"__"+e+Math.floor(1e6*Math.random())}class ra{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 sa(e,this.auth.name,t||{})),this.counter++,r}reset(e){var t,r=e||1e12;null!=(t=this._widgets.get(r))&&t.delete(),this._widgets.delete(r)}getResponse(e){var t;return(null==(t=this._widgets.get(e||1e12))?void 0:t.getResponse())||""}async execute(e){var t;return null!=(t=this._widgets.get(e||1e12))&&t.execute(),""}}class na{constructor(){this.enterprise=new ia}ready(e){e()}execute(e,t){return Promise.resolve("token")}render(e,t){return""}}class ia{ready(e){e()}execute(e,t){return Promise.resolve("token")}render(e,t){return""}}class sa{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 aa="NO_RECAPTCHA";class oa{constructor(e){this.type="recaptcha-enterprise",this.auth=Js(e)}async verify(i="verify",e=!1){function s(e,t,r){let n=window.grecaptcha;gs(n)?n.enterprise.ready(()=>{n.enterprise.execute(e,{action:i}).then(e=>{t(e)}).catch(()=>{t(aa)})}):r(Error("No reCAPTCHA enterprise script loaded."))}return this.auth.settings.appVerificationDisabledForTesting?(new na).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)=>{vs(i,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then(e=>{var t;if(void 0!==e.recaptchaKey)return t=new ms(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&&gs(window.grecaptcha))s(t,r,n);else if("undefined"==typeof window)n(new Error("RecaptchaVerifier is only supported in browser"));else{let e=Zs.recaptchaEnterpriseScript;0!==e.length&&(e+=t),ea(e).then(()=>{s(t,r,n)}).catch(e=>{n(e)})}}).catch(e=>{n(e)})})}}async function la(e,t,r,n=!1,i=!1){var s=new oa(e);let a;if(i)a=aa;else try{a=await s.verify(r)}catch(e){a=await s.verify(r,!0)}var o,l,s=Object.assign({},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 ha(r,n,i,s,e){var t;return"EMAIL_PASSWORD_PROVIDER"===e?null!=(t=r._getRecaptchaConfig())&&t.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")?(t=await la(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 la(r,n,i,"getOobCode"===i),s(r,t)):Promise.reject(e)}):"PHONE_PROVIDER"===e?null!=(t=r._getRecaptchaConfig())&&t.isProviderEnabled("PHONE_PROVIDER")?(t=await la(r,n,i),s(r,t).catch(async e=>{var t;if("AUDIT"===(null==(t=r._getRecaptchaConfig())?void 0:t.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 la(r,n,i,!1,!0),s(r,t);return Promise.reject(e)})):(t=await la(r,n,i,!1,!0),s(r,t)):Promise.reject(e+" provider is not supported.")}function ua(e,t,r){var n=Js(e),i=(m(n._canInitEmulator,n,"emulator-config-failed"),m(/^https?:\/\//.test(t),n,"invalid-emulator-scheme"),!(null==r||!r.disableWarnings)),s=ca(t),{host:a,port:o}=(e=>{var t,r=ca(e);return(r=/(\/\/)?([^?#/]+)/.exec(e.substr(r.length)))?(r=r[2].split("@").pop()||"",(t=/^(\[[^\]]+\])(:|$)/.exec(r))?{host:t=t[1],port:da(r.substr(t.length+1))}:([t,r]=r.split(":"),{host:t,port:da(r)})):{host:"",port:null}})(t);function l(){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.config.emulator={url:s+`//${a}${null===o?"":":"+o}/`},n.settings.appVerificationDisabledForTesting=!0,n.emulatorConfig=Object.freeze({host:a,port:o,protocol:s.replace(":",""),options:Object.freeze({disableWarnings:i})}),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",l):l()))}function ca(e){var t=e.indexOf(":");return t<0?"":e.substr(0,t+1)}function da(e){var t;return!e||(t=Number(e),isNaN(t))?null:t}class pa{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return Ji("not implemented")}_getIdTokenResponse(e){return Ji("not implemented")}_linkToIdToken(e,t){return Ji("not implemented")}_getReauthenticationResolver(e){return Ji("not implemented")}}async function fa(e,t){return ls(e,"POST","/v1/accounts:resetPassword",os(e,t))}async function ga(e,t){return ls(e,"POST","/v1/accounts:signUp",t)}async function ma(e,t){return us(e,"POST","/v1/accounts:signInWithPassword",os(e,t))}async function va(e,t){return ls(e,"POST","/v1/accounts:sendOobCode",os(e,t))}async function _a(e,t){return va(e,t)}async function ya(e,t){return va(e,t)}class wa extends pa{constructor(e,t,r,n=null){super("password",r),this._email=e,this._password=t,this._tenantId=n}static _fromEmailAndPassword(e,t){return new wa(e,t,"password")}static _fromEmailAndCode(e,t,r=null){return new wa(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(null!=t&&t.email&&null!=t&&t.password){if("password"===t.signInMethod)return this._fromEmailAndPassword(t.email,t.password);if("emailLink"===t.signInMethod)return this._fromEmailAndCode(t.email,t.password,t.tenantId)}return null}async _getIdTokenResponse(e){switch(this.signInMethod){case"password":return ha(e,{returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signInWithPassword",ma,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return(async(e,t)=>us(e,"POST","/v1/accounts:signInWithEmailLink",os(e,t)))(e,{email:this._email,oobCode:this._password});default:Wi(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":return ha(e,{idToken:t,returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",ga,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return(async(e,t)=>us(e,"POST","/v1/accounts:signInWithEmailLink",os(e,t)))(e,{idToken:t,email:this._email,oobCode:this._password});default:Wi(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function ba(e,t){return us(e,"POST","/v1/accounts:signInWithIdp",os(e,t))}class Ia extends pa{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){var t=new Ia(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):Wi("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="string"==typeof e?JSON.parse(e):e,{providerId:r,signInMethod:n}=t,t=Mi(t,["providerId","signInMethod"]);return r&&n?((r=new Ia(r,n)).idToken=t.idToken||void 0,r.accessToken=t.accessToken||void 0,r.secret=t.secret,r.nonce=t.nonce,r.pendingToken=t.pendingToken||null,r):null}_getIdTokenResponse(e){return ba(e,this.buildRequest())}_linkToIdToken(e,t){var r=this.buildRequest();return r.idToken=t,ba(e,r)}_getReauthenticationResolver(e){var t=this.buildRequest();return t.autoCreate=!1,ba(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=Ee(e)),t}}async function Ta(e,t){return ls(e,"POST","/v1/accounts:sendVerificationCode",os(e,t))}let Ea={USER_NOT_FOUND:"user-not-found"};class Ca extends pa{constructor(e){super("phone","phone"),this.params=e}static _fromVerification(e,t){return new Ca({verificationId:e,verificationCode:t})}static _fromTokenResponse(e,t){return new Ca({phoneNumber:e,temporaryProof:t})}_getIdTokenResponse(e){return(async(e,t)=>us(e,"POST","/v1/accounts:signInWithPhoneNumber",os(e,t)))(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return(async(e,t)=>{var r=await us(e,"POST","/v1/accounts:signInWithPhoneNumber",os(e,t));if(r.temporaryProof)throw ps(e,"account-exists-with-different-credential",r);return r})(e,Object.assign({idToken:t},this._makeVerificationRequest()))}_getReauthenticationResolver(e){return(async(e,t)=>us(e,"POST","/v1/accounts:signInWithPhoneNumber",os(e,Object.assign(Object.assign({},t),{operation:"REAUTH"})),Ea))(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 Ca({verificationId:t,verificationCode:r,phoneNumber:n,temporaryProof:i}):null}}class ka{constructor(e){var t=Ce(ke(e)),r=null!=(r=t.apiKey)?r:null,n=null!=(n=t.oobCode)?n: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}})(null!=(i=t.mode)?i:null);m(r&&n&&i,"argument-error"),this.apiKey=r,this.operation=i,this.code=n,this.continueUrl=null!=(r=t.continueUrl)?r:null,this.languageCode=null!=(i=t.languageCode)?i:null,this.tenantId=null!=(n=t.tenantId)?n:null}static parseLink(e){t=Ce(ke(e=e)).link,r=t?Ce(ke(t)).deep_link_id:null;var t,r,n=((n=Ce(ke(e)).deep_link_id)?Ce(ke(n)).link:null)||n||r||t||e;try{return new ka(n)}catch(e){return null}}}class Sa{constructor(){this.providerId=Sa.PROVIDER_ID}static credential(e,t){return wa._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){var r=ka.parseLink(t);return m(r,"argument-error"),wa._fromEmailAndCode(e,r.code,r.tenantId)}}Sa.PROVIDER_ID="password",Sa.EMAIL_PASSWORD_SIGN_IN_METHOD="password",Sa.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class Aa{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 Na extends Aa{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class Ra extends Na{static credentialFromJSON(e){var t="string"==typeof e?JSON.parse(e):e;return m("providerId"in t&&"signInMethod"in t,"argument-error"),Ia._fromParams(t)}credential(e){return this._credential(Object.assign(Object.assign({},e),{nonce:e.rawNonce}))}_credential(e){return m(e.idToken||e.accessToken,"argument-error"),Ia._fromParams(Object.assign(Object.assign({},e),{providerId:this.providerId,signInMethod:this.providerId}))}static credentialFromResult(e){return Ra.oauthCredentialFromTaggedObject(e)}static credentialFromError(e){return Ra.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 Ra(a)._credential({idToken:t,accessToken:r,nonce:s,pendingToken:i})}catch(e){return null}}}class Pa extends Na{constructor(){super("facebook.com")}static credential(e){return Ia._fromParams({providerId:Pa.PROVIDER_ID,signInMethod:Pa.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return Pa.credentialFromTaggedObject(e)}static credentialFromError(e){return Pa.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return Pa.credential(e.oauthAccessToken)}catch(e){return null}}}Pa.FACEBOOK_SIGN_IN_METHOD="facebook.com",Pa.PROVIDER_ID="facebook.com";class Da extends Na{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return Ia._fromParams({providerId:Da.PROVIDER_ID,signInMethod:Da.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return Da.credentialFromTaggedObject(e)}static credentialFromError(e){return Da.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthIdToken:t,oauthAccessToken:r}=e;if(!t&&!r)return null;try{return Da.credential(t,r)}catch(e){return null}}}Da.GOOGLE_SIGN_IN_METHOD="google.com",Da.PROVIDER_ID="google.com";class xa extends Na{constructor(){super("github.com")}static credential(e){return Ia._fromParams({providerId:xa.PROVIDER_ID,signInMethod:xa.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return xa.credentialFromTaggedObject(e)}static credentialFromError(e){return xa.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return xa.credential(e.oauthAccessToken)}catch(e){return null}}}xa.GITHUB_SIGN_IN_METHOD="github.com",xa.PROVIDER_ID="github.com";class Oa extends pa{constructor(e,t){super(e,e),this.pendingToken=t}_getIdTokenResponse(e){return ba(e,this.buildRequest())}_linkToIdToken(e,t){var r=this.buildRequest();return r.idToken=t,ba(e,r)}_getReauthenticationResolver(e){var t=this.buildRequest();return t.autoCreate=!1,ba(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 Oa(t,n):null}static _create(e,t){return new Oa(e,t)}buildRequest(){return{requestUri:"http://localhost",returnSecureToken:!0,pendingToken:this.pendingToken}}}class La extends Aa{constructor(e){m(e.startsWith("saml."),"argument-error"),super(e)}static credentialFromResult(e){return La.samlCredentialFromTaggedObject(e)}static credentialFromError(e){return La.samlCredentialFromTaggedObject(e.customData||{})}static credentialFromJSON(e){var t=Oa.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 Oa._create(r,t)}catch(e){return null}}}class Ma extends Na{constructor(){super("twitter.com")}static credential(e,t){return Ia._fromParams({providerId:Ma.PROVIDER_ID,signInMethod:Ma.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return Ma.credentialFromTaggedObject(e)}static credentialFromError(e){return Ma.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthAccessToken:t,oauthTokenSecret:r}=e;if(!t||!r)return null;try{return Ma.credential(t,r)}catch(e){return null}}}async function Fa(e,t){return us(e,"POST","/v1/accounts:signUp",os(e,t))}Ma.TWITTER_SIGN_IN_METHOD="twitter.com",Ma.PROVIDER_ID="twitter.com";class Ua{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 Rs._fromIdTokenResponse(e,r,n),s=Va(r);return new Ua({user:i,providerId:s,_tokenResponse:r,operationType:t})}static async _forOperation(e,t,r){await e._updateTokensIfNecessary(r,!0);var n=Va(r);return new Ua({user:e,providerId:n,_tokenResponse:r,operationType:t})}}function Va(e){return e.providerId||("phoneNumber"in e?"phone":null)}class qa extends de{constructor(e,t,r,n){var i;super(t.code,t.message),this.operationType=r,this.user=n,Object.setPrototypeOf(this,qa.prototype),this.customData={appName:e.name,tenantId:null!=(i=e.tenantId)?i:void 0,_serverResponse:t.customData._serverResponse,operationType:r}}static _fromErrorAndOperation(e,t,r,n){return new qa(e,t,r,n)}}function ja(t,r,e,n){return("reauthenticate"===r?e._getReauthenticationResolver(t):e._getIdTokenResponse(t)).catch(e=>{if("auth/multi-factor-auth-required"===e.code)throw qa._fromErrorAndOperation(t,e,r,n);throw e})}function Ba(e){return new Set(e.map(({providerId:e})=>e).filter(e=>!!e))}async function za(e,t){var r=w(e),n=(await Wa(!0,r,t),e=r.auth,t={idToken:await r.getIdToken(),deleteProvider:[t]},await ls(e,"POST","/v1/accounts:update",t)).providerUserInfo;let i=Ba(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 Ka(e,t,r=!1){var n=await Ts(e,t._linkToIdToken(e.auth,await e.getIdToken()),r);return Ua._forOperation(e,"link",n)}async function Wa(e,t,r){await ks(t);var n=!1===e?"provider-already-linked":"no-such-provider";m(Ba(t.providerData).has(r)===e,t.auth,n)}async function Ha(e,t,r=!1){var n=e.auth;if(h(n.app))return Promise.reject($i(n));var i="reauthenticate";try{var s=await Ts(e,ja(n,i,t,e),r),a=(m(s.idToken,n,"internal-error"),bs(s.idToken)),o=(m(a,n,"internal-error"),a).sub;return m(e.uid===o,n,"user-mismatch"),Ua._forOperation(e,i,s)}catch(e){throw"auth/user-not-found"===(null==e?void 0:e.code)&&Wi(n,"user-mismatch"),e}}async function Ga(e,t,r=!1){var n;return h(e.app)?Promise.reject($i(e)):(n=await ja(e,"signIn",t),n=await Ua._fromIdTokenResponse(e,"signIn",n),r||await e._updateCurrentUser(n.user),n)}async function $a(e,t){return Ga(Js(e),t)}async function Qa(e,t){var r=w(e);return await Wa(!1,r,t.providerId),Ka(r,t)}async function Ya(e,t){return Ha(w(e),t)}async function Ja(e,t){var r,n;return h(e.app)?Promise.reject($i(e)):(n=await us(r=Js(e),"POST","/v1/accounts:signInWithCustomToken",os(r,{token:t,returnSecureToken:!0})),n=await Ua._fromIdTokenResponse(r,"signIn",n),await r._updateCurrentUser(n.user),n)}class Xa{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?Za._fromServerResponse(e,t):"totpInfo"in t?eo._fromServerResponse(e,t):Wi(e,"internal-error")}}class Za extends Xa{constructor(e){super("phone",e),this.phoneNumber=e.phoneInfo}static _fromServerResponse(e,t){return new Za(t)}}class eo extends Xa{constructor(e){super("totp",e)}static _fromServerResponse(e,t){return new eo(t)}}function to(e,t,r){var n;m(0<(null==(n=r.url)?void 0:n.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 ro(e){var t=Js(e);t._getPasswordPolicyInternal()&&await t._updatePasswordPolicy()}async function no(e,t){await ls(e=w(e),"POST","/v1/accounts:update",os(e,{oobCode:t}))}async function io(e,t){var r=w(e),n=await fa(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=Xa._fromServerResponse(Js(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 so(e,t){var r=es()?Zi():"http://localhost",r=(await ls(e=w(e),"POST","/v1/accounts:createAuthUri",os(e,{identifier:t,continueUri:r}))).signinMethods;return r||[]}async function ao(e,t){var r=w(e),n={requestType:"VERIFY_EMAIL",idToken:await e.getIdToken()},r=(t&&to(r.auth,n,t),await va(r.auth,n)).email;r!==e.email&&await e.reload()}async function oo(e,t,r){var n=w(e),i={requestType:"VERIFY_AND_CHANGE_EMAIL",idToken:await e.getIdToken(),newEmail:t},n=(r&&to(n.auth,i,r),await va(n.auth,i)).email;n!==e.email&&await e.reload()}async function lo(e,{displayName:t,photoURL:r}){var n,i,s;void 0===t&&void 0===r||(i=await(n=w(e)).getIdToken(),i=await Ts(n,(async(e,t)=>ls(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 ho(e,t,r){var n=e.auth,i={idToken:await e.getIdToken(),returnSecureToken:!0},n=(t&&(i.email=t),r&&(i.password=r),await Ts(e,(async(e,t)=>ls(e,"POST","/v1/accounts:update",t))(n,i)));await e._updateTokensIfNecessary(n,!0)}class uo{constructor(e,t,r={}){this.isNewUser=e,this.providerId=t,this.profile=r}}class co extends uo{constructor(e,t,r,n){super(e,t,r),this.username=n}}class po extends uo{constructor(e,t){super(e,"facebook.com",t)}}class fo extends co{constructor(e,t){super(e,"github.com",t,"string"==typeof(null==t?void 0:t.login)?null==t?void 0:t.login:null)}}class go extends uo{constructor(e,t){super(e,"google.com",t)}}class mo extends co{constructor(e,t,r){super(e,"twitter.com",t,r)}}function vo(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&&null!=n&&n.idToken){t=null==(t=null==(t=bs(n.idToken))?void 0:t.firebase)?void 0:t.sign_in_provider;if(t)return t="anonymous"!==t&&"custom"!==t?t:null,new uo(a,t)}if(!i)return null;switch(i){case"facebook.com":return new po(a,s);case"github.com":return new fo(a,s);case"google.com":return new go(a,s);case"twitter.com":return new mo(a,s,n.screenName||null);case"custom":case"anonymous":return new uo(a,null);default:return new uo(a,i,s)}}class _o{constructor(e,t,r){this.type=e,this.credential=t,this.user=r}static _fromIdtoken(e,t){return new _o("enroll",e,t)}static _fromMfaPendingCredential(e){return new _o("signin",e)}toJSON(){return{multiFactorSession:{["enroll"===this.type?"idToken":"pendingCredential"]:this.credential}}}static fromJSON(e){var t;if(null!=e&&e.multiFactorSession){if(null!=(t=e.multiFactorSession)&&t.pendingCredential)return _o._fromMfaPendingCredential(e.multiFactorSession.pendingCredential);if(null!=(t=e.multiFactorSession)&&t.idToken)return _o._fromIdtoken(e.multiFactorSession.idToken)}return null}}class yo{constructor(e,t,r){this.session=e,this.hints=t,this.signInResolver=r}static _fromError(e,i){let s=Js(e),a=i.customData._serverResponse;var t=(a.mfaInfo||[]).map(e=>Xa._fromServerResponse(s,e));m(a.mfaPendingCredential,s,"internal-error");let o=_o._fromMfaPendingCredential(a.mfaPendingCredential);return new yo(o,t,async e=>{var t=await e._process(s,o),r=(delete a.mfaInfo,delete a.mfaPendingCredential,Object.assign(Object.assign({},a),{idToken:t.idToken,refreshToken:t.refreshToken}));switch(i.operationType){case"signIn":var n=await Ua._fromIdTokenResponse(s,i.operationType,r);return await s._updateCurrentUser(n.user),n;case"reauthenticate":return m(i.user,s,"internal-error"),Ua._forOperation(i.user,i.operationType,r);default:Wi(s,"internal-error")}})}async resolveSignIn(e){return this.signInResolver(e)}}function wo(e,t){return ls(e,"POST","/v2/accounts/mfaEnrollment:start",os(e,t))}class bo{constructor(t){this.user=t,this.enrolledFactors=[],t._onReload(e=>{e.mfaInfo&&(this.enrolledFactors=e.mfaInfo.map(e=>Xa._fromServerResponse(t.auth,e)))})}static _fromUser(e){return new bo(e)}async getSession(){return _o._fromIdtoken(await this.user.getIdToken(),this.user)}async enroll(e,t){var r=e,n=await this.getSession(),r=await Ts(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 Ts(this.user,(r=this.user.auth,n={idToken:i,mfaEnrollmentId:t},ls(r,"POST","/v2/accounts/mfaEnrollment:withdraw",os(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 Io=new WeakMap;let To="__sak";class Eo{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(To,"1"),this.storage.removeItem(To),Promise.resolve(!0)):Promise.resolve(!1)}catch(e){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 Co extends Eo{constructor(){super(()=>window.localStorage,"LOCAL"),this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t),this.listeners={},this.localCache={},this.pollTimer=null,this.fallbackToPolling=Hs(),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);ae()&&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]}}Co.type="LOCAL";let ko=Co;class So extends Eo{constructor(){super(()=>window.sessionStorage,"SESSION")}_addListener(e,t){}_removeListener(e,t){}}So.type="SESSION";let Ao=So;class No{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 No(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];null!=s&&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 Ro(e="",t=10){let r="";for(let n=0;n<t;n++)r+=Math.floor(10*Math.random());return e+r}No.receivers=[];class Po{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=Ro("",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 Do(){return window}function xo(){return void 0!==Do().WorkerGlobalScope&&"function"==typeof Do().importScripts}let Oo="firebaseLocalStorageDb",Lo="firebaseLocalStorage",Mo="fbase_key";class Fo{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 Uo(e,t){return e.transaction([Lo],t?"readwrite":"readonly").objectStore(Lo)}function Vo(){let n=indexedDB.open(Oo,1);return new Promise((t,r)=>{n.addEventListener("error",()=>{r(n.error)}),n.addEventListener("upgradeneeded",()=>{var e=n.result;try{e.createObjectStore(Lo,{keyPath:Mo})}catch(e){r(e)}}),n.addEventListener("success",async()=>{var e=n.result;e.objectStoreNames.contains(Lo)?t(e):(e.close(),e=indexedDB.deleteDatabase(Oo),await new Fo(e).toPromise(),t(await Vo()))})})}async function qo(e,t,r){var n=Uo(e,!0).put({fbase_key:t,value:r});return new Fo(n).toPromise()}function jo(e,t){var r=Uo(e,!0).delete(t);return new Fo(r).toPromise()}class Bo{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 Vo()),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 xo()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=No._getInstance(xo()?self:null),this.receiver._subscribe("keyChanged",async(e,t)=>({keyProcessed:(await this._poll()).includes(t.key)})),this.receiver._subscribe("ping",async(e,t)=>["keyChanged"])}async initializeSender(){var e,t;this.activeServiceWorker=await(async()=>{if(null==navigator||!navigator.serviceWorker)return null;try{return(await navigator.serviceWorker.ready).active}catch(e){return null}})(),this.activeServiceWorker&&(this.sender=new Po(this.activeServiceWorker),t=await this.sender._send("ping",{},800))&&null!=(e=t[0])&&e.fulfilled&&null!=(e=t[0])&&e.value.includes("keyChanged")&&(this.serviceWorkerReceiverAvailable=!0)}async notifyServiceWorker(e){var t;if(this.sender&&this.activeServiceWorker&&((null==(t=null==navigator?void 0:navigator.serviceWorker)?void 0:t.controller)||null)===this.activeServiceWorker)try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch(e){}}async _isAvailable(){try{var e;return indexedDB?(await qo(e=await Vo(),To,"1"),await jo(e,To),!0):!1}catch(e){}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=>qo(e,t,r)),this.localCache[t]=r,this.notifyServiceWorker(t)))}async _get(t){var e=await this._withRetries(e=>(async(e,t)=>{var r=Uo(e,!1).get(t);return void 0===(r=await new Fo(r).toPromise())?null:r.value})(e,t));return this.localCache[t]=e}async _remove(t){return this._withPendingWrite(async()=>(await this._withRetries(e=>jo(e,t)),delete this.localCache[t],this.notifyServiceWorker(t)))}async _poll(){var e=await this._withRetries(e=>{var t=Uo(e,!1).getAll();return new Fo(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()}}Bo.type="LOCAL";let zo=Bo;function Ko(e,t){return ls(e,"POST","/v2/accounts/mfaSignIn:start",os(e,t))}let Wo=ta("rcb"),Ho=new rs(3e4,6e4);class Go{constructor(){var e;this.hostLanguage="",this.counter=0,this.librarySeparatelyLoaded=!(null==(e=Do().grecaptcha)||!e.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)&&fs(Do().grecaptcha)?Promise.resolve(Do().grecaptcha):new Promise((t,r)=>{let n=Do().setTimeout(()=>{r(Hi(i,"network-request-failed"))},Ho.get());Do()[Wo]=()=>{Do().clearTimeout(n),delete Do()[Wo];var e=Do().grecaptcha;if(e&&fs(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(Hi(i,"internal-error"))},ea(Zs.recaptchaV2Script+"?"+Ee({onload:Wo,render:"explicit",hl:s})).catch(()=>{clearTimeout(n),r(Hi(i,"internal-error"))})})}clearedOneInstance(){this.counter--}shouldResolveImmediately(e){var t;return!(null==(t=Do().grecaptcha)||!t.render)&&(e===this.hostLanguage||0<this.counter||this.librarySeparatelyLoaded)}}class $o{async load(e){return new ra(e)}clearedOneInstance(){}}let Qo="recaptcha",Yo={theme:"light",type:"image"};class Jo{constructor(e,t,r=Object.assign({},Yo)){this.parameters=r,this.type=Qo,this.destroyed=!1,this.widgetId=null,this.tokenChangeListeners=new Set,this.renderPromise=null,this.recaptcha=null,this.auth=Js(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?$o:Go),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=Do()[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(es()&&!xo(),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 ls(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 Xo{constructor(e,t){this.verificationId=e,this.onConfirmation=t}confirm(e){var t=Ca._fromVerification(this.verificationId,e);return this.onConfirmation(t)}}async function Zo(t,r,n){var i,e,s,a,o,l,h,u;if(!t._getRecaptchaConfig())try{e=Js(t),s=await vs(e,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}),s=new ms(s),null==e.tenantId?e._agentRecaptchaConfig=s:e._tenantRecaptchaConfigs[e.tenantId]=s,await(!s.isAnyProviderEnabled()||!new oa(e).verify())}catch(e){console.log("Failed to initialize reCAPTCHA Enterprise config. Triggering the reCAPTCHA v2 verification.")}try{let e;return("session"in(e="string"==typeof r?{phoneNumber:r}:r)?(a=e.session,"phoneNumber"in e?(m("enroll"===a.type,t,"internal-error"),o={idToken:a.credential,phoneEnrollmentInfo:{phoneNumber:e.phoneNumber,clientType:"CLIENT_TYPE_WEB"}},(await ha(t,o,"mfaSmsEnrollment",async(e,t)=>t.phoneEnrollmentInfo.captchaResponse===aa?(m((null==n?void 0:n.type)===Qo,e,"argument-error"),wo(e,await el(e,t,n))):wo(e,t),"PHONE_PROVIDER").catch(e=>Promise.reject(e))).phoneSessionInfo):(m("signin"===a.type,t,"internal-error"),m(l=(null==(i=e.multiFactorHint)?void 0:i.uid)||e.multiFactorUid,t,"missing-multi-factor-info"),h={mfaPendingCredential:a.credential,mfaEnrollmentId:l,phoneSignInInfo:{clientType:"CLIENT_TYPE_WEB"}},(await ha(t,h,"mfaSmsSignIn",async(e,t)=>t.phoneSignInInfo.captchaResponse===aa?(m((null==n?void 0:n.type)===Qo,e,"argument-error"),Ko(e,await el(e,t,n))):Ko(e,t),"PHONE_PROVIDER").catch(e=>Promise.reject(e))).phoneResponseInfo)):(u={phoneNumber:e.phoneNumber,clientType:"CLIENT_TYPE_WEB"},await ha(t,u,"sendVerificationCode",async(e,t)=>t.captchaResponse===aa?(m((null==n?void 0:n.type)===Qo,e,"argument-error"),Ta(e,await el(e,t,n))):Ta(e,t),"PHONE_PROVIDER").catch(e=>Promise.reject(e)))).sessionInfo}finally{null!=n&&n._reset()}}async function el(e,t,r){m(r.type===Qo,e,"argument-error");var n,i,s,a,o=await r.verify(),l=(m("string"==typeof o,e,"argument-error"),Object.assign({},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 tl{constructor(e){this.providerId=tl.PROVIDER_ID,this.auth=Js(e)}verifyPhoneNumber(e,t){return Zo(this.auth,e,w(t))}static credential(e,t){return Ca._fromVerification(e,t)}static credentialFromResult(e){var t=e;return tl.credentialFromTaggedObject(t)}static credentialFromError(e){return tl.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){var t,r;return e&&({phoneNumber:t,temporaryProof:r}=e,t)&&r?Ca._fromTokenResponse(t,r):null}}function rl(e,t){return t?Ds(t):(m(e._popupRedirectResolver,e,"argument-error"),e._popupRedirectResolver)}tl.PROVIDER_ID="phone",tl.PHONE_SIGN_IN_METHOD="phone";class nl extends pa{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return ba(e,this._buildIdpRequest())}_linkToIdToken(e,t){return ba(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return ba(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 il(e){return Ga(e.auth,new nl(e),e.bypassAuthState)}function sl(e){var{auth:t,user:r}=e;return m(r,t,"internal-error"),Ha(r,new nl(e),e.bypassAuthState)}async function al(e){var{auth:t,user:r}=e;return m(r,t,"internal-error"),Ka(r,new nl(e),e.bypassAuthState)}class ol{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 il;case"linkViaPopup":case"linkViaRedirect":return al;case"reauthViaPopup":case"reauthViaRedirect":return sl;default:Wi(this.auth,"internal-error")}}resolve(e){Xi(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){Xi(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 ll=new rs(2e3,1e4);class hl extends ol{constructor(e,t,r,n,i){super(e,t,n,i),this.provider=r,this.authWindow=null,this.pollId=null,hl.currentPopupAction&&hl.currentPopupAction.cancel(),hl.currentPopupAction=this}async executeNotNull(){var e=await this.execute();return m(e,this.auth,"internal-error"),e}async onExecution(){Xi(1===this.filter.length,"Popup operations only handle one event");var e=Ro();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(Hi(this.auth,"web-storage-unsupported"))}),this.pollUserCancellation()}get eventId(){var e;return(null==(e=this.authWindow)?void 0:e.associatedEvent)||null}cancel(){this.reject(Hi(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,hl.currentPopupAction=null}pollUserCancellation(){let t=()=>{var e;null!=(e=null==(e=this.authWindow)?void 0:e.window)&&e.closed?this.pollId=window.setTimeout(()=>{this.pollId=null,this.reject(Hi(this.auth,"popup-closed-by-user"))},8e3):this.pollId=window.setTimeout(t,ll.get())};t()}}hl.currentPopupAction=null;let ul="pendingRedirect",cl=new Map;class dl extends ol{constructor(e,t,r=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,r),this.eventId=null}async execute(){let t=cl.get(this.auth._key());if(!t){try{let e=await(async(e,t)=>{var r,n=ml(t),i=gl(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)}cl.set(this.auth._key(),t)}return this.bypassAuthState||cl.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 pl(e,t){return gl(e)._set(ml(t),"true")}function fl(e,t){cl.set(e._key(),t)}function gl(e){return Ds(e._redirectPersistence)}function ml(e){return Ls(ul,e.config.apiKey,e.name)}function vl(e,t,r){return(async(e,t,r)=>{var n,i;return h(e.app)?Promise.reject($i(e)):(n=Js(e),Qi(e,t,Aa),await n._initializationPromise,await pl(i=rl(n,r),n),i._openRedirect(n,t,"signInViaRedirect"))})(e,t,r)}function _l(e,t,r){return(async(e,t,r)=>{var n=w(e);if(Qi(n.auth,t,Aa),h(n.auth.app))return Promise.reject($i(n.auth));await n.auth._initializationPromise;var i=rl(n.auth,r),s=(await pl(i,n.auth),await bl(n));return i._openRedirect(n.auth,t,"reauthViaRedirect",s)})(e,t,r)}function yl(e,t,r){return(async(e,t,r)=>{var n=w(e),i=(Qi(n.auth,t,Aa),await n.auth._initializationPromise,rl(n.auth,r)),s=(await Wa(!1,n,t.providerId),await pl(i,n.auth),await bl(n));return i._openRedirect(n.auth,t,"linkViaRedirect",s)})(e,t,r)}async function wl(e,t,r=!1){var n,i;return h(e.app)?Promise.reject($i(e)):(i=rl(n=Js(e),t),(i=await new dl(n,i,r).execute())&&!r&&(delete i.user._redirectEventId,await n._persistUserIfCurrent(i.user),await n._setRedirectUser(null,t)),i)}async function bl(e){var t=Ro(e.uid+":::");return e._redirectEventId=t,await e.auth._setRedirectUser(e),await e.auth._persistUserIfCurrent(e),t}class Il{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 El(e);default:return}})(t)||(this.hasHandledPotentialRedirect=!0,r)||(this.queuedRedirectEvent=t,r=!0),r}sendToConsumer(e,t){var r;e.error&&!El(e)?(r=(null==(r=e.error.code)?void 0:r.split("auth/")[1])||"internal-error",t.onError(Hi(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(Tl(e))}saveEventToCache(e){this.cachedEventUids.add(Tl(e)),this.lastProcessedEventTime=Date.now()}}function Tl(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter(e=>e).join("-")}function El({type:e,error:t}){return"unknown"===e&&"auth/no-auth-event"===(null==t?void 0:t.code)}async function Cl(e,t={}){return ls(e,"GET","/v1/projects",t)}let kl=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,Sl=/^https?/;async function Al(e){if(!e.config.emulator){var t,r=(await Cl(e)).authorizedDomains;for(t of r)try{if((e=>{var t,r=Zi(),{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:Sl.test(n)&&(kl.test(e)?i===e:(r=e.replace(/\./g,"\\."),(t=new RegExp("^(.+\\."+r+"|"+r+")$","i")).test(i)))})(t))return}catch(e){}Wi(e,"unauthorized-domain")}}let Nl=new rs(3e4,6e4);function Rl(){var t=Do().___jsl;if(null!=t&&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 Pl(i){return new Promise((e,t)=>{var r;function n(){Rl(),gapi.load("gapi.iframes",{callback:()=>{e(gapi.iframes.getContext())},ontimeout:()=>{Rl(),t(Hi(i,"network-request-failed"))},timeout:Nl.get()})}if(null!=(r=null==(r=Do().gapi)?void 0:r.iframes)&&r.Iframe)e(gapi.iframes.getContext());else{if(null==(r=Do().gapi)||!r.load)return r=ta("iframefcb"),Do()[r]=()=>{gapi.load?n():t(Hi(i,"network-request-failed"))},ea(Zs.gapiScript+"?onload="+r).catch(e=>t(e));n()}}).catch(e=>{throw Dl=null,e})}let Dl=null;let xl=new rs(5e3,15e3),Ol="__/auth/iframe",Ll="emulator/auth/iframe",Ml={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},Fl=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);async function Ul(a){e=a;var e,t,r,n=await(Dl=Dl||Pl(e)),i=Do().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?ns(n,Ll):`https://${e.config.authDomain}/`+Ol,n={apiKey:n.apiKey,appName:e.name,v:Dt},(r=Fl.get(e.config.apiHost))&&(n.eid=r),(r=e._getFrameworks()).length&&(n.fw=r.join(",")),t+"?"+Ee(n).slice(1)),messageHandlersFilter:i.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:Ml,dontclear:!0},s=>new Promise(async(e,t)=>{await s.restyle({setHideOnLeave:!1});let r=Hi(a,"network-request-failed"),n=Do().setTimeout(()=>{t(r)},xl.get());function i(){Do().clearTimeout(n),e(s)}s.ping(i).then(i,()=>{t(r)})}))}let Vl={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"};class ql{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch(e){}}}function jl(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=Object.assign(Object.assign({},Vl),{width:n.toString(),height:i.toString(),top:s,left:a}),a=ee().toLowerCase(),s=(r&&(o=qs(a)?"_blank":r),Us(a)&&(t=t||"http://localhost",s.scrollbars="yes"),Object.entries(s).reduce((e,[t,r])=>""+e+t+`=${r},`,""));if([n=ee()]=[a],Ws(n)&&null!=(a=window.navigator)&&a.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 ql(null);a=window.open(t||"",o,s);m(a,e,"popup-blocked");try{a.focus()}catch(e){}return new ql(a)}let Bl="__/auth/handler",zl="emulator/auth/handler",Kl=encodeURIComponent("fac");async function Wl(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:Dt,eventId:i};if(t instanceof Aa){t.setDefaultLanguage(e.languageCode),a.providerId=t.providerId||"",we(t.getCustomParameters())||(a.customParameters=JSON.stringify(t.getCustomParameters()));for(var[o,l]of Object.entries(s||{}))a[o]=l}t instanceof Na&&0<(c=t.getScopes().filter(e=>""!==e)).length&&(a.scopes=c.join(",")),e.tenantId&&(a.tid=e.tenantId);var h,u=a;for(h of Object.keys(u))void 0===u[h]&&delete u[h];var c=await e._getAppCheckToken(),c=c?`#${Kl}=`+encodeURIComponent(c):"";return`${r=[e.config][0],r.emulator?ns(r,zl):`https://${r.authDomain}/`+Bl}?`+Ee(u).slice(1)+c}let Hl="webStorageSupport";class Gl{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=Ao,this._completeRedirectFn=wl,this._overrideRedirectResult=fl}async _openPopup(e,t,r,n){Xi(null==(i=this.eventManagers[e._key()])?void 0:i.manager,"_initialize() not called before _openPopup()");var i=await Wl(e,t,r,Zi(),n);return jl(e,i,Ro())}async _openRedirect(e,t,r,n){await this._originValidation(e);var i=await Wl(e,t,r,Zi(),n);return Do().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):(Xi(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 Ul(t);let r=new Il(t);return e.register("authEvent",e=>(m(null==e?void 0: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(Hl,{type:Hl},e=>{var t=null==(t=null==e?void 0:e[0])?void 0:t[Hl];void 0!==t&&n(!!t),Wi(r,"internal-error")},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){var t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=Al(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return Hs()||Vs()||Ws()}}let $l=Gl;class Ql 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 Ji("unexpected MultiFactorSessionType")}}}{constructor(e){super("phone"),this.credential=e}static _fromCredential(e){return new Ql(e)}_finalizeEnroll(e,t,r){return e=e,t={idToken:t,displayName:r,phoneVerificationInfo:this.credential._makeVerificationRequest()},ls(e,"POST","/v2/accounts/mfaEnrollment:finalize",os(e,t))}_finalizeSignIn(e,t){return e=e,t={mfaPendingCredential:t,phoneVerificationInfo:this.credential._makeVerificationRequest()},ls(e,"POST","/v2/accounts/mfaSignIn:finalize",os(e,t))}}class Yl{constructor(){}static assertion(e){return Ql._fromCredential(e)}}Yl.FACTOR_ID="phone";Zt="@firebase/auth";class Jl{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){var e;return this.assertAuthConfigured(),(null==(e=this.auth.currentUser)?void 0:e.uid)||null}async getToken(e){return this.assertAuthConfigured(),await this.auth._initializationPromise,this.auth.currentUser?{accessToken:await this.auth.currentUser.getIdToken(e)}:null}addAuthTokenListener(t){var e;this.assertAuthConfigured(),this.internalListeners.has(t)||(e=this.auth.onIdTokenChanged(e=>{t((null==e?void 0: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 Xl;function Zl(){return window}t="authIdTokenMaxAge",null!=(er=Q())&&er["_"+t],Zs={loadJS(i){return new Promise((e,r)=>{var t,n=document.createElement("script");n.setAttribute("src",i),n.onload=e,n.onerror=e=>{var t=Hi("internal-error");t.customData=e,r(t)},n.type="text/javascript",n.charset="UTF-8",(null!=(t=null==(t=document.getElementsByTagName("head"))?void 0:t[0])?t:document).appendChild(n)})},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="},Xl="Browser",Ct(new u("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:Xl,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:Gs(Xl)}),a=new Ys(r,n,i,s);return e=a,r=(null==(t=t)?void 0:t.persistence)||[],r=(Array.isArray(r)?r:[r]).map(Ds),null!=t&&t.errorMap&&e._updateErrorMap(t.errorMap),e._initializeWithPersistence(r,null==t?void 0:t.popupRedirectResolver),a},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,r)=>{e.getProvider("auth-internal").initialize()})),Ct(new u("auth-internal",e=>{var t=Js(e.getProvider("auth").getImmediate());return e=t,new Jl(e)},"PRIVATE").setInstantiationMode("EXPLICIT")),d(Zt,"1.9.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}})(Xl)),d(Zt,"1.9.0","esm2017");async function eh(e,t,r){var n=Zl().BuildInfo,i=(Xi(t.sessionId,"AuthEvent did not contain a session ID"),i=(e=>{if(Xi(/[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 Ws()?s.ibi=n.packageName:Bs()?s.apn=n.packageName:Wi(e,"operation-not-supported-in-this-environment"),n.displayName&&(s.appDisplayName=n.displayName),s.sessionId=i,Wl(e,r,t.type,void 0,null!=(n=t.eventId)?n:void 0,s)}function th(n){let i=Zl().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=ee(),/(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 rh=20;class nh extends Il{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 ih(e,t,r=null){return{type:t,eventId:r,urlResponse:null,sessionId:(()=>{var e=[],t="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let n=0;n<rh;n++){var r=Math.floor(Math.random()*t.length);e.push(t.charAt(r))}return e.join("")})(),postBody:null,tenantId:e.tenantId,error:Hi(e,"no-auth-event")}}async function sh(e){var t=await oh()._get(lh(e));return t&&await oh()._remove(lh(e)),t}function ah(e,t){i=hh(t=t),n=i.link?decodeURIComponent(i.link):void 0,r=hh(n).link,i=i.deep_link_id?decodeURIComponent(i.deep_link_id):void 0;var r,n,i=hh(i).link||i||r||n||t;return i.includes("/__/auth/callback")?(n=(r=null==(n=null==(r=null==(n=(r=hh(i)).firebaseError?(e=>{try{return JSON.parse(e)}catch(e){return null}})(decodeURIComponent(r.firebaseError)):null)?void 0:n.code)?void 0:r.split("auth/"))?void 0:n[1])?Hi(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 oh(){return Ds(ko)}function lh(e){return Ls("authEvent",e.config.apiKey,e.name)}function hh(e){var t,r;return null!=e&&e.includes("?")?([t,...r]=e.split("?"),Ce(r.join("?"))):{}}class uh{constructor(){this._redirectPersistence=Ao,this._shouldInitProactively=!0,this.eventManagers=new Map,this.originValidationPromises={},this._completeRedirectFn=wl,this._overrideRedirectResult=fl}async _initialize(e){var t=e._key();let r=this.eventManagers.get(t);return r||(r=new nh(e),this.eventManagers.set(t,r),this.attachCallbackListeners(e,r)),r}_openPopup(e){Wi(e,"operation-not-supported-in-this-environment")}async _openRedirect(e,t,r,n){i=e,a=Zl(),m("function"==typeof(null==(s=null==a?void 0:a.universalLinks)?void 0:s.subscribe),i,"invalid-cordova-configuration",{missingPlugin:"cordova-universal-links-plugin-fix"}),m(void 0!==(null==(s=null==a?void 0:a.BuildInfo)?void 0:s.packageName),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-buildInfo"}),m("function"==typeof(null==(s=null==(s=null==(s=null==a?void 0:a.cordova)?void 0:s.plugins)?void 0:s.browsertab)?void 0:s.openUrl),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"}),m("function"==typeof(null==(s=null==(s=null==(s=null==a?void 0:a.cordova)?void 0:s.plugins)?void 0:s.browsertab)?void 0:s.isAvailable),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"}),m("function"==typeof(null==(a=null==(s=null==a?void 0:a.cordova)?void 0:s.InAppBrowser)?void 0:a.open),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-inappbrowser"});var i,s=await this._initialize(e),a=(await s.initialized(),s.resetRedirect(),cl.clear(),await this._originValidation(e),ih(e,r,n)),a=(i=e,r=a,await oh()._set(lh(i),r),await eh(e,a,t));return(async(a,o,l)=>{let h=Zl().cordova,u=()=>{};try{await new Promise((t,e)=>{let r=null;function n(){t();var e=null==(e=h.plugins.browsertab)?void 0:e.close;"function"==typeof e&&e(),"function"==typeof(null==l?void 0:l.close)&&l.close()}function i(){r=r||window.setTimeout(()=>{e(Hi(a,"redirect-cancelled-by-user"))},2e3)}function s(){"visible"===(null==document?void 0:document.visibilityState)&&i()}o.addPassiveListener(n),document.addEventListener("resume",i,!1),Bs()&&document.addEventListener("visibilitychange",s,!1),u=()=>{o.removePassiveListener(n),document.removeEventListener("resume",i,!1),document.removeEventListener("visibilitychange",s,!1),r&&window.clearTimeout(r)}})}finally{u()}})(e,s,await th(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=Zl().BuildInfo,r={};Ws()?r.iosBundleId=t.packageName:Bs()?r.androidPackageName=t.packageName:Wi(e,"operation-not-supported-in-this-environment"),await Cl(e,r)})(e)),this.originValidationPromises[t]}attachCallbackListeners(n,i){var{universalLinks:e,handleOpenURL:t,BuildInfo:r}=Zl();let s=setTimeout(async()=>{await sh(n),i.onEvent(dh())},500),a=async e=>{clearTimeout(s);var t=await sh(n);let r=null;t&&null!=e&&e.url&&(r=ah(t,e.url)),i.onEvent(r||dh())},o=(void 0!==e&&"function"==typeof e.subscribe&&e.subscribe(null,a),t),l=r.packageName.toLowerCase()+"://";Zl().handleOpenURL=async e=>{if(e.toLowerCase().startsWith(l)&&a({url:e}),"function"==typeof o)try{o(e)}catch(e){console.error(e)}}}}let ch=uh;function dh(){return{type:"unknown",eventId:null,sessionId:null,urlResponse:null,postBody:null,tenantId:null,error:Hi("no-auth-event")}}function ph(){var e;return(null==(e=null==self?void 0:self.location)?void 0:e.protocol)||null}function fh(e=ee()){return!("file:"!==ph()&&"ionic:"!==ph()&&"capacitor:"!==ph()||!e.toLowerCase().match(/iphone|ipad|ipod|android/))}function gh(e=ee()){return ae()&&11===(null==document?void 0:document.documentMode)||([e=ee()]=[e],/Edge\/\d+/.test(e))}function mh(){try{var e=self.localStorage,t=Ro();if(e)return e.setItem(t,"1"),e.removeItem(t),!gh()||he()}catch(e){return vh()&&he()}return!1}function vh(){return"undefined"!=typeof global&&"WorkerGlobalScope"in global&&"importScripts"in global}function _h(){return("http:"===ph()||"https:"===ph()||ie()||fh())&&!(se()||re())&&mh()&&!vh()}function yh(){return fh()&&"undefined"!=typeof document}let wh={LOCAL:"local",NONE:"none",SESSION:"session"},bh=m,Ih="persistence";async function Th(e){await e._initializationPromise;var t=Eh(),r=Ls(Ih,e.config.apiKey,e.name);t&&t.setItem(r,e._getPersistence())}function Eh(){var e;try{return(null===(e="undefined"!=typeof window?window:null)?void 0:e.sessionStorage)||null}catch(e){return null}}let Ch=m;class kh{constructor(){this.browserResolver=Ds($l),this.cordovaResolver=Ds(ch),this.underlyingResolver=null,this._redirectPersistence=Ao,this._completeRedirectFn=wl,this._overrideRedirectResult=fl}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 yh()||this.browserResolver._shouldInitProactively}get assertedUnderlyingResolver(){return Ch(this.underlyingResolver,"internal-error"),this.underlyingResolver}async selectUnderlyingResolver(){var e;this.underlyingResolver||(e=await(!!yh()&&new Promise(e=>{let t=setTimeout(()=>{e(!1)},1e3);document.addEventListener("deviceready",()=>{clearTimeout(t),e(!0)})})),this.underlyingResolver=e?this.cordovaResolver:this.browserResolver)}}function Sh(e){return e.unwrap()}function Ah(e,t){var r,n,i,s,a=null==(a=t.customData)?void 0:a._tokenResponse;"auth/multi-factor-auth-required"===(null==t?void 0:t.code)?t.resolver=new Dh(e,(r=t,i=w(e),m((s=r).customData.operationType,i,"argument-error"),m(null==(n=s.customData._serverResponse)?void 0:n.mfaPendingCredential,i,"argument-error"),yo._fromError(i,s))):a&&(i=Nh(n=t))&&(n.credential=i,n.tenantId=a.tenantId||void 0,n.email=a.email||void 0,n.phoneNumber=a.phoneNumber||void 0)}function Nh(e){var t=(e instanceof de?e.customData:e)._tokenResponse;if(!t)return null;if(!(e instanceof de)&&"temporaryProof"in t&&"phoneNumber"in t)return tl.credentialFromResult(e);var r=t.providerId;if(!r||r===Fi.PASSWORD)return null;let n;switch(r){case Fi.GOOGLE:n=Da;break;case Fi.FACEBOOK:n=Pa;break;case Fi.GITHUB:n=xa;break;case Fi.TWITTER:n=Ma;break;default:var{oauthIdToken:i,oauthAccessToken:s,oauthTokenSecret:a,pendingToken:o,nonce:l}=t;return s||a||i||o?o?r.startsWith("saml.")?Oa._create(r,o):Ia._fromParams({providerId:r,signInMethod:r,pendingToken:o,idToken:i,accessToken:s}):new Ra(r).credential({idToken:i,accessToken:s,rawNonce:l}):null}return e instanceof de?n.credentialFromError(e):n.credentialFromResult(e)}function Rh(t,e){return e.catch(e=>{throw e instanceof de&&Ah(t,e),e}).then(e=>{var t=e.operationType,r=e.user;return{operationType:t,credential:Nh(e),additionalUserInfo:vo(e),user:xh.getOrCreate(r)}})}async function Ph(t,e){let r=await e;return{verificationId:r.verificationId,confirm:e=>Rh(t,r.confirm(e))}}class Dh{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 Rh(Sh(this.auth),this.resolver.resolveSignIn(e))}}class xh{constructor(e){var t;this._delegate=e,this.multiFactor=(t=w(e),Io.has(t)||Io.set(t,bo._fromUser(t)),Io.get(t))}static getOrCreate(e){return xh.USER_MAP.has(e)||xh.USER_MAP.set(e,new xh(e)),xh.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 Rh(this.auth,Qa(this._delegate,e))}async linkWithPhoneNumber(e,t){return Ph(this.auth,(async(e,t,r)=>{let n=w(e);await Wa(!1,n,"phone");var i=await Zo(n.auth,t,w(r));return new Xo(i,e=>Qa(n,e))})(this._delegate,e,t))}async linkWithPopup(e){return Rh(this.auth,(async(e,t,r)=>{var n=w(e),i=(Qi(n.auth,t,Aa),rl(n.auth,r));return new hl(n.auth,"linkViaPopup",t,i,n).executeNotNull()})(this._delegate,e,kh))}async linkWithRedirect(e){return await Th(Js(this.auth)),yl(this._delegate,e,kh)}reauthenticateAndRetrieveDataWithCredential(e){return this.reauthenticateWithCredential(e)}async reauthenticateWithCredential(e){return Rh(this.auth,Ya(this._delegate,e))}reauthenticateWithPhoneNumber(e,t){return Ph(this.auth,(async(e,t,r)=>{let n=w(e);var i;return h(n.auth.app)?Promise.reject($i(n.auth)):(i=await Zo(n.auth,t,w(r)),new Xo(i,e=>Ya(n,e)))})(this._delegate,e,t))}reauthenticateWithPopup(e){return Rh(this.auth,(async(e,t,r)=>{var n=w(e);if(h(n.auth.app))return Promise.reject(Hi(n.auth,"operation-not-supported-in-this-environment"));Qi(n.auth,t,Aa);var i=rl(n.auth,r);return new hl(n.auth,"reauthViaPopup",t,i,n).executeNotNull()})(this._delegate,e,kh))}async reauthenticateWithRedirect(e){return await Th(Js(this.auth)),_l(this._delegate,e,kh)}sendEmailVerification(e){return ao(this._delegate,e)}async unlink(e){return await za(this._delegate,e),this}updateEmail(e){return t=this._delegate,e=e,h((r=w(t)).auth.app)?Promise.reject($i(r.auth)):ho(r,e,null);var t,r}updatePassword(e){return ho(w(this._delegate),null,e)}updatePhoneNumber(e){return(async(e,t)=>{var r=w(e);if(h(r.auth.app))return Promise.reject($i(r.auth));await Ka(r,t)})(this._delegate,e)}updateProfile(e){return lo(this._delegate,e)}verifyBeforeUpdateEmail(e,t){return oo(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}}xh.USER_MAP=new WeakMap;let Oh=m;class Lh{constructor(e,t){var r,n;this.app=e,t.isInitialized()?this._delegate=t.getImmediate():(r=e.options.apiKey,Oh(r,"invalid-api-key",{appName:e.name}),Oh(r,"invalid-api-key",{appName:e.name}),n="undefined"!=typeof window?kh:void 0,this._delegate=t.initialize({options:{persistence:((e,t)=>{var r=((e,t)=>{var r=Eh();if(!r)return[];var n=Ls(Ih,e,t);switch(r.getItem(n)){case wh.NONE:return[Os];case wh.LOCAL:return[zo,Ao];case wh.SESSION:return[Ao];default:return[]}})(e,t);if("undefined"==typeof self||r.includes(zo)||r.push(zo),"undefined"!=typeof window)for(var n of[ko,Ao])r.includes(n)||r.push(n);return r.includes(Os)||r.push(Os),r})(r,e.name),popupRedirectResolver:n}}),this._delegate._updateErrorMap(qi)),this.linkUnderlyingAuth()}get emulatorConfig(){return this._delegate.emulatorConfig}get currentUser(){return this._delegate.currentUser?xh.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){ua(this._delegate,e,t)}applyActionCode(e){return no(this._delegate,e)}checkActionCode(e){return io(this._delegate,e)}confirmPasswordReset(e,t){return(async(t,e,r)=>{await fa(w(t),{oobCode:e,newPassword:r}).catch(async e=>{throw"auth/password-does-not-meet-requirements"===e.code&&ro(t),e})})(this._delegate,e,t)}async createUserWithEmailAndPassword(e,t){return Rh(this._delegate,(async(t,e,r)=>{var n,i;return h(t.app)?Promise.reject($i(t)):(i=await ha(n=Js(t),{returnSecureToken:!0,email:e,password:r,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",Fa,"EMAIL_PASSWORD_PROVIDER").catch(e=>{throw"auth/password-does-not-meet-requirements"===e.code&&ro(t),e}),i=await Ua._fromIdTokenResponse(n,"signIn",i),await n._updateCurrentUser(i.user),i)})(this._delegate,e,t))}fetchProvidersForEmail(e){return this.fetchSignInMethodsForEmail(e)}fetchSignInMethodsForEmail(e){return so(this._delegate,e)}isSignInWithEmailLink(e){return this._delegate,e=e,"EMAIL_SIGNIN"===(null==(t=ka.parseLink(e))?void 0:t.operation);var t}async getRedirectResult(){Oh(_h(),this._delegate,"operation-not-supported-in-this-environment");e=this._delegate,t=kh,await Js(e)._initializationPromise;var e,t,r=await wl(e,t,!1);return r?Rh(this._delegate,Promise.resolve(r)):{credential:null,user:null}}addFrameworkForLogging(e){Js(this._delegate)._logFramework(e)}onAuthStateChanged(e,t,r){var{next:n,error:i,complete:s}=Mh(e,t,r);return this._delegate.onAuthStateChanged(n,i,s)}onIdTokenChanged(e,t,r){var{next:n,error:i,complete:s}=Mh(e,t,r);return this._delegate.onIdTokenChanged(n,i,s)}sendSignInLinkToEmail(e,t){return(async(e,t,r)=>{let n=Js(e);var i={requestType:"EMAIL_SIGNIN",email:t,clientType:"CLIENT_TYPE_WEB"};e=i,m((t=r).handleCodeInApp,n,"argument-error"),t&&to(n,e,t),await ha(n,i,"getOobCode",ya,"EMAIL_PASSWORD_PROVIDER")})(this._delegate,e,t)}sendPasswordResetEmail(e,t){return(async(e,t,r)=>{var n=Js(e),i={requestType:"PASSWORD_RESET",email:t,clientType:"CLIENT_TYPE_WEB"};r&&to(n,i,r),await ha(n,i,"getOobCode",_a,"EMAIL_PASSWORD_PROVIDER")})(this._delegate,e,t||void 0)}async setPersistence(e){var t,r;t=this._delegate,r=e,bh(Object.values(wh).includes(r),t,"invalid-persistence-type"),se()?bh(r!==wh.SESSION,t,"unsupported-persistence-type"):re()?bh(r===wh.NONE,t,"unsupported-persistence-type"):vh()?bh(r===wh.NONE||r===wh.LOCAL&&he(),t,"unsupported-persistence-type"):bh(r===wh.NONE||mh(),t,"unsupported-persistence-type");let n;switch(e){case wh.SESSION:n=Ao;break;case wh.LOCAL:var i=await Ds(zo)._isAvailable();n=i?zo:ko;break;case wh.NONE:n=Os;break;default:return Wi("argument-error",{appName:this._delegate.name})}return this._delegate.setPersistence(n)}signInAndRetrieveDataWithCredential(e){return this.signInWithCredential(e)}signInAnonymously(){return Rh(this._delegate,(async e=>{var t,r;return h(e.app)?Promise.reject($i(e)):(await(t=Js(e))._initializationPromise,null!=(r=t.currentUser)&&r.isAnonymous?new Ua({user:t.currentUser,providerId:null,operationType:"signIn"}):(r=await Fa(t,{returnSecureToken:!0}),r=await Ua._fromIdTokenResponse(t,"signIn",r,!0),await t._updateCurrentUser(r.user),r))})(this._delegate))}signInWithCredential(e){return Rh(this._delegate,$a(this._delegate,e))}signInWithCustomToken(e){return Rh(this._delegate,Ja(this._delegate,e))}signInWithEmailAndPassword(e,t){return Rh(this._delegate,(r=this._delegate,e=e,t=t,h(r.app)?Promise.reject($i(r)):$a(w(r),Sa.credential(e,t)).catch(async e=>{throw"auth/password-does-not-meet-requirements"===e.code&&ro(r),e})));var r}signInWithEmailLink(e,t){return Rh(this._delegate,(async(e,t,r)=>{var n,i;return h(e.app)?Promise.reject($i(e)):(n=w(e),m((i=Sa.credentialWithLink(t,r||Zi()))._tenantId===(n.tenantId||null),n,"tenant-id-mismatch"),$a(n,i))})(this._delegate,e,t))}signInWithPhoneNumber(e,t){return Ph(this._delegate,(async(e,t,r)=>{if(h(e.app))return Promise.reject($i(e));let n=Js(e);var i=await Zo(n,t,w(r));return new Xo(i,e=>$a(n,e))})(this._delegate,e,t))}async signInWithPopup(e){return Oh(_h(),this._delegate,"operation-not-supported-in-this-environment"),Rh(this._delegate,(async(e,t,r)=>{var n,i;return h(e.app)?Promise.reject(Hi(e,"operation-not-supported-in-this-environment")):(n=Js(e),Qi(e,t,Aa),i=rl(n,r),new hl(n,"signInViaPopup",t,i).executeNotNull())})(this._delegate,e,kh))}async signInWithRedirect(e){return Oh(_h(),this._delegate,"operation-not-supported-in-this-environment"),await Th(this._delegate),vl(this._delegate,e,kh)}updateCurrentUser(e){return this._delegate.updateCurrentUser(e)}verifyPasswordResetCode(e){return(async(e,t)=>{var r=(await io(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 Mh(e,t,r){let n=e,i=("function"!=typeof e&&({next:n,error:t,complete:r}=e),n);return{next:e=>i(e&&xh.getOrCreate(e)),error:t,complete:r}}Lh.Persistence=wh;class Fh{static credential(e,t){return tl.credential(e,t)}constructor(){this.providerId="phone",this._delegate=new tl(Sh(tr.auth()))}verifyPhoneNumber(e,t){return this._delegate.verifyPhoneNumber(e,t)}unwrap(){return this._delegate}}Fh.PHONE_SIGN_IN_METHOD=tl.PHONE_SIGN_IN_METHOD,Fh.PROVIDER_ID=tl.PROVIDER_ID;let Uh=m;class Vh{constructor(e,t,r=tr.app()){var n;Uh(null==(n=r.options)?void 0:n.apiKey,"invalid-api-key",{appName:r.name}),this._delegate=new Jo(r.auth(),e,t),this.type=this._delegate.type}clear(){this._delegate.clear()}render(){return this._delegate.render()}verify(){return this._delegate.verify()}}(t=tr).INTERNAL.registerComponent(new u("auth-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),r=e.getProvider("auth");return new Lh(t,r)},"PUBLIC").setServiceProps({ActionCodeInfo:{Operation:{EMAIL_SIGNIN:Ui.EMAIL_SIGNIN,PASSWORD_RESET:Ui.PASSWORD_RESET,RECOVER_EMAIL:Ui.RECOVER_EMAIL,REVERT_SECOND_FACTOR_ADDITION:Ui.REVERT_SECOND_FACTOR_ADDITION,VERIFY_AND_CHANGE_EMAIL:Ui.VERIFY_AND_CHANGE_EMAIL,VERIFY_EMAIL:Ui.VERIFY_EMAIL}},EmailAuthProvider:Sa,FacebookAuthProvider:Pa,GithubAuthProvider:xa,GoogleAuthProvider:Da,OAuthProvider:Ra,SAMLAuthProvider:La,PhoneAuthProvider:Fh,PhoneMultiFactorGenerator:Yl,RecaptchaVerifier:Vh,TwitterAuthProvider:Ma,Auth:Lh,AuthCredential:pa,Error:de}).setInstantiationMode("LAZY").setMultipleInstances(!1)),t.registerVersion("@firebase/auth-compat","0.5.18");let qh="@firebase/database",jh="";function Bh(e){jh=e}class zh{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),me(t))}get(e){var t=this.domStorage_.getItem(this.prefixedName_(e));return null==t?null:ge(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}class Kh{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){null==t?delete this.cache_[e]:this.cache_[e]=t}get(e){return _e(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}function Wh(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 zh(t)}catch(e){}return new Kh}var Hh;function Gh(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 Se,t=(r.update(t),r.digest());return s.encodeByteArray(t)}function $h(t){return function(...e){lu(t,...e)}}function Qh(...e){var t="FIREBASE INTERNAL ERROR: "+iu(...e);ru.error(t)}function Yh(e,t){return e===t?0:e<t?-1:1}function Jh(e,t){if(t&&e in t)return t[e];throw new Error("Missing required key ("+e+") in object: "+me(t))}function Xh(e){if("object"!=typeof e||null===e)return me(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+me(r[i])+":")+Xh(e[r[i]]);return n+="}"}function Zh(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 eu=Wh("localStorage"),tu=Wh("sessionStorage"),ru=new $e("@firebase/database"),nu=(()=>{let e=1;return function(){return e++}})(),iu=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+=iu.apply(null,r):t+="object"==typeof r?me(r):r,t+=" "}return t},su=null,au=!0,ou=function(e,t){g(!t||!0===e||!1===e,"Can't turn on custom loggers persistently."),!0===e?(ru.logLevel=c.VERBOSE,su=ru.log.bind(ru),t&&tu.set("logging_enabled",!0)):"function"==typeof e?su=e:(su=null,tu.remove("logging_enabled"))},lu=function(...e){var t;!0===au&&(au=!1,null===su)&&!0===tu.get("logging_enabled")&&ou(!0),su&&(t=iu.apply(null,e),su(t))},hu=function(...e){var t="FIREBASE FATAL ERROR: "+iu(...e);throw ru.error(t),new Error(t)},uu=function(...e){var t="FIREBASE WARNING: "+iu(...e);ru.warn(t)},cu=function(){"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&uu("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().")},du=function(e){return"number"==typeof e&&(e!=e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY)},pu="[MIN_NAME]",fu="[MAX_NAME]",gu=function(e,t){var r,n;return e===t?0:e===pu||t===fu?-1:t===pu||e===fu?1:(r=_u(e),n=_u(t),null!==r?null!==n?r-n==0?e.length-t.length:r-n:-1:null===n&&e<t?-1:1)};function mu(e,t){for(var r in e)e.hasOwnProperty(r)&&t(r,e[r])}function vu(e){g(!du(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 _u(e){if(wu.test(e)){var t=Number(e);if(t>=bu&&t<=Iu)return t}return null}function yu(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 wu=new RegExp("^-?(0*)\\d{1,10}$"),bu=-2147483648,Iu=2147483647,Tu=function(e){try{e()}catch(t){setTimeout(()=>{var e=t.stack||"";throw uu("Exception was thrown by user callback.",e),t},Math.floor(0))}};class Eu{constructor(e,t){this.appCheckProvider=t,this.appName=e.name,h(e)&&e.settings.appCheckToken&&(this.serverAppAppCheckToken=e.settings.appCheckToken),this.appCheck=null==t?void 0:t.getImmediate({optional:!0}),this.appCheck||null!=t&&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){var e;null!=(e=this.appCheckProvider)&&e.get().then(e=>e.addTokenListener(t))}notifyForInvalidToken(){uu(`Provided AppCheck credentials for the app named "${this.appName}" `+"are invalid. This usually indicates your app was not initialized correctly.")}}class Cu{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?(lu("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/.',uu(e)}}class ku{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}ku.OWNER="owner";let Su=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,Au="websocket",Nu="long_polling";class Ru{constructor(e,t,r,n,i=!1,s="",a=!1,o=!1){this.secure=t,this.namespace=r,this.webSocketOnly=n,this.nodeAdmin=i,this.persistenceKey=s,this.includeNamespaceInQueryParams=a,this.isUsingEmulator=o,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=eu.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())&&eu.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 Pu(e,t,r){g("string"==typeof t,"typeof type must == string"),g("object"==typeof r,"typeof params must == object");let n;if(t===Au)n=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?";else{if(t!==Nu)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 mu(r,(e,t)=>{i.push(e+"="+t)}),n+i.join("&")}class Du{constructor(){this.counters_={}}incrementCounter(e,t=1){_e(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return K(void 0,this.counters_)}}let xu={},Ou={};function Lu(e){var t=e.toString();return xu[t]||(xu[t]=new Du),xu[t]}class Mu{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]&&Tu(()=>{this.onMessage_(e[t])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}class Fu{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_=$h(e),this.stats_=Lu(t),this.urlFn=e=>(this.appCheckToken&&(e.ac=this.appCheckToken),Pu(t,Nu,e))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new Mu(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 Uu((...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&&Su.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(){Fu.forceAllow_=!0}static forceDisallow(){Fu.forceDisallow_=!0}static isAvailable(){return!!Fu.forceAllow_||!(Fu.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=me(e),t=(this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length),a(t)),r=Zh(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=me(e).length;this.bytesReceived+=t,this.stats_.incrementCounter("bytes_received",t)}}class Uu{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=nu(),window["pLPCommand"+this.uniqueCallbackIdentifier]=t,window["pRTLPCB"+this.uniqueCallbackIdentifier]=r,this.myIFrame=Uu.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){lu("frame writing exception"),e.stack&&lu(e.stack),lu(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||lu("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=()=>{lu("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(t)}}catch(e){}},Math.floor(1))}}let Vu=null;"undefined"!=typeof MozWebSocket?Vu=MozWebSocket:"undefined"!=typeof WebSocket&&(Vu=WebSocket);class qu{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_=$h(this.connId),this.stats_=Lu(t),this.connURL=qu.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&&Su.test(location.hostname)&&(s.r="f"),t&&(s.s=t),r&&(s.ls=r),n&&(s.ac=n),i&&(s.p=i),Pu(e,Au,s)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,eu.set("previous_websocket_failure",!0);try{oe(),this.mySock=new Vu(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(){qu.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!==Vu&&!qu.forceDisallow_}static previouslyFailed(){return eu.isInMemoryStorage||!0===eu.get("previous_websocket_failure")}markConnectionHealthy(){eu.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=ge(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=me(e),r=(this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length),Zh(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)}}}qu.responsesRequiredToBeHealthy=2,qu.healthyTimeout=3e4;class ju{static get ALL_TRANSPORTS(){return[Fu,qu]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}constructor(e){this.initTransports_(e)}initTransports_(e){var t=qu&&qu.isAvailable();let r=t&&!qu.previouslyFailed();if(e.webSocketOnly&&(t||uu("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),r=!0),r)this.transports_=[qu];else{var n,i=this.transports_=[];for(n of ju.ALL_TRANSPORTS)n&&n.isAvailable()&&i.push(n);ju.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}}ju.globalTransportInitialized_=!1;class Bu{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_=$h("c:"+this.id+":"),this.transportManager_=new ju(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_=yu(()=>{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=Jh("t",e),r=Jh("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=Jh("t",e),r=Jh("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=Jh("t",e);if("d"in e){var r=e.d;if("h"===t){var n=Object.assign({},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?Qh("Server Error: "+r):"o"===t?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):Qh("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&&uu("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),yu(()=>{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):yu(()=>{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()&&(eu.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 zu{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 Ku{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 Wu extends Ku{static getInstance(){return new Wu}constructor(){super(["online"]),this.online_=!0,"undefined"==typeof window||void 0===window.addEventListener||te()||(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 Hu=32,Gu=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 $u(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 Qu(e){return e.pieceNum_<e.pieces_.length?e.pieces_[e.pieces_.length-1]:null}function Yu(e,t=0){return e.pieces_.slice(e.pieceNum_+t)}function Ju(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 Xu(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 Zu(e,t){var r=_(e),n=_(t);if(null===r)return t;if(r===n)return Zu(y(e),y(t));throw new Error("INTERNAL ERROR: innerPath ("+t+") is not within outerPath ("+e+")")}function ec(e,t){var r=Yu(e,0),n=Yu(t,0);for(let s=0;s<r.length&&s<n.length;s++){var i=gu(r[s],n[s]);if(0!==i)return i}return r.length===n.length?0:r.length<n.length?-1:1}function tc(e,t){if($u(e)!==$u(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 rc(e,t){let r=e.pieceNum_,n=t.pieceNum_;if($u(e)>$u(t))return!1;for(;r<e.pieces_.length;){if(e.pieces_[r]!==t.pieces_[n])return!1;++r,++n}return!0}class nc{constructor(e,t){this.errorPrefix_=t,this.parts_=Yu(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let r=0;r<this.parts_.length;r++)this.byteLength_+=Oe(this.parts_[r]);ic(this)}}function ic(e){if(e.byteLength_>Gu)throw new Error(e.errorPrefix_+"has a key path longer than "+Gu+" bytes ("+e.byteLength_+").");if(e.parts_.length>Hu)throw new Error(e.errorPrefix_+"path specified exceeds the maximum depth that can be written ("+Hu+") or object contains a cycle "+sc(e))}function sc(e){return 0===e.parts_.length?"":"in property '"+e.parts_.join(".")+"'"}class ac extends Ku{static getInstance(){return new ac}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 oc extends zu{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=oc.nextPersistentConnectionId_++,this.log_=$h("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&&!oe())throw new Error("Auth override specified in options, but not supported on non Node.js platforms");ac.getInstance().on("visible",this.onVisible_,this),-1===e.host.indexOf("fblocal")&&Wu.getInstance().on("online",this.onOnline_,this)}sendRequest(e,t,r){var n=++this.requestNumber_,i={r:n,a:e,b:t};this.log_(me(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 X;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=(oc.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&&_e(e,"w")&&(r=ye(e,"w"),Array.isArray(r))&&~r.indexOf("no_index")&&(r='".indexOn": "'+t._queryParams.getIndex().toString()+'"',n=t._path.toString(),uu("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=ve(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=ve(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: "+me(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):Qh("Unrecognized action received from server: "+me(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+":"+oc.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,u]=await Promise.all([this.authTokenProvider_.getToken(l),this.appCheckTokenProvider_.getToken(l)]);t?lu("getToken() completed but was canceled"):(lu("getToken() completed. Creating connection."),this.authToken_=h&&h.accessToken,this.appCheckToken_=u&&u.token,r=new Bu(s,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,n,i,e,e=>{uu(e+" ("+this.repoInfo_.toString()+")"),this.interrupt("server_kill")},a))}catch(e){this.log_("Failed to get token: "+e),t||(this.repoInfo_.nodeAdmin&&uu(e),o())}}}interrupt(e){lu("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){lu("Resuming connection for reason: "+e),delete this.interruptReasons_[e],we(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=>Xh(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){lu("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){lu("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."+jh.replace(/\./g,"-")]=1,te()?e["framework.cordova"]=1:se()&&(e["framework.reactnative"]=1),this.reportStats(e)}shouldReconnect_(){var e=Wu.getInstance().currentlyOnline();return we(this.interruptReasons_)&&e}}oc.nextPersistentConnectionId_=0,oc.nextConnectionId_=0;class p{constructor(e,t){this.name=e,this.node=t}static Wrap(e,t){return new p(e,t)}}class lc{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,t){var r=new p(pu,e),n=new p(pu,t);return 0!==this.compare(r,n)}minPost(){return p.MIN}}let hc;class uc extends lc{static get __EMPTY_NODE(){return hc}static set __EMPTY_NODE(e){hc=e}compare(e,t){return gu(e.name,t.name)}isDefinedOn(e){throw j("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,t){return!1}minPost(){return p.MIN}maxPost(){return new p(fu,hc)}makePost(e,t){return g("string"==typeof e,"KeyIndex indexValue must always be a string."),new p(e,hc)}toString(){return".key"}}let cc=new uc;class dc{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 pc{constructor(e,t,r,n,i){this.key=e,this.value=t,this.color=null!=r?r:pc.RED,this.left=null!=n?n:gc.EMPTY_NODE,this.right=null!=i?i:gc.EMPTY_NODE}copy(e,t,r,n,i){return new pc(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 gc.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 gc.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,pc.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){var e=this.copy(null,null,pc.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)}}pc.RED=!0,pc.BLACK=!1;class fc{copy(e,t,r,n,i){return this}insert(e,t,r){return new pc(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 gc{constructor(e,t=gc.EMPTY_NODE){this.comparator_=e,this.root_=t}insert(e,t){return new gc(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,pc.BLACK,null,null))}remove(e){return new gc(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,pc.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 dc(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new dc(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new dc(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new dc(this.root_,null,this.comparator_,!0,e)}}function mc(e,t){return gu(e.name,t.name)}function vc(e,t){return gu(e,t)}gc.EMPTY_NODE=new fc;let _c;function yc(e){return"number"==typeof e?"number:"+vu(e):"string:"+e}function wc(e){var t;e.isLeafNode()?(t=e.val(),g("string"==typeof t||"number"==typeof t||"object"==typeof t&&_e(t,".sv"),"Priority must be a string or number.")):g(e===_c||e.isEmpty(),"priority of unexpected type."),g(e===_c||e.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")}let bc;class Ic{static set __childrenNodeConstructor(e){bc=e}static get __childrenNodeConstructor(){return bc}constructor(e,t=Ic.__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."),wc(this.priorityNode_)}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new Ic(this.value_,e)}getImmediateChild(e){return".priority"===e?this.priorityNode_:Ic.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return b(e)?this:".priority"===_(e)?this.priorityNode_:Ic.__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:Ic.__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===$u(e),".priority must be the last token in a path"),this.updateImmediateChild(r,Ic.__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:"+yc(this.priorityNode_.val())+":");var t=typeof this.value_;e=(e+=t+":")+("number"==t?vu(this.value_):this.value_),this.lazyHash_=Gh(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===Ic.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof Ic.__childrenNodeConstructor?-1:(g(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){var t=typeof e.value_,r=typeof this.value_,n=Ic.VALUE_TYPE_ORDER.indexOf(t),i=Ic.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_)}}Ic.VALUE_TYPE_ORDER=["object","boolean","number","string"];let Tc,Ec;class Cc extends lc{compare(e,t){var r=e.node.getPriority(),n=t.node.getPriority(),r=r.compareTo(n);return 0===r?gu(e.name,t.name):r}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return p.MIN}maxPost(){return new p(fu,new Ic("[PRIORITY-POST]",Ec))}makePost(e,t){var r=Tc(e);return new p(t,new Ic("[PRIORITY-POST]",r))}toString(){return".priority"}}let I=new Cc,kc=Math.log(2);class Sc{constructor(e){this.count=(t=e+1,parseInt(Math.log(t)/kc,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 Ac(l,e,h,t){l.sort(e);let u=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 pc(a,s.node,pc.BLACK,null,null)):(i=parseInt(i/2,10)+e,r=u(e,i),n=u(i+1,t),s=l[i],a=h?h(s):s,new pc(a,s.node,pc.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,u(1+r,n)),r=l[r],i=h?h(r):r,e=new pc(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,pc.BLACK):(t(n,pc.BLACK),t(n,pc.RED))}return a})(new Sc(l.length));return new gc(t||e,r)}let Nc,Rc={};class Pc{static get Default(){return g((Rc,I),"ChildrenNode.ts has not been loaded"),Nc=Nc||new Pc({".priority":Rc},{".priority":I})}constructor(e,t){this.indexes_=e,this.indexSet_=t}get(e){var t=ye(this.indexes_,e);if(t)return t instanceof gc?t:null;throw new Error("No index defined for "+e)}hasIndex(e){return _e(this.indexSet_,e.toString())}addIndex(e,t){g(e!==cc,"KeyIndex always exists and isn't meant to be added to the IndexMap.");var r=[];let n=!1;var i=t.getIterator(p.Wrap);let s=i.getNext();for(;s;)n=n||e.isDefinedOn(s.node),r.push(s),s=i.getNext();let a;a=n?Ac(r,e.getCompare()):Rc;var o=e.toString(),l=Object.assign({},this.indexSet_),h=(l[o]=e,Object.assign({},this.indexes_));return h[o]=a,new Pc(h,l)}addToIndexes(s,a){var e=be(this.indexes_,(t,e)=>{var r=ye(this.indexSet_,e);if(g(r,"Missing index implementation for "+e),t===Rc){if(r.isDefinedOn(s.node)){var n=[],i=a.getIterator(p.Wrap);let e=i.getNext();for(;e;)e.name!==s.name&&n.push(e),e=i.getNext();return n.push(s),Ac(n,r.getCompare())}return Rc}{r=a.get(s.name);let e=t;return(e=r?e.remove(new p(s.name,r)):e).insert(s,s.node)}});return new Pc(e,this.indexSet_)}removeFromIndexes(r,n){var e=be(this.indexes_,e=>{var t;return e!==Rc&&(t=n.get(r.name))?e.remove(new p(r.name,t)):e});return new Pc(e,this.indexSet_)}}let Dc;class T{static get EMPTY_NODE(){return Dc=Dc||new T(new gc(vc),null,Pc.Default)}constructor(e,t,r){this.children_=e,this.priorityNode_=t,this.indexMap_=r,this.lazyHash_=null,this.priorityNode_&&wc(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_||Dc}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))?Dc: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 p(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()?Dc:this.priorityNode_;return new T(e,i,t)}}updateChild(e,t){var r,n=_(e);return null===n?t:(g(".priority"!==_(e)||1===$u(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:"+yc(this.getPriority().val())+":"),this.forEachChild(I,(e,t)=>{var r=t.hash();""!==r&&(n+=":"+e+":"+r)}),this.lazyHash_=""===n?"":Gh(n)}return this.lazyHash_}getPredecessorChildName(e,t,r){var n=this.resolveIndex_(r);return n?(n=n.getPredecessorKey(new p(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 p(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 p(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,p.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,p.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===Oc?-1:0}withIndex(e){var t;return e===cc||this.indexMap_.hasIndex(e)?this:(t=this.indexMap_.addIndex(e,this.children_),new T(this.children_,this.priorityNode_,t))}isIndexed(e){return e===cc||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===cc?null:this.indexMap_.get(e.toString())}}T.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;class xc extends T{constructor(){super(new gc(vc),T.EMPTY_NODE,Pc.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 Oc=new xc,Lc=(Object.defineProperties(p,{MIN:{value:new p(pu,T.EMPTY_NODE)},MAX:{value:new p(fu,Oc)}}),uc.__EMPTY_NODE=T.EMPTY_NODE,Ic.__childrenNodeConstructor=T,t=Oc,_c=t,t=Oc,Ec=t,!0);function Mc(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 Ic(t,Mc(e));if(s instanceof Array||!Lc){let n=T.EMPTY_NODE;return mu(s,(e,t)=>{var r;!_e(s,e)||"."===e.substring(0,1)||!(r=Mc(t)).isLeafNode()&&r.isEmpty()||(n=n.updateImmediateChild(e,r))}),n.updatePriority(Mc(e))}{let n=[],i=!1;return mu(s,(e,t)=>{var r;"."===e.substring(0,1)||(r=Mc(t)).isEmpty()||(i=i||!r.getPriority().isEmpty(),n.push(new p(e,r)))}),0===n.length?T.EMPTY_NODE:(t=Ac(n,mc,e=>e.name,vc),i?(r=Ac(n,I.getCompare()),new T(t,Mc(e),new Pc({".priority":r},{".priority":I}))):new T(t,Mc(e),Pc.Default))}}Tc=Mc;class Fc extends lc{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?gu(e.name,t.name):r}makePost(e,t){var r=Mc(e),r=T.EMPTY_NODE.updateChild(this.indexPath_,r);return new p(t,r)}maxPost(){var e=T.EMPTY_NODE.updateChild(this.indexPath_,Oc);return new p(fu,e)}toString(){return Yu(this.indexPath_,0).join("/")}}class Uc extends lc{compare(e,t){var r=e.node.compareTo(t.node);return 0===r?gu(e.name,t.name):r}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return p.MIN}maxPost(){return p.MAX}makePost(e,t){var r=Mc(e);return new p(t,r)}toString(){return".value"}}let Vc=new Uc;function qc(e){return{type:"value",snapshotNode:e}}function jc(e,t){return{type:"child_added",snapshotNode:t,childName:e}}function Bc(e,t){return{type:"child_removed",snapshotNode:t,childName:e}}function zc(e,t,r){return{type:"child_changed",snapshotNode:t,childName:e,oldSnap:r}}class Kc{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(Bc(t,a)):g(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):a.isEmpty()?s.trackChildChange(jc(t,r)):s.trackChildChange(zc(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(Bc(e,t))}),r.isLeafNode()||r.forEachChild(I,(e,t)=>{var r;n.hasChild(e)?(r=n.getImmediateChild(e)).equals(t)||i.trackChildChange(zc(e,t,r)):i.trackChildChange(jc(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 Wc{constructor(e){this.indexedFilter_=new Kc(e.getIndex()),this.index_=e.getIndex(),this.startPost_=Wc.getStartPost_(e),this.endPost_=Wc.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 p(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 p(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 Hc{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 Wc(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 p(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 p(t,r)),l=this.reverse_?a.getFirstChild(this.index_):a.getLastChild(this.index_),h=this.rangedFilter_.matches(o);if(a.hasChild(t)){var u=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 c=null==e?1:s(e,o);return h&&!r.isEmpty()&&0<=c?(null!=i&&i.trackChildChange(zc(t,r,u)),a.updateImmediateChild(t,r)):(null!=i&&i.trackChildChange(Bc(t,u)),c=a.updateImmediateChild(t,T.EMPTY_NODE),null!=e&&this.rangedFilter_.matches(e)?(null!=i&&i.trackChildChange(jc(e.name,e.node)),c.updateImmediateChild(e.name,e.node)):c)}return!r.isEmpty()&&h&&0<=s(l,o)?(null!=i&&(i.trackChildChange(Bc(l.name,l.node)),i.trackChildChange(jc(t,r))),a.updateImmediateChild(t,r).updateImmediateChild(l.name,T.EMPTY_NODE)):e}}class Gc{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_:pu}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_:fu}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 Gc;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 $c(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 Qc(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 Yc(e,t){var r=e.copy();return r.index_=t,r}function Jc(t){var r,n={};if(!t.isDefault()){let e;e=t.index_===I?"$priority":t.index_===Vc?"$value":t.index_===cc?"$key":(g(t.index_ instanceof Fc,"Unrecognized index type!"),t.index_.toString()),n.orderBy=me(e),t.startSet_&&(n[r=t.startAfterSet_?"startAfter":"startAt"]=me(t.indexStartValue_),t.startNameSet_)&&(n[r]+=","+me(t.indexStartName_)),t.endSet_&&(n[r=t.endBeforeSet_?"endBefore":"endAt"]=me(t.indexEndValue_),t.endNameSet_)&&(n[r]+=","+me(t.indexEndName_)),t.limitSet_&&(t.isViewFromLeft()?n.limitToFirst=t.limit_:n.limitToLast=t.limit_)}return n}function Xc(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 Zc extends zu{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_=$h("p:rest:"),this.listens_={}}listen(e,t,n,i){let s=e._path.toString(),a=(this.log_("Listen called for "+s+" "+e._queryIdentifier),Zc.getListenId_(e,n)),o={};this.listens_[a]=o;var r=Jc(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),ye(this.listens_,a)===o){let e;e=t?401===t?"permission_denied":"rest_error:"+t:"ok",i(e,null)}})}unlisten(e,t){var r=Zc.getListenId_(e,t);delete this.listens_[r]}get(e){var t=Jc(e._queryParams);let n=e._path.toString(),i=new X;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+Ee(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=ge(n.responseText)}catch(e){uu("Failed to parse JSON response for "+r+": "+n.responseText)}a(null,e)}else 401!==n.status&&404!==n.status&&uu("Got unsuccessful REST response for "+r+" Status: "+n.status),a(n.status);a=null}},n.open("GET",r,!0),n.send()})}}class ed{constructor(){this.rootNode_=T.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}function td(){return{value:null,children:new Map}}function rd(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,td()),rd(e.children.get(n),t=y(t),r))}function nd(e,r,n){var i;null!==e.value?n(r,e.value):(i=(e,t)=>{nd(t,new f(r.toString()+"/"+e),n)},e.children.forEach((e,t)=>{i(t,e)}))}class id{constructor(e){this.collection_=e,this.last_=null}get(){var e=this.collection_.get();let r=Object.assign({},e);return this.last_&&mu(this.last_,(e,t)=>{r[e]=r[e]-t}),this.last_=e,r}}class sd{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new id(e);var r=1e4+2e4*Math.random();yu(this.reportStats_.bind(this),Math.floor(r))}reportStats_(){var e=this.statsListener_.get();let r={},n=!1;mu(e,(e,t)=>{0<t&&_e(this.statsToReport_,e)&&(r[e]=t,n=!0)}),n&&this.server_.reportStats(r),yu(this.reportStats_.bind(this),Math.floor(2*Math.random()*3e5))}}function ad(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function od(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function ld(e){return{fromUser:!1,fromServer:!0,queryId:e,tagged:!0}}(t=Hh=Hh||{})[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 hd{constructor(e,t,r){this.path=e,this.affectedTree=t,this.revert=r,this.type=Hh.ACK_USER_WRITE,this.source=ad()}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 hd(v(),t,this.revert)):(g(_(this.path)===e,"operationForChild called for unrelated child."),new hd(y(this.path),this.affectedTree,this.revert))}}class ud{constructor(e,t){this.source=e,this.path=t,this.type=Hh.LISTEN_COMPLETE}operationForChild(e){return b(this.path)?new ud(this.source,v()):new ud(this.source,y(this.path))}}class cd{constructor(e,t,r){this.source=e,this.path=t,this.snap=r,this.type=Hh.OVERWRITE}operationForChild(e){return b(this.path)?new cd(this.source,v(),this.snap.getImmediateChild(e)):new cd(this.source,y(this.path),this.snap)}}class dd{constructor(e,t,r){this.source=e,this.path=t,this.children=r,this.type=Hh.MERGE}operationForChild(e){var t;return b(this.path)?(t=this.children.subtree(new f(e))).isEmpty()?null:t.value?new cd(this.source,v(),t.value):new dd(this.source,v(),t):(g(_(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new dd(this.source,y(this.path),this.children))}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}class pd{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 fd{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function gd(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}))}),md(r,i,"child_removed",e,n,t),md(r,i,"child_added",e,n,t),md(r,i,"child_moved",s,n,t),md(r,i,"child_changed",e,n,t),md(r,i,"value",e,n,t),i}function md(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 j("Should only compare child_ events.");var n=new p(e.childName,e.snapshotNode),i=new p(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 vd(e,t){return{eventCache:e,serverCache:t}}function _d(e,t,r,n){return vd(new pd(t,r,n),e.serverCache)}function yd(e,t,r,n){return vd(e.eventCache,new pd(t,r,n))}function wd(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function bd(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}let Id;class E{static fromObject(e){let r=new E(null);return mu(e,(e,t)=>{r=r.set(new f(e),t)}),r}constructor(e,t=Id=Id||new gc(Yh)){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:Xu(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 E(null))}set(e,t){var r,n;return b(e)?new E(t,this.children):(n=_(e),r=(this.children.get(n)||new E(null)).set(y(e),t),n=this.children.insert(n,r),new E(this.value,n))}remove(t){if(b(t))return this.children.isEmpty()?new E(null):new E(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 E(null):new E(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 E(null)).setTree(y(t),r);let e;return e=i.isEmpty()?this.children.remove(n):this.children.insert(n,i),new E(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_(Xu(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),Xu(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),Xu(t,n),r):new E(null))}foreach(e){this.foreach_(v(),e)}foreach_(r,n){this.children.inorderTraversal((e,t)=>{t.foreach_(Xu(r,e),n)}),this.value&&n(r,this.value)}foreachChild(r){this.children.inorderTraversal((e,t)=>{t.value&&r(e,t.value)})}}class Td{constructor(e){this.writeTree_=e}static empty(){return new Td(new E(null))}}function Ed(t,r,n){if(b(r))return new Td(new E(n));var i=t.writeTree_.findRootMostValueAndPath(r);if(null==i)return s=new E(n),s=t.writeTree_.setTree(r,s),new Td(s);{var s=i.path;let e=i.value;i=Zu(s,r);return e=e.updateChild(i,n),new Td(t.writeTree_.set(s,e))}}function Cd(e,r,t){let n=e;return mu(t,(e,t)=>{n=Ed(n,Xu(r,e),t)}),n}function kd(e,t){var r;return b(t)?Td.empty():(r=e.writeTree_.setTree(t,new E(null)),new Td(r))}function Sd(e,t){return null!=Ad(e,t)}function Ad(e,t){var r=e.writeTree_.findRootMostValueAndPath(t);return null!=r?e.writeTree_.get(r.path).getChild(Zu(r.path,t)):null}function Nd(e){let r=[];var t=e.writeTree_.value;return null!=t?t.isLeafNode()||t.forEachChild(I,(e,t)=>{r.push(new p(e,t))}):e.writeTree_.children.inorderTraversal((e,t)=>{null!=t.value&&r.push(new p(e,t.value))}),r}function Rd(e,t){var r;return b(t)?e:null!=(r=Ad(e,t))?new Td(new E(r)):new Td(e.writeTree_.subtree(t))}function Pd(e){return e.writeTree_.isEmpty()}function Dd(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(Xu(i,e),t,s)}),s=s.getChild(i).isEmpty()||null===r?s:s.updateChild(Xu(i,".priority"),r)}}}(v(),e.writeTree_,t)}function xd(e,t){return Wd(t,e)}function Od(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 rc(e.path,t);for(var r in e.children)if(e.children.hasOwnProperty(r)&&rc(Xu(e.path,r),t))return 1})(l,i.path)?s=!1:rc(i.path,l.path)&&(a=!0)),o--}return!!s&&(a?((e=t).visibleWrites=Md(e.allWrites,Ld,v()),0<e.allWrites.length?e.lastWriteId=e.allWrites[e.allWrites.length-1].writeId:e.lastWriteId=-1):i.snap?t.visibleWrites=kd(t.visibleWrites,i.path):mu(i.children,e=>{t.visibleWrites=kd(t.visibleWrites,Xu(i.path,e))}),!0)}function Ld(e){return e.visible}function Md(e,t,r){let n=Td.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)rc(r,s)?(e=Zu(r,s),n=Ed(n,e,i.snap)):rc(s,r)&&(e=Zu(s,r),n=Ed(n,v(),i.snap.getChild(e)));else{if(!i.children)throw j("WriteRecord should have .snap or .children");rc(r,s)?(e=Zu(r,s),n=Cd(n,e,i.children)):rc(s,r)&&(b(e=Zu(s,r))?n=Cd(n,v(),i.children):(s=ye(i.children,_(e)))&&(i=s.getChild(y(e)),n=Ed(n,v(),i)))}}}return n}function Fd(e,t,r,n,i){var s;return n||i?(s=Rd(e.visibleWrites,t),!i&&Pd(s)?r:i||null!=r||Sd(s,v())?Dd(Md(e.allWrites,function(e){return(e.visible||i)&&(!n||!~n.indexOf(e.writeId))&&(rc(e.path,t)||rc(t,e.path))},t),r||T.EMPTY_NODE):null):null!=(s=Ad(e.visibleWrites,t))?s:Pd(s=Rd(e.visibleWrites,t))?r:null!=r||Sd(s,v())?Dd(s,r||T.EMPTY_NODE):null}function Ud(e,t,r,n){return Fd(e.writeTree,e.treePath,t,r,n)}function Vd(e,t){{var r=e.writeTree;e=e.treePath;let i=T.EMPTY_NODE;var n=Ad(r.visibleWrites,e);if(n)n.isLeafNode()||n.forEachChild(I,(e,t)=>{i=i.updateImmediateChild(e,t)});else if(t){let n=Rd(r.visibleWrites,e);t.forEachChild(I,(e,t)=>{var r=Dd(Rd(n,new f(e)),t);i=i.updateImmediateChild(e,r)}),Nd(n).forEach(e=>{i=i.updateImmediateChild(e.name,e.node)})}else Nd(Rd(r.visibleWrites,e)).forEach(e=>{i=i.updateImmediateChild(e.name,e.node)});return i}}function qd(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=Xu(e,t),Sd(i.visibleWrites,s)?null:Pd(s=Rd(i.visibleWrites,s))?n.getChild(t):Dd(s,n.getChild(t));var i,s}function jd(e,t){return r=e.writeTree,e=Xu(e.treePath,t),Ad(r.visibleWrites,e);var r}function Bd(e,r,n,i,s,a){{var o=e.writeTree,l=(e=e.treePath,n),h=i;n=s,i=a;let t;var u=Rd(o.visibleWrites,e),c=Ad(u,v());if(null!=c)t=c;else{if(null==r)return[];t=Dd(u,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 zd(e,t,r){return n=e.writeTree,r=r,i=Xu(e.treePath,e=t),null!=(s=Ad(n.visibleWrites,i))?s:r.isCompleteForChild(e)?Dd(Rd(n.visibleWrites,i),r.getNode().getImmediateChild(e)):null;var n,i,s}function Kd(e,t){return Wd(Xu(e.treePath,t),e.writeTree)}function Wd(e,t){return{treePath:e,writeTree:t}}class Hd{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,zc(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,Bc(r,n.oldSnap));else if("child_changed"===t&&"child_added"===i)this.changeMap.set(r,jc(r,e.snapshotNode));else{if("child_changed"!==t||"child_changed"!==i)throw j("Illegal combination of changes: "+e+" occurred after "+n);this.changeMap.set(r,zc(r,e.snapshotNode,n.oldSnap))}}else this.changeMap.set(r,e)}getChanges(){return Array.from(this.changeMap.values())}}let Gd=new class{getCompleteChild(e){return null}getChildAfterChild(e,t,r){return null}};class $d{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 pd(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache,zd(this.writes_,e,t))}getChildAfterChild(e,t,r){var n=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:bd(this.viewCache_),n=Bd(this.writes_,n,t,1,r,e);return 0===n.length?null:n[0]}}function Qd(e,t,r,n,i){var s=new Hd;let a,o;if(r.type===Hh.OVERWRITE){var l=r;a=l.source.fromUser?Xd(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),Jd(e,t,l.path,l.snap,n,i,o,s))}else if(r.type===Hh.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=Xu(s,e);Zd(i,_(r))&&(h=Xd(n,h,r,t,a,o,l))}),e.foreach((e,t)=>{var r=Xu(s,e);Zd(i,_(r))||(h=Xd(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(),tp(e,t,l.path,l.children,n,i,o,s))}else if(r.type===Hh.ACK_USER_WRITE){l=r;a=l.revert?((r,n,i,s,e,a)=>{let o;if(null!=jd(s,i))return n;{var l=new $d(s,n,e),h=n.eventCache.getNode();let t;if(b(i)||".priority"===_(i)){let e;e=e=n.serverCache.isFullyInitialized()?Ud(s,bd(n)):(u=n.serverCache.getNode(),g(u instanceof T,"serverChildren would be complete if leaf node"),Vd(s,u)),t=r.filter.updateFullNode(h,e,a)}else{var u=_(i);let e=zd(s,u,n.serverCache);null==e&&n.serverCache.isCompleteForChild(u)&&(e=h.getImmediateChild(u)),(t=null!=e?r.filter.updateChild(h,u,e,y(i),l,a):n.eventCache.getNode().hasChild(u)?r.filter.updateChild(h,u,T.EMPTY_NODE,y(i),l,a):h).isEmpty()&&n.serverCache.isFullyInitialized()&&(o=Ud(s,bd(n))).isLeafNode()&&(t=r.filter.updateFullNode(t,o,a))}return o=n.serverCache.isFullyInitialized()||null!=jd(s,v()),_d(n,t,o,r.filter.filtersNodes())}})(e,t,l.path,n,i,s):((e,t,i,r,s,a,o)=>{if(null!=jd(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 Jd(e,t,i,h.getNode().getChild(i),s,a,l,o);if(b(i)){let r=new E(null);return h.getNode().forEachChild(cc,(e,t)=>{r=r.set(new f(e),t)}),tp(e,t,i,r,s,a,l,o)}return t}{let n=new E(null);return r.foreach((e,t)=>{var r=Xu(i,e);h.isCompleteForPath(r)&&(n=n.set(e,h.getNode().getChild(r)))}),tp(e,t,i,n,s,a,l,o)}})(e,t,l.path,l.affectedTree,n,i,s)}else{if(r.type!==Hh.LISTEN_COMPLETE)throw j("Unknown operation type: "+r.type);a=(i=e,e=r.path,r=n,n=s,l=t.serverCache,l=yd(t,l.getNode(),l.isFullyInitialized()||b(e),l.isFiltered()),Yd(i,l,e,r,Gd,n))}var h,u,s=s.getChanges(),i=t,e=a,r=s,c=e.eventCache;return c.isFullyInitialized()&&(h=c.getNode().isLeafNode()||c.getNode().isEmpty(),u=wd(i),0<r.length||!i.eventCache.isFullyInitialized()||h&&!c.getNode().equals(u)||!c.getNode().getPriority().equals(u.getPriority()))&&r.push(qc(wd(e))),{viewCache:a,changes:s}}function Yd(n,i,s,a,o,l){var h=i.eventCache;if(null!=jd(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()?(u=Vd(a,(u=bd(i))instanceof T?u:T.EMPTY_NODE),n.filter.updateFullNode(i.eventCache.getNode(),u,l)):(u=Ud(a,bd(i)),n.filter.updateFullNode(i.eventCache.getNode(),u,l));else{var u=_(s);if(".priority"===u){g(1===$u(s),"Can't have a priority with additional path components");var c=h.getNode(),d=qd(a,s,c,r=i.serverCache.getNode());t=null!=d?n.filter.updatePriority(c,d):h.getNode()}else{c=y(s);let e;e=h.isCompleteForChild(u)?(r=i.serverCache.getNode(),null!=(d=qd(a,s,h.getNode(),r))?h.getNode().getImmediateChild(u).updateChild(c,d):h.getNode().getImmediateChild(u)):zd(a,u,i.serverCache),t=null!=e?n.filter.updateChild(h.getNode(),u,e,c,o,l):h.getNode()}}return _d(i,t,h.isFullyInitialized()||b(s),n.filter.filtersNodes())}}function Jd(e,t,r,n,i,s,a,o){var l=t.serverCache;let h;var u=a?e.filter:e.filter.getIndexedFilter();if(b(r))h=u.updateFullNode(l.getNode(),n,null);else if(u.filtersNodes()&&!l.isFiltered()){var c=l.getNode().updateChild(r,n);h=u.updateFullNode(l.getNode(),c,null)}else{c=_(r);if(!l.isCompleteForPath(r)&&1<$u(r))return t;var d=y(r),p=l.getNode().getImmediateChild(c).updateChild(d,n);h=".priority"===c?u.updatePriority(l.getNode(),p):u.updateChild(l.getNode(),c,p,d,Gd,null)}c=yd(t,h,l.isFullyInitialized()||b(r),u.filtersNodes());return Yd(e,c,r,i,new $d(i,c,s),o)}function Xd(t,r,n,i,e,s,a){var o=r.eventCache;let l,h;var u=new $d(e,r,s);if(b(n))h=t.filter.updateFullNode(r.eventCache.getNode(),i,a),l=_d(r,h,!0,t.filter.filtersNodes());else{var c=_(n);if(".priority"===c)h=t.filter.updatePriority(r.eventCache.getNode(),i),l=_d(r,h,o.isFullyInitialized(),o.isFiltered());else{var d,p=y(n),f=o.getNode().getImmediateChild(c);let e;e=b(p)?i:null!=(d=u.getCompleteChild(c))?".priority"===Qu(p)&&d.getChild(Ju(p)).isEmpty()?d:d.updateChild(p,i):T.EMPTY_NODE,l=f.equals(e)?r:_d(r,t.filter.updateChild(o.getNode(),c,e,p,u,a),o.isFullyInitialized(),t.filter.filtersNodes())}}return l}function Zd(e,t){return e.eventCache.isCompleteForChild(t)}function ep(e,r,t){return t.foreach((e,t)=>{r=r.updateChild(e,t)}),r}function tp(n,i,e,t,s,a,o,l){if(i.serverCache.getNode().isEmpty()&&!i.serverCache.isFullyInitialized())return i;let h=i,r,u=(r=b(e)?t:new E(null).setTree(e,t),i.serverCache.getNode());return r.children.inorderTraversal((e,t)=>{var r;u.hasChild(e)&&(r=ep(0,i.serverCache.getNode().getImmediateChild(e),t),h=Jd(n,h,new f(e),r,s,a,o,l))}),r.children.inorderTraversal((e,t)=>{var r=!i.serverCache.isCompleteForChild(e)&&null===t.value;u.hasChild(e)||r||(r=ep(0,i.serverCache.getNode().getImmediateChild(e),t),h=Jd(n,h,new f(e),r,s,a,o,l))}),h}class rp{constructor(e,t){this.query_=e,this.eventRegistrations_=[];var r=this.query_._queryParams,n=new Kc(r.getIndex()),r=(e=r).loadsAllData()?new Kc(e.getIndex()):new(e.hasLimit()?Hc:Wc)(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 pd(a,i.isFullyInitialized(),n.filtersNodes()),i=new pd(o,s.isFullyInitialized(),r.filtersNodes());this.viewCache_=vd(i,a),this.eventGenerator_=new fd(this.query_)}get query(){return this.query_}}function np(e){return 0===e.eventRegistrations_.length}function ip(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 sp(e,t,r,n){t.type===Hh.MERGE&&null!==t.source.queryId&&(g(bd(e.viewCache_),"We should always have a full cache before handling merges"),g(wd(e.viewCache_),"Missing event cache, even though we have a server cache"));var i=e.viewCache_,s=Qd(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,ap(e,s.changes,s.viewCache.eventCache.getNode(),null)}function ap(e,t,r,n){var i=n?[n]:e.eventRegistrations_;return gd(e.eventGenerator_,t,r,i)}let op;class lp{constructor(){this.views=new Map}}function hp(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."),sp(e,r,n,i);{let e=[];for(var s of t.views.values())e=e.concat(sp(s,r,n,i));return e}}function up(e,r,n,i,s){var a=r._queryIdentifier,a=e.views.get(a);if(a)return a;{let e=Ud(n,s?i:null),t=!1;t=!!e||(e=i instanceof T?Vd(n,i):T.EMPTY_NODE,!1);a=vd(new pd(e,t,!1),new pd(i,s,!1));return new rp(r,a)}}function cp(e,t,n,i,s,r){var a=up(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(jc(e,t))}),a.isFullyInitialized()&&r.push(qc(a.getNode())),ap(i,r,a.getNode(),s)}}function dp(e,t,r,n){var i=t._queryIdentifier,s=[];let a=[];var o=vp(e);if("default"===i)for(var[l,h]of e.views.entries())a=a.concat(ip(h,r,n)),np(h)&&(e.views.delete(l),h.query._queryParams.loadsAllData()||s.push(h.query));else{var u=e.views.get(i);u&&(a=a.concat(ip(u,r,n)),np(u))&&(e.views.delete(i),u.query._queryParams.loadsAllData()||s.push(u.query))}return o&&!vp(e)&&s.push((g(op,"Reference.ts has not been loaded"),new op(t._repo,t._path))),{removed:s,events:a}}function pp(e){var t,r=[];for(t of e.views.values())t.query._queryParams.loadsAllData()||r.push(t);return r}function fp(e,t){let r=null;for(var n of e.views.values())r=r||(i=n,s=t,n=void 0,(n=bd(i.viewCache_))&&(i.query._queryParams.loadsAllData()||!b(s)&&!n.getImmediateChild(_(s)).isEmpty())?n.getChild(s):null);var i,s;return r}function gp(e,t){var r;return t._queryParams.loadsAllData()?_p(e):(r=t._queryIdentifier,e.views.get(r))}function mp(e,t){return null!=gp(e,t)}function vp(e){return null!=_p(e)}function _p(e){for(var t of e.views.values())if(t.query._queryParams.loadsAllData())return t;return null}let yp;let wp=1;class bp{constructor(e){this.listenProvider_=e,this.syncPointTree_=new E(null),this.pendingWriteTree_={visibleWrites:Td.empty(),allWrites:[],lastWriteId:-1},this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function Ip(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=Ed(s.visibleWrites,a,o)),s.lastWriteId=n,i?Pp(e,new cd(ad(),t,r)):[]}function Tp(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=Cd(i.visibleWrites,s,a),i.lastWriteId=n;var i,s,a,o=E.fromObject(r);return Pp(e,new dd(ad(),t,o))}function Ep(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(Od(e.pendingWriteTree_,t)){let t=new E(null);return null!=n.snap?t=t.set(v(),!0):mu(n.children,e=>{t=t.set(new f(e),!0)}),Pp(e,new hd(n.path,t,r))}return[]}function Cp(e,t,r){return Pp(e,new cd(od(),t,r))}function kp(r,t,n,i,s=!1){var a=t._path,o=r.syncPointTree_.get(a);let l=[];if(o&&("default"===t._queryIdentifier||mp(o,t))){var h=dp(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()),u=r.syncPointTree_.findOnPath(a,(e,t)=>vp(t));if(h&&!u){a=r.syncPointTree_.subtree(a);if(!a.isEmpty()){var c=a.fold((e,t,n)=>{if(t&&vp(t))return[_p(t)];{let r=[];return t&&(r=pp(t)),mu(n,(e,t)=>{r=r.concat(t)}),r}});for(let e=0;e<c.length;++e){var d=c[e],p=d.query,d=xp(r,d);r.listenProvider_.startListening(Vp(p),Op(r,p),d.hashFn,d.onComplete)}}}!u&&0<o.length&&!i&&(h?r.listenProvider_.stopListening(Vp(t),null):o.forEach(e=>{var t=r.queryToTagMap.get(Lp(e));r.listenProvider_.stopListening(Vp(e),t)}))}var f=r,g=o;for(let e=0;e<g.length;++e){var m,v=g[e];v._queryParams.loadsAllData()||(v=Lp(v),m=f.queryToTagMap.get(v),f.queryToTagMap.delete(v),f.tagToQueryMap.delete(m))}}return l}function Sp(e,t,r,n){var i,s,a=Mp(e,n);return null!=a?(i=(a=Fp(a)).path,a=a.queryId,s=Zu(i,t),Up(e,i,new cd(ld(a),s,r))):[]}function Ap(e,t,r,n=!1){let i=t._path,s=null,a=!1,o=(e.syncPointTree_.foreachOnPath(i,(e,t)=>{var r=Zu(e,i);s=s||fp(t,r),a=a||vp(t)}),e.syncPointTree_.get(i));o?(a=a||vp(o),s=s||fp(o,v())):(o=new lp,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=fp(t,v());r&&(s=s.updateImmediateChild(e,r))}));var h,u=mp(o,t),c=(u||t._queryParams.loadsAllData()||(h=Lp(t),g(!e.queryToTagMap.has(h),"View does not exist, but we have a tag"),c=wp++,e.queryToTagMap.set(h,c),e.tagToQueryMap.set(c,h)),xd(e.pendingWriteTree_,i));let d=cp(o,t,r,c,s,l);return u||a||n||(h=gp(o,t),d=d.concat(((t,e,r)=>{var n=e._path,i=Op(t,e),s=xp(t,r),s=t.listenProvider_.startListening(Vp(e),i,s.hashFn,s.onComplete),n=t.syncPointTree_.subtree(n);if(i)g(!vp(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&&vp(t))return[_p(t).query];{let r=[];return t&&(r=r.concat(pp(t).map(e=>e.query))),mu(n,(e,t)=>{r=r.concat(t)}),r}});for(let e=0;e<a.length;++e){var o=a[e];t.listenProvider_.stopListening(Vp(o),Op(t,o))}}return s})(e,t,h))),d}function Np(e,n,t){var r=e.pendingWriteTree_,i=e.syncPointTree_.findOnPath(n,(e,t)=>{var r=fp(t,Zu(e,n));if(r)return r});return Fd(r,n,i,t,!0)}function Rp(e,t){let n=t._path,i=null,r=(e.syncPointTree_.foreachOnPath(n,(e,t)=>{var r=Zu(e,n);i=i||fp(t,r)}),e.syncPointTree_.get(n));r?i=i||fp(r,v()):(r=new lp,e.syncPointTree_=e.syncPointTree_.set(n,r));var s=null!=i,a=s?new pd(i,!0,!1):null,o=xd(e.pendingWriteTree_,t._path);return wd(up(r,t,o,s?a.getNode():T.EMPTY_NODE,s).viewCache_)}function Pp(e,t){return function a(t,o,l,h){{if(b(t.path))return Dp(t,o,l,h);{let e=o.get(v()),r=(null==l&&null!=e&&(l=fp(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=Kd(h,n);r=r.concat(a(i,s,e,t))}return r=e?r.concat(hp(e,t,h,l)):r}}}(t,e.syncPointTree_,null,xd(e.pendingWriteTree_,v()))}function Dp(s,e,a,o){var t=e.get(v());null==a&&null!=t&&(a=fp(t,v()));let l=[];return e.children.inorderTraversal((e,t)=>{var r=a?a.getImmediateChild(e):null,n=Kd(o,e),i=s.operationForChild(e);i&&(l=l.concat(Dp(i,t,r,n)))}),l=t?l.concat(hp(t,s,o,a)):l}function xp(o,e){let l=e.query,h=Op(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=Mp(t,n))?(i=(a=Fp(a)).path,a=a.queryId,s=Zu(i,r),Up(t,i,new ud(ld(a),s))):[]):(n=o,r=l._path,Pp(n,new ud(od(),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),kp(o,l,null,i))}}}function Op(e,t){var r=Lp(t);return e.queryToTagMap.get(r)}function Lp(e){return e._path.toString()+"$"+e._queryIdentifier}function Mp(e,t){return e.tagToQueryMap.get(t)}function Fp(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 Up(e,t,r){var n=e.syncPointTree_.get(t),i=(g(n,"Missing sync point for query tag that we're tracking"),xd(e.pendingWriteTree_,t));return hp(n,r,i,null)}function Vp(e){return e._queryParams.loadsAllData()&&!e._queryParams.isDefault()?(g(yp,"Reference.ts has not been loaded"),new yp(e._repo,e._path)):e}class qp{constructor(e){this.node_=e}getImmediateChild(e){var t=this.node_.getImmediateChild(e);return new qp(t)}node(){return this.node_}}class jp{constructor(e,t){this.syncTree_=e,this.path_=t}getImmediateChild(e){var t=Xu(this.path_,e);return new jp(this.syncTree_,t)}node(){return Np(this.syncTree_,this.path_)}}let Bp=function(e){return(e=e||{}).timestamp=e.timestamp||(new Date).getTime(),e},zp=function(e,t,r){return e&&"object"==typeof e?(g(".sv"in e,"Unexpected leaf node or priority contents"),"string"==typeof e[".sv"]?Kp(e[".sv"],t,r):"object"==typeof e[".sv"]?Wp(e[".sv"],t):void g(!1,"Unexpected server value: "+JSON.stringify(e,null,2))):e},Kp=function(e,t,r){if("timestamp"===e)return r.timestamp;g(!1,"Unexpected server value: "+e)},Wp=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},Hp=function(e,t,r,n){return $p(t,new jp(r,e),n)},Gp=function(e,t,r){return $p(e,new qp(t),r)};function $p(e,n,i){var t,r,s=e.getPriority().val(),s=zp(s,n.getImmediateChild(".priority"),i);let a;return e.isLeafNode()?(r=e,(t=zp(r.getValue(),n,i))!==r.getValue()||s!==r.getPriority().val()?new Ic(t,Mc(s)):e):(r=e,s!==(a=r).getPriority().val()&&(a=a.updatePriority(new Ic(s))),r.forEachChild(I,(e,t)=>{var r=$p(t,n.getImmediateChild(e),i);r!==t&&(a=a.updateImmediateChild(e,r))}),a)}class Qp{constructor(e="",t=null,r={children:{},childCount:0}){this.name=e,this.parent=t,this.node=r}}function Yp(e,t){let r=t instanceof f?t:new f(t),n=e,i=_(r);for(;null!==i;){var s=ye(n.node.children,i)||{children:{},childCount:0};n=new Qp(i,n,s),r=y(r),i=_(r)}return n}function Jp(e){return e.node.value}function Xp(e,t){e.node.value=t,rf(e)}function Zp(e){return 0<e.node.childCount}function ef(r,n){mu(r.node.children,(e,t)=>{n(new Qp(e,r,t))})}function tf(e){return new f(null===e.parent?e.name:tf(e.parent)+"/"+e.name)}function rf(e){var t,r,n,i;null!==e.parent&&(t=e.parent,r=e.name,n=(e=>void 0===Jp(e)&&!Zp(e))(e=e),i=_e(t.node.children,r),n&&i?(delete t.node.children[r],t.node.childCount--,rf(t)):n||i||(t.node.children[r]=e.node,t.node.childCount++,rf(t)))}function nf(e,t,r,n){n&&void 0===t||vf(Pe(e,"value"),t,r)}function sf(e,t,s,r){if(!r||void 0!==t){let n=Pe(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=[];mu(t,(e,t)=>{var r=new f(e);if(vf(n,t,Xu(s,r)),".priority"===Qu(r)&&!mf(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=Yu(r=o[t]);for(let e=0;e<l.length;e++)if((".priority"!==l[e]||e!==l.length-1)&&!pf(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(ec);let e=null;for(t=0;t<o.length;t++){if(r=o[t],null!==e&&rc(e,r))throw new Error(a+"contains a path "+e.toString()+" that is ancestor of another path "+r.toString());e=r}}}}function af(e,t,r){if(!r||void 0!==t){if(du(t))throw new Error(Pe(e,"priority")+"is "+t.toString()+", but must be a valid Firebase priority (a string, finite number, server value, or null).");if(!mf(t))throw new Error(Pe(e,"priority")+"must be a valid Firebase priority (a string, finite number, server value, or null).")}}function of(e,t,r,n){if(!(n&&void 0===r||pf(r)))throw new Error(Pe(e,t)+'was an invalid key = "'+r+'". Firebase keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]").')}function lf(e,t,r,n){r=r&&r.replace(/^\/*\.info(\/|$)/,"/"),_f(e,t,r,n)}function hf(e,t){if(".info"===_(t))throw new Error(e+" failed = Can't modify data under /.info/")}let uf=/[\[\].#$\/\u0000-\u001F\u007F]/,cf=/[\[\].#$\u0000-\u001F\u007F]/,df=10485760,pf=function(e){return"string"==typeof e&&0!==e.length&&!uf.test(e)},ff=function(e){return"string"==typeof e&&0!==e.length&&!cf.test(e)},gf=function(e){return e=e&&e.replace(/^\/*\.info(\/|$)/,"/"),ff(e)},mf=function(e){return null===e||"string"==typeof e||"number"==typeof e&&!du(e)||e&&"object"==typeof e&&_e(e,".sv")},vf=function(a,e,t){let o=t instanceof f?new nc(t,a):t;if(void 0===e)throw new Error(a+"contains undefined "+sc(o));if("function"==typeof e)throw new Error(a+"contains a function "+sc(o)+" with contents = "+e.toString());if(du(e))throw new Error(a+"contains "+e.toString()+" "+sc(o));if("string"==typeof e&&e.length>df/3&&Oe(e)>df)throw new Error(a+"contains a string greater than "+df+" utf8 bytes "+sc(o)+" ('"+e.substring(0,50)+"...')");if(e&&"object"==typeof e){let i=!1,s=!1;if(mu(e,(e,t)=>{if(".value"===e)i=!0;else if(".priority"!==e&&".sv"!==e&&(s=!0,!pf(e)))throw new Error(a+" contains an invalid key ("+e+") "+sc(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_+=Oe(e),ic(r),vf(a,t,o),e=o,n=e.parts_.pop(),e.byteLength_-=Oe(n),0<e.parts_.length&&--e.byteLength_}),i&&s)throw new Error(a+' contains ".value" child '+sc(o)+" in addition to actual children.")}},_f=function(e,t,r,n){if(!(n&&void 0===r||ff(r)))throw new Error(Pe(e,t)+'was an invalid path = "'+r+'". Paths must be non-empty strings and can\'t contain ".", "#", "$", "[", or "]"')},yf=function(e,t){var r=t.path.toString();if("string"!=typeof t.repoInfo.host||0===t.repoInfo.host.length||!pf(t.repoInfo.namespace)&&"localhost"!==t.repoInfo.host.split(":")[0]||0!==r.length&&!gf(r))throw new Error(Pe(e,"url")+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')};class wf{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function bf(e,t){let r=null;for(let s=0;s<t.length;s++){var n=t[s],i=n.getPath();null===r||tc(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 If(e,t,r){bf(e,r),Ef(e,e=>tc(e,t))}function Tf(e,t,r){bf(e,r),Ef(e,e=>rc(e,t)||rc(t,e))}function Ef(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(),su&&lu("event: "+a.toString()),Tu(s))}t.eventLists_[o]=null}else r=!1}r&&(t.eventLists_=[]),t.recursionDepth_--}let Cf="repo_interrupt",kf=25;class Sf{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 wf,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=td(),this.transactionQueueTree_=new Qp,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function Af(a,e,t){if(a.stats_=Lu(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 Zc(a.repoInfo_,(e,t,r,n)=>{Pf(a,e,t,r,n)},a.authTokenProvider_,a.appCheckProvider_),setTimeout(()=>Df(a,!0),0);else{if(null!=t){if("object"!=typeof t)throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{me(t)}catch(e){throw new Error("Invalid authOverride provided: "+e)}}a.persistentConnection_=new oc(a.repoInfo_,e,(e,t,r,n)=>{Pf(a,e,t,r,n)},e=>{Df(a,e)},e=>{var r;r=a,mu(e,(e,t)=>{xf(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 sd(a.stats_,a.server_),r=a.repoInfo_.toString(),Ou[r]||(Ou[r]=e()),Ou[r]),a.infoData_=new ed,a.infoSyncTree_=new bp({startListening:(e,t,r,n)=>{let i=[];var s=a.infoData_.getNode(e._path);return s.isEmpty()||(i=Cp(a.infoSyncTree_,e._path,s),setTimeout(()=>{n("ok")},0)),i},stopListening:()=>{}}),xf(a,"connected",!1),a.serverSyncTree_=new bp({startListening:(n,e,t,i)=>(a.server_.listen(n,t,e,(e,t)=>{var r=i(e,t);Tf(a.eventQueue_,n._path,r)}),[]),stopListening:(e,t)=>{a.server_.unlisten(e,t)}})}function Nf(e){var t=e.infoData_.getNode(new f(".info/serverTimeOffset")).val()||0;return(new Date).getTime()+t}function Rf(e){return Bp({timestamp:Nf(e)})}function Pf(e,t,r,n,i){e.dataUpdateCount++;var s,a,o,l,h,u,c=new f(t);r=e.interceptServerDataCallback_?e.interceptServerDataCallback_(t,r):r;let d=[],p=c;0<(d=i?n?(u=be(r,e=>Mc(e)),t=e.serverSyncTree_,s=c,a=u,(u=Mp(t,i))?(o=(u=Fp(u)).path,u=u.queryId,l=Zu(o,s),h=E.fromObject(a),Up(t,o,new dd(ld(u),l,h))):[]):(o=Mc(r),Sp(e.serverSyncTree_,c,o,i)):n?(u=be(r,e=>Mc(e)),s=e.serverSyncTree_,a=c,t=u,l=E.fromObject(t),Pp(s,new dd(od(),a,l))):(h=Mc(r),Cp(e.serverSyncTree_,c,h))).length&&(p=Kf(e,c)),Tf(e.eventQueue_,p,d)}function Df(e,t){if(xf(e,"connected",t),!1===t){var a=e;qf(a,"onDisconnectEvents");let n=Rf(a),i=td(),s=(nd(a.onDisconnect_,v(),(e,t)=>{var r=Hp(e,t,a.serverSyncTree_,n);rd(i,e,r)}),[]);nd(i,v(),(e,t)=>{s=s.concat(Cp(a.serverSyncTree_,e,t));var r=$f(a,e);Kf(a,r)}),a.onDisconnect_=td(),Tf(a.eventQueue_,v(),s)}}function xf(e,t,r){var n=new f("/.info/"+t),i=Mc(r),i=(e.infoData_.updateSnapshot(n,i),Cp(e.infoSyncTree_,n,i));Tf(e.eventQueue_,n,i)}function Of(e){return e.nextWriteId_++}function Lf(n,i,e,t,s){qf(n,"set",{path:i.toString(),value:e,priority:t});var r=Rf(n),a=Mc(e,t),o=Np(n.serverSyncTree_,i),o=Gp(a,o,r);let l=Of(n);r=Ip(n.serverSyncTree_,i,o,l,!0),bf(n.eventQueue_,r),n.server_.put(i.toString(),a.val(!0),(e,t)=>{var r="ok"===e,r=(r||uu("set at "+i+" failed: "+e),Ep(n.serverSyncTree_,l,!r));Tf(n.eventQueue_,i,r),jf(0,s,e,t)}),o=$f(n,i);Kf(n,o),Tf(n.eventQueue_,o,[])}function Mf(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)=>{rd(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),jf(0,i,e,t)})}function Ff(r,n,e,i){let s=Mc(e);r.server_.onDisconnectPut(n.toString(),s.val(!0),(e,t)=>{"ok"===e&&rd(r.onDisconnect_,n,s),jf(0,i,e,t)})}function Uf(e,t,r){let n;n=".info"===_(t._path)?kp(e.infoSyncTree_,t,r):kp(e.serverSyncTree_,t,r),If(e.eventQueue_,t._path,n)}function Vf(e){e.persistentConnection_&&e.persistentConnection_.interrupt(Cf)}function qf(e,...t){let r="";e.persistentConnection_&&(r=e.persistentConnection_.id+":"),lu(r,...t)}function jf(e,n,i,s){n&&Tu(()=>{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 Bf(e,t,r){return Np(e.serverSyncTree_,t,r)||T.EMPTY_NODE}function zf(o,l=o.transactionQueueTree_){if(l||Gf(o,l),Jp(l)){var h=Hf(o,l),e=(g(0<h.length,"Sending zero length transaction queue"),h.every(e=>0===e.status));if(e){var u=o;var c=tf(l);var d=h;let e=d.map(e=>e.currentWriteId),t=Bf(u,c,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++,Zu(c,p.path));r=r.updateChild(f,p.currentOutputSnapshotRaw)}let i=r.val(!0),s=c;u.server_.put(s.toString(),i,t=>{qf(u,"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(Ep(u.serverSyncTree_,d[e].currentWriteId)),d[e].onComplete&&n.push(()=>d[e].onComplete(null,!0,d[e].currentOutputSnapshotResolved)),d[e].unwatcher();Gf(u,Yp(u.transactionQueueTree_,c)),zf(u,u.transactionQueueTree_),Tf(u.eventQueue_,c,r);for(let t=0;t<n.length;t++)Tu(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{uu("transaction at "+s.toString()+" failed: "+t);for(let e=0;e<d.length;e++)d[e].status=4,d[e].abortReason=t}Kf(u,c)}},n)}}else Zp(l)&&ef(l,e=>{zf(o,e)})}function Kf(e,t){var r=Wf(e,t),n=tf(r),r=Hf(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],u=Zu(a,h.path);let e=!1,t;if(g(null!==u,"rerunTransactionsUnderNode_: relativePath should not be null."),4===h.status)e=!0,t=h.abortReason,r=r.concat(Ep(i.serverSyncTree_,h.currentWriteId,!0));else if(0===h.status)if(h.retryCount>=kf)e=!0,t="maxretry",r=r.concat(Ep(i.serverSyncTree_,h.currentWriteId,!0));else{var u=Bf(i,h.path,l),c=(h.currentInputSnapshot=u,s[n].update(u.val()));if(void 0!==c){vf("transaction failed: Data returned ",c,h.path);let e=Mc(c);"object"==typeof c&&null!=c&&_e(c,".priority")||(e=e.updatePriority(u.getPriority()));var c=h.currentWriteId,d=Rf(i),u=Gp(e,u,d);h.currentOutputSnapshotRaw=e,h.currentOutputSnapshotResolved=u,h.currentWriteId=Of(i),l.splice(l.indexOf(c),1),r=(r=r.concat(Ip(i.serverSyncTree_,h.path,u,h.currentWriteId,h.applyLocally))).concat(Ep(i.serverSyncTree_,c,!0))}else e=!0,t="nodata",r=r.concat(Ep(i.serverSyncTree_,h.currentWriteId,!0))}Tf(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)))}Gf(i,i.transactionQueueTree_);for(let e=0;e<o.length;e++)Tu(o[e]);zf(i,i.transactionQueueTree_)}return n}function Wf(e,t){let r,n=e.transactionQueueTree_;for(r=_(t);null!==r&&void 0===Jp(n);)n=Yp(n,r),t=y(t),r=_(t);return n}function Hf(e,t){var r=[];return function t(r,e,n){let i=Jp(e);if(i)for(let e=0;e<i.length;e++)n.push(i[e]);ef(e,e=>{t(r,e,n)})}(e,t,r),r.sort((e,t)=>e.order-t.order),r}function Gf(t,r){var n=Jp(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,Xp(r,0<n.length?n:void 0)}ef(r,e=>{Gf(t,e)})}function $f(t,e){var r=tf(Wf(t,e)),n=Yp(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=>{Qf(t,e)}),Qf(t,n),function t(e,r,n,i){n&&!i&&r(e),ef(e,e=>{t(e,r,!0,i)}),n&&i&&r(e)}(n,e=>{Qf(t,e)}),r}function Qf(i,s){var a=Jp(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(Ep(i.serverSyncTree_,a[r].currentWriteId,!0)),a[r].onComplete&&o.push(a[r].onComplete.bind(null,new Error("set"),!1,null))));-1===t?Xp(s,void 0):a.length=t+1,Tf(i.eventQueue_,tf(s),e);for(let n=0;n<o.length;n++)Tu(o[n])}}let Yf=function(e,t){var r=Jf(e),n=r.namespace,i=("firebase.com"===r.domain&&hu(r.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),n&&"undefined"!==n||"localhost"===r.domain||hu("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),r.secure||cu(),"ws"===r.scheme||"wss"===r.scheme);return{repoInfo:new Ru(r.host,r.secure,n,i,t,"",n!==r.subdomain),path:new f(r.pathString)}},Jf=function(n){let i="",s="",a="",o="",l="",h=!0,u="https",c=443;if("string"==typeof n){let e=n.indexOf("//"),t=(0<=e&&(u=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]):uu(`Invalid query segment '${t}' in query '${e}'`));return n})(n.substring(Math.min(n.length,r))),p=(0<=(e=i.indexOf(":"))?(h="https"===u||"wss"===u,c=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:c,domain:s,subdomain:a,secure:h,scheme:u,pathString:o,namespace:l}},Xf="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",Zf=(()=>{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]=Xf.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+=Xf.charAt(a[r]);return g(20===i.length,"nextPushId: Length should be 20."),i}})();class eg{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+":"+me(this.snapshot.exportVal())}}class tg{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 rg{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 ng{constructor(e,t){this._repo=e,this._path=t}cancel(){var e=new X;return Mf(this._repo,this._path,e.wrapCallback(()=>{})),e.promise}remove(){hf("OnDisconnect.remove",this._path);var e=new X;return Ff(this._repo,this._path,null,e.wrapCallback(()=>{})),e.promise}set(e){hf("OnDisconnect.set",this._path),nf("OnDisconnect.set",e,this._path,!1);var t=new X;return Ff(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}setWithPriority(e,t){hf("OnDisconnect.setWithPriority",this._path),nf("OnDisconnect.setWithPriority",e,this._path,!1),af("OnDisconnect.setWithPriority",t,!1);var n=new X;{var i=this._repo,s=this._path,a=n.wrapCallback(()=>{});let r=Mc(e,t);i.server_.onDisconnectPut(s.toString(),r.val(!0),(e,t)=>{"ok"===e&&rd(i.onDisconnect_,s,r),jf(0,a,e,t)})}return n.promise}update(e){hf("OnDisconnect.update",this._path),sf("OnDisconnect.update",e,this._path,!1);var n,i,r,s,t=new X;return n=this._repo,i=this._path,r=e,s=t.wrapCallback(()=>{}),we(r)?(lu("onDisconnect().update() called with empty data. Don't do anything."),jf(0,s,"ok",void 0)):n.server_.onDisconnectMerge(i.toString(),r,(e,t)=>{"ok"===e&&mu(r,(e,t)=>{var r=Mc(t);rd(n.onDisconnect_,Xu(i,e),r)}),jf(0,s,e,t)}),t.promise}}class ig{constructor(e,t,r,n){this._repo=e,this._path=t,this._queryParams=r,this._orderByCalled=n}get key(){return b(this._path)?null:Qu(this._path)}get ref(){return new lg(this._repo,this._path)}get _queryIdentifier(){var e=Xc(this._queryParams),e=Xh(e);return"{}"===e?"default":e}get _queryObject(){return Xc(this._queryParams)}isEqual(e){var t,r,n;return(e=w(e))instanceof ig&&(t=this._repo===e._repo,r=tc(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 sg(e,t){if(!0===e._orderByCalled)throw new Error(t+": You can't combine multiple orderBy calls.")}function ag(e){let t=null,r=null;if(e.hasStart()&&(t=e.getIndexStartValue()),e.hasEnd()&&(r=e.getIndexEndValue()),e.getIndex()===cc){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()!==pu)throw new Error(n);if("string"!=typeof t)throw new Error(i)}if(e.hasEnd()){if(e.getIndexEndName()!==fu)throw new Error(n);if("string"!=typeof r)throw new Error(i)}}else if(e.getIndex()===I){if(null!=t&&!mf(t)||null!=r&&!mf(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 Fc||e.getIndex()===Vc,"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 og(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 lg extends ig{constructor(e,t){super(e,t,new Gc,!1)}get parent(){var e=Ju(this._path);return null===e?null:new lg(this._repo,e)}get root(){let e=this;for(;null!==e.parent;)e=e.parent;return e}}class hg{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=dg(this.ref,e);return new hg(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 hg(t,dg(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 ug(e,t){return(e=w(e))._checkNotDeleted("ref"),void 0!==t?dg(e._root,t):e._root}function cg(e,t){(e=w(e))._checkNotDeleted("refFromURL");var r=Yf(t,e._repo.repoInfo_.nodeAdmin),n=(yf("refFromURL",r),r.repoInfo);return e._repo.repoInfo_.isCustomHost()||n.host===e._repo.repoInfo_.host||hu("refFromURL: Host name does not match the current database: (found "+n.host+" but expected "+e._repo.repoInfo_.host+")"),ug(e,r.path.toString())}function dg(e,t){return(null===_((e=w(e))._path)?lf:_f)("child","path",t,!1),new lg(e._repo,Xu(e._path,t))}function pg(e,t){e=w(e),hf("set",e._path),nf("set",t,e._path,!1);var r=new X;return Lf(e._repo,e._path,t,null,r.wrapCallback(()=>{})),r.promise}function fg(e,t){sf("update",t,e._path,!1);var i=new X;{var a=e._repo,o=e._path,l=(e=t,i.wrapCallback(()=>{}));qf(a,"update",{path:o.toString(),value:e});let r=!0,n=Rf(a),s={};if(mu(e,(e,t)=>{r=!1,s[e]=Hp(Xu(o,e),Mc(t),a.serverSyncTree_,n)}),r)lu("update() called with empty data. Don't do anything."),jf(0,l,"ok",void 0);else{let i=Of(a);var h=Tp(a.serverSyncTree_,o,s,i);bf(a.eventQueue_,h),a.server_.merge(o.toString(),e,(e,t)=>{var r="ok"===e,r=(r||uu("update at "+o+" failed: "+e),Ep(a.serverSyncTree_,i,!r)),n=0<r.length?Kf(a,o):o;Tf(a.eventQueue_,n,r),jf(0,l,e,t)}),mu(e,e=>{var t=$f(a,Xu(o,e));Kf(a,t)}),Tf(a.eventQueue_,o,[])}}return i.promise}function gg(t){t=w(t);var i,s,a,e=new rg(()=>{}),e=new mg(e);return i=t._repo,s=t,a=e,(null!=(e=Rp(i.serverSyncTree_,s))?Promise.resolve(e):i.server_.get(s).then(e=>{var t,r=Mc(e).withIndex(s._queryParams.getIndex());Ap(i.serverSyncTree_,s,a,!0);let n;return n=s._queryParams.loadsAllData()?Cp(i.serverSyncTree_,s._path,r):(t=Op(i.serverSyncTree_,s),Sp(i.serverSyncTree_,s._path,r,t)),Tf(i.eventQueue_,s._path,n),kp(i.serverSyncTree_,s,a,null,!0),r},e=>(qf(i,"get for query "+me(s)+" failed: "+e),Promise.reject(new Error(e))))).then(e=>new hg(e,new lg(t._repo,t._path),t._queryParams.getIndex()))}class mg{constructor(e){this.callbackContext=e}respondsTo(e){return"value"===e}createEvent(e,t){var r=t._queryParams.getIndex();return new eg("value",this,new hg(e.snapshotNode,new lg(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 tg(this,e,t):null}matches(e){return e instanceof mg&&(!e.callbackContext||!this.callbackContext||e.callbackContext.matches(this.callbackContext))}hasAnyCallback(){return null!==this.callbackContext}}class vg{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 tg(this,e,t):null}createEvent(e,t){g(null!=e.childName,"Child events should have a childName.");var r=dg(new lg(t._repo,t._path),e.childName),n=t._queryParams.getIndex();return new eg(e.type,this,new hg(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 vg&&this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext))}hasAnyCallback(){return!!this.callbackContext}}function _g(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)=>{Uf(n._repo,n,o),r(e,t)};a.userCallback=t.userCallback,a.context=t.context,t=a}a=new rg(t,s||void 0);let o="value"===e?new mg(a):new vg(e,a);{r=n._repo,i=n,t=o;let e;e=".info"===_(i._path)?Ap(r.infoSyncTree_,i,t):Ap(r.serverSyncTree_,i,t),If(r.eventQueue_,i._path,e)}return()=>Uf(n._repo,n,o)}function yg(e,t,r,n){return _g(e,"value",t,r,n)}function wg(e,t,r,n){_g(e,"child_added",t,r,n)}function bg(e,t,r,n){_g(e,"child_changed",t,r,n)}function Ig(e,t,r,n){_g(e,"child_moved",t,r,n)}function Tg(e,t,r,n){_g(e,"child_removed",t,r,n)}function Eg(e,t,r){let n=null;var i=r?new rg(r):null;"value"===t?n=new mg(i):t&&(n=new vg(t,i)),Uf(e._repo,e,n)}class Cg{}class kg extends Cg{constructor(e,t){super(),this._value=e,this._key=t,this.type="endAt"}_apply(e){nf("endAt",this._value,e._path,!0);var t=Qc(e._queryParams,this._value,this._key);if(og(t),ag(t),e._queryParams.hasEnd())throw new Error("endAt: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new ig(e._repo,e._path,t,e._orderByCalled)}}class Sg extends Cg{constructor(e,t){super(),this._value=e,this._key=t,this.type="endBefore"}_apply(e){nf("endBefore",this._value,e._path,!1);var t=((e,t,r)=>{let n;return(n=e.index_===cc||r?Qc(e,t,r):Qc(e,t,pu)).endBeforeSet_=!0,n})(e._queryParams,this._value,this._key);if(og(t),ag(t),e._queryParams.hasEnd())throw new Error("endBefore: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new ig(e._repo,e._path,t,e._orderByCalled)}}class Ag extends Cg{constructor(e,t){super(),this._value=e,this._key=t,this.type="startAt"}_apply(e){nf("startAt",this._value,e._path,!0);var t=$c(e._queryParams,this._value,this._key);if(og(t),ag(t),e._queryParams.hasStart())throw new Error("startAt: Starting point was already set (by another call to startAt, startBefore or equalTo).");return new ig(e._repo,e._path,t,e._orderByCalled)}}class Ng extends Cg{constructor(e,t){super(),this._value=e,this._key=t,this.type="startAfter"}_apply(e){nf("startAfter",this._value,e._path,!1);var t=((e,t,r)=>{let n;return(n=e.index_===cc||r?$c(e,t,r):$c(e,t,fu)).startAfterSet_=!0,n})(e._queryParams,this._value,this._key);if(og(t),ag(t),e._queryParams.hasStart())throw new Error("startAfter: Starting point was already set (by another call to startAt, startAfter, or equalTo).");return new ig(e._repo,e._path,t,e._orderByCalled)}}class Rg extends Cg{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 ig(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 Pg extends Cg{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 ig(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 Dg extends Cg{constructor(e){super(),this._path=e,this.type="orderByChild"}_apply(e){sg(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 Fc(t),t=Yc(e._queryParams,t);return ag(t),new ig(e._repo,e._path,t,!0)}}class xg extends Cg{constructor(){super(...arguments),this.type="orderByKey"}_apply(e){sg(e,"orderByKey");var t=Yc(e._queryParams,cc);return ag(t),new ig(e._repo,e._path,t,!0)}}class Og extends Cg{constructor(){super(...arguments),this.type="orderByPriority"}_apply(e){sg(e,"orderByPriority");var t=Yc(e._queryParams,I);return ag(t),new ig(e._repo,e._path,t,!0)}}class Lg extends Cg{constructor(){super(...arguments),this.type="orderByValue"}_apply(e){sg(e,"orderByValue");var t=Yc(e._queryParams,Vc);return ag(t),new ig(e._repo,e._path,t,!0)}}class Mg extends Cg{constructor(e,t){super(),this._value=e,this._key=t,this.type="equalTo"}_apply(e){if(nf("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 kg(this._value,this._key)._apply(new Ag(this._value,this._key)._apply(e))}}function Fg(e,...t){let r=w(e);for(var n of t)r=n._apply(r);return r}t=lg,g(!op,"__referenceConstructor has already been defined"),op=t,t=lg,g(!yp,"__referenceConstructor has already been defined"),yp=t;let Ug="FIREBASE_DATABASE_EMULATOR_HOST",Vg={},qg=!1;function jg(e,t,r,n,i){let s=n||e.options.databaseURL,a=(void 0===s&&(e.options.projectId||hu("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),lu("Using default host for project ",e.options.projectId),s=e.options.projectId+"-default-rtdb.firebaseio.com"),Yf(s,i)),o=a.repoInfo,l,h=void 0;(h="undefined"!=typeof process&&process.env?process.env[Ug]:h)?(l=!0,s=`http://${h}?ns=`+o.namespace,a=Yf(s,i),o=a.repoInfo):l=!a.repoInfo.secure;var u=i&&l?new ku(ku.OWNER):new Cu(e.name,e.options,t),u=(yf("Invalid Firebase Database URL",a),b(a.path)||hu("Database URL must point to the root of a Firebase Database (not including a child path)."),((e,t,r,n)=>{let i=Vg[t.name];var s;return i||(i={},Vg[t.name]=i),(s=i[e.toURLString()])&&hu("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call."),s=new Sf(e,qg,r,n),i[e.toURLString()]=s})(o,e,u,new Eu(e,r)));return new Bg(u,e)}class Bg{constructor(e,t){this._repoInternal=e,this.app=t,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(Af(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new lg(this._repo,v())),this._rootInternal}_delete(){var e,t,r;return null!==this._rootInternal&&(e=this._repo,t=this.app.name,(r=Vg[t])&&r[e.key]===e||hu(`Database ${t}(${e.repoInfo_}) has already been deleted.`),Vf(e),delete r[e.key],this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){null===this._rootInternal&&hu("Cannot call "+e+" on a deleted database.")}}function zg(){ju.IS_TRANSPORT_INITIALIZED&&uu("Transport has already been initialized. Please call this function before calling ref or setting up a listener")}function Kg(){zg(),Fu.forceDisallow()}function Wg(){zg(),qu.forceDisallow(),Fu.forceAllow()}function Hg(e,t,r,n={}){(e=w(e))._checkNotDeleted("useEmulator"),e._instanceStarted&&hu("Cannot call useEmulator() after instance has already been initialized.");var i,s=e._repoInternal;let a=void 0;s.repoInfo_.nodeAdmin?(n.mockUserToken&&hu('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),a=new ku(ku.OWNER)):n.mockUserToken&&(i="string"==typeof n.mockUserToken?n.mockUserToken:Z(n.mockUserToken,e.app.options.projectId),a=new ku(i)),n=s,e=t,t=r,r=a,n.repoInfo_=new Ru(e+":"+t,!1,n.repoInfo_.namespace,n.repoInfo_.webSocketOnly,n.repoInfo_.nodeAdmin,n.repoInfo_.persistenceKey,n.repoInfo_.includeNamespaceInQueryParams,!0),r&&(n.authTokenProvider_=r)}function Gg(e){(e=w(e))._checkNotDeleted("goOnline"),(e=e._repo).persistentConnection_&&e.persistentConnection_.resume(Cf)}function $g(e,t){ou(e,t)}let Qg={".sv":"timestamp"};class Yg{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}}function Jg(i,e,t){if(i=w(i),hf("Reference.transaction",i._path),".length"===i.key||".keys"===i.key)throw"Reference.transaction failed: "+i.key+" is a read-only object.";var r=null==(r=null==t?void 0:t.applyLocally)||r;let s=new X;var n=yg(i,()=>{}),t=i._repo,a=i._path,o=(e,t,r)=>{var n;e?s.reject(e):(n=new hg(r,new lg(i._repo,i._path),I),s.resolve(new Yg(t,n)))},l=n,h=r;qf(t,"transaction on "+a);var u,n={path:a,update:e,onComplete:o,status:null,order:nu(),applyLocally:h,retryCount:0,unwatcher:l,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},r=Bf(t,a,void 0);if(n.currentInputSnapshot=r,void 0===(u=n.update(r.val())))n.unwatcher(),n.currentOutputSnapshotRaw=null,n.currentOutputSnapshotResolved=null,n.onComplete&&n.onComplete(null,!1,n.currentInputSnapshot);else{vf("transaction failed: Data returned ",u,n.path),n.status=0;var c=Yp(t.transactionQueueTree_,a),d=Jp(c)||[];d.push(n),Xp(c,d);let e;"object"==typeof u&&null!==u&&_e(u,".priority")?(e=ye(u,".priority"),g(mf(e),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.")):(c=Np(t.serverSyncTree_,a)||T.EMPTY_NODE,e=c.getPriority().val());d=Rf(t),c=Mc(u,e),u=Gp(c,r,d),r=(n.currentOutputSnapshotRaw=c,n.currentOutputSnapshotResolved=u,n.currentWriteId=Of(t),Ip(t.serverSyncTree_,a,u,n.currentWriteId,n.applyLocally));Tf(t.eventQueue_,a,r),zf(t,t.transactionQueueTree_)}return s.promise}oc.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)},oc.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)},Bh(Dt),Ct(new u("database",(e,{instanceIdentifier:t})=>jg(e.getProvider("app").getImmediate(),e.getProvider("auth-internal"),e.getProvider("app-check-internal"),t),"PUBLIC").setMultipleInstances(!0)),d(qh,"1.0.12",KD),d(qh,"1.0.12","esm2017");function Xg(e){var t="FIREBASE WARNING: "+e;Zg.warn(t)}let Zg=new $e("@firebase/database-compat");class em{constructor(e){this._delegate=e}cancel(t){l("OnDisconnect.cancel",0,1,arguments.length),De("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),De("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),De("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),De("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,Xg("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.")}De("OnDisconnect.update","onComplete",r,!0);var e=this._delegate.update(t);return r&&e.then(()=>r(null),e=>r(e)),e}}class tm{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 rm{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),_f("DataSnapshot.child","path",e,!1),new rm(this._database,this._delegate.child(e))}hasChild(e){return l("DataSnapshot.hasChild",1,1,arguments.length),_f("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),De("DataSnapshot.forEach","action",t,!1),this._delegate.forEach(e=>t(new rm(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 im(this._database,this._delegate.ref)}get ref(){return this.getRef()}}class nm{constructor(e,t){this.database=e,this._delegate=t}on(e,r,t,n){var i;l("Query.on",2,4,arguments.length),De("Query.on","callback",r,!1);let s=nm.getCancelAndContextArgs_("Query.on",t,n);var a=(e,t)=>{r.call(s.context,new rm(this.database,e),t)},o=(a.userCallback=r,a.context=s.context,null==(i=s.cancel)?void 0:i.bind(s.context));switch(e){case"value":return yg(this._delegate,a,o),r;case"child_added":return wg(this._delegate,a,o),r;case"child_removed":return Tg(this._delegate,a,o),r;case"child_changed":return bg(this._delegate,a,o),r;case"child_moved":return Ig(this._delegate,a,o),r;default:throw new Error(Pe("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(Pe(i,"eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}De("Query.off","callback",t,!0),xe("Query.off","context",r,!0),t?((n=()=>{}).userCallback=t,n.context=r,Eg(this._delegate,e,n)):Eg(this._delegate,e)}get(){return gg(this._delegate).then(e=>new rm(this.database,e))}once(e,n,t,r){l("Query.once",1,4,arguments.length),De("Query.once","callback",n,!0);let i=nm.getCancelAndContextArgs_("Query.once",t,r),s=new X;var a=(e,t)=>{var r=new rm(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":yg(this._delegate,a,o,{onlyOnce:!0});break;case"child_added":wg(this._delegate,a,o,{onlyOnce:!0});break;case"child_removed":Tg(this._delegate,a,o,{onlyOnce:!0});break;case"child_changed":bg(this._delegate,a,o,{onlyOnce:!0});break;case"child_moved":Ig(this._delegate,a,o,{onlyOnce:!0});break;default:throw new Error(Pe("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 nm(this.database,Fg(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 Rg(e)})(e)))}limitToLast(e){return l("Query.limitToLast",1,1,arguments.length),new nm(this.database,Fg(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 Pg(e)})(e)))}orderByChild(e){return l("Query.orderByChild",1,1,arguments.length),new nm(this.database,Fg(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 _f("orderByChild","path",e,!1),new Dg(e)})(e)))}orderByKey(){return l("Query.orderByKey",0,0,arguments.length),new nm(this.database,Fg(this._delegate,new xg))}orderByPriority(){return l("Query.orderByPriority",0,0,arguments.length),new nm(this.database,Fg(this._delegate,new Og))}orderByValue(){return l("Query.orderByValue",0,0,arguments.length),new nm(this.database,Fg(this._delegate,new Lg))}startAt(e=null,t){return l("Query.startAt",0,2,arguments.length),new nm(this.database,Fg(this._delegate,([e=null,t]=[e,t],of("startAt","key",t,!0),new Ag(e,t))))}startAfter(e=null,t){return l("Query.startAfter",0,2,arguments.length),new nm(this.database,Fg(this._delegate,(e=e,t=t,of("startAfter","key",t,!0),new Ng(e,t))))}endAt(e=null,t){return l("Query.endAt",0,2,arguments.length),new nm(this.database,Fg(this._delegate,(e=e,t=t,of("endAt","key",t,!0),new kg(e,t))))}endBefore(e=null,t){return l("Query.endBefore",0,2,arguments.length),new nm(this.database,Fg(this._delegate,(e=e,t=t,of("endBefore","key",t,!0),new Sg(e,t))))}equalTo(e,t){return l("Query.equalTo",1,2,arguments.length),new nm(this.database,Fg(this._delegate,(e=e,t=t,of("equalTo","key",t,!0),new Mg(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 nm)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,De(e,"cancel",n.cancel,!0),n.context=r,xe(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(Pe(e,"cancelOrContext")+" must either be a cancel callback or a context object.");n.cancel=t}return n}get ref(){return new im(this.database,new lg(this._delegate._repo,this._delegate._path))}}class im extends nm{constructor(e,t){super(e,new ig(t._repo,t._path,new Gc,!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 im(this.database,dg(this._delegate,e))}getParent(){l("Reference.parent",0,0,arguments.length);var e=this._delegate.parent;return e?new im(this.database,e):null}getRoot(){return l("Reference.root",0,0,arguments.length),new im(this.database,this._delegate.root)}set(e,t){l("Reference.set",1,2,arguments.length),De("Reference.set","onComplete",t,!0);var r=pg(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,Xg("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.")}hf("Reference.update",this._delegate._path),De("Reference.update","onComplete",r,!0);var e=fg(this._delegate,t);return r&&e.then(()=>r(null),e=>r(e)),e}setWithPriority(e,t,r){l("Reference.setWithPriority",2,3,arguments.length),De("Reference.setWithPriority","onComplete",r,!0);var n=((e,t,r)=>{if(hf("setWithPriority",e._path),nf("setWithPriority",t,e._path,!1),af("setWithPriority",r,!1),".length"===e.key||".keys"===e.key)throw"setWithPriority failed: "+e.key+" is a read-only object.";var n=new X;return Lf(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),De("Reference.remove","onComplete",t,!0);e=this._delegate,hf("remove",e._path);var e,r=pg(e,null);return t&&r.then(()=>t(null),e=>t(e)),r}transaction(e,t,r){l("Reference.transaction",1,3,arguments.length),De("Reference.transaction","transactionUpdate",e,!1),De("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=Jg(this._delegate,e,{applyLocally:r}).then(e=>new tm(e.committed,new rm(this.database,e.snapshot))),t&&n.then(e=>t(null,e.committed,e.snapshot),e=>t(e,!1,null)),n;throw new Error(Pe(i,s)+"must be a boolean.")}setPriority(e,t){l("Reference.setPriority",1,2,arguments.length),De("Reference.setPriority","onComplete",t,!0);r=this._delegate,e=e,r=w(r),hf("setPriority",r._path),af("setPriority",e,!1),n=new X,Lf(r._repo,Xu(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),De("Reference.push","onComplete",t,!0);var r=((e,t)=>{e=w(e),hf("push",e._path),nf("push",t,e._path,!0);var r=Nf(e._repo),r=Zf(r),n=dg(e,r);let i=dg(e,r),s;return s=null!=t?pg(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 im(this.database,e)),r=(t&&n.then(()=>t(null),e=>t(e)),new im(this.database,r));return r.then=n.then.bind(n),r.catch=n.catch.bind(n,void 0),r}onDisconnect(){return hf("Reference.onDisconnect",this._delegate._path),new em(new ng(this._delegate._repo,this._delegate._path))}get key(){return this.getKey()}get parent(){return this.getParent()}get root(){return this.getRoot()}}class sm{constructor(e,t){this._delegate=e,this.app=t,this.INTERNAL={delete:()=>this._delegate._delete(),forceWebSockets:Kg,forceLongPolling:Wg}}useEmulator(e,t,r={}){Hg(this._delegate,e,t,r)}ref(e){var t;return l("database.ref",0,1,arguments.length),e instanceof im?(t=cg(this._delegate,e.toString()),new im(this,t)):(t=ug(this._delegate,e),new im(this,t))}refFromURL(e){l("database.refFromURL",1,1,arguments.length);var t=cg(this._delegate,e);return new im(this,t)}goOffline(){var e;l("database.goOffline",0,0,arguments.length),(e=w(e=this._delegate))._checkNotDeleted("goOffline"),Vf(e._repo)}goOnline(){return l("database.goOnline",0,0,arguments.length),Gg(this._delegate)}}sm.ServerValue={TIMESTAMP:Qg,increment:e=>({".sv":{increment:e}})};rr=Object.freeze({__proto__:null,initStandalone:function({app:e,url:t,version:r,customAuthImpl:n,customAppCheckImpl:i,namespace:s,nodeAdmin:a=!1}){Bh(r);var o=new Be("database-standalone"),l=new je("auth-internal",o);l.setComponent(new u("auth-internal",()=>n,"PRIVATE"));let h=void 0;return i&&(h=new je("app-check-internal",o)).setComponent(new u("app-check-internal",()=>i,"PRIVATE")),{instance:new sm(jg(e,l,h,t,a),e),namespace:s}}});let am=sm.ServerValue;(t=tr).INTERNAL.registerComponent(new u("database-compat",(e,{instanceIdentifier:t})=>{var r=e.getProvider("app-compat").getImmediate(),n=e.getProvider("database").getImmediate({identifier:t});return new sm(n,r)},"PUBLIC").setServiceProps({Reference:im,Query:nm,Database:sm,DataSnapshot:rm,enableLogging:$g,INTERNAL:rr,ServerValue:am}).setMultipleInstances(!0)),t.registerVersion("@firebase/database-compat","2.0.3");var om,lm,hm,um,cm,dm,pm,fm,gm,mm,vm,_m,ym="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},wm=(!(function(){var e,t,s;function r(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.B=Array(this.blockSize),this.o=this.h=0,this.s()}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=(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=t+(s^r&(i^s))+n[0]+3614090360&4294967295)<<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 h(e,t){this.h=t;for(var r=[],n=!0,i=e.length-1;0<=i;i--){var s=0|e[i];n&&s==t||(r[i]=s,n=!1)}this.g=r}t=r,s=function(){this.blockSize=-1},n.prototype=s.prototype,t.D=s.prototype,t.prototype=new n,(t.prototype.constructor=t).C=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.s=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.o=this.h=0},r.prototype.u=function(e,t){for(var r=(t=void 0===t?e.length:t)-this.blockSize,n=this.B,i=this.h,s=0;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.v=function(){var e=Array((this.h<56?this.blockSize:2*this.blockSize)-this.h);e[0]=128;for(var t=1;t<e.length-8;++t)e[t]=0;for(var r=8*this.o,t=e.length-8;t<e.length;++t)e[t]=255&r,r/=256;for(this.u(e),e=Array(16),t=r=0;t<4;++t)for(var n=0;n<32;n+=8)e[r++]=this.g[t]>>>n&255;return e};var i={};function o(e){return-128<=e&&e<128?(t=e,r=function(e){return new h([0|e],e<0?-1:0)},n=i,Object.prototype.hasOwnProperty.call(n,t)?n[t]:n[t]=r(t)):new h([0|e],e<0?-1:0);var t,r,n}function u(e){if(isNaN(e)||!isFinite(e))return c;if(e<0)return g(u(-e));for(var t=[],r=1,n=0;r<=e;n++)t[n]=e/r|0,r*=4294967296;return new h(t,0)}var c=o(0),l=o(1),d=o(16777216);function p(e){if(0==e.h){for(var t=0;t<e.g.length;t++)if(0!=e.g[t])return;return 1}}function f(e){return-1==e.h}function g(e){for(var t=e.g.length,r=[],n=0;n<t;n++)r[n]=~e.g[n];return new h(r,~e.h).add(l)}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=l,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=u(r)).j(t);f(a)||0<a.l(e);)a=(s=u(r-=n)).j(t);p(s)&&(s=l),i=i.add(s),e=m(e,a)}return new _(i,e)}function w(e){for(var t=e.g.length+1,r=[],n=0;n<t;n++)r[n]=e.i(n)<<1|e.i(n-1)>>>31;return new h(r,e.h)}function b(e,t){var r=t>>5;t%=32;for(var n=e.g.length-r,i=[],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 h(i,e.h)}(e=h.prototype).m=function(){if(f(this))return-g(this).m();for(var e=0,t=1,r=0;r<this.g.length;r++){var n=this.i(r);e+=(0<=n?n:4294967296+n)*t,t*=4294967296}return e},e.toString=function(e){if((e=e||10)<2||36<e)throw Error("radix out of range: "+e);if(p(this))return"0";if(f(this))return"-"+g(this).toString(e);for(var t=u(Math.pow(e,6)),r=this,n="";;){var i=y(r,t).g,s=((0<(r=m(r,i.j(t))).g.length?r.g[0]:r.h)>>>0).toString(e);if(p(r=i))return s+n;for(;s.length<6;)s="0"+s;n=s+n}},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){for(var t=Math.max(this.g.length,e.g.length),r=[],n=0,i=0;i<=t;i++){var s=n+(65535&this.i(i))+(65535&e.i(i)),a=(s>>>16)+(this.i(i)>>>16)+(e.i(i)>>>16),n=a>>>16;r[i]=(a&=65535)<<16|(s&=65535)}return new h(r,-2147483648&r[r.length-1]?-1:0)},e.j=function(e){if(p(this)||p(e))return c;if(f(this))return f(e)?g(this).j(g(e)):g(g(this).j(e));if(f(e))return g(this.j(g(e)));if(this.l(d)<0&&e.l(d)<0)return u(this.m()*e.m());for(var t=this.g.length+e.g.length,r=[],n=0;n<2*t;n++)r[n]=0;for(n=0;n<this.g.length;n++)for(var i=0;i<e.g.length;i++){var s=this.i(n)>>>16,a=65535&this.i(n),o=e.i(i)>>>16,l=65535&e.i(i);r[2*n+2*i]+=a*l,v(r,2*n+2*i),r[2*n+2*i+1]+=s*l,v(r,2*n+2*i+1),r[2*n+2*i+1]+=a*o,v(r,2*n+2*i+1),r[2*n+2*i+2]+=s*o,v(r,2*n+2*i+2)}for(n=0;n<t;n++)r[n]=r[2*n+1]<<16|r[2*n];for(n=t;n<2*t;n++)r[n]=0;return new h(r,0)},e.A=function(e){return y(this,e).h},e.and=function(e){for(var t=Math.max(this.g.length,e.g.length),r=[],n=0;n<t;n++)r[n]=this.i(n)&e.i(n);return new h(r,this.h&e.h)},e.or=function(e){for(var t=Math.max(this.g.length,e.g.length),r=[],n=0;n<t;n++)r[n]=this.i(n)|e.i(n);return new h(r,this.h|e.h)},e.xor=function(e){for(var t=Math.max(this.g.length,e.g.length),r=[],n=0;n<t;n++)r[n]=this.i(n)^e.i(n);return new h(r,this.h^e.h)},r.prototype.digest=r.prototype.v,r.prototype.reset=r.prototype.s,r.prototype.update=r.prototype.u,lm=r,h.prototype.multiply=h.prototype.j,h.prototype.modulo=h.prototype.A,h.prototype.compare=h.prototype.l,h.prototype.toNumber=h.prototype.m,h.prototype.getBits=h.prototype.i,h.fromNumber=u,h.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');for(var n=u(Math.pow(r,8)),i=c,s=0;s<t.length;s+=8)var a=Math.min(8,t.length-s),o=parseInt(t.substring(s,s+a),r),i=(a<8?(a=u(Math.pow(r,a)),i.j(a)):i=i.j(n)).add(u(o));return i},om=h}).apply(void 0!==ym?ym:"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,R="function"==typeof Object.defineProperties?Object.defineProperty:function(e,t,r){return e!=Array.prototype&&e!=Object.prototype&&(e[t]=r.value),e};var P=(e=>{e=["object"==typeof globalThis&&globalThis,e,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof wm&&wm];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);var t="Array.prototype.values",r=function(e){return e||function(){return r=function(e,t){return t},(t=this)instanceof String&&(t+=""),n=0,i=!1,(e={next:function(){var e;return!i&&n<t.length?(e=n++,{value:r(e,t[e]),done:!1}):{done:i=!0,value:void 0}}})[Symbol.iterator]=function(){return e},e;var t,r,n,i,e}};if(r)e:{var n=P;t=t.split(".");for(var i=0;i<t.length-1;i++){var U=t[i];if(!(U in n))break e;n=n[U]}(r=r(i=n[t=t[t.length-1]]))!=i&&null!=r&&R(n,t,{configurable:!0,writable:!0,value:r})}var V=V||{},D=this||self;function q(e){var t=typeof e;return"array"==(t="object"!=t?t:e?Array.isArray(e)?"array":t:"null")||"object"==t&&"number"==typeof e.length}function h(e){var t=typeof e;return"object"==t&&null!=e||"function"==t}function j(e,t,r){return e.call.apply(e.bind,arguments)}function B(t,r,e){var n;if(t)return 2<arguments.length?(n=Array.prototype.slice.call(arguments,2),function(){var e=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(e,n),t.apply(r,e)}):function(){return t.apply(r,arguments)};throw Error()}function m(e,t,r){return(m=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?j:B).apply(null,arguments)}function z(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 s(e,s){function t(){}t.prototype=s.prototype,e.aa=s.prototype,e.prototype=new t,(e.prototype.constructor=e).Qb=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)}}function K(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 W(t){for(let e=1;e<arguments.length;e++){var r=arguments[e];if(q(r)){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)}}function x(e){return/^[\s\xa0]*$/.test(e)}function a(){var e=D.navigator;return(e=e&&e.userAgent)||""}function H(e){return H[" "](e),e}H[" "]=function(){};var G=!(-1==a().indexOf("Gecko")||-1!=a().toLowerCase().indexOf("webkit")&&-1==a().indexOf("Edge")||-1!=a().indexOf("Trident")||-1!=a().indexOf("MSIE")||-1!=a().indexOf("Edge"));function $(e,t,r){for(var n in e)t.call(r,e[n],n,e)}function Q(e){var t,r={};for(t in e)r[t]=e[t];return r}let Y="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function J(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<Y.length;e++)r=Y[e],Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}}var X=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 Z,e=>e.reset());class Z{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 o,l=!1,ee=new class{constructor(){this.h=this.g=null}add(e,t){var r=X.get();r.set(e,t),this.h?this.h.next=r:this.g=r,this.h=r}},te=()=>{let e=D.Promise.resolve(void 0);o=()=>{e.then(re)}};var re=()=>{for(var e;e=(()=>{let e=ee,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=>{D.setTimeout(()=>{throw e},0)})(e)}var t=X;t.j(e),t.h<100&&(t.h++,e.next=t.g,t.g=e)}l=!1};function u(){this.s=this.s,this.C=this.C}function c(e,t){this.type=e,this.g=this.target=t,this.defaultPrevented=!1}u.prototype.s=!1,u.prototype.ma=function(){this.s||(this.s=!0,this.N())},u.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()},c.prototype.h=function(){this.defaultPrevented=!0};var ne=(()=>{if(!D.addEventListener||!Object.defineProperty)return!1;var e=!1,t=Object.defineProperty({},"passive",{get:function(){e=!0}});try{var r=()=>{};D.addEventListener("test",r,t),D.removeEventListener("test",r,t)}catch(e){}return e})();function d(e,t){if(c.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){var r=this.type=e.type,n=e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:null;if(this.target=e.target||e.srcElement,this.g=t,t=e.relatedTarget){if(G){e:{try{H(t.nodeName);var i=!0;break e}catch(e){}i=!1}i||(t=null)}}else"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="string"==typeof e.pointerType?e.pointerType:ie[e.pointerType]||"",this.state=e.state,(this.i=e).defaultPrevented&&d.aa.h.call(this)}}s(d,c);var ie={2:"touch",3:"pen",4:"mouse"},p=(d.prototype.h=function(){d.aa.h.call(this);var e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1},"closure_listenable_"+(1e6*Math.random()|0)),se=0;function ae(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=++se,this.da=this.fa=!1}function oe(e){e.da=!0,e.listener=null,e.proxy=null,e.src=null,e.ha=null}function le(e){this.src=e,this.g={},this.h=0}function he(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)&&(oe(t),0==e.g[s].length)&&(delete e.g[s],e.h--)}function ue(e,t,r,n){for(var i=0;i<e.length;++i){var s=e[i];if(!s.da&&s.listener==t&&s.capture==!!r&&s.ha==n)return i}return-1}le.prototype.add=function(e,t,r,n,i){var s=e.toString(),a=((e=this.g[s])||(e=this.g[s]=[],this.h++),ue(e,t,n,i));return-1<a?(t=e[a],r||(t.fa=!1)):((t=new ae(t,this.src,s,!!n,i)).fa=r,e.push(t)),t};var ce="closure_lm_"+(1e6*Math.random()|0),de={};function pe(e,t,r,n,i){if(n&&n.once)return 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);return null}n=we(n);return t&&t[p]?t.L(r,n,h(i)?!!i.capture:!!i,s):fe(t,r,n,!0,i,s)}(e,t,r,n,i);if(Array.isArray(t)){for(var s=0;s<t.length;s++)pe(e,t[s],r,n,i);return null}return r=we(r),e&&e[p]?e.K(t,r,h(n)?!!n.capture:!!n,i):fe(e,t,r,!1,n,i)}function fe(e,t,r,n,i,s){if(!t)throw Error("Invalid event type");var a=h(i)?!!i.capture:!!i,o=_e(e);if(o||(e[ce]=o=new le(e)),!(r=o.add(t,r,n,a,s)).proxy)if(n=(()=>{let r=ve;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=ne?i:a)&&(i=!1),e.addEventListener(t.toString(),n,i);else if(e.attachEvent)e.attachEvent(me(t.toString()),n);else{if(!e.addListener||!e.removeListener)throw Error("addEventListener and attachEvent are unavailable.");e.addListener(n)}return r}function ge(e){var t,r,n;"number"!=typeof e&&e&&!e.da&&((t=e.src)&&t[p]?he(t.i,e):(r=e.type,n=e.proxy,t.removeEventListener?t.removeEventListener(r,n,e.capture):t.detachEvent?t.detachEvent(me(r),n):t.addListener&&t.removeListener&&t.removeListener(n),(r=_e(t))?(he(r,e),0==r.h&&(r.src=null,t[ce]=null)):oe(e)))}function me(e){return e in de?de[e]:de[e]="on"+e}function ve(e,t){var r,n;return e=!!e.da||(t=new d(t,this),r=e.listener,n=e.ha||e.src,e.fa&&ge(e),r.call(n,t))}function _e(e){return(e=e[ce])instanceof le?e:null}var ye="__closure_events_fn_"+(1e9*Math.random()>>>0);function we(t){return"function"==typeof t?t:(t[ye]||(t[ye]=function(e){return t.handleEvent(e)}),t[ye])}function f(){u.call(this),this.i=new le(this),(this.M=this).F=null}function g(e,t){var r,n=e.F;if(n)for(r=[];n;n=n.F)r.push(n);if(e=e.M,n=t.type||t,"string"==typeof t?t=new c(t,e):t instanceof c?t.target=t.target||e:(a=t,J(t=new c(n,e),a)),a=!0,r)for(var i=r.length-1;0<=i;i--)var s=t.g=r[i],a=be(s,n,!0,t)&&a;if(a=be(s=t.g=e,n,!0,t)&&a,a=be(s,n,!1,t)&&a,r)for(i=0;i<r.length;i++)a=be(s=t.g=r[i],n,!1,t)&&a}function be(e,t,r,n){if(!(t=e.i.g[String(t)]))return!0;t=t.concat();for(var i=!0,s=0;s<t.length;++s){var a,o,l=t[s];l&&!l.da&&l.capture==r&&(a=l.listener,o=l.ha||l.src,l.fa&&he(e.i,l),i=!1!==a.call(o,n)&&i)}return i&&!n.defaultPrevented}function Ie(e,t,r){if("function"==typeof e)r&&(e=m(e,r));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=m(e.handleEvent,e)}return 2147483647<Number(t)?-1:D.setTimeout(e,t||0)}s(f,u),f.prototype[p]=!0,f.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=h(i)?!!i.capture:!!i,n=we(n),t&&t[p]?(t=t.i,(r=String(r).toString())in t.g&&-1<(n=ue(a=t.g[r],n,i,s))&&(oe(a[n]),Array.prototype.splice.call(a,n,1),0==a.length)&&(delete t.g[r],t.h--)):(t=t&&_e(t))&&(r=t.g[r.toString()],n=(t=-1)<(t=r?ue(r,n,i,s):t)?r[t]:null)&&ge(n)}(this,e,t,r,n)},f.prototype.N=function(){if(f.aa.N.call(this),this.i){var e,t=this.i;for(e in t.g){for(var r=t.g[e],n=0;n<r.length;n++)oe(r[n]);delete t.g[e],t.h--}}this.F=null},f.prototype.K=function(e,t,r,n){return this.i.add(String(e),t,!1,r,n)},f.prototype.L=function(e,t,r,n){return this.i.add(String(e),t,!0,r,n)};class Te extends u{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:function e(t){t.g=Ie(()=>{t.g=null,t.i&&(t.i=!1,e(t))},t.l);var r=t.h;t.h=null,t.m.apply(null,r)}(this)}N(){super.N(),this.g&&(D.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function v(e){u.call(this),this.h=e,this.g={}}s(v,u);var Ee=[];function Ce(e){$(e.g,function(e,t){this.g.hasOwnProperty(t)&&ge(e)},e),e.g={}}v.prototype.N=function(){v.aa.N.call(this),Ce(this)},v.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var ke=D.JSON.stringify,Se=D.JSON.parse,Ae=class{stringify(e){return D.JSON.stringify(e,void 0)}parse(e){return D.JSON.parse(e,void 0)}};function Ne(){}function Re(e){return e.h||(e.h=e.i())}function Pe(){}Ne.prototype.h=null;var De={OPEN:"a",kb:"b",Ja:"c",wb:"d"};function xe(){c.call(this,"d")}function Oe(){c.call(this,"c")}s(xe,c),s(Oe,c);var _={},Le=null;function Me(){return Le=Le||new f}function Fe(e){c.call(this,_.La,e)}function Ue(){var e=Me();g(e,new Fe(e))}function Ve(e,t){c.call(this,_.STAT_EVENT,e),this.stat=t}function O(e){var t=Me();g(t,new Ve(t,e))}function qe(e,t){c.call(this,_.Ma,e),this.size=t}function je(e,t){if("function"!=typeof e)throw Error("Fn must not be null and must be a function");return D.setTimeout(function(){e()},t)}function Be(){this.g=!0}function L(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(var a=1;a<i.length;a++)i[a]=""}}}return ke(r)}catch(e){return t}})(e,r)+(n?" "+n:"")})}_.La="serverreachability",s(Fe,c),_.STAT_EVENT="statevent",s(Ve,c),_.Ma="timingevent",s(qe,c),Be.prototype.xa=function(){this.g=!1},Be.prototype.info=function(){};var ze={NO_ERROR:0,gb:1,tb:2,sb:3,nb:4,rb:5,ub:6,Ia:7,TIMEOUT:8,xb:9},Ke={lb:"complete",Hb:"success",Ja:"error",Ia:"abort",zb:"ready",Ab:"readystatechange",TIMEOUT:"timeout",vb:"incrementaldata",yb:"progress",ob:"downloadprogress",Pb:"uploadprogress"};function We(){}function y(e,t,r,n){this.j=e,this.i=t,this.l=r,this.R=n||1,this.U=new v(this),this.I=45e3,this.H=null,this.o=!1,this.m=this.A=this.v=this.L=this.F=this.S=this.B=null,this.D=[],this.g=null,this.C=0,this.s=this.u=null,this.X=-1,this.J=!1,this.O=0,this.M=null,this.W=this.K=this.T=this.P=!1,this.h=new He}function He(){this.i=null,this.g="",this.h=!1}s(We,Ne),We.prototype.g=function(){return new XMLHttpRequest},We.prototype.i=function(){return{}};var Ge=new We,$e={},Qe={};function Ye(e,t,r){e.L=1,e.v=vt(b(t)),e.m=r,e.P=!0,Je(e,null)}function Je(e,t){e.F=Date.now(),Ze(e),e.A=b(e.v);var r=e.A,n=e.R,i=(Array.isArray(n)||(n=[String(n)]),Rt(r.i,"t",n),e.C=0,r=e.j.J,e.h=new He,e.g=cr(e.j,r?t:null,!e.m),0<e.O&&(e.M=new Te(m(e.Y,e,e.g),e.O)),t=e.U,r=e.g,n=e.ca,"readystatechange");Array.isArray(i)||(i&&(Ee[0]=i.toString()),i=Ee);for(var a,o,l,h,u,c,s=0;s<i.length;s++){var d=pe(r,i[s],n||t.handleEvent,!1,t.h||t);if(!d)break;t.g[d.key]=d}t=e.H?Q(e.H):{},e.m?(e.u||(e.u="POST"),t["Content-Type"]="application/x-www-form-urlencoded",e.g.ea(e.A,e.u,e.m,t)):(e.u="GET",e.g.ea(e.A,e.u,null,t)),Ue(),a=e.i,o=e.u,l=e.A,h=e.l,u=e.R,c=e.m,a.info(function(){if(a.g)if(c)for(var e="",t=c.split("&"),r=0;r<t.length;r++){var n,i,s=t[r].split("=");1<s.length&&(n=s[0],s=s[1],e=2<=(i=n.split("_")).length&&"type"==i[1]?e+(n+"=")+s+"&":e+(n+"=redacted&"))}else e=null;else e=c;return"XMLHTTP REQ ("+h+") [attempt "+u+"]: "+o+"\n"+l+"\n"+e})}function Xe(e){return e.g&&"GET"==e.u&&2!=e.L&&e.j.Ca}function Ze(e){e.S=Date.now()+e.I,et(e,e.I)}function et(e,t){if(null!=e.B)throw Error("WatchDog timer not null");e.B=je(m(e.ba,e),t)}function tt(e){e.B&&(D.clearTimeout(e.B),e.B=null)}function rt(e){0==e.j.G||e.J||or(e.j,e)}function M(e){tt(e);var t=e.M;t&&"function"==typeof t.ma&&t.ma(),e.M=null,Ce(e.U),e.g&&(t=e.g,e.g=null,t.abort(),t.ma())}function nt(e,t){try{var r=e.j;if(0!=r.G&&(r.g==e||lt(r.h,e)))if(!e.K&<(r.h,e)&&3==r.G){try{var n=r.Da.g.parse(t)}catch(e){n=null}if(Array.isArray(n)&&3==n.length){var i=n;if(0==i[0]){e:if(!r.u){if(r.g){if(!(r.g.F+3e3<e.F))break e;ar(r),Yt(r)}nr(r),O(18)}}else r.za=i[1],0<r.za-r.T&&i[2]<37500&&r.F&&0==r.v&&!r.C&&(r.C=je(m(r.Za,r),6e3));if(ot(r.h)<=1&&r.ca){try{r.ca()}catch(e){}r.ca=void 0}}else S(r,11)}else if(!e.K&&r.g!=e||ar(r),!x(t))for(i=r.Da.g.parse(t),t=0;t<i.length;t++){var s,a,o,l,h,u,c,d,p,f,g=i[t];r.T=g[0],g=g[1],2==r.G?"c"==g[0]?(r.K=g[1],r.ia=g[2],null!=(s=g[3])&&(r.la=s,r.j.info("VER="+r.la)),null!=(a=g[4])&&(r.Aa=a,r.j.info("SVER="+r.Aa)),null!=(o=g[5])&&"number"==typeof o&&0<o&&(n=1.5*o,r.L=n,r.j.info("backChannelRequestTimeoutMs_="+n)),n=r,(l=e.g)&&(!(h=l.g?l.g.getResponseHeader("X-Client-Wire-Protocol"):null)||(u=n.h).g||-1==h.indexOf("spdy")&&-1==h.indexOf("quic")&&-1==h.indexOf("h2")||(u.j=u.l,u.g=new Set,u.h&&(ht(u,u.h),u.h=null)),n.D)&&(c=l.g?l.g.getResponseHeader("X-HTTP-Session-Id"):null)&&(n.ya=c,I(n.I,n.D,c)),r.G=3,r.l&&r.l.ua(),r.ba&&(r.R=Date.now()-e.F,r.j.info("Handshake RTT: "+r.R+"ms")),d=e,(n=r).qa=ur(n,n.J?n.ia:null,n.W),d.K?(ut(n.h,d),p=d,(f=n.L)&&(p.I=f),p.B&&(tt(p),Ze(p)),n.g=d):rr(n),0<r.i.length&&Xt(r)):"stop"!=g[0]&&"close"!=g[0]||S(r,7):3==r.G&&("stop"==g[0]||"close"==g[0]?"stop"==g[0]?S(r,7):Qt(r):"noop"!=g[0]&&r.l&&r.l.ta(g),r.v=0)}Ue()}catch(e){}}y.prototype.ca=function(e){e=e.target;var t=this.M;t&&3==F(e)?t.j():this.Y(e)},y.prototype.Y=function(e){try{if(e==this.g)e:{var t=F(this.g),r=this.g.Ba();this.g.Z();if(!(t<3)&&(3!=t||this.g&&(this.h.h||this.g.oa()||Ht(this.g)))){this.J||4!=t||7==r||Ue(),tt(this);var n=this.g.Z();this.X=n;t:if(Xe(this)){var i=Ht(this.g),s=(e="",i.length),a=4==F(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){M(this),rt(this);var o="";break t}this.h.i=new D.TextDecoder}for(r=0;r<s;r++)this.h.h=!0,e+=this.h.i.decode(i[r],{stream:!(a&&r==s-1)});i.length=0,this.h.g+=e,this.C=0,o=this.h.g}else o=this.g.oa();if(this.o=200==n,C=this.i,k=this.u,S=this.A,A=this.l,N=this.R,R=t,P=n,C.info(function(){return"XMLHTTP RESP ("+A+") [ attempt "+N+"]: "+k+"\n"+S+"\n"+R+" "+P}),this.o){if(this.T&&!this.K){t:{if(this.g){var l,h=this.g;if((l=h.g?h.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!x(l)){var u=l;break t}}u=null}if(!(n=u)){this.o=!1,this.s=3,O(12),M(this),rt(this);break e}L(this.i,this.l,n,"Initial handshake response via X-HTTP-Initial-Response"),this.K=!0,nt(this,n)}if(this.P){for(var c,d,n=!0;!this.J&&this.C<o.length;){if(I=o,E=T=void 0,T=(b=this).C,(c=-1==(E=I.indexOf("\n",T))?Qe:(T=Number(I.substring(T,E)),isNaN(T)?$e:(E+=1)+T>I.length?Qe:(I=I.slice(E,E+T),b.C=E+T,I)))==Qe){4==t&&(this.s=4,O(14),n=!1),L(this.i,this.l,null,"[Incomplete Response]");break}if(c==$e){this.s=4,O(15),L(this.i,this.l,o,"[Invalid Chunk]"),n=!1;break}L(this.i,this.l,c,null),nt(this,c)}Xe(this)&&0!=this.C&&(this.h.g=this.h.g.slice(this.C),this.C=0),4!=t||0!=o.length||this.h.h||(this.s=1,O(16),n=!1),this.o=this.o&&n,n?0<o.length&&!this.W&&(this.W=!0,(d=this.j).g==this)&&d.ba&&!d.M&&(d.j.info("Great, no buffering proxy detected. Bytes received: "+o.length),ir(d),d.M=!0,O(11)):(L(this.i,this.l,o,"[Invalid Chunked Response]"),M(this),rt(this))}else L(this.i,this.l,o,null),nt(this,o);4==t&&M(this),this.o&&!this.J&&(4==t?or(this.j,this):(this.o=!1,Ze(this)))}else{{var p=this.g;var f,g,m,v={};p=(p.g&&2<=F(p)&&p.g.getAllResponseHeaders()||"").split("\r\n");for(let e=0;e<p.length;e++)x(p[e])||(f=(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})(p[e]),g=f[0],"string"==typeof(f=f[1])&&(f=f.trim(),m=v[g]||[],(v[g]=m).push(f)));var _,y=v,w=function(e){return e.join(", ")};for(_ in y)w.call(void 0,y[_],_,y)}400==n&&0<o.indexOf("Unknown SID")?(this.s=3,O(12)):(this.s=0,O(13)),M(this),rt(this)}}}}catch(e){}var b,I,T,E,C,k,S,A,N,R,P},y.prototype.cancel=function(){this.J=!0,M(this)},y.prototype.ba=function(){this.B=null;var e,t,r=Date.now();0<=r-this.S?(e=this.i,t=this.A,e.info(function(){return"TIMEOUT: "+t}),2!=this.L&&(Ue(),O(17)),M(this),this.s=2,rt(this)):et(this,this.S-r)};var it=class{constructor(e,t){this.g=e,this.map=t}};function st(e){this.l=e||10,e=D.PerformanceNavigationTiming?0<(e=D.performance.getEntriesByType("navigation")).length&&("hq"==e[0].nextHopProtocol||"h2"==e[0].nextHopProtocol):!!(D.chrome&&D.chrome.loadTimes&&D.chrome.loadTimes()&&D.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 at(e){return e.h||e.g&&e.g.size>=e.j}function ot(e){return e.h?1:e.g?e.g.size:0}function lt(e,t){return e.h?e.h==t:e.g&&e.g.has(t)}function ht(e,t){e.g?e.g.add(t):e.h=t}function ut(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function ct(t){if(null!=t.h)return t.i.concat(t.h.D);if(null==t.g||0===t.g.size)return K(t.i);{let e=t.i;for(var r of t.g.values())e=e.concat(r.D);return e}}function dt(e,t){if(e.forEach&&"function"==typeof e.forEach)e.forEach(t,void 0);else if(q(e)||"string"==typeof e)Array.prototype.forEach.call(e,t,void 0);else for(var r=(e=>{if(e.na&&"function"==typeof e.na)return e.na();if(!e.V||"function"!=typeof e.V){if("undefined"!=typeof Map&&e instanceof Map)return Array.from(e.keys());if(!("undefined"!=typeof Set&&e instanceof Set)){if(q(e)||"string"==typeof e){var t=[];e=e.length;for(var r=0;r<e;r++)t.push(r)}else for(var n in t=[],r=0,e)t[r++]=n;return t}}})(e),n=(e=>{if(e.V&&"function"==typeof e.V)return e.V();if("undefined"!=typeof Map&&e instanceof Map||"undefined"!=typeof Set&&e instanceof Set)return Array.from(e.values());if("string"==typeof e)return e.split("");if(q(e))for(var t=[],r=e.length,n=0;n<r;n++)t.push(e[n]);else for(n in t=[],r=0,e)t[r++]=e[n];return t})(e),i=n.length,s=0;s<i;s++)t.call(void 0,n[s],r&&r[s],e)}st.prototype.cancel=function(){if(this.i=ct(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 pt=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function w(e){var t,r;this.g=this.o=this.j="",this.s=null,this.m=this.l="",this.h=!1,e instanceof w?(this.h=e.h,ft(this,e.j),this.o=e.o,this.g=e.g,gt(this,e.s),this.l=e.l,t=e.i,(r=new St).i=t.i,t.g&&(r.g=new Map(t.g),r.h=t.h),mt(this,r),this.m=e.m):e&&(t=String(e).match(pt))?(this.h=!1,ft(this,t[1]||"",!0),this.o=_t(t[2]||""),this.g=_t(t[3]||"",!0),gt(this,t[4]),this.l=_t(t[5]||"",!0),mt(this,t[6]||"",!0),this.m=_t(t[7]||"")):(this.h=!1,this.i=new St(null,this.h))}function b(e){return new w(e)}function ft(e,t,r){e.j=r?_t(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function gt(e,t){if(t){if(t=Number(t),isNaN(t)||t<0)throw Error("Bad port number "+t);e.s=t}else e.s=null}function mt(e,t,r){var n,i;t instanceof St?(e.i=t,n=e.i,(i=e.h)&&!n.j&&(T(n),n.i=null,n.g.forEach(function(e,t){var r=t.toLowerCase();t!=r&&(At(this,t),Rt(this,r,e))},n)),n.j=i):(r||(t=yt(t,Ct)),e.i=new St(t,e.h))}function I(e,t,r){e.i.set(t,r)}function vt(e){return I(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function _t(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function yt(e,t,r){return"string"==typeof e?(e=encodeURI(e).replace(t,wt),e=r?e.replace(/%25([0-9a-fA-F]{2})/g,"%$1"):e):null}function wt(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}w.prototype.toString=function(){var e=[],t=this.j,r=(t&&e.push(yt(t,It,!0),":"),this.g);return!r&&"file"!=t||(e.push("//"),(t=this.o)&&e.push(yt(t,It,!0),"@"),e.push(encodeURIComponent(String(r)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null==(r=this.s))||e.push(":",String(r)),(r=this.l)&&(this.g&&"/"!=r.charAt(0)&&e.push("/"),e.push(yt(r,"/"==r.charAt(0)?Et:Tt,!0))),(r=this.i.toString())&&e.push("?",r),(r=this.m)&&e.push("#",yt(r,kt)),e.join("")};var bt,It=/[#\/\?@]/g,Tt=/[#\?:]/g,Et=/[#\?]/g,Ct=/[#\?@]/g,kt=/#/g;function St(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function T(r){if(!r.g&&(r.g=new Map,r.h=0,r.i)){var e=r.i,t=function(e,t){r.add(decodeURIComponent(e.replace(/\+/g," ")),t)};if(e){e=e.split("&");for(var n=0;n<e.length;n++){var i,s=e[n].indexOf("="),a=null;0<=s?(i=e[n].substring(0,s),a=e[n].substring(s+1)):i=e[n],t(i,a?decodeURIComponent(a.replace(/\+/g," ")):"")}}}}function At(e,t){T(e),t=E(e,t),e.g.has(t)&&(e.i=null,e.h-=e.g.get(t).length,e.g.delete(t))}function Nt(e,t){return T(e),t=E(e,t),e.g.has(t)}function Rt(e,t,r){At(e,t),0<r.length&&(e.i=null,e.g.set(E(e,t),K(r)),e.h+=r.length)}function E(e,t){return t=String(t),t=e.j?t.toLowerCase():t}function C(e,t,r,n,i){try{i&&(i.onload=null,i.onerror=null,i.onabort=null,i.ontimeout=null),n(r)}catch(e){}}function Pt(){this.g=new Ae}function Dt(e){this.l=e.Ub||null,this.j=e.eb||!1}function xt(e,t){f.call(this),this.D=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.u=new Headers,this.h=null,this.B="GET",this.A="",this.g=!1,this.v=this.j=this.l=null}function Ot(e){e.j.read().then(e.Pa.bind(e)).catch(e.ga.bind(e))}function Lt(e){e.readyState=4,e.l=null,e.j=null,e.v=null,Mt(e)}function Mt(e){e.onreadystatechange&&e.onreadystatechange.call(e)}function Ft(e){let r="";return $(e,function(e,t){r=(r=r+t+":")+e+"\r\n"}),r}function Ut(e,t,r){e:{for(n in r){var n=!1;break e}n=!0}n||(r=Ft(r),"string"==typeof e?null!=r&&encodeURIComponent(String(r)):I(e,t,r))}function k(e){f.call(this),this.headers=new Map,this.o=e||null,this.h=!1,this.v=this.g=null,this.D="",this.m=0,this.l="",this.j=this.B=this.u=this.A=!1,this.I=null,this.H="",this.J=!1}(e=St.prototype).add=function(e,t){T(this),this.i=null,e=E(this,e);var r=this.g.get(e);return r||this.g.set(e,r=[]),r.push(t),this.h+=1,this},e.forEach=function(r,n){T(this),this.g.forEach(function(e,t){e.forEach(function(e){r.call(n,e,t,this)},this)},this)},e.na=function(){T(this);var t=Array.from(this.g.values()),r=Array.from(this.g.keys()),n=[];for(let s=0;s<r.length;s++){var i=t[s];for(let e=0;e<i.length;e++)n.push(r[s])}return n},e.V=function(t){T(this);let r=[];if("string"==typeof t)Nt(this,t)&&(r=r.concat(this.g.get(E(this,t))));else{t=Array.from(this.g.values());for(let e=0;e<t.length;e++)r=r.concat(t[e])}return r},e.set=function(e,t){return T(this),this.i=null,Nt(this,e=E(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=this.V(e)).length?String(e[0]):t},e.toString=function(){if(this.i)return this.i;if(!this.g)return"";for(var e=[],t=Array.from(this.g.keys()),r=0;r<t.length;r++)for(var n=t[r],i=encodeURIComponent(String(n)),s=this.V(n),n=0;n<s.length;n++){var a=i;""!==s[n]&&(a+="="+encodeURIComponent(String(s[n]))),e.push(a)}return this.i=e.join("&")},s(Dt,Ne),Dt.prototype.g=function(){return new xt(this.l,this.j)},Dt.prototype.i=(bt={},function(){return bt}),s(xt,f),(e=xt.prototype).open=function(e,t){if(0!=this.readyState)throw this.abort(),Error("Error reopening a connection");this.B=e,this.A=t,this.readyState=1,Mt(this)},e.send=function(e){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.g=!0;var t={headers:this.u,method:this.B,credentials:this.m,cache:void 0};e&&(t.body=e),(this.D||D).fetch(new Request(this.A,t)).then(this.Sa.bind(this),this.ga.bind(this))},e.abort=function(){this.response=this.responseText="",this.u=new Headers,this.status=0,this.j&&this.j.cancel("Request was aborted.").catch(()=>{}),1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,Lt(this)),this.readyState=0},e.Sa=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,Mt(this)),this.g)&&(this.readyState=3,Mt(this),this.g))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Qa.bind(this),this.ga.bind(this));else if(void 0!==D.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.v=new TextDecoder;Ot(this)}else e.text().then(this.Ra.bind(this),this.ga.bind(this))},e.Pa=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.v.decode(t,{stream:!e.done}))&&(this.response=this.responseText+=t),(e.done?Lt:Mt)(this),3==this.readyState)&&Ot(this)},e.Ra=function(e){this.g&&(this.response=this.responseText=e,Lt(this))},e.Qa=function(e){this.g&&(this.response=e,Lt(this))},e.ga=function(){this.g&&Lt(this)},e.setRequestHeader=function(e,t){this.u.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(xt.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}}),s(k,f);var Vt=/^https?$/i,qt=["POST","PUT"];function jt(e,t){e.h=!1,e.g&&(e.j=!0,e.g.abort(),e.j=!1),e.l=t,e.m=5,Bt(e),Kt(e)}function Bt(e){e.A||(e.A=!0,g(e,"complete"),g(e,"error"))}function zt(e){if(e.h&&void 0!==V&&(!e.v[1]||4!=F(e)||2!=e.Z()))if(e.u&&4==F(e))Ie(e.Ea,0,e);else if(g(e,"readystatechange"),4==F(e)){e.h=!1;try{var t,r,n,i=e.Z();switch(i){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var s=!0;break;default:s=!1}if((t=s)||((r=0===i)&&(!(n=String(e.D).match(pt)[1]||null)&&D.self&&D.self.location&&(n=D.self.location.protocol.slice(0,-1)),r=!Vt.test(n?n.toLowerCase():"")),t=r),t)g(e,"complete"),g(e,"success");else{e.m=6;try{var a=2<F(e)?e.g.statusText:""}catch(e){a=""}e.l=a+" ["+e.Z()+"]",Bt(e)}}finally{Kt(e)}}}function Kt(e,t){if(e.g){Wt(e);var r=e.g,n=e.v[0]?()=>{}:null;e.g=null,e.v=null,t||g(e,"ready");try{r.onreadystatechange=n}catch(e){}}}function Wt(e){e.I&&(D.clearTimeout(e.I),e.I=null)}function F(e){return e.g?e.g.readyState:0}function Ht(e){try{if(e.g){if("response"in e.g)return e.g.response;switch(e.H){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 Gt(e,t,r){return r&&r.internalChannelParams&&r.internalChannelParams[e]||t}function $t(e){this.Aa=0,this.i=[],this.j=new Be,this.ia=this.qa=this.I=this.W=this.g=this.ya=this.D=this.H=this.m=this.S=this.o=null,this.Ya=this.U=0,this.Va=Gt("failFast",!1,e),this.F=this.C=this.u=this.s=this.l=null,this.X=!0,this.za=this.T=-1,this.Y=this.v=this.B=0,this.Ta=Gt("baseRetryDelayMs",5e3,e),this.cb=Gt("retryDelaySeedMs",1e4,e),this.Wa=Gt("forwardChannelMaxRetries",2,e),this.wa=Gt("forwardChannelRequestTimeoutMs",2e4,e),this.pa=e&&e.xmlHttpFactory||void 0,this.Xa=e&&e.Tb||void 0,this.Ca=e&&e.useFetchStreams||!1,this.L=void 0,this.J=e&&e.supportsCrossDomainXhr||!1,this.K="",this.h=new st(e&&e.concurrentRequestLimit),this.Da=new Pt,this.P=e&&e.fastHandshake||!1,this.O=e&&e.encodeInitMessageHeaders||!1,this.P&&this.O&&(this.O=!1),this.Ua=e&&e.Rb||!1,e&&e.xa&&this.j.xa(),e&&e.forceLongPolling&&(this.X=!1),this.ba=!this.P&&this.X&&e&&e.detectBufferingProxy||!1,this.ja=void 0,e&&e.longPollingTimeout&&0<e.longPollingTimeout&&(this.ja=e.longPollingTimeout),this.ca=void 0,this.R=0,this.M=!1,this.ka=this.A=null}function Qt(e){if(Jt(e),3==e.G){var t=e.U++,r=b(e.I);if(I(r,"SID",e.K),I(r,"RID",t),I(r,"TYPE","terminate"),er(e,r),(t=new y(e,e.j,t)).L=2,t.v=vt(b(r)),r=!1,D.navigator&&D.navigator.sendBeacon)try{r=D.navigator.sendBeacon(t.v.toString(),"")}catch(e){}!r&&D.Image&&((new Image).src=t.v,r=!0),r||(t.g=cr(t.j,null),t.g.ea(t.v)),t.F=Date.now(),Ze(t)}hr(e)}function Yt(e){e.g&&(ir(e),e.g.cancel(),e.g=null)}function Jt(e){Yt(e),e.u&&(D.clearTimeout(e.u),e.u=null),ar(e),e.h.cancel(),e.s&&("number"==typeof e.s&&D.clearTimeout(e.s),e.s=null)}function Xt(e){var t;at(e.h)||e.s||(e.s=!0,t=e.Ga,o||te(),l||(o(),l=!0),ee.add(t,e),e.B=0)}function Zt(e,t){var r=t?t.l:e.U++,n=b(e.I);I(n,"SID",e.K),I(n,"RID",r),I(n,"AID",e.T),er(e,n),e.m&&e.o&&Ut(n,e.m,e.o),r=new y(e,e.j,r,e.B+1),null===e.m&&(r.H=e.o),t&&(e.i=t.D.concat(e.i)),t=tr(e,r,1e3),r.I=Math.round(.5*e.wa)+Math.round(.5*e.wa*Math.random()),ht(e.h,r),Ye(r,n,t)}function er(e,r){e.H&&$(e.H,function(e,t){I(r,t,e)}),e.l&&dt({},function(e,t){I(r,t,e)})}function tr(e,t,i){i=Math.min(e.i.length,i);var s=e.l?m(e.l.Na,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{((e,n,t)=>{let i=t||"";try{dt(e,function(e,t){let r=e;h(e)&&(r=ke(e)),n.push(i+t+"="+encodeURIComponent(r))})}catch(e){throw n.push(i+"type="+encodeURIComponent("_badmap")),e}})(l,a,"req"+o+"_")}catch(e){s&&s(l)}}if(e){s=a.join("&");break e}}}return e=e.i.splice(0,i),t.D=e,s}function rr(e){var t;e.g||e.u||(e.Y=1,t=e.Fa,o||te(),l||(o(),l=!0),ee.add(t,e),e.v=0)}function nr(e){return!(e.g||e.u||3<=e.v)&&(e.Y++,e.u=je(m(e.Fa,e),lr(e,e.v)),e.v++,1)}function ir(e){null!=e.A&&(D.clearTimeout(e.A),e.A=null)}function sr(e){e.g=new y(e,e.j,"rpc",e.Y),null===e.m&&(e.g.H=e.o),e.g.O=0;var t=b(e.qa),r=(I(t,"RID","rpc"),I(t,"SID",e.K),I(t,"AID",e.T),I(t,"CI",e.F?"0":"1"),!e.F&&e.ja&&I(t,"TO",e.ja),I(t,"TYPE","xmlhttp"),er(e,t),e.m&&e.o&&Ut(t,e.m,e.o),e.L&&(e.g.I=e.L),e.g);e=e.ia,r.L=1,r.v=vt(b(t)),r.m=null,r.P=!0,Je(r,e)}function ar(e){null!=e.C&&(D.clearTimeout(e.C),e.C=null)}function or(e,t){var r,n,i,s=null;if(e.g==t){ar(e),ir(e),e.g=null;var a=2}else{if(!lt(e.h,t))return;s=t.D,ut(e.h,t),a=1}if(0!=e.G)if(t.o)(1==a?(s=t.m?t.m.length:0,t=Date.now()-t.F,r=e.B,g(a=Me(),new qe(a,s)),Xt):rr)(e);else if(3==(r=t.s)||0==r&&0<t.X||(1!=a||(i=t,ot((n=e).h)>=n.h.j-(n.s?1:0))||(n.s?(n.i=i.D.concat(n.i),0):1==n.G||2==n.G||n.B>=(n.Va?0:n.Wa)||(n.s=je(m(n.Ga,n,i),lr(n,n.B)),n.B++,0)))&&(2!=a||!nr(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 lr(e,t){let r=e.Ta+Math.floor(Math.random()*e.cb);return e.isActive()||(r*=2),r*t}function S(e,t){var r,n,i;e.j.info("Error code "+t),2==t?(r=m(e.fb,e),n=!(i=e.Xa),i=new w(i||"//www.google.com/images/cleardot.gif"),D.location&&"http"==D.location.protocol||ft(i,"https"),vt(i),(n?(t,r)=>{var n=new Be;if(D.Image){let e=new Image;e.onload=z(C,n,"TestLoadImage: loaded",!0,r,e),e.onerror=z(C,n,"TestLoadImage: error",!1,r,e),e.onabort=z(C,n,"TestLoadImage: abort",!1,r,e),e.ontimeout=z(C,n,"TestLoadImage: timeout",!1,r,e),D.setTimeout(function(){e.ontimeout&&e.ontimeout()},1e4),e.src=t}else r(!1)}:(e,t)=>{let r=new Be,n=new AbortController,i=setTimeout(()=>{n.abort(),C(r,0,!1,t)},1e4);fetch(e,{signal:n.signal}).then(e=>{clearTimeout(i),e.ok?C(r,0,!0,t):C(r,0,!1,t)}).catch(()=>{clearTimeout(i),C(r,0,!1,t)})})(i.toString(),r)):O(2),e.G=0,e.l&&e.l.sa(t),hr(e),Jt(e)}function hr(e){var t;e.G=0,e.ka=[],e.l&&(0==(t=ct(e.h)).length&&0==e.i.length||(W(e.ka,t),W(e.ka,e.i),e.h.i.length=0,K(e.i),e.i.length=0),e.l.ra())}function ur(e,t,r){var n,i,s=r instanceof w?b(r):new w(r);return""!=s.g?(t&&(s.g=t+"."+s.g),gt(s,s.s)):(s=(n=D.location).protocol,t=t?t+"."+n.hostname:n.hostname,n=+n.port,i=new w(null),s&&ft(i,s),t&&(i.g=t),n&>(i,n),r&&(i.l=r),s=i),r=e.D,t=e.ya,r&&t&&I(s,r,t),I(s,"VER",e.la),er(e,s),s}function cr(e,t,r){if(t&&!e.J)throw Error("Can't create secondary domain capable XhrIo object.");return(t=e.Ca&&!e.pa?new k(new Dt({eb:r})):new k(e.pa)).Ha(e.J),t}function dr(){}function pr(){}function A(e,t){f.call(this),this.g=new $t(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.va&&(e?e["X-WebChannel-Client-Profile"]=t.va:e={"X-WebChannel-Client-Profile":t.va}),this.g.S=e,(e=t&&t.Sb)&&!x(e)&&(this.g.m=e),this.v=t&&t.supportsCrossDomainXhr||!1,this.u=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!x(t)&&(this.g.D=t,null!==(e=this.h))&&t in e&&t in(e=this.h)&&delete e[t],this.j=new N(this)}function fr(e){xe.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 gr(){Oe.call(this),this.status=1}function N(e){this.g=e}(e=k.prototype).Ha=function(e){this.J=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.m=0,this.A=!1,this.h=!0,this.g=(this.o||Ge).g(),this.v=this.o?Re(this.o):Re(Ge),this.g.onreadystatechange=m(this.Ea,this);try{this.B=!0,this.g.open(t,String(e),!0),this.B=!1}catch(e){return void jt(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=D.FormData&&e instanceof D.FormData,0<=Array.prototype.indexOf.call(qt,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.H&&(this.g.responseType=this.H),"withCredentials"in this.g&&this.g.withCredentials!==this.J&&(this.g.withCredentials=this.J);try{Wt(this),this.u=!0,this.g.send(e),this.u=!1}catch(e){jt(this,e)}},e.abort=function(e){this.g&&this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1,this.m=e||7,g(this,"complete"),g(this,"abort"),Kt(this))},e.N=function(){this.g&&(this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1),Kt(this,!0)),k.aa.N.call(this)},e.Ea=function(){this.s||(this.B||this.u||this.j?zt(this):this.bb())},e.bb=function(){zt(this)},e.isActive=function(){return!!this.g},e.Z=function(){try{return 2<F(this)?this.g.status:-1}catch(e){return-1}},e.oa=function(){try{return this.g?this.g.responseText:""}catch(e){return""}},e.Oa=function(e){var t;if(this.g)return t=this.g.responseText,e&&0==t.indexOf(e)&&(t=t.substring(e.length)),Se(t)},e.Ba=function(){return this.m},e.Ka=function(){return"string"==typeof this.l?this.l:String(this.l)},(e=$t.prototype).la=8,e.G=1,e.connect=function(e,t,r,n){O(0),this.W=e,this.H=t||{},r&&void 0!==n&&(this.H.OSID=r,this.H.OAID=n),this.F=this.X,this.I=ur(this,null,this.W),Xt(this)},e.Ga=function(t){if(this.s)if(this.s=null,1==this.G){if(!t){this.U=Math.floor(1e5*Math.random()),t=this.U++;var r=new y(this,this.j,t);let e=this.o;if(this.S&&(e?J(e=Q(e),this.S):e=this.S),null!==this.m||this.O||(r.H=e,e=null),this.P)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=tr(this,r,n),I(i=b(this.I),"RID",t),I(i,"CVER",22),this.D&&I(i,"X-HTTP-Session-Id",this.D),er(this,i),e&&(this.O?n="headers="+encodeURIComponent(String(Ft(e)))+"&"+n:this.m&&Ut(i,this.m,e)),ht(this.h,r),this.Ua&&I(i,"TYPE","init"),this.P?(I(i,"$req",n),I(i,"SID","null"),r.T=!0,Ye(r,i,null)):Ye(r,i,n),this.G=2}}else 3==this.G&&(t?Zt(this,t):0==this.i.length||at(this.h)||Zt(this))},e.Fa=function(){var e;this.u=null,sr(this),this.ba&&!(this.M||null==this.g||this.R<=0)&&(e=2*this.R,this.j.info("BP detection timer enabled: "+e),this.A=je(m(this.ab,this),e))},e.ab=function(){this.A&&(this.A=null,this.j.info("BP detection timeout reached."),this.j.info("Buffering proxy detected and switch to long-polling!"),this.F=!1,this.M=!0,O(10),Yt(this),sr(this))},e.Za=function(){null!=this.C&&(this.C=null,Yt(this),nr(this),O(19))},e.fb=function(e){e?(this.j.info("Successfully pinged google.com"),O(2)):(this.j.info("Failed to ping google.com"),O(1))},e.isActive=function(){return!!this.l&&this.l.isActive(this)},(e=dr.prototype).ua=function(){},e.ta=function(){},e.sa=function(){},e.ra=function(){},e.isActive=function(){return!0},e.Na=function(){},pr.prototype.g=function(e,t){return new A(e,t)},s(A,f),A.prototype.m=function(){this.g.l=this.j,this.v&&(this.g.J=!0),this.g.connect(this.l,this.h||void 0)},A.prototype.close=function(){Qt(this.g)},A.prototype.o=function(e){var t,r=this.g;"string"==typeof e?((t={}).__data__=e,e=t):this.u&&((t={}).__data__=ke(e),e=t),r.i.push(new it(r.Ya++,e)),3==r.G&&Xt(r)},A.prototype.N=function(){this.g.l=null,delete this.j,Qt(this.g),delete this.g,A.aa.N.call(this)},s(fr,xe),s(gr,Oe),s(N,dr),N.prototype.ua=function(){g(this.g,"a")},N.prototype.ta=function(e){g(this.g,new fr(e))},N.prototype.sa=function(e){g(this.g,new gr)},N.prototype.ra=function(){g(this.g,"b")},pr.prototype.createWebChannel=pr.prototype.g,A.prototype.send=A.prototype.o,A.prototype.open=A.prototype.m,mm=function(){return new pr},gm=Me,fm=_,pm={mb:0,pb:1,qb:2,Jb:3,Ob:4,Lb:5,Mb:6,Kb:7,Ib:8,Nb:9,PROXY:10,NOPROXY:11,Gb:12,Cb:13,Db:14,Bb:15,Eb:16,Fb:17,ib:18,hb:19,jb:20},ze.NO_ERROR=0,ze.TIMEOUT=8,ze.HTTP_ERROR=6,dm=ze,Ke.COMPLETE="complete",cm=Ke,(Pe.EventType=De).OPEN="a",De.CLOSE="b",De.ERROR="c",De.MESSAGE="d",f.prototype.listen=f.prototype.K,um=Pe,k.prototype.listenOnce=k.prototype.L,k.prototype.getLastError=k.prototype.Ka,k.prototype.getLastErrorCode=k.prototype.Ba,k.prototype.getStatus=k.prototype.Z,k.prototype.getResponseJson=k.prototype.Oa,k.prototype.getResponseText=k.prototype.oa,k.prototype.send=k.prototype.ea,k.prototype.setWithCredentials=k.prototype.Ha,hm=k}).apply(void 0!==wm?wm:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});let bm="@firebase/firestore";class Im{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}}Im.UNAUTHENTICATED=new Im(null),Im.GOOGLE_CREDENTIALS=new Im("google-credentials-uid"),Im.FIRST_PARTY=new Im("first-party-uid"),Im.MOCK_USER=new Im("mock-user");let Tm="11.3.1",Em=new $e("@firebase/firestore");function Cm(){return Em.logLevel}function C(e,...t){var r;Em.logLevel<=c.DEBUG&&(r=t.map(Am),Em.debug(`Firestore (${Tm}): `+e,...r))}function km(e,...t){var r;Em.logLevel<=c.ERROR&&(r=t.map(Am),Em.error(`Firestore (${Tm}): `+e,...r))}function Sm(e,...t){var r;Em.logLevel<=c.WARN&&(r=t.map(Am),Em.warn(`Firestore (${Tm}): `+e,...r))}function Am(t){if("string"==typeof t)return t;try{return JSON.stringify(t)}catch(e){return t}}function k(e="Unexpected state"){var t=`FIRESTORE (${Tm}) INTERNAL ASSERTION FAILED: `+e;throw km(t),new Error(t)}function S(e){e||k()}let A={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 N extends de{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: `+this.message}}class Nm{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class Rm{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization","Bearer "+e)}}class Pm{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(Im.UNAUTHENTICATED))}shutdown(){}}class Dm{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 xm{constructor(e){this.t=e,this.currentUser=Im.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(t,r){S(void 0===this.o);let n=this.i,i=e=>this.i!==n?(n=this.i,r(e)):Promise.resolve(),s=new Nm,a=(this.o=()=>{this.i++,this.currentUser=this.u(),s.resolve(),s=new Nm,t.enqueueRetryable(()=>i(this.currentUser))},()=>{let e=s;t.enqueueRetryable(async()=>{await e.promise,await i(this.currentUser)})}),o=e=>{C("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):(C("FirebaseAuthCredentialsProvider","Auth not yet detected"),s.resolve(),s=new Nm))},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?(C("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):e?(S("string"==typeof e.accessToken),new Rm(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),new Im(e)}}class Om{constructor(e,t,r){this.l=e,this.h=t,this.P=r,this.type="FirstParty",this.user=Im.FIRST_PARTY,this.T=new Map}I(){return this.P?this.P():null}get headers(){this.T.set("X-Goog-AuthUser",this.l);var e=this.I();return e&&this.T.set("Authorization",e),this.h&&this.T.set("X-Goog-Iam-Authorization-Token",this.h),this.T}}class Lm{constructor(e,t,r){this.l=e,this.h=t,this.P=r}getToken(){return Promise.resolve(new Om(this.l,this.h,this.P))}start(e,t){e.enqueueRetryable(()=>t(Im.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class Mm{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 Fm{constructor(e,t){this.A=t,this.forceRefresh=!1,this.appCheck=null,this.R=null,this.V=null,h(e)&&e.settings.appCheckToken&&(this.V=e.settings.appCheckToken)}start(t,r){S(void 0===this.o);let n=e=>{null!=e.error&&C("FirebaseAppCheckTokenProvider","Error getting App Check token; using placeholder token instead. Error: "+e.error.message);var t=e.token!==this.R;return this.R=e.token,C("FirebaseAppCheckTokenProvider",`Received ${t?"new":"existing"} token.`),t?r(e.token):Promise.resolve()},i=(this.o=e=>{t.enqueueRetryable(()=>n(e))},e=>{C("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.o&&this.appCheck.addTokenListener(this.o)});this.A.onInit(e=>i(e)),setTimeout(()=>{var e;this.appCheck||((e=this.A.getImmediate({optional:!0}))?i(e):C("FirebaseAppCheckTokenProvider","AppCheck not yet detected"))},0)}getToken(){var e;return this.V?Promise.resolve(new Mm(this.V)):(e=this.forceRefresh,this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>e?(S("string"==typeof e.token),this.R=e.token,new Mm(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 Um{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 R(e,t){return e<t?-1:t<e?1:0}function Vm(e,r,n){return e.length===r.length&&e.every((e,t)=>n(e,r[t]))}function qm(e){return e+"\0"}let jm=-62135596800;class Bm{static now(){return Bm.fromMillis(Date.now())}static fromDate(e){return Bm.fromMillis(e.getTime())}static fromMillis(e){var t=Math.floor(e/1e3),r=Math.floor(1e6*(e-1e3*t));return new Bm(t,r)}constructor(e,t){if(this.seconds=e,(this.nanoseconds=t)<0)throw new N(A.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(1e9<=t)throw new N(A.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<jm)throw new N(A.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(253402300800<=e)throw new N(A.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?R(this.nanoseconds,e.nanoseconds):R(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{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){var e=this.seconds-jm;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}class P{static fromTimestamp(e){return new P(e)}static min(){return new P(new Bm(0,0))}static max(){return new P(new Bm(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 zm="__name__";class Km{constructor(e,t,r){void 0===t?t=0:t>e.length&&k(),void 0===r?r=e.length-t:r>e.length-t&&k(),this.segments=e,this.offset=t,this.len=r}get length(){return this.len}isEqual(e){return 0===Km.comparator(this,e)}child(e){let t=this.segments.slice(this.offset,this.limit());return e instanceof Km?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=Km.compareSegments(t.get(n),r.get(n));if(0!==e)return e}return Math.sign(t.length-r.length)}static compareSegments(e,t){var r=Km.isNumericId(e),n=Km.isNumericId(t);return r&&!n?-1:!r&&n?1:r&&n?Km.extractNumericId(e).compare(Km.extractNumericId(t)):e<t?-1:t<e?1:0}static isNumericId(e){return e.startsWith("__id")&&e.endsWith("__")}static extractNumericId(e){return om.fromString(e.substring(4,e.length-2))}}class D extends Km{construct(e,t,r){return new D(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 N(A.INVALID_ARGUMENT,`Invalid segment (${t}). Paths must not contain // in them.`);r.push(...t.split("/").filter(e=>0<e.length))}return new D(r)}static emptyPath(){return new D([])}}let Wm=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class Hm extends Km{construct(e,t,r){return new Hm(e,t,r)}static isValidIdentifier(e){return Wm.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),e=Hm.isValidIdentifier(e)?e:"`"+e+"`")).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&this.get(0)===zm}static keyField(){return new Hm([zm])}static fromServerFormat(t){let e=[],r="",n=0;var i=()=>{if(0===r.length)throw new N(A.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 N(A.INVALID_ARGUMENT,"Path has trailing escape character: "+t);let e=t[n+1];if("\\"!==e&&"."!==e&&"`"!==e)throw new N(A.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 N(A.INVALID_ARGUMENT,"Unterminated ` in path: "+t);return new Hm(e)}static emptyPath(){return new Hm([])}}class x{constructor(e){this.path=e}static fromPath(e){return new x(D.fromString(e))}static fromName(e){return new x(D.fromString(e).popFirst(5))}static empty(){return new x(D.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===D.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return D.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new x(new D(e.slice()))}}let Gm=-1;class $m{constructor(e,t,r,n){this.indexId=e,this.collectionGroup=t,this.fields=r,this.indexState=n}}function Qm(e){return e.fields.find(e=>2===e.kind)}function Ym(e){return e.fields.filter(e=>2!==e.kind)}$m.UNKNOWN_ID=-1;class Jm{constructor(e,t){this.fieldPath=e,this.kind=t}}class Xm{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new Xm(0,tv.min())}}function Zm(e,t){var r=e.toTimestamp().seconds,n=e.toTimestamp().nanoseconds+1,r=P.fromTimestamp(1e9===n?new Bm(r+1,0):new Bm(r,n));return new tv(r,x.empty(),t)}function ev(e){return new tv(e.readTime,e.key,Gm)}class tv{constructor(e,t,r){this.readTime=e,this.documentKey=t,this.largestBatchId=r}static min(){return new tv(P.min(),x.empty(),Gm)}static max(){return new tv(P.max(),x.empty(),Gm)}}function rv(e,t){var r=e.readTime.compareTo(t.readTime);return 0!==r||0!==(r=x.comparator(e.documentKey,t.documentKey))?r:R(e.largestBatchId,t.largestBatchId)}let nv="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 sv(e){if(e.code!==A.FAILED_PRECONDITION||e.message!==nv)throw e;C("LocalStore","Unexpectedly lost primary lease")}class O{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&&k(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(i,this.error):this.wrapSuccess(n,this.result):new O((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 O?t:O.resolve(t)}catch(e){return O.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):O.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):O.reject(t)}static resolve(r){return new O((e,t)=>{e(r)})}static reject(r){return new O((e,t)=>{t(r)})}static waitFor(e){return new O((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=O.resolve(!1);for(let r of e)t=t.next(e=>e?O.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 O((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 O((e,t)=>{let r=()=>{!0===n()?i().next(()=>{r()},t):e()};r()})}}let av="SimpleDb";class ov{static open(e,t,r,n){try{return new ov(t,e.transaction(n,r))}catch(e){throw new cv(t,e)}}constructor(r,e){this.action=r,this.transaction=e,this.aborted=!1,this.m=new Nm,this.transaction.oncomplete=()=>{this.m.resolve()},this.transaction.onabort=()=>{e.error?this.m.reject(new cv(r,e.error)):this.m.resolve()},this.transaction.onerror=e=>{var t=mv(e.target.error);this.m.reject(new cv(r,t))}}get p(){return this.m.promise}abort(e){e&&this.m.reject(e),this.aborted||(C(av,"Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}S(){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 lv{static delete(e){return C(av,"Removing database:",e),fv(window.indexedDB.deleteDatabase(e)).toPromise()}static D(){var e,t,r;return!(!he()||!lv.v()&&(e=ee(),t=0<(t=lv.C(e))&&t<10,r=0<(r=hv(e))&&r<4.5,0<e.indexOf("MSIE ")||0<e.indexOf("Trident/")||0<e.indexOf("Edge/")||t||r))}static v(){var e;return"undefined"!=typeof process&&"YES"===(null==(e=process.__PRIVATE_env)?void 0:e.F)}static M(e,t){return e.store(t)}static C(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.O=r,12.2===lv.C(ee())&&km("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 N(s){return this.db||(C(av,"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 cv(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 N(A.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 N(A.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 cv(s,t))},i.onupgradeneeded=e=>{C(av,'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);var t=e.target.result;this.O.B(t,i.transaction,e.oldVersion,this.version).next(()=>{C(av,"Database upgrade to version "+this.version+" complete")})}})),this.L&&(this.db.onversionchange=e=>this.L(e)),this.db}k(t){this.L=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.N(r);let t=ov.open(this.db,r,s?"readonly":"readwrite",n),e=i(t).next(e=>(t.S(),e)).catch(e=>(t.abort(e),O.reject(e))).toPromise();return e.catch(()=>{}),await t.p,e}catch(r){let e=r,t="FirebaseError"!==e.name&&a<3;if(C(av,"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 hv(e){var t=e.match(/Android ([\d.]+)/i),t=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(t)}class uv{constructor(e){this.q=e,this.$=!1,this.K=null}get isDone(){return this.$}get U(){return this.K}set cursor(e){this.q=e}done(){this.$=!0}W(e){this.K=e}delete(){return fv(this.q.delete())}}class cv extends N{constructor(e,t){super(A.UNAVAILABLE,`IndexedDB transaction '${e}' failed: `+t),this.name="IndexedDbTransactionError"}}function dv(e){return"IndexedDbTransactionError"===e.name}class pv{constructor(e){this.store=e}put(e,t){let r;return fv(r=void 0!==t?(C(av,"PUT",this.store.name,e,t),this.store.put(t,e)):(C(av,"PUT",this.store.name,"<auto-key>",e),this.store.put(e)))}add(e){return C(av,"ADD",this.store.name,e,e),fv(this.store.add(e))}get(t){return fv(this.store.get(t)).next(e=>(void 0===e&&(e=null),C(av,"GET",this.store.name,t,e),e))}delete(e){return C(av,"DELETE",this.store.name,e),fv(this.store.delete(e))}count(){return C(av,"COUNT",this.store.name),fv(this.store.count())}G(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 O((t,r)=>{e.onerror=e=>{r(e.target.error)},e.onsuccess=e=>{t(e.target.result)}})}{let e=this.cursor(n),r=[];return this.j(e,(e,t)=>{r.push(t)}).next(()=>r)}}H(e,t){let n=this.store.getAll(e,null===t?void 0:t);return new O((t,r)=>{n.onerror=e=>{r(e.target.error)},n.onsuccess=e=>{t(e.target.result)}})}J(e,t){C(av,"DELETE ALL",this.store.name);var r=this.options(e,t),r=(r.Y=!1,this.cursor(r));return this.j(r,(e,t,r)=>r.delete())}Z(e,t){let r;t?r=e:(r={},t=e);var n=this.cursor(r);return this.j(n,t)}X(i){let e=this.cursor({});return new O((r,n)=>{e.onerror=e=>{var t=mv(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()}})}j(e,s){let a=[];return new O((i,t)=>{e.onerror=e=>{t(e.target.error)},e.onsuccess=e=>{var n=e.target.result;if(n){let t=new uv(n),r=s(n.primaryKey,n.value,t);if(r instanceof O){let e=r.catch(e=>(t.done(),O.reject(e)));a.push(e)}t.isDone?i():null===t.U?n.continue():n.continue(t.U)}else i()}}).next(()=>O.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 fv(e){return new O((r,n)=>{e.onsuccess=e=>{var t=e.target.result;r(t)},e.onerror=e=>{var t=mv(e.target.error);n(t)}})}let gv=!1;function mv(e){let t=lv.C(ee());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 N("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 gv||(gv=!0,setTimeout(()=>{throw e},0)),e}}return e}let vv="IndexBackfiller";class _v{constructor(e,t){this.asyncQueue=e,this.ee=t,this.task=null}start(){this.te(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return null!==this.task}te(e){C(vv,`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,async()=>{this.task=null;try{var e=await this.ee.ne();C(vv,"Documents written: "+e)}catch(e){dv(e)?C(vv,"Ignoring IndexedDB error during index backfill: ",e):await sv(e)}await this.te(6e4)})}}class yv{constructor(e,t){this.localStore=e,this.persistence=t}async ne(t=50){return this.persistence.runTransaction("Backfill Indexes","readwrite-primary",e=>this.re(e,t))}re(e,t){let r=new Set,n=t,i=!0;return O.doWhile(()=>!0===i&&0<n,()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next(t=>{if(null!==t&&!r.has(t))return C(vv,"Processing collection: "+t),this.ie(e,t,n).next(e=>{n-=e,r.add(t)});i=!1})).next(()=>t-n)}ie(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.se(r,e)).next(e=>(C(vv,"Updating offset: "+e),this.localStore.indexManager.updateCollectionGroup(n,i,e))).next(()=>t.size)}))}se(e,t){let n=e;return t.changes.forEach((e,t)=>{var r=ev(t);0<rv(r,n)&&(n=r)}),new tv(n.readTime,n.documentKey,Math.max(t.batchId,e.largestBatchId))}}class wv{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.oe(e),this._e=e=>t.writeSequenceNumber(e))}oe(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){var e=++this.previousValue;return this._e&&this._e(e),e}}let bv=wv.ae=-1;function Iv(e){return null==e}function Tv(e){return 0===e&&1/e==-1/0}function Ev(e){return"number"==typeof e&&Number.isInteger(e)&&!Tv(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}let Cv="";function kv(e){let t="";for(let r=0;r<e.length;r++)0<t.length&&(t=Sv(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 Cv:r+="";break;default:r+=e}}return r})(e.get(r),t);return Sv(t)}function Sv(e){return e+Cv+""}function Av(r){let e=r.length;if(S(2<=e),2===e)return S(r.charAt(0)===Cv&&""===r.charAt(1)),D.emptyPath();var __PRIVATE_lastReasonableEscapeIndex=e-2,n=[];let i="";for(let a=0;a<e;){let t=r.indexOf(Cv,a);switch((t<0||t>__PRIVATE_lastReasonableEscapeIndex)&&k(),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:k()}a=t+2}return new D(n)}let Nv="remoteDocuments",Rv="owner",Pv="owner",Dv="mutationQueues",xv="mutations",Ov="batchId",Lv="userMutationsIndex",Mv=["userId","batchId"];function Fv(e,t){return[e,kv(t)]}function Uv(e,t,r){return[e,kv(t),r]}let Vv={},qv="documentMutations",jv="remoteDocumentsV14",Bv=["prefixPath","collectionGroup","readTime","documentId"],zv="documentKeyIndex",Kv=["prefixPath","collectionGroup","documentId"],Wv="collectionGroupIndex",Hv=["collectionGroup","readTime","prefixPath","documentId"],Gv="remoteDocumentGlobal",$v="remoteDocumentGlobalKey",Qv="targets",Yv="queryTargetsIndex",Jv=["canonicalId","targetId"],Xv="targetDocuments",Zv=["targetId","path"],e_="documentTargetsIndex",t_=["path","targetId"],r_="targetGlobalKey",n_="targetGlobal",i_="collectionParents",s_=["collectionId","parent"],a_="clientMetadata",o_="bundles",l_="namedQueries",h_="indexConfiguration",u_="collectionGroupIndex",c_="indexState",d_=["indexId","uid"],p_="sequenceNumberIndex",f_=["uid","sequenceNumber"],g_="indexEntries",m_=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],v_="documentKeyIndex",__=["indexId","uid","orderedDocumentKey"],y_="documentOverlays",w_=["userId","collectionPath","documentId"],b_="collectionPathOverlayIndex",I_=["userId","collectionPath","largestBatchId"],T_="collectionGroupOverlayIndex",E_=["userId","collectionGroup","largestBatchId"],C_="globals",k_=[Dv,xv,qv,Nv,Qv,Rv,n_,Xv,a_,Gv,i_,o_,l_],S_=[...k_,y_],A_=[Dv,xv,qv,jv,Qv,Rv,n_,Xv,a_,Gv,i_,o_,l_,y_],N_=A_,R_=[...N_,h_,c_,g_],P_=R_,D_=[...R_,C_];class x_ extends iv{constructor(e,t){super(),this.ue=e,this.currentSequenceNumber=t}}function O_(e,t){var r=e;return lv.M(r.ue,t)}function L_(e){let t=0;for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}function M_(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t(r,e[r])}function F_(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class L{constructor(e,t){this.comparator=e,this.root=t||V_.EMPTY}insert(e,t){return new L(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,V_.BLACK,null,null))}remove(e){return new L(this.comparator,this.root.remove(e,this.comparator).copy(null,null,V_.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 U_(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new U_(this.root,e,this.comparator,!1)}getReverseIterator(){return new U_(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new U_(this.root,e,this.comparator,!0)}}class U_{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 V_{constructor(e,t,r,n,i){this.key=e,this.value=t,this.color=null!=r?r:V_.RED,this.left=null!=n?n:V_.EMPTY,this.right=null!=i?i:V_.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,r,n,i){return new V_(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 V_.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 V_.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,V_.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){var e=this.copy(null,null,V_.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 k();if(this.right.isRed())throw k();var e=this.left.check();if(e!==this.right.check())throw k();return e+(this.isRed()?0:1)}}V_.EMPTY=null,V_.RED=!0,V_.BLACK=!1,V_.EMPTY=new class{constructor(){this.size=0}get key(){throw k()}get value(){throw k()}get color(){throw k()}get left(){throw k()}get right(){throw k()}copy(e,t,r,n,i){return this}insert(e,t,r){return new V_(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 M{constructor(e){this.comparator=e,this.data=new L(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 q_(this.data.getIterator())}getIteratorFrom(e){return new q_(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 M))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 M(this.comparator);return t.data=e,t}}class q_{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function j_(e){return e.hasNext()?e.getNext():void 0}class B_{constructor(e){(this.fields=e).sort(Hm.comparator)}static empty(){return new B_([])}unionWith(e){let t=new M(Hm.comparator);for(let e of this.fields)t=t.add(e);for(var r of e)t=t.add(r);return new B_(t.toArray())}covers(e){for(var t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return Vm(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class z_ extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class K_{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 z_("Invalid base64 string: "+e):e}})(e);return new K_(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 K_(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 R(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}K_.EMPTY_BYTE_STRING=new K_("");let W_=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function H_(t){if(S(!!t),"string"!=typeof t)return{seconds:G_(t.seconds),nanos:G_(t.nanos)};{let e=0;var r=W_.exec(t),r=(S(!!r),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 G_(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function $_(e){return"string"==typeof e?K_.fromBase64String(e):K_.fromUint8Array(e)}let Q_="server_timestamp",Y_="__type__",J_="__previous_value__",X_="__local_write_time__";function Z_(e){var t;return(null==(t=((null==(t=null==e?void 0:e.mapValue)?void 0:t.fields)||{})[Y_])?void 0:t.stringValue)===Q_}function ey(e){var t=e.mapValue.fields[J_];return Z_(t)?ey(t):t}function ty(e){var t=H_(e.mapValue.fields[X_].timestampValue);return new Bm(t.seconds,t.nanos)}class ry{constructor(e,t,r,n,i,s,a,o,l){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}}let ny="(default)";class iy{constructor(e,t){this.projectId=e,this.database=t||ny}static empty(){return new iy("","")}get isDefaultDatabase(){return this.database===ny}isEqual(e){return e instanceof iy&&e.projectId===this.projectId&&e.database===this.database}}let sy="__type__",ay="__max__",oy={mapValue:{fields:{__type__:{stringValue:ay}}}},ly="__vector__",hy="value",uy={nullValue:"NULL_VALUE"};function cy(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?Z_(e)?4:ky(e)?9007199254740991:Ey(e)?10:11:k()}function dy(t,r){if(t===r)return!0;var n,i,s,a,o,e=cy(t);if(e!==cy(r))return!1;switch(e){case 0:case 9007199254740991:return!0;case 1:return t.booleanValue===r.booleanValue;case 4:return ty(t).isEqual(ty(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=H_(i.timestampValue),o=H_(s.timestampValue),a.seconds===o.seconds&&a.nanos===o.nanos);case 5:return t.stringValue===r.stringValue;case 6:return i=r,$_(t.bytesValue).isEqual($_(i.bytesValue));case 7:return t.referenceValue===r.referenceValue;case 8:return s=r,G_((n=t).geoPointValue.latitude)===G_(s.geoPointValue.latitude)&&G_(n.geoPointValue.longitude)===G_(s.geoPointValue.longitude);case 2:return n=r,"integerValue"in(h=t)&&"integerValue"in n?G_(h.integerValue)===G_(n.integerValue):"doubleValue"in h&&"doubleValue"in n&&((a=G_(h.doubleValue))===(o=G_(n.doubleValue))?Tv(a)===Tv(o):isNaN(a)&&isNaN(o));case 9:return Vm(t.arrayValue.values||[],r.arrayValue.values||[],dy);case 10:case 11:var l=t,h=r,u=l.mapValue.fields||{},c=h.mapValue.fields||{};if(L_(u)!==L_(c))return!1;for(let e in u)if(u.hasOwnProperty(e)&&(void 0===c[e]||!dy(u[e],c[e])))return!1;return!0;default:return k()}}function py(e,t){return void 0!==(e.values||[]).find(e=>dy(e,t))}function fy(e,n){if(e===n)return 0;var i,s,a,o,l,h,u,c,t=cy(e),r=cy(n);if(t!==r)return R(t,r);switch(t){case 0:case 9007199254740991:return 0;case 1:return R(e.booleanValue,n.booleanValue);case 2:return h=n,u=G_((l=e).integerValue||l.doubleValue),c=G_(h.integerValue||h.doubleValue),u<c?-1:c<u?1:u===c?0:isNaN(u)?isNaN(c)?0:-1:1;case 3:return gy(e.timestampValue,n.timestampValue);case 4:return gy(ty(e),ty(n));case 5:return R(e.stringValue,n.stringValue);case 6:return l=e.bytesValue,h=n.bytesValue,u=$_(l),c=$_(h),u.compareTo(c);case 7:var d=e.referenceValue,p=n.referenceValue,f=d.split("/"),g=p.split("/");for(let t=0;t<f.length&&t<g.length;t++){let e=R(f[t],g[t]);if(0!==e)return e}return R(f.length,g.length);case 8:return d=e.geoPointValue,p=n.geoPointValue,0!==(o=R(G_(d.latitude),G_(p.latitude)))?o:R(G_(d.longitude),G_(p.longitude));case 9:return my(e.arrayValue,n.arrayValue);case 10:return m=e.mapValue,i=n.mapValue,o=m.fields||{},s=i.fields||{},o=null==(o=o[hy])?void 0:o.arrayValue,s=null==(s=s[hy])?void 0:s.arrayValue,0!==(a=R((null==(a=null==o?void 0:o.values)?void 0:a.length)||0,(null==(a=null==s?void 0:s.values)?void 0:a.length)||0))?a:my(o,s);case 11:var m=e.mapValue,v=n.mapValue;if(m===oy.mapValue&&v===oy.mapValue)return 0;if(m===oy.mapValue)return 1;if(v===oy.mapValue)return-1;var _=m.fields||{},y=Object.keys(_),w=v.fields||{},b=Object.keys(w);y.sort(),b.sort();for(let r=0;r<y.length&&r<b.length;++r){let e=R(y[r],b[r]);if(0!==e)return e;var I=fy(_[y[r]],w[b[r]]);if(0!==I)return I}return R(y.length,b.length);default:throw k()}}function gy(e,t){var r,n,i;return"string"==typeof e&&"string"==typeof t&&e.length===t.length?R(e,t):(r=H_(e),n=H_(t),0!==(i=R(r.seconds,n.seconds))?i:R(r.nanos,n.nanos))}function my(e,t){var r=e.values||[],n=t.values||[];for(let i=0;i<r.length&&i<n.length;++i){let e=fy(r[i],n[i]);if(e)return e}return R(r.length,n.length)}function vy(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=H_(e);return`time(${t.seconds},${t.nanos})`})(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?(e=>$_(e).toBase64())(e.bytesValue):"referenceValue"in e?(e=>x.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):k()}(e)}function _y(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/`+t.path.canonicalString()}}function yy(e){return!!e&&"integerValue"in e}function wy(e){return!!e&&"arrayValue"in e}function by(e){return e&&"nullValue"in e}function Iy(e){return e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function Ty(e){return e&&"mapValue"in e}function Ey(e){var t;return(null==(t=((null==(t=null==e?void 0:e.mapValue)?void 0:t.fields)||{})[sy])?void 0:t.stringValue)===ly}function Cy(t){if(t.geoPointValue)return{geoPointValue:Object.assign({},t.geoPointValue)};if(t.timestampValue&&"object"==typeof t.timestampValue)return{timestampValue:Object.assign({},t.timestampValue)};if(t.mapValue){let r={mapValue:{fields:{}}};return M_(t.mapValue.fields,(e,t)=>r.mapValue.fields[e]=Cy(t)),r}if(t.arrayValue){var r={arrayValue:{values:[]}};for(let e=0;e<(t.arrayValue.values||[]).length;++e)r.arrayValue.values[e]=Cy(t.arrayValue.values[e]);return r}return Object.assign({},t)}function ky(e){return(((e.mapValue||{}).fields||{}).__type__||{}).stringValue===ay}let Sy={mapValue:{fields:{[sy]:{stringValue:ly},[hy]:{arrayValue:{}}}}};function Ay(e,t){var r=fy(e.value,t.value);return 0!==r?r:e.inclusive&&!t.inclusive?-1:!e.inclusive&&t.inclusive?1:0}function Ny(e,t){var r=fy(e.value,t.value);return 0!==r?r:e.inclusive&&!t.inclusive?1:!e.inclusive&&t.inclusive?-1:0}class Ry{constructor(e){this.value=e}static empty(){return new Ry({mapValue:{}})}field(r){if(r.isEmpty())return this.value;{let e=this.value;for(let t=0;t<r.length-1;++t)if(!Ty(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()]=Cy(t)}setAll(e){let r=Hm.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()]=Cy(e):i.push(t.lastSegment())});var t=this.getFieldsMap(r);this.applyChanges(t,n,i)}delete(e){var t=this.field(e.popLast());Ty(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)];Ty(e)&&e.mapValue.fields||(e={mapValue:{fields:{}}},r.mapValue.fields[t.get(n)]=e),r=e}return r.mapValue.fields}applyChanges(r,e,t){M_(e,(e,t)=>r[e]=t);for(let e of t)delete r[e]}clone(){return new Ry(Cy(this.value))}}class Py{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 Py(e,0,P.min(),P.min(),P.min(),Ry.empty(),0)}static newFoundDocument(e,t,r,n){return new Py(e,1,t,P.min(),r,n,0)}static newNoDocument(e,t){return new Py(e,2,t,P.min(),P.min(),Ry.empty(),0)}static newUnknownDocument(e,t){return new Py(e,3,t,P.min(),P.min(),Ry.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(P.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=Ry.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=Ry.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=P.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 Py&&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 Py(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 Dy{constructor(e,t){this.position=e,this.inclusive=t}}function xy(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()?x.comparator(x.fromName(s.referenceValue),r.key):fy(s,r.data.field(i.field)),"desc"===i.dir&&(n*=-1),0!==n)break}return n}function Oy(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 Ly{constructor(e,t="asc"){this.field=e,this.dir=t}}class My{}class F extends My{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 zy(e,t,r):"array-contains"===t?new Gy(e,r):"in"===t?new $y(e,r):"not-in"===t?new Qy(e,r):"array-contains-any"===t?new Yy(e,r):new F(e,t,r)}static createKeyFieldInFilter(e,t,r){return new("in"===t?Ky:Wy)(e,r)}matches(e){var t=e.data.field(this.field);return"!="===this.op?null!==t&&this.matchesComparison(fy(t,this.value)):null!==t&&cy(this.value)===cy(t)&&this.matchesComparison(fy(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 k()}}isInequality(){return 0<=["<","<=",">",">=","!=","not-in"].indexOf(this.op)}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class U extends My{constructor(e,t){super(),this.filters=e,this.op=t,this.ce=null}static create(e,t){return new U(e,t)}matches(t){return Fy(this)?void 0===this.filters.find(e=>!e.matches(t)):void 0!==this.filters.find(e=>e.matches(t))}getFlattenedFilters(){return null===this.ce&&(this.ce=this.filters.reduce((e,t)=>e.concat(t.getFlattenedFilters()),[])),this.ce}getFilters(){return Object.assign([],this.filters)}}function Fy(e){return"and"===e.op}function Uy(e){return"or"===e.op}function Vy(e){return qy(e)&&Fy(e)}function qy(e){for(var t of e.filters)if(t instanceof U)return!1;return!0}function jy(e,t){var r=e.filters.concat(t);return U.create(r,e.op)}function By(e){return e instanceof F?`${(t=e).field.canonicalString()} ${t.op} `+vy(t.value):e instanceof U?(t=e).op.toString()+" {"+t.getFilters().map(By).join(" ,")+"}":"Filter";var t}class zy extends F{constructor(e,t,r){super(e,t,r),this.key=x.fromName(r.referenceValue)}matches(e){var t=x.comparator(e.key,this.key);return this.matchesComparison(t)}}class Ky extends F{constructor(e,t){super(e,"in",t),this.keys=Hy(0,t)}matches(t){return this.keys.some(e=>e.isEqual(t.key))}}class Wy extends F{constructor(e,t){super(e,"not-in",t),this.keys=Hy(0,t)}matches(t){return!this.keys.some(e=>e.isEqual(t.key))}}function Hy(e,t){var r;return((null==(r=t.arrayValue)?void 0:r.values)||[]).map(e=>x.fromName(e.referenceValue))}class Gy extends F{constructor(e,t){super(e,"array-contains",t)}matches(e){var t=e.data.field(this.field);return wy(t)&&py(t.arrayValue,this.value)}}class $y extends F{constructor(e,t){super(e,"in",t)}matches(e){var t=e.data.field(this.field);return null!==t&&py(this.value.arrayValue,t)}}class Qy extends F{constructor(e,t){super(e,"not-in",t)}matches(e){var t;return!py(this.value.arrayValue,{nullValue:"NULL_VALUE"})&&null!==(t=e.data.field(this.field))&&!py(this.value.arrayValue,t)}}class Yy extends F{constructor(e,t){super(e,"array-contains-any",t)}matches(e){var t=e.data.field(this.field);return!(!wy(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>py(this.value.arrayValue,e))}}class Jy{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.le=null}}function Xy(e,t=null,r=[],n=[],i=null,s=null,a=null){return new Jy(e,t,r,n,i,s,a)}function Zy(e){var t=e;if(null===t.le){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()+vy(e.value):Vy(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(","),Iv(t.limit)||(e=(e+="|l:")+t.limit),t.startAt&&(e=(e=(e+="|lb:")+(t.startAt.inclusive?"b:":"a:"))+t.startAt.position.map(e=>vy(e)).join(",")),t.endAt&&(e=(e=(e+="|ub:")+(t.endAt.inclusive?"a:":"b:"))+t.endAt.position.map(e=>vy(e)).join(",")),t.le=e}return t.le}function ew(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 k();var i,r,s}(e.filters[s],t.filters[s]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!Oy(e.startAt,t.startAt)&&Oy(e.endAt,t.endAt)}function tw(e){return x.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function rw(e,t){return e.filters.filter(e=>e instanceof F&&e.field.isEqual(t))}function nw(e,r,n){let i=uy,s=!0;for(let n of rw(e,r)){let e=uy,t=!0;switch(n.op){case"<":case"<=":e="nullValue"in(a=n.value)?uy:"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?_y(iy.empty(),x.empty()):"geoPointValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in a?{arrayValue:{}}:"mapValue"in a?Ey(a)?Sy:{mapValue:{}}:k();break;case"==":case"in":case">=":e=n.value;break;case">":e=n.value,t=!1;break;case"!=":case"not-in":e=uy}Ay({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];Ay({value:i,inclusive:s},{value:e,inclusive:n.inclusive})<0&&(i=e,s=n.inclusive);break}return{value:i,inclusive:s}}function iw(e,r,n){let i=oy,s=!0;for(let n of rw(e,r)){let e=oy,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?_y(iy.empty(),x.empty()):"referenceValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in a?{arrayValue:{}}:"arrayValue"in a?Sy:"mapValue"in a?Ey(a)?{mapValue:{}}:oy:k(),t=!1;break;case"==":case"in":case"<=":e=n.value;break;case"<":e=n.value,t=!1;break;case"!=":case"not-in":e=oy}0<Ny({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<Ny({value:i,inclusive:s},{value:e,inclusive:n.inclusive})&&(i=e,s=n.inclusive);break}return{value:i,inclusive:s}}class sw{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.he=null,this.Pe=null,this.Te=null,this.startAt,this.endAt}}function aw(e,t,r,n,i,s,a,o){return new sw(e,t,r,n,i,s,a,o)}function ow(e){return new sw(e)}function lw(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 hw(e){return null!==e.collectionGroup}function uw(e){let n=e;if(null===n.he){n.he=[];let t=new Set;for(var i of n.explicitOrderBy)n.he.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 M(Hm.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.he.push(new Ly(e,r))}),t.has(Hm.keyField().canonicalString())||n.he.push(new Ly(Hm.keyField(),r))}return n.he}function cw(e){var t=e;return t.Pe||(t.Pe=((e,t)=>{if("F"===e.limitType)return Xy(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 Ly(e.field,t)});var r=e.endAt?new Dy(e.endAt.position,e.endAt.inclusive):null,n=e.startAt?new Dy(e.startAt.position,e.startAt.inclusive):null;return Xy(e.path,e.collectionGroup,t,e.filters,e.limit,r,n)})(t,uw(e))),t.Pe}function dw(e,t){var r=e.filters.concat([t]);return new sw(e.path,e.collectionGroup,e.explicitOrderBy.slice(),r,e.limit,e.limitType,e.startAt,e.endAt)}function pw(e,t,r){return new sw(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,r,e.startAt,e.endAt)}function fw(e,t){return ew(cw(e),cw(t))&&e.limitType===t.limitType}function gw(e){return Zy(cw(e))+"|lt:"+e.limitType}function mw(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=>By(e)).join(", ")}]`),Iv(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=>vy(e)).join(",")),`Target(${t=e.endAt?(t=(t+=", endAt: ")+(e.endAt.inclusive?"a:":"b:"))+e.endAt.position.map(e=>vy(e)).join(","):t})`})(cw(e))}; limitType=${e.limitType})`}function vw(e,t){return t.isFoundDocument()&&(s=e,o=(a=t).key.path,null!==s.collectionGroup?a.key.hasCollectionId(s.collectionGroup)&&s.path.isPrefixOf(o):x.isDocumentKey(s.path)?s.path.isEqual(o):s.path.isImmediateParentOf(o))&&((e,t)=>{for(var r of uw(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=uw(s),i=xy(n,r,a),n.inclusive?i<=0:i<0))&&(!s.endAt||(r=s.endAt,n=uw(s),i=xy(r,n,a),r.inclusive?0<=i:0<i));var r,n,i,s,a,o}function _w(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function yw(e){return(t,r)=>{let n=!1;for(var i of uw(e)){let e=((e,t,r)=>{var n=e.field.isKeyField()?x.comparator(t.key,r.key):((e,t,r)=>{var n=t.data.field(e),i=r.data.field(e);return null!==n&&null!==i?fy(n,i):k()})(e.field,t,r);switch(e.dir){case"asc":return n;case"desc":return-1*n;default:return k()}})(i,t,r);if(0!==e)return e;n=n||i.field.isKeyField()}return 0}}class ww{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){M_(this.inner,(e,t)=>{for(let[e,r]of t)n(e,r)})}isEmpty(){return F_(this.inner)}size(){return this.innerSize}}let bw=new L(x.comparator);let Iw=new L(x.comparator);function Tw(...e){let t=Iw;for(var r of e)t=t.insert(r.key,r);return t}function Ew(e){let r=Iw;return e.forEach((e,t)=>r=r.insert(e,t.overlayedDocument)),r}function Cw(){return new ww(e=>e.toString(),(e,t)=>e.isEqual(t))}let kw=new L(x.comparator),Sw=new M(x.comparator);function V(...e){let t=Sw;for(var r of e)t=t.add(r);return t}let Aw=new M(R);function Nw(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:Tv(t)?"-0":t}}function Rw(e){return{integerValue:""+e}}function Pw(e,t){return Ev(t)?Rw(t):Nw(e,t)}class Dw{constructor(){this._=void 0}}function xw(e,t){return e instanceof Vw?yy(e=t)||(e=e)&&"doubleValue"in e?t:{integerValue:0}:null}class Ow extends Dw{}class Lw extends Dw{constructor(e){super(),this.elements=e}}function Mw(e,t){var r=jw(t);for(let t of e.elements)r.some(e=>dy(e,t))||r.push(t);return{arrayValue:{values:r}}}class Fw extends Dw{constructor(e){super(),this.elements=e}}function Uw(e,t){let r=jw(t);for(let t of e.elements)r=r.filter(e=>!dy(e,t));return{arrayValue:{values:r}}}class Vw extends Dw{constructor(e,t){super(),this.serializer=e,this.Ie=t}}function qw(e){return G_(e.integerValue||e.doubleValue)}function jw(e){return wy(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class Bw{constructor(e,t){this.field=e,this.transform=t}}class zw{constructor(e,t){this.version=e,this.transformResults=t}}class Kw{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new Kw}static exists(e){return new Kw(void 0,e)}static updateTime(e){return new Kw(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 Ww(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class Hw{}function Gw(e,r){if(!e.hasLocalMutations||r&&0===r.fields.length)return null;if(null===r)return e.isNoDocument()?new tb(e.key,Kw.none()):new Yw(e.key,e.data,Kw.none());{var n,i=e.data,s=Ry.empty();let t=new M(Hm.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 Jw(e.key,s,new B_(t.toArray()),Kw.none())}}function $w(e,t,r,n){return e instanceof Yw?(s=t,a=r,o=n,Ww((i=e).precondition,s)?(l=i.value.clone(),h=eb(i.fieldTransforms,o,s),l.setAll(h),s.convertToFoundDocument(s.version,l).setHasLocalMutations(),null):a):e instanceof Jw?(i=t,o=r,s=n,Ww((a=e).precondition,i)?(h=eb(a.fieldTransforms,s,i),(l=i.data).setAll(Xw(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,Ww(e.precondition,n)?(n.convertToNoDocument(n.version).setHasLocalMutations(),null):t);var i,s,a,o,l,h}function Qw(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&&Vm(r,n,(e,t)=>(t=t,(e=e).field.isEqual(t.field)&&(e=e.transform,t=t.transform,e instanceof Lw&&t instanceof Lw||e instanceof Fw&&t instanceof Fw?Vm(e.elements,t.elements,dy):e instanceof Vw&&t instanceof Vw?dy(e.Ie,t.Ie):e instanceof Ow&&t instanceof Ow)))))&&(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 Yw extends Hw{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 Jw extends Hw{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 Xw(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 Zw(e,t,r){var n,i,s,a=new Map;S(e.length===r.length);for(let u=0;u<r.length;u++){var o=e[u],l=o.transform,h=t.data.field(o.field);a.set(o.field,(n=l,i=h,s=r[u],n instanceof Lw?Mw(n,i):n instanceof Fw?Uw(n,i):s))}return a}function eb(e,r,n){var i,s,a,o,l,h,u,c=new Map;for(i of e){let e=i.transform,t=n.data.field(i.field);c.set(i.field,(s=e,a=t,o=r,u=h=l=void 0,s instanceof Ow?(o=o,h=a,u={fields:{[Y_]:{stringValue:Q_},[X_]:{timestampValue:{seconds:o.seconds,nanos:o.nanoseconds}}}},(h=h&&Z_(h)?ey(h):h)&&(u.fields[J_]=h),{mapValue:u}):s instanceof Lw?Mw(s,a):s instanceof Fw?Uw(s,a):(u=xw(o=s,a),l=qw(u)+qw(o.Ie),yy(u)&&yy(o.Ie)?Rw(l):Nw(o.serializer,l))))}return c}class tb extends Hw{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class rb extends Hw{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class nb{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 c=0;c<this.mutations.length;c++){var u=this.mutations[c];u.key.isEqual(e.key)&&(r=u,n=e,i=h[c],l=u=o=a=s=void 0,r instanceof Yw?(a=n,o=i,u=(s=r).value.clone(),l=Zw(s.fieldTransforms,a,o.transformResults),u.setAll(l),a.convertToFoundDocument(o.version,u).setHasCommittedMutations()):r instanceof Jw?(s=n,a=i,Ww((o=r).precondition,s)?(l=Zw(o.fieldTransforms,s,a.transformResults),(u=s.data).setAll(Xw(o)),u.setAll(l),s.convertToFoundDocument(a.version,u).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=$w(r,e,t,this.localWriteTime));for(var n of this.mutations)n.key.isEqual(e.key)&&(t=$w(n,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(n,i){let s=Cw();return this.mutations.forEach(e=>{var t=n.get(e.key),r=t.overlayedDocument,t=this.applyToLocalView(r,t.mutatedFields),t=Gw(r,i.has(e.key)?null:t);null!==t&&s.set(e.key,t),r.isValidDocument()||r.convertToNoDocument(P.min())}),s}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),V())}isEqual(e){return this.batchId===e.batchId&&Vm(this.mutations,e.mutations,(e,t)=>Qw(e,t))&&Vm(this.baseMutations,e.baseMutations,(e,t)=>Qw(e,t))}}class ib{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);let n=kw;var i=e.mutations;for(let s=0;s<i.length;s++)n=n.insert(i[s].key,r[s].version);return new ib(e,t,r,n)}}class sb{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
|
-
}`}}class lb{constructor(e,t){this.count=e,this.unchangedNames=t}}function hb(e){switch(e){case A.OK:return k();case A.CANCELLED:case A.UNKNOWN:case A.DEADLINE_EXCEEDED:case A.RESOURCE_EXHAUSTED:case A.INTERNAL:case A.UNAVAILABLE:case A.UNAUTHENTICATED:return!1;case A.INVALID_ARGUMENT:case A.NOT_FOUND:case A.ALREADY_EXISTS:case A.PERMISSION_DENIED:case A.FAILED_PRECONDITION:case A.ABORTED:case A.OUT_OF_RANGE:case A.UNIMPLEMENTED:case A.DATA_LOSS:return!0;default:return k()}}function ub(e){if(void 0===e)return km("GRPC error has no .code"),A.UNKNOWN;switch(e){case vm.OK:return A.OK;case vm.CANCELLED:return A.CANCELLED;case vm.UNKNOWN:return A.UNKNOWN;case vm.DEADLINE_EXCEEDED:return A.DEADLINE_EXCEEDED;case vm.RESOURCE_EXHAUSTED:return A.RESOURCE_EXHAUSTED;case vm.INTERNAL:return A.INTERNAL;case vm.UNAVAILABLE:return A.UNAVAILABLE;case vm.UNAUTHENTICATED:return A.UNAUTHENTICATED;case vm.INVALID_ARGUMENT:return A.INVALID_ARGUMENT;case vm.NOT_FOUND:return A.NOT_FOUND;case vm.ALREADY_EXISTS:return A.ALREADY_EXISTS;case vm.PERMISSION_DENIED:return A.PERMISSION_DENIED;case vm.FAILED_PRECONDITION:return A.FAILED_PRECONDITION;case vm.ABORTED:return A.ABORTED;case vm.OUT_OF_RANGE:return A.OUT_OF_RANGE;case vm.UNIMPLEMENTED:return A.UNIMPLEMENTED;case vm.DATA_LOSS:return A.DATA_LOSS;default:return k()}}(e=vm=vm||{})[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";let cb=new om([4294967295,4294967295],0);function db(e){var t=Um().encode(e),r=new lm;return r.update(t),new Uint8Array(r.digest())}function pb(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 om([r,n],0),new om([i,t],0)]}class fb{constructor(e,t,r){if(this.bitmap=e,this.padding=t,this.hashCount=r,t<0||8<=t)throw new gb("Invalid padding: "+t);if(r<0)throw new gb("Invalid hash count: "+r);if(0<e.length&&0===this.hashCount)throw new gb("Invalid hash count: "+r);if(0===e.length&&0!==t)throw new gb("Invalid padding when bitmap length is 0: "+t);this.Ee=8*e.length-t,this.de=om.fromNumber(this.Ee)}Ae(e,t,r){let n=e.add(t.multiply(om.fromNumber(r)));return(n=1===n.compare(cb)?new om([n.getBits(0),n.getBits(1)],0):n).modulo(this.de).toNumber()}Re(e){return!!(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(0===this.Ee)return!1;let t=db(e),[r,n]=pb(t);for(let i=0;i<this.hashCount;i++){let e=this.Ae(r,n,i);if(!this.Re(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 fb(i,n,t);return r.forEach(e=>s.insert(e)),s}insert(i){if(0!==this.Ee){let e=db(i),[t,r]=pb(e);for(let n=0;n<this.hashCount;n++){let e=this.Ae(t,r,n);this.Ve(e)}}}Ve(e){var t=Math.floor(e/8);this.bitmap[t]|=1<<e%8}}class gb 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,vb.createSynthesizedTargetChangeForCurrentChange(e,t,r)),new mb(P.min(),n,new L(R),Tw,V())}}class vb{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 vb(r,t,V(),V(),V())}}class _b{constructor(e,t,r,n){this.me=e,this.removedTargetIds=t,this.key=r,this.fe=n}}class yb{constructor(e,t){this.targetId=e,this.ge=t}}class wb{constructor(e,t,r=H_.EMPTY_BYTE_STRING,n=null){this.state=e,this.targetIds=t,this.resumeToken=r,this.cause=n}}class bb{constructor(){this.pe=0,this.ye=Eb(),this.we=H_.EMPTY_BYTE_STRING,this.Se=!1,this.be=!0}get current(){return this.Se}get resumeToken(){return this.we}get De(){return 0!==this.pe}get ve(){return this.be}Ce(e){0<e.approximateByteSize()&&(this.be=!0,this.we=e)}Fe(){let r=V(),n=V(),i=V();return this.ye.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:k()}}),new vb(this.we,this.Se,r,n,i)}Me(){this.be=!1,this.ye=Eb()}xe(e,t){this.be=!0,this.ye=this.ye.insert(e,t)}Oe(e){this.be=!0,this.ye=this.ye.remove(e)}Ne(){this.pe+=1}Be(){--this.pe,S(0<=this.pe)}Le(){this.be=!0,this.Se=!0}}class Ib{constructor(e){this.ke=e,this.qe=new Map,this.Qe=Tw,this.$e=Tb(),this.Ue=Tb(),this.Ke=new L(R)}We(e){for(var t of e.me)e.fe&&e.fe.isFoundDocument()?this.Ge(t,e.fe):this.ze(t,e.key,e.fe);for(var r of e.removedTargetIds)this.ze(r,e.key,e.fe)}je(r){this.forEachTarget(r,e=>{var t=this.He(e);switch(r.state){case 0:this.Je(e)&&t.Ce(r.resumeToken);break;case 1:t.Be(),t.De||t.Me(),t.Ce(r.resumeToken);break;case 2:t.Be(),t.De||this.removeTarget(e);break;case 3:this.Je(e)&&(t.Le(),t.Ce(r.resumeToken));break;case 4:this.Je(e)&&(this.Ye(e),t.Ce(r.resumeToken));break;default:k()}})}forEachTarget(e,r){0<e.targetIds.length?e.targetIds.forEach(r):this.qe.forEach((e,t)=>{this.Je(t)&&r(t)})}Ze(n){let i=n.targetId,e=n.ge.count,t=this.Xe(i);if(t){var r=t.target;if(nw(r))if(0===e){let e=new x(r.path);this.ze(i,e,xy.newNoDocument(e,P.min()))}else S(1===e);else{let r=this.et(i);if(r!==e){let e=this.tt(n),t=e?this.nt(e,n,r):1;if(0!==t){this.Ye(i);let e=2===t?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch";this.Ke=this.Ke.insert(i,e)}}}}}tt(e){var t=e.ge.unchangedNames;if(!t||!t.bits)return null;var{bits:{bitmap:t="",padding:r=0},hashCount:n=0}=t;let i,s;try{i=Y_(t).toUint8Array()}catch(e){if(e instanceof W_)return Sm("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 fb(i,r,n)}catch(e){return Sm(e instanceof gb?"BloomFilter error: ":"Applying bloom filter failed: ",e),null}return 0===s.Ee?null:s}nt(e,t,r){return t.ge.count===r-this.st(e,t.targetId)?0:2}st(r,n){var e=this.ke.getRemoteKeysForTarget(n);let i=0;return e.forEach(e=>{var t=this.ke.it(),t=`projects/${t.projectId}/databases/${t.database}/documents/`+e.path.canonicalString();r.mightContain(t)||(this.ze(n,e,null),i++)}),i}ot(n){let i=new Map,s=(this.qe.forEach((e,t)=>{var r=this.Xe(t);if(r){if(e.current&&nw(r.target)){let e=new x(r.target.path);this._t(e).has(t)||this.ut(t,e)||this.ze(t,e,xy.newNoDocument(e,n))}e.ve&&(i.set(t,e.Fe()),e.Me())}}),V());this.Ue.forEach((e,t)=>{let r=!0;t.forEachWhile(e=>{var t=this.Xe(e);return!t||"TargetPurposeLimboResolution"===t.purpose||(r=!1)}),r&&(s=s.add(e))}),this.Qe.forEach((e,t)=>t.setReadTime(n));var e=new mb(n,i,this.Ke,this.Qe,s);return this.Qe=Tw,this.$e=Tb(),this.Ue=Tb(),this.Ke=new L(R),e}Ge(e,t){var r;this.Je(e)&&(r=this.ut(e,t.key)?2:0,this.He(e).xe(t.key,r),this.Qe=this.Qe.insert(t.key,t),this.$e=this.$e.insert(t.key,this._t(t.key).add(e)),this.Ue=this.Ue.insert(t.key,this.ct(t.key).add(e)))}ze(e,t,r){var n;this.Je(e)&&(n=this.He(e),this.ut(e,t)?n.xe(t,1):n.Oe(t),this.Ue=this.Ue.insert(t,this.ct(t).delete(e)),this.Ue=this.Ue.insert(t,this.ct(t).add(e)),r)&&(this.Qe=this.Qe.insert(t,r))}removeTarget(e){this.qe.delete(e)}et(e){var t=this.He(e).Fe();return this.ke.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}Ne(e){this.He(e).Ne()}He(e){let t=this.qe.get(e);return t||(t=new bb,this.qe.set(e,t)),t}ct(e){let t=this.Ue.get(e);return t||(t=new M(R),this.Ue=this.Ue.insert(e,t)),t}_t(e){let t=this.$e.get(e);return t||(t=new M(R),this.$e=this.$e.insert(e,t)),t}Je(e){var t=null!==this.Xe(e);return t||C("WatchChangeAggregator","Detected inactive target",e),t}Xe(e){var t=this.qe.get(e);return t&&t.De?null:this.ke.lt(e)}Ye(t){this.qe.set(t,new bb),this.ke.getRemoteKeysForTarget(t).forEach(e=>{this.ze(t,e,null)})}ut(e,t){return this.ke.getRemoteKeysForTarget(e).has(t)}}function Tb(){return new L(x.comparator)}function Eb(){return new L(x.comparator)}let Cb={asc:"ASCENDING",desc:"DESCENDING"},kb={"<":"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"},Sb={and:"AND",or:"OR"};class Ab{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function Nb(e,t){return e.useProto3Json||Ev(t)?t:{value:t}}function Rb(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 Pb(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function Db(e){return S(!!e),P.fromTimestamp((t=$_(e),new Km(t.seconds,t.nanos)));var t}function xb(e,t){return Ob(e,t).canonicalString()}function Ob(e,t){e=e;var r=new D(["projects",e.projectId,"databases",e.database]).child("documents");return void 0===t?r:r.child(t)}function Lb(e){var t=D.fromString(e);return S(tI(t)),t}function Mb(e,t){return xb(e.databaseId,t.path)}function Fb(e,t){var r=Lb(t);if(r.get(1)!==e.databaseId.projectId)throw new N(A.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 N(A.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+r.get(3)+" vs "+e.databaseId.database);return new x(jb(r))}function Ub(e,t){return xb(e.databaseId,t)}function Vb(e){var t=Lb(e);return 4===t.length?D.emptyPath():jb(t)}function qb(e){return new D(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function jb(e){return S(4<e.length&&"documents"===e.get(4)),e.popFirst(5)}function Bb(e,t,r){return{name:Mb(e,t),fields:r.value.mapValue.fields}}function zb(e,t,r){var n=Fb(e,t.name),i=Db(t.updateTime),s=t.createTime?Db(t.createTime):P.min(),a=new Dy({mapValue:{fields:t.fields}}),n=xy.newFoundDocument(n,i,s,a);return r&&n.setHasCommittedMutations(),r?n.setHasCommittedMutations():n}function Kb(e,t){let r;if(t instanceof Xw)r={update:Bb(e,t.key,t.value)};else if(t instanceof nb)r={delete:Mb(e,t.key)};else if(t instanceof Zw)r={update:Bb(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 k();r={verify:Mb(e,t.key)}}return 0<t.fieldTransforms.length&&(r.updateTransforms=t.fieldTransforms.map(e=>{var t=e.transform;if(t instanceof Mw)return{fieldPath:e.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(t instanceof Fw)return{fieldPath:e.field.canonicalString(),appendMissingElements:{values:t.elements}};if(t instanceof Vw)return{fieldPath:e.field.canonicalString(),removeAllFromArray:{values:t.elements}};if(t instanceof jw)return{fieldPath:e.field.canonicalString(),increment:t.Ie};throw k()})),t.precondition.isNone||(r.currentDocument=(e=e,void 0!==(t=t.precondition).updateTime?{updateTime:(n=t.updateTime,Rb(e,n.toTimestamp()))}:void 0!==t.exists?{exists:t.exists}:k())),r;var n}function Wb(i,t){let r=t.currentDocument?void 0!==(s=t.currentDocument).updateTime?Hw.updateTime(Db(s.updateTime)):void 0!==s.exists?Hw.exists(s.exists):Hw.none():Hw.none(),n=t.updateTransforms?t.updateTransforms.map(r=>{{var e=i;let t=null;if("setToServerValue"in r)S("REQUEST_TIME"===r.setToServerValue),t=new Mw;else if("appendMissingElements"in r){let e=r.appendMissingElements.values||[];t=new Fw(e)}else if("removeAllFromArray"in r){let e=r.removeAllFromArray.values||[];t=new Vw(e)}else"increment"in r?t=new jw(e,r.increment):k();var n=$m.fromServerFormat(r.fieldPath);return new Kw(n,t)}}):[];var s,a;if(t.update){t.update.name;var o=Fb(i,t.update.name),l=new Dy({mapValue:{fields:t.update.fields}});if(t.updateMask){s=t.updateMask,a=s.fieldPaths||[];let e=new K_(a.map(e=>$m.fromServerFormat(e)));return new Zw(o,l,e,r,n)}return new Xw(o,l,r,n)}if(t.delete){let e=Fb(i,t.delete);return new nb(e,r)}if(t.verify){let e=Fb(i,t.verify);return new ib(e,r)}return k()}function Hb(e,n){return e&&0<e.length?(S(void 0!==n),e.map(t=>{{var r=n;let e=t.updateTime?Db(t.updateTime):Db(r);return e.isEqual(P.min())&&(e=Db(r)),new Ww(e,t.transformResults||[])}})):[]}function Gb(e,t){return{documents:[Ub(e,t.path)]}}function $b(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=Ub(e,i);n=(e=>{if(0!==e.length)return function r(e){return e instanceof F?(e=>{if("=="===e.op){if(Ey(e.value))return{unaryFilter:{field:Zb(e.field),op:"IS_NAN"}};if(Ty(e.value))return{unaryFilter:{field:Zb(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(Ey(e.value))return{unaryFilter:{field:Zb(e.field),op:"IS_NOT_NAN"}};if(Ty(e.value))return{unaryFilter:{field:Zb(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:Zb(e.field),op:Jb(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:Xb(e.op),filters:t}}})(e):k()}(U.create(e,"and"))})(t.filters),n&&(r.structuredQuery.where=n),n=(e=>{if(0!==e.length)return e.map(e=>({field:Zb((e=e).field),direction:(e=e.dir,Cb[e])}))})(t.orderBy),n&&(r.structuredQuery.orderBy=n),n=Nb(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}),{ht:r,parent:i}}function Qb(e){let t=Vb(e.parent);var r,n=e.structuredQuery,i=n.from?n.from.length:0;let s=null;if(0<i){S(1===i);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=eI(i.unaryFilter.field);return F.create(e,"==",{doubleValue:NaN});case"IS_NULL":let t=eI(i.unaryFilter.field);return F.create(t,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":let r=eI(i.unaryFilter.field);return F.create(r,"!=",{doubleValue:NaN});case"IS_NOT_NULL":let n=eI(i.unaryFilter.field);return F.create(n,"!=",{nullValue:"NULL_VALUE"});default:return k()}})(e):void 0!==e.fieldFilter?(e=>F.create(eI(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";default:return k()}})(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 k()}})(e.compositeFilter.op)))(e):k()}(e))instanceof U&&jy(i)?i.getFilters():[i])),[]),l=(n.orderBy&&(o=n.orderBy.map(e=>(e=e,new Fy(eI(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,Ev(i="object"==typeof e?e.value:e)?null:i)),null),u=(n.startAt&&(h=(e=n.startAt,i=!!e.before,r=e.values||[],new Oy(r,i))),null);return n.endAt&&(u=(e=n.endAt,r=!e.before,i=e.values||[],new Oy(i,r))),lw(t,s,o,a,l,"F",h,u)}function Yb(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 k()}})(t.purpose);return null==r?null:{"goog-listen-tags":r}}function Jb(e){return kb[e]}function Xb(e){return Sb[e]}function Zb(e){return{fieldPath:e.canonicalString()}}function eI(e){return $m.fromServerFormat(e.fieldPath)}function tI(e){return 4<=e.length&&"projects"===e.get(0)&&"databases"===e.get(2)}class rI{constructor(e,t,r,n,i=P.min(),s=P.min(),a=H_.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 rI(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new rI(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new rI(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new rI(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class nI{constructor(e){this.Tt=e}}function iI(e,t){var r,n=t.key,i={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:sI(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument())i.document={name:Mb(e=e.Tt,(r=t).key),fields:r.data.value.mapValue.fields,updateTime:Rb(e,r.version.toTimestamp()),createTime:Rb(e,r.createTime.toTimestamp())};else if(t.isNoDocument())i.noDocument={path:n.path.toArray(),readTime:aI(t.version)};else{if(!t.isUnknownDocument())return k();i.unknownDocument={path:n.path.toArray(),version:aI(t.version)}}return i}function sI(e){var t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function aI(e){var t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function oI(e){var t=new Km(e.seconds,e.nanoseconds);return P.fromTimestamp(t)}function lI(t,r){let e=(r.baseMutations||[]).map(e=>Wb(t.Tt,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=>Wb(t.Tt,e)),i=Km.fromMillis(r.localWriteTimeMs);return new sb(r.batchId,i,e,n)}function hI(e){var t,r=oI(e.readTime),n=void 0!==e.lastLimboFreeSnapshotVersion?oI(e.lastLimboFreeSnapshotVersion):P.min(),i=void 0!==e.query.documents?(S(1===(t=e.query).documents.length),pw(hw(Vb(t.documents[0])))):pw(Qb(e.query));return new rI(i,e.targetId,"TargetPurposeListen",e.lastListenSequenceNumber,r,n,H_.fromBase64String(e.resumeToken))}function uI(e,t){var r=aI(t.snapshotVersion),n=aI(t.lastLimboFreeSnapshotVersion),i=nw(t.target)?Gb(e.Tt,t.target):$b(e.Tt,t.target).ht,s=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:tw(t.target),readTime:r,resumeToken:s,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:n,query:i}}function cI(e){var t=Qb({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?gw(t,t.limit,"L"):t}function dI(e,t){return new ob(t.largestBatchId,Wb(e.Tt,t.overlayMutation))}function pI(e,t){var r=t.path.lastSegment();return[e,Av(t.path.popLast()),r]}function fI(e,t,r,n){return{indexId:e,uid:t,sequenceNumber:r,readTime:aI(n.readTime),documentKey:Av(n.documentKey.path),largestBatchId:n.largestBatchId}}class gI{getBundleMetadata(e,t){return mI(e).get(t).next(e=>{if(e)return{id:(e=e).bundleId,createTime:oI(e.createTime),version:e.version}})}saveBundleMetadata(e,t){return mI(e).put({bundleId:(e=t).id,createTime:aI(Db(e.createTime)),version:e.version})}getNamedQuery(e,t){return vI(e).get(t).next(e=>{if(e)return{name:(e=e).name,query:cI(e.bundledQuery),readTime:oI(e.readTime)}})}saveNamedQuery(e,t){return vI(e).put({name:(e=t).name,readTime:aI(Db(e.readTime)),bundledQuery:e.bundledQuery})}}function mI(e){return M_(e,h_)}function vI(e){return M_(e,u_)}class _I{constructor(e,t){this.serializer=e,this.userId=t}static It(e,t){var r=t.uid||"";return new _I(e,r)}getOverlay(e,t){return yI(e).get(pI(this.userId,t)).next(e=>e?dI(this.serializer,e):null)}getOverlays(e,t){let r=Sw();return O.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 ob(i,t);s.push(this.Et(n,r))}),O.waitFor(s)}removeOverlaysForBatchId(r,e,n){let t=new Set,i=(e.forEach(e=>t.add(Av(e.getCollectionPath()))),[]);return t.forEach(e=>{var t=IDBKeyRange.bound([this.userId,e,n],[this.userId,e,n+1],!1,!0);i.push(yI(r).J(T_,t))}),O.waitFor(i)}getOverlaysForCollection(e,t,r){let n=Sw(),i=Av(t),s=IDBKeyRange.bound([this.userId,i,r],[this.userId,i,Number.POSITIVE_INFINITY],!0);return yI(e).G(T_,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=Sw(),a;var n=IDBKeyRange.bound([this.userId,t,r],[this.userId,t,Number.POSITIVE_INFINITY],!0);return yI(e).Z({index:C_,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)}Et(e,t){return yI(e).put(((e,t,r)=>{var[,n,i]=pI(t,r.mutation.key);return{userId:t,collectionPath:n,documentId:i,collectionGroup:r.mutation.key.getCollectionGroup(),largestBatchId:r.largestBatchId,overlayMutation:Kb(e.Tt,r.mutation)}})(this.serializer,this.userId,t))}}function yI(e){return M_(e,b_)}class wI{dt(e){return M_(e,S_)}getSessionToken(e){return this.dt(e).get("sessionToken").next(e=>{var t=null==e?void 0:e.value;return t?H_.fromUint8Array(t):H_.EMPTY_BYTE_STRING})}setSessionToken(e,t){return this.dt(e).put({name:"sessionToken",value:t.toUint8Array()})}}class bI{constructor(){}At(e,t){this.Rt(e,t),t.Vt()}Rt(t,r){if("nullValue"in t)this.ft(r,5);else if("booleanValue"in t)this.ft(r,10),r.gt(t.booleanValue?1:0);else if("integerValue"in t)this.ft(r,15),r.gt(Q_(t.integerValue));else if("doubleValue"in t){var e=Q_(t.doubleValue);isNaN(e)?this.ft(r,13):(this.ft(r,15),Cv(e)?r.gt(0):r.gt(e))}else if("timestampValue"in t){let e=t.timestampValue;this.ft(r,20),"string"==typeof e&&(e=$_(e)),r.yt(""+(e.seconds||"")),r.gt(e.nanos||0)}else"stringValue"in t?(this.wt(t.stringValue,r),this.St(r)):"bytesValue"in t?(this.ft(r,30),r.bt(Y_(t.bytesValue)),this.St(r)):"referenceValue"in t?this.Dt(t.referenceValue,r):"geoPointValue"in t?(e=t.geoPointValue,this.ft(r,45),r.gt(e.latitude||0),r.gt(e.longitude||0)):"mapValue"in t?Ay(t)?this.ft(r,Number.MAX_SAFE_INTEGER):ky(t)?this.vt(t.mapValue,r):(this.Ct(t.mapValue,r),this.St(r)):"arrayValue"in t?(this.Ft(t.arrayValue,r),this.St(r)):k()}wt(e,t){this.ft(t,25),this.Mt(e,t)}Mt(e,t){t.yt(e)}Ct(e,t){var r=e.fields||{};this.ft(t,55);for(let e of Object.keys(r))this.wt(e,t),this.Rt(r[e],t)}vt(e,t){var r=e.fields||{},n=(this.ft(t,53),cy),i=(null==(i=null==(i=r[n].arrayValue)?void 0:i.values)?void 0:i.length)||0;this.ft(t,15),t.gt(Q_(i)),this.wt(n,t),this.Rt(r[n],t)}Ft(e,t){var r=e.values||[];this.ft(t,50);for(let e of r)this.Rt(e,t)}Dt(e,t){this.ft(t,37),x.fromName(e).path.forEach(e=>{this.ft(t,60),this.Mt(e,t)})}ft(e,t){e.gt(t)}St(e){e.gt(2)}}bI.xt=new bI;function II(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 TI{constructor(){this.buffer=new Uint8Array(1024),this.position=0}Ot(e){var t=e[Symbol.iterator]();let r=t.next();for(;!r.done;)this.Nt(r.value),r=t.next();this.Bt()}Lt(e){var t=e[Symbol.iterator]();let r=t.next();for(;!r.done;)this.kt(r.value),r=t.next();this.qt()}Qt(e){for(var t of e){let e=t.charCodeAt(0);if(e<128)this.Nt(e);else if(e<2048)this.Nt(960|e>>>6),this.Nt(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Nt(480|e>>>12),this.Nt(128|63&e>>>6),this.Nt(128|63&e);else{let e=t.codePointAt(0);this.Nt(240|e>>>18),this.Nt(128|63&e>>>12),this.Nt(128|63&e>>>6),this.Nt(128|63&e)}}this.Bt()}$t(e){for(var t of e){let e=t.charCodeAt(0);if(e<128)this.kt(e);else if(e<2048)this.kt(960|e>>>6),this.kt(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.kt(480|e>>>12),this.kt(128|63&e>>>6),this.kt(128|63&e);else{let e=t.codePointAt(0);this.kt(240|e>>>18),this.kt(128|63&e>>>12),this.kt(128|63&e>>>6),this.kt(128|63&e)}}this.qt()}Ut(e){var t=this.Kt(e),r=II(t);this.Wt(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]}Gt(e){var t=this.Kt(e),r=II(t);this.Wt(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])}zt(){this.jt(255),this.jt(255)}Ht(){this.Jt(255),this.Jt(255)}reset(){this.position=0}seed(e){this.Wt(e.length),this.buffer.set(e,this.position),this.position+=e.length}Yt(){return this.buffer.slice(0,this.position)}Kt(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}Nt(e){var t=255&e;0==t?(this.jt(0),this.jt(255)):255==t?(this.jt(255),this.jt(0)):this.jt(t)}kt(e){var t=255&e;0==t?(this.Jt(0),this.Jt(255)):255==t?(this.Jt(255),this.Jt(0)):this.Jt(e)}Bt(){this.jt(0),this.jt(1)}qt(){this.Jt(0),this.Jt(1)}jt(e){this.Wt(1),this.buffer[this.position++]=e}Jt(e){this.Wt(1),this.buffer[this.position++]=~e}Wt(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 EI{constructor(e){this.Zt=e}bt(e){this.Zt.Ot(e)}yt(e){this.Zt.Qt(e)}gt(e){this.Zt.Ut(e)}Vt(){this.Zt.zt()}}class CI{constructor(e){this.Zt=e}bt(e){this.Zt.Lt(e)}yt(e){this.Zt.$t(e)}gt(e){this.Zt.Gt(e)}Vt(){this.Zt.Ht()}}class kI{constructor(){this.Zt=new TI,this.Xt=new EI(this.Zt),this.en=new CI(this.Zt)}seed(e){this.Zt.seed(e)}tn(e){return 0===e?this.Xt:this.en}Yt(){return this.Zt.Yt()}reset(){this.Zt.reset()}}class SI{constructor(e,t,r,n){this.indexId=e,this.documentKey=t,this.arrayValue=r,this.directionalValue=n}nn(){var e=this.directionalValue.length,t=0===e||255===this.directionalValue[e-1]?e+1:e,r=new Uint8Array(t);return r.set(this.directionalValue,0),t!==e?r.set([0],this.directionalValue.length):++r[r.length-1],new SI(this.indexId,this.documentKey,this.arrayValue,r)}}function AI(e,t){var r=e.indexId-t.indexId;return 0!=r||0!==(r=NI(e.arrayValue,t.arrayValue))||0!==(r=NI(e.directionalValue,t.directionalValue))?r:x.comparator(e.documentKey,t.documentKey)}function NI(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}class RI{constructor(e){this.rn=new M((e,t)=>$m.comparator(e.field,t.field)),this.collectionId=null!=e.collectionGroup?e.collectionGroup:e.path.lastSegment(),this.sn=e.orderBy,this._n=[];for(var t of e.filters){let e=t;e.isInequality()?this.rn=this.rn.add(e):this._n.push(e)}}get an(){return 1<this.rn.size}un(e){if(S(e.collectionGroup===this.collectionId),this.an)return!1;let t=Jm(e);if(void 0!==t&&!this.cn(t))return!1;var r=Xm(e);let n=new Set,i=0,s=0;for(;i<r.length&&this.cn(r[i]);++i)n=n.add(r[i].fieldPath.canonicalString());if(i!==r.length){if(0<this.rn.size){let t=this.rn.getIterator().getNext();if(!n.has(t.field.canonicalString())){let e=r[i];if(!this.ln(t,e)||!this.hn(this.sn[s++],e))return!1}++i}for(;i<r.length;++i){let e=r[i];if(s>=this.sn.length||!this.hn(this.sn[s++],e))return!1}}return!0}Pn(){if(this.an)return null;let e=new M($m.comparator);var t,r,n=[];for(t of this._n)t.field.isKeyField()||("array-contains"===t.op||"array-contains-any"===t.op?n.push(new Zm(t.field,2)):e.has(t.field)||(e=e.add(t.field),n.push(new Zm(t.field,0))));for(r of this.sn)r.field.isKeyField()||e.has(r.field)||(e=e.add(r.field),n.push(new Zm(r.field,"asc"===r.dir?0:1)));return new Ym(Ym.UNKNOWN_ID,this.collectionId,n,ev.empty())}cn(e){for(var t of this._n)if(this.ln(t,e))return!0;return!1}ln(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)}hn(e,t){return!!e.field.isEqual(t.fieldPath)&&(0===t.kind&&"asc"===e.dir||1===t.kind&&"desc"===e.dir)}}function PI(e){var t;return 0===e.getFilters().length?[]:(t=function t(e){if(S(e instanceof F||e instanceof U),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=FI(n),OI(n)?n:(S(n instanceof U),S(Vy(n)),S(1<n.filters.length),n.filters.reduce((e,t)=>LI(e,t)))}(function t(r){var n;if(S(r instanceof F||r instanceof U),r instanceof F){if(r instanceof Yy){let e=(null==(n=null==(n=r.value.arrayValue)?void 0:n.values)?void 0:n.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(OI(t)),DI(t)||xI(t)?[t]:t.getFilters())}function DI(e){return e instanceof F}function xI(e){return e instanceof U&&jy(e)}function OI(e){return DI(e)||xI(e)||(e=>{if(e instanceof U&&qy(e)){for(var t of e.getFilters())if(!DI(t)&&!xI(t))return!1;return!0}return!1})(e)}function LI(e,t){var r,n;return S(e instanceof F||e instanceof U),S(t instanceof F||t instanceof U),FI(e instanceof F?t instanceof F?(r=e,n=t,U.create([r,n],"and")):MI(e,t):t instanceof F?MI(t,e):((e,t)=>{if(S(0<e.filters.length&&0<t.filters.length),Vy(e)&&Vy(t))return zy(e,t.getFilters());let r=qy(e)?e:t,n=qy(e)?t:e,i=r.filters.map(e=>LI(e,n));return U.create(i,"or")})(e,t))}function MI(t,e){var r;return Vy(e)?zy(e,t.getFilters()):(r=e.filters.map(e=>LI(t,e)),U.create(r,"or"))}function FI(t){if(S(t instanceof F||t instanceof U),t instanceof F)return t;var e=t.getFilters();if(1===e.length)return FI(e[0]);if(By(t))return t;let r=e.map(e=>FI(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 UI{constructor(){this.Tn=new VI}addToCollectionParentIndex(e,t){return this.Tn.add(t),O.resolve()}getCollectionParents(e,t){return O.resolve(this.Tn.getEntries(t))}addFieldIndex(e,t){return O.resolve()}deleteFieldIndex(e,t){return O.resolve()}deleteAllFieldIndexes(e){return O.resolve()}createTargetIndexes(e,t){return O.resolve()}getDocumentsMatchingTarget(e,t){return O.resolve(null)}getIndexType(e,t){return O.resolve(0)}getFieldIndexes(e,t){return O.resolve([])}getNextCollectionGroupToUpdate(e){return O.resolve(null)}getMinOffset(e,t){return O.resolve(nv.min())}getMinOffsetFromCollectionGroup(e,t){return O.resolve(nv.min())}updateCollectionGroup(e,t,r){return O.resolve()}updateIndexEntries(e,t){return O.resolve()}}class VI{constructor(){this.index={}}add(e){var t=e.lastSegment(),r=e.popLast(),n=this.index[t]||new M(D.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 M(D.comparator)).toArray()}}let qI="IndexedDbIndexManager",jI=new Uint8Array(0);class BI{constructor(e,t){this.databaseId=t,this.In=new VI,this.En=new Iw(e=>tw(e),(e,t)=>rw(e,t)),this.uid=e.uid||""}addToCollectionParentIndex(e,t){var r,n;return this.In.has(t)?O.resolve():(n=t.lastSegment(),r=t.popLast(),e.addOnCommittedListener(()=>{this.In.add(t)}),n={collectionId:n,parent:Av(r)},zI(e).put(n))}getCollectionParents(e,r){let n=[],t=IDBKeyRange.bound([r,""],[Bm(r),""],!1,!0);return zI(e).G(t).next(e=>{for(var t of e){if(t.collectionId!==r)break;n.push(Rv(t.parent))}return n})}addFieldIndex(e,r){let t=WI(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=HI(e);return i.next(e=>{t.put(fI(e,this.uid,r.indexState.sequenceNumber,r.indexState.offset))})}return i.next()}deleteFieldIndex(e,t){let r=WI(e),n=HI(e),i=KI(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=WI(e),r=KI(e),n=HI(e);return t.J().next(()=>r.J()).next(()=>n.J())}createTargetIndexes(r,e){return O.forEach(this.dn(e),t=>this.getIndexType(r,t).next(e=>{if(0===e||1===e){let e=new RI(t).Pn();if(null!=e)return this.addFieldIndex(r,e)}}))}getDocumentsMatchingTarget(e,c){let d=KI(e),r=!0,n=new Map;return O.forEach(this.dn(c),t=>this.An(e,t).next(e=>{r=r&&!!e,n.set(t,e)})).next(()=>{if(r){let h=V(),u=[];return O.forEach(n,(e,t)=>{C(qI,`Using index ${r=e,`id=${r.indexId}|cg=${r.collectionGroup}|f=`+r.fields.map(e=>e.fieldPath+":"+e.kind).join(",")} to execute `+tw(c));var r,n=((t,e)=>{var r=Jm(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 Xm(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 Xm(e)){let e=(0===r.kind?sw:aw)(t,r.fieldPath,t.startAt);n.push(e.value),i=i&&e.inclusive}return new Oy(n,i)})(t,e),a=((t,e)=>{var r,n=[];let i=!0;for(r of Xm(e)){let e=(0===r.kind?aw:sw)(t,r.fieldPath,t.endAt);n.push(e.value),i=i&&e.inclusive}return new Oy(n,i)})(t,e),o=this.Rn(e,t,s),l=this.Rn(e,t,a),i=this.Vn(e,t,i),n=this.mn(e.indexId,n,o,s.inclusive,l,a.inclusive,i);return O.forEach(n,e=>d.H(e,c.limit).next(e=>{e.forEach(e=>{var t=x.fromSegments(e.documentKey);h.has(t)||(h=h.add(t),u.push(t))})}))}).next(()=>u)}return O.resolve(null)})}dn(t){let e=this.En.get(t);return e||(e=0===t.filters.length?[t]:PI(U.create(t.filters,"and")).map(e=>ew(t.path,t.collectionGroup,t.orderBy,e.getFilters(),t.limit,t.startAt,t.endAt)),this.En.set(t,e)),e}mn(i,s,a,o,l,h,u){let e=(null!=s?s.length:1)*Math.max(a.length,l.length),c=e/(null!=s?s.length:1),d=[];for(let p=0;p<e;++p){let t=s?this.fn(s[p/c]):jI,e=this.gn(i,t,a[p%c],o),r=this.pn(i,t,l[p%c],h),n=u.map(e=>this.gn(i,t,e,!0));d.push(...this.createRange(e,r,n))}return d}gn(e,t,r,n){var i=new SI(e,x.empty(),t,r);return n?i:i.nn()}pn(e,t,r,n){var i=new SI(e,x.empty(),t,r);return n?i.nn():i}An(e,t){let n=new RI(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.un(r)&&(!t||r.fields.length>t.fields.length)&&(t=r);return t})}getIndexType(e,t){let r=2,n=this.dn(t);return O.forEach(n,t=>this.An(e,t).next(e=>{e?0!==r&&e.fields.length<(t=>{let r=new M($m.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)}yn(e,t){var r,n=new kI;for(r of Xm(e)){let e=t.data.field(r.fieldPath);if(null==e)return null;var i=n.tn(r.kind);bI.xt.At(e,i)}return n.Yt()}fn(e){var t=new kI;return bI.xt.At(e,t.tn(0)),t.Yt()}wn(e,t){var r,n=new kI;return bI.xt.At(wy(this.databaseId,t),n.tn(0===(r=Xm(e)).length?0:r[r.length-1].kind)),n.Yt()}Vn(e,n,i){if(null===i)return[];let s=[],a=(s.push(new kI),0);for(var o of Xm(e)){let t=i[a++];for(let r of s)if(this.Sn(n,o.fieldPath)&&Iy(t))s=this.bn(s,o,t);else{let e=r.tn(o.kind);bI.xt.At(t,e)}}return this.Dn(s)}Rn(e,t,r){return this.Vn(e,t,r.position)}Dn(e){var t=[];for(let r=0;r<e.length;++r)t[r]=e[r].Yt();return t}bn(r,n,e){let i=[...r],s=[];for(let r of e.arrayValue.values||[])for(let t of i){let e=new kI;e.seed(t.Yt()),bI.xt.At(r,e.tn(n.kind)),s.push(e)}return s}Sn(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=WI(e),n=HI(e);return(t?r.G(d_,IDBKeyRange.bound(t,t)):r.G()).next(e=>{let s=[];return O.forEach(e,i=>n.get([i.indexId,this.uid]).next(e=>{var t,r,n;s.push((t=i,r=(e=e)?new ev(e.sequenceNumber,new nv(oI(e.readTime),new x(Rv(e.documentKey)),e.largestBatchId)):ev.empty(),n=t.fields.map(([e,t])=>new Zm($m.fromServerFormat(e),t)),new Ym(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:R(e.collectionGroup,t.collectionGroup)}),e[0].collectionGroup))}updateCollectionGroup(e,r,n){let i=WI(e),s=HI(e);return this.vn(e).next(t=>i.G(d_,IDBKeyRange.bound(r,r)).next(e=>O.forEach(e,e=>s.put(fI(e.indexId,this.uid,t,n)))))}updateIndexEntries(i,e){let r=new Map;return O.forEach(e,(t,n)=>{var e=r.get(t.collectionGroup);return(e?O.resolve(e):this.getFieldIndexes(i,t.collectionGroup)).next(e=>(r.set(t.collectionGroup,e),O.forEach(e,r=>this.Cn(i,t,r).next(e=>{var t=this.Fn(n,r);return e.isEqual(t)?O.resolve():this.Mn(i,n,r,e,t)}))))})}xn(e,t,r,n){return KI(e).put({indexId:n.indexId,uid:this.uid,arrayValue:n.arrayValue,directionalValue:n.directionalValue,orderedDocumentKey:this.wn(r,t.key),documentKey:t.key.path.toArray()})}On(e,t,r,n){return KI(e).delete([n.indexId,this.uid,n.arrayValue,n.directionalValue,this.wn(r,t.key),t.key.path.toArray()])}Cn(e,r,n){var t=KI(e);let i=new M(AI);return t.Z({index:y_,range:IDBKeyRange.only([n.indexId,this.uid,this.wn(n,r)])},(e,t)=>{i=i.add(new SI(n.indexId,r,t.arrayValue,t.directionalValue))}).next(()=>i)}Fn(t,r){let n=new M(AI);var i=this.yn(r,t);if(null!=i){let e=Jm(r);if(null!=e){var s=t.data.field(e.fieldPath);if(Iy(s))for(let e of s.arrayValue.values||[])n=n.add(new SI(r.indexId,t.key,this.fn(e),i))}else n=n.add(new SI(r.indexId,t.key,jI,i))}return n}Mn(t,r,s,e,a){C(qI,"Updating index entries for document '%s'",r.key);let o=[];{var l=AI,h=e=>{o.push(this.xn(t,r,s,e))},u=e=>{o.push(this.On(t,r,s,e))},c=e.getIterator(),d=a.getIterator();let n=z_(c),i=z_(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=z_(d)):r?(u(n),n=z_(c)):(n=z_(c),i=z_(d))}}return O.waitFor(o)}vn(e){let n=1;return HI(e).Z({index:g_,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)=>AI(e,t)).filter((e,t,r)=>!t||0!==AI(e,r[t-1]));var i=[];i.push(r);for(let s of e){let e=AI(s,r),t=AI(s,n);if(0===e)i[0]=r.nn();else if(0<e&&t<0)i.push(s),i.push(s.nn());else if(0<t)break}i.push(n);let s=[];for(let a=0;a<i.length;a+=2){if(this.Nn(i[a],i[a+1]))return[];let e=[i[a].indexId,this.uid,i[a].arrayValue,i[a].directionalValue,jI,[]],t=[i[a+1].indexId,this.uid,i[a+1].arrayValue,i[a+1].directionalValue,jI,[]];s.push(IDBKeyRange.bound(e,t))}return s}Nn(e,t){return 0<AI(e,t)}getMinOffsetFromCollectionGroup(e,t){return this.getFieldIndexes(e,t).next(GI)}getMinOffset(t,e){return O.mapArray(this.dn(e),e=>this.An(t,e).next(e=>e||k())).next(GI)}}function zI(e){return M_(e,a_)}function KI(e){return M_(e,v_)}function WI(e){return M_(e,c_)}function HI(e){return M_(e,p_)}function GI(e){S(0!==e.length);let t=e[0].indexState.offset,r=t.largestBatchId;for(let i=1;i<e.length;i++){var n=e[i].indexState.offset;iv(n,t)<0&&(t=n),r<n.largestBatchId&&(r=n.largestBatchId)}return new nv(t.readTime,t.documentKey,r)}let $I={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class QI{static withCacheSize(e){return new QI(e,QI.DEFAULT_COLLECTION_PERCENTILE,QI.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}constructor(e,t,r){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=r}}function YI(t,r,n){let e=t.store(Lv),i=t.store(Bv),s=[],a=IDBKeyRange.only(n.batchId),o=0;var l=e.Z({range:a},(e,t,r)=>(o++,r.delete()));s.push(l.next(()=>{S(1===o)}));let h=[];for(let t of n.mutations){let e=qv(r,t.key.path,n.batchId);s.push(i.delete(e)),h.push(t.key)}return O.waitFor(s).next(()=>h)}function JI(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 k();t=e.noDocument}return JSON.stringify(t).length}QI.DEFAULT_COLLECTION_PERCENTILE=10,QI.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,QI.DEFAULT=new QI(41943040,QI.DEFAULT_COLLECTION_PERCENTILE,QI.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),QI.DISABLED=new QI(-1,0,0);class XI{constructor(e,t,r,n){this.userId=e,this.serializer=t,this.indexManager=r,this.referenceDelegate=n,this.Bn={}}static It(e,t,r,n){S(""!==e.uid);var i=e.isAuthenticated()?e.uid:"";return new XI(i,t,r,n)}checkEmpty(e){let n=!0;var t=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return eT(e).Z({index:Fv,range:t},(e,t,r)=>{n=!1,r.done()}).next(()=>n)}addMutationBatch(c,d,p,f){let g=tT(c),m=eT(c);return m.add({}).next(t=>{S("number"==typeof t);let e=new sb(t,d,p,f),r=(i=this.serializer,s=this.userId,a=e,o=a.baseMutations.map(e=>Kb(i.Tt,e)),l=a.mutations.map(e=>Kb(i.Tt,e)),{userId:s,batchId:a.batchId,localWriteTimeMs:a.localWriteTime.toMillis(),baseMutations:o,mutations:l}),n=[];var i,s,a,o,l;let h=new M((e,t)=>R(e.canonicalString(),t.canonicalString()));for(let u of f){let e=qv(this.userId,u.key.path,t);h=h.add(u.key.path.popLast()),n.push(m.put(r)),n.push(g.put(e,jv))}return h.forEach(e=>{n.push(this.indexManager.addToCollectionParentIndex(c,e))}),c.addOnCommittedListener(()=>{this.Bn[t]=e.keys()}),O.waitFor(n).next(()=>e)})}lookupMutationBatch(e,t){return eT(e).get(t).next(e=>e?(S(e.userId===this.userId),lI(this.serializer,e)):null)}Ln(e,r){return this.Bn[r]?O.resolve(this.Bn[r]):this.lookupMutationBatch(e,r).next(e=>{var t;return e?(t=e.keys(),this.Bn[r]=t):null})}getNextMutationBatchAfterBatchId(e,t){let n=t+1,r=IDBKeyRange.lowerBound([this.userId,n]),i=null;return eT(e).Z({index:Fv,range:r},(e,t,r)=>{t.userId===this.userId&&(S(t.batchId>=n),i=lI(this.serializer,t)),r.done()}).next(()=>i)}getHighestUnacknowledgedBatchId(e){var t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let n=Tv;return eT(e).Z({index:Fv,range:t,reverse:!0},(e,t,r)=>{n=t.batchId,r.done()}).next(()=>n)}getAllMutationBatches(e){var t=IDBKeyRange.bound([this.userId,Tv],[this.userId,Number.POSITIVE_INFINITY]);return eT(e).G(Fv,t).next(e=>e.map(e=>lI(this.serializer,e)))}getAllMutationBatchesAffectingDocumentKey(a,o){let e=Vv(this.userId,o.path),t=IDBKeyRange.lowerBound(e),l=[];return tT(a).Z({range:t},(e,t,r)=>{var[n,i,s]=e,i=Rv(i);if(n===this.userId&&o.path.isEqual(i))return eT(a).get(s).next(e=>{if(!e)throw k();S(e.userId===this.userId),l.push(lI(this.serializer,e))});r.done()}).next(()=>l)}getAllMutationBatchesAffectingDocumentKeys(t,e){let o=new M(R),r=[];return e.forEach(a=>{var e=Vv(this.userId,a.path),e=IDBKeyRange.lowerBound(e),e=tT(t).Z({range:e},(e,t,r)=>{var[n,i,s]=e,i=Rv(i);n===this.userId&&a.path.isEqual(i)?o=o.add(s):r.done()});r.push(e)}),O.waitFor(r).next(()=>this.kn(t,o))}getAllMutationBatchesAffectingQuery(e,t){let a=t.path,o=a.length+1,r=Vv(this.userId,a),n=IDBKeyRange.lowerBound(r),l=new M(R);return tT(e).Z({range:n},(e,t,r)=>{var[n,i,s]=e,i=Rv(i);n===this.userId&&a.isPrefixOf(i)?i.length===o&&(l=l.add(s)):r.done()}).next(()=>this.kn(e,l))}kn(t,e){let r=[],n=[];return e.forEach(e=>{n.push(eT(t).get(e).next(e=>{if(null===e)throw k();S(e.userId===this.userId),r.push(lI(this.serializer,e))}))}),O.waitFor(n).next(()=>r)}removeMutationBatch(t,r){return YI(t.ue,this.userId,r).next(e=>(t.addOnCommittedListener(()=>{this.qn(r.batchId)}),O.forEach(e,e=>this.referenceDelegate.markPotentiallyOrphaned(t,e))))}qn(e){delete this.Bn[e]}performConsistencyCheck(r){return this.checkEmpty(r).next(e=>{if(!e)return O.resolve();let t=IDBKeyRange.lowerBound([this.userId]),n=[];return tT(r).Z({range:t},(t,e,r)=>{if(t[0]===this.userId){let e=Rv(t[1]);n.push(e)}else r.done()}).next(()=>{S(0===n.length)})})}containsKey(e,t){return ZI(e,this.userId,t)}Qn(e){return rT(e).get(this.userId).next(e=>e||{userId:this.userId,lastAcknowledgedBatchId:Tv,lastStreamToken:""})}}function ZI(e,s,t){let r=Vv(s,t.path),a=r[1],n=IDBKeyRange.lowerBound(r),o=!1;return tT(e).Z({range:n,Y:!0},(e,t,r)=>{var[n,i,,]=e;n===s&&i===a&&(o=!0),r.done()}).next(()=>o)}function eT(e){return M_(e,Lv)}function tT(e){return M_(e,Bv)}function rT(e){return M_(e,Ov)}class nT{constructor(e){this.$n=e}next(){return this.$n+=2,this.$n}static Un(){return new nT(0)}static Kn(){return new nT(-1)}}class iT{constructor(e,t){this.referenceDelegate=e,this.serializer=t}allocateTargetId(r){return this.Wn(r).next(e=>{var t=new nT(e.highestTargetId);return e.highestTargetId=t.next(),this.Gn(r,e).next(()=>e.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.Wn(e).next(e=>P.fromTimestamp(new Km(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.Wn(e).next(e=>e.highestListenSequenceNumber)}setTargetsMetadata(t,r,n){return this.Wn(t).next(e=>(e.highestListenSequenceNumber=r,n&&(e.lastRemoteSnapshotVersion=n.toTimestamp()),e.highestListenSequenceNumber<r&&(e.highestListenSequenceNumber=r),this.Gn(t,e)))}addTargetData(t,r){return this.zn(t,r).next(()=>this.Wn(t).next(e=>(e.targetCount+=1,this.jn(r,e),this.Gn(t,e))))}updateTargetData(e,t){return this.zn(e,t)}removeTargetData(t,e){return this.removeMatchingKeysForTargetId(t,e.targetId).next(()=>sT(t).delete(e.targetId)).next(()=>this.Wn(t)).next(e=>(S(0<e.targetCount),--e.targetCount,this.Gn(t,e)))}removeTargets(n,i,s){let a=0,o=[];return sT(n).Z((e,t)=>{var r=hI(t);r.sequenceNumber<=i&&null===s.get(r.targetId)&&(a++,o.push(this.removeTargetData(n,r)))}).next(()=>O.waitFor(o)).next(()=>a)}forEachTarget(e,n){return sT(e).Z((e,t)=>{var r=hI(t);n(r)})}Wn(e){return aT(e).get(i_).next(e=>(S(null!==e),e))}Gn(e,t){return aT(e).put(i_,t)}zn(e,t){return sT(e).put(uI(this.serializer,t))}jn(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.Wn(e).next(e=>e.targetCount)}getTargetData(e,i){var t=tw(i),t=IDBKeyRange.bound([t,Number.NEGATIVE_INFINITY],[t,Number.POSITIVE_INFINITY]);let s=null;return sT(e).Z({range:t,index:Xv},(e,t,r)=>{var n=hI(t);rw(i,n.target)&&(s=n,r.done())}).next(()=>s)}addMatchingKeys(r,e,n){let i=[],s=oT(r);return e.forEach(e=>{var t=Av(e.path);i.push(s.put({targetId:n,path:t})),i.push(this.referenceDelegate.addReference(r,n,e))}),O.waitFor(i)}removeMatchingKeys(r,e,n){let i=oT(r);return O.forEach(e,e=>{var t=Av(e.path);return O.waitFor([i.delete([n,t]),this.referenceDelegate.removeReference(r,n,e)])})}removeMatchingKeysForTargetId(e,t){var r=oT(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=oT(e);let i=V();return n.Z({range:r,Y:!0},(e,t,r)=>{var n=Rv(e[1]),n=new x(n);i=i.add(n)}).next(()=>i)}containsKey(e,t){var r=Av(t.path),r=IDBKeyRange.bound([r],[Bm(r)],!1,!0);let n=0;return oT(e).Z({index:r_,Y:!0,range:r},([e],t,r)=>{0!==e&&(n++,r.done())}).next(()=>0<n)}lt(e,t){return sT(e).get(t).next(e=>e?hI(e):null)}}function sT(e){return M_(e,Jv)}function aT(e){return M_(e,s_)}function oT(e){return M_(e,e_)}let lT="LruGarbageCollector";function hT([e,t],[r,n]){var i=R(e,r);return 0===i?R(t,n):i}class uT{constructor(e){this.Hn=e,this.buffer=new M(hT),this.Jn=0}Yn(){return++this.Jn}Zn(e){var t=[e,this.Yn()];if(this.buffer.size<this.Hn)this.buffer=this.buffer.add(t);else{let e=this.buffer.last();hT(t,e)<0&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class cT{constructor(e,t,r){this.garbageCollector=e,this.asyncQueue=t,this.localStore=r,this.Xn=null}start(){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.er(6e4)}stop(){this.Xn&&(this.Xn.cancel(),this.Xn=null)}get started(){return null!==this.Xn}er(e){C(lT,`Garbage collection scheduled in ${e}ms`),this.Xn=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,async()=>{this.Xn=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){fv(e)?C(lT,"Ignoring IndexedDB error during garbage collection: ",e):await ov(e)}await this.er(3e5)})}}class dT{constructor(e,t){this.tr=e,this.params=t}calculateTargetCount(e,t){return this.tr.nr(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return O.resolve(Iv.ae);let r=new uT(t);return this.tr.forEachTarget(e,e=>r.Zn(e.sequenceNumber)).next(()=>this.tr.rr(e,e=>r.Zn(e))).next(()=>r.maxValue)}removeTargets(e,t,r){return this.tr.removeTargets(e,t,r)}removeOrphanedDocuments(e,t){return this.tr.removeOrphanedDocuments(e,t)}collect(t,r){return-1===this.params.cacheSizeCollectionThreshold?(C("LruGarbageCollector","Garbage collection skipped; disabled"),O.resolve($I)):this.getCacheSize(t).next(e=>e<this.params.cacheSizeCollectionThreshold?(C("LruGarbageCollector",`Garbage collection skipped; Cache size ${e} is lower than threshold `+this.params.cacheSizeCollectionThreshold),$I):this.ir(t,r))}getCacheSize(e){return this.tr.getCacheSize(e)}ir(t,r){let n,i,s,a,o,l,h,u=Date.now();return this.calculateTargetCount(t,this.params.percentileToCollect).next(e=>(i=e>this.params.maximumSequenceNumbersToCollect?(C("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(),Cm()<=c.DEBUG&&C("LruGarbageCollector",`LRU Garbage Collection
|
|
12
|
+
}`}}class ab{constructor(e,t){this.count=e,this.unchangedNames=t}}function ob(e){switch(e){case A.OK:return k();case A.CANCELLED:case A.UNKNOWN:case A.DEADLINE_EXCEEDED:case A.RESOURCE_EXHAUSTED:case A.INTERNAL:case A.UNAVAILABLE:case A.UNAUTHENTICATED:return!1;case A.INVALID_ARGUMENT:case A.NOT_FOUND:case A.ALREADY_EXISTS:case A.PERMISSION_DENIED:case A.FAILED_PRECONDITION:case A.ABORTED:case A.OUT_OF_RANGE:case A.UNIMPLEMENTED:case A.DATA_LOSS:return!0;default:return k()}}function lb(e){if(void 0===e)return km("GRPC error has no .code"),A.UNKNOWN;switch(e){case vm.OK:return A.OK;case vm.CANCELLED:return A.CANCELLED;case vm.UNKNOWN:return A.UNKNOWN;case vm.DEADLINE_EXCEEDED:return A.DEADLINE_EXCEEDED;case vm.RESOURCE_EXHAUSTED:return A.RESOURCE_EXHAUSTED;case vm.INTERNAL:return A.INTERNAL;case vm.UNAVAILABLE:return A.UNAVAILABLE;case vm.UNAUTHENTICATED:return A.UNAUTHENTICATED;case vm.INVALID_ARGUMENT:return A.INVALID_ARGUMENT;case vm.NOT_FOUND:return A.NOT_FOUND;case vm.ALREADY_EXISTS:return A.ALREADY_EXISTS;case vm.PERMISSION_DENIED:return A.PERMISSION_DENIED;case vm.FAILED_PRECONDITION:return A.FAILED_PRECONDITION;case vm.ABORTED:return A.ABORTED;case vm.OUT_OF_RANGE:return A.OUT_OF_RANGE;case vm.UNIMPLEMENTED:return A.UNIMPLEMENTED;case vm.DATA_LOSS:return A.DATA_LOSS;default:return k()}}function hb(){return new TextEncoder}(e=vm=vm||{})[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";let ub=new om([4294967295,4294967295],0);function cb(e){var t=hb().encode(e),r=new lm;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 om([r,n],0),new om([i,t],0)]}class pb{constructor(e,t,r){if(this.bitmap=e,this.padding=t,this.hashCount=r,t<0||8<=t)throw new fb("Invalid padding: "+t);if(r<0)throw new fb("Invalid hash count: "+r);if(0<e.length&&0===this.hashCount)throw new fb("Invalid hash count: "+r);if(0===e.length&&0!==t)throw new fb("Invalid padding when bitmap length is 0: "+t);this.Ee=8*e.length-t,this.de=om.fromNumber(this.Ee)}Ae(e,t,r){let n=e.add(t.multiply(om.fromNumber(r)));return(n=1===n.compare(ub)?new om([n.getBits(0),n.getBits(1)],0):n).modulo(this.de).toNumber()}Re(e){return!!(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(0===this.Ee)return!1;let t=cb(e),[r,n]=db(t);for(let i=0;i<this.hashCount;i++){let e=this.Ae(r,n,i);if(!this.Re(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 pb(i,n,t);return r.forEach(e=>s.insert(e)),s}insert(i){if(0!==this.Ee){let e=cb(i),[t,r]=db(e);for(let n=0;n<this.hashCount;n++){let e=this.Ae(t,r,n);this.Ve(e)}}}Ve(e){var t=Math.floor(e/8);this.bitmap[t]|=1<<e%8}}class fb extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}class gb{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,mb.createSynthesizedTargetChangeForCurrentChange(e,t,r)),new gb(P.min(),n,new L(R),bw,V())}}class mb{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 mb(r,t,V(),V(),V())}}class vb{constructor(e,t,r,n){this.me=e,this.removedTargetIds=t,this.key=r,this.fe=n}}class _b{constructor(e,t){this.targetId=e,this.ge=t}}class yb{constructor(e,t,r=K_.EMPTY_BYTE_STRING,n=null){this.state=e,this.targetIds=t,this.resumeToken=r,this.cause=n}}class wb{constructor(){this.pe=0,this.ye=Tb(),this.we=K_.EMPTY_BYTE_STRING,this.Se=!1,this.be=!0}get current(){return this.Se}get resumeToken(){return this.we}get De(){return 0!==this.pe}get ve(){return this.be}Ce(e){0<e.approximateByteSize()&&(this.be=!0,this.we=e)}Fe(){let r=V(),n=V(),i=V();return this.ye.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:k()}}),new mb(this.we,this.Se,r,n,i)}Me(){this.be=!1,this.ye=Tb()}xe(e,t){this.be=!0,this.ye=this.ye.insert(e,t)}Oe(e){this.be=!0,this.ye=this.ye.remove(e)}Ne(){this.pe+=1}Be(){--this.pe,S(0<=this.pe)}Le(){this.be=!0,this.Se=!0}}class bb{constructor(e){this.ke=e,this.qe=new Map,this.Qe=bw,this.$e=Ib(),this.Ke=Ib(),this.Ue=new L(R)}We(e){for(var t of e.me)e.fe&&e.fe.isFoundDocument()?this.Ge(t,e.fe):this.ze(t,e.key,e.fe);for(var r of e.removedTargetIds)this.ze(r,e.key,e.fe)}je(r){this.forEachTarget(r,e=>{var t=this.He(e);switch(r.state){case 0:this.Je(e)&&t.Ce(r.resumeToken);break;case 1:t.Be(),t.De||t.Me(),t.Ce(r.resumeToken);break;case 2:t.Be(),t.De||this.removeTarget(e);break;case 3:this.Je(e)&&(t.Le(),t.Ce(r.resumeToken));break;case 4:this.Je(e)&&(this.Ye(e),t.Ce(r.resumeToken));break;default:k()}})}forEachTarget(e,r){0<e.targetIds.length?e.targetIds.forEach(r):this.qe.forEach((e,t)=>{this.Je(t)&&r(t)})}Ze(n){let i=n.targetId,e=n.ge.count,t=this.Xe(i);if(t){var r=t.target;if(tw(r))if(0===e){let e=new x(r.path);this.ze(i,e,Py.newNoDocument(e,P.min()))}else S(1===e);else{let r=this.et(i);if(r!==e){let e=this.tt(n),t=e?this.nt(e,n,r):1;if(0!==t){this.Ye(i);let e=2===t?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch";this.Ue=this.Ue.insert(i,e)}}}}}tt(e){var t=e.ge.unchangedNames;if(!t||!t.bits)return null;var{bits:{bitmap:t="",padding:r=0},hashCount:n=0}=t;let i,s;try{i=$_(t).toUint8Array()}catch(e){if(e instanceof z_)return Sm("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 pb(i,r,n)}catch(e){return Sm(e instanceof fb?"BloomFilter error: ":"Applying bloom filter failed: ",e),null}return 0===s.Ee?null:s}nt(e,t,r){return t.ge.count===r-this.st(e,t.targetId)?0:2}st(r,n){var e=this.ke.getRemoteKeysForTarget(n);let i=0;return e.forEach(e=>{var t=this.ke.it(),t=`projects/${t.projectId}/databases/${t.database}/documents/`+e.path.canonicalString();r.mightContain(t)||(this.ze(n,e,null),i++)}),i}ot(n){let i=new Map,s=(this.qe.forEach((e,t)=>{var r=this.Xe(t);if(r){if(e.current&&tw(r.target)){let e=new x(r.target.path);this._t(e).has(t)||this.ut(t,e)||this.ze(t,e,Py.newNoDocument(e,n))}e.ve&&(i.set(t,e.Fe()),e.Me())}}),V());this.Ke.forEach((e,t)=>{let r=!0;t.forEachWhile(e=>{var t=this.Xe(e);return!t||"TargetPurposeLimboResolution"===t.purpose||(r=!1)}),r&&(s=s.add(e))}),this.Qe.forEach((e,t)=>t.setReadTime(n));var e=new gb(n,i,this.Ue,this.Qe,s);return this.Qe=bw,this.$e=Ib(),this.Ke=Ib(),this.Ue=new L(R),e}Ge(e,t){var r;this.Je(e)&&(r=this.ut(e,t.key)?2:0,this.He(e).xe(t.key,r),this.Qe=this.Qe.insert(t.key,t),this.$e=this.$e.insert(t.key,this._t(t.key).add(e)),this.Ke=this.Ke.insert(t.key,this.ct(t.key).add(e)))}ze(e,t,r){var n;this.Je(e)&&(n=this.He(e),this.ut(e,t)?n.xe(t,1):n.Oe(t),this.Ke=this.Ke.insert(t,this.ct(t).delete(e)),this.Ke=this.Ke.insert(t,this.ct(t).add(e)),r)&&(this.Qe=this.Qe.insert(t,r))}removeTarget(e){this.qe.delete(e)}et(e){var t=this.He(e).Fe();return this.ke.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}Ne(e){this.He(e).Ne()}He(e){let t=this.qe.get(e);return t||(t=new wb,this.qe.set(e,t)),t}ct(e){let t=this.Ke.get(e);return t||(t=new M(R),this.Ke=this.Ke.insert(e,t)),t}_t(e){let t=this.$e.get(e);return t||(t=new M(R),this.$e=this.$e.insert(e,t)),t}Je(e){var t=null!==this.Xe(e);return t||C("WatchChangeAggregator","Detected inactive target",e),t}Xe(e){var t=this.qe.get(e);return t&&t.De?null:this.ke.lt(e)}Ye(t){this.qe.set(t,new wb),this.ke.getRemoteKeysForTarget(t).forEach(e=>{this.ze(t,e,null)})}ut(e,t){return this.ke.getRemoteKeysForTarget(e).has(t)}}function Ib(){return new L(x.comparator)}function Tb(){return new L(x.comparator)}let Eb={asc:"ASCENDING",desc:"DESCENDING"},Cb={"<":"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"},kb={and:"AND",or:"OR"};class Sb{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function Ab(e,t){return e.useProto3Json||Iv(t)?t:{value:t}}function Nb(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 Rb(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function Pb(e){return S(!!e),P.fromTimestamp((t=H_(e),new Bm(t.seconds,t.nanos)));var t}function Db(e,t){return xb(e,t).canonicalString()}function xb(e,t){e=e;var r=new D(["projects",e.projectId,"databases",e.database]).child("documents");return void 0===t?r:r.child(t)}function Ob(e){var t=D.fromString(e);return S(eI(t)),t}function Lb(e,t){return Db(e.databaseId,t.path)}function Mb(e,t){var r=Ob(t);if(r.get(1)!==e.databaseId.projectId)throw new N(A.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 N(A.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+r.get(3)+" vs "+e.databaseId.database);return new x(qb(r))}function Fb(e,t){return Db(e.databaseId,t)}function Ub(e){var t=Ob(e);return 4===t.length?D.emptyPath():qb(t)}function Vb(e){return new D(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function qb(e){return S(4<e.length&&"documents"===e.get(4)),e.popFirst(5)}function jb(e,t,r){return{name:Lb(e,t),fields:r.value.mapValue.fields}}function Bb(e,t,r){var n=Mb(e,t.name),i=Pb(t.updateTime),s=t.createTime?Pb(t.createTime):P.min(),a=new Ry({mapValue:{fields:t.fields}}),n=Py.newFoundDocument(n,i,s,a);return r&&n.setHasCommittedMutations(),r?n.setHasCommittedMutations():n}function zb(e,t){let r;if(t instanceof Yw)r={update:jb(e,t.key,t.value)};else if(t instanceof tb)r={delete:Lb(e,t.key)};else if(t instanceof Jw)r={update:jb(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 rb))return k();r={verify:Lb(e,t.key)}}return 0<t.fieldTransforms.length&&(r.updateTransforms=t.fieldTransforms.map(e=>{var t=e.transform;if(t instanceof Ow)return{fieldPath:e.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(t instanceof Lw)return{fieldPath:e.field.canonicalString(),appendMissingElements:{values:t.elements}};if(t instanceof Fw)return{fieldPath:e.field.canonicalString(),removeAllFromArray:{values:t.elements}};if(t instanceof Vw)return{fieldPath:e.field.canonicalString(),increment:t.Ie};throw k()})),t.precondition.isNone||(r.currentDocument=(e=e,void 0!==(t=t.precondition).updateTime?{updateTime:(n=t.updateTime,Nb(e,n.toTimestamp()))}:void 0!==t.exists?{exists:t.exists}:k())),r;var n}function Kb(i,t){let r=t.currentDocument?void 0!==(s=t.currentDocument).updateTime?Kw.updateTime(Pb(s.updateTime)):void 0!==s.exists?Kw.exists(s.exists):Kw.none():Kw.none(),n=t.updateTransforms?t.updateTransforms.map(r=>{{var e=i;let t=null;if("setToServerValue"in r)S("REQUEST_TIME"===r.setToServerValue),t=new Ow;else if("appendMissingElements"in r){let e=r.appendMissingElements.values||[];t=new Lw(e)}else if("removeAllFromArray"in r){let e=r.removeAllFromArray.values||[];t=new Fw(e)}else"increment"in r?t=new Vw(e,r.increment):k();var n=Hm.fromServerFormat(r.fieldPath);return new Bw(n,t)}}):[];var s,a;if(t.update){t.update.name;var o=Mb(i,t.update.name),l=new Ry({mapValue:{fields:t.update.fields}});if(t.updateMask){s=t.updateMask,a=s.fieldPaths||[];let e=new B_(a.map(e=>Hm.fromServerFormat(e)));return new Jw(o,l,e,r,n)}return new Yw(o,l,r,n)}if(t.delete){let e=Mb(i,t.delete);return new tb(e,r)}if(t.verify){let e=Mb(i,t.verify);return new rb(e,r)}return k()}function Wb(e,n){return e&&0<e.length?(S(void 0!==n),e.map(t=>{{var r=n;let e=t.updateTime?Pb(t.updateTime):Pb(r);return e.isEqual(P.min())&&(e=Pb(r)),new zw(e,t.transformResults||[])}})):[]}function Hb(e,t){return{documents:[Fb(e,t.path)]}}function Gb(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=Fb(e,i);n=(e=>{if(0!==e.length)return function r(e){return e instanceof F?(e=>{if("=="===e.op){if(Iy(e.value))return{unaryFilter:{field:Xb(e.field),op:"IS_NAN"}};if(by(e.value))return{unaryFilter:{field:Xb(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(Iy(e.value))return{unaryFilter:{field:Xb(e.field),op:"IS_NOT_NAN"}};if(by(e.value))return{unaryFilter:{field:Xb(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:Xb(e.field),op:Yb(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:Jb(e.op),filters:t}}})(e):k()}(U.create(e,"and"))})(t.filters),n&&(r.structuredQuery.where=n),n=(e=>{if(0!==e.length)return e.map(e=>({field:Xb((e=e).field),direction:(e=e.dir,Eb[e])}))})(t.orderBy),n&&(r.structuredQuery.orderBy=n),n=Ab(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}),{ht:r,parent:i}}function $b(e){let t=Ub(e.parent);var r,n=e.structuredQuery,i=n.from?n.from.length:0;let s=null;if(0<i){S(1===i);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=Zb(i.unaryFilter.field);return F.create(e,"==",{doubleValue:NaN});case"IS_NULL":let t=Zb(i.unaryFilter.field);return F.create(t,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":let r=Zb(i.unaryFilter.field);return F.create(r,"!=",{doubleValue:NaN});case"IS_NOT_NULL":let n=Zb(i.unaryFilter.field);return F.create(n,"!=",{nullValue:"NULL_VALUE"});default:return k()}})(e):void 0!==e.fieldFilter?(e=>F.create(Zb(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";default:return k()}})(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 k()}})(e.compositeFilter.op)))(e):k()}(e))instanceof U&&Vy(i)?i.getFilters():[i])),[]),l=(n.orderBy&&(o=n.orderBy.map(e=>(e=e,new Ly(Zb(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,Iv(i="object"==typeof e?e.value:e)?null:i)),null),u=(n.startAt&&(h=(e=n.startAt,i=!!e.before,r=e.values||[],new Dy(r,i))),null);return n.endAt&&(u=(e=n.endAt,r=!e.before,i=e.values||[],new Dy(i,r))),aw(t,s,o,a,l,"F",h,u)}function Qb(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 k()}})(t.purpose);return null==r?null:{"goog-listen-tags":r}}function Yb(e){return Cb[e]}function Jb(e){return kb[e]}function Xb(e){return{fieldPath:e.canonicalString()}}function Zb(e){return Hm.fromServerFormat(e.fieldPath)}function eI(e){return 4<=e.length&&"projects"===e.get(0)&&"databases"===e.get(2)}class tI{constructor(e,t,r,n,i=P.min(),s=P.min(),a=K_.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 tI(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new tI(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new tI(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new tI(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class rI{constructor(e){this.Tt=e}}function nI(e,t){var r,n=t.key,i={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:iI(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument())i.document={name:Lb(e=e.Tt,(r=t).key),fields:r.data.value.mapValue.fields,updateTime:Nb(e,r.version.toTimestamp()),createTime:Nb(e,r.createTime.toTimestamp())};else if(t.isNoDocument())i.noDocument={path:n.path.toArray(),readTime:sI(t.version)};else{if(!t.isUnknownDocument())return k();i.unknownDocument={path:n.path.toArray(),version:sI(t.version)}}return i}function iI(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 aI(e){var t=new Bm(e.seconds,e.nanoseconds);return P.fromTimestamp(t)}function oI(t,r){let e=(r.baseMutations||[]).map(e=>Kb(t.Tt,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=>Kb(t.Tt,e)),i=Bm.fromMillis(r.localWriteTimeMs);return new nb(r.batchId,i,e,n)}function lI(e){var t,r=aI(e.readTime),n=void 0!==e.lastLimboFreeSnapshotVersion?aI(e.lastLimboFreeSnapshotVersion):P.min(),i=void 0!==e.query.documents?(S(1===(t=e.query).documents.length),cw(ow(Ub(t.documents[0])))):cw($b(e.query));return new tI(i,e.targetId,"TargetPurposeListen",e.lastListenSequenceNumber,r,n,K_.fromBase64String(e.resumeToken))}function hI(e,t){var r=sI(t.snapshotVersion),n=sI(t.lastLimboFreeSnapshotVersion),i=tw(t.target)?Hb(e.Tt,t.target):Gb(e.Tt,t.target).ht,s=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:Zy(t.target),readTime:r,resumeToken:s,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:n,query:i}}function uI(e){var t=$b({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?pw(t,t.limit,"L"):t}function cI(e,t){return new sb(t.largestBatchId,Kb(e.Tt,t.overlayMutation))}function dI(e,t){var r=t.path.lastSegment();return[e,kv(t.path.popLast()),r]}function pI(e,t,r,n){return{indexId:e,uid:t,sequenceNumber:r,readTime:sI(n.readTime),documentKey:kv(n.documentKey.path),largestBatchId:n.largestBatchId}}class fI{getBundleMetadata(e,t){return gI(e).get(t).next(e=>{if(e)return{id:(e=e).bundleId,createTime:aI(e.createTime),version:e.version}})}saveBundleMetadata(e,t){return gI(e).put({bundleId:(e=t).id,createTime:sI(Pb(e.createTime)),version:e.version})}getNamedQuery(e,t){return mI(e).get(t).next(e=>{if(e)return{name:(e=e).name,query:uI(e.bundledQuery),readTime:aI(e.readTime)}})}saveNamedQuery(e,t){return mI(e).put({name:(e=t).name,readTime:sI(Pb(e.readTime)),bundledQuery:e.bundledQuery})}}function gI(e){return O_(e,o_)}function mI(e){return O_(e,l_)}class vI{constructor(e,t){this.serializer=e,this.userId=t}static It(e,t){var r=t.uid||"";return new vI(e,r)}getOverlay(e,t){return _I(e).get(dI(this.userId,t)).next(e=>e?cI(this.serializer,e):null)}getOverlays(e,t){let r=Cw();return O.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 sb(i,t);s.push(this.Et(n,r))}),O.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(_I(r).J(b_,t))}),O.waitFor(i)}getOverlaysForCollection(e,t,r){let n=Cw(),i=kv(t),s=IDBKeyRange.bound([this.userId,i,r],[this.userId,i,Number.POSITIVE_INFINITY],!0);return _I(e).G(b_,s).next(e=>{for(var t of e){let e=cI(this.serializer,t);n.set(e.getKey(),e)}return n})}getOverlaysForCollectionGroup(e,t,r,i){let s=Cw(),a;var n=IDBKeyRange.bound([this.userId,t,r],[this.userId,t,Number.POSITIVE_INFINITY],!0);return _I(e).Z({index:T_,range:n},(e,t,r)=>{var n=cI(this.serializer,t);s.size()<i||n.largestBatchId===a?(s.set(n.getKey(),n),a=n.largestBatchId):r.done()}).next(()=>s)}Et(e,t){return _I(e).put(((e,t,r)=>{var[,n,i]=dI(t,r.mutation.key);return{userId:t,collectionPath:n,documentId:i,collectionGroup:r.mutation.key.getCollectionGroup(),largestBatchId:r.largestBatchId,overlayMutation:zb(e.Tt,r.mutation)}})(this.serializer,this.userId,t))}}function _I(e){return O_(e,y_)}class yI{dt(e){return O_(e,C_)}getSessionToken(e){return this.dt(e).get("sessionToken").next(e=>{var t=null==e?void 0:e.value;return t?K_.fromUint8Array(t):K_.EMPTY_BYTE_STRING})}setSessionToken(e,t){return this.dt(e).put({name:"sessionToken",value:t.toUint8Array()})}}class wI{constructor(){}At(e,t){this.Rt(e,t),t.Vt()}Rt(t,r){if("nullValue"in t)this.ft(r,5);else if("booleanValue"in t)this.ft(r,10),r.gt(t.booleanValue?1:0);else if("integerValue"in t)this.ft(r,15),r.gt(G_(t.integerValue));else if("doubleValue"in t){var e=G_(t.doubleValue);isNaN(e)?this.ft(r,13):(this.ft(r,15),Tv(e)?r.gt(0):r.gt(e))}else if("timestampValue"in t){let e=t.timestampValue;this.ft(r,20),"string"==typeof e&&(e=H_(e)),r.yt(""+(e.seconds||"")),r.gt(e.nanos||0)}else"stringValue"in t?(this.wt(t.stringValue,r),this.St(r)):"bytesValue"in t?(this.ft(r,30),r.bt($_(t.bytesValue)),this.St(r)):"referenceValue"in t?this.Dt(t.referenceValue,r):"geoPointValue"in t?(e=t.geoPointValue,this.ft(r,45),r.gt(e.latitude||0),r.gt(e.longitude||0)):"mapValue"in t?ky(t)?this.ft(r,Number.MAX_SAFE_INTEGER):Ey(t)?this.vt(t.mapValue,r):(this.Ct(t.mapValue,r),this.St(r)):"arrayValue"in t?(this.Ft(t.arrayValue,r),this.St(r)):k()}wt(e,t){this.ft(t,25),this.Mt(e,t)}Mt(e,t){t.yt(e)}Ct(e,t){var r=e.fields||{};this.ft(t,55);for(let e of Object.keys(r))this.wt(e,t),this.Rt(r[e],t)}vt(e,t){var r=e.fields||{},n=(this.ft(t,53),hy),i=(null==(i=null==(i=r[n].arrayValue)?void 0:i.values)?void 0:i.length)||0;this.ft(t,15),t.gt(G_(i)),this.wt(n,t),this.Rt(r[n],t)}Ft(e,t){var r=e.values||[];this.ft(t,50);for(let e of r)this.Rt(e,t)}Dt(e,t){this.ft(t,37),x.fromName(e).path.forEach(e=>{this.ft(t,60),this.Mt(e,t)})}ft(e,t){e.gt(t)}St(e){e.gt(2)}}wI.xt=new wI;function bI(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 II{constructor(){this.buffer=new Uint8Array(1024),this.position=0}Ot(e){var t=e[Symbol.iterator]();let r=t.next();for(;!r.done;)this.Nt(r.value),r=t.next();this.Bt()}Lt(e){var t=e[Symbol.iterator]();let r=t.next();for(;!r.done;)this.kt(r.value),r=t.next();this.qt()}Qt(e){for(var t of e){let e=t.charCodeAt(0);if(e<128)this.Nt(e);else if(e<2048)this.Nt(960|e>>>6),this.Nt(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Nt(480|e>>>12),this.Nt(128|63&e>>>6),this.Nt(128|63&e);else{let e=t.codePointAt(0);this.Nt(240|e>>>18),this.Nt(128|63&e>>>12),this.Nt(128|63&e>>>6),this.Nt(128|63&e)}}this.Bt()}$t(e){for(var t of e){let e=t.charCodeAt(0);if(e<128)this.kt(e);else if(e<2048)this.kt(960|e>>>6),this.kt(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.kt(480|e>>>12),this.kt(128|63&e>>>6),this.kt(128|63&e);else{let e=t.codePointAt(0);this.kt(240|e>>>18),this.kt(128|63&e>>>12),this.kt(128|63&e>>>6),this.kt(128|63&e)}}this.qt()}Kt(e){var t=this.Ut(e),r=bI(t);this.Wt(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]}Gt(e){var t=this.Ut(e),r=bI(t);this.Wt(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])}zt(){this.jt(255),this.jt(255)}Ht(){this.Jt(255),this.Jt(255)}reset(){this.position=0}seed(e){this.Wt(e.length),this.buffer.set(e,this.position),this.position+=e.length}Yt(){return this.buffer.slice(0,this.position)}Ut(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}Nt(e){var t=255&e;0==t?(this.jt(0),this.jt(255)):255==t?(this.jt(255),this.jt(0)):this.jt(t)}kt(e){var t=255&e;0==t?(this.Jt(0),this.Jt(255)):255==t?(this.Jt(255),this.Jt(0)):this.Jt(e)}Bt(){this.jt(0),this.jt(1)}qt(){this.Jt(0),this.Jt(1)}jt(e){this.Wt(1),this.buffer[this.position++]=e}Jt(e){this.Wt(1),this.buffer[this.position++]=~e}Wt(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 TI{constructor(e){this.Zt=e}bt(e){this.Zt.Ot(e)}yt(e){this.Zt.Qt(e)}gt(e){this.Zt.Kt(e)}Vt(){this.Zt.zt()}}class EI{constructor(e){this.Zt=e}bt(e){this.Zt.Lt(e)}yt(e){this.Zt.$t(e)}gt(e){this.Zt.Gt(e)}Vt(){this.Zt.Ht()}}class CI{constructor(){this.Zt=new II,this.Xt=new TI(this.Zt),this.en=new EI(this.Zt)}seed(e){this.Zt.seed(e)}tn(e){return 0===e?this.Xt:this.en}Yt(){return this.Zt.Yt()}reset(){this.Zt.reset()}}class kI{constructor(e,t,r,n){this.indexId=e,this.documentKey=t,this.arrayValue=r,this.directionalValue=n}nn(){var e=this.directionalValue.length,t=0===e||255===this.directionalValue[e-1]?e+1:e,r=new Uint8Array(t);return r.set(this.directionalValue,0),t!==e?r.set([0],this.directionalValue.length):++r[r.length-1],new kI(this.indexId,this.documentKey,this.arrayValue,r)}}function SI(e,t){var r=e.indexId-t.indexId;return 0!=r||0!==(r=AI(e.arrayValue,t.arrayValue))||0!==(r=AI(e.directionalValue,t.directionalValue))?r:x.comparator(e.documentKey,t.documentKey)}function AI(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}class NI{constructor(e){this.rn=new M((e,t)=>Hm.comparator(e.field,t.field)),this.collectionId=null!=e.collectionGroup?e.collectionGroup:e.path.lastSegment(),this.sn=e.orderBy,this._n=[];for(var t of e.filters){let e=t;e.isInequality()?this.rn=this.rn.add(e):this._n.push(e)}}get an(){return 1<this.rn.size}un(e){if(S(e.collectionGroup===this.collectionId),this.an)return!1;let t=Qm(e);if(void 0!==t&&!this.cn(t))return!1;var r=Ym(e);let n=new Set,i=0,s=0;for(;i<r.length&&this.cn(r[i]);++i)n=n.add(r[i].fieldPath.canonicalString());if(i!==r.length){if(0<this.rn.size){let t=this.rn.getIterator().getNext();if(!n.has(t.field.canonicalString())){let e=r[i];if(!this.ln(t,e)||!this.hn(this.sn[s++],e))return!1}++i}for(;i<r.length;++i){let e=r[i];if(s>=this.sn.length||!this.hn(this.sn[s++],e))return!1}}return!0}Pn(){if(this.an)return null;let e=new M(Hm.comparator);var t,r,n=[];for(t of this._n)t.field.isKeyField()||("array-contains"===t.op||"array-contains-any"===t.op?n.push(new Jm(t.field,2)):e.has(t.field)||(e=e.add(t.field),n.push(new Jm(t.field,0))));for(r of this.sn)r.field.isKeyField()||e.has(r.field)||(e=e.add(r.field),n.push(new Jm(r.field,"asc"===r.dir?0:1)));return new $m($m.UNKNOWN_ID,this.collectionId,n,Xm.empty())}cn(e){for(var t of this._n)if(this.ln(t,e))return!0;return!1}ln(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)}hn(e,t){return!!e.field.isEqual(t.fieldPath)&&(0===t.kind&&"asc"===e.dir||1===t.kind&&"desc"===e.dir)}}function RI(e){var t;return 0===e.getFilters().length?[]:(t=function t(e){if(S(e instanceof F||e instanceof U),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=MI(n),xI(n)?n:(S(n instanceof U),S(Fy(n)),S(1<n.filters.length),n.filters.reduce((e,t)=>OI(e,t)))}(function t(r){var n;if(S(r instanceof F||r instanceof U),r instanceof F){if(r instanceof $y){let e=(null==(n=null==(n=r.value.arrayValue)?void 0:n.values)?void 0:n.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(xI(t)),PI(t)||DI(t)?[t]:t.getFilters())}function PI(e){return e instanceof F}function DI(e){return e instanceof U&&Vy(e)}function xI(e){return PI(e)||DI(e)||(e=>{if(e instanceof U&&Uy(e)){for(var t of e.getFilters())if(!PI(t)&&!DI(t))return!1;return!0}return!1})(e)}function OI(e,t){var r,n;return S(e instanceof F||e instanceof U),S(t instanceof F||t instanceof U),MI(e instanceof F?t instanceof F?(r=e,n=t,U.create([r,n],"and")):LI(e,t):t instanceof F?LI(t,e):((e,t)=>{if(S(0<e.filters.length&&0<t.filters.length),Fy(e)&&Fy(t))return jy(e,t.getFilters());let r=Uy(e)?e:t,n=Uy(e)?t:e,i=r.filters.map(e=>OI(e,n));return U.create(i,"or")})(e,t))}function LI(t,e){var r;return Fy(e)?jy(e,t.getFilters()):(r=e.filters.map(e=>OI(t,e)),U.create(r,"or"))}function MI(t){if(S(t instanceof F||t instanceof U),t instanceof F)return t;var e=t.getFilters();if(1===e.length)return MI(e[0]);if(qy(t))return t;let r=e.map(e=>MI(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 FI{constructor(){this.Tn=new UI}addToCollectionParentIndex(e,t){return this.Tn.add(t),O.resolve()}getCollectionParents(e,t){return O.resolve(this.Tn.getEntries(t))}addFieldIndex(e,t){return O.resolve()}deleteFieldIndex(e,t){return O.resolve()}deleteAllFieldIndexes(e){return O.resolve()}createTargetIndexes(e,t){return O.resolve()}getDocumentsMatchingTarget(e,t){return O.resolve(null)}getIndexType(e,t){return O.resolve(0)}getFieldIndexes(e,t){return O.resolve([])}getNextCollectionGroupToUpdate(e){return O.resolve(null)}getMinOffset(e,t){return O.resolve(tv.min())}getMinOffsetFromCollectionGroup(e,t){return O.resolve(tv.min())}updateCollectionGroup(e,t,r){return O.resolve()}updateIndexEntries(e,t){return O.resolve()}}class UI{constructor(){this.index={}}add(e){var t=e.lastSegment(),r=e.popLast(),n=this.index[t]||new M(D.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 M(D.comparator)).toArray()}}let VI="IndexedDbIndexManager",qI=new Uint8Array(0);class jI{constructor(e,t){this.databaseId=t,this.In=new UI,this.En=new ww(e=>Zy(e),(e,t)=>ew(e,t)),this.uid=e.uid||""}addToCollectionParentIndex(e,t){var r,n;return this.In.has(t)?O.resolve():(n=t.lastSegment(),r=t.popLast(),e.addOnCommittedListener(()=>{this.In.add(t)}),n={collectionId:n,parent:kv(r)},BI(e).put(n))}getCollectionParents(e,r){let n=[],t=IDBKeyRange.bound([r,""],[qm(r),""],!1,!0);return BI(e).G(t).next(e=>{for(var t of e){if(t.collectionId!==r)break;n.push(Av(t.parent))}return n})}addFieldIndex(e,r){let t=KI(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=WI(e);return i.next(e=>{t.put(pI(e,this.uid,r.indexState.sequenceNumber,r.indexState.offset))})}return i.next()}deleteFieldIndex(e,t){let r=KI(e),n=WI(e),i=zI(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=KI(e),r=zI(e),n=WI(e);return t.J().next(()=>r.J()).next(()=>n.J())}createTargetIndexes(r,e){return O.forEach(this.dn(e),t=>this.getIndexType(r,t).next(e=>{if(0===e||1===e){let e=new NI(t).Pn();if(null!=e)return this.addFieldIndex(r,e)}}))}getDocumentsMatchingTarget(e,c){let d=zI(e),r=!0,n=new Map;return O.forEach(this.dn(c),t=>this.An(e,t).next(e=>{r=r&&!!e,n.set(t,e)})).next(()=>{if(r){let h=V(),u=[];return O.forEach(n,(e,t)=>{C(VI,`Using index ${r=e,`id=${r.indexId}|cg=${r.collectionGroup}|f=`+r.fields.map(e=>e.fieldPath+":"+e.kind).join(",")} to execute `+Zy(c));var r,n=((t,e)=>{var r=Qm(e);if(void 0!==r)for(let e of rw(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 Ym(r))for(let e of rw(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 Ym(e)){let e=(0===r.kind?nw:iw)(t,r.fieldPath,t.startAt);n.push(e.value),i=i&&e.inclusive}return new Dy(n,i)})(t,e),a=((t,e)=>{var r,n=[];let i=!0;for(r of Ym(e)){let e=(0===r.kind?iw:nw)(t,r.fieldPath,t.endAt);n.push(e.value),i=i&&e.inclusive}return new Dy(n,i)})(t,e),o=this.Rn(e,t,s),l=this.Rn(e,t,a),i=this.Vn(e,t,i),n=this.mn(e.indexId,n,o,s.inclusive,l,a.inclusive,i);return O.forEach(n,e=>d.H(e,c.limit).next(e=>{e.forEach(e=>{var t=x.fromSegments(e.documentKey);h.has(t)||(h=h.add(t),u.push(t))})}))}).next(()=>u)}return O.resolve(null)})}dn(t){let e=this.En.get(t);return e||(e=0===t.filters.length?[t]:RI(U.create(t.filters,"and")).map(e=>Xy(t.path,t.collectionGroup,t.orderBy,e.getFilters(),t.limit,t.startAt,t.endAt)),this.En.set(t,e)),e}mn(i,s,a,o,l,h,u){let e=(null!=s?s.length:1)*Math.max(a.length,l.length),c=e/(null!=s?s.length:1),d=[];for(let p=0;p<e;++p){let t=s?this.fn(s[p/c]):qI,e=this.gn(i,t,a[p%c],o),r=this.pn(i,t,l[p%c],h),n=u.map(e=>this.gn(i,t,e,!0));d.push(...this.createRange(e,r,n))}return d}gn(e,t,r,n){var i=new kI(e,x.empty(),t,r);return n?i:i.nn()}pn(e,t,r,n){var i=new kI(e,x.empty(),t,r);return n?i.nn():i}An(e,t){let n=new NI(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.un(r)&&(!t||r.fields.length>t.fields.length)&&(t=r);return t})}getIndexType(e,t){let r=2,n=this.dn(t);return O.forEach(n,t=>this.An(e,t).next(e=>{e?0!==r&&e.fields.length<(t=>{let r=new M(Hm.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)}yn(e,t){var r,n=new CI;for(r of Ym(e)){let e=t.data.field(r.fieldPath);if(null==e)return null;var i=n.tn(r.kind);wI.xt.At(e,i)}return n.Yt()}fn(e){var t=new CI;return wI.xt.At(e,t.tn(0)),t.Yt()}wn(e,t){var r,n=new CI;return wI.xt.At(_y(this.databaseId,t),n.tn(0===(r=Ym(e)).length?0:r[r.length-1].kind)),n.Yt()}Vn(e,n,i){if(null===i)return[];let s=[],a=(s.push(new CI),0);for(var o of Ym(e)){let t=i[a++];for(let r of s)if(this.Sn(n,o.fieldPath)&&wy(t))s=this.bn(s,o,t);else{let e=r.tn(o.kind);wI.xt.At(t,e)}}return this.Dn(s)}Rn(e,t,r){return this.Vn(e,t,r.position)}Dn(e){var t=[];for(let r=0;r<e.length;++r)t[r]=e[r].Yt();return t}bn(r,n,e){let i=[...r],s=[];for(let r of e.arrayValue.values||[])for(let t of i){let e=new CI;e.seed(t.Yt()),wI.xt.At(r,e.tn(n.kind)),s.push(e)}return s}Sn(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=KI(e),n=WI(e);return(t?r.G(u_,IDBKeyRange.bound(t,t)):r.G()).next(e=>{let s=[];return O.forEach(e,i=>n.get([i.indexId,this.uid]).next(e=>{var t,r,n;s.push((t=i,r=(e=e)?new Xm(e.sequenceNumber,new tv(aI(e.readTime),new x(Av(e.documentKey)),e.largestBatchId)):Xm.empty(),n=t.fields.map(([e,t])=>new Jm(Hm.fromServerFormat(e),t)),new $m(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:R(e.collectionGroup,t.collectionGroup)}),e[0].collectionGroup))}updateCollectionGroup(e,r,n){let i=KI(e),s=WI(e);return this.vn(e).next(t=>i.G(u_,IDBKeyRange.bound(r,r)).next(e=>O.forEach(e,e=>s.put(pI(e.indexId,this.uid,t,n)))))}updateIndexEntries(i,e){let r=new Map;return O.forEach(e,(t,n)=>{var e=r.get(t.collectionGroup);return(e?O.resolve(e):this.getFieldIndexes(i,t.collectionGroup)).next(e=>(r.set(t.collectionGroup,e),O.forEach(e,r=>this.Cn(i,t,r).next(e=>{var t=this.Fn(n,r);return e.isEqual(t)?O.resolve():this.Mn(i,n,r,e,t)}))))})}xn(e,t,r,n){return zI(e).put({indexId:n.indexId,uid:this.uid,arrayValue:n.arrayValue,directionalValue:n.directionalValue,orderedDocumentKey:this.wn(r,t.key),documentKey:t.key.path.toArray()})}On(e,t,r,n){return zI(e).delete([n.indexId,this.uid,n.arrayValue,n.directionalValue,this.wn(r,t.key),t.key.path.toArray()])}Cn(e,r,n){var t=zI(e);let i=new M(SI);return t.Z({index:v_,range:IDBKeyRange.only([n.indexId,this.uid,this.wn(n,r)])},(e,t)=>{i=i.add(new kI(n.indexId,r,t.arrayValue,t.directionalValue))}).next(()=>i)}Fn(t,r){let n=new M(SI);var i=this.yn(r,t);if(null!=i){let e=Qm(r);if(null!=e){var s=t.data.field(e.fieldPath);if(wy(s))for(let e of s.arrayValue.values||[])n=n.add(new kI(r.indexId,t.key,this.fn(e),i))}else n=n.add(new kI(r.indexId,t.key,qI,i))}return n}Mn(t,r,s,e,a){C(VI,"Updating index entries for document '%s'",r.key);let o=[];{var l=SI,h=e=>{o.push(this.xn(t,r,s,e))},u=e=>{o.push(this.On(t,r,s,e))},c=e.getIterator(),d=a.getIterator();let n=j_(c),i=j_(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=j_(d)):r?(u(n),n=j_(c)):(n=j_(c),i=j_(d))}}return O.waitFor(o)}vn(e){let n=1;return WI(e).Z({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)=>SI(e,t)).filter((e,t,r)=>!t||0!==SI(e,r[t-1]));var i=[];i.push(r);for(let s of e){let e=SI(s,r),t=SI(s,n);if(0===e)i[0]=r.nn();else if(0<e&&t<0)i.push(s),i.push(s.nn());else if(0<t)break}i.push(n);let s=[];for(let a=0;a<i.length;a+=2){if(this.Nn(i[a],i[a+1]))return[];let e=[i[a].indexId,this.uid,i[a].arrayValue,i[a].directionalValue,qI,[]],t=[i[a+1].indexId,this.uid,i[a+1].arrayValue,i[a+1].directionalValue,qI,[]];s.push(IDBKeyRange.bound(e,t))}return s}Nn(e,t){return 0<SI(e,t)}getMinOffsetFromCollectionGroup(e,t){return this.getFieldIndexes(e,t).next(HI)}getMinOffset(t,e){return O.mapArray(this.dn(e),e=>this.An(t,e).next(e=>e||k())).next(HI)}}function BI(e){return O_(e,i_)}function zI(e){return O_(e,g_)}function KI(e){return O_(e,h_)}function WI(e){return O_(e,c_)}function HI(e){S(0!==e.length);let t=e[0].indexState.offset,r=t.largestBatchId;for(let i=1;i<e.length;i++){var n=e[i].indexState.offset;rv(n,t)<0&&(t=n),r<n.largestBatchId&&(r=n.largestBatchId)}return new tv(t.readTime,t.documentKey,r)}let GI={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class $I{static withCacheSize(e){return new $I(e,$I.DEFAULT_COLLECTION_PERCENTILE,$I.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}constructor(e,t,r){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=r}}function QI(t,r,n){let e=t.store(xv),i=t.store(qv),s=[],a=IDBKeyRange.only(n.batchId),o=0;var l=e.Z({range:a},(e,t,r)=>(o++,r.delete()));s.push(l.next(()=>{S(1===o)}));let h=[];for(let t of n.mutations){let e=Uv(r,t.key.path,n.batchId);s.push(i.delete(e)),h.push(t.key)}return O.waitFor(s).next(()=>h)}function YI(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 k();t=e.noDocument}return JSON.stringify(t).length}$I.DEFAULT_COLLECTION_PERCENTILE=10,$I.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,$I.DEFAULT=new $I(41943040,$I.DEFAULT_COLLECTION_PERCENTILE,$I.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),$I.DISABLED=new $I(-1,0,0);class JI{constructor(e,t,r,n){this.userId=e,this.serializer=t,this.indexManager=r,this.referenceDelegate=n,this.Bn={}}static It(e,t,r,n){S(""!==e.uid);var i=e.isAuthenticated()?e.uid:"";return new JI(i,t,r,n)}checkEmpty(e){let n=!0;var t=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return ZI(e).Z({index:Lv,range:t},(e,t,r)=>{n=!1,r.done()}).next(()=>n)}addMutationBatch(c,d,p,f){let g=eT(c),m=ZI(c);return m.add({}).next(t=>{S("number"==typeof t);let e=new nb(t,d,p,f),r=(i=this.serializer,s=this.userId,a=e,o=a.baseMutations.map(e=>zb(i.Tt,e)),l=a.mutations.map(e=>zb(i.Tt,e)),{userId:s,batchId:a.batchId,localWriteTimeMs:a.localWriteTime.toMillis(),baseMutations:o,mutations:l}),n=[];var i,s,a,o,l;let h=new M((e,t)=>R(e.canonicalString(),t.canonicalString()));for(let u of f){let e=Uv(this.userId,u.key.path,t);h=h.add(u.key.path.popLast()),n.push(m.put(r)),n.push(g.put(e,Vv))}return h.forEach(e=>{n.push(this.indexManager.addToCollectionParentIndex(c,e))}),c.addOnCommittedListener(()=>{this.Bn[t]=e.keys()}),O.waitFor(n).next(()=>e)})}lookupMutationBatch(e,t){return ZI(e).get(t).next(e=>e?(S(e.userId===this.userId),oI(this.serializer,e)):null)}Ln(e,r){return this.Bn[r]?O.resolve(this.Bn[r]):this.lookupMutationBatch(e,r).next(e=>{var t;return e?(t=e.keys(),this.Bn[r]=t):null})}getNextMutationBatchAfterBatchId(e,t){let n=t+1,r=IDBKeyRange.lowerBound([this.userId,n]),i=null;return ZI(e).Z({index:Lv,range:r},(e,t,r)=>{t.userId===this.userId&&(S(t.batchId>=n),i=oI(this.serializer,t)),r.done()}).next(()=>i)}getHighestUnacknowledgedBatchId(e){var t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let n=bv;return ZI(e).Z({index:Lv,range:t,reverse:!0},(e,t,r)=>{n=t.batchId,r.done()}).next(()=>n)}getAllMutationBatches(e){var t=IDBKeyRange.bound([this.userId,bv],[this.userId,Number.POSITIVE_INFINITY]);return ZI(e).G(Lv,t).next(e=>e.map(e=>oI(this.serializer,e)))}getAllMutationBatchesAffectingDocumentKey(a,o){let e=Fv(this.userId,o.path),t=IDBKeyRange.lowerBound(e),l=[];return eT(a).Z({range:t},(e,t,r)=>{var[n,i,s]=e,i=Av(i);if(n===this.userId&&o.path.isEqual(i))return ZI(a).get(s).next(e=>{if(!e)throw k();S(e.userId===this.userId),l.push(oI(this.serializer,e))});r.done()}).next(()=>l)}getAllMutationBatchesAffectingDocumentKeys(t,e){let o=new M(R),r=[];return e.forEach(a=>{var e=Fv(this.userId,a.path),e=IDBKeyRange.lowerBound(e),e=eT(t).Z({range:e},(e,t,r)=>{var[n,i,s]=e,i=Av(i);n===this.userId&&a.path.isEqual(i)?o=o.add(s):r.done()});r.push(e)}),O.waitFor(r).next(()=>this.kn(t,o))}getAllMutationBatchesAffectingQuery(e,t){let a=t.path,o=a.length+1,r=Fv(this.userId,a),n=IDBKeyRange.lowerBound(r),l=new M(R);return eT(e).Z({range:n},(e,t,r)=>{var[n,i,s]=e,i=Av(i);n===this.userId&&a.isPrefixOf(i)?i.length===o&&(l=l.add(s)):r.done()}).next(()=>this.kn(e,l))}kn(t,e){let r=[],n=[];return e.forEach(e=>{n.push(ZI(t).get(e).next(e=>{if(null===e)throw k();S(e.userId===this.userId),r.push(oI(this.serializer,e))}))}),O.waitFor(n).next(()=>r)}removeMutationBatch(t,r){return QI(t.ue,this.userId,r).next(e=>(t.addOnCommittedListener(()=>{this.qn(r.batchId)}),O.forEach(e,e=>this.referenceDelegate.markPotentiallyOrphaned(t,e))))}qn(e){delete this.Bn[e]}performConsistencyCheck(r){return this.checkEmpty(r).next(e=>{if(!e)return O.resolve();let t=IDBKeyRange.lowerBound([this.userId]),n=[];return eT(r).Z({range:t},(t,e,r)=>{if(t[0]===this.userId){let e=Av(t[1]);n.push(e)}else r.done()}).next(()=>{S(0===n.length)})})}containsKey(e,t){return XI(e,this.userId,t)}Qn(e){return tT(e).get(this.userId).next(e=>e||{userId:this.userId,lastAcknowledgedBatchId:bv,lastStreamToken:""})}}function XI(e,s,t){let r=Fv(s,t.path),a=r[1],n=IDBKeyRange.lowerBound(r),o=!1;return eT(e).Z({range:n,Y:!0},(e,t,r)=>{var[n,i,,]=e;n===s&&i===a&&(o=!0),r.done()}).next(()=>o)}function ZI(e){return O_(e,xv)}function eT(e){return O_(e,qv)}function tT(e){return O_(e,Dv)}class rT{constructor(e){this.$n=e}next(){return this.$n+=2,this.$n}static Kn(){return new rT(0)}static Un(){return new rT(-1)}}class nT{constructor(e,t){this.referenceDelegate=e,this.serializer=t}allocateTargetId(r){return this.Wn(r).next(e=>{var t=new rT(e.highestTargetId);return e.highestTargetId=t.next(),this.Gn(r,e).next(()=>e.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.Wn(e).next(e=>P.fromTimestamp(new Bm(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.Wn(e).next(e=>e.highestListenSequenceNumber)}setTargetsMetadata(t,r,n){return this.Wn(t).next(e=>(e.highestListenSequenceNumber=r,n&&(e.lastRemoteSnapshotVersion=n.toTimestamp()),e.highestListenSequenceNumber<r&&(e.highestListenSequenceNumber=r),this.Gn(t,e)))}addTargetData(t,r){return this.zn(t,r).next(()=>this.Wn(t).next(e=>(e.targetCount+=1,this.jn(r,e),this.Gn(t,e))))}updateTargetData(e,t){return this.zn(e,t)}removeTargetData(t,e){return this.removeMatchingKeysForTargetId(t,e.targetId).next(()=>iT(t).delete(e.targetId)).next(()=>this.Wn(t)).next(e=>(S(0<e.targetCount),--e.targetCount,this.Gn(t,e)))}removeTargets(n,i,s){let a=0,o=[];return iT(n).Z((e,t)=>{var r=lI(t);r.sequenceNumber<=i&&null===s.get(r.targetId)&&(a++,o.push(this.removeTargetData(n,r)))}).next(()=>O.waitFor(o)).next(()=>a)}forEachTarget(e,n){return iT(e).Z((e,t)=>{var r=lI(t);n(r)})}Wn(e){return sT(e).get(r_).next(e=>(S(null!==e),e))}Gn(e,t){return sT(e).put(r_,t)}zn(e,t){return iT(e).put(hI(this.serializer,t))}jn(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.Wn(e).next(e=>e.targetCount)}getTargetData(e,i){var t=Zy(i),t=IDBKeyRange.bound([t,Number.NEGATIVE_INFINITY],[t,Number.POSITIVE_INFINITY]);let s=null;return iT(e).Z({range:t,index:Yv},(e,t,r)=>{var n=lI(t);ew(i,n.target)&&(s=n,r.done())}).next(()=>s)}addMatchingKeys(r,e,n){let i=[],s=aT(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))}),O.waitFor(i)}removeMatchingKeys(r,e,n){let i=aT(r);return O.forEach(e,e=>{var t=kv(e.path);return O.waitFor([i.delete([n,t]),this.referenceDelegate.removeReference(r,n,e)])})}removeMatchingKeysForTargetId(e,t){var r=aT(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=aT(e);let i=V();return n.Z({range:r,Y:!0},(e,t,r)=>{var n=Av(e[1]),n=new x(n);i=i.add(n)}).next(()=>i)}containsKey(e,t){var r=kv(t.path),r=IDBKeyRange.bound([r],[qm(r)],!1,!0);let n=0;return aT(e).Z({index:e_,Y:!0,range:r},([e],t,r)=>{0!==e&&(n++,r.done())}).next(()=>0<n)}lt(e,t){return iT(e).get(t).next(e=>e?lI(e):null)}}function iT(e){return O_(e,Qv)}function sT(e){return O_(e,n_)}function aT(e){return O_(e,Xv)}let oT="LruGarbageCollector";function lT([e,t],[r,n]){var i=R(e,r);return 0===i?R(t,n):i}class hT{constructor(e){this.Hn=e,this.buffer=new M(lT),this.Jn=0}Yn(){return++this.Jn}Zn(e){var t=[e,this.Yn()];if(this.buffer.size<this.Hn)this.buffer=this.buffer.add(t);else{let e=this.buffer.last();lT(t,e)<0&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class uT{constructor(e,t,r){this.garbageCollector=e,this.asyncQueue=t,this.localStore=r,this.Xn=null}start(){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.er(6e4)}stop(){this.Xn&&(this.Xn.cancel(),this.Xn=null)}get started(){return null!==this.Xn}er(e){C(oT,`Garbage collection scheduled in ${e}ms`),this.Xn=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,async()=>{this.Xn=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){dv(e)?C(oT,"Ignoring IndexedDB error during garbage collection: ",e):await sv(e)}await this.er(3e5)})}}class cT{constructor(e,t){this.tr=e,this.params=t}calculateTargetCount(e,t){return this.tr.nr(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return O.resolve(wv.ae);let r=new hT(t);return this.tr.forEachTarget(e,e=>r.Zn(e.sequenceNumber)).next(()=>this.tr.rr(e,e=>r.Zn(e))).next(()=>r.maxValue)}removeTargets(e,t,r){return this.tr.removeTargets(e,t,r)}removeOrphanedDocuments(e,t){return this.tr.removeOrphanedDocuments(e,t)}collect(t,r){return-1===this.params.cacheSizeCollectionThreshold?(C("LruGarbageCollector","Garbage collection skipped; disabled"),O.resolve(GI)):this.getCacheSize(t).next(e=>e<this.params.cacheSizeCollectionThreshold?(C("LruGarbageCollector",`Garbage collection skipped; Cache size ${e} is lower than threshold `+this.params.cacheSizeCollectionThreshold),GI):this.ir(t,r))}getCacheSize(e){return this.tr.getCacheSize(e)}ir(t,r){let n,i,s,a,o,l,h,u=Date.now();return this.calculateTargetCount(t,this.params.percentileToCollect).next(e=>(i=e>this.params.maximumSequenceNumbersToCollect?(C("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(),Cm()<=c.DEBUG&&C("LruGarbageCollector",`LRU Garbage Collection
|
|
13
13
|
Counted targets in ${a-u}ms
|
|
14
|
-
Determined least recently used ${i} in `+(o-a)+"ms\n"+` Removed ${s} targets in `+(l-o)+"ms\n"+` Removed ${e} documents in `+(h-l)+"ms\n"+`Total Duration: ${h-u}ms`),O.resolve({didRun:!0,sequenceNumbersCollected:i,targetsRemoved:s,documentsRemoved:e})))}}function pT(e,t){return new dT(e,t)}class fT{constructor(e,t){this.db=e,this.garbageCollector=pT(this,t)}nr(e){let r=this.sr(e);return this.db.getTargetCache().getTargetCount(e).next(t=>r.next(e=>t+e))}sr(e){let t=0;return this.rr(e,e=>{t++}).next(()=>t)}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}rr(e,r){return this._r(e,(e,t)=>r(t))}addReference(e,t,r){return gT(e,r)}removeReference(e,t,r){return gT(e,r)}removeTargets(e,t,r){return this.db.getTargetCache().removeTargets(e,t,r)}markPotentiallyOrphaned(e,t){return gT(e,t)}ar(e,r){{var n=e,i=r;let t=!1;return rT(n).X(e=>ZI(n,e,i).next(e=>(e&&(t=!0),O.resolve(!e)))).next(()=>t)}}removeOrphanedDocuments(r,n){let i=this.db.getRemoteDocumentCache().newChangeBuffer(),s=[],a=0;return this._r(r,(t,e)=>{if(e<=n){let e=this.ar(r,t).next(e=>{if(!e)return a++,i.getEntry(r,t).next(()=>(i.removeEntry(t,P.min()),oT(r).delete([0,Av(t.path)])))});s.push(e)}}).next(()=>O.waitFor(s)).next(()=>i.apply(r)).next(()=>a)}removeTarget(e,t){var r=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,r)}updateLimboDocument(e,t){return gT(e,t)}_r(e,n){var t=oT(e);let i,s=Iv.ae;return t.Z({index:r_},([e],{path:t,sequenceNumber:r})=>{0===e?(s!==Iv.ae&&n(new x(Rv(i)),s),s=r,i=t):s=Iv.ae}).next(()=>{s!==Iv.ae&&n(new x(Rv(i)),s)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function gT(e,t){return oT(e).put((e=e.currentSequenceNumber,{targetId:0,path:Av(t.path),sequenceNumber:e}))}class mT{constructor(){this.changes=new Iw(e=>e.toString(),(e,t)=>e.isEqual(t)),this.changesApplied=!1}addEntry(e){this.assertNotApplied(),this.changes.set(e.key,e)}removeEntry(e,t){this.assertNotApplied(),this.changes.set(e,xy.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();var r=this.changes.get(t);return void 0!==r?O.resolve(r):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}}class vT{constructor(e){this.serializer=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,r){return bT(e).put(r)}removeEntry(e,t,r){return bT(e).delete((e=r,[(n=t.path.toArray()).slice(0,n.length-2),n[n.length-2],sI(e),n[n.length-1]]));var n}updateMetadata(t,r){return this.getMetadata(t).next(e=>(e.byteSize+=r,this.ur(t,e)))}getEntry(e,r){let n=xy.newInvalidDocument(r);return bT(e).Z({index:Wv,range:IDBKeyRange.only(IT(r))},(e,t)=>{n=this.cr(r,t)}).next(()=>n)}lr(e,r){let n={size:0,document:xy.newInvalidDocument(r)};return bT(e).Z({index:Wv,range:IDBKeyRange.only(IT(r))},(e,t)=>{n={document:this.cr(r,t),size:JI(t)}}).next(()=>n)}getEntries(e,t){let n=Tw;return this.hr(e,t,(e,t)=>{var r=this.cr(e,t);n=n.insert(e,r)}).next(()=>n)}Pr(e,t){let n=Tw,i=new L(x.comparator);return this.hr(e,t,(e,t)=>{var r=this.cr(e,t);n=n.insert(e,r),i=i.insert(e,JI(t))}).next(()=>({documents:n,Tr:i}))}hr(e,t,i){if(t.isEmpty())return O.resolve();let r=new M(ET),n=(t.forEach(e=>r=r.add(e)),IDBKeyRange.bound(IT(r.first()),IT(r.last()))),s=r.getIterator(),a=s.getNext();return bT(e).Z({index:Wv,range:n},(e,t,r)=>{for(var n=x.fromSegments([...t.prefixPath,t.collectionGroup,t.documentId]);a&&ET(a,n)<0;)i(a,null),a=s.getNext();a&&a.isEqual(n)&&(i(a,t),a=s.hasNext()?s.getNext():null),a?r.W(IT(a)):r.done()}).next(()=>{for(;a;)i(a,null),a=s.hasNext()?s.getNext():null})}getDocumentsMatchingQuery(e,n,t,i,s){var r=n.path,a=[r.popLast().toArray(),r.lastSegment(),sI(t.readTime),t.documentKey.path.isEmpty()?"":t.documentKey.path.lastSegment()],r=[r.popLast().toArray(),r.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return bT(e).G(IDBKeyRange.bound(a,r,!0)).next(e=>{null!=s&&s.incrementDocumentReadCount(e.length);let t=Tw;for(let r of e){let e=this.cr(x.fromSegments(r.prefixPath.concat(r.collectionGroup,r.documentId)),r);e.isFoundDocument()&&(yw(n,e)||i.has(e.key))&&(t=t.insert(e.key,e))}return t})}getAllFromCollectionGroup(e,t,r,i){let s=Tw;var n=TT(t,r),a=TT(t,nv.max());return bT(e).Z({index:Gv,range:IDBKeyRange.bound(n,a,!0)},(e,t,r)=>{var n=this.cr(x.fromSegments(t.prefixPath.concat(t.collectionGroup,t.documentId)),t);(s=s.insert(n.key,n)).size===i&&r.done()}).next(()=>s)}newChangeBuffer(e){return new yT(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(e=>e.byteSize)}getMetadata(e){return wT(e).get(Yv).next(e=>(S(!!e),e))}ur(e,t){return wT(e).put(Yv,t)}cr(e,t){if(t){let e=((e,r)=>{let n;if(r.document)n=zb(e.Tt,r.document,!!r.hasCommittedMutations);else if(r.noDocument){let e=x.fromSegments(r.noDocument.path),t=oI(r.noDocument.readTime);n=xy.newNoDocument(e,t),r.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!r.unknownDocument)return k();{let e=x.fromSegments(r.unknownDocument.path),t=oI(r.unknownDocument.version);n=xy.newUnknownDocument(e,t)}}return r.readTime&&n.setReadTime((e=r.readTime,t=new Km(e[0],e[1]),P.fromTimestamp(t))),n;var t})(this.serializer,t);if(!e.isNoDocument()||!e.version.isEqual(P.min()))return e}return xy.newInvalidDocument(e)}}function _T(e){return new vT(e)}class yT extends mT{constructor(e,t){super(),this.Ir=e,this.trackRemovals=t,this.Er=new Iw(e=>e.toString(),(e,t)=>e.isEqual(t))}applyChanges(s){let a=[],o=0,l=new M((e,t)=>R(e.canonicalString(),t.canonicalString()));return this.changes.forEach((t,r)=>{var e=this.Er.get(t);if(a.push(this.Ir.removeEntry(s,t,e.readTime)),r.isValidDocument()){var n=iI(this.Ir.serializer,r),i=(l=l.add(t.path.popLast()),JI(n));o+=i-e.size,a.push(this.Ir.addEntry(s,t,n))}else if(o-=e.size,this.trackRemovals){let e=iI(this.Ir.serializer,r.convertToNoDocument(P.min()));a.push(this.Ir.addEntry(s,t,e))}}),l.forEach(e=>{a.push(this.Ir.indexManager.addToCollectionParentIndex(s,e))}),a.push(this.Ir.updateMetadata(s,o)),O.waitFor(a)}getFromCache(e,t){return this.Ir.lr(e,t).next(e=>(this.Er.set(t,{size:e.size,readTime:e.document.readTime}),e.document))}getAllFromCache(e,t){return this.Ir.Pr(e,t).next(({documents:r,Tr:e})=>(e.forEach((e,t)=>{this.Er.set(e,{size:t,readTime:r.get(e).readTime})}),r))}}function wT(e){return M_(e,Qv)}function bT(e){return M_(e,zv)}function IT(e){var t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function TT(e,t){var r=t.documentKey.path.toArray();return[e,sI(t.readTime),r.slice(0,r.length-2),0<r.length?r[r.length-1]:""]}function ET(e,t){var r=e.path.toArray(),n=t.path.toArray();let i=0;for(let s=0;s<r.length-2&&s<n.length-2;++s)if(i=R(r[s],n[s]))return i;return(i=R(r.length,n.length))||(i=R(r[r.length-2],n[n.length-2]))||R(r[r.length-1],n[n.length-1])}class CT{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class kT{constructor(e,t,r,n){this.remoteDocumentCache=e,this.mutationQueue=t,this.documentOverlayCache=r,this.indexManager=n}getDocument(t,r){let n=null;return this.documentOverlayCache.getOverlay(t,r).next(e=>(n=e,this.remoteDocumentCache.getEntry(t,r))).next(e=>(null!==n&&Yw(n.mutation,e,K_.empty(),Km.now()),e))}getDocuments(t,e){return this.remoteDocumentCache.getEntries(t,e).next(e=>this.getLocalViewOfDocuments(t,e,V()).next(()=>e))}getLocalViewOfDocuments(e,t,r=V()){let n=Sw();return this.populateOverlays(e,n,t).next(()=>this.computeViews(e,t,n,r).next(e=>{let r=Cw();return e.forEach((e,t)=>{r=r.insert(e,t.overlayedDocument)}),r}))}getOverlayedDocuments(e,t){let r=Sw();return this.populateOverlays(e,r,t).next(()=>this.computeViews(e,t,r,V()))}populateOverlays(e,r,t){let n=[];return t.forEach(e=>{r.has(e)||n.push(e)}),this.documentOverlayCache.getOverlays(e,n).next(e=>{e.forEach((e,t)=>{r.set(e,t)})})}computeViews(e,t,n,i){let s=Tw,a=Sw(),o=Sw();return t.forEach((e,t)=>{var r=n.get(t.key);i.has(t.key)&&(void 0===r||r.mutation instanceof Zw)?s=s.insert(t.key,t):void 0!==r?(a.set(t.key,r.mutation.getFieldMask()),Yw(r.mutation,t,r.mutation.getFieldMask(),Km.now())):a.set(t.key,K_.empty())}),this.recalculateAndSaveOverlays(e,s).next(e=>(e.forEach((e,t)=>a.set(e,t)),t.forEach((e,t)=>{var r;return o.set(e,new CT(t,null!=(r=a.get(e))?r:null))}),o))}recalculateAndSaveOverlays(a,o){let l=Sw(),h=new L((e,t)=>e-t),u=V();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(a,o).next(e=>{for(let n of e)n.keys().forEach(e=>{var t,r=o.get(e);null!==r&&(t=l.get(e)||K_.empty(),t=n.applyToLocalView(r,t),l.set(e,t),r=(h.get(n.batchId)||V()).add(e),h=h.insert(n.batchId,r))})}).next(()=>{for(var i=[],s=h.getReverseIterator();s.hasNext();){let e=s.getNext(),t=e.key,r=e.value,n=Sw();r.forEach(e=>{var t;u.has(e)||(null!==(t=Qw(o.get(e),l.get(e)))&&n.set(e,t),u=u.add(e))}),i.push(this.documentOverlayCache.saveOverlays(a,t,n))}return O.waitFor(i)}).next(()=>l)}recalculateAndSaveOverlaysForDocumentKeys(t,e){return this.remoteDocumentCache.getEntries(t,e).next(e=>this.recalculateAndSaveOverlays(t,e))}getDocumentsMatchingQuery(e,t,r,n){return i=t,x.isDocumentKey(i.path)&&null===i.collectionGroup&&0===i.filters.length?this.getDocumentsMatchingDocumentQuery(e,t.path):cw(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,r,n):this.getDocumentsMatchingCollectionQuery(e,t,r,n);var i}getNextDocuments(s,t,a,o){return this.remoteDocumentCache.getAllFromCollectionGroup(s,t,a,o).next(r=>{var e=0<o-r.size?this.documentOverlayCache.getOverlaysForCollectionGroup(s,t,a.largestBatchId,o-r.size):O.resolve(Sw());let n=Qm,i=r;return e.next(e=>O.forEach(e,(t,e)=>(n<e.largestBatchId&&(n=e.largestBatchId),r.get(t)?O.resolve():this.remoteDocumentCache.getEntry(s,t).next(e=>{i=i.insert(t,e)}))).next(()=>this.populateOverlays(s,e,r)).next(()=>this.computeViews(s,i,e,V())).next(e=>({batchId:n,changes:kw(e)})))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new x(t)).next(e=>{let t=Cw();return t=e.isFoundDocument()?t.insert(e.key,e):t})}getDocumentsMatchingCollectionGroupQuery(n,i,s,a){let o=i.collectionGroup,l=Cw();return this.indexManager.getCollectionParents(n,o).next(e=>O.forEach(e,e=>{t=i,e=e.child(o);var t,r=new ow(e,null,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt);return this.getDocumentsMatchingCollectionQuery(n,r,s,a).next(e=>{e.forEach((e,t)=>{l=l.insert(e,t)})})}).next(()=>l))}getDocumentsMatchingCollectionQuery(t,s,r,n){let a;return this.documentOverlayCache.getOverlaysForCollection(t,s.path,r.largestBatchId).next(e=>(a=e,this.remoteDocumentCache.getDocumentsMatchingQuery(t,s,r,a,n))).next(n=>{a.forEach((e,t)=>{var r=t.getKey();null===n.get(r)&&(n=n.insert(r,xy.newInvalidDocument(r)))});let i=Cw();return n.forEach((e,t)=>{var r=a.get(e);void 0!==r&&Yw(r.mutation,t,K_.empty(),Km.now()),yw(s,t)&&(i=i.insert(e,t))}),i})}}class ST{constructor(e){this.serializer=e,this.dr=new Map,this.Ar=new Map}getBundleMetadata(e,t){return O.resolve(this.dr.get(t))}saveBundleMetadata(e,t){return this.dr.set(t.id,{id:t.id,version:t.version,createTime:Db(t.createTime)}),O.resolve()}getNamedQuery(e,t){return O.resolve(this.Ar.get(t))}saveNamedQuery(e,t){return this.Ar.set(t.name,{name:(t=t).name,query:cI(t.bundledQuery),readTime:Db(t.readTime)}),O.resolve()}}class AT{constructor(){this.overlays=new L(x.comparator),this.Rr=new Map}getOverlay(e,t){return O.resolve(this.overlays.get(t))}getOverlays(e,t){let r=Sw();return O.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&r.set(t,e)})).next(()=>r)}saveOverlays(r,n,e){return e.forEach((e,t)=>{this.Et(r,n,t)}),O.resolve()}removeOverlaysForBatchId(e,t,r){var n=this.Rr.get(r);return void 0!==n&&(n.forEach(e=>this.overlays=this.overlays.remove(e)),this.Rr.delete(r)),O.resolve()}getOverlaysForCollection(e,r,n){let i=Sw(),s=r.length+1,t=new x(r.child("")),a=this.overlays.getIteratorFrom(t);for(;a.hasNext();){let e=a.getNext().value,t=e.getKey();if(!r.isPrefixOf(t.path))break;t.path.length===s&&e.largestBatchId>n&&i.set(e.getKey(),e)}return O.resolve(i)}getOverlaysForCollectionGroup(e,r,n,t){let i=new L((e,t)=>e-t);for(var s=this.overlays.getIterator();s.hasNext();){let t=s.getNext().value;if(t.getKey().getCollectionGroup()===r&&t.largestBatchId>n){let e=i.get(t.largestBatchId);null===e&&(e=Sw(),i=i.insert(t.largestBatchId,e)),e.set(t.getKey(),t)}}let a=Sw(),o=i.getIterator();for(;o.hasNext()&&(o.getNext().value.forEach((e,t)=>a.set(e,t)),!(a.size()>=t)););return O.resolve(a)}Et(e,t,r){var n=this.overlays.get(r.key);if(null!==n){let e=this.Rr.get(n.largestBatchId).delete(r.key);this.Rr.set(n.largestBatchId,e)}this.overlays=this.overlays.insert(r.key,new ob(t,r));let i=this.Rr.get(t);void 0===i&&(i=V(),this.Rr.set(t,i)),this.Rr.set(t,i.add(r.key))}}class NT{constructor(){this.sessionToken=H_.EMPTY_BYTE_STRING}getSessionToken(e){return O.resolve(this.sessionToken)}setSessionToken(e,t){return this.sessionToken=t,O.resolve()}}class RT{constructor(){this.Vr=new M(PT.mr),this.gr=new M(PT.pr)}isEmpty(){return this.Vr.isEmpty()}addReference(e,t){var r=new PT(e,t);this.Vr=this.Vr.add(r),this.gr=this.gr.add(r)}yr(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.wr(new PT(e,t))}Sr(e,t){e.forEach(e=>this.removeReference(e,t))}br(e){let t=new x(new D([])),r=new PT(t,e),n=new PT(t,e+1),i=[];return this.gr.forEachInRange([r,n],e=>{this.wr(e),i.push(e.key)}),i}Dr(){this.Vr.forEach(e=>this.wr(e))}wr(e){this.Vr=this.Vr.delete(e),this.gr=this.gr.delete(e)}vr(e){var t=new x(new D([])),r=new PT(t,e),t=new PT(t,e+1);let n=V();return this.gr.forEachInRange([r,t],e=>{n=n.add(e.key)}),n}containsKey(e){var t=new PT(e,0),t=this.Vr.firstAfterOrEqual(t);return null!==t&&e.isEqual(t.key)}}class PT{constructor(e,t){this.key=e,this.Cr=t}static mr(e,t){return x.comparator(e.key,t.key)||R(e.Cr,t.Cr)}static pr(e,t){return R(e.Cr,t.Cr)||x.comparator(e.key,t.key)}}class DT{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.Fr=1,this.Mr=new M(PT.mr)}checkEmpty(e){return O.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,r,n){var i=this.Fr,s=(this.Fr++,0<this.mutationQueue.length&&this.mutationQueue[this.mutationQueue.length-1],new sb(i,t,r,n));this.mutationQueue.push(s);for(let t of n)this.Mr=this.Mr.add(new PT(t.key,i)),this.indexManager.addToCollectionParentIndex(e,t.key.path.popLast());return O.resolve(s)}lookupMutationBatch(e,t){return O.resolve(this.Or(t))}getNextMutationBatchAfterBatchId(e,t){var r=this.Nr(t+1),r=r<0?0:r;return O.resolve(this.mutationQueue.length>r?this.mutationQueue[r]:null)}getHighestUnacknowledgedBatchId(){return O.resolve(0===this.mutationQueue.length?Tv:this.Fr-1)}getAllMutationBatches(e){return O.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){let r=new PT(t,0),n=new PT(t,Number.POSITIVE_INFINITY),i=[];return this.Mr.forEachInRange([r,n],e=>{var t=this.Or(e.Cr);i.push(t)}),O.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new M(R);return t.forEach(e=>{var t=new PT(e,0),r=new PT(e,Number.POSITIVE_INFINITY);this.Mr.forEachInRange([t,r],e=>{n=n.add(e.Cr)})}),O.resolve(this.Br(n))}getAllMutationBatchesAffectingQuery(e,t){let r=t.path,n=r.length+1,i=r;x.isDocumentKey(i)||(i=i.child(""));var s=new PT(new x(i),0);let a=new M(R);return this.Mr.forEachWhile(e=>{var t=e.key.path;return!!r.isPrefixOf(t)&&(t.length===n&&(a=a.add(e.Cr)),!0)},s),O.resolve(this.Br(a))}Br(e){let r=[];return e.forEach(e=>{var t=this.Or(e);null!==t&&r.push(t)}),r}removeMutationBatch(r,n){S(0===this.Lr(n.batchId,"removed")),this.mutationQueue.shift();let i=this.Mr;return O.forEach(n.mutations,e=>{var t=new PT(e.key,n.batchId);return i=i.delete(t),this.referenceDelegate.markPotentiallyOrphaned(r,e.key)}).next(()=>{this.Mr=i})}qn(e){}containsKey(e,t){var r=new PT(t,0),r=this.Mr.firstAfterOrEqual(r);return O.resolve(t.isEqual(r&&r.key))}performConsistencyCheck(e){return this.mutationQueue.length,O.resolve()}Lr(e,t){return this.Nr(e)}Nr(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}Or(e){var t=this.Nr(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class xT{constructor(e){this.kr=e,this.docs=new L(x.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){var r=t.key,n=this.docs.get(r),n=n?n.size:0,i=this.kr(t);return this.docs=this.docs.insert(r,{document:t.mutableCopy(),size:i}),this.size+=i-n,this.indexManager.addToCollectionParentIndex(e,r.path.popLast())}removeEntry(e){var t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){var r=this.docs.get(t);return O.resolve(r?r.document.mutableCopy():xy.newInvalidDocument(t))}getEntries(e,t){let r=Tw;return t.forEach(e=>{var t=this.docs.get(e);r=r.insert(e,t?t.document.mutableCopy():xy.newInvalidDocument(e))}),O.resolve(r)}getDocumentsMatchingQuery(e,r,n,i){let s=Tw,a=r.path,t=new x(a.child("__id-9223372036854775808__")),o=this.docs.getIteratorFrom(t);for(;o.hasNext();){let{key:e,value:{document:t}}=o.getNext();if(!a.isPrefixOf(e.path))break;e.path.length>a.length+1||iv(rv(t),n)<=0||(i.has(t.key)||yw(r,t))&&(s=s.insert(t.key,t.mutableCopy()))}return O.resolve(s)}getAllFromCollectionGroup(e,t,r,n){k()}qr(e,t){return O.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new OT(this)}getSize(e){return O.resolve(this.size)}}class OT extends mT{constructor(e){super(),this.Ir=e}applyChanges(r){let n=[];return this.changes.forEach((e,t)=>{t.isValidDocument()?n.push(this.Ir.addEntry(r,t)):this.Ir.removeEntry(e)}),O.waitFor(n)}getFromCache(e,t){return this.Ir.getEntry(e,t)}getAllFromCache(e,t){return this.Ir.getEntries(e,t)}}class LT{constructor(e){this.persistence=e,this.Qr=new Iw(e=>tw(e),rw),this.lastRemoteSnapshotVersion=P.min(),this.highestTargetId=0,this.$r=0,this.Ur=new RT,this.targetCount=0,this.Kr=nT.Un()}forEachTarget(e,r){return this.Qr.forEach((e,t)=>r(t)),O.resolve()}getLastRemoteSnapshotVersion(e){return O.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return O.resolve(this.$r)}allocateTargetId(e){return this.highestTargetId=this.Kr.next(),O.resolve(this.highestTargetId)}setTargetsMetadata(e,t,r){return r&&(this.lastRemoteSnapshotVersion=r),t>this.$r&&(this.$r=t),O.resolve()}zn(e){this.Qr.set(e.target,e);var t=e.targetId;t>this.highestTargetId&&(this.Kr=new nT(t),this.highestTargetId=t),e.sequenceNumber>this.$r&&(this.$r=e.sequenceNumber)}addTargetData(e,t){return this.zn(t),this.targetCount+=1,O.resolve()}updateTargetData(e,t){return this.zn(t),O.resolve()}removeTargetData(e,t){return this.Qr.delete(t.target),this.Ur.br(t.targetId),--this.targetCount,O.resolve()}removeTargets(r,n,i){let s=0,a=[];return this.Qr.forEach((e,t)=>{t.sequenceNumber<=n&&null===i.get(t.targetId)&&(this.Qr.delete(e),a.push(this.removeMatchingKeysForTargetId(r,t.targetId)),s++)}),O.waitFor(a).next(()=>s)}getTargetCount(e){return O.resolve(this.targetCount)}getTargetData(e,t){var r=this.Qr.get(t)||null;return O.resolve(r)}addMatchingKeys(e,t,r){return this.Ur.yr(t,r),O.resolve()}removeMatchingKeys(t,e,r){this.Ur.Sr(e,r);let n=this.persistence.referenceDelegate,i=[];return n&&e.forEach(e=>{i.push(n.markPotentiallyOrphaned(t,e))}),O.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.Ur.br(t),O.resolve()}getMatchingKeysForTargetId(e,t){var r=this.Ur.vr(t);return O.resolve(r)}containsKey(e,t){return O.resolve(this.Ur.containsKey(t))}}class MT{constructor(e,t){this.Wr={},this.overlays={},this.Gr=new Iv(0),this.zr=!1,this.zr=!0,this.jr=new NT,this.referenceDelegate=e(this),this.Hr=new LT(this),this.indexManager=new UI,this.remoteDocumentCache=(e=e=>this.referenceDelegate.Jr(e),new xT(e)),this.serializer=new nI(t),this.Yr=new ST(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.zr=!1,Promise.resolve()}get started(){return this.zr}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new AT,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let r=this.Wr[e.toKey()];return r||(r=new DT(t,this.referenceDelegate),this.Wr[e.toKey()]=r),r}getGlobalsCache(){return this.jr}getTargetCache(){return this.Hr}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.Yr}runTransaction(e,t,r){C("MemoryPersistence","Starting transaction:",e);let n=new FT(this.Gr.next());return this.referenceDelegate.Zr(),r(n).next(e=>this.referenceDelegate.Xr(n).next(()=>e)).toPromise().then(e=>(n.raiseOnCommittedEvent(),e))}ei(t,r){return O.or(Object.values(this.Wr).map(e=>()=>e.containsKey(t,r)))}}class FT extends av{constructor(e){super(),this.currentSequenceNumber=e}}class UT{constructor(e){this.persistence=e,this.ti=new RT,this.ni=null}static ri(e){return new UT(e)}get ii(){if(this.ni)return this.ni;throw k()}addReference(e,t,r){return this.ti.addReference(r,t),this.ii.delete(r.toString()),O.resolve()}removeReference(e,t,r){return this.ti.removeReference(r,t),this.ii.add(r.toString()),O.resolve()}markPotentiallyOrphaned(e,t){return this.ii.add(t.toString()),O.resolve()}removeTarget(e,t){this.ti.br(t.targetId).forEach(e=>this.ii.add(e.toString()));let r=this.persistence.getTargetCache();return r.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.ii.add(e.toString()))}).next(()=>r.removeTargetData(e,t))}Zr(){this.ni=new Set}Xr(r){let n=this.persistence.getRemoteDocumentCache().newChangeBuffer();return O.forEach(this.ii,e=>{let t=x.fromPath(e);return this.si(r,t).next(e=>{e||n.removeEntry(t,P.min())})}).next(()=>(this.ni=null,n.apply(r)))}updateLimboDocument(e,t){return this.si(e,t).next(e=>{e?this.ii.delete(t.toString()):this.ii.add(t.toString())})}Jr(e){return 0}si(e,t){return O.or([()=>O.resolve(this.ti.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.ei(e,t)])}}class VT{constructor(e,t){this.persistence=e,this.oi=new Iw(e=>Av(e.path),(e,t)=>e.isEqual(t)),this.garbageCollector=pT(this,t)}static ri(e,t){return new VT(e,t)}Zr(){}Xr(e){return O.resolve()}forEachTarget(e,t){return this.persistence.getTargetCache().forEachTarget(e,t)}nr(e){let r=this.sr(e);return this.persistence.getTargetCache().getTargetCount(e).next(t=>r.next(e=>t+e))}sr(e){let t=0;return this.rr(e,e=>{t++}).next(()=>t)}rr(r,n){return O.forEach(this.oi,(e,t)=>this.ar(r,e,t).next(e=>e?O.resolve():n(t)))}removeTargets(e,t,r){return this.persistence.getTargetCache().removeTargets(e,t,r)}removeOrphanedDocuments(e,r){let n=0,t=this.persistence.getRemoteDocumentCache(),i=t.newChangeBuffer();return t.qr(e,t=>this.ar(e,t,r).next(e=>{e||(n++,i.removeEntry(t,P.min()))})).next(()=>i.apply(e)).next(()=>n)}markPotentiallyOrphaned(e,t){return this.oi.set(t,e.currentSequenceNumber),O.resolve()}removeTarget(e,t){var r=t.withSequenceNumber(e.currentSequenceNumber);return this.persistence.getTargetCache().updateTargetData(e,r)}addReference(e,t,r){return this.oi.set(r,e.currentSequenceNumber),O.resolve()}removeReference(e,t,r){return this.oi.set(r,e.currentSequenceNumber),O.resolve()}updateLimboDocument(e,t){return this.oi.set(t,e.currentSequenceNumber),O.resolve()}Jr(e){let t=e.key.toString().length;return e.isFoundDocument()&&(t+=function n(e){switch(py(e)){case 0:case 1:return 4;case 2:return 8;case 3:case 8:return 16;case 4:var t=ry(e);return t?16+n(t):16;case 5:return 2*e.stringValue.length;case 6:return Y_(e.bytesValue).approximateByteSize();case 7:return e.referenceValue.length;case 9:return(e.arrayValue.values||[]).reduce((e,t)=>e+n(t),0);case 10:case 11:{var i=e.mapValue;let r=0;return U_(i.fields,(e,t)=>{r+=e.length+n(t)}),r}default:throw k()}}(e.data.value)),t}ar(e,t,r){return O.or([()=>this.persistence.ei(e,t),()=>this.persistence.getTargetCache().containsKey(e,t),()=>{var e=this.oi.get(t);return O.resolve(void 0!==e&&r<e)}])}getCacheSize(e){return this.persistence.getRemoteDocumentCache().getSize(e)}}class qT{constructor(e){this.serializer=e}B(t,e,r,n){let s=new hv("createOrUpgrade",e);var i;r<1&&1<=n&&(t.createObjectStore(Dv),(i=t).createObjectStore(Ov,{keyPath:"userId"}),i.createObjectStore(Lv,{keyPath:Mv,autoIncrement:!0}).createIndex(Fv,Uv,{unique:!0}),i.createObjectStore(Bv),jT(t),t.createObjectStore(Pv));let a=O.resolve();return r<3&&3<=n&&(0!==r&&((i=t).deleteObjectStore(e_),i.deleteObjectStore(Jv),i.deleteObjectStore(s_),jT(t)),a=a.next(()=>{return e=s,t=e.store(s_),r={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:P.min().toTimestamp(),targetCount:0},t.put(i_,r);var e,t,r})),r<4&&4<=n&&(a=(a=0!==r?a.next(()=>{return n=t,(i=s).store(Lv).G().next(e=>{n.deleteObjectStore(Lv),n.createObjectStore(Lv,{keyPath:Mv,autoIncrement:!0}).createIndex(Fv,Uv,{unique:!0});let t=i.store(Lv),r=e.map(e=>t.put(e));return O.waitFor(r)});var n,i}):a).next(()=>{t.createObjectStore(l_,{keyPath:"clientId"})})),r<5&&5<=n&&(a=a.next(()=>this._i(s))),r<6&&6<=n&&(a=a.next(()=>(t.createObjectStore(Qv),this.ai(s)))),r<7&&7<=n&&(a=a.next(()=>this.ui(s))),r<8&&8<=n&&(a=a.next(()=>this.ci(t,s))),r<9&&9<=n&&(a=a.next(()=>{var e;(e=t).objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges")})),r<10&&10<=n&&(a=a.next(()=>this.li(s))),r<11&&11<=n&&(a=a.next(()=>{t.createObjectStore(h_,{keyPath:"bundleId"}),t.createObjectStore(u_,{keyPath:"name"})})),r<12&&12<=n&&(a=a.next(()=>{var e;(e=t.createObjectStore(b_,{keyPath:I_})).createIndex(T_,E_,{unique:!1}),e.createIndex(C_,k_,{unique:!1})})),r<13&&13<=n&&(a=a.next(()=>{var e;(e=t.createObjectStore(zv,{keyPath:Kv})).createIndex(Wv,Hv),e.createIndex(Gv,$v)}).next(()=>this.hi(t,s)).next(()=>t.deleteObjectStore(Pv))),r<14&&14<=n&&(a=a.next(()=>this.Pi(t,s))),r<15&&15<=n&&(a=a.next(()=>{var e;(e=t).createObjectStore(c_,{keyPath:"indexId",autoIncrement:!0}).createIndex(d_,"collectionGroup",{unique:!1}),e.createObjectStore(p_,{keyPath:f_}).createIndex(g_,m_,{unique:!1}),e.createObjectStore(v_,{keyPath:__}).createIndex(y_,w_,{unique:!1})})),r<16&&16<=n&&(a=a.next(()=>{e.objectStore(p_).clear()}).next(()=>{e.objectStore(v_).clear()})),a=r<17&&17<=n?a.next(()=>{t.createObjectStore(S_,{keyPath:"name"})}):a}ai(t){let r=0;return t.store(Pv).Z((e,t)=>{r+=JI(t)}).next(()=>{var e={byteSize:r};return t.store(Qv).put(Yv,e)})}_i(n){let e=n.store(Ov),t=n.store(Lv);return e.G().next(e=>O.forEach(e,r=>{var e=IDBKeyRange.bound([r.userId,Tv],[r.userId,r.lastAcknowledgedBatchId]);return t.G(Fv,e).next(e=>O.forEach(e,e=>{S(e.userId===r.userId);var t=lI(this.serializer,e);return YI(n,r.userId,t).next(()=>{})}))}))}ui(e){let a=e.store(e_),t=e.store(Pv);return e.store(s_).get(i_).next(i=>{let s=[];return t.Z((e,t)=>{let r=new D(e),n=[0,Av(r)];s.push(a.get(n).next(e=>e?O.resolve():(e=r,a.put({targetId:0,path:Av(e),sequenceNumber:i.highestListenSequenceNumber}))))}).next(()=>O.waitFor(s))})}ci(e,t){e.createObjectStore(a_,{keyPath:o_});let n=t.store(a_),i=new VI,s=r=>{if(i.add(r)){let e=r.lastSegment(),t=r.popLast();return n.put({collectionId:e,parent:Av(t)})}};return t.store(Pv).Z({Y:!0},(e,t)=>{var r=new D(e);return s(r.popLast())}).next(()=>t.store(Bv).Z({Y:!0},([,e],t)=>{var r=Rv(e);return s(r.popLast())}))}li(e){let n=e.store(Jv);return n.Z((e,t)=>{var r=hI(t),r=uI(this.serializer,r);return n.put(r)})}hi(e,s){let t=s.store(Pv),a=[];return t.Z((e,t)=>{var r,n=s.store(zv),i=((r=t).document?new x(D.fromString(r.document.name).popFirst(5)):r.noDocument?x.fromSegments(r.noDocument.path):r.unknownDocument?x.fromSegments(r.unknownDocument.path):k()).path.toArray(),i={prefixPath:i.slice(0,i.length-2),collectionGroup:i[i.length-2],documentId:i[i.length-1],readTime:t.readTime||[0,0],unknownDocument:t.unknownDocument,noDocument:t.noDocument,document:t.document,hasCommittedMutations:!!t.hasCommittedMutations};a.push(n.put(i))}).next(()=>O.waitFor(a))}Pi(e,s){let t=s.store(Lv),a=_T(this.serializer),o=new MT(UT.ri,this.serializer.Tt);return t.G().next(e=>{let n=new Map;return e.forEach(e=>{let t,r=null!=(t=n.get(e.userId))?t:V();lI(this.serializer,e).keys().forEach(e=>r=r.add(e)),n.set(e.userId,r)}),O.forEach(n,(e,t)=>{var r=new Im(t),n=_I.It(this.serializer,r),i=o.getIndexManager(r),r=XI.It(r,this.serializer,i,o.referenceDelegate);return new kT(a,r,n,i).recalculateAndSaveOverlaysForDocumentKeys(new L_(s,Iv.ae),e).next()})})}}function jT(e){e.createObjectStore(e_,{keyPath:t_}).createIndex(r_,n_,{unique:!0}),e.createObjectStore(Jv,{keyPath:"targetId"}).createIndex(Xv,Zv,{unique:!0}),e.createObjectStore(s_)}let BT="IndexedDbPersistence",zT="Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.";class KT{constructor(e,t,r,n,i,s,a,o,l,h,u=17){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=r,this.Ti=i,this.window=s,this.document=a,this.Ii=l,this.Ei=h,this.di=u,this.Gr=null,this.zr=!1,this.isPrimary=!1,this.networkEnabled=!0,this.Ai=null,this.inForeground=!1,this.Ri=null,this.Vi=null,this.mi=Number.NEGATIVE_INFINITY,this.fi=e=>Promise.resolve(),!KT.D())throw new N(A.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new fT(this,n),this.gi=t+"main",this.serializer=new nI(o),this.pi=new uv(this.gi,this.di,new qT(this.serializer)),this.jr=new wI,this.Hr=new iT(this.referenceDelegate,this.serializer),this.remoteDocumentCache=_T(this.serializer),this.Yr=new gI,this.window&&this.window.localStorage?this.yi=this.window.localStorage:(this.yi=null,!1===h&&km(BT,"LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."))}start(){return this.wi().then(()=>{if(this.isPrimary||this.allowTabSynchronization)return this.Si(),this.bi(),this.Di(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.Hr.getHighestSequenceNumber(e));throw new N(A.FAILED_PRECONDITION,zT)}).then(e=>{this.Gr=new Iv(e,this.Ii)}).then(()=>{this.zr=!0}).catch(e=>(this.pi&&this.pi.close(),Promise.reject(e)))}Ci(t){return this.fi=async e=>{if(this.started)return t(e)},t(this.isPrimary)}setDatabaseDeletedListener(t){this.pi.k(async e=>{null===e.newVersion&&await t()})}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.Ti.enqueueAndForget(async()=>{this.started&&await this.wi()}))}wi(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",t=>HT(t).put({clientId:this.clientId,updateTimeMs:Date.now(),networkEnabled:this.networkEnabled,inForeground:this.inForeground}).next(()=>{if(this.isPrimary)return this.Fi(t).next(e=>{e||(this.isPrimary=!1,this.Ti.enqueueRetryable(()=>this.fi(!1)))})}).next(()=>this.Mi(t)).next(e=>this.isPrimary&&!e?this.xi(t).next(()=>!1):!!e&&this.Oi(t).next(()=>!0))).catch(e=>{if(fv(e))return C(BT,"Failed to extend owner lease: ",e),this.isPrimary;if(this.allowTabSynchronization)return C(BT,"Releasing owner lease after error during lease refresh",e),!1;throw e}).then(e=>{this.isPrimary!==e&&this.Ti.enqueueRetryable(()=>this.fi(e)),this.isPrimary=e})}Fi(e){return WT(e).get(xv).next(e=>O.resolve(this.Ni(e)))}Bi(e){return HT(e).delete(this.clientId)}async Li(){if(this.isPrimary&&!this.ki(this.mi,18e5)){this.mi=Date.now();var e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",e=>{let n=M_(e,l_);return n.G().next(e=>{let t=this.qi(e,18e5),r=e.filter(e=>-1===t.indexOf(e));return O.forEach(r,e=>n.delete(e.clientId)).next(()=>r)})}).catch(()=>[]);if(this.yi)for(var t of e)this.yi.removeItem(this.Qi(t.clientId))}}Di(){this.Vi=this.Ti.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.wi().then(()=>this.Li()).then(()=>this.Di()))}Ni(e){return!!e&&e.ownerId===this.clientId}Mi(t){return this.Ei?O.resolve(!0):WT(t).get(xv).next(e=>{if(null!==e&&this.ki(e.leaseTimestampMs,5e3)&&!this.$i(e.ownerId)){if(this.Ni(e)&&this.networkEnabled)return!0;if(!this.Ni(e)){if(e.allowTabSynchronization)return!1;throw new N(A.FAILED_PRECONDITION,zT)}}return!(!this.networkEnabled||!this.inForeground)||HT(t).G().next(e=>void 0===this.qi(e,5e3).find(e=>{if(this.clientId!==e.clientId){var t=!this.networkEnabled&&e.networkEnabled,r=!this.inForeground&&e.inForeground,n=this.networkEnabled===e.networkEnabled;if(t||r&&n)return!0}return!1}))}).next(e=>(this.isPrimary!==e&&C(BT,`Client ${e?"is":"is not"} eligible for a primary lease.`),e))}async shutdown(){this.zr=!1,this.Ui(),this.Vi&&(this.Vi.cancel(),this.Vi=null),this.Ki(),this.Wi(),await this.pi.runTransaction("shutdown","readwrite",[Dv,l_],e=>{let t=new L_(e,Iv.ae);return this.xi(t).next(()=>this.Bi(t))}),this.pi.close(),this.Gi()}qi(e,t){return e.filter(e=>this.ki(e.updateTimeMs,t)&&!this.$i(e.clientId))}zi(){return this.runTransaction("getActiveClients","readonly",e=>HT(e).G().next(e=>this.qi(e,18e5).map(e=>e.clientId)))}get started(){return this.zr}getGlobalsCache(){return this.jr}getMutationQueue(e,t){return XI.It(e,this.serializer,t,this.referenceDelegate)}getTargetCache(){return this.Hr}getRemoteDocumentCache(){return this.remoteDocumentCache}getIndexManager(e){return new BI(e,this.serializer.Tt.databaseId)}getDocumentOverlayCache(e){return _I.It(this.serializer,e)}getBundleCache(){return this.Yr}runTransaction(t,r,n){C(BT,"Starting transaction:",t);var e,i="readonly"===r?"readonly":"readwrite",s=17===(e=this.di)?O_:16===e?x_:15===e?D_:14===e?P_:13===e?R_:12===e?N_:11===e?A_:void k();let a;return this.pi.runTransaction(t,i,s,e=>(a=new L_(e,this.Gr?this.Gr.next():Iv.ae),"readwrite-primary"===r?this.Fi(a).next(e=>!!e||this.Mi(a)).next(e=>{if(e)return n(a);throw km(`Failed to obtain primary lease for action '${t}'.`),this.isPrimary=!1,this.Ti.enqueueRetryable(()=>this.fi(!1)),new N(A.FAILED_PRECONDITION,sv)}).next(e=>this.Oi(a).next(()=>e)):this.ji(a).next(()=>n(a)))).then(e=>(a.raiseOnCommittedEvent(),e))}ji(e){return WT(e).get(xv).next(e=>{if(null!==e&&this.ki(e.leaseTimestampMs,5e3)&&!this.$i(e.ownerId)&&!this.Ni(e)&&!(this.Ei||this.allowTabSynchronization&&e.allowTabSynchronization))throw new N(A.FAILED_PRECONDITION,zT)})}Oi(e){var t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return WT(e).put(xv,t)}static D(){return uv.D()}xi(e){let t=WT(e);return t.get(xv).next(e=>this.Ni(e)?(C(BT,"Releasing primary lease."),t.delete(xv)):O.resolve())}ki(e,t){var r=Date.now();return!(e<r-t||r<e&&(km(`Detected an update time that is in the future: ${e} > `+r),1))}Si(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.Ri=()=>{this.Ti.enqueueAndForget(()=>(this.inForeground="visible"===this.document.visibilityState,this.wi()))},this.document.addEventListener("visibilitychange",this.Ri),this.inForeground="visible"===this.document.visibilityState)}Ki(){this.Ri&&(this.document.removeEventListener("visibilitychange",this.Ri),this.Ri=null)}bi(){var e;"function"==typeof(null==(e=this.window)?void 0:e.addEventListener)&&(this.Ai=()=>{this.Ui();var e=/(?:Version|Mobile)\/1[456]/;le()&&(navigator.appVersion.match(e)||navigator.userAgent.match(e))&&this.Ti.enterRestrictedMode(!0),this.Ti.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.Ai))}Wi(){this.Ai&&(this.window.removeEventListener("pagehide",this.Ai),this.Ai=null)}$i(e){var t;try{var r=null!==(null==(t=this.yi)?void 0:t.getItem(this.Qi(e)));return C(BT,`Client '${e}' ${r?"is":"is not"} zombied in LocalStorage`),r}catch(e){return km(BT,"Failed to get zombied client id.",e),!1}}Ui(){if(this.yi)try{this.yi.setItem(this.Qi(this.clientId),String(Date.now()))}catch(e){km("Failed to set zombie client id.",e)}}Gi(){if(this.yi)try{this.yi.removeItem(this.Qi(this.clientId))}catch(e){}}Qi(e){return`firestore_zombie_${this.persistenceKey}_`+e}}function WT(e){return M_(e,Dv)}function HT(e){return M_(e,l_)}function GT(e,t){let r=e.projectId;return e.isDefaultDatabase||(r+="."+e.database),"firestore/"+t+"/"+r+"/"}class $T{constructor(e,t,r,n){this.targetId=e,this.fromCache=t,this.Hi=r,this.Ji=n}static Yi(e,t){let r=V(),n=V();for(let e of t.docChanges)switch(e.type){case 0:r=r.add(e.doc.key);break;case 1:n=n.add(e.doc.key)}return new $T(e,t.fromCache,r,n)}}class QT{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}}class YT{constructor(){this.Zi=!1,this.Xi=!1,this.es=100,this.ts=le()?8:0<cv(ee())?6:4}initialize(e,t){this.ns=e,this.indexManager=t,this.Zi=!0}getDocumentsMatchingQuery(r,n,e,t){let i={result:null};return this.rs(r,n).next(e=>{i.result=e}).next(()=>{if(!i.result)return this.ss(r,n,t,e).next(e=>{i.result=e})}).next(()=>{if(!i.result){let t=new QT;return this._s(r,n,t).next(e=>{if(i.result=e,this.Xi)return this.us(r,n,t,e.size)})}}).next(()=>i.result)}us(e,t,r,n){return r.documentReadCount<this.es?(Cm()<=c.DEBUG&&C("QueryEngine","SDK will not create cache indexes for query:",_w(t),"since it only creates cache indexes for collection contains","more than or equal to",this.es,"documents"),O.resolve()):(Cm()<=c.DEBUG&&C("QueryEngine","Query:",_w(t),"scans",r.documentReadCount,"local documents and returns",n,"documents as results."),r.documentReadCount>this.ts*n?(Cm()<=c.DEBUG&&C("QueryEngine","The SDK decides to create cache indexes for query:",_w(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,pw(t))):O.resolve())}rs(i,s){if(uw(s))return O.resolve(null);let t=pw(s);return this.indexManager.getIndexType(i,t).next(e=>0===e?null:(null!==s.limit&&1===e&&(s=gw(s,null,"F"),t=pw(s)),this.indexManager.getDocumentsMatchingTarget(i,t).next(e=>{let n=V(...e);return this.ns.getDocuments(i,n).next(r=>this.indexManager.getMinOffset(i,t).next(e=>{var t=this.cs(s,r);return this.ls(s,t,n,e.readTime)?this.rs(i,gw(s,null,"F")):this.hs(i,t,s,e)}))})))}ss(r,n,i,s){return uw(n)||s.isEqual(P.min())?O.resolve(null):this.ns.getDocuments(r,i).next(e=>{var t=this.cs(n,e);return this.ls(n,t,i,s)?O.resolve(null):(Cm()<=c.DEBUG&&C("QueryEngine","Re-using previous result from %s to execute query: %s",s.toString(),_w(n)),this.hs(r,t,n,tv(s,Qm)).next(e=>e))})}cs(r,e){let n=new M(bw(r));return e.forEach((e,t)=>{yw(r,t)&&(n=n.add(t))}),n}ls(e,t,r,n){var i;return null!==e.limit&&(r.size!==t.size||!!(i="F"===e.limitType?t.last():t.first())&&(i.hasPendingWrites||0<i.version.compareTo(n)))}_s(e,t,r){return Cm()<=c.DEBUG&&C("QueryEngine","Using full collection scan to execute query:",_w(t)),this.ns.getDocumentsMatchingQuery(e,t,nv.min(),r)}hs(e,r,t,n){return this.ns.getDocumentsMatchingQuery(e,t,n).next(t=>(r.forEach(e=>{t=t.insert(e.key,e)}),t))}}let JT="LocalStore",XT=3e8;class ZT{constructor(e,t,r,n){this.persistence=e,this.Ps=t,this.serializer=n,this.Ts=new L(R),this.Is=new Iw(e=>tw(e),rw),this.Es=new Map,this.ds=e.getRemoteDocumentCache(),this.Hr=e.getTargetCache(),this.Yr=e.getBundleCache(),this.As(r)}As(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new kT(this.ds,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.ds.setIndexManager(this.indexManager),this.Ps.initialize(this.localDocuments,this.indexManager)}collectGarbage(t){return this.persistence.runTransaction("Collect garbage","readwrite-primary",e=>t.collect(e,this.Ts))}}function eE(e,t,r,n){return new ZT(e,t,r,n)}async function tE(e,t){let o=e;return o.persistence.runTransaction("Handle user change","readonly",s=>{let a;return o.mutationQueue.getAllMutationBatches(s).next(e=>(a=e,o.As(t),o.mutationQueue.getAllMutationBatches(s))).next(e=>{let t=[],r=[],n=V();for(let i of a){t.push(i.batchId);for(let e of i.mutations)n=n.add(e.key)}for(let i of e){r.push(i.batchId);for(let e of i.mutations)n=n.add(e.key)}return o.localDocuments.getDocuments(s,n).next(e=>({Rs:e,removedBatchIds:t,addedBatchIds:r}))})})}function rE(e,n){let i=e;return i.persistence.runTransaction("Acknowledge batch","readwrite-primary",e=>{let t=n.batch.keys(),r=i.ds.newChangeBuffer({trackRemovals:!0});return((e,t,n,i)=>{let s=n.batch,r=s.keys(),a=O.resolve();return r.forEach(r=>{a=a.next(()=>i.getEntry(t,r)).next(e=>{var t=n.docVersions.get(r);S(null!==t),e.version.compareTo(t)<0&&(s.applyToRemoteDocument(e,n),e.isValidDocument())&&(e.setReadTime(n.commitVersion),i.addEntry(e))})}),a.next(()=>e.mutationQueue.removeMutationBatch(t,s))})(i,e,n,r).next(()=>r.apply(e)).next(()=>i.mutationQueue.performConsistencyCheck(e)).next(()=>i.documentOverlayCache.removeOverlaysForBatchId(e,t,n.batch.batchId)).next(()=>i.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,(e=>{let t=V();for(let r=0;r<e.mutationResults.length;++r)0<e.mutationResults[r].transformResults.length&&(t=t.add(e.batch.mutations[r].key));return t})(n))).next(()=>i.localDocuments.getDocuments(e,t))})}function nE(e){let t=e;return t.persistence.runTransaction("Get last remote snapshot version","readonly",e=>t.Hr.getLastRemoteSnapshotVersion(e))}function iE(e,h){let u=e,c=h.snapshotVersion,d=u.Ts;return u.persistence.runTransaction("Apply remote event","readwrite-primary",o=>{let e=u.ds.newChangeBuffer({trackRemovals:!0}),l=(d=u.Ts,[]),t=(h.targetChanges.forEach((t,r)=>{var n,i,s,a=d.get(r);if(a){l.push(u.Hr.removeMatchingKeys(o,t.removedDocuments,r).next(()=>u.Hr.addMatchingKeys(o,t.addedDocuments,r)));let e=a.withSequenceNumber(o.currentSequenceNumber);null!==h.targetMismatches.get(r)?e=e.withResumeToken(H_.EMPTY_BYTE_STRING,P.min()).withLastLimboFreeSnapshotVersion(P.min()):0<t.resumeToken.approximateByteSize()&&(e=e.withResumeToken(t.resumeToken,c)),d=d.insert(r,e),n=a,i=e,s=t,(0===n.resumeToken.approximateByteSize()||i.snapshotVersion.toMicroseconds()-n.snapshotVersion.toMicroseconds()>=XT||0<s.addedDocuments.size+s.modifiedDocuments.size+s.removedDocuments.size)&&l.push(u.Hr.updateTargetData(o,e))}}),Tw),r=V();if(h.documentUpdates.forEach(e=>{h.resolvedLimboDocuments.has(e)&&l.push(u.persistence.referenceDelegate.updateLimboDocument(o,e))}),l.push(sE(o,e,h.documentUpdates).next(e=>{t=e.Vs,r=e.fs})),!c.isEqual(P.min())){let e=u.Hr.getLastRemoteSnapshotVersion(o).next(e=>u.Hr.setTargetsMetadata(o,o.currentSequenceNumber,c));l.push(e)}return O.waitFor(l).next(()=>e.apply(o)).next(()=>u.localDocuments.getLocalViewOfDocuments(o,t,r)).next(()=>t)}).then(e=>(u.Ts=d,e))}function sE(e,s,t){let r=V(),a=V();return t.forEach(e=>r=r.add(e)),s.getEntries(e,r).next(n=>{let i=Tw;return t.forEach((e,t)=>{var r=n.get(e);t.isFoundDocument()!==r.isFoundDocument()&&(a=a.add(e)),t.isNoDocument()&&t.version.isEqual(P.min())?(s.removeEntry(e,t.readTime),i=i.insert(e,t)):!r.isValidDocument()||0<t.version.compareTo(r.version)||0===t.version.compareTo(r.version)&&r.hasPendingWrites?(s.addEntry(t),i=i.insert(e,t)):C(JT,"Ignoring outdated watch update for ",e,". Current version:",r.version," Watch version:",t.version)}),{Vs:i,fs:a}})}function aE(e,n){let i=e;return i.persistence.runTransaction("Allocate target","readwrite",t=>{let r;return i.Hr.getTargetData(t,n).next(e=>e?(r=e,O.resolve(r)):i.Hr.allocateTargetId(t).next(e=>(r=new rI(n,e,"TargetPurposeListen",t.currentSequenceNumber),i.Hr.addTargetData(t,r).next(()=>r))))}).then(e=>{var t=i.Ts.get(e.targetId);return(null===t||0<e.snapshotVersion.compareTo(t.snapshotVersion))&&(i.Ts=i.Ts.insert(e.targetId,e),i.Is.set(n,e.targetId)),e})}async function oE(e,t,r){let n=e,i=n.Ts.get(t),s=r?"readwrite":"readwrite-primary";try{r||await n.persistence.runTransaction("Release target",s,e=>n.persistence.referenceDelegate.removeTarget(e,i))}catch(e){if(!fv(e))throw e;C(JT,`Failed to update sequence numbers for target ${t}: `+e)}n.Ts=n.Ts.remove(t),n.Is.delete(i.target)}function lE(e,a,o){let l=e,h=P.min(),u=V();return l.persistence.runTransaction("Execute query","readwrite",t=>{return e=l,r=t,n=pw(a),(void 0!==(s=(i=e).Is.get(n))?O.resolve(i.Ts.get(s)):i.Hr.getTargetData(r,n)).next(e=>{if(e)return h=e.lastLimboFreeSnapshotVersion,l.Hr.getMatchingKeysForTargetId(t,e.targetId).next(e=>{u=e})}).next(()=>l.Ps.getDocumentsMatchingQuery(t,a,o?h:P.min(),o?u:V())).next(e=>(cE(l,ww(a),e),{documents:e,gs:u}));var e,r,n,i,s})}function hE(e,t){let r=e,n=r.Hr,i=r.Ts.get(t);return i?Promise.resolve(i.target):r.persistence.runTransaction("Get target data","readonly",e=>n.lt(e,t).next(e=>e?e.target:null))}function uE(e,t){let r=e,n=r.Es.get(t)||P.min();return r.persistence.runTransaction("Get new document changes","readonly",e=>r.ds.getAllFromCollectionGroup(e,t,tv(n,Qm),Number.MAX_SAFE_INTEGER)).then(e=>(cE(r,t,e),e))}function cE(e,t,r){let n=e.Es.get(t)||P.min();r.forEach((e,t)=>{0<t.readTime.compareTo(n)&&(n=t.readTime)}),e.Es.set(t,n)}let dE="firestore_clients";function pE(e,t){return dE+`_${e}_`+t}let fE="firestore_mutations";function gE(e,t,r){let n=fE+`_${e}_`+r;return t.isAuthenticated()&&(n+="_"+t.uid),n}let mE="firestore_targets";function vE(e,t){return mE+`_${e}_`+t}let _E="SharedClientState";class yE{constructor(e,t,r,n){this.user=e,this.batchId=t,this.state=r,this.error=n}static Ss(e,t,r){var n=JSON.parse(r);let i,s="object"==typeof n&&-1!==["pending","acknowledged","rejected"].indexOf(n.state)&&(void 0===n.error||"object"==typeof n.error);return s&&n.error&&(s="string"==typeof n.error.message&&"string"==typeof n.error.code)&&(i=new N(n.error.code,n.error.message)),s?new yE(e,t,n.state,i):(km(_E,`Failed to parse mutation state for ID '${t}': `+r),null)}bs(){var e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class wE{constructor(e,t,r){this.targetId=e,this.state=t,this.error=r}static Ss(e,t){var r=JSON.parse(t);let n,i="object"==typeof r&&-1!==["not-current","current","rejected"].indexOf(r.state)&&(void 0===r.error||"object"==typeof r.error);return i&&r.error&&(i="string"==typeof r.error.message&&"string"==typeof r.error.code)&&(n=new N(r.error.code,r.error.message)),i?new wE(e,r.state,n):(km(_E,`Failed to parse target state for ID '${e}': `+t),null)}bs(){var e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class bE{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static Ss(e,t){var r=JSON.parse(t);let n="object"==typeof r&&r.activeTargetIds instanceof Array,i=Rw;for(let s=0;n&&s<r.activeTargetIds.length;++s)n=kv(r.activeTargetIds[s]),i=i.add(r.activeTargetIds[s]);return n?new bE(e,i):(km(_E,`Failed to parse client data for instance '${e}': `+t),null)}}class IE{constructor(e,t){this.clientId=e,this.onlineState=t}static Ss(e){var t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new IE(t.clientId,t.onlineState):(km(_E,"Failed to parse online state: "+e),null)}}class TE{constructor(){this.activeTargetIds=Rw}Ds(e){this.activeTargetIds=this.activeTargetIds.add(e)}vs(e){this.activeTargetIds=this.activeTargetIds.delete(e)}bs(){var e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class EE{constructor(e,t,r,n,i){this.window=e,this.Ti=t,this.persistenceKey=r,this.Cs=n,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.Fs=this.Ms.bind(this),this.xs=new L(R),this.started=!1,this.Os=[];var s=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=i,this.Ns=pE(this.persistenceKey,this.Cs),this.Bs="firestore_sequence_number_"+this.persistenceKey,this.xs=this.xs.insert(this.Cs,new TE),this.Ls=new RegExp(`^${dE}_${s}_([^_]*)$`),this.ks=new RegExp(`^${fE}_${s}_(\\d+)(?:_(.*))?$`),this.qs=new RegExp(`^${mE}_${s}_(\\d+)$`),this.Qs="firestore_online_state_"+this.persistenceKey,this.$s="firestore_bundle_loaded_v2_"+this.persistenceKey,this.window.addEventListener("storage",this.Fs)}static D(e){return!(!e||!e.localStorage)}async start(){let e=await this.syncEngine.zi();for(let r of e)if(r!==this.Cs){let e=this.getItem(pE(this.persistenceKey,r));var t;e&&(t=bE.Ss(r,e))&&(this.xs=this.xs.insert(t.clientId,t))}this.Us();let r=this.storage.getItem(this.Qs);if(r){let e=this.Ks(r);e&&this.Ws(e)}for(let e of this.Os)this.Ms(e);this.Os=[],this.window.addEventListener("pagehide",()=>this.shutdown()),this.started=!0}writeSequenceNumber(e){this.setItem(this.Bs,JSON.stringify(e))}getAllActiveQueryTargets(){return this.Gs(this.xs)}isActiveQueryTarget(r){let n=!1;return this.xs.forEach((e,t)=>{t.activeTargetIds.has(r)&&(n=!0)}),n}addPendingMutation(e){this.zs(e,"pending")}updateMutationState(e,t,r){this.zs(e,t,r),this.js(e)}addLocalQueryTarget(t,e=!0){let r="not-current";if(this.isActiveQueryTarget(t)){let e=this.storage.getItem(vE(this.persistenceKey,t));var n;e&&(n=wE.Ss(t,e))&&(r=n.state)}return e&&this.Hs.Ds(t),this.Us(),r}removeLocalQueryTarget(e){this.Hs.vs(e),this.Us()}isLocalQueryTarget(e){return this.Hs.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(vE(this.persistenceKey,e))}updateQueryState(e,t,r){this.Js(e,t,r)}handleUserChange(e,t,r){t.forEach(e=>{this.js(e)}),this.currentUser=e,r.forEach(e=>{this.addPendingMutation(e)})}setOnlineState(e){this.Ys(e)}notifyBundleLoaded(e){this.Zs(e)}shutdown(){this.started&&(this.window.removeEventListener("storage",this.Fs),this.removeItem(this.Ns),this.started=!1)}getItem(e){var t=this.storage.getItem(e);return C(_E,"READ",e,t),t}setItem(e,t){C(_E,"SET",e,t),this.storage.setItem(e,t)}removeItem(e){C(_E,"REMOVE",e),this.storage.removeItem(e)}Ms(e){let t=e;t.storageArea===this.storage&&(C(_E,"EVENT",t.key,t.newValue),t.key===this.Ns?km("Received WebStorage notification for local change. Another client might have garbage-collected our state"):this.Ti.enqueueRetryable(async()=>{if(this.started){if(null!==t.key){if(this.Ls.test(t.key))return null==t.newValue?(e=this.Xs(t.key),this.eo(e,null)):(e=this.no(t.key,t.newValue))?this.eo(e.clientId,e):void 0;if(this.ks.test(t.key)){if(null!==t.newValue){var e=this.ro(t.key,t.newValue);if(e)return this.io(e)}}else if(this.qs.test(t.key)){if(null!==t.newValue){var e=this.so(t.key,t.newValue);if(e)return this.oo(e)}}else if(t.key===this.Qs){if(null!==t.newValue){var e=this.Ks(t.newValue);if(e)return this.Ws(e)}}else t.key===this.Bs?(e=(e=>{let t=Iv.ae;if(null!=e)try{var r=JSON.parse(e);S("number"==typeof r),t=r}catch(e){km(_E,"Failed to read sequence number from WebStorage",e)}return t})(t.newValue))!==Iv.ae&&this.sequenceNumberHandler(e):t.key===this.$s&&(e=this._o(t.newValue),await Promise.all(e.map(e=>this.syncEngine.ao(e))))}}else this.Os.push(t)}))}get Hs(){return this.xs.get(this.Cs)}Us(){this.setItem(this.Ns,this.Hs.bs())}zs(e,t,r){var n=new yE(this.currentUser,e,t,r),i=gE(this.persistenceKey,this.currentUser,e);this.setItem(i,n.bs())}js(e){var t=gE(this.persistenceKey,this.currentUser,e);this.removeItem(t)}Ys(e){var t={clientId:this.Cs,onlineState:e};this.storage.setItem(this.Qs,JSON.stringify(t))}Js(e,t,r){var n=vE(this.persistenceKey,e),i=new wE(e,t,r);this.setItem(n,i.bs())}Zs(e){var t=JSON.stringify(Array.from(e));this.setItem(this.$s,t)}Xs(e){var t=this.Ls.exec(e);return t?t[1]:null}no(e,t){var r=this.Xs(e);return bE.Ss(r,t)}ro(e,t){var r=this.ks.exec(e),n=Number(r[1]),r=void 0!==r[2]?r[2]:null;return yE.Ss(new Im(r),n,t)}so(e,t){var r=this.qs.exec(e),r=Number(r[1]);return wE.Ss(r,t)}Ks(e){return IE.Ss(e)}_o(e){return JSON.parse(e)}async io(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.uo(e.batchId,e.state,e.error);C(_E,"Ignoring mutation for non-active user "+e.user.uid)}oo(e){return this.syncEngine.co(e.targetId,e.state,e.error)}eo(e,t){let r=t?this.xs.insert(e,t):this.xs.remove(e),n=this.Gs(this.xs),i=this.Gs(r),s=[],a=[];return i.forEach(e=>{n.has(e)||s.push(e)}),n.forEach(e=>{i.has(e)||a.push(e)}),this.syncEngine.lo(s,a).then(()=>{this.xs=r})}Ws(e){this.xs.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}Gs(e){let r=Rw;return e.forEach((e,t)=>{r=r.unionWith(t.activeTargetIds)}),r}}class CE{constructor(){this.ho=new TE,this.Po={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,r){}addLocalQueryTarget(e,t=!0){return t&&this.ho.Ds(e),this.Po[e]||"not-current"}updateQueryState(e,t,r){this.Po[e]=t}removeLocalQueryTarget(e){this.ho.vs(e)}isLocalQueryTarget(e){return this.ho.activeTargetIds.has(e)}clearQueryState(e){delete this.Po[e]}getAllActiveQueryTargets(){return this.ho.activeTargetIds}isActiveQueryTarget(e){return this.ho.activeTargetIds.has(e)}start(){return this.ho=new TE,Promise.resolve()}handleUserChange(e,t,r){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class kE{To(e){}shutdown(){}}let SE="ConnectivityMonitor";class AE{constructor(){this.Io=()=>this.Eo(),this.Ao=()=>this.Ro(),this.Vo=[],this.mo()}To(e){this.Vo.push(e)}shutdown(){window.removeEventListener("online",this.Io),window.removeEventListener("offline",this.Ao)}mo(){window.addEventListener("online",this.Io),window.addEventListener("offline",this.Ao)}Eo(){C(SE,"Network connectivity changed: AVAILABLE");for(var e of this.Vo)e(0)}Ro(){C(SE,"Network connectivity changed: UNAVAILABLE");for(var e of this.Vo)e(1)}static D(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}let NE=null;function RE(){return null===NE?NE=268435456+Math.round(2147483648*Math.random()):NE++,"0x"+NE.toString(16)}let PE="RestConnection",DE={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"};class xE{constructor(e){this.Fo=e.Fo,this.Mo=e.Mo}xo(e){this.Oo=e}No(e){this.Bo=e}Lo(e){this.ko=e}onMessage(e){this.qo=e}close(){this.Mo()}send(e){this.Fo(e)}Qo(){this.Oo()}$o(){this.Bo()}Uo(e){this.ko(e)}Ko(e){this.qo(e)}}let OE="WebChannelConnection";class LE extends class{get fo(){return!1}constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;var t=e.ssl?"https":"http",r=encodeURIComponent(this.databaseId.projectId),n=encodeURIComponent(this.databaseId.database);this.po=t+"://"+e.host,this.yo=`projects/${r}/databases/`+n,this.wo=this.databaseId.database===sy?"project_id="+r:`project_id=${r}&database_id=`+n}So(t,e,r,n,i){let s=RE(),a=this.bo(t,e.toUriEncodedString());C(PE,`Sending RPC '${t}' ${s}:`,a,r);var o={"google-cloud-resource-prefix":this.yo,"x-goog-request-params":this.wo};return this.Do(o,n,i),this.vo(t,a,o,r).then(e=>(C(PE,`Received RPC '${t}' ${s}: `,e),e),e=>{throw Sm(PE,`RPC '${t}' ${s} failed with error: `,e,"url: ",a,"request:",r),e})}Co(e,t,r,n,i,s){return this.So(e,t,r,n,i)}Do(r,e,t){r["X-Goog-Api-Client"]="gl-js/ fire/"+Tm,r["Content-Type"]="text/plain",this.databaseInfo.appId&&(r["X-Firebase-GMPID"]=this.databaseInfo.appId),e&&e.headers.forEach((e,t)=>r[t]=e),t&&t.headers.forEach((e,t)=>r[t]=e)}bo(e,t){var r=DE[e];return this.po+`/v1/${t}:`+r}terminate(){}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}vo(l,t,r,n){let h=RE();return new Promise((s,a)=>{let o=new hm;o.setWithCredentials(!0),o.listenOnce(cm.COMPLETE,()=>{try{switch(o.getLastErrorCode()){case dm.NO_ERROR:var e=o.getResponseJson();C(OE,`XHR for RPC '${l}' ${h} received:`,JSON.stringify(e)),s(e);break;case dm.TIMEOUT:C(OE,`RPC '${l}' ${h} timed out`),a(new N(A.DEADLINE_EXCEEDED,"Request time out"));break;case dm.HTTP_ERROR:var t=o.getStatus();if(C(OE,`RPC '${l}' ${h} failed with status:`,t,"response text:",o.getResponseText()),0<t){let e=o.getResponseJson();var r=null==(e=Array.isArray(e)?e[0]:e)?void 0:e.error;if(r&&r.status&&r.message){n=r.status,i=n.toLowerCase().replace(/_/g,"-");let e=0<=Object.values(A).indexOf(i)?i:A.UNKNOWN;a(new N(e,r.message))}else a(new N(A.UNKNOWN,"Server responded with status "+o.getStatus()))}else a(new N(A.UNAVAILABLE,"Connection failed."));break;default:k()}}finally{C(OE,`RPC '${l}' ${h} completed.`)}var n,i});var e=JSON.stringify(n);C(OE,`RPC '${l}' ${h} sending request:`,n),o.send(t,"POST",e,r,15)})}Wo(i,e,t){let s=RE(),r=[this.po,"/","google.firestore.v1.Firestore","/",i,"/channel"],n=mm(),a=gm(),o={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/`+this.databaseId.database},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling},l=this.longPollingOptions.timeoutSeconds;void 0!==l&&(o.longPollingTimeout=Math.round(1e3*l)),this.useFetchStreams&&(o.useFetchStreams=!0),this.Do(o.initMessageHeaders,e,t),o.encodeInitMessageHeaders=!0;var h=r.join("");C(OE,`Creating RPC '${i}' stream ${s}: `+h,o);let u=n.createWebChannel(h,o),c=!1,d=!1,p=new xE({Fo:e=>{d?C(OE,`Not sending because RPC '${i}' stream ${s} is closed:`,e):(c||(C(OE,`Opening RPC '${i}' stream ${s} transport.`),u.open(),c=!0),C(OE,`RPC '${i}' stream ${s} sending:`,e),u.send(e))},Mo:()=>u.close()}),f=(e,t,r)=>{e.listen(t,e=>{try{r(e)}catch(e){setTimeout(()=>{throw e},0)}})};return f(u,um.EventType.OPEN,()=>{d||(C(OE,`RPC '${i}' stream ${s} transport opened.`),p.Qo())}),f(u,um.EventType.CLOSE,()=>{d||(d=!0,C(OE,`RPC '${i}' stream ${s} transport closed`),p.Uo())}),f(u,um.EventType.ERROR,e=>{d||(d=!0,Sm(OE,`RPC '${i}' stream ${s} transport errored:`,e),p.Uo(new N(A.UNAVAILABLE,"The operation could not be completed")))}),f(u,um.EventType.MESSAGE,e=>{if(!d){var t=e.data[0],n=(S(!!t),t),n=(null==n?void 0:n.error)||(null==(n=n[0])?void 0:n.error);if(n){C(OE,`RPC '${i}' stream ${s} received error:`,n);let e=n.status,t=(e=>{var t=vm[e];if(void 0!==t)return ub(t)})(e),r=n.message;void 0===t&&(t=A.INTERNAL,r="Unknown error status: "+e+" with message "+n.message),d=!0,p.Uo(new N(t,r)),u.close()}else C(OE,`RPC '${i}' stream ${s} received:`,t),p.Ko(t)}}),f(a,fm.STAT_EVENT,e=>{e.stat===pm.PROXY?C(OE,`RPC '${i}' stream ${s} detected buffering proxy`):e.stat===pm.NOPROXY&&C(OE,`RPC '${i}' stream ${s} detected no buffering proxy`)}),setTimeout(()=>{p.$o()},0),p}}function ME(){return"undefined"!=typeof window?window:null}function FE(){return"undefined"!=typeof document?document:null}function UE(e){return new Ab(e,!0)}class VE{constructor(e,t,r=1e3,n=1.5,i=6e4){this.Ti=e,this.timerId=t,this.Go=r,this.zo=n,this.jo=i,this.Ho=0,this.Jo=null,this.Yo=Date.now(),this.reset()}reset(){this.Ho=0}Zo(){this.Ho=this.jo}Xo(e){this.cancel();var t=Math.floor(this.Ho+this.e_()),r=Math.max(0,Date.now()-this.Yo),n=Math.max(0,t-r);0<n&&C("ExponentialBackoff",`Backing off for ${n} ms (base delay: ${this.Ho} ms, delay with jitter: ${t} ms, last attempt: ${r} ms ago)`),this.Jo=this.Ti.enqueueAfterDelay(this.timerId,n,()=>(this.Yo=Date.now(),e())),this.Ho*=this.zo,this.Ho<this.Go&&(this.Ho=this.Go),this.Ho>this.jo&&(this.Ho=this.jo)}t_(){null!==this.Jo&&(this.Jo.skipDelay(),this.Jo=null)}cancel(){null!==this.Jo&&(this.Jo.cancel(),this.Jo=null)}e_(){return(Math.random()-.5)*this.Ho}}let qE="PersistentStream";class jE{constructor(e,t,r,n,i,s,a,o){this.Ti=e,this.n_=r,this.r_=n,this.connection=i,this.authCredentialsProvider=s,this.appCheckCredentialsProvider=a,this.listener=o,this.state=0,this.i_=0,this.s_=null,this.o_=null,this.stream=null,this.__=0,this.a_=new VE(e,t)}u_(){return 1===this.state||5===this.state||this.c_()}c_(){return 2===this.state||3===this.state}start(){this.__=0,4!==this.state?this.auth():this.l_()}async stop(){this.u_()&&await this.close(0)}h_(){this.state=0,this.a_.reset()}P_(){this.c_()&&null===this.s_&&(this.s_=this.Ti.enqueueAfterDelay(this.n_,6e4,()=>this.T_()))}I_(e){this.E_(),this.stream.send(e)}async T_(){if(this.c_())return this.close(0)}E_(){this.s_&&(this.s_.cancel(),this.s_=null)}d_(){this.o_&&(this.o_.cancel(),this.o_=null)}async close(e,t){this.E_(),this.d_(),this.a_.cancel(),this.i_++,4!==e?this.a_.reset():t&&t.code===A.RESOURCE_EXHAUSTED?(km(t.toString()),km("Using maximum backoff delay to prevent overloading the backend."),this.a_.Zo()):t&&t.code===A.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.A_(),this.stream.close(),this.stream=null),this.state=e,await this.listener.Lo(t)}A_(){}auth(){this.state=1;let e=this.R_(this.i_),r=this.i_;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,t])=>{this.i_===r&&this.V_(e,t)},t=>{e(()=>{var e=new N(A.UNKNOWN,"Fetching auth token failed: "+t.message);return this.m_(e)})})}V_(e,t){let r=this.R_(this.i_);this.stream=this.f_(e,t),this.stream.xo(()=>{r(()=>this.listener.xo())}),this.stream.No(()=>{r(()=>(this.state=2,this.o_=this.Ti.enqueueAfterDelay(this.r_,1e4,()=>(this.c_()&&(this.state=3),Promise.resolve())),this.listener.No()))}),this.stream.Lo(e=>{r(()=>this.m_(e))}),this.stream.onMessage(e=>{r(()=>1==++this.__?this.g_(e):this.onNext(e))})}l_(){this.state=5,this.a_.Xo(async()=>{this.state=0,this.start()})}m_(e){return C(qE,"close with error: "+e),this.stream=null,this.close(4,e)}R_(t){return e=>{this.Ti.enqueueAndForget(()=>this.i_===t?e():(C(qE,"stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class BE extends jE{constructor(e,t,r,n,i,s){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,r,n,s),this.serializer=i}f_(e,t){return this.connection.Wo("Listen",e,t)}g_(e){return this.onNext(e)}onNext(e){this.a_.reset();var t=((e,t)=>{let r;if("targetChange"in t){t.targetChange;var n="NO_CHANGE"===(l=t.targetChange.targetChangeType||"NO_CHANGE")?0:"ADD"===l?1:"REMOVE"===l?2:"CURRENT"===l?3:"RESET"===l?4:k(),i=t.targetChange.targetIds||[],s=(l=t.targetChange.resumeToken,e.useProto3Json?(S(void 0===l||"string"==typeof l),H_.fromBase64String(l||"")):(S(void 0===l||l instanceof Buffer||l instanceof Uint8Array),H_.fromUint8Array(l||new Uint8Array))),a=t.targetChange.cause,a=a&&(a=void 0===(l=a).code?A.UNKNOWN:ub(l.code),new N(a,l.message||""));r=new wb(n,i,s,a||null)}else if("documentChange"in t){t.documentChange;var n=t.documentChange,i=(n.document,n.document.name,n.document.updateTime,Fb(e,n.document.name)),s=Db(n.document.updateTime),a=n.document.createTime?Db(n.document.createTime):P.min(),o=new Dy({mapValue:{fields:n.document.fields}}),i=xy.newFoundDocument(i,s,a,o),s=n.targetIds||[],o=n.removedTargetIds||[];r=new _b(s,o,i.key,i)}else if("documentDelete"in t){t.documentDelete;n=t.documentDelete,s=(n.document,Fb(e,n.document)),o=n.readTime?Db(n.readTime):P.min(),i=xy.newNoDocument(s,o),s=n.removedTargetIds||[];r=new _b([],s,i.key,i)}else if("documentRemove"in t){t.documentRemove;o=t.documentRemove,n=(o.document,Fb(e,o.document)),s=o.removedTargetIds||[];r=new _b([],s,n,null)}else{if(!("filter"in t))return k();{t.filter;let e=t.filter;e.targetId;var{count:i=0,unchangedNames:o}=e,s=new lb(i,o),n=e.targetId;r=new yb(n,s)}}var l;return r})(this.serializer,e),r="targetChange"in(e=e)&&(!(r=e.targetChange).targetIds||!r.targetIds.length)&&r.readTime?Db(r.readTime):P.min();return this.listener.p_(t,r)}y_(e){var t={},r=(t.database=qb(this.serializer),t.addTarget=((t,r)=>{var n;let e=r.target;if((n=nw(e)?{documents:Gb(t,e)}:{query:$b(t,e).ht}).targetId=r.targetId,0<r.resumeToken.approximateByteSize()){n.resumeToken=Pb(t,r.resumeToken);let e=Nb(t,r.expectedCount);null!==e&&(n.expectedCount=e)}else if(0<r.snapshotVersion.compareTo(P.min())){n.readTime=Rb(t,r.snapshotVersion.toTimestamp());let e=Nb(t,r.expectedCount);null!==e&&(n.expectedCount=e)}return n})(this.serializer,e),Yb(this.serializer,e));r&&(t.labels=r),this.I_(t)}w_(e){var t={};t.database=qb(this.serializer),t.removeTarget=e,this.I_(t)}}class zE extends jE{constructor(e,t,r,n,i,s){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,r,n,s),this.serializer=i}get S_(){return 0<this.__}start(){this.lastStreamToken=void 0,super.start()}A_(){this.S_&&this.b_([])}f_(e,t){return this.connection.Wo("Write",e,t)}g_(e){return S(!!e.streamToken),this.lastStreamToken=e.streamToken,S(!e.writeResults||0===e.writeResults.length),this.listener.D_()}onNext(e){S(!!e.streamToken),this.lastStreamToken=e.streamToken,this.a_.reset();var t=Hb(e.writeResults,e.commitTime),r=Db(e.commitTime);return this.listener.v_(r,t)}C_(){var e={};e.database=qb(this.serializer),this.I_(e)}b_(e){var t={streamToken:this.lastStreamToken,writes:e.map(e=>Kb(this.serializer,e))};this.I_(t)}}class KE extends class{}{constructor(e,t,r,n){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=r,this.serializer=n,this.F_=!1}M_(){if(this.F_)throw new N(A.FAILED_PRECONDITION,"The client has already been terminated.")}So(r,n,i,s){return this.M_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.connection.So(r,Ob(n,i),s,e,t)).catch(e=>{throw"FirebaseError"===e.name?(e.code===A.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new N(A.UNKNOWN,e.toString())})}Co(r,n,i,s,a){return this.M_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.connection.Co(r,Ob(n,i),s,e,t,a)).catch(e=>{throw"FirebaseError"===e.name?(e.code===A.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new N(A.UNKNOWN,e.toString())})}terminate(){this.F_=!0,this.connection.terminate()}}class WE{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.x_=0,this.O_=null,this.N_=!0}B_(){0===this.x_&&(this.L_("Unknown"),this.O_=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.O_=null,this.k_("Backend didn't respond within 10 seconds."),this.L_("Offline"),Promise.resolve())))}q_(e){"Online"===this.state?this.L_("Unknown"):(this.x_++,1<=this.x_&&(this.Q_(),this.k_("Connection failed 1 times. Most recent error: "+e.toString()),this.L_("Offline")))}set(e){this.Q_(),this.x_=0,"Online"===e&&(this.N_=!1),this.L_(e)}L_(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}k_(e){var t=`Could not reach Cloud Firestore backend. ${e}
|
|
15
|
-
This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;this.N_?(km(t),this.N_=!1):C("OnlineStateTracker",t)}Q_(){null!==this.O_&&(this.O_.cancel(),this.O_=null)}}let HE="RemoteStore";class GE{constructor(e,t,r,n,i){this.localStore=e,this.datastore=t,this.asyncQueue=r,this.remoteSyncer={},this.U_=[],this.K_=new Map,this.W_=new Set,this.G_=[],this.z_=i,this.z_.To(e=>{r.enqueueAndForget(async()=>{var e;r0(this)&&(C(HE,"Restarting streams for network reachability change."),(e=this).W_.add(4),await QE(e),e.j_.set("Unknown"),e.W_.delete(4),await $E(e))})}),this.j_=new WE(r,n)}}async function $E(e){if(r0(e))for(var t of e.G_)await t(!0)}async function QE(e){for(var t of e.G_)await t(!1)}function YE(e,t){var r=e;r.K_.has(t.targetId)||(r.K_.set(t.targetId,t),t0(r)?e0(r):c0(r).c_()&&XE(r,t))}function JE(e,t){var r=e,n=c0(r);r.K_.delete(t),n.c_()&&ZE(r,t),0===r.K_.size&&(n.c_()?n.P_():r0(r)&&r.j_.set("Unknown"))}function XE(e,t){var r;e.H_.Ne(t.targetId),(0<t.resumeToken.approximateByteSize()||0<t.snapshotVersion.compareTo(P.min()))&&(r=e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size,t=t.withExpectedCount(r)),c0(e).y_(t)}function ZE(e,t){e.H_.Ne(t),c0(e).w_(t)}function e0(t){t.H_=new Ib({getRemoteKeysForTarget:e=>t.remoteSyncer.getRemoteKeysForTarget(e),lt:e=>t.K_.get(e)||null,it:()=>t.datastore.serializer.databaseId}),c0(t).start(),t.j_.B_()}function t0(e){return r0(e)&&!c0(e).u_()&&0<e.K_.size}function r0(e){return 0===e.W_.size}function n0(e){e.H_=void 0}async function i0(e,t,r){if(!fv(t))throw t;e.W_.add(1),await QE(e),e.j_.set("Offline"),r=r||(()=>nE(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{C(HE,"Retrying IndexedDB access"),await r(),e.W_.delete(1),await $E(e)})}function s0(t,r){return r().catch(e=>i0(t,e,r))}async function a0(e){var t,r,n,i,s=e,a=d0(s);let o=0<s.U_.length?s.U_[s.U_.length-1].batchId:Tv;for(;r0(i=s)&&i.U_.length<10;)try{let e=await((e,t)=>{let r=e;return r.persistence.runTransaction("Get next mutation batch","readonly",e=>(void 0===t&&(t=Tv),r.mutationQueue.getNextMutationBatchAfterBatchId(e,t)))})(s.localStore,o);if(null===e){0===s.U_.length&&a.P_();break}o=e.batchId,t=s,r=e,n=void 0,t.U_.push(r),(n=d0(t)).c_()&&n.S_&&n.b_(r.mutations)}catch(e){await i0(s,e)}o0(s)&&l0(s)}function o0(e){return r0(e)&&!d0(e).u_()&&0<e.U_.length}function l0(e){d0(e).start()}async function h0(e,t){var r=e,n=(r.asyncQueue.verifyOperationInProgress(),C(HE,"RemoteStore received new credentials"),r0(r));r.W_.add(3),await QE(r),n&&r.j_.set("Unknown"),await r.remoteSyncer.handleCredentialChange(t),r.W_.delete(3),await $E(r)}async function u0(e,t){var r=e;t?(r.W_.delete(2),await $E(r)):(r.W_.add(2),await QE(r),r.j_.set("Unknown"))}function c0(t){return t.J_||(t.J_=(e=t.datastore,r=t.asyncQueue,n={xo:(async function(e){e.j_.set("Online")}).bind(null,t),No:(async function(r){r.K_.forEach((e,t)=>{XE(r,e)})}).bind(null,t),Lo:(async function(e,t){n0(e),t0(e)?(e.j_.q_(t),e0(e)):e.j_.set("Unknown")}).bind(null,t),p_:(async function(t,e,r){if(t.j_.set("Online"),e instanceof wb&&2===e.state&&e.cause)try{var n,i=t,s=e,a=s.cause;for(n of s.targetIds)i.K_.has(n)&&(await i.remoteSyncer.rejectListen(n,a),i.K_.delete(n),i.H_.removeTarget(n))}catch(r){C(HE,"Failed to remove targets %s: %s ",e.targetIds.join(","),r),await i0(t,r)}else if(e instanceof _b?t.H_.We(e):e instanceof yb?t.H_.Ze(e):t.H_.je(e),!r.isEqual(P.min()))try{let e=await nE(t.localStore);0<=r.compareTo(e)&&(l=r,(h=(o=t).H_.ot(l)).targetChanges.forEach((e,t)=>{var r;0<e.resumeToken.approximateByteSize()&&(r=o.K_.get(t))&&o.K_.set(t,r.withResumeToken(e.resumeToken,l))}),h.targetMismatches.forEach((e,t)=>{var r=o.K_.get(e);r&&(o.K_.set(e,r.withResumeToken(H_.EMPTY_BYTE_STRING,r.snapshotVersion)),ZE(o,e),r=new rI(r.target,e,t,r.sequenceNumber),XE(o,r))}),await o.remoteSyncer.applyRemoteEvent(h))}catch(e){C(HE,"Failed to raise snapshot:",e),await i0(t,e)}var o,l,h}).bind(null,t)},(i=e).M_(),new BE(r,i.connection,i.authCredentials,i.appCheckCredentials,i.serializer,n)),t.G_.push(async e=>{e?(t.J_.h_(),t0(t)?e0(t):t.j_.set("Unknown")):(await t.J_.stop(),n0(t))})),t.J_;var e,r,n,i}function d0(t){return t.Y_||(t.Y_=(e=t.datastore,r=t.asyncQueue,n={xo:()=>Promise.resolve(),No:(async function(e){d0(e).C_()}).bind(null,t),Lo:(async function(e,t){if(t&&d0(e).S_){var r=e,n=t;if(hb(t=n.code)&&t!==A.ABORTED){let e=r.U_.shift();d0(r).h_(),await s0(r,()=>r.remoteSyncer.rejectFailedWrite(e.batchId,n)),await a0(r)}await 0}o0(e)&&l0(e)}).bind(null,t),D_:(async function(e){var t,r=d0(e);for(t of e.U_)r.b_(t.mutations)}).bind(null,t),v_:(async function(e,t,r){let n=e.U_.shift(),i=ab.from(n,t,r);await s0(e,()=>e.remoteSyncer.applySuccessfulWrite(i)),await a0(e)}).bind(null,t)},(i=e).M_(),new zE(r,i.connection,i.authCredentials,i.appCheckCredentials,i.serializer,n)),t.G_.push(async e=>{e?(t.Y_.h_(),await a0(t)):(await t.Y_.stop(),0<t.U_.length&&(C(HE,`Stopping write stream with ${t.U_.length} pending writes`),t.U_=[]))})),t.Y_;var e,r,n,i}class p0{constructor(e,t,r,n,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=r,this.op=n,this.removalCallback=i,this.deferred=new Nm,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch(e=>{})}get promise(){return this.deferred.promise}static createAndSchedule(e,t,r,n,i){var s=Date.now()+r,s=new p0(e,t,s,n,i);return s.start(r),s}start(e){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new N(A.CANCELLED,"Operation cancelled"+(e?": "+e:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget(()=>null!==this.timerHandle?(this.clearTimeout(),this.op().then(e=>this.deferred.resolve(e))):Promise.resolve())}clearTimeout(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}}function f0(e,t){if(km("AsyncQueue",t+": "+e),fv(e))return new N(A.UNAVAILABLE,t+": "+e);throw e}class g0{static emptySet(e){return new g0(e.comparator)}constructor(r){this.comparator=r?(e,t)=>r(e,t)||x.comparator(e.key,t.key):(e,t)=>x.comparator(e.key,t.key),this.keyedMap=Cw(),this.sortedSet=new L(this.comparator)}has(e){return null!=this.keyedMap.get(e)}get(e){return this.keyedMap.get(e)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(e){var t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(r){this.sortedSet.inorderTraversal((e,t)=>(r(e),!1))}add(e){var t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))}delete(e){var t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof g0))return!1;if(this.size!==e.size)return!1;for(var r=this.sortedSet.getIterator(),n=e.sortedSet.getIterator();r.hasNext();){let e=r.getNext().key,t=n.getNext().key;if(!e.isEqual(t))return!1}return!0}toString(){let t=[];return this.forEach(e=>{t.push(e.toString())}),0===t.length?"DocumentSet ()":"DocumentSet (\n "+t.join(" \n")+"\n)"}copy(e,t){var r=new g0;return r.comparator=this.comparator,r.keyedMap=e,r.sortedSet=t,r}}class m0{constructor(){this.Z_=new L(x.comparator)}track(e){var t=e.doc.key,r=this.Z_.get(t);!r||0!==e.type&&3===r.type?this.Z_=this.Z_.insert(t,e):3===e.type&&1!==r.type?this.Z_=this.Z_.insert(t,{type:r.type,doc:e.doc}):2===e.type&&2===r.type?this.Z_=this.Z_.insert(t,{type:2,doc:e.doc}):2===e.type&&0===r.type?this.Z_=this.Z_.insert(t,{type:0,doc:e.doc}):1===e.type&&0===r.type?this.Z_=this.Z_.remove(t):1===e.type&&2===r.type?this.Z_=this.Z_.insert(t,{type:1,doc:r.doc}):0===e.type&&1===r.type?this.Z_=this.Z_.insert(t,{type:2,doc:e.doc}):k()}X_(){let r=[];return this.Z_.inorderTraversal((e,t)=>{r.push(t)}),r}}class v0{constructor(e,t,r,n,i,s,a,o,l){this.query=e,this.docs=t,this.oldDocs=r,this.docChanges=n,this.mutatedKeys=i,this.fromCache=s,this.syncStateChanged=a,this.excludesMetadataChanges=o,this.hasCachedResults=l}static fromInitialDocuments(e,t,r,n,i){let s=[];return t.forEach(e=>{s.push({type:0,doc:e})}),new v0(e,t,g0.emptySet(t),s,r,n,!0,!1,i)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.hasCachedResults===e.hasCachedResults&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&mw(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;var t=this.docChanges,r=e.docChanges;if(t.length!==r.length)return!1;for(let n=0;n<t.length;n++)if(t[n].type!==r[n].type||!t[n].doc.isEqual(r[n].doc))return!1;return!0}}class _0{constructor(){this.ea=void 0,this.ta=[]}na(){return this.ta.some(e=>e.ra())}}class y0{constructor(){this.queries=w0(),this.onlineState="Unknown",this.ia=new Set}terminate(){var e,r,t,n;e=this,r=new N(A.ABORTED,"Firestore shutting down"),n=(t=e).queries,t.queries=w0(),n.forEach((e,t)=>{for(let e of t.ta)e.onError(r)})}}function w0(){return new Iw(e=>vw(e),mw)}async function b0(t,r){let e=t,n=3;var i=r.query;let s=e.queries.get(i);s?!s.na()&&r.ra()&&(n=2):(s=new _0,n=r.ra()?0:1);try{switch(n){case 0:s.ea=await e.onListen(i,!0);break;case 1:s.ea=await e.onListen(i,!1);break;case 2:await e.onFirstRemoteStoreListen(i)}}catch(t){let e=f0(t,`Initialization of query '${_w(r.query)}' failed`);return void r.onError(e)}e.queries.set(i,s),s.ta.push(r),r.sa(e.onlineState),s.ea&&r.oa(s.ea)&&T0(e)}async function I0(e,t){var r=e,n=t.query;let i=3;var s=r.queries.get(n);if(s){let e=s.ta.indexOf(t);0<=e&&(s.ta.splice(e,1),0===s.ta.length?i=t.ra()?0:1:!s.na()&&t.ra()&&(i=2))}switch(i){case 0:return r.queries.delete(n),r.onUnlisten(n,!0);case 1:return r.queries.delete(n),r.onUnlisten(n,!1);case 2:return r.onLastRemoteStoreUnlisten(n);default:return}}function T0(e){e.ia.forEach(e=>{e.next()})}(_m=_m||{})._a="default",_m.Cache="cache";class E0{constructor(e,t,r){this.query=e,this.aa=t,this.ua=!1,this.ca=null,this.onlineState="Unknown",this.options=r||{}}oa(t){if(!this.options.includeMetadataChanges){let e=[];for(var r of t.docChanges)3!==r.type&&e.push(r);t=new v0(t.query,t.docs,t.oldDocs,e,t.mutatedKeys,t.fromCache,t.syncStateChanged,!0,t.hasCachedResults)}let e=!1;return this.ua?this.la(t)&&(this.aa.next(t),e=!0):this.ha(t,this.onlineState)&&(this.Pa(t),e=!0),this.ca=t,e}onError(e){this.aa.error(e)}sa(e){this.onlineState=e;let t=!1;return this.ca&&!this.ua&&this.ha(this.ca,e)&&(this.Pa(this.ca),t=!0),t}ha(e,t){return!e.fromCache||!this.ra()||(!this.options.Ta||!("Offline"!==t))&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t)}la(e){var t;return 0<e.docChanges.length||(t=this.ca&&this.ca.hasPendingWrites!==e.hasPendingWrites,!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges)}Pa(e){e=v0.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.ua=!0,this.aa.next(e)}ra(){return this.options.source!==_m.Cache}}class C0{constructor(e,t){this.Ia=e,this.byteLength=t}Ea(){return"metadata"in this.Ia}}class k0{constructor(e){this.serializer=e}ps(e){return Fb(this.serializer,e)}ys(e){return e.metadata.exists?zb(this.serializer,e.document,!1):xy.newNoDocument(this.ps(e.metadata.name),this.ws(e.metadata.readTime))}ws(e){return Db(e)}}class S0{constructor(e,t,r){this.da=e,this.localStore=t,this.serializer=r,this.queries=[],this.documents=[],this.collectionGroups=new Set,this.progress=A0(e)}Aa(e){this.progress.bytesLoaded+=e.byteLength;let t=this.progress.documentsLoaded;var r;return e.Ia.namedQuery?this.queries.push(e.Ia.namedQuery):e.Ia.documentMetadata?(this.documents.push({metadata:e.Ia.documentMetadata}),e.Ia.documentMetadata.exists||++t,r=D.fromString(e.Ia.documentMetadata.name),this.collectionGroups.add(r.get(r.length-2))):e.Ia.document&&(this.documents[this.documents.length-1].document=e.Ia.document,++t),t!==this.progress.documentsLoaded?(this.progress.documentsLoaded=t,Object.assign({},this.progress)):null}Ra(e){let r=new Map,n=new k0(this.serializer);for(var i of e)if(i.metadata.queries){let e=n.ps(i.metadata.name);for(let t of i.metadata.queries){var s=(r.get(t)||V()).add(e);r.set(t,s)}}return r}async complete(){let e=await(async(r,n,e,t)=>{let i=r,s=V(),a=Tw;for(let r of e){let e=n.ps(r.metadata.name),t=(r.document&&(s=s.add(e)),n.ys(r));t.setReadTime(n.ws(r.metadata.readTime)),a=a.insert(e,t)}let o=i.ds.newChangeBuffer({trackRemovals:!0}),l=await aE(i,(r=t,pw(hw(D.fromString("__bundle__/docs/"+r)))));return i.persistence.runTransaction("Apply bundle documents","readwrite",t=>sE(t,o,a).next(e=>(o.apply(t),e)).next(e=>i.Hr.removeMatchingKeysForTargetId(t,l.targetId).next(()=>i.Hr.addMatchingKeys(t,s,l.targetId)).next(()=>i.localDocuments.getLocalViewOfDocuments(t,e.Vs,e.fs)).next(()=>e.Vs)))})(this.localStore,new k0(this.serializer),this.documents,this.da.id),t=this.Ra(this.documents);for(let e of this.queries)await(async(e,r,n=V())=>{let i=await aE(e,pw(cI(r.bundledQuery))),s=e;return s.persistence.runTransaction("Save named query","readwrite",e=>{var t=Db(r.readTime);return 0<=i.snapshotVersion.compareTo(t)?s.Yr.saveNamedQuery(e,r):(t=i.withResumeToken(H_.EMPTY_BYTE_STRING,t),s.Ts=s.Ts.insert(t.targetId,t),s.Hr.updateTargetData(e,t).next(()=>s.Hr.removeMatchingKeysForTargetId(e,i.targetId)).next(()=>s.Hr.addMatchingKeys(e,n,i.targetId)).next(()=>s.Yr.saveNamedQuery(e,r)))})})(this.localStore,e,t.get(e.name));return this.progress.taskState="Success",{progress:this.progress,Va:this.collectionGroups,ma:e}}}function A0(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class N0{constructor(e){this.key=e}}class R0{constructor(e){this.key=e}}class P0{constructor(e,t){this.query=e,this.fa=t,this.ga=null,this.hasCachedResults=!1,this.current=!1,this.pa=V(),this.mutatedKeys=V(),this.ya=bw(e),this.wa=new g0(this.ya)}get Sa(){return this.fa}ba(e,t){let o=t?t.Da:new m0,l=(t||this).wa,h=(t||this).mutatedKeys,u=l,c=!1,d="F"===this.query.limitType&&l.size===this.query.limit?l.last():null,p="L"===this.query.limitType&&l.size===this.query.limit?l.first():null;if(e.inorderTraversal((e,t)=>{var r=l.get(e),n=yw(this.query,t)?t:null,i=!!r&&this.mutatedKeys.has(r.key),s=!!n&&(n.hasLocalMutations||this.mutatedKeys.has(n.key)&&n.hasCommittedMutations);let a=!1;r&&n?r.data.isEqual(n.data)?i!==s&&(o.track({type:3,doc:n}),a=!0):!this.va(r,n)&&(o.track({type:2,doc:n}),a=!0,d&&0<this.ya(n,d)||p&&this.ya(n,p)<0)&&(c=!0):!r&&n?(o.track({type:0,doc:n}),a=!0):r&&!n&&(o.track({type:1,doc:r}),a=!0,d||p)&&(c=!0),a&&(h=n?(u=u.add(n),s?h.add(e):h.delete(e)):(u=u.delete(e),h.delete(e)))}),null!==this.query.limit)for(;u.size>this.query.limit;){let e="F"===this.query.limitType?u.last():u.first();u=u.delete(e.key),h=h.delete(e.key),o.track({type:1,doc:e})}return{wa:u,Da:o,ls:c,mutatedKeys:h}}va(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,r,n){var i=this.wa,s=(this.wa=e.wa,this.mutatedKeys=e.mutatedKeys,e.Da.X_()),a=(s.sort((e,t)=>{return r=e.type,n=t.type,(i=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return k()}})(r)-i(n)||this.ya(e.doc,t.doc);var r,n,i}),this.Ca(r),n=null!=n&&n,t&&!n?this.Fa():[]),o=0===this.pa.size&&this.current&&!n?1:0,l=o!==this.ga;return this.ga=o,0!==s.length||l?{snapshot:new v0(this.query,e.wa,i,s,e.mutatedKeys,0==o,l,!1,!!r&&0<r.resumeToken.approximateByteSize()),Ma:a}:{Ma:a}}sa(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({wa:this.wa,Da:new m0,mutatedKeys:this.mutatedKeys,ls:!1},!1)):{Ma:[]}}xa(e){return!this.fa.has(e)&&!!this.wa.has(e)&&!this.wa.get(e).hasLocalMutations}Ca(e){e&&(e.addedDocuments.forEach(e=>this.fa=this.fa.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.fa=this.fa.delete(e)),this.current=e.current)}Fa(){if(!this.current)return[];let t=this.pa,r=(this.pa=V(),this.wa.forEach(e=>{this.xa(e.key)&&(this.pa=this.pa.add(e.key))}),[]);return t.forEach(e=>{this.pa.has(e)||r.push(new R0(e))}),this.pa.forEach(e=>{t.has(e)||r.push(new N0(e))}),r}Oa(e){this.fa=e.gs,this.pa=V();var t=this.ba(e.documents);return this.applyChanges(t,!0)}Na(){return v0.fromInitialDocuments(this.query,this.wa,this.mutatedKeys,0===this.ga,this.hasCachedResults)}}let D0="SyncEngine";class x0{constructor(e,t,r){this.query=e,this.targetId=t,this.view=r}}class O0{constructor(e){this.key=e,this.Ba=!1}}class L0{constructor(e,t,r,n,i,s){this.localStore=e,this.remoteStore=t,this.eventManager=r,this.sharedClientState=n,this.currentUser=i,this.maxConcurrentLimboResolutions=s,this.La={},this.ka=new Iw(e=>vw(e),mw),this.qa=new Map,this.Qa=new Set,this.$a=new L(x.comparator),this.Ua=new Map,this.Ka=new RT,this.Wa={},this.Ga=new Map,this.za=nT.Kn(),this.onlineState="Unknown",this.ja=void 0}get isPrimaryClient(){return!0===this.ja}}async function M0(e,t,r,n){var i=await aE(e.localStore,pw(t)),s=i.targetId,a=e.sharedClientState.addLocalQueryTarget(s,r);let o;return n&&(o=await F0(e,t,s,"current"===a,i.resumeToken)),e.isPrimaryClient&&r&&YE(e.remoteStore,i),o}async function F0(n,e,t,r,i){n.Ha=(e,t,r)=>(async(e,t,r,n)=>{let i=t.view.ba(r);i.ls&&(i=await lE(e.localStore,t.query,!1).then(({documents:e})=>t.view.ba(e,i)));var s=n&&n.targetChanges.get(t.targetId),a=n&&null!=n.targetMismatches.get(t.targetId),s=t.view.applyChanges(i,e.isPrimaryClient,s,a);return G0(e,t.targetId,s.Ma),s.snapshot})(n,e,t,r);var s=await lE(n.localStore,e,!0),a=new P0(e,s.gs),s=a.ba(s.documents),o=vb.createSynthesizedTargetChangeForCurrentChange(t,r&&"Offline"!==n.onlineState,i),s=a.applyChanges(s,n.isPrimaryClient,o),o=(G0(n,t,s.Ma),new x0(e,t,a));return n.ka.set(e,o),n.qa.has(t)?n.qa.get(t).push(e):n.qa.set(t,[e]),s.snapshot}async function U0(t,e,r){var n=eC(t);try{let t=await((e,i)=>{let s=e,a=Km.now(),o=i.reduce((e,t)=>e.add(t.key),V()),l,h;return s.persistence.runTransaction("Locally write mutations","readwrite",n=>{let t=Tw,r=V();return s.ds.getEntries(n,o).next(e=>{(t=e).forEach((e,t)=>{t.isValidDocument()||(r=r.add(e))})}).next(()=>s.localDocuments.getOverlayedDocuments(n,t)).next(e=>{l=e;var t=[];for(let r of i){let e=((e,r)=>{let n=null;for(var i of e.fieldTransforms){let e=r.data.field(i.field),t=Lw(i.transform,e||null);null!=t&&(n=null===n?Dy.empty():n).set(i.field,t)}return n||null})(r,l.get(r.key).overlayedDocument);null!=e&&t.push(new Zw(r.key,e,function i(e){let s=[];return U_(e.fields,(e,r)=>{var n=new $m([e]);if(Cy(r)){let t=i(r.mapValue).fields;if(0===t.length)s.push(n);else for(let e of t)s.push(n.child(e))}else s.push(n)}),new K_(s)}(e.value.mapValue),Hw.exists(!0)))}return s.mutationQueue.addMutationBatch(n,a,t,i)}).next(e=>{var t=(h=e).applyToLocalDocumentSet(l,r);return s.documentOverlayCache.saveOverlays(n,e.batchId,t)})}).then(()=>({batchId:h.batchId,changes:kw(l)}))})(n.localStore,e);n.sharedClientState.addPendingMutation(t.batchId);{var i=n;var s=t.batchId;var a=r;let e=i.Wa[i.currentUser.toKey()];e=(e=e||new L(R)).insert(s,a),i.Wa[i.currentUser.toKey()]=e}await Q0(n,t.changes),await a0(n.remoteStore)}catch(t){let e=f0(t,"Failed to persist write");r.reject(e)}}async function V0(e,t){let n=e;try{let e=await iE(n.localStore,t);t.targetChanges.forEach((e,t)=>{var r=n.Ua.get(t);r&&(S(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),0<e.addedDocuments.size?r.Ba=!0:0<e.modifiedDocuments.size?S(r.Ba):0<e.removedDocuments.size&&(S(r.Ba),r.Ba=!1))}),await Q0(n,e,t)}catch(e){await ov(e)}}function q0(e,i,t){var s=e;if(s.isPrimaryClient&&0===t||!s.isPrimaryClient&&1===t){let n=[];s.ka.forEach((e,t)=>{var r=t.view.sa(i);r.snapshot&&n.push(r.snapshot)});{t=s.eventManager;var a=i;var o=t;o.onlineState=a;let r=!1;o.queries.forEach((e,t)=>{for(let e of t.ta)e.sa(a)&&(r=!0)}),r&&T0(o)}n.length&&s.La.p_(n),s.onlineState=i,s.isPrimaryClient&&s.sharedClientState.setOnlineState(i)}}async function j0(e,t,r){var n=e;try{let e=await((e,n)=>{let i=e;return i.persistence.runTransaction("Reject batch","readwrite-primary",t=>{let r;return i.mutationQueue.lookupMutationBatch(t,n).next(e=>(S(null!==e),r=e.keys(),i.mutationQueue.removeMutationBatch(t,e))).next(()=>i.mutationQueue.performConsistencyCheck(t)).next(()=>i.documentOverlayCache.removeOverlaysForBatchId(t,r,n)).next(()=>i.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t,r)).next(()=>i.localDocuments.getDocuments(t,r))})})(n.localStore,t);K0(n,t,r),z0(n,t),n.sharedClientState.updateMutationState(t,"rejected",r),await Q0(n,e)}catch(r){await ov(r)}}async function B0(t,r){let n=t;r0(n.remoteStore)||C(D0,"The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");try{let e=await(e=>{let t=e;return t.persistence.runTransaction("Get highest unacknowledged batch id","readonly",e=>t.mutationQueue.getHighestUnacknowledgedBatchId(e))})(n.localStore);var i;e===Tv?r.resolve():((i=n.Ga.get(e)||[]).push(r),n.Ga.set(e,i))}catch(t){let e=f0(t,"Initialization of waitForPendingWrites() operation failed");r.reject(e)}}function z0(e,t){(e.Ga.get(t)||[]).forEach(e=>{e.resolve()}),e.Ga.delete(t)}function K0(e,t,r){var n=e;let i=n.Wa[n.currentUser.toKey()];if(i){let e=i.get(t);e&&(r?e.reject(r):e.resolve(),i=i.remove(t)),n.Wa[n.currentUser.toKey()]=i}}function W0(t,e,r=null){t.sharedClientState.removeLocalQueryTarget(e);for(var n of t.qa.get(e))t.ka.delete(n),r&&t.La.Ja(n,r);t.qa.delete(e),t.isPrimaryClient&&t.Ka.br(e).forEach(e=>{t.Ka.containsKey(e)||H0(t,e)})}function H0(e,t){e.Qa.delete(t.path.canonicalString());var r=e.$a.get(t);null!==r&&(JE(e.remoteStore,r),e.$a=e.$a.remove(t),e.Ua.delete(r),$0(e))}function G0(e,t,r){for(var n of r)n instanceof N0?(e.Ka.addReference(n.key,t),i=e,s=n,o=a=void 0,a=s.key,o=a.path.canonicalString(),i.$a.get(a)||i.Qa.has(o)||(C(D0,"New document in limbo: "+a),i.Qa.add(o),$0(i))):n instanceof R0?(C(D0,"Document no longer in limbo: "+n.key),e.Ka.removeReference(n.key,t),e.Ka.containsKey(n.key)||H0(e,n.key)):k();var i,s,a,o}function $0(e){for(;0<e.Qa.size&&e.$a.size<e.maxConcurrentLimboResolutions;){var t=e.Qa.values().next().value,t=(e.Qa.delete(t),new x(D.fromString(t))),r=e.za.next();e.Ua.set(r,new O0(t)),e.$a=e.$a.insert(t,r),YE(e.remoteStore,new rI(pw(hw(t.path)),r,"TargetPurposeLimboResolution",Iv.ae))}}async function Q0(e,t,i){let s=e,a=[],o=[],r=[];if(!s.ka.isEmpty()){s.ka.forEach((e,n)=>{r.push(s.Ha(n,t,i).then(t=>{var r;if((t||i)&&s.isPrimaryClient){let e=t?!t.fromCache:null==(r=null==i?void 0:i.targetChanges.get(n.targetId))?void 0:r.current;s.sharedClientState.updateQueryState(n.targetId,e?"current":"not-current")}if(t){a.push(t);let e=$T.Yi(n.targetId,t);o.push(e)}}))}),await Promise.all(r),s.La.p_(a);{var n=s.localStore,l=o;let i=n;try{await i.persistence.runTransaction("notifyLocalViewChanges","readwrite",r=>O.forEach(l,t=>O.forEach(t.Hi,e=>i.persistence.referenceDelegate.addReference(r,t.targetId,e)).next(()=>O.forEach(t.Ji,e=>i.persistence.referenceDelegate.removeReference(r,t.targetId,e)))))}catch(n){if(!fv(n))throw n;C(JT,"Failed to update sequence numbers: "+n)}for(let e of l){let n=e.targetId;if(!e.fromCache){let e=i.Ts.get(n),t=e.snapshotVersion,r=e.withLastLimboFreeSnapshotVersion(t);i.Ts=i.Ts.insert(n,r)}}}}}async function Y0(e,t,r,n){var i=e,s=await((e,r)=>{let n=e,i=n.mutationQueue;return n.persistence.runTransaction("Lookup mutation documents","readonly",t=>i.Ln(t,r).next(e=>e?n.localDocuments.getDocuments(t,e):O.resolve(null)))})(i.localStore,t);null!==s?("pending"===r?await a0(i.remoteStore):"acknowledged"===r||"rejected"===r?(K0(i,t,n||null),z0(i,t),i.localStore.mutationQueue.qn(t)):k(),await Q0(i,s)):C(D0,"Cannot apply mutation batch with id: "+t)}async function J0(r,e){var n,i,s,a=r,o=[],l=[];for(let r of e){let t,e=a.qa.get(r);if(e&&0!==e.length){t=await aE(a.localStore,pw(e[0]));for(let r of e){let e=a.ka.get(r),t=(n=e,s=i=void 0,s=await lE((i=a).localStore,n.query,!0),s=n.view.Oa(s),i.isPrimaryClient&&G0(i,n.targetId,s.Ma),await s);t.snapshot&&l.push(t.snapshot)}}else{let e=await hE(a.localStore,r);t=await aE(a.localStore,e),await F0(a,X0(e),r,!1,t.resumeToken)}o.push(t)}return a.La.p_(l),o}function X0(e){return lw(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,"F",e.startAt,e.endAt)}function Z0(e){var t=e;return t.remoteStore.remoteSyncer.applyRemoteEvent=V0.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=(function(e,t){let n=e,r=n.Ua.get(t);if(r&&r.Ba)return V().add(r.key);{let r=V(),e=n.qa.get(t);if(e)for(let t of e){let e=n.ka.get(t);r=r.unionWith(e.view.Sa)}return r}}).bind(null,t),t.remoteStore.remoteSyncer.rejectListen=(async function(e,n,t){let i=e,r=(i.sharedClientState.updateQueryState(n,"rejected",t),i.Ua.get(n)),s=r&&r.key;if(s){let e=new L(x.comparator),t=(e=e.insert(s,xy.newNoDocument(s,P.min())),V().add(s)),r=new mb(P.min(),new Map,new L(R),e,t);await V0(i,r),i.$a=i.$a.remove(s),i.Ua.delete(n),$0(i)}else await oE(i.localStore,n,!1).then(()=>W0(i,n,t)).catch(ov)}).bind(null,t),t.La.p_=(function(r,e){var n=r;let i=!1;for(let r of e){let e=r.query,t=n.queries.get(e);if(t){for(let e of t.ta)e.oa(r)&&(i=!0);t.ea=r}}i&&T0(n)}).bind(null,t.eventManager),t.La.Ja=(function(e,t,r){var n=e,i=n.queries.get(t);if(i)for(let e of i.ta)e.onError(r);n.queries.delete(t)}).bind(null,t.eventManager),t}function eC(e){var t=e;return t.remoteStore.remoteSyncer.applySuccessfulWrite=(async function(e,t){var r=e,n=t.batch.batchId;try{let e=await rE(r.localStore,t);K0(r,n,null),z0(r,n),r.sharedClientState.updateMutationState(n,"acknowledged"),await Q0(r,e)}catch(e){await ov(e)}}).bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=j0.bind(null,t),t}function tC(e,t,r){let n=e;(async(e,r,n)=>{try{var i=await r.getMetadata();if(await((e,t)=>{let r=e,n=Db(t.createTime);return r.persistence.runTransaction("hasNewerBundle","readonly",e=>r.Yr.getBundleMetadata(e,t.id)).then(e=>!!e&&0<=e.createTime.compareTo(n))})(e.localStore,i))return await r.close(),n._completeWith({taskState:"Success",documentsLoaded:i.totalDocuments,bytesLoaded:i.totalBytes,totalDocuments:i.totalDocuments,totalBytes:i.totalBytes}),Promise.resolve(new Set);n._updateProgress(A0(i));var s=new S0(i,e.localStore,r.serializer);let t=await r.Ya();for(;t;){let e=await s.Aa(t);e&&n._updateProgress(e),t=await r.Ya()}var a=await s.complete();return await Q0(e,a.ma,void 0),await((e,t)=>{let r=e;return r.persistence.runTransaction("Save bundle","readwrite",e=>r.Yr.saveBundleMetadata(e,t))})(e.localStore,i),n._completeWith(a.progress),Promise.resolve(a.Va)}catch(e){return Sm(D0,"Loading bundle failed with "+e),n._failWith(e),Promise.resolve(new Set)}})(n,t,r).then(e=>{n.sharedClientState.notifyBundleLoaded(e)})}class rC{constructor(){this.kind="memory",this.synchronizeTabs=!1}async initialize(e){this.serializer=UE(e.databaseInfo.databaseId),this.sharedClientState=this.Za(e),this.persistence=this.Xa(e),await this.persistence.start(),this.localStore=this.eu(e),this.gcScheduler=this.tu(e,this.localStore),this.indexBackfillerScheduler=this.nu(e,this.localStore)}tu(e,t){return null}nu(e,t){return null}eu(e){return eE(this.persistence,new YT,e.initialUser,this.serializer)}Xa(e){return new MT(UT.ri,this.serializer)}Za(e){return new CE}async terminate(){var e;null!=(e=this.gcScheduler)&&e.stop(),null!=(e=this.indexBackfillerScheduler)&&e.stop(),this.sharedClientState.shutdown(),await this.persistence.shutdown()}}rC.provider={build:()=>new rC};class nC extends rC{constructor(e){super(),this.cacheSizeBytes=e}tu(e,t){S(this.persistence.referenceDelegate instanceof VT);var r=this.persistence.referenceDelegate.garbageCollector;return new cT(r,e.asyncQueue,t)}Xa(e){let t=void 0!==this.cacheSizeBytes?QI.withCacheSize(this.cacheSizeBytes):QI.DEFAULT;return new MT(e=>VT.ri(e,t),this.serializer)}}class iC extends rC{constructor(e,t,r){super(),this.ru=e,this.cacheSizeBytes=t,this.forceOwnership=r,this.kind="persistent",this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.ru.initialize(this,e),await eC(this.ru.syncEngine),await a0(this.ru.remoteStore),await this.persistence.Ci(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve()))}eu(e){return eE(this.persistence,new YT,e.initialUser,this.serializer)}tu(e,t){var r=this.persistence.referenceDelegate.garbageCollector;return new cT(r,e.asyncQueue,t)}nu(e,t){var r=new bv(t,this.persistence);return new wv(e.asyncQueue,r)}Xa(e){var t=GT(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),r=void 0!==this.cacheSizeBytes?QI.withCacheSize(this.cacheSizeBytes):QI.DEFAULT;return new KT(this.synchronizeTabs,t,e.clientId,r,e.asyncQueue,ME(),FE(),this.serializer,this.sharedClientState,!!this.forceOwnership)}Za(e){return new CE}}class sC extends iC{constructor(e,t){super(e,t,!1),this.ru=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);var t=this.ru.syncEngine;this.sharedClientState instanceof EE&&(this.sharedClientState.syncEngine={uo:Y0.bind(null,t),co:(async function(e,r,n,t){var i=e;if(i.ja)C(D0,"Ignoring unexpected query state notification.");else{var s=i.qa.get(r);if(s&&0<s.length)switch(n){case"current":case"not-current":{let e=await uE(i.localStore,ww(s[0])),t=mb.createSynthesizedRemoteEventForCurrentChange(r,"current"===n,H_.EMPTY_BYTE_STRING);await Q0(i,e,t);break}case"rejected":await oE(i.localStore,r,!0),W0(i,r,t);break;default:k()}}}).bind(null,t),lo:(async function(e,t,n){let i=Z0(e);if(i.ja){for(let r of t)if(i.qa.has(r)&&i.sharedClientState.isActiveQueryTarget(r))C(D0,"Adding an already active target "+r);else{let e=await hE(i.localStore,r),t=await aE(i.localStore,e);await F0(i,X0(e),t.targetId,!1,t.resumeToken),YE(i.remoteStore,t)}for(let r of n)i.qa.has(r)&&await oE(i.localStore,r,!1).then(()=>{JE(i.remoteStore,r),W0(i,r)}).catch(ov)}}).bind(null,t),zi:(function(e){return e.localStore.persistence.zi()}).bind(null,t),ao:(async function(e,t){let r=e;return uE(r.localStore,t).then(e=>Q0(r,e))}).bind(null,t)},await this.sharedClientState.start()),await this.persistence.Ci(async e=>{{var t=this.ru.syncEngine,s=e;let i=t;if(Z0(i),eC(i),!0===s&&!0!==i.ja){let e=i.sharedClientState.getAllActiveQueryTargets(),t=await J0(i,e.toArray());i.ja=!0,await u0(i.remoteStore,!0);for(let e of t)YE(i.remoteStore,e)}else if(!1===s&&!1!==i.ja){let r=[],n=Promise.resolve();i.qa.forEach((e,t)=>{i.sharedClientState.isLocalQueryTarget(t)?r.push(t):n=n.then(()=>(W0(i,t),oE(i.localStore,t,!0))),JE(i.remoteStore,t)}),await n,await J0(i,r);{s=i;let r=s;r.Ua.forEach((e,t)=>{JE(r.remoteStore,t)}),r.Ka.Dr(),r.Ua=new Map,r.$a=new L(x.comparator)}i.ja=!1,await u0(i.remoteStore,!1)}}await 0,this.gcScheduler&&(e&&!this.gcScheduler.started?this.gcScheduler.start():e||this.gcScheduler.stop()),this.indexBackfillerScheduler&&(e&&!this.indexBackfillerScheduler.started?this.indexBackfillerScheduler.start():e||this.indexBackfillerScheduler.stop())})}Za(e){var t,r=ME();if(EE.D(r))return t=GT(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),new EE(r,e.asyncQueue,t,e.clientId,e.initialUser);throw new N(A.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.")}}class aC{async initialize(e,t){this.localStore||(this.localStore=e.localStore,this.sharedClientState=e.sharedClientState,this.datastore=this.createDatastore(t),this.remoteStore=this.createRemoteStore(t),this.eventManager=this.createEventManager(t),this.syncEngine=this.createSyncEngine(t,!e.synchronizeTabs),this.sharedClientState.onlineStateHandler=e=>q0(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=(async function(e,t){var r,n,i=e;if(!i.currentUser.isEqual(t)){C(D0,"User change. New user:",t.toKey());let e=await tE(i.localStore,t);i.currentUser=t,n="'waitForPendingWrites' promise is rejected due to a user change.",(r=i).Ga.forEach(e=>{e.forEach(e=>{e.reject(new N(A.CANCELLED,n))})}),r.Ga.clear(),i.sharedClientState.handleUserChange(t,e.removedBatchIds,e.addedBatchIds),await Q0(i,e.Rs)}}).bind(null,this.syncEngine),await u0(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new y0}createDatastore(e){var t,r,n,i=UE(e.databaseInfo.databaseId),s=(t=e.databaseInfo,new LE(t));return t=e.authCredentials,e=e.appCheckCredentials,r=s,n=i,new KE(t,e,r,n)}createRemoteStore(e){return t=this.localStore,r=this.datastore,e=e.asyncQueue,n=e=>q0(this.syncEngine,e,0),i=new(AE.D()?AE:kE),new GE(t,r,e,n,i);var t,r,n,i}createSyncEngine(e,t){return r=this.localStore,n=this.remoteStore,i=this.eventManager,s=this.sharedClientState,a=e.initialUser,e=e.maxConcurrentLimboResolutions,t=t,o=new L0(r,n,i,s,a,e),t&&(o.ja=!0),o;var r,n,i,s,a,o}async terminate(){var e,t;e=this.remoteStore,t=e,C(HE,"RemoteStore shutting down."),t.W_.add(5),await QE(t),t.z_.shutdown(),await!t.j_.set("Unknown"),null!=(t=this.datastore)&&t.terminate(),null!=(t=this.eventManager)&&t.terminate()}}function oC(t,r=10240){let n=0;return{async read(){var e;return n<t.byteLength?(e={value:t.slice(n,n+r),done:!1},n+=r,e):{done:!0}},async cancel(){},releaseLock(){},closed:Promise.resolve()}}aC.provider={build:()=>new aC};class lC{constructor(e){this.observer=e,this.muted=!1}next(e){this.muted||this.observer.next&&this.iu(this.observer.next,e)}error(e){this.muted||(this.observer.error?this.iu(this.observer.error,e):km("Uncaught Error in snapshot listener:",e.toString()))}su(){this.muted=!0}iu(e,t){setTimeout(()=>{this.muted||e(t)},0)}}class hC{constructor(e,t){this.ou=e,this.serializer=t,this.metadata=new Nm,this.buffer=new Uint8Array,this._u=new TextDecoder("utf-8"),this.au().then(e=>{e&&e.Ea()?this.metadata.resolve(e.Ia.metadata):this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is
|
|
16
|
-
`+JSON.stringify(null==e?void 0:e.Ia)))},e=>this.metadata.reject(e))}close(){return this.ou.cancel()}async getMetadata(){return this.metadata.promise}async Ya(){return await this.getMetadata(),this.au()}async au(){var e,t,r=await this.uu();return null===r?null:(t=this._u.decode(r),e=Number(t),isNaN(e)&&this.cu(`length string (${t}) is not valid number`),t=await this.lu(e),new C0(JSON.parse(t),r.length+e))}hu(){return this.buffer.findIndex(e=>e==="{".charCodeAt(0))}async uu(){for(;this.hu()<0&&!await this.Pu(););var e,t;return 0===this.buffer.length?null:((e=this.hu())<0&&this.cu("Reached the end of bundle when a length string is expected."),t=this.buffer.slice(0,e),this.buffer=this.buffer.slice(e),t)}async lu(e){for(;this.buffer.length<e;)await this.Pu()&&this.cu("Reached the end of bundle when more is expected.");var t=this._u.decode(this.buffer.slice(0,e));return this.buffer=this.buffer.slice(e),t}cu(e){throw this.ou.cancel(),new Error("Invalid bundle format: "+e)}async Pu(){var e,t=await this.ou.read();return t.done||((e=new Uint8Array(this.buffer.length+t.value.length)).set(this.buffer),e.set(t.value,this.buffer.length),this.buffer=e),t.done}}class uC{constructor(e){this.datastore=e,this.readVersions=new Map,this.mutations=[],this.committed=!1,this.lastTransactionError=null,this.writtenDocs=new Set}async lookup(e){if(this.ensureCommitNotCalled(),0<this.mutations.length)throw this.lastTransactionError=new N(A.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes."),this.lastTransactionError;var t=await(async(e,t)=>{let l=e,r={documents:t.map(e=>Mb(l.serializer,e))},n=await l.Co("BatchGetDocuments",l.serializer.databaseId,D.emptyPath(),r,t.length),h=new Map,i=(n.forEach(e=>{t=l.serializer;var t,r,n,i,s,a,o="found"in(e=e)?(r=t,S(!!(n=e).found),n.found.name,n.found.updateTime,i=Fb(r,n.found.name),s=Db(n.found.updateTime),o=n.found.createTime?Db(n.found.createTime):P.min(),a=new Dy({mapValue:{fields:n.found.fields}}),xy.newFoundDocument(i,s,o,a)):"missing"in e?(r=t,S(!!(n=e).missing),S(!!n.readTime),i=Fb(r,n.missing),s=Db(n.readTime),xy.newNoDocument(i,s)):k();h.set(o.key.toString(),o)}),[]);return t.forEach(e=>{var t=h.get(e.toString());S(!!t),i.push(t)}),i})(this.datastore,e);return t.forEach(e=>this.recordVersion(e)),t}set(e,t){this.write(t.toMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}update(e,t){try{this.write(t.toMutation(e,this.preconditionForUpdate(e)))}catch(e){this.lastTransactionError=e}this.writtenDocs.add(e.toString())}delete(e){this.write(new nb(e,this.precondition(e))),this.writtenDocs.add(e.toString())}async commit(){if(this.ensureCommitNotCalled(),this.lastTransactionError)throw this.lastTransactionError;let t=this.readVersions;this.mutations.forEach(e=>{t.delete(e.key.toString())}),t.forEach((e,t)=>{var r=x.fromPath(t);this.mutations.push(new ib(r,this.precondition(r)))});{var r=this.datastore,n=this.mutations;let t=r,e={writes:n.map(e=>Kb(t.serializer,e))};await t.So("Commit",t.serializer.databaseId,D.emptyPath(),e)}await 0,this.committed=!0}recordVersion(e){let t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw k();t=P.min()}var r=this.readVersions.get(e.key.toString());if(r){if(!t.isEqual(r))throw new N(A.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),t)}precondition(e){var t=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&t?t.isEqual(P.min())?Hw.exists(!1):Hw.updateTime(t):Hw.none()}preconditionForUpdate(e){var t=this.readVersions.get(e.toString());if(this.writtenDocs.has(e.toString())||!t)return Hw.exists(!0);if(t.isEqual(P.min()))throw new N(A.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return Hw.updateTime(t)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}class cC{constructor(e,t,r,n,i){this.asyncQueue=e,this.datastore=t,this.options=r,this.updateFunction=n,this.deferred=i,this.Tu=r.maxAttempts,this.a_=new VE(this.asyncQueue,"transaction_retry")}Iu(){--this.Tu,this.Eu()}Eu(){this.a_.Xo(async()=>{let t=new uC(this.datastore),e=this.du(t);e&&e.then(e=>{this.asyncQueue.enqueueAndForget(()=>t.commit().then(()=>{this.deferred.resolve(e)}).catch(e=>{this.Au(e)}))}).catch(e=>{this.Au(e)})})}du(e){try{var t=this.updateFunction(e);return!Ev(t)&&t.catch&&t.then?t:(this.deferred.reject(Error("Transaction callback must return a Promise")),null)}catch(e){return this.deferred.reject(e),null}}Au(e){0<this.Tu&&this.Ru(e)?(--this.Tu,this.asyncQueue.enqueueAndForget(()=>(this.Eu(),Promise.resolve()))):this.deferred.reject(e)}Ru(e){var t;return"FirebaseError"===e.name&&("aborted"===(t=e.code)||"failed-precondition"===t||"already-exists"===t||!hb(t))}}let dC="FirestoreClient";class pC{constructor(e,t,r,n,i){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=r,this.databaseInfo=n,this.user=Im.UNAUTHENTICATED,this.clientId=Vm.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=i,this.authCredentials.start(r,async e=>{C(dC,"Received user=",e.uid),await this.authCredentialListener(e),this.user=e}),this.appCheckCredentials.start(r,e=>(C(dC,"Received new app check token=",e),this.appCheckCredentialListener(e,this.user)))}get configuration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}terminate(){this.asyncQueue.enterRestrictedMode();let r=new Nm;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async()=>{try{this._onlineComponents&&await this._onlineComponents.terminate(),this._offlineComponents&&await this._offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),r.resolve()}catch(e){var t=f0(e,"Failed to shutdown persistence");r.reject(t)}}),r.promise}}async function fC(e,t){e.asyncQueue.verifyOperationInProgress(),C(dC,"Initializing OfflineComponentProvider");var r=e.configuration;await t.initialize(r);let n=r.initialUser;e.setCredentialChangeListener(async e=>{n.isEqual(e)||(await tE(t.localStore,e),n=e)}),t.persistence.setDatabaseDeletedListener(()=>e.terminate()),e._offlineComponents=t}async function gC(e,r){e.asyncQueue.verifyOperationInProgress();var t=await mC(e);C(dC,"Initializing OnlineComponentProvider"),await r.initialize(t,e.configuration),e.setCredentialChangeListener(e=>h0(r.remoteStore,e)),e.setAppCheckTokenChangeListener((e,t)=>h0(r.remoteStore,t)),e._onlineComponents=r}async function mC(t){if(!t._offlineComponents)if(t._uninitializedComponentsProvider){C(dC,"Using user provided OfflineComponentProvider");try{await fC(t,t._uninitializedComponentsProvider._offline)}catch(e){var r=e;if(!("FirebaseError"===(n=r).name?n.code===A.FAILED_PRECONDITION||n.code===A.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&n instanceof DOMException)||22===n.code||20===n.code||11===n.code))throw r;Sm("Error using user provided cache. Falling back to memory cache: "+r),await fC(t,new rC)}}else C(dC,"Using default OfflineComponentProvider"),await fC(t,new nC(void 0));var n;return t._offlineComponents}async function vC(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(C(dC,"Using user provided OnlineComponentProvider"),await gC(e,e._uninitializedComponentsProvider._online)):(C(dC,"Using default OnlineComponentProvider"),await gC(e,new aC))),e._onlineComponents}function _C(e){return mC(e).then(e=>e.persistence)}function yC(e){return mC(e).then(e=>e.localStore)}function wC(e){return vC(e).then(e=>e.remoteStore)}function bC(e){return vC(e).then(e=>e.syncEngine)}async function IC(e){var t=await vC(e),r=t.eventManager;return r.onListen=(async function(e,t,r=!0){var n=Z0(e);let i;var s=n.ka.get(t);return i=s?(n.sharedClientState.addLocalQueryTarget(s.targetId),s.view.Na()):await M0(n,t,r,!0)}).bind(null,t.syncEngine),r.onUnlisten=(async function(e,t,r){let n=e,i=n.ka.get(t),s=n.qa.get(i.targetId);1<s.length?(n.qa.set(i.targetId,s.filter(e=>!mw(e,t))),n.ka.delete(t)):n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(i.targetId),n.sharedClientState.isActiveQueryTarget(i.targetId)||await oE(n.localStore,i.targetId,!1).then(()=>{n.sharedClientState.clearQueryState(i.targetId),r&&JE(n.remoteStore,i.targetId),W0(n,i.targetId)}).catch(ov)):(W0(n,i.targetId),await oE(n.localStore,i.targetId,!0))}).bind(null,t.syncEngine),r.onFirstRemoteStoreListen=(async function(e,t){await M0(Z0(e),t,!0,!1)}).bind(null,t.syncEngine),r.onLastRemoteStoreUnlisten=(async function(e,t){var r=e,n=r.ka.get(t),i=r.qa.get(n.targetId);r.isPrimaryClient&&1===i.length&&(r.sharedClientState.removeLocalQueryTarget(n.targetId),JE(r.remoteStore,n.targetId))}).bind(null,t.syncEngine),r}function TC(r){return r.asyncQueue.enqueue(async()=>{var e=await _C(r),t=await wC(r);return e.setNetworkEnabled(!1),(async e=>{var t=e;t.W_.add(0),await QE(t),t.j_.set("Offline")})(t)})}function EC(e,t){let r=new Nm;return e.asyncQueue.enqueueAndForget(async()=>(async(e,t,r)=>{try{var n=await((e,t)=>{let r=e;return r.persistence.runTransaction("read document","readonly",e=>r.localDocuments.getDocument(e,t))})(e,t);n.isFoundDocument()?r.resolve(n):n.isNoDocument()?r.resolve(null):r.reject(new N(A.UNAVAILABLE,"Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)"))}catch(e){n=f0(e,`Failed to get document '${t} from cache`);r.reject(n)}})(await yC(e),t,r)),r.promise}function CC(e,t,h={}){let u=new Nm;return e.asyncQueue.enqueueAndForget(async()=>{{var i=await IC(e),s=e.asyncQueue,a=t,o=h,l=u;let r=new lC({next:e=>{r.su(),s.enqueueAndForget(()=>I0(i,n));var t=e.docs.has(a);!t&&e.fromCache?l.reject(new N(A.UNAVAILABLE,"Failed to get document because the client is offline.")):t&&e.fromCache&&o&&"server"===o.source?l.reject(new N(A.UNAVAILABLE,'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')):l.resolve(e)},error:e=>l.reject(e)}),n=new E0(hw(a.path),r,{includeMetadataChanges:!0,Ta:!0});return b0(i,n)}}),u.promise}function kC(e,t){let r=new Nm;return e.asyncQueue.enqueueAndForget(async()=>(async(e,t,r)=>{try{var n=await lE(e,t,!0),i=new P0(t,n.gs),s=i.ba(n.documents),a=i.applyChanges(s,!1);r.resolve(a.snapshot)}catch(e){n=f0(e,`Failed to execute query '${t} against cache`);r.reject(n)}})(await yC(e),t,r)),r.promise}function SC(o,l,h={}){let u=new Nm;return o.asyncQueue.enqueueAndForget(async()=>{{var n=await IC(o),i=o.asyncQueue,e=l,s=h,a=u;let t=new lC({next:e=>{t.su(),i.enqueueAndForget(()=>I0(n,r)),e.fromCache&&"server"===s.source?a.reject(new N(A.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')):a.resolve(e)},error:e=>a.reject(e)}),r=new E0(e,t,{includeMetadataChanges:!0,Ta:!0});return b0(n,r)}}),u.promise}function AC(r,e){let n=new lC(e);return r.asyncQueue.enqueueAndForget(async()=>{return e=await IC(r),t=n,e.ia.add(t),void t.next();var e,t}),()=>{n.su(),r.asyncQueue.enqueueAndForget(async()=>{var e,t;e=await IC(r),t=n,e.ia.delete(t)})}}function NC(e,t,r,n){r=r,t=UE(t),s="string"==typeof r?Um().encode(r):r,r=((e,t)=>{if(e instanceof Uint8Array)return oC(e,t);if(e instanceof ArrayBuffer)return oC(new Uint8Array(e),t);if(e instanceof ReadableStream)return e.getReader();throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream")})(s),t=t;let i=new hC(r,t);var s;e.asyncQueue.enqueueAndForget(async()=>{tC(await bC(e),i,n)})}function RC(n,i){return n.asyncQueue.enqueue(async()=>{{var e=await yC(n),r=i;let t=e;return t.persistence.runTransaction("Get named query","readonly",e=>t.Yr.getNamedQuery(e,r))}})}function PC(e){var t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t}let DC=new Map;function xC(e,t,r){if(!r)throw new N(A.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function OC(e,t,r,n){if(!0===t&&!0===n)throw new N(A.INVALID_ARGUMENT,e+` and ${r} cannot be used together.`)}function LC(e){if(!x.isDocumentKey(e))throw new N(A.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function MC(e){if(x.isDocumentKey(e))throw new N(A.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function FC(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":k()}function q(e,t){if((e="_delegate"in e?e._delegate:e)instanceof t)return e;if(t.name===e.constructor.name)throw new N(A.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");var r=FC(e);throw new N(A.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: `+r)}function UC(e,t){if(t<=0)throw new N(A.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}let VC="firestore.googleapis.com";class qC{constructor(e){var t;if(void 0===e.host){if(void 0!==e.ssl)throw new N(A.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=VC,this.ssl=!0}else this.host=e.host,this.ssl=null==(t=e.ssl)||t;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new N(A.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}OC("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:void 0===e.experimentalAutoDetectLongPolling?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=PC(null!=(t=e.experimentalLongPollingOptions)?t:{});var r=this.experimentalLongPollingOptions;if(void 0!==r.timeoutSeconds){if(isNaN(r.timeoutSeconds))throw new N(A.INVALID_ARGUMENT,`invalid long polling timeout: ${r.timeoutSeconds} (must not be NaN)`);if(r.timeoutSeconds<5)throw new N(A.INVALID_ARGUMENT,`invalid long polling timeout: ${r.timeoutSeconds} (minimum allowed value is 5)`);if(30<r.timeoutSeconds)throw new N(A.INVALID_ARGUMENT,`invalid long polling timeout: ${r.timeoutSeconds} (maximum allowed value is 30)`)}this.useFetchStreams=!!e.useFetchStreams}isEqual(e){return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&(t=this.experimentalLongPollingOptions,r=e.experimentalLongPollingOptions,t.timeoutSeconds===r.timeoutSeconds)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams;var t,r}}class jC{constructor(e,t,r,n){this._authCredentials=e,this._appCheckCredentials=t,this._databaseId=r,this._app=n,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new qC({}),this._settingsFrozen=!1,this._terminateTask="notTerminated"}get app(){if(this._app)return this._app;throw new N(A.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available")}get _initialized(){return this._settingsFrozen}get _terminated(){return"notTerminated"!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new N(A.FAILED_PRECONDITION,"Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");this._settings=new qC(e),void 0!==e.credentials&&(this._authCredentials=(e=>{if(!e)return new Pm;switch(e.type){case"firstParty":return new Lm(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new N(A.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}})(e.credentials))}_getSettings(){return this._settings}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return"notTerminated"===this._terminateTask&&(this._terminateTask=this._terminate()),this._terminateTask}async _restart(){"notTerminated"===this._terminateTask?await this._terminate():this._terminateTask="notTerminated"}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return e=this,(t=DC.get(e))&&(C("ComponentProvider","Removing Datastore"),DC.delete(e),t.terminate()),Promise.resolve();var e,t}}class BC{constructor(e,t,r){this.converter=t,this._query=r,this.type="query",this.firestore=e}withConverter(e){return new BC(this.firestore,e,this._query)}}class zC{constructor(e,t,r){this.converter=t,this._key=r,this.type="document",this.firestore=e}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new KC(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new zC(this.firestore,e,this._key)}}class KC extends BC{constructor(e,t,r){super(e,t,hw(r)),this._path=r,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){var e=this._path.popLast();return e.isEmpty()?null:new zC(this.firestore,null,new x(e))}withConverter(e){return new KC(this.firestore,e,this._path)}}function WC(e,t,...r){var n;if(e=w(e),xC("collection","path",t),e instanceof jC)return MC(n=D.fromString(t,...r)),new KC(e,null,n);if(e instanceof zC||e instanceof KC)return MC(n=e._path.child(D.fromString(t,...r))),new KC(e.firestore,null,n);throw new N(A.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore")}function HC(e,t,...r){var n;if(e=w(e),xC("doc","path",t=1===arguments.length?Vm.newId():t),e instanceof jC)return LC(n=D.fromString(t,...r)),new zC(e,null,new x(n));if(e instanceof zC||e instanceof KC)return LC(n=e._path.child(D.fromString(t,...r))),new zC(e.firestore,e instanceof KC?e.converter:null,new x(n));throw new N(A.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore")}function GC(e,t){return e=w(e),t=w(t),(e instanceof zC||e instanceof KC)&&(t instanceof zC||t instanceof KC)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter}function $C(e,t){return e=w(e),t=w(t),e instanceof BC&&t instanceof BC&&e.firestore===t.firestore&&mw(e._query,t._query)&&e.converter===t.converter}let QC="AsyncQueue";class YC{constructor(e=Promise.resolve()){this.Vu=[],this.mu=!1,this.fu=[],this.gu=null,this.pu=!1,this.yu=!1,this.wu=[],this.a_=new VE(this,"async_queue_retry"),this.Su=()=>{var e=FE();e&&C(QC,"Visibility state changed to "+e.visibilityState),this.a_.t_()},this.bu=e;var t=FE();t&&"function"==typeof t.addEventListener&&t.addEventListener("visibilitychange",this.Su)}get isShuttingDown(){return this.mu}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.Du(),this.vu(e)}enterRestrictedMode(e){var t;this.mu||(this.mu=!0,this.yu=e||!1,(t=FE())&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.Su))}enqueue(e){if(this.Du(),this.mu)return new Promise(()=>{});let t=new Nm;return this.vu(()=>this.mu&&this.yu?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.Vu.push(e),this.Cu()))}async Cu(){if(0!==this.Vu.length){try{await this.Vu[0](),this.Vu.shift(),this.a_.reset()}catch(e){if(!fv(e))throw e;C(QC,"Operation failed with retryable error: "+e)}0<this.Vu.length&&this.a_.Xo(()=>this.Cu())}}vu(e){var t=this.bu.then(()=>(this.pu=!0,e().catch(e=>{throw this.gu=e,this.pu=!1,km("INTERNAL UNHANDLED ERROR: ",(e=>{let t=e.message||"";return t=e.stack?e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack:t})(e)),e}).then(e=>(this.pu=!1,e))));return this.bu=t}enqueueAfterDelay(e,t,r){this.Du(),-1<this.wu.indexOf(e)&&(t=0);var n=p0.createAndSchedule(this,e,t,r,e=>this.Fu(e));return this.fu.push(n),n}Du(){this.gu&&k()}verifyOperationInProgress(){}async Mu(){for(var e;await(e=this.bu),e!==this.bu;);}xu(e){for(var t of this.fu)if(t.timerId===e)return!0;return!1}Ou(t){return this.Mu().then(()=>{this.fu.sort((e,t)=>e.targetTimeMs-t.targetTimeMs);for(var e of this.fu)if(e.skipDelay(),"all"!==t&&e.timerId===t)break;return this.Mu()})}Nu(e){this.wu.push(e)}Fu(e){var t=this.fu.indexOf(e);this.fu.splice(t,1)}}function JC(t){var r=t,t=["next","error","complete"];if("object"==typeof r&&null!==r){var n=r;for(let e of t)if(e in n&&"function"==typeof n[e])return 1}}class XC{constructor(){this._progressObserver={},this._taskCompletionResolver=new Nm,this._lastProgress={taskState:"Running",totalBytes:0,totalDocuments:0,bytesLoaded:0,documentsLoaded:0}}onProgress(e,t,r){this._progressObserver={next:e,error:t,complete:r}}catch(e){return this._taskCompletionResolver.promise.catch(e)}then(e,t){return this._taskCompletionResolver.promise.then(e,t)}_completeWith(e){this._updateProgress(e),this._progressObserver.complete&&this._progressObserver.complete(),this._taskCompletionResolver.resolve(e)}_failWith(e){this._lastProgress.taskState="Error",this._progressObserver.next&&this._progressObserver.next(this._lastProgress),this._progressObserver.error&&this._progressObserver.error(e),this._taskCompletionResolver.reject(e)}_updateProgress(e){this._lastProgress=e,this._progressObserver.next&&this._progressObserver.next(e)}}var ZC,ek;class tk extends jC{constructor(e,t,r,n){super(e,t,r,n),this.type="firestore",this._queue=new YC,this._persistenceKey=(null==n?void 0:n.name)||"[DEFAULT]"}async _terminate(){var e;this._firestoreClient&&(e=this._firestoreClient.terminate(),this._queue=new YC(e),this._firestoreClient=void 0,await e)}}function rk(e){if(e._terminated)throw new N(A.FAILED_PRECONDITION,"The client has already been terminated.");return e._firestoreClient||nk(e),e._firestoreClient}function nk(e){var t,r,n,i,s,a=e._freezeSettings(),o=(i=e._databaseId,t=(null==(o=e._app)?void 0:o.options.appId)||"",r=e._persistenceKey,n=a,new iy(i,t,r,n.host,n.ssl,n.experimentalForceLongPolling,n.experimentalAutoDetectLongPolling,PC(n.experimentalLongPollingOptions),n.useFetchStreams));e._componentsProvider||null!=(s=a.localCache)&&s._offlineComponentProvider&&null!=(s=a.localCache)&&s._onlineComponentProvider&&(e._componentsProvider={_offline:a.localCache._offlineComponentProvider,_online:a.localCache._onlineComponentProvider}),e._firestoreClient=new pC(e._authCredentials,e._appCheckCredentials,e._queue,o,e._componentsProvider&&(i=e._componentsProvider,s=null==i?void 0:i._online.build(),{_offline:null==i?void 0:i._offline.build(s),_online:s}))}function ik(e,t,r){if((e=q(e,tk))._firestoreClient||e._terminated)throw new N(A.FAILED_PRECONDITION,"Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.");if(e._componentsProvider||e._getSettings().localCache)throw new N(A.FAILED_PRECONDITION,"SDK cache is already specified.");e._componentsProvider={_online:t,_offline:r},nk(e)}function sk(r){if(r._initialized&&!r._terminated)throw new N(A.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");let n=new Nm;return r._queue.enqueueAndForgetEvenWhileRestricted(async()=>{try{e=GT(r._databaseId,r._persistenceKey),await(uv.D()?(t=e+"main",void await uv.delete(t)):Promise.resolve()),n.resolve()}catch(e){n.reject(e)}var e,t}),n.promise}function ak(e){return(r=rk(e=q(e,tk))).asyncQueue.enqueue(async()=>{var e=await _C(r),t=await wC(r);return e.setNetworkEnabled(!0),(e=t).W_.delete(0),$E(e)});var r}class ok{constructor(e){this._byteString=e}static fromBase64String(e){try{return new ok(H_.fromBase64String(e))}catch(e){throw new N(A.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new ok(H_.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(e){return this._byteString.isEqual(e._byteString)}}class lk{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new N(A.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new $m(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class hk{constructor(e){this._methodName=e}}class uk{constructor(e,t){if(!isFinite(e)||e<-90||90<e)throw new N(A.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||180<t)throw new N(A.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+t);this._lat=e,this._long=t}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}toJSON(){return{latitude:this._lat,longitude:this._long}}_compareTo(e){return R(this._lat,e._lat)||R(this._long,e._long)}}class ck{constructor(e){this._values=(e||[]).map(e=>e)}toArray(){return this._values.map(e=>e)}isEqual(e){var t=this._values,r=e._values;if(t.length!==r.length)return!1;for(let n=0;n<t.length;++n)if(t[n]!==r[n])return!1;return!0}}let dk=/^__.*__$/;class pk{constructor(e,t,r){this.data=e,this.fieldMask=t,this.fieldTransforms=r}toMutation(e,t){return null!==this.fieldMask?new Zw(e,this.data,this.fieldMask,t,this.fieldTransforms):new Xw(e,this.data,t,this.fieldTransforms)}}class fk{constructor(e,t,r){this.data=e,this.fieldMask=t,this.fieldTransforms=r}toMutation(e,t){return new Zw(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function gk(e){switch(e){case 0:case 2:case 1:return 1;case 3:case 4:return;default:throw k()}}class mk{constructor(e,t,r,n,i,s){this.settings=e,this.databaseId=t,this.serializer=r,this.ignoreUndefinedProperties=n,void 0===i&&this.Bu(),this.fieldTransforms=i||[],this.fieldMask=s||[]}get path(){return this.settings.path}get Lu(){return this.settings.Lu}ku(e){return new mk(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}qu(e){var t=null==(t=this.path)?void 0:t.child(e),t=this.ku({path:t,Qu:!1});return t.$u(e),t}Uu(e){var t=null==(t=this.path)?void 0:t.child(e),t=this.ku({path:t,Qu:!1});return t.Bu(),t}Ku(e){return this.ku({path:void 0,Qu:!0})}Wu(e){return Mk(e,this.settings.methodName,this.settings.Gu||!1,this.path,this.settings.zu)}contains(t){return void 0!==this.fieldMask.find(e=>t.isPrefixOf(e))||void 0!==this.fieldTransforms.find(e=>t.isPrefixOf(e.field))}Bu(){if(this.path)for(let e=0;e<this.path.length;e++)this.$u(this.path.get(e))}$u(e){if(0===e.length)throw this.Wu("Document fields must not be empty");if(gk(this.Lu)&&dk.test(e))throw this.Wu('Document fields cannot begin and end with "__"')}}class vk{constructor(e,t,r){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=r||UE(e)}ju(e,t,r,n=!1){return new mk({Lu:e,methodName:t,zu:r,path:$m.emptyPath(),Qu:!1,Gu:n},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function _k(e){var t=e._freezeSettings(),r=UE(e._databaseId);return new vk(e._databaseId,!!t.ignoreUndefinedProperties,r)}function yk(e,n,i,t,r,s={}){var a=e.ju(s.merge||s.mergeFields?2:0,n,i,r),o=(Dk("Data must be an object, but it was:",a,t),Rk(t,a));let l,h;if(s.merge)l=new K_(a.fieldMask),h=a.fieldTransforms;else if(s.mergeFields){let t=[];for(let r of s.mergeFields){let e=xk(n,r,i);if(!a.contains(e))throw new N(A.INVALID_ARGUMENT,`Field '${e}' is specified in your field mask but missing from your input data.`);Fk(t,e)||t.push(e)}l=new K_(t),h=a.fieldTransforms.filter(e=>l.covers(e.field))}else l=null,h=a.fieldTransforms;return new pk(new Dy(o),l,h)}class wk extends hk{_toFieldTransform(e){if(2!==e.Lu)throw 1===e.Lu?e.Wu(this._methodName+"() can only appear at the top level of your update data"):e.Wu(this._methodName+"() cannot be used with set() unless you pass {merge:true}");return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof wk}}function bk(e,t,r){return new mk({Lu:3,zu:t.settings.zu,methodName:e._methodName,Qu:r},t.databaseId,t.serializer,t.ignoreUndefinedProperties)}class Ik extends hk{_toFieldTransform(e){return new Kw(e.path,new Mw)}isEqual(e){return e instanceof Ik}}class Tk extends hk{constructor(e,t){super(e),this.Hu=t}_toFieldTransform(e){let t=bk(this,e,!0),r=this.Hu.map(e=>Nk(e,t)),n=new Fw(r);return new Kw(e.path,n)}isEqual(e){return e instanceof Tk&&Ie(this.Hu,e.Hu)}}class Ek extends hk{constructor(e,t){super(e),this.Hu=t}_toFieldTransform(e){let t=bk(this,e,!0),r=this.Hu.map(e=>Nk(e,t)),n=new Vw(r);return new Kw(e.path,n)}isEqual(e){return e instanceof Ek&&Ie(this.Hu,e.Hu)}}class Ck extends hk{constructor(e,t){super(e),this.Ju=t}_toFieldTransform(e){var t=new jw(e.serializer,xw(e.serializer,this.Ju));return new Kw(e.path,t)}isEqual(e){return e instanceof Ck&&this.Ju===e.Ju}}function kk(e,i,s,t){let a=e.ju(1,i,s),o=(Dk("Data must be an object, but it was:",a,t),[]),l=Dy.empty();U_(t,(e,t)=>{var r=Lk(i,e,s),n=(t=w(t),a.Uu(r));if(t instanceof wk)o.push(r);else{let e=Nk(t,n);null!=e&&(o.push(r),l.set(r,e))}});var r=new K_(o);return new fk(l,r,a.fieldTransforms)}function Sk(e,t,r,n,i,s){var a=e.ju(1,t,r),o=[xk(t,n,r)],l=[i];if(s.length%2!=0)throw new N(A.INVALID_ARGUMENT,`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let p=0;p<s.length;p+=2)o.push(xk(t,s[p])),l.push(s[p+1]);var h=[],u=Dy.empty();for(let f=o.length-1;0<=f;--f)if(!Fk(h,o[f])){let t=o[f];var c=w(l[f]);let r=a.Uu(t);if(c instanceof wk)h.push(t);else{let e=Nk(c,r);null!=e&&(h.push(t),u.set(t,e))}}var d=new K_(h);return new fk(u,d,a.fieldTransforms)}function Ak(e,t,r,n=!1){return Nk(r,e.ju(n?4:3,t))}function Nk(e,r){if(Pk(e=w(e)))return Dk("Unsupported field value:",r,e),Rk(e,r);if(e instanceof hk){{var t=e;var n=r;if(!gk(n.Lu))throw n.Wu(t._methodName+"() can only be used with update() and set()");if(!n.path)throw n.Wu(t._methodName+"() is not currently supported inside arrays");var i=t._toFieldTransform(n);i&&n.fieldTransforms.push(i)}return null}if(void 0===e&&r.ignoreUndefinedProperties)return null;if(r.path&&r.fieldMask.push(r.path),e instanceof Array){if(r.settings.Qu&&4!==r.Lu)throw r.Wu("Nested arrays are not supported");{var s,a=r,o=[];let t=0;for(s of e){let e=Nk(s,a.Ku(t));null==e&&(e={nullValue:"NULL_VALUE"}),o.push(e),t++}return{arrayValue:{values:o}}}}var l,t=e,n=r;if(null===(t=w(t)))return{nullValue:"NULL_VALUE"};if("number"==typeof t)return xw(n.serializer,t);if("boolean"==typeof t)return{booleanValue:t};if("string"==typeof t)return{stringValue:t};if(t instanceof Date)return h=Km.fromDate(t),{timestampValue:Rb(n.serializer,h)};if(t instanceof Km)return h=new Km(t.seconds,1e3*Math.floor(t.nanoseconds/1e3)),{timestampValue:Rb(n.serializer,h)};if(t instanceof uk)return{geoPointValue:{latitude:t.latitude,longitude:t.longitude}};if(t instanceof ok)return{bytesValue:Pb(n.serializer,t._byteString)};if(t instanceof zC){var h=n.databaseId,i=t.firestore._databaseId;if(i.isEqual(h))return{referenceValue:xb(t.firestore._databaseId||n.databaseId,t._key.path)};throw n.Wu(`Document reference is for database ${i.projectId}/${i.database} but should be for database ${h.projectId}/`+h.database)}if(t instanceof ck)return e=t,l=n,{mapValue:{fields:{[oy]:{stringValue:uy},[cy]:{arrayValue:{values:e.toArray().map(e=>{if("number"!=typeof e)throw l.Wu("VectorValues must only contain numeric values.");return Pw(l.serializer,e)})}}}}};throw n.Wu("Unsupported field value: "+FC(t))}function Rk(e,n){let i={};return V_(e)?n.path&&0<n.path.length&&n.fieldMask.push(n.path):U_(e,(e,t)=>{var r=Nk(t,n.qu(e));null!=r&&(i[e]=r)}),{mapValue:{fields:i}}}function Pk(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof Km||e instanceof uk||e instanceof ok||e instanceof zC||e instanceof hk||e instanceof ck)}function Dk(e,t,r){var n,i;if(!Pk(r)||"object"!=typeof(i=r)||null===i||Object.getPrototypeOf(i)!==Object.prototype&&null!==Object.getPrototypeOf(i))throw"an object"===(n=FC(r))?t.Wu(e+" a custom object"):t.Wu(e+" "+n)}function xk(e,t,r){if((t=w(t))instanceof lk)return t._internalPath;if("string"==typeof t)return Lk(e,t);throw Mk("Field path arguments must be of type string or ",e,!1,void 0,r)}let Ok=new RegExp("[~\\*/\\[\\]]");function Lk(t,r,n){if(0<=r.search(Ok))throw Mk(`Invalid field path (${r}). Paths must not contain '~', '*', '/', '[', or ']'`,t,!1,void 0,n);try{return new lk(...r.split("."))._internalPath}catch(e){throw Mk(`Invalid field path (${r}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,t,!1,void 0,n)}}function Mk(e,t,r,n,i){var s=n&&!n.isEmpty(),a=void 0!==i;let o=`Function ${t}() called with invalid data`,l=(r&&(o+=" (via `toFirestore()`)"),o+=". ","");return(s||a)&&(l+=" (found",s&&(l+=" in field "+n),a&&(l+=" in document "+i),l+=")"),new N(A.INVALID_ARGUMENT,o+e+l)}function Fk(e,t){return e.some(e=>e.isEqual(t))}class Uk{constructor(e,t,r,n,i){this._firestore=e,this._userDataWriter=t,this._key=r,this._document=n,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new zC(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){var e;if(this._document)return this._converter?(e=new Vk(this._firestore,this._userDataWriter,this._key,this._document,null),this._converter.fromFirestore(e)):this._userDataWriter.convertValue(this._document.data.value)}get(e){if(this._document){var t=this._document.data.field(qk("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class Vk extends Uk{data(){return super.data()}}function qk(e,t){return"string"==typeof t?Lk(e,t):(t instanceof lk?t:t._delegate)._internalPath}function jk(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new N(A.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class Bk{}class zk extends Bk{}function Kk(e,t,...r){let n=[];t instanceof Bk&&n.push(t);var t=n=n.concat(r),i=t.filter(e=>!1).length,s=t.filter(e=>e instanceof Wk).length;if(1<i||0<i&&0<s)throw new N(A.INVALID_ARGUMENT,"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.");for(let t of n)e=t._apply(e);return e}class Wk extends zk{constructor(e,t,r){super(),this._field=e,this._op=t,this._value=r,this.type="where"}static _create(e,t,r){return new Wk(e,t,r)}_apply(e){var t=this._parse(e);return Zk(e._query,t),new BC(e.firestore,e.converter,fw(e._query,t))}_parse(e){var t=_k(e.firestore);{var n=e._query,i="where",s=t,a=e.firestore._databaseId,o=(e=this._field,this._op),l=this._value;let r;if(e.isKeyField()){if("array-contains"===o||"array-contains-any"===o)throw new N(A.INVALID_ARGUMENT,`Invalid Query. You can't perform '${o}' queries on documentId().`);if("in"===o||"not-in"===o){Xk(l,o);let e=[];for(let t of l)e.push(Jk(a,n,t));r={arrayValue:{values:e}}}else r=Jk(a,n,l)}else"in"!==o&&"not-in"!==o&&"array-contains-any"!==o||Xk(l,o),r=Ak(s,i,l,"in"===o||"not-in"===o);return F.create(e,o,r)}}}(class extends Bk{});class Hk extends zk{constructor(e,t){super(),this._field=e,this._direction=t,this.type="orderBy"}static _create(e,t){return new Hk(e,t)}_apply(e){var t=((e,t,r)=>{if(null!==e.startAt)throw new N(A.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new N(A.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");return new Fy(t,r)})(e._query,this._field,this._direction);return new BC(e.firestore,e.converter,(t=(e=e._query).explicitOrderBy.concat([t]),new ow(e.path,e.collectionGroup,t,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)))}}class Gk extends zk{constructor(e,t,r){super(),this.type=e,this._limit=t,this._limitType=r}static _create(e,t,r){return new Gk(e,t,r)}_apply(e){return new BC(e.firestore,e.converter,gw(e._query,this._limit,this._limitType))}}class $k extends zk{constructor(e,t,r){super(),this.type=e,this._docOrFields=t,this._inclusive=r}static _create(e,t,r){return new $k(e,t,r)}_apply(e){var t,r=Yk(e,this.type,this._docOrFields,this._inclusive);return new BC(e.firestore,e.converter,(e=e._query,t=r,new ow(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,t,e.endAt)))}}class Qk extends zk{constructor(e,t,r){super(),this.type=e,this._docOrFields=t,this._inclusive=r}static _create(e,t,r){return new Qk(e,t,r)}_apply(e){var t,r=Yk(e,this.type,this._docOrFields,this._inclusive);return new BC(e.firestore,e.converter,(e=e._query,t=r,new ow(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,t)))}}function Yk(e,r,n,i){if(n[0]=w(n[0]),n[0]instanceof Uk){var s=e._query,a=e.firestore._databaseId,o=r,l=n[0]._document,h=i;if(!l)throw new N(A.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${o}().`);var u=[];for(let t of dw(s))if(t.field.isKeyField())u.push(wy(a,l.key));else{let e=l.data.field(t.field);if(ty(e))throw new N(A.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+t.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(null===e){let e=t.field.canonicalString();throw new N(A.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${e}' (used as the orderBy) does not exist.`)}u.push(e)}return new Oy(u,h)}var t=_k(e.firestore),c=e._query,d=e.firestore._databaseId,p=t,f=r,g=n,o=i,m=c.explicitOrderBy;if(g.length>m.length)throw new N(A.INVALID_ARGUMENT,`Too many arguments provided to ${f}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);var v=[];for(let y=0;y<g.length;y++){var _=g[y];if(m[y].field.isKeyField()){if("string"!=typeof _)throw new N(A.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${f}(), but got a `+typeof _);if(!cw(c)&&-1!==_.indexOf("/"))throw new N(A.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${f}() must be a plain document ID, but '${_}' contains a slash.`);let e=c.path.child(D.fromString(_));if(!x.isDocumentKey(e))throw new N(A.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${f}() must result in a valid document path, but '${e}' is not because it contains an odd number of segments.`);let t=new x(e);v.push(wy(d,t))}else{let e=Ak(p,f,_);v.push(e)}}return new Oy(v,o)}function Jk(e,t,r){if("string"==typeof(r=w(r))){if(""===r)throw new N(A.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!cw(t)&&-1!==r.indexOf("/"))throw new N(A.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${r}' contains a '/' character.`);var n=t.path.child(D.fromString(r));if(x.isDocumentKey(n))return wy(e,new x(n));throw new N(A.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${n}' is not because it has an odd number of segments (${n.length}).`)}if(r instanceof zC)return wy(e,r._key);throw new N(A.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${FC(r)}.`)}function Xk(e,t){if(!Array.isArray(e)||0===e.length)throw new N(A.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`)}function Zk(e,t){var r=((t,r)=>{for(var n of t)for(let e of n.getFlattenedFilters())if(0<=r.indexOf(e.op))return e.op;return null})(e.filters,(e=>{switch(e){case"!=":return["!=","not-in"];case"array-contains-any":case"in":return["not-in"];case"not-in":return["array-contains-any","in","not-in","!="];default:return[]}})(t.op));if(null!==r)throw r===t.op?new N(A.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new N(A.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${r.toString()}' filters.`)}class eS{convertValue(e,t="none"){switch(py(e)){case 0:return null;case 1:return e.booleanValue;case 2:return Q_(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,t);case 5:return e.stringValue;case 6:return this.convertBytes(Y_(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,t);case 11:return this.convertObject(e.mapValue,t);case 10:return this.convertVectorValue(e.mapValue);default:throw k()}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,r="none"){let n={};return U_(e,(e,t)=>{n[e]=this.convertValue(t,r)}),n}convertVectorValue(e){var t=null==(t=null==(t=null==(t=e.fields)?void 0:t[cy].arrayValue)?void 0:t.values)?void 0:t.map(e=>Q_(e.doubleValue));return new ck(t)}convertGeoPoint(e){return new uk(Q_(e.latitude),Q_(e.longitude))}convertArray(e,t){return(e.values||[]).map(e=>this.convertValue(e,t))}convertServerTimestamp(e,t){switch(t){case"previous":var r=ry(e);return null==r?null:this.convertValue(r,t);case"estimate":return this.convertTimestamp(ny(e));default:return null}}convertTimestamp(e){var t=$_(e);return new Km(t.seconds,t.nanos)}convertDocumentKey(e,t){var r=D.fromString(e),n=(S(tI(r)),new ay(r.get(1),r.get(3))),r=new x(r.popFirst(5));return n.isEqual(t)||km(`Document ${r} contains a document reference within a different database (${n.projectId}/${n.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),r}}function tS(e,t,r){return e?r&&(r.merge||r.mergeFields)?e.toFirestore(t,r):e.toFirestore(t):t}class rS extends eS{constructor(e){super(),this.firestore=e}convertBytes(e){return new ok(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new zC(this.firestore,null,t)}}class nS{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class iS extends Uk{constructor(e,t,r,n,i,s){super(e,t,r,n,s),this._firestore=e,this._firestoreImpl=e,this.metadata=i}exists(){return super.exists()}data(e={}){var t;if(this._document)return this._converter?(t=new sS(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null),this._converter.fromFirestore(t,e)):this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}get(e,t={}){if(this._document){var r=this._document.data.field(qk("DocumentSnapshot.get",e));if(null!==r)return this._userDataWriter.convertValue(r,t.serverTimestamps)}}}class sS extends iS{data(e={}){return super.data(e)}}class aS{constructor(e,t,r,n){this._firestore=e,this._userDataWriter=t,this._snapshot=n,this.metadata=new nS(n.hasPendingWrites,n.fromCache),this.query=r}get docs(){let t=[];return this.forEach(e=>t.push(e)),t}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(t,r){this._snapshot.docs.forEach(e=>{t.call(r,new sS(this._firestore,this._userDataWriter,e.key,e,new nS(this._snapshot.mutatedKeys.has(e.key),this._snapshot.fromCache),this.query.converter))})}docChanges(e={}){var t=!!e.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new N(A.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===t||(this._cachedChanges=((s,t)=>{if(s._snapshot.oldDocs.isEmpty()){let r=0;return s._snapshot.docChanges.map(e=>{var t=new sS(s._firestore,s._userDataWriter,e.doc.key,e.doc,new nS(s._snapshot.mutatedKeys.has(e.doc.key),s._snapshot.fromCache),s.query.converter);return e.doc,{type:"added",doc:t,oldIndex:-1,newIndex:r++}})}{let i=s._snapshot.oldDocs;return s._snapshot.docChanges.filter(e=>t||3!==e.type).map(e=>{var t=new sS(s._firestore,s._userDataWriter,e.doc.key,e.doc,new nS(s._snapshot.mutatedKeys.has(e.doc.key),s._snapshot.fromCache),s.query.converter);let r=-1,n=-1;return 0!==e.type&&(r=i.indexOf(e.doc.key),i=i.delete(e.doc.key)),1!==e.type&&(i=i.add(e.doc),n=i.indexOf(e.doc.key)),{type:(e=>{switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return k()}})(e.type),doc:t,oldIndex:r,newIndex:n}})}})(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function oS(e,t){return e instanceof iS&&t instanceof iS?e._firestore===t._firestore&&e._key.isEqual(t._key)&&(null===e._document?null===t._document:e._document.isEqual(t._document))&&e._converter===t._converter:e instanceof aS&&t instanceof aS&&e._firestore===t._firestore&&$C(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)}class lS extends eS{constructor(e){super(),this.firestore=e}convertBytes(e){return new ok(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new zC(this.firestore,null,t)}}function hS(e,t,r){e=q(e,zC);var n=q(e.firestore,tk),i=tS(e.converter,t,r);return dS(n,[yk(_k(n),"setDoc",e._key,i,null!==e.converter,r).toMutation(e._key,Hw.none())])}function uS(e,t,r,...n){e=q(e,zC);var i=q(e.firestore,tk),s=_k(i);return dS(i,[("string"==typeof(t=w(t))||t instanceof lk?Sk(s,"updateDoc",e._key,t,r,n):kk(s,"updateDoc",e._key,t)).toMutation(e._key,Hw.exists(!0))])}function cS(n,...i){var t,r;n=w(n);let e={includeMetadataChanges:!1,source:"default"},s=0;"object"!=typeof i[s]||JC(i[s])||(e=i[s],s++);var a={includeMetadataChanges:e.includeMetadataChanges,source:e.source};if(JC(i[s])){let e=i[s];i[s]=null==(r=e.next)?void 0:r.bind(e),i[s+1]=null==(t=e.error)?void 0:t.bind(e),i[s+2]=null==(r=e.complete)?void 0:r.bind(e)}let o,l,h;if(n instanceof zC)l=q(n.firestore,tk),h=hw(n._key.path),o={next:e=>{i[s]&&i[s](pS(l,n,e))},error:i[s+1],complete:i[s+2]};else{let t=q(n,BC),r=(l=q(t.firestore,tk),h=t._query,new lS(l));o={next:e=>{i[s]&&i[s](new aS(l,r,t,e))},error:i[s+1],complete:i[s+2]},jk(n._query)}{var u=rk(l),c=h,d=a,p=o;let e=new lC(p),t=new E0(c,e,d);return u.asyncQueue.enqueueAndForget(async()=>b0(await IC(u),t)),()=>{e.su(),u.asyncQueue.enqueueAndForget(async()=>I0(await IC(u),t))}}}function dS(t,r){{var n=rk(t),i=r;let e=new Nm;return n.asyncQueue.enqueueAndForget(async()=>U0(await bC(n),i,e)),e.promise}}function pS(e,t,r){var n=r.docs.get(t._key),i=new lS(e);return new iS(e,i,t._key,n,new nS(r.hasPendingWrites,r.fromCache),t.converter)}let fS={maxAttempts:5};class gS{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=_k(e)}set(e,t,r){this._verifyNotCommitted();var n=mS(e,this._firestore),i=tS(n.converter,t,r),i=yk(this._dataReader,"WriteBatch.set",n._key,i,null!==n.converter,r);return this._mutations.push(i.toMutation(n._key,Hw.none())),this}update(e,t,r,...n){this._verifyNotCommitted();var i=mS(e,this._firestore),s="string"==typeof(t=w(t))||t instanceof lk?Sk(this._dataReader,"WriteBatch.update",i._key,t,r,n):kk(this._dataReader,"WriteBatch.update",i._key,t);return this._mutations.push(s.toMutation(i._key,Hw.exists(!0))),this}delete(e){this._verifyNotCommitted();var t=mS(e,this._firestore);return this._mutations=this._mutations.concat(new nb(t._key,Hw.none())),this}commit(){return this._verifyNotCommitted(),this._committed=!0,0<this._mutations.length?this._commitHandler(this._mutations):Promise.resolve()}_verifyNotCommitted(){if(this._committed)throw new N(A.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function mS(e,t){if((e=w(e)).firestore!==t)throw new N(A.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}class vS extends class{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=_k(e)}get(e){let r=mS(e,this._firestore),n=new rS(this._firestore);return this._transaction.lookup([r._key]).then(e=>{if(!e||1!==e.length)return k();var t=e[0];if(t.isFoundDocument())return new Uk(this._firestore,n,t.key,t,r.converter);if(t.isNoDocument())return new Uk(this._firestore,n,r._key,null,r.converter);throw k()})}set(e,t,r){var n=mS(e,this._firestore),i=tS(n.converter,t,r),i=yk(this._dataReader,"Transaction.set",n._key,i,null!==n.converter,r);return this._transaction.set(n._key,i),this}update(e,t,r,...n){var i=mS(e,this._firestore),s="string"==typeof(t=w(t))||t instanceof lk?Sk(this._dataReader,"Transaction.update",i._key,t,r,n):kk(this._dataReader,"Transaction.update",i._key,t);return this._transaction.update(i._key,s),this}delete(e){var t=mS(e,this._firestore);return this._transaction.delete(t._key),this}}{constructor(e,t){super(e,t),this._firestore=e}get(e){let t=mS(e,this._firestore),r=new lS(this._firestore);return super.get(e).then(e=>new iS(this._firestore,r,t._key,e._document,new nS(!1,!1),t.converter))}}function _S(r,n,e){r=q(r,tk);var i=Object.assign(Object.assign({},fS),e);if(i.maxAttempts<1)throw new N(A.INVALID_ARGUMENT,"Max attempts must be at least 1");{var s=rk(r),a=e=>n(new vS(r,e)),o=i;let t=new Nm;return s.asyncQueue.enqueueAndForget(async()=>{var e=await vC(s).then(e=>e.datastore);new cC(s.asyncQueue,e,o,a,t).Iu()}),t.promise}}ZC=!0,WD=Dt,Tm=WD,Ct(new u("firestore",(e,{instanceIdentifier:t,options:r})=>{var n=e.getProvider("app").getImmediate(),n=new tk(new xm(e.getProvider("auth-internal")),new Fm(n,e.getProvider("app-check-internal")),((e,t)=>{if(Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))return new ay(e.options.projectId,t);throw new N(A.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.')})(n,t),n);return r=Object.assign({useFetchStreams:ZC},r),n._setSettings(r),n},"PUBLIC").setMultipleInstances(!0)),d(bm,"4.7.7",QN),d(bm,"4.7.7","esm2017");function yS(e,t){if(void 0===t)return{merge:!1};if(void 0!==t.mergeFields&&void 0!==t.merge)throw new N("invalid-argument",`Invalid options passed to function ${e}(): You cannot `+'specify both "merge" and "mergeFields".');return t}function wS(){if("undefined"==typeof Uint8Array)throw new N("unimplemented","Uint8Arrays are not available in this environment.")}function bS(){if("undefined"==typeof atob)throw new N("unimplemented","Blobs are unavailable in Firestore in this environment.")}class IS{constructor(e){this._delegate=e}static fromBase64String(e){return bS(),new IS(ok.fromBase64String(e))}static fromUint8Array(e){return wS(),new IS(ok.fromUint8Array(e))}toBase64(){return bS(),this._delegate.toBase64()}toUint8Array(){return wS(),this._delegate.toUint8Array()}isEqual(e){return this._delegate.isEqual(e._delegate)}toString(){return"Blob(base64: "+this.toBase64()+")"}}function TS(e){var t=["next","error","complete"];if("object"==typeof e&&null!==e){var r,n=e;for(r of t)if(r in n&&"function"==typeof n[r])return 1}}class ES{enableIndexedDbPersistence(e,r){{e=e._delegate;var n={forceOwnership:r};Sm("enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");let t=e._freezeSettings();return ik(e,aC.provider,{build:e=>new iC(e,t.cacheSizeBytes,null==n?void 0:n.forceOwnership)}),Promise.resolve()}}enableMultiTabIndexedDbPersistence(e){return(async e=>{Sm("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");let t=e._freezeSettings();ik(e,aC.provider,{build:e=>new sC(e,t.cacheSizeBytes)})})(e._delegate)}clearIndexedDbPersistence(e){return sk(e._delegate)}}class CS{constructor(e,t,r){this._delegate=t,this._persistenceProvider=r,this.INTERNAL={delete:()=>this.terminate()},e instanceof ay||(this._appCompat=e)}get _databaseId(){return this._delegate._databaseId}settings(e){var t=this._delegate._getSettings();e.merge||t.host===e.host||Sm("You are overriding the original host. If you did not intend to override your settings, use {merge: true}."),e.merge&&delete(e=Object.assign(Object.assign({},t),e)).merge,this._delegate._setSettings(e)}useEmulator(i,r,s={}){{var[i,r,s,a={}]=[this._delegate,i,r,s];let n,e=(i=q(i,jC))._getSettings(),t=r+":"+s;if(e.host!==VC&&e.host!==t&&Sm("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."),i._setSettings(Object.assign(Object.assign({},e),{host:t,ssl:!1})),a.mockUserToken){let t,r;if("string"==typeof a.mockUserToken)t=a.mockUserToken,r=Im.MOCK_USER;else{t=Z(a.mockUserToken,null==(n=i._app)?void 0:n.options.projectId);let e=a.mockUserToken.sub||a.mockUserToken.user_id;if(!e)throw new N(A.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");r=new Im(e)}i._authCredentials=new Dm(new Rm(t,r))}}}enableNetwork(){return ak(this._delegate)}disableNetwork(){return TC(rk(q(this._delegate,tk)))}enablePersistence(e){let t=!1,r=!1;return e&&(t=!!e.synchronizeTabs,r=!!e.experimentalForceOwningTab,OC("synchronizeTabs",t,"experimentalForceOwningTab",r)),t?this._persistenceProvider.enableMultiTabIndexedDbPersistence(this):this._persistenceProvider.enableIndexedDbPersistence(this,r)}clearPersistence(){return this._persistenceProvider.clearIndexedDbPersistence(this)}terminate(){return this._appCompat&&(this._appCompat._removeServiceInstance("firestore-compat"),this._appCompat._removeServiceInstance("firestore")),this._delegate._delete()}waitForPendingWrites(){var t=this._delegate;{var r=rk(t=q(t,tk));let e=new Nm;return r.asyncQueue.enqueueAndForget(async()=>B0(await bC(r),e)),e.promise}}onSnapshotsInSync(e){return t=this._delegate,e=e,AC(rk(t=q(t,tk)),JC(e)?e:{next:e});var t}get app(){if(this._appCompat)return this._appCompat;throw new N("failed-precondition","Firestore was not initialized using the Firebase SDK. 'app' is not available")}collection(e){try{return new VS(this,WC(this._delegate,e))}catch(e){throw PS(e,"collection()","Firestore.collection()")}}doc(e){try{return new RS(this,HC(this._delegate,e))}catch(e){throw PS(e,"doc()","Firestore.doc()")}}collectionGroup(e){try{return new MS(this,((e,t)=>{if(e=q(e,jC),xC("collectionGroup","collection id",t),0<=t.indexOf("/"))throw new N(A.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new BC(e,null,(e=t,new ow(D.emptyPath(),e)))})(this._delegate,e))}catch(e){throw PS(e,"collectionGroup()","Firestore.collectionGroup()")}}runTransaction(t){return _S(this._delegate,e=>t(new SS(this,e)))}batch(){return rk(this._delegate),new AS(new gS(this._delegate,e=>dS(this._delegate,e)))}loadBundle(e){return t=this._delegate,e=e,r=rk(t=q(t,tk)),n=new XC,NC(r,t._databaseId,e,n),n;var t,r,n}namedQuery(e){return t=this._delegate,e=e,RC(rk(t=q(t,tk)),e).then(e=>e?new BC(t,null,e.query):null).then(e=>e?new MS(this,e):null);var t}}class kS extends eS{constructor(e){super(),this.firestore=e}convertBytes(e){return new IS(new ok(e))}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return RS.forKey(t,this.firestore,null)}}class SS{constructor(e,t){this._firestore=e,this._delegate=t,this._userDataWriter=new kS(e)}get(e){let t=qS(e);return this._delegate.get(t).then(e=>new OS(this._firestore,new iS(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,t.converter)))}set(e,t,r){var n=qS(e);return r?(yS("Transaction.set",r),this._delegate.set(n,t,r)):this._delegate.set(n,t),this}update(e,t,r,...n){var i=qS(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,r,...n),this}delete(e){var t=qS(e);return this._delegate.delete(t),this}}class AS{constructor(e){this._delegate=e}set(e,t,r){var n=qS(e);return r?(yS("WriteBatch.set",r),this._delegate.set(n,t,r)):this._delegate.set(n,t),this}update(e,t,r,...n){var i=qS(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,r,...n),this}delete(e){var t=qS(e);return this._delegate.delete(t),this}commit(){return this._delegate.commit()}}class NS{constructor(e,t,r){this._firestore=e,this._userDataWriter=t,this._delegate=r}fromFirestore(e,t){var r=new sS(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,null);return this._delegate.fromFirestore(new LS(this._firestore,r),null!=t?t:{})}toFirestore(e,t){return t?this._delegate.toFirestore(e,t):this._delegate.toFirestore(e)}static getInstance(e,t){var r=NS.INSTANCES;let n=r.get(e),i=(n||(n=new WeakMap,r.set(e,n)),n.get(t));return i||(i=new NS(e,new kS(e),t),n.set(t,i)),i}}NS.INSTANCES=new WeakMap;class RS{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new kS(e)}static forPath(e,t,r){if(e.length%2!=0)throw new N("invalid-argument","Invalid document reference. Document references must have an even number of segments, but "+e.canonicalString()+" has "+e.length);return new RS(t,new zC(t._delegate,r,new x(e)))}static forKey(e,t,r){return new RS(t,new zC(t._delegate,r,e))}get id(){return this._delegate.id}get parent(){return new VS(this.firestore,this._delegate.parent)}get path(){return this._delegate.path}collection(e){try{return new VS(this.firestore,WC(this._delegate,e))}catch(e){throw PS(e,"collection()","DocumentReference.collection()")}}isEqual(e){return(e=w(e))instanceof zC&&GC(this._delegate,e)}set(e,t){t=yS("DocumentReference.set",t);try{return t?hS(this._delegate,e,t):hS(this._delegate,e)}catch(e){throw PS(e,"setDoc()","DocumentReference.set()")}}update(e,t,...r){try{return 1===arguments.length?uS(this._delegate,e):uS(this._delegate,e,t,...r)}catch(e){throw PS(e,"updateDoc()","DocumentReference.update()")}}delete(){return dS(q((e=this._delegate).firestore,tk),[new nb(e._key,Hw.none())]);var e}onSnapshot(...e){var t=DS(e),r=xS(e,e=>new OS(this.firestore,new iS(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)));return cS(this._delegate,t,r)}get(e){let t;return(t=("cache"===(null==e?void 0:e.source)?t=>{t=q(t,zC);let r=q(t.firestore,tk),e=rk(r),n=new lS(r);return EC(e,t._key).then(e=>new iS(r,n,t._key,e,new nS(null!==e&&e.hasLocalMutations,!0),t.converter))}:"server"===(null==e?void 0:e.source)?t=>{t=q(t,zC);let r=q(t.firestore,tk);return CC(rk(r),t._key,{source:"server"}).then(e=>pS(r,t,e))}:t=>{t=q(t,zC);let r=q(t.firestore,tk);return CC(rk(r),t._key).then(e=>pS(r,t,e))})(this._delegate)).then(e=>new OS(this.firestore,new iS(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)))}withConverter(e){return new RS(this.firestore,e?this._delegate.withConverter(NS.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function PS(e,t,r){return e.message=e.message.replace(t,r),e}function DS(e){for(var t of e)if("object"==typeof t&&!TS(t))return t;return{}}function xS(e,t){let r,n,i;return i=TS(e[0])?e[0]:TS(e[1])?e[1]:"function"==typeof e[0]?{next:e[0],error:e[1],complete:e[2]}:{next:e[1],error:e[2],complete:e[3]},{next:e=>{i.next&&i.next(t(e))},error:null==(r=i.error)?void 0:r.bind(i),complete:null==(n=i.complete)?void 0:n.bind(i)}}class OS{constructor(e,t){this._firestore=e,this._delegate=t}get ref(){return new RS(this._firestore,this._delegate.ref)}get id(){return this._delegate.id}get metadata(){return this._delegate.metadata}get exists(){return this._delegate.exists()}data(e){return this._delegate.data(e)}get(e,t){return this._delegate.get(e,t)}isEqual(e){return oS(this._delegate,e._delegate)}}class LS extends OS{data(e){var t=this._delegate.data(e);return this._delegate._converter||void 0!==t||k(),t}}class MS{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new kS(e)}where(e,t,r){try{return new MS(this.firestore,Kk(this._delegate,(n=r,i=t,s=qk("where",e),Wk._create(s,i,n))))}catch(e){throw PS(e,/(orderBy|where)\(\)/,"Query.$1()")}var n,i,s}orderBy(e,t){try{return new MS(this.firestore,Kk(this._delegate,([r,n="asc"]=[e,t],i=n,s=qk("orderBy",r),Hk._create(s,i))))}catch(e){throw PS(e,/(orderBy|where)\(\)/,"Query.$1()")}var r,n,i,s}limit(e){try{return new MS(this.firestore,Kk(this._delegate,(UC("limit",t=e),Gk._create("limit",t,"F"))))}catch(e){throw PS(e,"limit()","Query.limit()")}var t}limitToLast(e){try{return new MS(this.firestore,Kk(this._delegate,(UC("limitToLast",t=e),Gk._create("limitToLast",t,"L"))))}catch(e){throw PS(e,"limitToLast()","Query.limitToLast()")}var t}startAt(...e){try{return new MS(this.firestore,Kk(this._delegate,([...t]=[...e],$k._create("startAt",t,!0))))}catch(e){throw PS(e,"startAt()","Query.startAt()")}var t}startAfter(...e){try{return new MS(this.firestore,Kk(this._delegate,([...t]=[...e],$k._create("startAfter",t,!1))))}catch(e){throw PS(e,"startAfter()","Query.startAfter()")}var t}endBefore(...e){try{return new MS(this.firestore,Kk(this._delegate,([...t]=[...e],Qk._create("endBefore",t,!1))))}catch(e){throw PS(e,"endBefore()","Query.endBefore()")}var t}endAt(...e){try{return new MS(this.firestore,Kk(this._delegate,([...t]=[...e],Qk._create("endAt",t,!0))))}catch(e){throw PS(e,"endAt()","Query.endAt()")}var t}isEqual(e){return $C(this._delegate,e._delegate)}get(e){let t;return(t=("cache"===(null==e?void 0:e.source)?t=>{t=q(t,BC);let r=q(t.firestore,tk),e=rk(r),n=new lS(r);return kC(e,t._query).then(e=>new aS(r,n,t,e))}:"server"===(null==e?void 0:e.source)?t=>{t=q(t,BC);let r=q(t.firestore,tk),e=rk(r),n=new lS(r);return SC(e,t._query,{source:"server"}).then(e=>new aS(r,n,t,e))}:t=>{t=q(t,BC);let r=q(t.firestore,tk),e=rk(r),n=new lS(r);return jk(t._query),SC(e,t._query).then(e=>new aS(r,n,t,e))})(this._delegate)).then(e=>new US(this.firestore,new aS(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)))}onSnapshot(...e){var t=DS(e),r=xS(e,e=>new US(this.firestore,new aS(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)));return cS(this._delegate,t,r)}withConverter(e){return new MS(this.firestore,e?this._delegate.withConverter(NS.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}class FS{constructor(e,t){this._firestore=e,this._delegate=t}get type(){return this._delegate.type}get doc(){return new LS(this._firestore,this._delegate.doc)}get oldIndex(){return this._delegate.oldIndex}get newIndex(){return this._delegate.newIndex}}class US{constructor(e,t){this._firestore=e,this._delegate=t}get query(){return new MS(this._firestore,this._delegate.query)}get metadata(){return this._delegate.metadata}get size(){return this._delegate.size}get empty(){return this._delegate.empty}get docs(){return this._delegate.docs.map(e=>new LS(this._firestore,e))}docChanges(e){return this._delegate.docChanges(e).map(e=>new FS(this._firestore,e))}forEach(t,r){this._delegate.forEach(e=>{t.call(r,new LS(this._firestore,e))})}isEqual(e){return oS(this._delegate,e._delegate)}}class VS extends MS{constructor(e,t){super(e,t),this.firestore=e,this._delegate=t}get id(){return this._delegate.id}get path(){return this._delegate.path}get parent(){var e=this._delegate.parent;return e?new RS(this.firestore,e):null}doc(e){try{return void 0===e?new RS(this.firestore,HC(this._delegate)):new RS(this.firestore,HC(this._delegate,e))}catch(e){throw PS(e,"doc()","CollectionReference.doc()")}}add(e){return((e,t)=>{let r=q(e.firestore,tk),n=HC(e),i=tS(e.converter,t);return dS(r,[yk(_k(e.firestore),"addDoc",n._key,i,null!==e.converter,{}).toMutation(n._key,Hw.exists(!1))]).then(()=>n)})(this._delegate,e).then(e=>new RS(this.firestore,e))}isEqual(e){return GC(this._delegate,e._delegate)}withConverter(e){return new VS(this.firestore,e?this._delegate.withConverter(NS.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function qS(e){return q(e,zC)}class jS{static serverTimestamp(){var e=new Ik("serverTimestamp");return e._methodName="FieldValue.serverTimestamp",new jS(e)}static delete(){var e=new wk("deleteField");return e._methodName="FieldValue.delete",new jS(e)}static arrayUnion(...e){[...e]=[...e];var t=new Tk("arrayUnion",e);return t._methodName="FieldValue.arrayUnion",new jS(t)}static arrayRemove(...e){[...e]=[...e];var t=new Ek("arrayRemove",e);return t._methodName="FieldValue.arrayRemove",new jS(t)}static increment(e){e=e;var t=new Ck("increment",e);return t._methodName="FieldValue.increment",new jS(t)}constructor(e){this._delegate=e}isEqual(e){return this._delegate.isEqual(e._delegate)}}let BS={Firestore:CS,GeoPoint:uk,Timestamp:Km,Blob:IS,Transaction:SS,WriteBatch:AS,DocumentReference:RS,DocumentSnapshot:OS,Query:MS,QueryDocumentSnapshot:LS,QuerySnapshot:US,CollectionReference:VS,FieldPath:class d1{constructor(...e){this._delegate=new lk(...e)}static documentId(){return new d1($m.keyField().canonicalString())}isEqual(e){return(e=w(e))instanceof lk&&this._delegate._internalPath.isEqual(e._internalPath)}},FieldValue:jS,setLogLevel:function(e){e=e,Em.setLogLevel(e)},CACHE_SIZE_UNLIMITED:-1};t=tr,ek=(e,t)=>new CS(e,t,new ES),t.INTERNAL.registerComponent(new u("firestore-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),r=e.getProvider("firestore").getImmediate();return ek(t,r)},"PUBLIC").setServiceProps(Object.assign({},BS))),t.registerVersion("@firebase/firestore-compat","0.3.42");let zS="type.googleapis.com/google.protobuf.Int64Value",KS="type.googleapis.com/google.protobuf.UInt64Value";function WS(e,t){var r,n={};for(r in e)e.hasOwnProperty(r)&&(n[r]=t(e[r]));return n}function HS(e){if(null==e)return null;if("number"==typeof(e=e instanceof Number?e.valueOf():e)&&isFinite(e))return e;if(!0===e||!1===e)return e;if("[object String]"===Object.prototype.toString.call(e))return e;if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(e=>HS(e));if("function"==typeof e||"object"==typeof e)return WS(e,e=>HS(e));throw new Error("Data cannot be encoded in JSON: "+e)}function GS(e){if(null==e)return e;if(e["@type"])switch(e["@type"]){case zS:case KS:var t=Number(e.value);if(isNaN(t))throw new Error("Data cannot be decoded from JSON: "+e);return t;default:throw new Error("Data cannot be decoded from JSON: "+e)}return Array.isArray(e)?e.map(e=>GS(e)):"function"==typeof e||"object"==typeof e?WS(e,e=>GS(e)):e}let $S="functions",QS={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 YS extends de{constructor(e,t,r){super($S+"/"+e,t||""),this.details=r,Object.setPrototypeOf(this,YS.prototype)}}function JS(e,t){let r=(e=>{if(200<=e&&e<300)return"ok";switch(e){case 0:return"internal";case 400:return"invalid-argument";case 401:return"unauthenticated";case 403:return"permission-denied";case 404:return"not-found";case 409:return"aborted";case 429:return"resource-exhausted";case 499:return"cancelled";case 500:return"internal";case 501:return"unimplemented";case 503:return"unavailable";case 504:return"deadline-exceeded"}return"unknown"})(e),n=r,i=void 0;try{var s=t&&t.error;if(s){let e=s.status;if("string"==typeof e){if(!QS[e])return new YS("internal","internal");r=QS[e],n=e}var a=s.message;"string"==typeof a&&(n=a),void 0!==(i=s.details)&&(i=GS(i))}}catch(e){}return"ok"===r?null:new YS(r,n,i)}class XS{constructor(e,t,r,n){this.app=e,this.auth=null,this.messaging=null,this.appCheck=null,this.serverAppAppCheckToken=null,h(e)&&e.settings.appCheckToken&&(this.serverAppAppCheckToken=e.settings.appCheckToken),this.auth=t.getImmediate({optional:!0}),this.messaging=r.getImmediate({optional:!0}),this.auth||t.get().then(e=>this.auth=e,()=>{}),this.messaging||r.get().then(e=>this.messaging=e,()=>{}),this.appCheck||null!=n&&n.get().then(e=>this.appCheck=e,()=>{})}async getAuthToken(){if(this.auth)try{var e=await this.auth.getToken();return null==e?void 0:e.accessToken}catch(e){}}async getMessagingToken(){if(this.messaging&&"Notification"in self&&"granted"===Notification.permission)try{return await this.messaging.getToken()}catch(e){}}async getAppCheckToken(e){var t;return this.serverAppAppCheckToken||(!this.appCheck||(t=e?await this.appCheck.getLimitedUseToken():await this.appCheck.getToken()).error?null:t.token)}async getContext(e){return{authToken:await this.getAuthToken(),messagingToken:await this.getMessagingToken(),appCheckToken:await this.getAppCheckToken(e)}}}let ZS="us-central1",eA=/^data: (.*?)(?:\n|$)/;class tA{constructor(e,t,r,n,i=ZS,s=(...e)=>fetch(...e)){this.app=e,this.fetchImpl=s,this.emulatorOrigin=null,this.contextProvider=new XS(e,t,r,n),this.cancelAllRequests=new Promise(e=>{this.deleteService=()=>Promise.resolve(e())});try{var a=new URL(i);this.customDomain=a.origin+("/"===a.pathname?"":a.pathname),this.region=ZS}catch(e){this.customDomain=null,this.region=i}}_delete(){return this.deleteService()}_url(e){var t=this.app.options.projectId;return null!==this.emulatorOrigin?`${this.emulatorOrigin}/${t}/${this.region}/`+e:null!==this.customDomain?this.customDomain+"/"+e:`https://${this.region}-${t}.cloudfunctions.net/`+e}}function rA(i,s,a){var e=e=>{return e=e,r=a||{},n=(t=i)._url(s),iA(t,n,e,r);var t,r,n};return e.stream=(e,t)=>{return e=e,t=t,n=(r=i)._url(s),sA(r,n,e,t||{});var r,n},e}async function nA(e,t){var r={},n=await e.contextProvider.getContext(t.limitedUseAppCheckTokens);return n.authToken&&(r.Authorization="Bearer "+n.authToken),n.messagingToken&&(r["Firebase-Instance-ID-Token"]=n.messagingToken),null!==n.appCheckToken&&(r["X-Firebase-AppCheck"]=n.appCheckToken),r}async function iA(e,t,r,n){var i={data:r=HS(r)},s=await nA(e,n),a=(r=>{let n=null;return{promise:new Promise((e,t)=>{n=setTimeout(()=>{t(new YS("deadline-exceeded","deadline-exceeded"))},r)}),cancel:()=>{n&&clearTimeout(n)}}})(n.timeout||7e4),i=await Promise.race([(async(e,t,r,n)=>{r["Content-Type"]="application/json";let i;try{i=await n(e,{method:"POST",body:JSON.stringify(t),headers:r})}catch(e){return{status:0,json:null}}let s=null;try{s=await i.json()}catch(e){}return{status:i.status,json:s}})(t,i,s,e.fetchImpl),a.promise,e.cancelAllRequests]);if(a.cancel(),!i)throw new YS("cancelled","Firebase Functions instance was deleted.");s=JS(i.status,i.json);if(s)throw s;if(!i.json)throw new YS("internal","Response is not valid JSON object.");let o=i.json.data;if(void 0===(o=void 0===o?i.json.result:o))throw new YS("internal","Response is missing data field.");return{data:GS(o)}}async function sA(e,t,r,n){var i={data:r=HS(r)},s=await nA(e,n);s["Content-Type"]="application/json",s.Accept="text/event-stream";let a;try{a=await e.fetchImpl(t,{method:"POST",body:JSON.stringify(i),headers:s,signal:null==n?void 0:n.signal})}catch(e){if(e instanceof Error&&"AbortError"===e.name){let e=new YS("cancelled","Request was cancelled.");return{data:Promise.reject(e),stream:{[Symbol.asyncIterator](){return{next(){return Promise.reject(e)}}}}}}let t=JS(0,null);return{data:Promise.reject(t),stream:{[Symbol.asyncIterator](){return{next(){return Promise.reject(t)}}}}}}let o,l;i=new Promise((e,t)=>{o=e,l=t}),null!=(s=null==n?void 0:n.signal)&&s.addEventListener("abort",()=>{var e=new YS("cancelled","Request was cancelled.");l(e)}),s=a.body.getReader();let h=((a,s,o,l)=>{let h=(e,t)=>{var r=e.match(eA);if(r){r=r[1];try{var n,i=JSON.parse(r);"result"in i?s(GS(i.result)):"message"in i?t.enqueue(GS(i.message)):"error"in i&&(n=JS(0,i),t.error(n),o(n))}catch(e){e instanceof YS&&(t.error(e),o(e))}}},u=new TextDecoder;return new ReadableStream({start(i){let s="";return async function r(){if(null!=l&&l.aborted){let e=new YS("cancelled","Request was cancelled");return i.error(e),o(e),Promise.resolve()}try{let{value:t,done:e}=await a.read();if(e)s.trim()&&h(s.trim(),i),i.close();else{if(null==l||!l.aborted){let e=(s+=u.decode(t,{stream:!0})).split("\n");s=e.pop()||"";for(var n of e)n.trim()&&h(n.trim(),i);return r()}{let e=new YS("cancelled","Request was cancelled");i.error(e),o(e),void await a.cancel()}}}catch(e){let t=e instanceof YS?e:JS(0,null);i.error(t),o(t)}}()},cancel(){return a.cancel()}})})(s,o,l,null==n?void 0:n.signal);return{stream:{[Symbol.asyncIterator](){let r=h.getReader();return{async next(){var{value:e,done:t}=await r.read();return{value:e,done:t}},async return(){return await r.cancel(),{done:!0,value:void 0}}}}},data:i}}let aA="@firebase/functions";function oA(e,t,r){w(e).emulatorOrigin=`http://${t}:`+r}function lA(e,t,r){return n=w(e),i=t,s=r,(a=e=>iA(n,i,e,s||{})).stream=(e,t)=>sA(n,i,e,t||{}),a;var n,i,s,a}Ct(new u($S,(e,{instanceIdentifier:t})=>{var r=e.getProvider("app").getImmediate(),n=e.getProvider("auth-internal"),i=e.getProvider("messaging-internal"),s=e.getProvider("app-check-internal");return new tA(r,n,i,s,t)},"PUBLIC").setMultipleInstances(!0)),d(aA,"0.12.2",r),d(aA,"0.12.2","esm2017");var hA,uA,cA;class dA{constructor(e,t){this.app=e,this._delegate=t,this._region=this._delegate.region,this._customDomain=this._delegate.customDomain}httpsCallable(e,t){return rA(w(this._delegate),e,t)}httpsCallableFromURL(e,t){return lA(this._delegate,e,t)}useFunctionsEmulator(e){var t=e.match("[a-zA-Z]+://([a-zA-Z0-9.-]+)(?::([0-9]+))?");if(null==t)throw new de("functions","No origin provided to useFunctionsEmulator()");if(null==t[2])throw new de("functions","Port missing in origin provided to useFunctionsEmulator()");return oA(this._delegate,t[1],Number(t[2]))}useEmulator(e,t){return oA(this._delegate,e,t)}}let pA="us-central1",fA=(e,{instanceIdentifier:t})=>{var r=e.getProvider("app-compat").getImmediate(),n=e.getProvider("functions").getImmediate({identifier:null!=t?t:pA});return new dA(r,n)};Zt={Functions:dA},tr.INTERNAL.registerComponent(new u("functions-compat",fA,"PUBLIC").setServiceProps(Zt).setMultipleInstances(!0)),tr.registerVersion("@firebase/functions-compat","0.3.19");let gA="/firebase-messaging-sw.js",mA="/firebase-cloud-messaging-push-scope",vA="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4",_A="https://fcmregistrations.googleapis.com/v1",yA="google.c.a.c_id",wA="google.c.a.c_l",bA="google.c.a.ts",IA="google.c.a.e",TA=1e4;function EA(e){var t=new Uint8Array(e);return btoa(String.fromCharCode(...t)).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}(WD=hA=hA||{}).PUSH_RECEIVED="push-received",WD.NOTIFICATION_CLICKED="notification-clicked";let CA="fcm_token_details_db",kA=5,SA="fcm_token_object_Store";async function AA(o){if("databases"in indexedDB&&!(await indexedDB.databases()).map(e=>e.name).includes(CA))return null;let l=null;return(await lt(CA,kA,{upgrade:async(e,t,r,n)=>{var i,s,a;t<2||e.objectStoreNames.contains(SA)&&(i=await(a=n.objectStore(SA)).index("fcmSenderId").get(o),await a.clear(),i)&&(2===t?(a=i).auth&&a.p256dh&&a.endpoint&&(l={token:a.fcmToken,createTime:null!=(s=a.createTime)?s:Date.now(),subscriptionOptions:{auth:a.auth,p256dh:a.p256dh,endpoint:a.endpoint,swScope:a.swScope,vapidKey:"string"==typeof a.vapidKey?a.vapidKey:EA(a.vapidKey)}}):3===t?(s=i,l={token:s.fcmToken,createTime:s.createTime,subscriptionOptions:{auth:EA(s.auth),p256dh:EA(s.p256dh),endpoint:s.endpoint,swScope:s.swScope,vapidKey:EA(s.vapidKey)}}):4===t&&(a=i,l={token:a.fcmToken,createTime:a.createTime,subscriptionOptions:{auth:EA(a.auth),p256dh:EA(a.p256dh),endpoint:a.endpoint,swScope:a.swScope,vapidKey:EA(a.vapidKey)}}))}})).close(),await ht(CA),await ht("fcm_vapid_details_db"),await ht("undefined"),(e=>{var t;if(e&&e.subscriptionOptions)return t=e.subscriptionOptions,"number"==typeof e.createTime&&0<e.createTime&&"string"==typeof e.token&&0<e.token.length&&"string"==typeof t.auth&&0<t.auth.length&&"string"==typeof t.p256dh&&0<t.p256dh.length&&"string"==typeof t.endpoint&&0<t.endpoint.length&&"string"==typeof t.swScope&&0<t.swScope.length&&"string"==typeof t.vapidKey&&0<t.vapidKey.length})(l)?l:null}let NA="firebase-messaging-database",RA=1,PA="firebase-messaging-store",DA=null;function xA(){return DA=DA||lt(NA,RA,{upgrade:(e,t)=>{0===t&&e.createObjectStore(PA)}})}async function OA(e){var t=MA(e),t=await(await xA()).transaction(PA).objectStore(PA).get(t);return t||((t=await AA(e.appConfig.senderId))?(await LA(e,t),t):void 0)}async function LA(e,t){var r=MA(e),n=(await xA()).transaction(PA,"readwrite");return await n.objectStore(PA).put(t,r),await n.done,t}function MA({appConfig:e}){return e.appId}let FA=new pe("messaging","Messaging",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"only-available-in-window":"This method is available in a Window context.","only-available-in-sw":"This method is available in a service worker context.","permission-default":"The notification permission was not granted and dismissed instead.","permission-blocked":"The notification permission was not granted and blocked instead.","unsupported-browser":"This browser doesn't support the API's required to use the Firebase SDK.","indexed-db-unsupported":"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)","failed-service-worker-registration":"We are unable to register the default service worker. {$browserErrorMessage}","token-subscribe-failed":"A problem occurred while subscribing the user to FCM: {$errorInfo}","token-subscribe-no-token":"FCM returned no token when subscribing the user to push.","token-unsubscribe-failed":"A problem occurred while unsubscribing the user from FCM: {$errorInfo}","token-update-failed":"A problem occurred while updating the user from FCM: {$errorInfo}","token-update-no-token":"FCM returned no token when updating the user to push.","use-sw-after-get-token":"The useServiceWorker() method may only be called once and must be called before calling getToken() to ensure your service worker is used.","invalid-sw-registration":"The input to useServiceWorker() must be a ServiceWorkerRegistration.","invalid-bg-handler":"The input to setBackgroundMessageHandler() must be a function.","invalid-vapid-key":"The public VAPID key must be a string.","use-vapid-key-after-get-token":"The usePublicVapidKey() method may only be called once and must be called before calling getToken() to ensure your VAPID key is used."});async function UA(e,t){var r={method:"DELETE",headers:await qA(e)};try{var n,i=await(await fetch(VA(e.appConfig)+"/"+t,r)).json();if(i.error)throw n=i.error.message,FA.create("token-unsubscribe-failed",{errorInfo:n})}catch(e){throw FA.create("token-unsubscribe-failed",{errorInfo:null==e?void 0:e.toString()})}}function VA({projectId:e}){return _A+`/projects/${e}/registrations`}async function qA({appConfig:e,installations:t}){var r=await t.getToken();return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e.apiKey,"x-goog-firebase-installations-auth":"FIS "+r})}function jA({p256dh:e,auth:t,endpoint:r,vapidKey:n}){var i={web:{endpoint:r,auth:t,p256dh:e}};return n!==vA&&(i.web.applicationPubKey=n),i}let BA=6048e5;async function zA(e){var t,r,n,i,s,a=await(async(e,t)=>{var r=await e.pushManager.getSubscription();return r||e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:(e=>{var t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/"),r=atob(t),n=new Uint8Array(r.length);for(let i=0;i<r.length;++i)n[i]=r.charCodeAt(i);return n})(t)})})(e.swRegistration,e.vapidKey),a={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:a.endpoint,auth:EA(a.getKey("auth")),p256dh:EA(a.getKey("p256dh"))},o=await OA(e.firebaseDependencies);if(o){if(t=o.subscriptionOptions,r=a.vapidKey===t.vapidKey,n=a.endpoint===t.endpoint,i=a.auth===t.auth,s=a.p256dh===t.p256dh,r&&n&&i&&s)return Date.now()>=o.createTime+BA?(async(e,t)=>{try{var r=await(async(e,t)=>{var r=await qA(e),n=jA(t.subscriptionOptions),r={method:"PATCH",headers:r,body:JSON.stringify(n)};let i;try{var s=await fetch(VA(e.appConfig)+"/"+t.token,r);i=await s.json()}catch(e){throw FA.create("token-update-failed",{errorInfo:null==e?void 0:e.toString()})}if(i.error)throw n=i.error.message,FA.create("token-update-failed",{errorInfo:n});if(i.token)return i.token;throw FA.create("token-update-no-token")})(e.firebaseDependencies,t),n=Object.assign(Object.assign({},t),{token:r,createTime:Date.now()});return await LA(e.firebaseDependencies,n),r}catch(e){throw e}})(e,{token:o.token,createTime:Date.now(),subscriptionOptions:a}):o.token;try{await UA(e.firebaseDependencies,o.token)}catch(e){console.warn(e)}}return WA(e.firebaseDependencies,a)}async function KA(e){var t,r=await OA(e.firebaseDependencies),r=(r&&(await UA(e.firebaseDependencies,r.token),r=MA(e.firebaseDependencies),await(t=(await xA()).transaction(PA,"readwrite")).objectStore(PA).delete(r),await t.done),await e.swRegistration.pushManager.getSubscription());return!r||r.unsubscribe()}async function WA(e,t){var r={token:await(async(e,t)=>{var r=await qA(e),n=jA(t),r={method:"POST",headers:r,body:JSON.stringify(n)};let i;try{var s=await fetch(VA(e.appConfig),r);i=await s.json()}catch(e){throw FA.create("token-subscribe-failed",{errorInfo:null==e?void 0:e.toString()})}if(i.error)throw n=i.error.message,FA.create("token-subscribe-failed",{errorInfo:n});if(i.token)return i.token;throw FA.create("token-subscribe-no-token")})(e,t),createTime:Date.now(),subscriptionOptions:t};return await LA(e,r),r.token}function HA(e){var t,r,n,i,s={from:e.from,collapseKey:e.collapse_key,messageId:e.fcmMessageId};return n=s,(r=e).notification&&(n.notification={},(t=r.notification.title)&&(n.notification.title=t),(t=r.notification.body)&&(n.notification.body=t),(t=r.notification.image)&&(n.notification.image=t),t=r.notification.icon)&&(n.notification.icon=t),r=s,(n=e).data&&(r.data=n.data),r=s,((n=e).fcmOptions||null!=(i=n.notification)&&i.click_action)&&(r.fcmOptions={},(i=null!=(i=null==(i=n.fcmOptions)?void 0:i.link)?i:null==(i=n.notification)?void 0:i.click_action)&&(r.fcmOptions.link=i),i=null==(i=n.fcmOptions)?void 0:i.analytics_label)&&(r.fcmOptions.analyticsLabel=i),s}var GA="AzSCbw63g1R0nCw85jG8",$A="Iaya3yLKwmgvh7cF0q4",QA=[];for(let p1=0;p1<GA.length;p1++)QA.push(GA.charAt(p1)),p1<$A.length&&QA.push($A.charAt(p1));function YA(e){return FA.create("missing-app-config-values",{valueName:e})}QA.join("");class JA{constructor(e,t,r){this.deliveryMetricsExportedToBigQueryEnabled=!1,this.onBackgroundMessageHandler=null,this.onMessageHandler=null,this.logEvents=[],this.isLogServiceStarted=!1;var n=(e=>{if(!e||!e.options)throw YA("App Configuration Object");if(!e.name)throw YA("App Name");var t,r=e.options;for(t of["projectId","apiKey","appId","messagingSenderId"])if(!r[t])throw YA(t);return{appName:e.name,projectId:r.projectId,apiKey:r.apiKey,appId:r.appId,senderId:r.messagingSenderId}})(e);this.firebaseDependencies={app:e,appConfig:n,installations:t,analyticsProvider:r}}_delete(){return Promise.resolve()}}async function XA(e){try{e.swRegistration=await navigator.serviceWorker.register(gA,{scope:mA}),e.swRegistration.update().catch(()=>{}),t=e.swRegistration,await new Promise((r,e)=>{let n=setTimeout(()=>e(new Error(`Service worker not registered after ${TA} ms`)),TA),i=t.installing||t.waiting;t.active?(clearTimeout(n),r()):i?i.onstatechange=e=>{var t;"activated"===(null==(t=e.target)?void 0:t.state)&&(i.onstatechange=null,clearTimeout(n),r())}:(clearTimeout(n),e(new Error("No incoming service worker found.")))})}catch(e){throw FA.create("failed-service-worker-registration",{browserErrorMessage:null==e?void 0:e.message})}var t}async function ZA(e,t){if(!navigator)throw FA.create("only-available-in-window");if("default"===Notification.permission&&await Notification.requestPermission(),"granted"!==Notification.permission)throw FA.create("permission-blocked");n=e,await!((r=null==t?void 0:t.vapidKey)?n.vapidKey=r:n.vapidKey||(n.vapidKey=vA));var r=e,n=null==t?void 0:t.serviceWorkerRegistration;if(n||r.swRegistration||await XA(r),n||!r.swRegistration){if(!(n instanceof ServiceWorkerRegistration))throw FA.create("invalid-sw-registration");r.swRegistration=n}return await 0,zA(e)}async function eN(e,t,r){var n=(e=>{switch(e){case hA.NOTIFICATION_CLICKED:return"notification_open";case hA.PUSH_RECEIVED:return"notification_foreground";default:throw new Error}})(t);(await e.firebaseDependencies.analyticsProvider.get()).logEvent(n,{message_id:r[yA],message_name:r[wA],message_time:r[bA],message_device_time:Math.floor(Date.now()/1e3)})}async function tN(e,t){var r,n=t.data;n.isFirebaseMessaging&&(e.onMessageHandler&&n.messageType===hA.PUSH_RECEIVED&&("function"==typeof e.onMessageHandler?e.onMessageHandler(HA(n)):e.onMessageHandler.next(HA(n))),"object"==typeof(t=r=n.data))&&t&&yA in t&&"1"===r[IA]&&await eN(e,n.messageType,r)}let rN="@firebase/messaging",nN="0.12.16",iN=e=>{let t=new JA(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return navigator.serviceWorker.addEventListener("message",e=>tN(t,e)),t},sN=e=>{let t=e.getProvider("messaging").getImmediate();return{getToken:e=>ZA(t,e)}};function aN(e){return(async e=>{if(navigator)return e.swRegistration||await XA(e),KA(e);throw FA.create("only-available-in-window")})(e=w(e))}function oN(e,t){var r=e=w(e),e=t;if(navigator)return r.onMessageHandler=e,()=>{r.onMessageHandler=null};throw FA.create("only-available-in-window")}Ct(new u("messaging",iN,"PUBLIC")),Ct(new u("messaging-internal",sN,"PRIVATE")),d(rN,nN),d(rN,nN,"esm2017");let lN="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4",hN="https://fcmregistrations.googleapis.com/v1",uN="FCM_MSG",cN="google.c.a.c_id",dN=3,pN=1;function fN(e){var t=new Uint8Array(e);return btoa(String.fromCharCode(...t)).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}(QN=uA=uA||{})[QN.DATA_MESSAGE=1]="DATA_MESSAGE",QN[QN.DISPLAY_NOTIFICATION=3]="DISPLAY_NOTIFICATION",(t=cA=cA||{}).PUSH_RECEIVED="push-received",t.NOTIFICATION_CLICKED="notification-clicked";let gN="fcm_token_details_db",mN=5,vN="fcm_token_object_Store";async function _N(o){if("databases"in indexedDB&&!(await indexedDB.databases()).map(e=>e.name).includes(gN))return null;let l=null;return(await lt(gN,mN,{upgrade:async(e,t,r,n)=>{var i,s,a;t<2||e.objectStoreNames.contains(vN)&&(i=await(a=n.objectStore(vN)).index("fcmSenderId").get(o),await a.clear(),i)&&(2===t?(a=i).auth&&a.p256dh&&a.endpoint&&(l={token:a.fcmToken,createTime:null!=(s=a.createTime)?s:Date.now(),subscriptionOptions:{auth:a.auth,p256dh:a.p256dh,endpoint:a.endpoint,swScope:a.swScope,vapidKey:"string"==typeof a.vapidKey?a.vapidKey:fN(a.vapidKey)}}):3===t?(s=i,l={token:s.fcmToken,createTime:s.createTime,subscriptionOptions:{auth:fN(s.auth),p256dh:fN(s.p256dh),endpoint:s.endpoint,swScope:s.swScope,vapidKey:fN(s.vapidKey)}}):4===t&&(a=i,l={token:a.fcmToken,createTime:a.createTime,subscriptionOptions:{auth:fN(a.auth),p256dh:fN(a.p256dh),endpoint:a.endpoint,swScope:a.swScope,vapidKey:fN(a.vapidKey)}}))}})).close(),await ht(gN),await ht("fcm_vapid_details_db"),await ht("undefined"),(e=>{var t;if(e&&e.subscriptionOptions)return t=e.subscriptionOptions,"number"==typeof e.createTime&&0<e.createTime&&"string"==typeof e.token&&0<e.token.length&&"string"==typeof t.auth&&0<t.auth.length&&"string"==typeof t.p256dh&&0<t.p256dh.length&&"string"==typeof t.endpoint&&0<t.endpoint.length&&"string"==typeof t.swScope&&0<t.swScope.length&&"string"==typeof t.vapidKey&&0<t.vapidKey.length})(l)?l:null}let yN="firebase-messaging-database",wN=1,bN="firebase-messaging-store",IN=null;function TN(){return IN=IN||lt(yN,wN,{upgrade:(e,t)=>{0===t&&e.createObjectStore(bN)}})}async function EN(e){var t=kN(e),t=await(await TN()).transaction(bN).objectStore(bN).get(t);return t||((t=await _N(e.appConfig.senderId))?(await CN(e,t),t):void 0)}async function CN(e,t){var r=kN(e),n=(await TN()).transaction(bN,"readwrite");return await n.objectStore(bN).put(t,r),await n.done,t}function kN({appConfig:e}){return e.appId}let SN=new pe("messaging","Messaging",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"only-available-in-window":"This method is available in a Window context.","only-available-in-sw":"This method is available in a service worker context.","permission-default":"The notification permission was not granted and dismissed instead.","permission-blocked":"The notification permission was not granted and blocked instead.","unsupported-browser":"This browser doesn't support the API's required to use the Firebase SDK.","indexed-db-unsupported":"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)","failed-service-worker-registration":"We are unable to register the default service worker. {$browserErrorMessage}","token-subscribe-failed":"A problem occurred while subscribing the user to FCM: {$errorInfo}","token-subscribe-no-token":"FCM returned no token when subscribing the user to push.","token-unsubscribe-failed":"A problem occurred while unsubscribing the user from FCM: {$errorInfo}","token-update-failed":"A problem occurred while updating the user from FCM: {$errorInfo}","token-update-no-token":"FCM returned no token when updating the user to push.","use-sw-after-get-token":"The useServiceWorker() method may only be called once and must be called before calling getToken() to ensure your service worker is used.","invalid-sw-registration":"The input to useServiceWorker() must be a ServiceWorkerRegistration.","invalid-bg-handler":"The input to setBackgroundMessageHandler() must be a function.","invalid-vapid-key":"The public VAPID key must be a string.","use-vapid-key-after-get-token":"The usePublicVapidKey() method may only be called once and must be called before calling getToken() to ensure your VAPID key is used."});async function AN(e,t){var r={method:"DELETE",headers:await RN(e)};try{var n,i=await(await fetch(NN(e.appConfig)+"/"+t,r)).json();if(i.error)throw n=i.error.message,SN.create("token-unsubscribe-failed",{errorInfo:n})}catch(e){throw SN.create("token-unsubscribe-failed",{errorInfo:null==e?void 0:e.toString()})}}function NN({projectId:e}){return hN+`/projects/${e}/registrations`}async function RN({appConfig:e,installations:t}){var r=await t.getToken();return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e.apiKey,"x-goog-firebase-installations-auth":"FIS "+r})}function PN({p256dh:e,auth:t,endpoint:r,vapidKey:n}){var i={web:{endpoint:r,auth:t,p256dh:e}};return n!==lN&&(i.web.applicationPubKey=n),i}let DN=6048e5;async function xN(e){var t,r,n,i,s,a=await(async(e,t)=>{var r=await e.pushManager.getSubscription();return r||e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:(e=>{var t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/"),r=atob(t),n=new Uint8Array(r.length);for(let i=0;i<r.length;++i)n[i]=r.charCodeAt(i);return n})(t)})})(e.swRegistration,e.vapidKey),a={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:a.endpoint,auth:fN(a.getKey("auth")),p256dh:fN(a.getKey("p256dh"))},o=await EN(e.firebaseDependencies);if(o){if(t=o.subscriptionOptions,r=a.vapidKey===t.vapidKey,n=a.endpoint===t.endpoint,i=a.auth===t.auth,s=a.p256dh===t.p256dh,r&&n&&i&&s)return Date.now()>=o.createTime+DN?(async(e,t)=>{try{var r=await(async(e,t)=>{var r=await RN(e),n=PN(t.subscriptionOptions),r={method:"PATCH",headers:r,body:JSON.stringify(n)};let i;try{var s=await fetch(NN(e.appConfig)+"/"+t.token,r);i=await s.json()}catch(e){throw SN.create("token-update-failed",{errorInfo:null==e?void 0:e.toString()})}if(i.error)throw n=i.error.message,SN.create("token-update-failed",{errorInfo:n});if(i.token)return i.token;throw SN.create("token-update-no-token")})(e.firebaseDependencies,t),n=Object.assign(Object.assign({},t),{token:r,createTime:Date.now()});return await CN(e.firebaseDependencies,n),r}catch(e){throw e}})(e,{token:o.token,createTime:Date.now(),subscriptionOptions:a}):o.token;try{await AN(e.firebaseDependencies,o.token)}catch(e){console.warn(e)}}return LN(e.firebaseDependencies,a)}async function ON(e){var t,r=await EN(e.firebaseDependencies),r=(r&&(await AN(e.firebaseDependencies,r.token),r=kN(e.firebaseDependencies),await(t=(await TN()).transaction(bN,"readwrite")).objectStore(bN).delete(r),await t.done),await e.swRegistration.pushManager.getSubscription());return!r||r.unsubscribe()}async function LN(e,t){var r={token:await(async(e,t)=>{var r=await RN(e),n=PN(t),r={method:"POST",headers:r,body:JSON.stringify(n)};let i;try{var s=await fetch(NN(e.appConfig),r);i=await s.json()}catch(e){throw SN.create("token-subscribe-failed",{errorInfo:null==e?void 0:e.toString()})}if(i.error)throw n=i.error.message,SN.create("token-subscribe-failed",{errorInfo:n});if(i.token)return i.token;throw SN.create("token-subscribe-no-token")})(e,t),createTime:Date.now(),subscriptionOptions:t};return await CN(e,r),r.token}var MN="AzSCbw63g1R0nCw85jG8",FN="Iaya3yLKwmgvh7cF0q4",UN=[];for(let f1=0;f1<MN.length;f1++)UN.push(MN.charAt(f1)),f1<FN.length&&UN.push(FN.charAt(f1));async function VN(e,t){var r=((e,t)=>{var r,n={};return e.from&&(n.project_number=e.from),e.fcmMessageId&&(n.message_id=e.fcmMessageId),n.instance_id=t,n.message_type=(e.notification?uA.DISPLAY_NOTIFICATION:uA.DATA_MESSAGE).toString(),n.sdk_platform=dN.toString(),n.package_name=self.origin.replace(/(^\w+:|^)\/\//,""),e.collapse_key&&(n.collapse_key=e.collapse_key),n.event=pN.toString(),null!=(r=e.fcmOptions)&&r.analytics_label&&(n.analytics_label=null==(r=e.fcmOptions)?void 0:r.analytics_label),n})(t,await e.firebaseDependencies.installations.getId()),n=r,t=t.productId,r={};r.event_time_ms=Math.floor(Date.now()).toString(),r.source_extension_json_proto3=JSON.stringify({messaging_client_event:n}),t&&(r.compliance_data=(e=>({privacy_context:{prequest:{origin_associated_product_id:e}}}))(t)),e.logEvents.push(r)}async function qN(e,t){var r=(({data:e})=>{if(!e)return null;try{return e.json()}catch(e){return null}})(e);if(r){t.deliveryMetricsExportedToBigQueryEnabled&&await VN(t,r);var n,i,s,a=await BN();if(a.some(e=>"visible"===e.visibilityState&&!e.url.startsWith("chrome-extension://"))){var o,e=a,l=r;l.isFirebaseMessaging=!0,l.messageType=cA.PUSH_RECEIVED;for(o of e)o.postMessage(l)}else r.notification&&await(e=>{var t=e.actions,r=Notification.maxActions;return t&&r&&t.length>r&&console.warn(`This browser only supports ${r} actions. The remaining actions will not be displayed.`),self.registration.showNotification(null!=(t=e.title)?t:"",e)})((e=r,(a=Object.assign({},e.notification)).data={[uN]:e},a)),t&&t.onBackgroundMessageHandler&&(a={from:(e=r).from,collapseKey:e.collapse_key,messageId:e.fcmMessageId},i=a,(n=e).notification&&(i.notification={},(r=n.notification.title)&&(i.notification.title=r),(r=n.notification.body)&&(i.notification.body=r),(r=n.notification.image)&&(i.notification.image=r),r=n.notification.icon)&&(i.notification.icon=r),n=a,(i=e).data&&(n.data=i.data),n=a,((i=e).fcmOptions||null!=(s=i.notification)&&s.click_action)&&(n.fcmOptions={},(s=null!=(s=null==(s=i.fcmOptions)?void 0:s.link)?s:null==(s=i.notification)?void 0:s.click_action)&&(n.fcmOptions.link=s),s=null==(s=i.fcmOptions)?void 0:s.analytics_label)&&(n.fcmOptions.analyticsLabel=s),r=a,"function"==typeof t.onBackgroundMessageHandler?await t.onBackgroundMessageHandler(r):t.onBackgroundMessageHandler.next(r))}}async function jN(e){var t=null==(t=null==(t=e.notification)?void 0:t.data)?void 0:t[uN];if(t&&!e.action){e.stopImmediatePropagation(),e.notification.close();var r=(e=>{var t=null!=(t=null==(t=e.fcmOptions)?void 0:t.link)?t:null==(t=e.notification)?void 0:t.click_action;return t||((e=>"object"==typeof e&&e&&cN in e)(e.data)?self.location.origin:null)})(t);if(r){var n,i=new URL(r,self.location.href),s=new URL(self.location.origin);if(i.host===s.host){let e=await(async e=>{var t;for(t of await BN()){var r=new URL(t.url,self.location.href);if(e.host===r.host)return t}return null})(i);if(e?e=await e.focus():(e=await self.clients.openWindow(r),n=3e3,await new Promise(e=>{setTimeout(e,n)})),e)return t.messageType=cA.NOTIFICATION_CLICKED,t.isFirebaseMessaging=!0,e.postMessage(t)}}}}function BN(){return self.clients.matchAll({type:"window",includeUncontrolled:!0})}function zN(e){return SN.create("missing-app-config-values",{valueName:e})}UN.join("");class KN{constructor(e,t,r){this.deliveryMetricsExportedToBigQueryEnabled=!1,this.onBackgroundMessageHandler=null,this.onMessageHandler=null,this.logEvents=[],this.isLogServiceStarted=!1;var n=(e=>{if(!e||!e.options)throw zN("App Configuration Object");if(!e.name)throw zN("App Name");var t,r=e.options;for(t of["projectId","apiKey","appId","messagingSenderId"])if(!r[t])throw zN(t);return{appName:e.name,projectId:r.projectId,apiKey:r.apiKey,appId:r.appId,senderId:r.messagingSenderId}})(e);this.firebaseDependencies={app:e,appConfig:n,installations:t,analyticsProvider:r}}_delete(){return Promise.resolve()}}let WN=e=>{let t=new KN(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return self.addEventListener("push",e=>{e.waitUntil(qN(e,t))}),self.addEventListener("pushsubscriptionchange",e=>{e.waitUntil((async(e,t)=>{var r;(r=e.newSubscription)?(r=await EN(t.firebaseDependencies),await ON(t),t.vapidKey=null!=(r=null==(r=null==r?void 0:r.subscriptionOptions)?void 0:r.vapidKey)?r:lN,await xN(t)):await ON(t)})(e,t))}),self.addEventListener("notificationclick",e=>{e.waitUntil(jN(e))}),t};function HN(e,t){var r=e=w(e),e=t;if(void 0!==self.document)throw SN.create("only-available-in-sw");return r.onBackgroundMessageHandler=e,()=>{r.onBackgroundMessageHandler=null}}Ct(new u("messaging-sw",WN,"PUBLIC"));var GN,$N,QN;class YN{constructor(e,t){this.app=e,this._delegate=t,this.app=e,this._delegate=t}async getToken(e){return(async(e,t)=>ZA(e=w(e),t))(this._delegate,e)}async deleteToken(){return aN(this._delegate)}onMessage(e){return oN(this._delegate,e)}onBackgroundMessage(e){return HN(this._delegate,e)}}let JN=e=>self&&"ServiceWorkerGlobalScope"in self?new YN(e.getProvider("app-compat").getImmediate(),e.getProvider("messaging-sw").getImmediate()):new YN(e.getProvider("app-compat").getImmediate(),e.getProvider("messaging").getImmediate()),XN={isSupported:function(){return self&&"ServiceWorkerGlobalScope"in self?he()&&"PushManager"in self&&"Notification"in self&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey"):"undefined"!=typeof window&&he()&&ce()&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window&&"fetch"in window&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey")}};tr.INTERNAL.registerComponent(new u("messaging-compat",JN,"PUBLIC").setServiceProps(XN)),tr.registerVersion("@firebase/messaging-compat","0.2.16");let ZN="firebasestorage.googleapis.com",eR="storageBucket";class tR extends de{constructor(e,t,r=0){super(rR(e),`Firebase Storage: ${t} (${rR(e)})`),this.status_=r,this.customData={serverResponse:null},this._baseMessage=this.message,Object.setPrototypeOf(this,tR.prototype)}get status(){return this.status_}set status(e){this.status_=e}_codeEquals(e){return rR(e)===this.code}get serverResponse(){return this.customData.serverResponse}set serverResponse(e){this.customData.serverResponse=e,this.customData.serverResponse?this.message=this._baseMessage+`
|
|
17
|
-
`+this.customData.serverResponse:this.message=this._baseMessage}}function rR(e){return"storage/"+e}function nR(){return new tR(GN.UNKNOWN,"An unknown error occurred, please check the error payload for server response.")}function iR(){return new tR(GN.RETRY_LIMIT_EXCEEDED,"Max retry time for operation exceeded, please try again.")}function sR(){return new tR(GN.CANCELED,"User canceled the upload/download.")}function aR(){return new tR(GN.CANNOT_SLICE_BLOB,"Cannot slice blob for upload. Please retry the upload.")}function oR(e){return new tR(GN.INVALID_ARGUMENT,e)}function lR(){return new tR(GN.APP_DELETED,"The Firebase app was deleted.")}function hR(e){return new tR(GN.INVALID_ROOT_OPERATION,"The operation '"+e+"' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').")}function uR(e,t){return new tR(GN.INVALID_FORMAT,"String does not match format '"+e+"': "+t)}function cR(e){throw new tR(GN.INTERNAL_ERROR,"Internal error: "+e)}(r=GN=GN||{}).UNKNOWN="unknown",r.OBJECT_NOT_FOUND="object-not-found",r.BUCKET_NOT_FOUND="bucket-not-found",r.PROJECT_NOT_FOUND="project-not-found",r.QUOTA_EXCEEDED="quota-exceeded",r.UNAUTHENTICATED="unauthenticated",r.UNAUTHORIZED="unauthorized",r.UNAUTHORIZED_APP="unauthorized-app",r.RETRY_LIMIT_EXCEEDED="retry-limit-exceeded",r.INVALID_CHECKSUM="invalid-checksum",r.CANCELED="canceled",r.INVALID_EVENT_NAME="invalid-event-name",r.INVALID_URL="invalid-url",r.INVALID_DEFAULT_BUCKET="invalid-default-bucket",r.NO_DEFAULT_BUCKET="no-default-bucket",r.CANNOT_SLICE_BLOB="cannot-slice-blob",r.SERVER_FILE_WRONG_SIZE="server-file-wrong-size",r.NO_DOWNLOAD_URL="no-download-url",r.INVALID_ARGUMENT="invalid-argument",r.INVALID_ARGUMENT_COUNT="invalid-argument-count",r.APP_DELETED="app-deleted",r.INVALID_ROOT_OPERATION="invalid-root-operation",r.INVALID_FORMAT="invalid-format",r.INTERNAL_ERROR="internal-error",r.UNSUPPORTED_ENVIRONMENT="unsupported-environment";class dR{constructor(e,t){this.bucket=e,this.path_=t}get path(){return this.path_}get isRoot(){return 0===this.path.length}fullServerUrl(){var e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o/"+e(this.path)}bucketOnlyServerUrl(){return"/b/"+encodeURIComponent(this.bucket)+"/o"}static makeFromBucketSpec(t,e){let r;try{r=dR.makeFromUrl(t,e)}catch(e){return new dR(t,"")}if(""===r.path)return r;throw e=t,new tR(GN.INVALID_DEFAULT_BUCKET,"Invalid default bucket '"+e+"'.")}static makeFromUrl(e,t){let r=null;var n="([A-Za-z0-9.\\-_]+)";var i=new RegExp("^gs://"+n+"(/(.*))?$","i");function s(e){e.path_=decodeURIComponent(e.path)}var a=t.replace(/[.]/g,"\\."),a=new RegExp(`^https?://${a}/v[A-Za-z0-9_]+/b/${n}/o(/([^?#]*).*)?$`,"i"),o=t===ZN?"(?:storage.googleapis.com|storage.cloud.google.com)":t,l=[{regex:i,indices:{bucket:1,path:3},postModify:function(e){"/"===e.path.charAt(e.path.length-1)&&(e.path_=e.path_.slice(0,-1))}},{regex:a,indices:{bucket:1,path:3},postModify:s},{regex:new RegExp(`^https?://${o}/${n}/([^?#]*)`,"i"),indices:{bucket:1,path:2},postModify:s}];for(let d=0;d<l.length;d++){var h=l[d],u=h.regex.exec(e);if(u){var c=u[h.indices.bucket];let e=u[h.indices.path];e=e||"",r=new dR(c,e),h.postModify(r);break}}if(null==r)throw t=e,new tR(GN.INVALID_URL,"Invalid URL '"+t+"'.");return r}}class pR{constructor(e){this.promise_=Promise.reject(e)}getPromise(){return this.promise_}cancel(e=0){}}function fR(e){return"string"==typeof e||e instanceof String}function gR(e){return mR()&&e instanceof Blob}function mR(){return"undefined"!=typeof Blob}function vR(e,t,r,n){if(n<t)throw oR(`Invalid value for '${e}'. Expected ${t} or greater.`);if(r<n)throw oR(`Invalid value for '${e}'. Expected ${r} or less.`)}function _R(e,t,r){let n=null==r?"https://"+t:t;return`${r}://${n}/v0`+e}function yR(e){var t,r,n=encodeURIComponent;let i="?";for(t in e)e.hasOwnProperty(t)&&(r=n(t)+"="+n(e[t]),i=i+r+"&");return i=i.slice(0,-1)}function wR(e,t){var r=500<=e&&e<600,n=-1!==[408,429].indexOf(e),i=-1!==t.indexOf(e);return r||n||i}(WD=$N=$N||{})[WD.NO_ERROR=0]="NO_ERROR",WD[WD.NETWORK_ERROR=1]="NETWORK_ERROR",WD[WD.ABORT=2]="ABORT";class bR{constructor(e,t,r,n,i,s,a,o,l,h,u,c=!0){this.url_=e,this.method_=t,this.headers_=r,this.body_=n,this.successCodes_=i,this.additionalRetryCodes_=s,this.callback_=a,this.errorCallback_=o,this.timeout_=l,this.progressCallback_=h,this.connectionFactory_=u,this.retry=c,this.pendingConnection_=null,this.backoffId_=null,this.canceled_=!1,this.appDelete_=!1,this.promise_=new Promise((e,t)=>{this.resolve_=e,this.reject_=t,this.start_()})}start_(){var e=(i,e)=>{if(e)i(!1,new IR(!1,null,!0));else{let r=this.connectionFactory_(),n=(this.pendingConnection_=r,e=>{var t=e.loaded,r=e.lengthComputable?e.total:-1;null!==this.progressCallback_&&this.progressCallback_(t,r)});null!==this.progressCallback_&&r.addUploadProgressListener(n),r.send(this.url_,this.method_,this.body_,this.headers_).then(()=>{null!==this.progressCallback_&&r.removeUploadProgressListener(n),this.pendingConnection_=null;var e=r.getErrorCode()===$N.NO_ERROR,t=r.getStatus();!e||wR(t,this.additionalRetryCodes_)&&this.retry?(e=r.getErrorCode()===$N.ABORT,i(!1,new IR(!1,null,e))):(e=-1!==this.successCodes_.indexOf(t),i(!0,new IR(e,r)))})}},t=(e,t)=>{var r=this.resolve_,n=this.reject_,i=t.connection;if(t.wasSuccessCode)try{var s=this.callback_(i,i.getResponse());void 0!==s?r(s):r()}catch(e){n(e)}else null!==i?((s=nR()).serverResponse=i.getErrorText(),this.errorCallback_?n(this.errorCallback_(i,s)):n(s)):t.canceled?n((this.appDelete_?lR:sR)()):n(iR())};this.canceled_?t(0,new IR(!1,null,!0)):this.backoffId_=((t,r,e)=>{let n=1,i=null,s=null,a=!1,o=0;function l(){return 2===o}let h=!1;function u(...e){h||(h=!0,r.apply(null,e))}function c(e){i=setTimeout(()=>{i=null,t(p,l())},e)}function d(){s&&clearTimeout(s)}function p(e,...t){if(h)d();else if(e)d(),u.call(null,e,...t);else if(l()||a)d(),u.call(null,e,...t);else{n<64&&(n*=2);let e;c(e=1===o?(o=2,0):1e3*(n+Math.random()))}}let f=!1;function g(e){f||(f=!0,d(),h)||(null!==i?(e||(o=2),clearTimeout(i),c(0)):e||(o=1))}return c(0),s=setTimeout(()=>{g(a=!0)},e),g})(e,t,this.timeout_)}getPromise(){return this.promise_}cancel(e){this.canceled_=!0,this.appDelete_=e||!1,null!==this.backoffId_&&(0,this.backoffId_)(!1),null!==this.pendingConnection_&&this.pendingConnection_.abort()}}class IR{constructor(e,t,r){this.wasSuccessCode=e,this.connection=t,this.canceled=!!r}}function TR(...t){var r="undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:void 0;if(void 0!==r){var n=new r;for(let e=0;e<t.length;e++)n.append(t[e]);return n.getBlob()}if(mR())return new Blob(t);throw new tR(GN.UNSUPPORTED_ENVIRONMENT,"This browser doesn't seem to support creating Blobs")}function ER(e){if("undefined"==typeof atob)throw new tR(GN.UNSUPPORTED_ENVIRONMENT,"base-64 is missing. Make sure to install the required polyfills. See https://firebase.google.com/docs/web/environments-js-sdk#polyfills for more information.");return atob(e)}let CR={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"};class kR{constructor(e,t){this.data=e,this.contentType=t||null}}function SR(e,t){switch(e){case CR.RAW:return new kR(AR(t));case CR.BASE64:case CR.BASE64URL:return new kR(NR(e,t));case CR.DATA_URL:return new kR((r=t,(n=new RR(r)).base64?NR(CR.BASE64,n.rest):(e=>{let t;try{t=decodeURIComponent(e)}catch(e){throw uR(CR.DATA_URL,"Malformed data URL.")}return AR(t)})(n.rest)),(r=t,new RR(r).contentType))}var r,n;throw nR()}function AR(t){var r,n,i=[];for(let s=0;s<t.length;s++){let e=t.charCodeAt(s);e<=127?i.push(e):e<=2047?i.push(192|e>>6,128|63&e):55296==(64512&e)?s<t.length-1&&56320==(64512&t.charCodeAt(s+1))?(r=e,n=t.charCodeAt(++s),e=65536|(1023&r)<<10|1023&n,i.push(240|e>>18,128|e>>12&63,128|e>>6&63,128|63&e)):i.push(239,191,189):56320==(64512&e)?i.push(239,191,189):i.push(224|e>>12,128|e>>6&63,128|63&e)}return new Uint8Array(i)}function NR(t,e){switch(t){case CR.BASE64:var r=-1!==e.indexOf("-"),n=-1!==e.indexOf("_");if(r||n)throw uR(t,"Invalid character '"+(r?"-":"_")+"' found: is it base64url encoded?");break;case CR.BASE64URL:n=-1!==e.indexOf("+"),r=-1!==e.indexOf("/");if(n||r)throw uR(t,"Invalid character '"+(n?"+":"/")+"' found: is it base64 encoded?");e=e.replace(/-/g,"+").replace(/_/g,"/")}let i;try{i=ER(e)}catch(e){if(e.message.includes("polyfill"))throw e;throw uR(t,"Invalid character found")}var s=new Uint8Array(i.length);for(let a=0;a<i.length;a++)s[a]=i.charCodeAt(a);return s}class RR{constructor(e){this.base64=!1,this.contentType=null;var t=e.match(/^data:([^,]+)?,/);if(null===t)throw uR(CR.DATA_URL,"Must be formatted 'data:[<mediatype>][;base64],<data>");var r,n,t=t[1]||null;null!=t&&(this.base64=(n=";base64",(r=t).length>=n.length&&r.substring(r.length-n.length)===n),this.contentType=this.base64?t.substring(0,t.length-";base64".length):t),this.rest=e.substring(e.indexOf(",")+1)}}class PR{constructor(e,t){let r=0,n="";gR(e)?(this.data_=e,r=e.size,n=e.type):e instanceof ArrayBuffer?(t?this.data_=new Uint8Array(e):(this.data_=new Uint8Array(e.byteLength),this.data_.set(new Uint8Array(e))),r=this.data_.length):e instanceof Uint8Array&&(t?this.data_=e:(this.data_=new Uint8Array(e.length),this.data_.set(e)),r=e.length),this.size_=r,this.type_=n}size(){return this.size_}type(){return this.type_}slice(e,t){var r,n,i,s;return gR(this.data_)?(r=this.data_,i=e,s=t,null===(r=(n=r).webkitSlice?n.webkitSlice(i,s):n.mozSlice?n.mozSlice(i,s):n.slice?n.slice(i,s):null)?null:new PR(r)):(r=new Uint8Array(this.data_.buffer,e,t-e),new PR(r,!0))}static getBlob(...e){if(mR())return i=e.map(e=>e instanceof PR?e.data_:e),new PR(TR.apply(null,i));{var i=e.map(e=>fR(e)?SR(CR.RAW,e).data:e.data_);let t=0,r=(i.forEach(e=>{t+=e.byteLength}),new Uint8Array(t)),n=0;return i.forEach(e=>{for(let t=0;t<e.length;t++)r[n++]=e[t]}),new PR(r,!0)}}uploadData(){return this.data_}}function DR(e){let t;try{t=JSON.parse(e)}catch(e){return null}return"object"!=typeof(e=t)||Array.isArray(e)?null:t}function xR(e){var t=e.lastIndexOf("/",e.length-2);return-1===t?e:e.slice(t+1)}function OR(e,t){return t}class LR{constructor(e,t,r,n){this.server=e,this.local=t||e,this.writable=!!r,this.xform=n||OR}}let MR=null;function FR(){var e,t;return MR||((e=[]).push(new LR("bucket")),e.push(new LR("generation")),e.push(new LR("metageneration")),e.push(new LR("name","fullPath",!0)),(t=new LR("name")).xform=function(e,t){return!fR(t=t)||t.length<2?t:xR(t)},e.push(t),(t=new LR("size")).xform=function(e,t){return void 0!==t?Number(t):t},e.push(t),e.push(new LR("timeCreated")),e.push(new LR("updated")),e.push(new LR("md5Hash",null,!0)),e.push(new LR("cacheControl",null,!0)),e.push(new LR("contentDisposition",null,!0)),e.push(new LR("contentEncoding",null,!0)),e.push(new LR("contentLanguage",null,!0)),e.push(new LR("contentType",null,!0)),e.push(new LR("metadata","customMetadata",!0)),MR=e),MR}function UR(r,n){Object.defineProperty(r,"ref",{get:function(){var e=r.bucket,t=r.fullPath,e=new dR(e,t);return n._makeStorageReference(e)}})}function VR(e,t,r){var n=DR(t);if(null===n)return null;var t=e,i=n,s=r,a={type:"file"},o=s.length;for(let h=0;h<o;h++){var l=s[h];a[l.local]=l.xform(a,i[l.server])}return UR(a,t),a}function qR(e,t){var r={},n=t.length;for(let s=0;s<n;s++){var i=t[s];i.writable&&(r[i.server]=e[i.local])}return JSON.stringify(r)}let jR="prefixes",BR="items";function zR(e,t,r){var n=DR(r);if(null===n)return null;var i=e,s=t,r=n,a={prefixes:[],items:[],nextPageToken:r.nextPageToken};if(r[jR])for(var o of r[jR]){o=o.replace(/\/$/,""),o=i._makeStorageReference(new dR(s,o));a.prefixes.push(o)}if(r[BR])for(var l of r[BR]){l=i._makeStorageReference(new dR(s,l.name));a.items.push(l)}return a}class KR{constructor(e,t,r,n){this.url=e,this.method=t,this.handler=r,this.timeout=n,this.urlParams={},this.headers={},this.body=null,this.errorHandler=null,this.progressCallback=null,this.successCodes=[200],this.additionalRetryCodes=[]}}function WR(e){if(!e)throw nR()}function HR(n,i){return function(e,t){var r=VR(n,t,i);return WR(null!==r),r}}function GR(n,i){return function(e,t){var r=zR(n,i,t);return WR(null!==r),r}}function $R(o,n){return function(e,t){var r=VR(o,t,n);WR(null!==r);{var i=r,s=o.host,a=o._protocol;if(null===(r=DR(t)))return null;if(!fR(r.downloadTokens))return null;if(0===(r=r.downloadTokens).length)return null;let n=encodeURIComponent;return r.split(",").map(e=>{var t=i.bucket,r=i.fullPath;return _R("/b/"+n(t)+"/o/"+n(r),s,a)+yR({alt:"media",token:e})})[0]}}}function QR(i){return function(e,t){let r;var n;return(r=401===e.getStatus()?e.getErrorText().includes("Firebase App Check token is invalid")?new tR(GN.UNAUTHORIZED_APP,"This app does not have permission to access Firebase Storage on this project."):new tR(GN.UNAUTHENTICATED,"User is not authenticated, please authenticate using Firebase Authentication and try again."):402===e.getStatus()?(n=i.bucket,new tR(GN.QUOTA_EXCEEDED,"Quota for bucket '"+n+"' exceeded, please view quota on https://firebase.google.com/pricing/.")):403===e.getStatus()?(n=i.path,new tR(GN.UNAUTHORIZED,"User does not have permission to access '"+n+"'.")):t).status=e.getStatus(),r.serverResponse=t.serverResponse,r}}function YR(n){let i=QR(n);return function(e,t){let r=i(e,t);return(r=404===e.getStatus()?(e=n.path,new tR(GN.OBJECT_NOT_FOUND,"Object '"+e+"' does not exist.")):r).serverResponse=t.serverResponse,r}}function JR(e,t,r){var n=_R(t.fullServerUrl(),e.host,e._protocol),i=e.maxOperationRetryTime,n=new KR(n,"GET",HR(e,r),i);return n.errorHandler=YR(t),n}function XR(e,t,r){var n=Object.assign({},r);return n.fullPath=e.path,n.size=t.size(),n.contentType||(n.contentType=(r=t,(e=null)&&e.contentType||r&&r.type()||"application/octet-stream")),n}function ZR(e,t,r,n,i){var s=t.bucketOnlyServerUrl(),a={"X-Goog-Upload-Protocol":"multipart"};var o=(()=>{let e="";for(let t=0;t<2;t++)e+=Math.random().toString().slice(2);return e})(),l=(a["Content-Type"]="multipart/related; boundary="+o,XR(t,n,i)),h="--"+o+"\r\nContent-Type: application/json; charset=utf-8\r\n\r\n"+qR(l,r)+"\r\n--"+o+"\r\nContent-Type: "+l.contentType+"\r\n\r\n",o="\r\n--"+o+"--",h=PR.getBlob(h,n,o);if(null===h)throw aR();o={name:l.fullPath},l=_R(s,e.host,e._protocol),s=e.maxUploadRetryTime,l=new KR(l,"POST",HR(e,r),s);return l.urlParams=o,l.headers=a,l.body=h.uploadData(),l.errorHandler=QR(t),l}class eP{constructor(e,t,r,n){this.current=e,this.total=t,this.finalized=!!r,this.metadata=n||null}}function tP(e,t){let r=null;try{r=e.getResponseHeader("X-Goog-Upload-Status")}catch(e){WR(!1)}return WR(!!r&&-1!==(t||["active"]).indexOf(r)),r}function rP(e,t,r,n,i){var s=t.bucketOnlyServerUrl(),a=XR(t,n,i),o={name:a.fullPath},s=_R(s,e.host,e._protocol),l={"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":""+n.size(),"X-Goog-Upload-Header-Content-Type":a.contentType,"Content-Type":"application/json; charset=utf-8"},a=qR(a,r),h=e.maxUploadRetryTime;s=new KR(s,"POST",function(e){tP(e);let t;try{t=e.getResponseHeader("X-Goog-Upload-URL")}catch(e){WR(!1)}return WR(fR(t)),t},h);return s.urlParams=o,s.headers=l,s.body=a,s.errorHandler=QR(t),s}function nP(e,t,r,i){var n=e.maxUploadRetryTime,n=new KR(r,"POST",function(e){var t=tP(e,["active","final"]);let r=null;try{r=e.getResponseHeader("X-Goog-Upload-Size-Received")}catch(e){WR(!1)}r||WR(!1);var n=Number(r);return WR(!isNaN(n)),new eP(n,i.size(),"final"===t)},n);return n.headers={"X-Goog-Upload-Command":"query"},n.errorHandler=QR(t),n}function iP(e,a,t,o,r,l,n,i){let h=new eP(0,0);if(n?(h.current=n.current,h.total=n.total):(h.current=0,h.total=o.size()),o.size()!==h.total)throw new tR(GN.SERVER_FILE_WRONG_SIZE,"Server recorded incorrect upload file size, please retry the upload.");var s=h.total-h.current;let u=s;0<r&&(u=Math.min(u,r));var c=h.current,d=c+u;let p="";s={"X-Goog-Upload-Command":p=0===u?"finalize":s===u?"upload, finalize":"upload","X-Goog-Upload-Offset":""+h.current},c=o.slice(c,d);if(null===c)throw aR();d=a.maxUploadRetryTime,d=new KR(t,"POST",function(e,t){var r=tP(e,["active","final"]),n=h.current+u,i=o.size();let s;return s="final"===r?HR(a,l)(e,t):null,new eP(n,i,"final"===r,s)},d);return d.headers=s,d.body=c.uploadData(),d.progressCallback=i||null,d.errorHandler=QR(e),d}let sP={STATE_CHANGED:"state_changed"},aP={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function oP(e){switch(e){case"running":case"pausing":case"canceling":return aP.RUNNING;case"paused":return aP.PAUSED;case"success":return aP.SUCCESS;case"canceled":return aP.CANCELED;default:return aP.ERROR}}class lP{constructor(e,t,r){var n;"function"==typeof e||null!=t||null!=r?(this.next=e,this.error=null!=t?t:void 0,this.complete=null!=r?r:void 0):(this.next=(n=e).next,this.error=n.error,this.complete=n.complete)}}function hP(t){return(...e)=>{Promise.resolve().then(()=>t(...e))}}class uP extends class{constructor(){this.sent_=!1,this.xhr_=new XMLHttpRequest,this.initXhr(),this.errorCode_=$N.NO_ERROR,this.sendPromise_=new Promise(e=>{this.xhr_.addEventListener("abort",()=>{this.errorCode_=$N.ABORT,e()}),this.xhr_.addEventListener("error",()=>{this.errorCode_=$N.NETWORK_ERROR,e()}),this.xhr_.addEventListener("load",()=>{e()})})}send(e,t,r,n){if(this.sent_)throw cR("cannot .send() more than once");if(this.sent_=!0,this.xhr_.open(t,e,!0),void 0!==n)for(var i in n)n.hasOwnProperty(i)&&this.xhr_.setRequestHeader(i,n[i].toString());return void 0!==r?this.xhr_.send(r):this.xhr_.send(),this.sendPromise_}getErrorCode(){if(this.sent_)return this.errorCode_;throw cR("cannot .getErrorCode() before sending")}getStatus(){if(!this.sent_)throw cR("cannot .getStatus() before sending");try{return this.xhr_.status}catch(e){return-1}}getResponse(){if(this.sent_)return this.xhr_.response;throw cR("cannot .getResponse() before sending")}getErrorText(){if(this.sent_)return this.xhr_.statusText;throw cR("cannot .getErrorText() before sending")}abort(){this.xhr_.abort()}getResponseHeader(e){return this.xhr_.getResponseHeader(e)}addUploadProgressListener(e){null!=this.xhr_.upload&&this.xhr_.upload.addEventListener("progress",e)}removeUploadProgressListener(e){null!=this.xhr_.upload&&this.xhr_.upload.removeEventListener("progress",e)}}{initXhr(){this.xhr_.responseType="text"}}function cP(){return new uP}class dP{isExponentialBackoffExpired(){return this.sleepTime>this.maxSleepTime}constructor(e,t,r=null){this._transferred=0,this._needToFetchStatus=!1,this._needToFetchMetadata=!1,this._observers=[],this._error=void 0,this._uploadUrl=void 0,this._request=void 0,this._chunkMultiplier=1,this._resolve=void 0,this._reject=void 0,this._ref=e,this._blob=t,this._metadata=r,this._mappings=FR(),this._resumable=this._shouldDoResumable(this._blob),this._state="running",this._errorHandler=e=>{if(this._request=void 0,this._chunkMultiplier=1,e._codeEquals(GN.CANCELED))this._needToFetchStatus=!0,this.completeTransitions_();else{var t=this.isExponentialBackoffExpired();if(wR(e.status,[])){if(!t)return this.sleepTime=Math.max(2*this.sleepTime,1e3),this._needToFetchStatus=!0,void this.completeTransitions_();e=iR()}this._error=e,this._transition("error")}},this._metadataErrorHandler=e=>{this._request=void 0,e._codeEquals(GN.CANCELED)?this.completeTransitions_():(this._error=e,this._transition("error"))},this.sleepTime=0,this.maxSleepTime=this._ref.storage.maxUploadRetryTime,this._promise=new Promise((e,t)=>{this._resolve=e,this._reject=t,this._start()}),this._promise.then(null,()=>{})}_makeProgressCallback(){let t=this._transferred;return e=>this._updateProgress(t+e)}_shouldDoResumable(e){return 262144<e.size()}_start(){"running"===this._state&&void 0===this._request&&(this._resumable?void 0===this._uploadUrl?this._createResumable():this._needToFetchStatus?this._fetchStatus():this._needToFetchMetadata?this._fetchMetadata():this.pendingTimeout=setTimeout(()=>{this.pendingTimeout=void 0,this._continueUpload()},this.sleepTime):this._oneShotUpload())}_resolveToken(r){Promise.all([this._ref.storage._getAuthToken(),this._ref.storage._getAppCheckToken()]).then(([e,t])=>{switch(this._state){case"running":r(e,t);break;case"canceling":this._transition("canceled");break;case"pausing":this._transition("paused")}})}_createResumable(){this._resolveToken((e,t)=>{var r=rP(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),r=this._ref.storage._makeRequest(r,cP,e,t);(this._request=r).getPromise().then(e=>{this._request=void 0,this._uploadUrl=e,this._needToFetchStatus=!1,this.completeTransitions_()},this._errorHandler)})}_fetchStatus(){let n=this._uploadUrl;this._resolveToken((e,t)=>{var r=nP(this._ref.storage,this._ref._location,n,this._blob),r=this._ref.storage._makeRequest(r,cP,e,t);(this._request=r).getPromise().then(e=>{this._request=void 0,this._updateProgress(e.current),this._needToFetchStatus=!1,e.finalized&&(this._needToFetchMetadata=!0),this.completeTransitions_()},this._errorHandler)})}_continueUpload(){let i=262144*this._chunkMultiplier,s=new eP(this._transferred,this._blob.size()),a=this._uploadUrl;this._resolveToken((e,t)=>{let r;try{r=iP(this._ref._location,this._ref.storage,a,this._blob,i,this._mappings,s,this._makeProgressCallback())}catch(e){return this._error=e,void this._transition("error")}var n=this._ref.storage._makeRequest(r,cP,e,t,!1);(this._request=n).getPromise().then(e=>{this._increaseMultiplier(),this._request=void 0,this._updateProgress(e.current),e.finalized?(this._metadata=e.metadata,this._transition("success")):this.completeTransitions_()},this._errorHandler)})}_increaseMultiplier(){2*(262144*this._chunkMultiplier)<33554432&&(this._chunkMultiplier*=2)}_fetchMetadata(){this._resolveToken((e,t)=>{var r=JR(this._ref.storage,this._ref._location,this._mappings),r=this._ref.storage._makeRequest(r,cP,e,t);(this._request=r).getPromise().then(e=>{this._request=void 0,this._metadata=e,this._transition("success")},this._metadataErrorHandler)})}_oneShotUpload(){this._resolveToken((e,t)=>{var r=ZR(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),r=this._ref.storage._makeRequest(r,cP,e,t);(this._request=r).getPromise().then(e=>{this._request=void 0,this._metadata=e,this._updateProgress(this._blob.size()),this._transition("success")},this._errorHandler)})}_updateProgress(e){var t=this._transferred;this._transferred=e,this._transferred!==t&&this._notifyObservers()}_transition(e){if(this._state!==e)switch(e){case"canceling":case"pausing":this._state=e,void 0!==this._request?this._request.cancel():this.pendingTimeout&&(clearTimeout(this.pendingTimeout),this.pendingTimeout=void 0,this.completeTransitions_());break;case"running":var t="paused"===this._state;this._state=e,t&&(this._notifyObservers(),this._start());break;case"paused":this._state=e,this._notifyObservers();break;case"canceled":this._error=sR(),this._state=e,this._notifyObservers();break;case"error":case"success":this._state=e,this._notifyObservers()}}completeTransitions_(){switch(this._state){case"pausing":this._transition("paused");break;case"canceling":this._transition("canceled");break;case"running":this._start()}}get snapshot(){var e=oP(this._state);return{bytesTransferred:this._transferred,totalBytes:this._blob.size(),state:e,metadata:this._metadata,task:this,ref:this._ref}}on(e,t,r,n){let i=new lP(t||void 0,r||void 0,n||void 0);return this._addObserver(i),()=>{this._removeObserver(i)}}then(e,t){return this._promise.then(e,t)}catch(e){return this.then(null,e)}_addObserver(e){this._observers.push(e),this._notifyObserver(e)}_removeObserver(e){var t=this._observers.indexOf(e);-1!==t&&this._observers.splice(t,1)}_notifyObservers(){this._finishPromise(),this._observers.slice().forEach(e=>{this._notifyObserver(e)})}_finishPromise(){if(void 0!==this._resolve){let e=!0;switch(oP(this._state)){case aP.SUCCESS:hP(this._resolve.bind(null,this.snapshot))();break;case aP.CANCELED:case aP.ERROR:hP(this._reject.bind(null,this._error))();break;default:e=!1}e&&(this._resolve=void 0,this._reject=void 0)}}_notifyObserver(e){switch(oP(this._state)){case aP.RUNNING:case aP.PAUSED:e.next&&hP(e.next.bind(e,this.snapshot))();break;case aP.SUCCESS:e.complete&&hP(e.complete.bind(e))();break;case aP.CANCELED:case aP.ERROR:default:e.error&&hP(e.error.bind(e,this._error))()}}resume(){var e="paused"===this._state||"pausing"===this._state;return e&&this._transition("running"),e}pause(){var e="running"===this._state;return e&&this._transition("pausing"),e}cancel(){var e="running"===this._state||"pausing"===this._state;return e&&this._transition("canceling"),e}}class pP{constructor(e,t){this._service=e,t instanceof dR?this._location=t:this._location=dR.makeFromUrl(t,e.host)}toString(){return"gs://"+this._location.bucket+"/"+this._location.path}_newRef(e,t){return new pP(e,t)}get root(){var e=new dR(this._location.bucket,"");return this._newRef(this._service,e)}get bucket(){return this._location.bucket}get fullPath(){return this._location.path}get name(){return xR(this._location.path)}get storage(){return this._service}get parent(){var e,t,r=0===(e=this._location.path).length?null:-1===(r=e.lastIndexOf("/"))?"":e.slice(0,r);return null===r?null:(t=new dR(this._location.bucket,r),new pP(this._service,t))}_throwIfRoot(e){if(""===this._location.path)throw hR(e)}}function fP(e){let t={prefixes:[],items:[]};return async function e(t,r,n){let i={pageToken:n};let s=await gP(t,i);r.prefixes.push(...s.prefixes);r.items.push(...s.items);null!=s.nextPageToken&&await e(t,r,s.nextPageToken)}(e,t).then(()=>t)}function gP(e,t){null!=t&&"number"==typeof t.maxResults&&vR("options.maxResults",1,1e3,t.maxResults);var r,n,i,s,a,o=t||{},l=(t=e.storage,r=e._location,n="/",i=o.pageToken,s=o.maxResults,o={},r.isRoot?o.prefix="":o.prefix=r.path+"/",n&&0<n.length&&(o.delimiter=n),i&&(o.pageToken=i),s&&(o.maxResults=s),a=_R(a=r.bucketOnlyServerUrl(),t.host,t._protocol),l=t.maxOperationRetryTime,(a=new KR(a,"GET",GR(t,r.bucket),l)).urlParams=o,a.errorHandler=QR(r),a);return e.storage.makeRequestWithTokens(l,cP)}function mP(e,t){e._throwIfRoot("updateMetadata");r=e.storage,n=e._location,t=t,i=FR(),s=_R(n.fullServerUrl(),r.host,r._protocol),a=qR(t,i),o=r.maxOperationRetryTime,(s=new KR(s,"PATCH",HR(r,i),o)).headers={"Content-Type":"application/json; charset=utf-8"},s.body=a,s.errorHandler=YR(n);var r,n,i,s,a,o=s;return e.storage.makeRequestWithTokens(o,cP)}function vP(e){e._throwIfRoot("getDownloadURL");t=e.storage,r=e._location,n=FR(),i=_R(r.fullServerUrl(),t.host,t._protocol),s=t.maxOperationRetryTime,(i=new KR(i,"GET",$R(t,n),s)).errorHandler=YR(r);var t,r,n,i,s=i;return e.storage.makeRequestWithTokens(s,cP).then(e=>{if(null===e)throw new tR(GN.NO_DOWNLOAD_URL,"The given file does not have any download URLs.");return e})}function _P(e){e._throwIfRoot("deleteObject");t=e.storage,n=_R((r=e._location).fullServerUrl(),t.host,t._protocol),i=t.maxOperationRetryTime,(n=new KR(n,"DELETE",function(e,t){},i)).successCodes=[200,204],n.errorHandler=YR(r);var t,r,n,i=n;return e.storage.makeRequestWithTokens(i,cP)}function yP(e,t){r=e._location.path,n=t.split("/").filter(e=>0<e.length).join("/");var r,n=0===r.length?n:r+"/"+n,n=new dR(e._location.bucket,n);return new pP(e.storage,n)}function wP(e,t){if(e instanceof TP){var r=e;if(null==r._bucket)throw new tR(GN.NO_DEFAULT_BUCKET,"No default bucket found. Did you set the '"+eR+"' property when initializing the app?");r=new pP(r,r._bucket);return null!=t?wP(r,t):r}return void 0!==t?yP(e,t):e}function bP(e,t){if(t&&/^[A-Za-z]+:\/\//.test(t)){if(e instanceof TP)return r=e,n=t,new pP(r,n);throw oR("To use ref(service, url), the first argument must be a Storage instance.")}return wP(e,t);var r,n}function IP(e,t){var r=null==t?void 0:t[eR];return null==r?null:dR.makeFromBucketSpec(r,e)}class TP{constructor(e,t,r,n,i){this.app=e,this._authProvider=t,this._appCheckProvider=r,this._url=n,this._firebaseVersion=i,this._bucket=null,this._host=ZN,this._protocol="https",this._appId=null,this._deleted=!1,this._maxOperationRetryTime=12e4,this._maxUploadRetryTime=6e5,this._requests=new Set,this._bucket=null!=n?dR.makeFromBucketSpec(n,this._host):IP(this._host,this.app.options)}get host(){return this._host}set host(e){this._host=e,null!=this._url?this._bucket=dR.makeFromBucketSpec(this._url,e):this._bucket=IP(e,this.app.options)}get maxUploadRetryTime(){return this._maxUploadRetryTime}set maxUploadRetryTime(e){vR("time",0,Number.POSITIVE_INFINITY,e),this._maxUploadRetryTime=e}get maxOperationRetryTime(){return this._maxOperationRetryTime}set maxOperationRetryTime(e){vR("time",0,Number.POSITIVE_INFINITY,e),this._maxOperationRetryTime=e}async _getAuthToken(){if(this._overrideAuthToken)return this._overrideAuthToken;var e=this._authProvider.getImmediate({optional:!0});if(e){e=await e.getToken();if(null!==e)return e.accessToken}return null}async _getAppCheckToken(){var e;return h(this.app)&&this.app.settings.appCheckToken?this.app.settings.appCheckToken:(e=this._appCheckProvider.getImmediate({optional:!0}))?(await e.getToken()).token:null}_delete(){return this._deleted||(this._deleted=!0,this._requests.forEach(e=>e.cancel()),this._requests.clear()),Promise.resolve()}_makeStorageReference(e){return new pP(this,e)}_makeRequest(t,r,n,i,s=!0){if(this._deleted)return new pR(lR());{[t,n,i,r,s,a,o=!0]=[t,this._appId,n,i,r,this._firebaseVersion,s],h=yR(t.urlParams),h=t.url+h,u=Object.assign({},t.headers),l=u,(n=n)&&(l["X-Firebase-GMPID"]=n),l=u,null!==(n=i)&&0<n.length&&(l.Authorization="Firebase "+n),i=a,u["X-Firebase-Storage-Version"]="webjs/"+(null!=i?i:"AppManager"),l=u,null!==(n=r)&&(l["X-Firebase-AppCheck"]=n);let e=new bR(h,t.method,u,t.body,t.successCodes,t.additionalRetryCodes,t.handler,t.errorHandler,t.timeout,t.progressCallback,s,o);return this._requests.add(e),e.getPromise().then(()=>this._requests.delete(e),()=>this._requests.delete(e)),e}var a,o,l,h,u}async makeRequestWithTokens(e,t){var[r,n]=await Promise.all([this._getAuthToken(),this._getAppCheckToken()]);return this._makeRequest(e,t,r,n).getPromise()}}let EP="@firebase/storage";function CP(e,t,r){return e=w(e),t=t,r=r,(e=e)._throwIfRoot("uploadBytesResumable"),new dP(e,new PR(t),r)}function kP(e){return e=w(e),(e=e)._throwIfRoot("getMetadata"),t=JR(e.storage,e._location,FR()),e.storage.makeRequestWithTokens(t,cP);var t}function SP(e,t){return bP(e=w(e),t)}function AP(e,t,r,n={}){var i;[e,t,r,n={}]=[e,t,r,n],e.host=t+":"+r,e._protocol="http",(i=n.mockUserToken)&&(e._overrideAuthToken="string"==typeof i?i:Z(i,e.app.options.projectId))}function NP(e,{instanceIdentifier:t}){var r=e.getProvider("app").getImmediate(),n=e.getProvider("auth-internal"),i=e.getProvider("app-check-internal");return new TP(r,n,i,t,Dt)}Ct(new u("storage",NP,"PUBLIC").setMultipleInstances(!0)),d(EP,"0.13.6",""),d(EP,"0.13.6","esm2017");class RP{constructor(e,t,r){this._delegate=e,this.task=t,this.ref=r}get bytesTransferred(){return this._delegate.bytesTransferred}get metadata(){return this._delegate.metadata}get state(){return this._delegate.state}get totalBytes(){return this._delegate.totalBytes}}class PP{constructor(e,t){this._delegate=e,this._ref=t,this.cancel=this._delegate.cancel.bind(this._delegate),this.catch=this._delegate.catch.bind(this._delegate),this.pause=this._delegate.pause.bind(this._delegate),this.resume=this._delegate.resume.bind(this._delegate)}get snapshot(){return new RP(this._delegate.snapshot,this,this._ref)}then(t,e){return this._delegate.then(e=>{if(t)return t(new RP(e,this,this._ref))},e)}on(e,t,r,n){let i=void 0;return t&&(i="function"==typeof t?e=>t(new RP(e,this,this._ref)):{next:t.next?e=>t.next(new RP(e,this,this._ref)):void 0,complete:t.complete||void 0,error:t.error||void 0}),this._delegate.on(e,i,r||void 0,n||void 0)}}class DP{constructor(e,t){this._delegate=e,this._service=t}get prefixes(){return this._delegate.prefixes.map(e=>new xP(e,this._service))}get items(){return this._delegate.items.map(e=>new xP(e,this._service))}get nextPageToken(){return this._delegate.nextPageToken||null}}class xP{constructor(e,t){this._delegate=e,this.storage=t}get name(){return this._delegate.name}get bucket(){return this._delegate.bucket}get fullPath(){return this._delegate.fullPath}toString(){return this._delegate.toString()}child(e){var t=yP(this._delegate,e);return new xP(t,this.storage)}get root(){return new xP(this._delegate.root,this.storage)}get parent(){var e=this._delegate.parent;return null==e?null:new xP(e,this.storage)}put(e,t){return this._throwIfRoot("put"),new PP(CP(this._delegate,e,t),this)}putString(e,t=CR.RAW,r){this._throwIfRoot("putString");var n=SR(t,e),i=Object.assign({},r);return null==i.contentType&&null!=n.contentType&&(i.contentType=n.contentType),new PP(new dP(this._delegate,new PR(n.data,!0),i),this)}listAll(){return fP(w(this._delegate)).then(e=>new DP(e,this.storage))}list(e){return t=this._delegate,e=e||void 0,gP(t=w(t),e).then(e=>new DP(e,this.storage));var t}getMetadata(){return kP(this._delegate)}updateMetadata(e){return mP(w(this._delegate),e)}getDownloadURL(){return vP(w(this._delegate))}delete(){return this._throwIfRoot("delete"),_P(w(this._delegate))}_throwIfRoot(e){if(""===this._delegate._location.path)throw hR(e)}}class OP{constructor(e,t){this.app=e,this._delegate=t}get maxOperationRetryTime(){return this._delegate.maxOperationRetryTime}get maxUploadRetryTime(){return this._delegate.maxUploadRetryTime}ref(e){if(LP(e))throw oR("ref() expected a child path but got a URL, use refFromURL instead.");return new xP(SP(this._delegate,e),this)}refFromURL(e){if(!LP(e))throw oR("refFromURL() expected a full URL but got a child path, use ref() instead.");try{dR.makeFromUrl(e,this._delegate.host)}catch(e){throw oR("refFromUrl() expected a valid full URL but got an invalid one.")}return new xP(SP(this._delegate,e),this)}setMaxUploadRetryTime(e){this._delegate.maxUploadRetryTime=e}setMaxOperationRetryTime(e){this._delegate.maxOperationRetryTime=e}useEmulator(e,t,r={}){AP(this._delegate,e,t,r)}}function LP(e){return/^[A-Za-z]+:\/\//.test(e)}function MP(e,{instanceIdentifier:t}){var r=e.getProvider("app-compat").getImmediate(),n=e.getProvider("storage").getImmediate({identifier:t});return new OP(r,n)}QN=tr,ym={TaskState:aP,TaskEvent:sP,StringFormat:CR,Storage:OP,Reference:xP},QN.INTERNAL.registerComponent(new u("storage-compat",MP,"PUBLIC").setServiceProps(ym).setMultipleInstances(!0)),QN.registerVersion("@firebase/storage-compat","0.3.16");function FP(e){if("loading"===document.readyState)return"loading";var t=GP();if(t){if(e<t.domInteractive)return"loading";if(0===t.domContentLoadedEventStart||e<t.domContentLoadedEventStart)return"dom-interactive";if(0===t.domComplete||e<t.domComplete)return"dom-content-loaded"}return"complete"}function UP(e,t){var r="";try{for(;e&&9!==e.nodeType;){var n=e,i=n.id?"#"+n.id:$P(n)+(n.classList&&n.classList.value&&n.classList.value.trim()&&n.classList.value.trim().length?"."+n.classList.value.trim().replace(/\s+/g,"."):"");if(r.length+i.length>(t||100)-1)return r||i;if(r=r?i+">"+r:i,n.id)break;e=n.parentNode}}catch(e){}return r}function VP(i,e){var a,o,s,l;a=function(e){r={},(e=e).entries.length&&(t=e.entries.reduce(function(e,t){return e&&e.value>t.value?e:t}))&&t.sources&&t.sources.length&&(n=(n=t.sources).find(function(e){return e.node&&1===e.node.nodeType})||n[0])&&(r={largestShiftTarget:UP(n.node),largestShiftTime:t.startTime,largestShiftValue:t.value,largestShiftSource:n,largestShiftEntry:t,loadState:FP(t.startTime)});var t,r,n=Object.assign(e,{attribution:r});i(n)},o=e||{},s=iD(function(){function e(e){e.forEach(function(e){var t,r;e.hadRecentInput||(t=i[0],r=i[i.length-1],n&&e.startTime-r.startTime<1e3&&e.startTime-t.startTime<5e3?(n+=e.value,i.push(e)):(n=e.value,i=[e]))}),n>r.value&&(r.value=n,r.entries=i,t())}var t,r=ZP("CLS",0),n=0,i=[],s=eD("layout-shift",e);s&&(t=tD(a,r,pD,o.reportAllChanges),nD(function(){e(s.takeRecords()),t(!0)}),JP(function(){r=ZP("CLS",n=0),t=tD(a,r,pD,o.reportAllChanges),rD(function(){return t()})}),setTimeout(t,0))}),l=l||{},cD(function(){var t,r=uD(),n=ZP("FCP"),i=eD("paint",function(e){e.forEach(function(e){"first-contentful-paint"===e.name&&(i.disconnect(),e.startTime<r.firstHiddenTime)&&(n.value=Math.max(e.startTime-XP(),0),n.entries.push(e),t(!0))})});i&&(t=tD(s,n,dD,l.reportAllChanges),JP(function(e){n=ZP("FCP"),t=tD(s,n,dD,l.reportAllChanges),rD(function(){n.value=performance.now()-e.timeStamp,t(!0)})}))})}function qP(s,a){"PerformanceEventTiming"in self&&"interactionId"in PerformanceEventTiming.prototype&&(a=a||{},cD(function(){var e;yD();function t(t){kD(function(){t.forEach(CD);var e=TD();e&&e.latency!==r.value&&(r.value=e.latency,r.entries=e.entries,i())})}var r=ZP("INP"),n=eD("event",t,{durationThreshold:null!=(e=a.durationThreshold)?e:40}),i=tD(s,r,SD,a.reportAllChanges);n&&(n.observe({type:"first-input",buffered:!0}),nD(function(){t(n.takeRecords()),i(!0)}),JP(function(){ID=_D(),wD.length=0,bD.clear(),r=ZP("INP"),i=tD(s,r,SD,a.reportAllChanges)}))}))}function jP(e){AD=AD.concat(e),OD()}function BP(){10<DD.size&&DD.forEach(function(e,t){bD.has(t)||DD.delete(t)});var r=wD.map(function(e){return PD.get(e.entries[0])}),n=ND.length-50;ND=ND.filter(function(e,t){return n<=t||r.includes(e)});for(var i=new Set,e=0;e<ND.length;e++){var t=ND[e];LD(t.startTime,t.processingEnd).forEach(function(e){i.add(e)})}var s=AD.length-1-50;AD=AD.filter(function(e,t){return e.startTime>RD&&s<t||i.has(e)}),xD=-1}function zP(l,e){HP=HP||eD("long-animation-frame",jP),qP(function(e){t=(e=e).entries[0],o=PD.get(t),r=t.processingStart,n=o.processingEnd,o=o.entries.sort(function(e,t){return e.processingStart-t.processingStart}),i=LD(t.startTime,n),s=(s=e.entries.find(function(e){return e.target}))&&s.target||DD.get(t.interactionId),a=[t.startTime+t.duration,n].concat(i.map(function(e){return e.startTime+e.duration})),a=Math.max.apply(Math,a),s={interactionTarget:UP(s),interactionTargetElement:s,interactionType:t.name.startsWith("key")?"keyboard":"pointer",interactionTime:t.startTime,nextPaintTime:a,processedEventEntries:o,longAnimationFrameEntries:i,inputDelay:r-t.startTime,processingDuration:n-r,presentationDelay:Math.max(a-n,0),loadState:FP(t.startTime)};var t,r,n,i,s,a,o=Object.assign(e,{attribution:s});l(o)},e)}function KP(h,e){var a,o;a=function(e){o={timeToFirstByte:0,resourceLoadDelay:0,resourceLoadDuration:0,elementRenderDelay:(e=e).value},e.entries.length&&(t=GP())&&(a=t.activationStart||0,n=(r=e.entries[e.entries.length-1]).url&&performance.getEntriesByType("resource").filter(function(e){return e.name===r.url})[0],l=Math.max(0,t.responseStart-a),i=Math.max(l,n?(n.requestStart||n.startTime)-a:0),s=Math.max(i,n?n.responseEnd-a:0),a=Math.max(s,r.startTime-a),o={element:UP(r.element),timeToFirstByte:l,resourceLoadDelay:i-l,resourceLoadDuration:s-i,elementRenderDelay:a-s,navigationEntry:t,lcpEntry:r},r.url&&(o.url=r.url),n)&&(o.lcpResourceEntry=n);var t,r,n,i,s,a,o,l=Object.assign(e,{attribution:o});h(l)},o=e||{},cD(function(){function e(e){(e=o.reportAllChanges?e:e.slice(-1)).forEach(function(e){e.startTime<n.firstHiddenTime&&(i.value=Math.max(e.startTime-XP(),0),i.entries=[e],t())})}var t,r,n=uD(),i=ZP("LCP"),s=eD("largest-contentful-paint",e);s&&(t=tD(a,i,MD,o.reportAllChanges),r=iD(function(){FD[i.id]||(e(s.takeRecords()),s.disconnect(),FD[i.id]=!0,t(!0))}),["keydown","click"].forEach(function(e){addEventListener(e,function(){return kD(r)},{once:!0,capture:!0})}),nD(r),JP(function(e){i=ZP("LCP"),t=tD(a,i,MD,o.reportAllChanges),rD(function(){i.value=performance.now()-e.timeStamp,FD[i.id]=!0,t(!0)})}))})}var WP,HP,GP=function(){var e=self.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0];if(e&&0<e.responseStart&&e.responseStart<performance.now())return e},$P=function(e){var t=e.nodeName;return 1===e.nodeType?t.toLowerCase():t.toUpperCase().replace(/^#/,"")},QP=-1,YP=function(){return QP},JP=function(t){addEventListener("pageshow",function(e){e.persisted&&(QP=e.timeStamp,t(e))},!0)},XP=function(){var e=GP();return e&&e.activationStart||0},ZP=function(e,t){var r=GP(),n="navigate";return 0<=YP()?n="back-forward-cache":r&&(document.prerendering||0<XP()?n="prerender":document.wasDiscarded?n="restore":r.type&&(n=r.type.replace(/_/g,"-"))),{name:e,value:void 0===t?-1:t,rating:"good",delta:0,entries:[],id:"v4-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:n}},eD=function(e,t,r){try{var n;if(PerformanceObserver.supportedEntryTypes.includes(e))return(n=new PerformanceObserver(function(e){Promise.resolve().then(function(){t(e.getEntries())})})).observe(Object.assign({type:e,buffered:!0},r||{})),n}catch(e){}},tD=function(t,r,n,i){var s,a;return function(e){0<=r.value&&(e||i)&&((a=r.value-(s||0))||void 0===s)&&(s=r.value,r.delta=a,r.rating=(e=r.value)>n[1]?"poor":e>n[0]?"needs-improvement":"good",t(r))}},rD=function(e){requestAnimationFrame(function(){return requestAnimationFrame(function(){return e()})})},nD=function(e){document.addEventListener("visibilitychange",function(){"hidden"===document.visibilityState&&e()})},iD=function(e){var t=!1;return function(){t||(e(),t=!0)}},sD=-1,aD=function(){return"hidden"!==document.visibilityState||document.prerendering?1/0:0},oD=function(e){"hidden"===document.visibilityState&&-1<sD&&(sD="visibilitychange"===e.type?e.timeStamp:0,hD())},lD=function(){addEventListener("visibilitychange",oD,!0),addEventListener("prerenderingchange",oD,!0)},hD=function(){removeEventListener("visibilitychange",oD,!0),removeEventListener("prerenderingchange",oD,!0)},uD=function(){return sD<0&&(sD=aD(),lD(),JP(function(){setTimeout(function(){sD=aD(),lD()},0)})),{get firstHiddenTime(){return sD}}},cD=function(e){document.prerendering?addEventListener("prerenderingchange",function(){return e()},!0):e()},dD=[1800,3e3],pD=[.1,.25],fD=0,gD=1/0,mD=0,vD=function(e){e.forEach(function(e){e.interactionId&&(gD=Math.min(gD,e.interactionId),mD=Math.max(mD,e.interactionId),fD=mD?(mD-gD)/7+1:0)})},_D=function(){return WP?fD:performance.interactionCount||0},yD=function(){"interactionCount"in performance||(WP=WP||eD("event",vD,{type:"event",buffered:!0,durationThreshold:0}))},wD=[],bD=new Map,ID=0,TD=function(){var e=Math.min(wD.length-1,Math.floor((_D()-ID)/50));return wD[e]},ED=[],CD=function(t){var e,r;ED.forEach(function(e){return e(t)}),!t.interactionId&&"first-input"!==t.entryType||(r=wD[wD.length-1],((e=bD.get(t.interactionId))||wD.length<10||t.duration>r.latency)&&(e?t.duration>e.latency?(e.entries=[t],e.latency=t.duration):t.duration===e.latency&&t.startTime===e.entries[0].startTime&&e.entries.push(t):(r={id:t.interactionId,latency:t.duration,entries:[t]},bD.set(r.id,r),wD.push(r)),wD.sort(function(e,t){return t.latency-e.latency}),10<wD.length)&&wD.splice(10).forEach(function(e){return bD.delete(e.id)}))},kD=function(e){var t=self.requestIdleCallback||self.setTimeout,r=-1;return e=iD(e),"hidden"===document.visibilityState?e():(r=t(e),nD(e)),r},SD=[200,500],AD=[],ND=[],RD=0,PD=new WeakMap,DD=new Map,xD=-1,OD=function(){xD<0&&(xD=kD(BP))},LD=(ED.push(function(e){e.interactionId&&e.target&&!DD.has(e.interactionId)&&DD.set(e.interactionId,e.target)},function(e){var t,r=e.startTime+e.duration;RD=Math.max(RD,e.processingEnd);for(var n=ND.length-1;0<=n;n--){var i=ND[n];if(Math.abs(r-i.renderTime)<=8){(t=i).startTime=Math.min(e.startTime,t.startTime),t.processingStart=Math.min(e.processingStart,t.processingStart),t.processingEnd=Math.max(e.processingEnd,t.processingEnd),t.entries.push(e);break}}t||(t={startTime:e.startTime,processingStart:e.processingStart,processingEnd:e.processingEnd,renderTime:r,entries:[e]},ND.push(t)),!e.interactionId&&"first-input"!==e.entryType||PD.set(e,t),OD()}),function(e,t){for(var r,n=[],i=0;r=AD[i];i++)if(!(r.startTime+r.duration<e)){if(r.startTime>t)break;n.push(r)}return n}),MD=[2500,4e3],FD={};let UD="@firebase/performance",VD="0.7.0",qD=VD,jD="FB-PERF-TRACE-MEASURE",BD="@firebase/performance/config",zD="@firebase/performance/configexpire";var KD,t,r,WD,e="Performance";let HD=new pe("performance",e,{"trace started":"Trace {$traceName} was started before.","trace stopped":"Trace {$traceName} is not running.","nonpositive trace startTime":"Trace {$traceName} startTime should be positive.","nonpositive trace duration":"Trace {$traceName} duration should be positive.","no window":"Window is not available.","no app id":"App id is not available.","no project id":"Project id is not available.","no api key":"Api key is not available.","invalid cc log":"Attempted to queue invalid cc event","FB not default":"Performance can only start when Firebase app instance is the default one.","RC response not ok":"RC response is not ok","invalid attribute name":"Attribute name {$attributeName} is invalid.","invalid attribute value":"Attribute value {$attributeValue} is invalid.","invalid custom metric name":"Custom metric name {$customMetricName} is invalid","invalid String merger input":"Input for String merger is invalid, contact support team to resolve.","already initialized":"initializePerformance() has already been called with different options. To avoid this error, call initializePerformance() with the same options as when it was originally called, or call getPerformance() to return the already initialized instance."}),GD=new $e(e);GD.logLevel=c.INFO;let $D,QD;class YD{constructor(e){if(!(this.window=e))throw HD.create("no window");this.performance=e.performance,this.PerformanceObserver=e.PerformanceObserver,this.windowLocation=e.location,this.navigator=e.navigator,this.document=e.document,this.navigator&&this.navigator.cookieEnabled&&(this.localStorage=e.localStorage),e.perfMetrics&&e.perfMetrics.onFirstInputDelay&&(this.onFirstInputDelay=e.perfMetrics.onFirstInputDelay),this.onLCP=KP,this.onINP=zP,this.onCLS=VP}getUrl(){return this.windowLocation.href.split("?")[0]}mark(e){this.performance&&this.performance.mark&&this.performance.mark(e)}measure(e,t,r){this.performance&&this.performance.measure&&this.performance.measure(e,t,r)}getEntriesByType(e){return this.performance&&this.performance.getEntriesByType?this.performance.getEntriesByType(e):[]}getEntriesByName(e){return this.performance&&this.performance.getEntriesByName?this.performance.getEntriesByName(e):[]}getTimeOrigin(){return this.performance&&(this.performance.timeOrigin||this.performance.timing.navigationStart)}requiredApisAvailable(){return fetch&&Promise&&ce()?!!he()||(GD.info("IndexedDB is not supported by current browser"),!1):(GD.info("Firebase Performance cannot start if browser does not support fetch and Promise or cookie is disabled."),!1)}setupObserver(e,r){this.PerformanceObserver&&new this.PerformanceObserver(e=>{for(var t of e.getEntries())r(t)}).observe({entryTypes:[e]})}static getInstance(){return $D=void 0===$D?new YD(QD):$D}}let JD;function XD(e,t){var r=e.length-t.length;if(r<0||1<r)throw HD.create("invalid String merger input");var n=[];for(let i=0;i<e.length;i++)n.push(e.charAt(i)),t.length>i&&n.push(t.charAt(i));return n.join("")}let ZD;class ex{constructor(){this.instrumentationEnabled=!0,this.dataCollectionEnabled=!0,this.loggingEnabled=!1,this.tracesSamplingRate=1,this.networkRequestsSamplingRate=1,this.logEndPointUrl="https://firebaselogging.googleapis.com/v0cc/log?format=json_proto",this.flTransportEndpointUrl=XD("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),this.transportKey=XD("AzSC8r6ReiGqFMyfvgow","Iayx0u-XT3vksVM-pIV"),this.logSource=462,this.logTraceAfterSampling=!1,this.logNetworkAfterSampling=!1,this.configTimeToLive=12}getFlTransportFullUrl(){return this.flTransportEndpointUrl.concat("?key=",this.transportKey)}static getInstance(){return ZD=void 0===ZD?new ex:ZD}}(t=KD=KD||{})[t.UNKNOWN=0]="UNKNOWN",t[t.VISIBLE=1]="VISIBLE",t[t.HIDDEN=2]="HIDDEN";let tx=["firebase_","google_","ga_"],rx=new RegExp("^[a-zA-Z]\\w*$");function nx(e){var t=null==(t=e.options)?void 0:t.appId;if(t)return t;throw HD.create("no app id")}let ix="0.0.1",sx={loggingEnabled:!0},ax="FIREBASE_INSTALLATIONS_AUTH";function ox(e,t){var n,i,r=(()=>{var e=YD.getInstance().localStorage;if(e){var t=e.getItem(zD);if(t&&(e=>Number(e)>Date.now())(t)){t=e.getItem(BD);if(t)try{return JSON.parse(t)}catch(e){}}}})();return r?(hx(r),Promise.resolve()):(i=t,(e=>{var t=e.getToken();return t.then(e=>{}),t})((n=e).installations).then(e=>{var t=(e=>{var t=null==(t=e.options)?void 0:t.projectId;if(t)return t;throw HD.create("no project id")})(n.app),r=(e=>{var t=null==(t=e.options)?void 0:t.apiKey;if(t)return t;throw HD.create("no api key")})(n.app),t=new Request(`https://firebaseremoteconfig.googleapis.com/v1/projects/${t}/namespaces/fireperf:fetch?key=`+r,{method:"POST",headers:{Authorization:ax+" "+e},body:JSON.stringify({app_instance_id:i,app_instance_id_token:e,app_id:nx(n.app),app_version:qD,sdk_version:ix})});return fetch(t).then(e=>{if(e.ok)return e.json();throw HD.create("RC response not ok")})}).catch(()=>{GD.info(lx)}).then(hx).then(e=>{var t;e=e,t=YD.getInstance().localStorage,e&&t&&(t.setItem(BD,JSON.stringify(e)),t.setItem(zD,String(Date.now()+60*ex.getInstance().configTimeToLive*60*1e3)))},()=>{}))}let lx="Could not fetch config, will use default configs";function hx(e){var t,r;return e&&(t=ex.getInstance(),void 0!==(r=e.entries||{}).fpr_enabled?t.loggingEnabled="true"===String(r.fpr_enabled):t.loggingEnabled=sx.loggingEnabled,r.fpr_log_source?t.logSource=Number(r.fpr_log_source):sx.logSource&&(t.logSource=sx.logSource),r.fpr_log_endpoint_url?t.logEndPointUrl=r.fpr_log_endpoint_url:sx.logEndPointUrl&&(t.logEndPointUrl=sx.logEndPointUrl),r.fpr_log_transport_key?t.transportKey=r.fpr_log_transport_key:sx.transportKey&&(t.transportKey=sx.transportKey),void 0!==r.fpr_vc_network_request_sampling_rate?t.networkRequestsSamplingRate=Number(r.fpr_vc_network_request_sampling_rate):void 0!==sx.networkRequestsSamplingRate&&(t.networkRequestsSamplingRate=sx.networkRequestsSamplingRate),void 0!==r.fpr_vc_trace_sampling_rate?t.tracesSamplingRate=Number(r.fpr_vc_trace_sampling_rate):void 0!==sx.tracesSamplingRate&&(t.tracesSamplingRate=sx.tracesSamplingRate),t.logTraceAfterSampling=ux(t.tracesSamplingRate),t.logNetworkAfterSampling=ux(t.networkRequestsSamplingRate)),e}function ux(e){return Math.random()<=e}let cx=1,dx;function px(e){var r;return cx=2,dx=dx||(r=e,(()=>{let r=YD.getInstance().document;return new Promise(t=>{if(r&&"complete"!==r.readyState){let e=()=>{"complete"===r.readyState&&(r.removeEventListener("readystatechange",e),t())};r.addEventListener("readystatechange",e)}else t()})})().then(()=>{return e=r.installations,(t=e.getId()).then(e=>{JD=e}),t;var e,t}).then(e=>ox(r,e)).then(()=>fx(),()=>fx()))}function fx(){cx=3}let gx=1e4,mx=1e3,vx=3,_x=vx,yx=[],wx=!1;function bx(e){setTimeout(()=>{0!==_x&&(0<yx.length&&Ix(),bx(gx))},e)}function Ix(){let e=yx.splice(0,mx);var t,r,n=e.map(e=>({source_extension_json_proto3:e.message,event_time_ms:String(e.eventTime)})),n={request_time_ms:String(Date.now()),client_info:{client_type:1,js_client_info:{}},log_source:ex.getInstance().logSource,log_event:n};t=n,n=ex.getInstance().getFlTransportFullUrl(),r=JSON.stringify(t),(navigator.sendBeacon&&navigator.sendBeacon(n,r)?Promise.resolve():fetch(n,{method:"POST",body:r,keepalive:!0}).then()).then(()=>{_x=vx}).catch(()=>{yx=[...e,...yx],_x--,GD.info(`Tries left: ${_x}.`),bx(gx)})}function Tx(t){return(...e)=>{e={message:t(...e),eventTime:Date.now()};if(!e.eventTime||!e.message)throw HD.create("invalid cc log");yx=[...yx,e]}}function Ex(){for(;0<yx.length;)Ix()}let Cx;function kx(e,t){(Cx=Cx||{send:Tx(Nx),flush:Ex}).send(e,t)}function Sx(e){var t=ex.getInstance();!t.instrumentationEnabled&&e.isAuto||(t.dataCollectionEnabled||e.isAuto)&&YD.getInstance().requiredApisAvailable()&&(3===cx?Ax(e):px(e.performanceController).then(()=>Ax(e),()=>Ax(e)))}function Ax(e){var t;JD&&(t=ex.getInstance()).loggingEnabled&&t.logTraceAfterSampling&&kx(e,1)}function Nx(e,t){var r,n;return 0===t?(r={url:e.url,http_method:e.httpMethod||0,http_response_code:200,response_payload_bytes:e.responsePayloadBytes,client_start_time_us:e.startTimeUs,time_to_response_initiated_us:e.timeToResponseInitiatedUs,time_to_response_completed_us:e.timeToResponseCompletedUs},r={application_info:Rx(e.performanceController.app),network_request_metric:r},JSON.stringify(r)):(r={name:(t=e).name,is_auto:t.isAuto,client_start_time_us:t.startTimeUs,duration_us:t.durationUs},0!==Object.keys(t.counters).length&&(r.counters=t.counters),n=t.getAttributes(),0!==Object.keys(n).length&&(r.custom_attributes=n),n={application_info:Rx(t.performanceController.app),trace_metric:r},JSON.stringify(n))}function Rx(e){return{google_app_id:nx(e),app_instance_id:JD,web_app_info:{sdk_version:qD,page_url:YD.getInstance().getUrl(),service_worker_status:null!=(t=YD.getInstance().navigator)&&t.serviceWorker?t.serviceWorker.controller?2:3:1,visibility_state:(()=>{switch(YD.getInstance().document.visibilityState){case"visible":return KD.VISIBLE;case"hidden":return KD.HIDDEN;default:return KD.UNKNOWN}})(),effective_connection_type:(()=>{var e=YD.getInstance().navigator.connection;switch(e&&e.effectiveType){case"slow-2g":return 1;case"2g":return 2;case"3g":return 3;case"4g":return 4;default:return 0}})()},application_process_state:0};var t}function Px(e,t){var r,n,i,s=t;s&&void 0!==s.responseStart&&(i=YD.getInstance().getTimeOrigin(),i=Math.floor(1e3*(s.startTime+i)),r=s.responseStart?Math.floor(1e3*(s.responseStart-s.startTime)):void 0,n=Math.floor(1e3*(s.responseEnd-s.startTime)),s={performanceController:e,url:s.name&&s.name.split("?")[0],responsePayloadBytes:s.transferSize,startTimeUs:i,timeToResponseInitiatedUs:r,timeToResponseCompletedUs:n},t=s,(i=ex.getInstance()).instrumentationEnabled)&&(r=t.url,n=i.logEndPointUrl.split("?")[0],s=i.flTransportEndpointUrl.split("?")[0],r!==n)&&r!==s&&i.loggingEnabled&&i.logNetworkAfterSampling&&kx(t,0)}let Dx=["_fp","_fcp","_fid","_lcp","_cls","_inp"];class xx{constructor(e,t,r=!1,n){this.performanceController=e,this.name=t,this.isAuto=r,this.state=1,this.customAttributes={},this.counters={},this.api=YD.getInstance(),this.randomId=Math.floor(1e6*Math.random()),this.isAuto||(this.traceStartMark=`FB-PERF-TRACE-START-${this.randomId}-`+this.name,this.traceStopMark=`FB-PERF-TRACE-STOP-${this.randomId}-`+this.name,this.traceMeasure=n||`${jD}-${this.randomId}-`+this.name,n&&this.calculateTraceMetrics())}start(){if(1!==this.state)throw HD.create("trace started",{traceName:this.name});this.api.mark(this.traceStartMark),this.state=2}stop(){if(2!==this.state)throw HD.create("trace stopped",{traceName:this.name});this.state=3,this.api.mark(this.traceStopMark),this.api.measure(this.traceMeasure,this.traceStartMark,this.traceStopMark),this.calculateTraceMetrics(),Sx(this)}record(e,t,r){if(e<=0)throw HD.create("nonpositive trace startTime",{traceName:this.name});if(t<=0)throw HD.create("nonpositive trace duration",{traceName:this.name});if(this.durationUs=Math.floor(1e3*t),this.startTimeUs=Math.floor(1e3*e),r&&r.attributes&&(this.customAttributes=Object.assign({},r.attributes)),r&&r.metrics)for(var n of Object.keys(r.metrics))isNaN(Number(r.metrics[n]))||(this.counters[n]=Math.floor(Number(r.metrics[n])));Sx(this)}incrementMetric(e,t=1){void 0===this.counters[e]?this.putMetric(e,t):this.putMetric(e,this.counters[e]+t)}putMetric(e,t){if(n=e,i=this.name,0===n.length||100<n.length||!(i&&i.startsWith("_wt_")&&-1<Dx.indexOf(n))&&n.startsWith("_"))throw HD.create("invalid custom metric name",{customMetricName:e});var r,n,i;this.counters[e]=(i=null!=t?t:0,(r=Math.floor(i))<i&&GD.info(`Metric value should be an Integer, setting the value as : ${r}.`),r)}getMetric(e){return this.counters[e]||0}putAttribute(e,t){var r,n,i=!(0===(r=e).length||40<r.length||tx.some(e=>r.startsWith(e))||!r.match(rx)),s=0!==(n=t).length&&n.length<=100;if(i&&s)this.customAttributes[e]=t;else{if(!i)throw HD.create("invalid attribute name",{attributeName:e});if(!s)throw HD.create("invalid attribute value",{attributeValue:t})}}getAttribute(e){return this.customAttributes[e]}removeAttribute(e){void 0!==this.customAttributes[e]&&delete this.customAttributes[e]}getAttributes(){return Object.assign({},this.customAttributes)}setStartTime(e){this.startTimeUs=e}setDuration(e){this.durationUs=e}calculateTraceMetrics(){var e=this.api.getEntriesByName(this.traceMeasure),e=e&&e[0];e&&(this.durationUs=Math.floor(1e3*e.duration),this.startTimeUs=Math.floor(1e3*(e.startTime+this.api.getTimeOrigin())))}static createOobTrace(e,t,r,n,i){var s=YD.getInstance().getUrl();if(s){var s=new xx(e,"_wt_"+s,!0),a=Math.floor(1e3*YD.getInstance().getTimeOrigin());s.setStartTime(a),t&&t[0]&&(s.setDuration(Math.floor(1e3*t[0].duration)),s.putMetric("domInteractive",Math.floor(1e3*t[0].domInteractive)),s.putMetric("domContentLoadedEventEnd",Math.floor(1e3*t[0].domContentLoadedEventEnd)),s.putMetric("loadEventEnd",Math.floor(1e3*t[0].loadEventEnd)));r&&((a=r.find(e=>"first-paint"===e.name))&&a.startTime&&s.putMetric("_fp",Math.floor(1e3*a.startTime)),(a=r.find(e=>"first-contentful-paint"===e.name))&&a.startTime&&s.putMetric("_fcp",Math.floor(1e3*a.startTime)),i)&&s.putMetric("_fid",Math.floor(1e3*i)),this.addWebVitalMetric(s,"_lcp","lcp_element",n.lcp),this.addWebVitalMetric(s,"_cls","cls_largestShiftTarget",n.cls),this.addWebVitalMetric(s,"_inp","inp_interactionTarget",n.inp),Sx(s),Cx&&Cx.flush()}}static addWebVitalMetric(e,t,r,n){n&&(e.putMetric(t,Math.floor(1e3*n.value)),n.elementAttribution)&&e.putAttribute(r,n.elementAttribution)}static createUserTimingTrace(e,t){Sx(new xx(e,t,!1,t))}}let Ox={},Lx=!1,Mx;function Fx(n){JD&&(setTimeout(()=>{{var t=n;let e=YD.getInstance();"onpagehide"in window?e.document.addEventListener("pagehide",()=>Vx(t)):e.document.addEventListener("unload",()=>Vx(t)),e.document.addEventListener("visibilitychange",()=>{"hidden"===e.document.visibilityState&&Vx(t)}),e.onFirstInputDelay&&e.onFirstInputDelay(e=>{Mx=e}),e.onLCP(e=>{var t;Ox.lcp={value:e.value,elementAttribution:null==(t=e.attribution)?void 0:t.element}}),e.onCLS(e=>{var t;Ox.cls={value:e.value,elementAttribution:null==(t=e.attribution)?void 0:t.largestShiftTarget}}),e.onINP(e=>{var t;Ox.inp={value:e.value,elementAttribution:null==(t=e.attribution)?void 0:t.interactionTarget}})}},0),setTimeout(()=>{var e,t=n,r=YD.getInstance();for(e of r.getEntriesByType("resource"))Px(t,e);r.setupObserver("resource",e=>Px(t,e))},0),setTimeout(()=>{var e,t=n,r=YD.getInstance();for(e of r.getEntriesByType("measure"))Ux(t,e);r.setupObserver("measure",e=>Ux(t,e))},0))}function Ux(e,t){var r=t.name;r.substring(0,jD.length)!==jD&&xx.createUserTimingTrace(e,r)}function Vx(r){if(!Lx){Lx=!0;var n=YD.getInstance();let e=n.getEntriesByType("navigation"),t=n.getEntriesByType("paint");setTimeout(()=>{xx.createOobTrace(r,e,t,Ox,Mx)},0)}}class qx{constructor(e,t){this.app=e,this.installations=t,this.initialized=!1}_init(e){this.initialized||(void 0!==(null==e?void 0:e.dataCollectionEnabled)&&(this.dataCollectionEnabled=e.dataCollectionEnabled),void 0!==(null==e?void 0:e.instrumentationEnabled)&&(this.instrumentationEnabled=e.instrumentationEnabled),YD.getInstance().requiredApisAvailable()?ue().then(e=>{e&&(wx||(bx(5500),wx=!0),px(this).then(()=>Fx(this),()=>Fx(this)),this.initialized=!0)}).catch(e=>{GD.info("Environment doesn't support IndexedDB: "+e)}):GD.info('Firebase Performance cannot start if the browser does not support "Fetch" and "Promise", or cookies are disabled.'))}set instrumentationEnabled(e){ex.getInstance().instrumentationEnabled=e}get instrumentationEnabled(){return ex.getInstance().instrumentationEnabled}set dataCollectionEnabled(e){ex.getInstance().dataCollectionEnabled=e}get dataCollectionEnabled(){return ex.getInstance().dataCollectionEnabled}}let jx="[DEFAULT]";let Bx=(e,{options:t})=>{var r=e.getProvider("app").getImmediate(),n=e.getProvider("installations-internal").getImmediate();if(r.name!==jx)throw HD.create("FB not default");if("undefined"==typeof window)throw HD.create("no window");e=window,QD=e;r=new qx(r,n);return r._init(t),r};Ct(new u("performance",Bx,"PUBLIC")),d(UD,VD),d(UD,VD,"esm2017");class zx{constructor(e,t){this.app=e,this._delegate=t}get instrumentationEnabled(){return this._delegate.instrumentationEnabled}set instrumentationEnabled(e){this._delegate.instrumentationEnabled=e}get dataCollectionEnabled(){return this._delegate.dataCollectionEnabled}set dataCollectionEnabled(e){this._delegate.dataCollectionEnabled=e}trace(e){return t=this._delegate,e=e,t=w(t),new xx(t,e);var t}}function Kx(e){var t=e.getProvider("app-compat").getImmediate(),r=e.getProvider("performance").getImmediate();return new zx(t,r)}(r=tr).INTERNAL.registerComponent(new u("performance-compat",Kx,"PUBLIC")),r.registerVersion("@firebase/performance-compat","0.2.13");let Wx="@firebase/remote-config";class Hx{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach(e=>e())}}let Gx=new pe("remoteconfig","Remote Config",{"registration-window":"Undefined window object. This SDK only supports usage in a browser environment.","registration-project-id":"Undefined project identifier. Check Firebase app initialization.","registration-api-key":"Undefined API key. Check Firebase app initialization.","registration-app-id":"Undefined app identifier. Check Firebase app initialization.","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}.","storage-delete":"Error thrown when deleting from storage. Original error: {$originalErrorMessage}.","fetch-client-network":"Fetch client failed to connect to a network. Check Internet connection. Original error: {$originalErrorMessage}.","fetch-timeout":'The config fetch request timed out. Configure timeout using "fetchTimeoutMillis" SDK setting.',"fetch-throttle":'The config fetch request timed out while in an exponential backoff state. Configure timeout using "fetchTimeoutMillis" SDK setting. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',"fetch-client-parse":"Fetch client could not parse response. Original error: {$originalErrorMessage}.","fetch-status":"Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.","indexed-db-unavailable":"Indexed DB is not supported by current browser","custom-signal-max-allowed-signals":"Setting more than {$maxSignals} custom signals is not supported."});let $x=["1","true","t","yes","y","on"];class Qx{constructor(e,t=""){this._source=e,this._value=t}asString(){return this._value}asBoolean(){return"static"!==this._source&&0<=$x.indexOf(this._value.toLowerCase())}asNumber(){if("static"===this._source)return 0;let e=Number(this._value);return e=isNaN(e)?0:e}getSource(){return this._source}}async function Yx(e){var t=w(e),[r,n]=await Promise.all([t._storage.getLastSuccessfulFetchResponse(),t._storage.getActiveConfigEtag()]);return!!(r&&r.config&&r.eTag&&r.eTag!==n)&&(await Promise.all([t._storageCache.setActiveConfig(r.config),t._storage.setActiveConfigEtag(r.eTag)]),!0)}function Jx(e){let t=w(e);return t._initializePromise||(t._initializePromise=t._storageCache.loadFromStorage().then(()=>{t._isInitializationComplete=!0})),t._initializePromise}async function Xx(t){var r=w(t);let e=new Hx;setTimeout(async()=>{e.abort()},r.settings.fetchTimeoutMillis);var n,i=r._storageCache.getCustomSignals();i&&r._logger.debug("Fetching config with custom signals: "+JSON.stringify(i));try{await r._client.fetch({cacheMaxAgeMillis:r.settings.minimumFetchIntervalMillis,signal:e,customSignals:i}),await r._storageCache.setLastFetchStatus("success")}catch(e){t="fetch-throttle";i=(n=e)instanceof de&&-1!==n.code.indexOf(t)?"throttle":"failure";throw await r._storageCache.setLastFetchStatus(i),e}}function Zx(r){var e,t,n=w(r);return[e={},t={}]=[n._storageCache.getActiveConfig(),n.defaultConfig],Object.keys(Object.assign(Object.assign({},e),t)).reduce((e,t)=>(e[t]=e1(r,t),e),{})}function e1(e,t){var r=w(e),n=(r._isInitializationComplete||r._logger.debug(`A value was requested for key "${t}" before SDK initialization completed.`+" Await on ensureInitialized if the intent was to get a previously activated value."),r._storageCache.getActiveConfig());return n&&void 0!==n[t]?new Qx("remote",n[t]):r.defaultConfig&&void 0!==r.defaultConfig[t]?new Qx("default",String(r.defaultConfig[t])):(r._logger.debug(`Returning static value for key "${t}".`+" Define a default or remote value if this is unintentional."),new Qx("static"))}class t1{constructor(e,t,r,n){this.client=e,this.storage=t,this.storageCache=r,this.logger=n}isCachedDataFresh(e,t){var r;return t?(r=Date.now()-t,this.logger.debug("Config fetch cache check."+` Cache age millis: ${r}.`+` Cache max age millis (minimumFetchIntervalMillis setting): ${e}.`+` Is cache hit: ${r=r<=e}.`),r):(this.logger.debug("Config fetch cache check. Cache unpopulated."),!1)}async fetch(e){var[t,r]=await Promise.all([this.storage.getLastSuccessfulFetchTimestampMillis(),this.storage.getLastSuccessfulFetchResponse()]);if(r&&this.isCachedDataFresh(e.cacheMaxAgeMillis,t))return r;e.eTag=r&&r.eTag;t=await this.client.fetch(e),r=[this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now())];return 200===t.status&&r.push(this.storage.setLastSuccessfulFetchResponse(t)),await Promise.all(r),t}}class r1{constructor(e,t,r,n,i,s){this.firebaseInstallations=e,this.sdkVersion=t,this.namespace=r,this.projectId=n,this.apiKey=i,this.appId=s}async fetch(r){var e,[t,n]=await Promise.all([this.firebaseInstallations.getId(),this.firebaseInstallations.getToken()]),i=`${window.FIREBASE_REMOTE_CONFIG_URL_BASE||"https://firebaseremoteconfig.googleapis.com"}/v1/projects/${this.projectId}/namespaces/${this.namespace}:fetch?key=`+this.apiKey,s={"Content-Type":"application/json","Content-Encoding":"gzip","If-None-Match":r.eTag||"*"},t={sdk_version:this.sdkVersion,app_instance_id:t,app_instance_id_token:n,app_id:this.appId,language_code:(e=navigator).languages&&e.languages[0]||e.language,custom_signals:r.customSignals},n={method:"POST",headers:s,body:JSON.stringify(t)},s=fetch(i,n),t=new Promise((e,t)=>{r.signal.addEventListener(()=>{var e=new Error("The operation was aborted.");e.name="AbortError",t(e)})});let a;try{await Promise.race([s,t]),a=await s}catch(e){let t="fetch-client-network";throw"AbortError"===(null==e?void 0:e.name)&&(t="fetch-timeout"),Gx.create(t,{originalErrorMessage:null==e?void 0:e.message})}let o=a.status;i=a.headers.get("ETag")||void 0;let l,h;if(200===a.status){let e;try{e=await a.json()}catch(e){throw Gx.create("fetch-client-parse",{originalErrorMessage:null==e?void 0:e.message})}l=e.entries,h=e.state}if("INSTANCE_STATE_UNSPECIFIED"===h?o=500:"NO_CHANGE"===h?o=304:"NO_TEMPLATE"!==h&&"EMPTY_CONFIG"!==h||(l={}),304!==o&&200!==o)throw Gx.create("fetch-status",{httpStatus:o});return{status:o,eTag:i,config:l}}}class n1{constructor(e,t){this.client=e,this.storage=t}async fetch(e){var t=await this.storage.getThrottleMetadata()||{backoffCount:0,throttleEndTimeMillis:Date.now()};return this.attemptFetch(e,t)}async attemptFetch(t,{throttleEndTimeMillis:e,backoffCount:r}){var i,s;i=t.signal,s=e,await new Promise((e,t)=>{var r=Math.max(s-Date.now(),0);let n=setTimeout(e,r);i.addEventListener(()=>{clearTimeout(n),t(Gx.create("fetch-throttle",{throttleEndTimeMillis:s}))})});try{var n=await this.client.fetch(t);return await this.storage.deleteThrottleMetadata(),n}catch(e){if((e=>{var t;return e instanceof de&&e.customData&&(429===(t=Number(e.customData.httpStatus))||500===t||503===t||504===t)})(e))return n={throttleEndTimeMillis:Date.now()+Ve(r),backoffCount:r+1},await this.storage.setThrottleMetadata(n),this.attemptFetch(t,n);throw e}}}class i1{get fetchTimeMillis(){return this._storageCache.getLastSuccessfulFetchTimestampMillis()||-1}get lastFetchStatus(){return this._storageCache.getLastFetchStatus()||"no-fetch-yet"}constructor(e,t,r,n,i){this.app=e,this._client=t,this._storageCache=r,this._storage=n,this._logger=i,this._isInitializationComplete=!1,this.settings={fetchTimeoutMillis:6e4,minimumFetchIntervalMillis:432e5},this.defaultConfig={}}}function s1(e,t){var r=e.target.error||void 0;return Gx.create(t,{originalErrorMessage:r&&(null==r?void 0:r.message)})}let a1="app_namespace_store";class o1{constructor(e,t,r,n=(()=>new Promise((t,r)=>{try{var e=indexedDB.open("firebase_remote_config",1);e.onerror=e=>{r(s1(e,"storage-open"))},e.onsuccess=e=>{t(e.target.result)},e.onupgradeneeded=e=>{var t=e.target.result;0===e.oldVersion&&t.createObjectStore(a1,{keyPath:"compositeKey"})}}catch(e){r(Gx.create("storage-open",{originalErrorMessage:null==e?void 0:e.message}))}}))()){this.appId=e,this.appName=t,this.namespace=r,this.openDbPromise=n}getLastFetchStatus(){return this.get("last_fetch_status")}setLastFetchStatus(e){return this.set("last_fetch_status",e)}getLastSuccessfulFetchTimestampMillis(){return this.get("last_successful_fetch_timestamp_millis")}setLastSuccessfulFetchTimestampMillis(e){return this.set("last_successful_fetch_timestamp_millis",e)}getLastSuccessfulFetchResponse(){return this.get("last_successful_fetch_response")}setLastSuccessfulFetchResponse(e){return this.set("last_successful_fetch_response",e)}getActiveConfig(){return this.get("active_config")}setActiveConfig(e){return this.set("active_config",e)}getActiveConfigEtag(){return this.get("active_config_etag")}setActiveConfigEtag(e){return this.set("active_config_etag",e)}getThrottleMetadata(){return this.get("throttle_metadata")}setThrottleMetadata(e){return this.set("throttle_metadata",e)}deleteThrottleMetadata(){return this.delete("throttle_metadata")}getCustomSignals(){return this.get("custom_signals")}async setCustomSignals(e){var t=(await this.openDbPromise).transaction([a1],"readwrite"),r=await this.getWithTransaction("custom_signals",t),r=Object.assign(Object.assign({},r),e),r=Object.fromEntries(Object.entries(r).filter(([,e])=>null!==e).map(([e,t])=>"number"==typeof t?[e,t.toString()]:[e,t]));if(100<Object.keys(r).length)throw Gx.create("custom-signal-max-allowed-signals",{maxSignals:100});return await this.setWithTransaction("custom_signals",r,t),r}async getWithTransaction(s,a){return new Promise((r,t)=>{var e=a.objectStore(a1),n=this.createCompositeKey(s);try{var i=e.get(n);i.onerror=e=>{t(s1(e,"storage-get"))},i.onsuccess=e=>{var t=e.target.result;r(t?t.value:void 0)}}catch(e){t(Gx.create("storage-get",{originalErrorMessage:null==e?void 0:e.message}))}})}async setWithTransaction(s,a,o){return new Promise((e,t)=>{var r=o.objectStore(a1),n=this.createCompositeKey(s);try{var i=r.put({compositeKey:n,value:a});i.onerror=e=>{t(s1(e,"storage-set"))},i.onsuccess=()=>{e()}}catch(e){t(Gx.create("storage-set",{originalErrorMessage:null==e?void 0:e.message}))}})}async get(e){var t=(await this.openDbPromise).transaction([a1],"readonly");return this.getWithTransaction(e,t)}async set(e,t){var r=(await this.openDbPromise).transaction([a1],"readwrite");return this.setWithTransaction(e,t,r)}async delete(s){let a=await this.openDbPromise;return new Promise((e,t)=>{var r=a.transaction([a1],"readwrite").objectStore(a1),n=this.createCompositeKey(s);try{var i=r.delete(n);i.onerror=e=>{t(s1(e,"storage-delete"))},i.onsuccess=()=>{e()}}catch(e){t(Gx.create("storage-delete",{originalErrorMessage:null==e?void 0:e.message}))}})}createCompositeKey(e){return[this.appId,this.appName,this.namespace,e].join()}}class l1{constructor(e){this.storage=e}getLastFetchStatus(){return this.lastFetchStatus}getLastSuccessfulFetchTimestampMillis(){return this.lastSuccessfulFetchTimestampMillis}getActiveConfig(){return this.activeConfig}getCustomSignals(){return this.customSignals}async loadFromStorage(){var e=this.storage.getLastFetchStatus(),t=this.storage.getLastSuccessfulFetchTimestampMillis(),r=this.storage.getActiveConfig(),n=this.storage.getCustomSignals(),e=await e,e=(e&&(this.lastFetchStatus=e),await t),t=(e&&(this.lastSuccessfulFetchTimestampMillis=e),await r),e=(t&&(this.activeConfig=t),await n);e&&(this.customSignals=e)}setLastFetchStatus(e){return this.lastFetchStatus=e,this.storage.setLastFetchStatus(e)}setLastSuccessfulFetchTimestampMillis(e){return this.lastSuccessfulFetchTimestampMillis=e,this.storage.setLastSuccessfulFetchTimestampMillis(e)}setActiveConfig(e){return this.activeConfig=e,this.storage.setActiveConfig(e)}async setCustomSignals(e){this.customSignals=await this.storage.setCustomSignals(e)}}async function h1(){if(!he())return!1;try{return await ue()}catch(e){return!1}}Ct(new u("remote-config",function(e,{instanceIdentifier:t}){var r=e.getProvider("app").getImmediate(),n=e.getProvider("installations-internal").getImmediate();if("undefined"==typeof window)throw Gx.create("registration-window");if(!he())throw Gx.create("indexed-db-unavailable");var{projectId:i,apiKey:s,appId:a}=r.options;if(!i)throw Gx.create("registration-project-id");if(!s)throw Gx.create("registration-api-key");if(!a)throw Gx.create("registration-app-id");t=t||"firebase";var o=new o1(a,r.name,t),l=new l1(o),h=new $e(Wx),n=(h.logLevel=c.ERROR,new r1(n,Dt,t,i,s,a)),i=new n1(n,o),s=new t1(i,o,l,h),a=new i1(r,s,l,o,h);return Jx(a),a},"PUBLIC").setMultipleInstances(!0)),d(Wx,"0.5.0"),d(Wx,"0.5.0","esm2017");class u1{constructor(e,t){this.app=e,this._delegate=t}get defaultConfig(){return this._delegate.defaultConfig}set defaultConfig(e){this._delegate.defaultConfig=e}get fetchTimeMillis(){return this._delegate.fetchTimeMillis}get lastFetchStatus(){return this._delegate.lastFetchStatus}get settings(){return this._delegate.settings}set settings(e){this._delegate.settings=e}activate(){return Yx(this._delegate)}ensureInitialized(){return Jx(this._delegate)}fetch(){return Xx(this._delegate)}fetchAndActivate(){return(async e=>(await Xx(e=w(e)),Yx(e)))(this._delegate)}getAll(){return Zx(this._delegate)}getBoolean(e){return e1(w(this._delegate),e).asBoolean()}getNumber(e){return e1(w(this._delegate),e).asNumber()}getString(e){return e1(w(this._delegate),e).asString()}getValue(e){return e1(this._delegate,e)}setLogLevel(e){var t=this._delegate,r=w(t);switch(e){case"debug":r._logger.logLevel=c.DEBUG;break;case"silent":r._logger.logLevel=c.SILENT;break;default:r._logger.logLevel=c.ERROR}}}function c1(e,{instanceIdentifier:t}){var r=e.getProvider("app-compat").getImmediate(),n=e.getProvider("remote-config").getImmediate({identifier:t});return new u1(r,n)}return(WD=tr).INTERNAL.registerComponent(new u("remoteConfig-compat",c1,"PUBLIC").setMultipleInstances(!0).setServiceProps({isSupported:h1})),WD.registerVersion("@firebase/remote-config-compat","0.2.12"),console.warn(`
|
|
14
|
+
Determined least recently used ${i} in `+(o-a)+"ms\n"+` Removed ${s} targets in `+(l-o)+"ms\n"+` Removed ${e} documents in `+(h-l)+"ms\n"+`Total Duration: ${h-u}ms`),O.resolve({didRun:!0,sequenceNumbersCollected:i,targetsRemoved:s,documentsRemoved:e})))}}function dT(e,t){return new cT(e,t)}class pT{constructor(e,t){this.db=e,this.garbageCollector=dT(this,t)}nr(e){let r=this.sr(e);return this.db.getTargetCache().getTargetCount(e).next(t=>r.next(e=>t+e))}sr(e){let t=0;return this.rr(e,e=>{t++}).next(()=>t)}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}rr(e,r){return this._r(e,(e,t)=>r(t))}addReference(e,t,r){return fT(e,r)}removeReference(e,t,r){return fT(e,r)}removeTargets(e,t,r){return this.db.getTargetCache().removeTargets(e,t,r)}markPotentiallyOrphaned(e,t){return fT(e,t)}ar(e,r){{var n=e,i=r;let t=!1;return tT(n).X(e=>XI(n,e,i).next(e=>(e&&(t=!0),O.resolve(!e)))).next(()=>t)}}removeOrphanedDocuments(r,n){let i=this.db.getRemoteDocumentCache().newChangeBuffer(),s=[],a=0;return this._r(r,(t,e)=>{if(e<=n){let e=this.ar(r,t).next(e=>{if(!e)return a++,i.getEntry(r,t).next(()=>(i.removeEntry(t,P.min()),aT(r).delete([0,kv(t.path)])))});s.push(e)}}).next(()=>O.waitFor(s)).next(()=>i.apply(r)).next(()=>a)}removeTarget(e,t){var r=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,r)}updateLimboDocument(e,t){return fT(e,t)}_r(e,n){var t=aT(e);let i,s=wv.ae;return t.Z({index:e_},([e],{path:t,sequenceNumber:r})=>{0===e?(s!==wv.ae&&n(new x(Av(i)),s),s=r,i=t):s=wv.ae}).next(()=>{s!==wv.ae&&n(new x(Av(i)),s)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function fT(e,t){return aT(e).put((e=e.currentSequenceNumber,{targetId:0,path:kv(t.path),sequenceNumber:e}))}class gT{constructor(){this.changes=new ww(e=>e.toString(),(e,t)=>e.isEqual(t)),this.changesApplied=!1}addEntry(e){this.assertNotApplied(),this.changes.set(e.key,e)}removeEntry(e,t){this.assertNotApplied(),this.changes.set(e,Py.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();var r=this.changes.get(t);return void 0!==r?O.resolve(r):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}}class mT{constructor(e){this.serializer=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,r){return wT(e).put(r)}removeEntry(e,t,r){return wT(e).delete((e=r,[(n=t.path.toArray()).slice(0,n.length-2),n[n.length-2],iI(e),n[n.length-1]]));var n}updateMetadata(t,r){return this.getMetadata(t).next(e=>(e.byteSize+=r,this.ur(t,e)))}getEntry(e,r){let n=Py.newInvalidDocument(r);return wT(e).Z({index:zv,range:IDBKeyRange.only(bT(r))},(e,t)=>{n=this.cr(r,t)}).next(()=>n)}lr(e,r){let n={size:0,document:Py.newInvalidDocument(r)};return wT(e).Z({index:zv,range:IDBKeyRange.only(bT(r))},(e,t)=>{n={document:this.cr(r,t),size:YI(t)}}).next(()=>n)}getEntries(e,t){let n=bw;return this.hr(e,t,(e,t)=>{var r=this.cr(e,t);n=n.insert(e,r)}).next(()=>n)}Pr(e,t){let n=bw,i=new L(x.comparator);return this.hr(e,t,(e,t)=>{var r=this.cr(e,t);n=n.insert(e,r),i=i.insert(e,YI(t))}).next(()=>({documents:n,Tr:i}))}hr(e,t,i){if(t.isEmpty())return O.resolve();let r=new M(TT),n=(t.forEach(e=>r=r.add(e)),IDBKeyRange.bound(bT(r.first()),bT(r.last()))),s=r.getIterator(),a=s.getNext();return wT(e).Z({index:zv,range:n},(e,t,r)=>{for(var n=x.fromSegments([...t.prefixPath,t.collectionGroup,t.documentId]);a&&TT(a,n)<0;)i(a,null),a=s.getNext();a&&a.isEqual(n)&&(i(a,t),a=s.hasNext()?s.getNext():null),a?r.W(bT(a)):r.done()}).next(()=>{for(;a;)i(a,null),a=s.hasNext()?s.getNext():null})}getDocumentsMatchingQuery(e,n,t,i,s){var r=n.path,a=[r.popLast().toArray(),r.lastSegment(),iI(t.readTime),t.documentKey.path.isEmpty()?"":t.documentKey.path.lastSegment()],r=[r.popLast().toArray(),r.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return wT(e).G(IDBKeyRange.bound(a,r,!0)).next(e=>{null!=s&&s.incrementDocumentReadCount(e.length);let t=bw;for(let r of e){let e=this.cr(x.fromSegments(r.prefixPath.concat(r.collectionGroup,r.documentId)),r);e.isFoundDocument()&&(vw(n,e)||i.has(e.key))&&(t=t.insert(e.key,e))}return t})}getAllFromCollectionGroup(e,t,r,i){let s=bw;var n=IT(t,r),a=IT(t,tv.max());return wT(e).Z({index:Wv,range:IDBKeyRange.bound(n,a,!0)},(e,t,r)=>{var n=this.cr(x.fromSegments(t.prefixPath.concat(t.collectionGroup,t.documentId)),t);(s=s.insert(n.key,n)).size===i&&r.done()}).next(()=>s)}newChangeBuffer(e){return new _T(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(e=>e.byteSize)}getMetadata(e){return yT(e).get($v).next(e=>(S(!!e),e))}ur(e,t){return yT(e).put($v,t)}cr(e,t){if(t){let e=((e,r)=>{let n;if(r.document)n=Bb(e.Tt,r.document,!!r.hasCommittedMutations);else if(r.noDocument){let e=x.fromSegments(r.noDocument.path),t=aI(r.noDocument.readTime);n=Py.newNoDocument(e,t),r.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!r.unknownDocument)return k();{let e=x.fromSegments(r.unknownDocument.path),t=aI(r.unknownDocument.version);n=Py.newUnknownDocument(e,t)}}return r.readTime&&n.setReadTime((e=r.readTime,t=new Bm(e[0],e[1]),P.fromTimestamp(t))),n;var t})(this.serializer,t);if(!e.isNoDocument()||!e.version.isEqual(P.min()))return e}return Py.newInvalidDocument(e)}}function vT(e){return new mT(e)}class _T extends gT{constructor(e,t){super(),this.Ir=e,this.trackRemovals=t,this.Er=new ww(e=>e.toString(),(e,t)=>e.isEqual(t))}applyChanges(s){let a=[],o=0,l=new M((e,t)=>R(e.canonicalString(),t.canonicalString()));return this.changes.forEach((t,r)=>{var e=this.Er.get(t);if(a.push(this.Ir.removeEntry(s,t,e.readTime)),r.isValidDocument()){var n=nI(this.Ir.serializer,r),i=(l=l.add(t.path.popLast()),YI(n));o+=i-e.size,a.push(this.Ir.addEntry(s,t,n))}else if(o-=e.size,this.trackRemovals){let e=nI(this.Ir.serializer,r.convertToNoDocument(P.min()));a.push(this.Ir.addEntry(s,t,e))}}),l.forEach(e=>{a.push(this.Ir.indexManager.addToCollectionParentIndex(s,e))}),a.push(this.Ir.updateMetadata(s,o)),O.waitFor(a)}getFromCache(e,t){return this.Ir.lr(e,t).next(e=>(this.Er.set(t,{size:e.size,readTime:e.document.readTime}),e.document))}getAllFromCache(e,t){return this.Ir.Pr(e,t).next(({documents:r,Tr:e})=>(e.forEach((e,t)=>{this.Er.set(e,{size:t,readTime:r.get(e).readTime})}),r))}}function yT(e){return O_(e,Gv)}function wT(e){return O_(e,jv)}function bT(e){var t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function IT(e,t){var r=t.documentKey.path.toArray();return[e,iI(t.readTime),r.slice(0,r.length-2),0<r.length?r[r.length-1]:""]}function TT(e,t){var r=e.path.toArray(),n=t.path.toArray();let i=0;for(let s=0;s<r.length-2&&s<n.length-2;++s)if(i=R(r[s],n[s]))return i;return(i=R(r.length,n.length))||(i=R(r[r.length-2],n[n.length-2]))||R(r[r.length-1],n[n.length-1])}class ET{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class CT{constructor(e,t,r,n){this.remoteDocumentCache=e,this.mutationQueue=t,this.documentOverlayCache=r,this.indexManager=n}getDocument(t,r){let n=null;return this.documentOverlayCache.getOverlay(t,r).next(e=>(n=e,this.remoteDocumentCache.getEntry(t,r))).next(e=>(null!==n&&$w(n.mutation,e,B_.empty(),Bm.now()),e))}getDocuments(t,e){return this.remoteDocumentCache.getEntries(t,e).next(e=>this.getLocalViewOfDocuments(t,e,V()).next(()=>e))}getLocalViewOfDocuments(e,t,r=V()){let n=Cw();return this.populateOverlays(e,n,t).next(()=>this.computeViews(e,t,n,r).next(e=>{let r=Tw();return e.forEach((e,t)=>{r=r.insert(e,t.overlayedDocument)}),r}))}getOverlayedDocuments(e,t){let r=Cw();return this.populateOverlays(e,r,t).next(()=>this.computeViews(e,t,r,V()))}populateOverlays(e,r,t){let n=[];return t.forEach(e=>{r.has(e)||n.push(e)}),this.documentOverlayCache.getOverlays(e,n).next(e=>{e.forEach((e,t)=>{r.set(e,t)})})}computeViews(e,t,n,i){let s=bw,a=Cw(),o=Cw();return t.forEach((e,t)=>{var r=n.get(t.key);i.has(t.key)&&(void 0===r||r.mutation instanceof Jw)?s=s.insert(t.key,t):void 0!==r?(a.set(t.key,r.mutation.getFieldMask()),$w(r.mutation,t,r.mutation.getFieldMask(),Bm.now())):a.set(t.key,B_.empty())}),this.recalculateAndSaveOverlays(e,s).next(e=>(e.forEach((e,t)=>a.set(e,t)),t.forEach((e,t)=>{var r;return o.set(e,new ET(t,null!=(r=a.get(e))?r:null))}),o))}recalculateAndSaveOverlays(a,o){let l=Cw(),h=new L((e,t)=>e-t),u=V();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(a,o).next(e=>{for(let n of e)n.keys().forEach(e=>{var t,r=o.get(e);null!==r&&(t=l.get(e)||B_.empty(),t=n.applyToLocalView(r,t),l.set(e,t),r=(h.get(n.batchId)||V()).add(e),h=h.insert(n.batchId,r))})}).next(()=>{for(var i=[],s=h.getReverseIterator();s.hasNext();){let e=s.getNext(),t=e.key,r=e.value,n=Cw();r.forEach(e=>{var t;u.has(e)||(null!==(t=Gw(o.get(e),l.get(e)))&&n.set(e,t),u=u.add(e))}),i.push(this.documentOverlayCache.saveOverlays(a,t,n))}return O.waitFor(i)}).next(()=>l)}recalculateAndSaveOverlaysForDocumentKeys(t,e){return this.remoteDocumentCache.getEntries(t,e).next(e=>this.recalculateAndSaveOverlays(t,e))}getDocumentsMatchingQuery(e,t,r,n){return i=t,x.isDocumentKey(i.path)&&null===i.collectionGroup&&0===i.filters.length?this.getDocumentsMatchingDocumentQuery(e,t.path):hw(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,r,n):this.getDocumentsMatchingCollectionQuery(e,t,r,n);var i}getNextDocuments(s,t,a,o){return this.remoteDocumentCache.getAllFromCollectionGroup(s,t,a,o).next(r=>{var e=0<o-r.size?this.documentOverlayCache.getOverlaysForCollectionGroup(s,t,a.largestBatchId,o-r.size):O.resolve(Cw());let n=Gm,i=r;return e.next(e=>O.forEach(e,(t,e)=>(n<e.largestBatchId&&(n=e.largestBatchId),r.get(t)?O.resolve():this.remoteDocumentCache.getEntry(s,t).next(e=>{i=i.insert(t,e)}))).next(()=>this.populateOverlays(s,e,r)).next(()=>this.computeViews(s,i,e,V())).next(e=>({batchId:n,changes:Ew(e)})))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new x(t)).next(e=>{let t=Tw();return t=e.isFoundDocument()?t.insert(e.key,e):t})}getDocumentsMatchingCollectionGroupQuery(n,i,s,a){let o=i.collectionGroup,l=Tw();return this.indexManager.getCollectionParents(n,o).next(e=>O.forEach(e,e=>{t=i,e=e.child(o);var t,r=new sw(e,null,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt);return this.getDocumentsMatchingCollectionQuery(n,r,s,a).next(e=>{e.forEach((e,t)=>{l=l.insert(e,t)})})}).next(()=>l))}getDocumentsMatchingCollectionQuery(t,s,r,n){let a;return this.documentOverlayCache.getOverlaysForCollection(t,s.path,r.largestBatchId).next(e=>(a=e,this.remoteDocumentCache.getDocumentsMatchingQuery(t,s,r,a,n))).next(n=>{a.forEach((e,t)=>{var r=t.getKey();null===n.get(r)&&(n=n.insert(r,Py.newInvalidDocument(r)))});let i=Tw();return n.forEach((e,t)=>{var r=a.get(e);void 0!==r&&$w(r.mutation,t,B_.empty(),Bm.now()),vw(s,t)&&(i=i.insert(e,t))}),i})}}class kT{constructor(e){this.serializer=e,this.dr=new Map,this.Ar=new Map}getBundleMetadata(e,t){return O.resolve(this.dr.get(t))}saveBundleMetadata(e,t){return this.dr.set(t.id,{id:t.id,version:t.version,createTime:Pb(t.createTime)}),O.resolve()}getNamedQuery(e,t){return O.resolve(this.Ar.get(t))}saveNamedQuery(e,t){return this.Ar.set(t.name,{name:(t=t).name,query:uI(t.bundledQuery),readTime:Pb(t.readTime)}),O.resolve()}}class ST{constructor(){this.overlays=new L(x.comparator),this.Rr=new Map}getOverlay(e,t){return O.resolve(this.overlays.get(t))}getOverlays(e,t){let r=Cw();return O.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&r.set(t,e)})).next(()=>r)}saveOverlays(r,n,e){return e.forEach((e,t)=>{this.Et(r,n,t)}),O.resolve()}removeOverlaysForBatchId(e,t,r){var n=this.Rr.get(r);return void 0!==n&&(n.forEach(e=>this.overlays=this.overlays.remove(e)),this.Rr.delete(r)),O.resolve()}getOverlaysForCollection(e,r,n){let i=Cw(),s=r.length+1,t=new x(r.child("")),a=this.overlays.getIteratorFrom(t);for(;a.hasNext();){let e=a.getNext().value,t=e.getKey();if(!r.isPrefixOf(t.path))break;t.path.length===s&&e.largestBatchId>n&&i.set(e.getKey(),e)}return O.resolve(i)}getOverlaysForCollectionGroup(e,r,n,t){let i=new L((e,t)=>e-t);for(var s=this.overlays.getIterator();s.hasNext();){let t=s.getNext().value;if(t.getKey().getCollectionGroup()===r&&t.largestBatchId>n){let e=i.get(t.largestBatchId);null===e&&(e=Cw(),i=i.insert(t.largestBatchId,e)),e.set(t.getKey(),t)}}let a=Cw(),o=i.getIterator();for(;o.hasNext()&&(o.getNext().value.forEach((e,t)=>a.set(e,t)),!(a.size()>=t)););return O.resolve(a)}Et(e,t,r){var n=this.overlays.get(r.key);if(null!==n){let e=this.Rr.get(n.largestBatchId).delete(r.key);this.Rr.set(n.largestBatchId,e)}this.overlays=this.overlays.insert(r.key,new sb(t,r));let i=this.Rr.get(t);void 0===i&&(i=V(),this.Rr.set(t,i)),this.Rr.set(t,i.add(r.key))}}class AT{constructor(){this.sessionToken=K_.EMPTY_BYTE_STRING}getSessionToken(e){return O.resolve(this.sessionToken)}setSessionToken(e,t){return this.sessionToken=t,O.resolve()}}class NT{constructor(){this.Vr=new M(RT.mr),this.gr=new M(RT.pr)}isEmpty(){return this.Vr.isEmpty()}addReference(e,t){var r=new RT(e,t);this.Vr=this.Vr.add(r),this.gr=this.gr.add(r)}yr(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.wr(new RT(e,t))}Sr(e,t){e.forEach(e=>this.removeReference(e,t))}br(e){let t=new x(new D([])),r=new RT(t,e),n=new RT(t,e+1),i=[];return this.gr.forEachInRange([r,n],e=>{this.wr(e),i.push(e.key)}),i}Dr(){this.Vr.forEach(e=>this.wr(e))}wr(e){this.Vr=this.Vr.delete(e),this.gr=this.gr.delete(e)}vr(e){var t=new x(new D([])),r=new RT(t,e),t=new RT(t,e+1);let n=V();return this.gr.forEachInRange([r,t],e=>{n=n.add(e.key)}),n}containsKey(e){var t=new RT(e,0),t=this.Vr.firstAfterOrEqual(t);return null!==t&&e.isEqual(t.key)}}class RT{constructor(e,t){this.key=e,this.Cr=t}static mr(e,t){return x.comparator(e.key,t.key)||R(e.Cr,t.Cr)}static pr(e,t){return R(e.Cr,t.Cr)||x.comparator(e.key,t.key)}}class PT{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.Fr=1,this.Mr=new M(RT.mr)}checkEmpty(e){return O.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,r,n){var i=this.Fr,s=(this.Fr++,0<this.mutationQueue.length&&this.mutationQueue[this.mutationQueue.length-1],new nb(i,t,r,n));this.mutationQueue.push(s);for(let t of n)this.Mr=this.Mr.add(new RT(t.key,i)),this.indexManager.addToCollectionParentIndex(e,t.key.path.popLast());return O.resolve(s)}lookupMutationBatch(e,t){return O.resolve(this.Or(t))}getNextMutationBatchAfterBatchId(e,t){var r=this.Nr(t+1),r=r<0?0:r;return O.resolve(this.mutationQueue.length>r?this.mutationQueue[r]:null)}getHighestUnacknowledgedBatchId(){return O.resolve(0===this.mutationQueue.length?bv:this.Fr-1)}getAllMutationBatches(e){return O.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){let r=new RT(t,0),n=new RT(t,Number.POSITIVE_INFINITY),i=[];return this.Mr.forEachInRange([r,n],e=>{var t=this.Or(e.Cr);i.push(t)}),O.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new M(R);return t.forEach(e=>{var t=new RT(e,0),r=new RT(e,Number.POSITIVE_INFINITY);this.Mr.forEachInRange([t,r],e=>{n=n.add(e.Cr)})}),O.resolve(this.Br(n))}getAllMutationBatchesAffectingQuery(e,t){let r=t.path,n=r.length+1,i=r;x.isDocumentKey(i)||(i=i.child(""));var s=new RT(new x(i),0);let a=new M(R);return this.Mr.forEachWhile(e=>{var t=e.key.path;return!!r.isPrefixOf(t)&&(t.length===n&&(a=a.add(e.Cr)),!0)},s),O.resolve(this.Br(a))}Br(e){let r=[];return e.forEach(e=>{var t=this.Or(e);null!==t&&r.push(t)}),r}removeMutationBatch(r,n){S(0===this.Lr(n.batchId,"removed")),this.mutationQueue.shift();let i=this.Mr;return O.forEach(n.mutations,e=>{var t=new RT(e.key,n.batchId);return i=i.delete(t),this.referenceDelegate.markPotentiallyOrphaned(r,e.key)}).next(()=>{this.Mr=i})}qn(e){}containsKey(e,t){var r=new RT(t,0),r=this.Mr.firstAfterOrEqual(r);return O.resolve(t.isEqual(r&&r.key))}performConsistencyCheck(e){return this.mutationQueue.length,O.resolve()}Lr(e,t){return this.Nr(e)}Nr(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}Or(e){var t=this.Nr(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class DT{constructor(e){this.kr=e,this.docs=new L(x.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){var r=t.key,n=this.docs.get(r),n=n?n.size:0,i=this.kr(t);return this.docs=this.docs.insert(r,{document:t.mutableCopy(),size:i}),this.size+=i-n,this.indexManager.addToCollectionParentIndex(e,r.path.popLast())}removeEntry(e){var t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){var r=this.docs.get(t);return O.resolve(r?r.document.mutableCopy():Py.newInvalidDocument(t))}getEntries(e,t){let r=bw;return t.forEach(e=>{var t=this.docs.get(e);r=r.insert(e,t?t.document.mutableCopy():Py.newInvalidDocument(e))}),O.resolve(r)}getDocumentsMatchingQuery(e,r,n,i){let s=bw,a=r.path,t=new x(a.child("__id-9223372036854775808__")),o=this.docs.getIteratorFrom(t);for(;o.hasNext();){let{key:e,value:{document:t}}=o.getNext();if(!a.isPrefixOf(e.path))break;e.path.length>a.length+1||rv(ev(t),n)<=0||(i.has(t.key)||vw(r,t))&&(s=s.insert(t.key,t.mutableCopy()))}return O.resolve(s)}getAllFromCollectionGroup(e,t,r,n){k()}qr(e,t){return O.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new xT(this)}getSize(e){return O.resolve(this.size)}}class xT extends gT{constructor(e){super(),this.Ir=e}applyChanges(r){let n=[];return this.changes.forEach((e,t)=>{t.isValidDocument()?n.push(this.Ir.addEntry(r,t)):this.Ir.removeEntry(e)}),O.waitFor(n)}getFromCache(e,t){return this.Ir.getEntry(e,t)}getAllFromCache(e,t){return this.Ir.getEntries(e,t)}}class OT{constructor(e){this.persistence=e,this.Qr=new ww(e=>Zy(e),ew),this.lastRemoteSnapshotVersion=P.min(),this.highestTargetId=0,this.$r=0,this.Kr=new NT,this.targetCount=0,this.Ur=rT.Kn()}forEachTarget(e,r){return this.Qr.forEach((e,t)=>r(t)),O.resolve()}getLastRemoteSnapshotVersion(e){return O.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return O.resolve(this.$r)}allocateTargetId(e){return this.highestTargetId=this.Ur.next(),O.resolve(this.highestTargetId)}setTargetsMetadata(e,t,r){return r&&(this.lastRemoteSnapshotVersion=r),t>this.$r&&(this.$r=t),O.resolve()}zn(e){this.Qr.set(e.target,e);var t=e.targetId;t>this.highestTargetId&&(this.Ur=new rT(t),this.highestTargetId=t),e.sequenceNumber>this.$r&&(this.$r=e.sequenceNumber)}addTargetData(e,t){return this.zn(t),this.targetCount+=1,O.resolve()}updateTargetData(e,t){return this.zn(t),O.resolve()}removeTargetData(e,t){return this.Qr.delete(t.target),this.Kr.br(t.targetId),--this.targetCount,O.resolve()}removeTargets(r,n,i){let s=0,a=[];return this.Qr.forEach((e,t)=>{t.sequenceNumber<=n&&null===i.get(t.targetId)&&(this.Qr.delete(e),a.push(this.removeMatchingKeysForTargetId(r,t.targetId)),s++)}),O.waitFor(a).next(()=>s)}getTargetCount(e){return O.resolve(this.targetCount)}getTargetData(e,t){var r=this.Qr.get(t)||null;return O.resolve(r)}addMatchingKeys(e,t,r){return this.Kr.yr(t,r),O.resolve()}removeMatchingKeys(t,e,r){this.Kr.Sr(e,r);let n=this.persistence.referenceDelegate,i=[];return n&&e.forEach(e=>{i.push(n.markPotentiallyOrphaned(t,e))}),O.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.Kr.br(t),O.resolve()}getMatchingKeysForTargetId(e,t){var r=this.Kr.vr(t);return O.resolve(r)}containsKey(e,t){return O.resolve(this.Kr.containsKey(t))}}class LT{constructor(e,t){this.Wr={},this.overlays={},this.Gr=new wv(0),this.zr=!1,this.zr=!0,this.jr=new AT,this.referenceDelegate=e(this),this.Hr=new OT(this),this.indexManager=new FI,this.remoteDocumentCache=(e=e=>this.referenceDelegate.Jr(e),new DT(e)),this.serializer=new rI(t),this.Yr=new kT(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.zr=!1,Promise.resolve()}get started(){return this.zr}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new ST,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let r=this.Wr[e.toKey()];return r||(r=new PT(t,this.referenceDelegate),this.Wr[e.toKey()]=r),r}getGlobalsCache(){return this.jr}getTargetCache(){return this.Hr}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.Yr}runTransaction(e,t,r){C("MemoryPersistence","Starting transaction:",e);let n=new MT(this.Gr.next());return this.referenceDelegate.Zr(),r(n).next(e=>this.referenceDelegate.Xr(n).next(()=>e)).toPromise().then(e=>(n.raiseOnCommittedEvent(),e))}ei(t,r){return O.or(Object.values(this.Wr).map(e=>()=>e.containsKey(t,r)))}}class MT extends iv{constructor(e){super(),this.currentSequenceNumber=e}}class FT{constructor(e){this.persistence=e,this.ti=new NT,this.ni=null}static ri(e){return new FT(e)}get ii(){if(this.ni)return this.ni;throw k()}addReference(e,t,r){return this.ti.addReference(r,t),this.ii.delete(r.toString()),O.resolve()}removeReference(e,t,r){return this.ti.removeReference(r,t),this.ii.add(r.toString()),O.resolve()}markPotentiallyOrphaned(e,t){return this.ii.add(t.toString()),O.resolve()}removeTarget(e,t){this.ti.br(t.targetId).forEach(e=>this.ii.add(e.toString()));let r=this.persistence.getTargetCache();return r.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.ii.add(e.toString()))}).next(()=>r.removeTargetData(e,t))}Zr(){this.ni=new Set}Xr(r){let n=this.persistence.getRemoteDocumentCache().newChangeBuffer();return O.forEach(this.ii,e=>{let t=x.fromPath(e);return this.si(r,t).next(e=>{e||n.removeEntry(t,P.min())})}).next(()=>(this.ni=null,n.apply(r)))}updateLimboDocument(e,t){return this.si(e,t).next(e=>{e?this.ii.delete(t.toString()):this.ii.add(t.toString())})}Jr(e){return 0}si(e,t){return O.or([()=>O.resolve(this.ti.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.ei(e,t)])}}class UT{constructor(e,t){this.persistence=e,this.oi=new ww(e=>kv(e.path),(e,t)=>e.isEqual(t)),this.garbageCollector=dT(this,t)}static ri(e,t){return new UT(e,t)}Zr(){}Xr(e){return O.resolve()}forEachTarget(e,t){return this.persistence.getTargetCache().forEachTarget(e,t)}nr(e){let r=this.sr(e);return this.persistence.getTargetCache().getTargetCount(e).next(t=>r.next(e=>t+e))}sr(e){let t=0;return this.rr(e,e=>{t++}).next(()=>t)}rr(r,n){return O.forEach(this.oi,(e,t)=>this.ar(r,e,t).next(e=>e?O.resolve():n(t)))}removeTargets(e,t,r){return this.persistence.getTargetCache().removeTargets(e,t,r)}removeOrphanedDocuments(e,r){let n=0,t=this.persistence.getRemoteDocumentCache(),i=t.newChangeBuffer();return t.qr(e,t=>this.ar(e,t,r).next(e=>{e||(n++,i.removeEntry(t,P.min()))})).next(()=>i.apply(e)).next(()=>n)}markPotentiallyOrphaned(e,t){return this.oi.set(t,e.currentSequenceNumber),O.resolve()}removeTarget(e,t){var r=t.withSequenceNumber(e.currentSequenceNumber);return this.persistence.getTargetCache().updateTargetData(e,r)}addReference(e,t,r){return this.oi.set(r,e.currentSequenceNumber),O.resolve()}removeReference(e,t,r){return this.oi.set(r,e.currentSequenceNumber),O.resolve()}updateLimboDocument(e,t){return this.oi.set(t,e.currentSequenceNumber),O.resolve()}Jr(e){let t=e.key.toString().length;return e.isFoundDocument()&&(t+=function n(e){switch(cy(e)){case 0:case 1:return 4;case 2:return 8;case 3:case 8:return 16;case 4:var t=ey(e);return t?16+n(t):16;case 5:return 2*e.stringValue.length;case 6:return $_(e.bytesValue).approximateByteSize();case 7:return e.referenceValue.length;case 9:return(e.arrayValue.values||[]).reduce((e,t)=>e+n(t),0);case 10:case 11:{var i=e.mapValue;let r=0;return M_(i.fields,(e,t)=>{r+=e.length+n(t)}),r}default:throw k()}}(e.data.value)),t}ar(e,t,r){return O.or([()=>this.persistence.ei(e,t),()=>this.persistence.getTargetCache().containsKey(e,t),()=>{var e=this.oi.get(t);return O.resolve(void 0!==e&&r<e)}])}getCacheSize(e){return this.persistence.getRemoteDocumentCache().getSize(e)}}class VT{constructor(e){this.serializer=e}B(t,e,r,n){let s=new ov("createOrUpgrade",e);var i;r<1&&1<=n&&(t.createObjectStore(Rv),(i=t).createObjectStore(Dv,{keyPath:"userId"}),i.createObjectStore(xv,{keyPath:Ov,autoIncrement:!0}).createIndex(Lv,Mv,{unique:!0}),i.createObjectStore(qv),qT(t),t.createObjectStore(Nv));let a=O.resolve();return r<3&&3<=n&&(0!==r&&((i=t).deleteObjectStore(Xv),i.deleteObjectStore(Qv),i.deleteObjectStore(n_),qT(t)),a=a.next(()=>{return e=s,t=e.store(n_),r={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:P.min().toTimestamp(),targetCount:0},t.put(r_,r);var e,t,r})),r<4&&4<=n&&(a=(a=0!==r?a.next(()=>{return n=t,(i=s).store(xv).G().next(e=>{n.deleteObjectStore(xv),n.createObjectStore(xv,{keyPath:Ov,autoIncrement:!0}).createIndex(Lv,Mv,{unique:!0});let t=i.store(xv),r=e.map(e=>t.put(e));return O.waitFor(r)});var n,i}):a).next(()=>{t.createObjectStore(a_,{keyPath:"clientId"})})),r<5&&5<=n&&(a=a.next(()=>this._i(s))),r<6&&6<=n&&(a=a.next(()=>(t.createObjectStore(Gv),this.ai(s)))),r<7&&7<=n&&(a=a.next(()=>this.ui(s))),r<8&&8<=n&&(a=a.next(()=>this.ci(t,s))),r<9&&9<=n&&(a=a.next(()=>{var e;(e=t).objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges")})),r<10&&10<=n&&(a=a.next(()=>this.li(s))),r<11&&11<=n&&(a=a.next(()=>{t.createObjectStore(o_,{keyPath:"bundleId"}),t.createObjectStore(l_,{keyPath:"name"})})),r<12&&12<=n&&(a=a.next(()=>{var e;(e=t.createObjectStore(y_,{keyPath:w_})).createIndex(b_,I_,{unique:!1}),e.createIndex(T_,E_,{unique:!1})})),r<13&&13<=n&&(a=a.next(()=>{var e;(e=t.createObjectStore(jv,{keyPath:Bv})).createIndex(zv,Kv),e.createIndex(Wv,Hv)}).next(()=>this.hi(t,s)).next(()=>t.deleteObjectStore(Nv))),r<14&&14<=n&&(a=a.next(()=>this.Pi(t,s))),r<15&&15<=n&&(a=a.next(()=>{var e;(e=t).createObjectStore(h_,{keyPath:"indexId",autoIncrement:!0}).createIndex(u_,"collectionGroup",{unique:!1}),e.createObjectStore(c_,{keyPath:d_}).createIndex(p_,f_,{unique:!1}),e.createObjectStore(g_,{keyPath:m_}).createIndex(v_,__,{unique:!1})})),r<16&&16<=n&&(a=a.next(()=>{e.objectStore(c_).clear()}).next(()=>{e.objectStore(g_).clear()})),a=r<17&&17<=n?a.next(()=>{t.createObjectStore(C_,{keyPath:"name"})}):a}ai(t){let r=0;return t.store(Nv).Z((e,t)=>{r+=YI(t)}).next(()=>{var e={byteSize:r};return t.store(Gv).put($v,e)})}_i(n){let e=n.store(Dv),t=n.store(xv);return e.G().next(e=>O.forEach(e,r=>{var e=IDBKeyRange.bound([r.userId,bv],[r.userId,r.lastAcknowledgedBatchId]);return t.G(Lv,e).next(e=>O.forEach(e,e=>{S(e.userId===r.userId);var t=oI(this.serializer,e);return QI(n,r.userId,t).next(()=>{})}))}))}ui(e){let a=e.store(Xv),t=e.store(Nv);return e.store(n_).get(r_).next(i=>{let s=[];return t.Z((e,t)=>{let r=new D(e),n=[0,kv(r)];s.push(a.get(n).next(e=>e?O.resolve():(e=r,a.put({targetId:0,path:kv(e),sequenceNumber:i.highestListenSequenceNumber}))))}).next(()=>O.waitFor(s))})}ci(e,t){e.createObjectStore(i_,{keyPath:s_});let n=t.store(i_),i=new UI,s=r=>{if(i.add(r)){let e=r.lastSegment(),t=r.popLast();return n.put({collectionId:e,parent:kv(t)})}};return t.store(Nv).Z({Y:!0},(e,t)=>{var r=new D(e);return s(r.popLast())}).next(()=>t.store(qv).Z({Y:!0},([,e],t)=>{var r=Av(e);return s(r.popLast())}))}li(e){let n=e.store(Qv);return n.Z((e,t)=>{var r=lI(t),r=hI(this.serializer,r);return n.put(r)})}hi(e,s){let t=s.store(Nv),a=[];return t.Z((e,t)=>{var r,n=s.store(jv),i=((r=t).document?new x(D.fromString(r.document.name).popFirst(5)):r.noDocument?x.fromSegments(r.noDocument.path):r.unknownDocument?x.fromSegments(r.unknownDocument.path):k()).path.toArray(),i={prefixPath:i.slice(0,i.length-2),collectionGroup:i[i.length-2],documentId:i[i.length-1],readTime:t.readTime||[0,0],unknownDocument:t.unknownDocument,noDocument:t.noDocument,document:t.document,hasCommittedMutations:!!t.hasCommittedMutations};a.push(n.put(i))}).next(()=>O.waitFor(a))}Pi(e,s){let t=s.store(xv),a=vT(this.serializer),o=new LT(FT.ri,this.serializer.Tt);return t.G().next(e=>{let n=new Map;return e.forEach(e=>{let t,r=null!=(t=n.get(e.userId))?t:V();oI(this.serializer,e).keys().forEach(e=>r=r.add(e)),n.set(e.userId,r)}),O.forEach(n,(e,t)=>{var r=new Im(t),n=vI.It(this.serializer,r),i=o.getIndexManager(r),r=JI.It(r,this.serializer,i,o.referenceDelegate);return new CT(a,r,n,i).recalculateAndSaveOverlaysForDocumentKeys(new x_(s,wv.ae),e).next()})})}}function qT(e){e.createObjectStore(Xv,{keyPath:Zv}).createIndex(e_,t_,{unique:!0}),e.createObjectStore(Qv,{keyPath:"targetId"}).createIndex(Yv,Jv,{unique:!0}),e.createObjectStore(n_)}let jT="IndexedDbPersistence",BT="Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.";class zT{constructor(e,t,r,n,i,s,a,o,l,h,u=17){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=r,this.Ti=i,this.window=s,this.document=a,this.Ii=l,this.Ei=h,this.di=u,this.Gr=null,this.zr=!1,this.isPrimary=!1,this.networkEnabled=!0,this.Ai=null,this.inForeground=!1,this.Ri=null,this.Vi=null,this.mi=Number.NEGATIVE_INFINITY,this.fi=e=>Promise.resolve(),!zT.D())throw new N(A.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new pT(this,n),this.gi=t+"main",this.serializer=new rI(o),this.pi=new lv(this.gi,this.di,new VT(this.serializer)),this.jr=new yI,this.Hr=new nT(this.referenceDelegate,this.serializer),this.remoteDocumentCache=vT(this.serializer),this.Yr=new fI,this.window&&this.window.localStorage?this.yi=this.window.localStorage:(this.yi=null,!1===h&&km(jT,"LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."))}start(){return this.wi().then(()=>{if(this.isPrimary||this.allowTabSynchronization)return this.Si(),this.bi(),this.Di(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.Hr.getHighestSequenceNumber(e));throw new N(A.FAILED_PRECONDITION,BT)}).then(e=>{this.Gr=new wv(e,this.Ii)}).then(()=>{this.zr=!0}).catch(e=>(this.pi&&this.pi.close(),Promise.reject(e)))}Ci(t){return this.fi=async e=>{if(this.started)return t(e)},t(this.isPrimary)}setDatabaseDeletedListener(t){this.pi.k(async e=>{null===e.newVersion&&await t()})}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.Ti.enqueueAndForget(async()=>{this.started&&await this.wi()}))}wi(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",t=>WT(t).put({clientId:this.clientId,updateTimeMs:Date.now(),networkEnabled:this.networkEnabled,inForeground:this.inForeground}).next(()=>{if(this.isPrimary)return this.Fi(t).next(e=>{e||(this.isPrimary=!1,this.Ti.enqueueRetryable(()=>this.fi(!1)))})}).next(()=>this.Mi(t)).next(e=>this.isPrimary&&!e?this.xi(t).next(()=>!1):!!e&&this.Oi(t).next(()=>!0))).catch(e=>{if(dv(e))return C(jT,"Failed to extend owner lease: ",e),this.isPrimary;if(this.allowTabSynchronization)return C(jT,"Releasing owner lease after error during lease refresh",e),!1;throw e}).then(e=>{this.isPrimary!==e&&this.Ti.enqueueRetryable(()=>this.fi(e)),this.isPrimary=e})}Fi(e){return KT(e).get(Pv).next(e=>O.resolve(this.Ni(e)))}Bi(e){return WT(e).delete(this.clientId)}async Li(){if(this.isPrimary&&!this.ki(this.mi,18e5)){this.mi=Date.now();var e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",e=>{let n=O_(e,a_);return n.G().next(e=>{let t=this.qi(e,18e5),r=e.filter(e=>-1===t.indexOf(e));return O.forEach(r,e=>n.delete(e.clientId)).next(()=>r)})}).catch(()=>[]);if(this.yi)for(var t of e)this.yi.removeItem(this.Qi(t.clientId))}}Di(){this.Vi=this.Ti.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.wi().then(()=>this.Li()).then(()=>this.Di()))}Ni(e){return!!e&&e.ownerId===this.clientId}Mi(t){return this.Ei?O.resolve(!0):KT(t).get(Pv).next(e=>{if(null!==e&&this.ki(e.leaseTimestampMs,5e3)&&!this.$i(e.ownerId)){if(this.Ni(e)&&this.networkEnabled)return!0;if(!this.Ni(e)){if(e.allowTabSynchronization)return!1;throw new N(A.FAILED_PRECONDITION,BT)}}return!(!this.networkEnabled||!this.inForeground)||WT(t).G().next(e=>void 0===this.qi(e,5e3).find(e=>{if(this.clientId!==e.clientId){var t=!this.networkEnabled&&e.networkEnabled,r=!this.inForeground&&e.inForeground,n=this.networkEnabled===e.networkEnabled;if(t||r&&n)return!0}return!1}))}).next(e=>(this.isPrimary!==e&&C(jT,`Client ${e?"is":"is not"} eligible for a primary lease.`),e))}async shutdown(){this.zr=!1,this.Ki(),this.Vi&&(this.Vi.cancel(),this.Vi=null),this.Ui(),this.Wi(),await this.pi.runTransaction("shutdown","readwrite",[Rv,a_],e=>{let t=new x_(e,wv.ae);return this.xi(t).next(()=>this.Bi(t))}),this.pi.close(),this.Gi()}qi(e,t){return e.filter(e=>this.ki(e.updateTimeMs,t)&&!this.$i(e.clientId))}zi(){return this.runTransaction("getActiveClients","readonly",e=>WT(e).G().next(e=>this.qi(e,18e5).map(e=>e.clientId)))}get started(){return this.zr}getGlobalsCache(){return this.jr}getMutationQueue(e,t){return JI.It(e,this.serializer,t,this.referenceDelegate)}getTargetCache(){return this.Hr}getRemoteDocumentCache(){return this.remoteDocumentCache}getIndexManager(e){return new jI(e,this.serializer.Tt.databaseId)}getDocumentOverlayCache(e){return vI.It(this.serializer,e)}getBundleCache(){return this.Yr}runTransaction(t,r,n){C(jT,"Starting transaction:",t);var e,i="readonly"===r?"readonly":"readwrite",s=17===(e=this.di)?D_:16===e?P_:15===e?R_:14===e?N_:13===e?A_:12===e?S_:11===e?k_:void k();let a;return this.pi.runTransaction(t,i,s,e=>(a=new x_(e,this.Gr?this.Gr.next():wv.ae),"readwrite-primary"===r?this.Fi(a).next(e=>!!e||this.Mi(a)).next(e=>{if(e)return n(a);throw km(`Failed to obtain primary lease for action '${t}'.`),this.isPrimary=!1,this.Ti.enqueueRetryable(()=>this.fi(!1)),new N(A.FAILED_PRECONDITION,nv)}).next(e=>this.Oi(a).next(()=>e)):this.ji(a).next(()=>n(a)))).then(e=>(a.raiseOnCommittedEvent(),e))}ji(e){return KT(e).get(Pv).next(e=>{if(null!==e&&this.ki(e.leaseTimestampMs,5e3)&&!this.$i(e.ownerId)&&!this.Ni(e)&&!(this.Ei||this.allowTabSynchronization&&e.allowTabSynchronization))throw new N(A.FAILED_PRECONDITION,BT)})}Oi(e){var t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return KT(e).put(Pv,t)}static D(){return lv.D()}xi(e){let t=KT(e);return t.get(Pv).next(e=>this.Ni(e)?(C(jT,"Releasing primary lease."),t.delete(Pv)):O.resolve())}ki(e,t){var r=Date.now();return!(e<r-t||r<e&&(km(`Detected an update time that is in the future: ${e} > `+r),1))}Si(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.Ri=()=>{this.Ti.enqueueAndForget(()=>(this.inForeground="visible"===this.document.visibilityState,this.wi()))},this.document.addEventListener("visibilitychange",this.Ri),this.inForeground="visible"===this.document.visibilityState)}Ui(){this.Ri&&(this.document.removeEventListener("visibilitychange",this.Ri),this.Ri=null)}bi(){var e;"function"==typeof(null==(e=this.window)?void 0:e.addEventListener)&&(this.Ai=()=>{this.Ki();var e=/(?:Version|Mobile)\/1[456]/;le()&&(navigator.appVersion.match(e)||navigator.userAgent.match(e))&&this.Ti.enterRestrictedMode(!0),this.Ti.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.Ai))}Wi(){this.Ai&&(this.window.removeEventListener("pagehide",this.Ai),this.Ai=null)}$i(e){var t;try{var r=null!==(null==(t=this.yi)?void 0:t.getItem(this.Qi(e)));return C(jT,`Client '${e}' ${r?"is":"is not"} zombied in LocalStorage`),r}catch(e){return km(jT,"Failed to get zombied client id.",e),!1}}Ki(){if(this.yi)try{this.yi.setItem(this.Qi(this.clientId),String(Date.now()))}catch(e){km("Failed to set zombie client id.",e)}}Gi(){if(this.yi)try{this.yi.removeItem(this.Qi(this.clientId))}catch(e){}}Qi(e){return`firestore_zombie_${this.persistenceKey}_`+e}}function KT(e){return O_(e,Rv)}function WT(e){return O_(e,a_)}function HT(e,t){let r=e.projectId;return e.isDefaultDatabase||(r+="."+e.database),"firestore/"+t+"/"+r+"/"}class GT{constructor(e,t,r,n){this.targetId=e,this.fromCache=t,this.Hi=r,this.Ji=n}static Yi(e,t){let r=V(),n=V();for(let e of t.docChanges)switch(e.type){case 0:r=r.add(e.doc.key);break;case 1:n=n.add(e.doc.key)}return new GT(e,t.fromCache,r,n)}}class $T{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}}class QT{constructor(){this.Zi=!1,this.Xi=!1,this.es=100,this.ts=le()?8:0<hv(ee())?6:4}initialize(e,t){this.ns=e,this.indexManager=t,this.Zi=!0}getDocumentsMatchingQuery(r,n,e,t){let i={result:null};return this.rs(r,n).next(e=>{i.result=e}).next(()=>{if(!i.result)return this.ss(r,n,t,e).next(e=>{i.result=e})}).next(()=>{if(!i.result){let t=new $T;return this._s(r,n,t).next(e=>{if(i.result=e,this.Xi)return this.us(r,n,t,e.size)})}}).next(()=>i.result)}us(e,t,r,n){return r.documentReadCount<this.es?(Cm()<=c.DEBUG&&C("QueryEngine","SDK will not create cache indexes for query:",mw(t),"since it only creates cache indexes for collection contains","more than or equal to",this.es,"documents"),O.resolve()):(Cm()<=c.DEBUG&&C("QueryEngine","Query:",mw(t),"scans",r.documentReadCount,"local documents and returns",n,"documents as results."),r.documentReadCount>this.ts*n?(Cm()<=c.DEBUG&&C("QueryEngine","The SDK decides to create cache indexes for query:",mw(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,cw(t))):O.resolve())}rs(i,s){if(lw(s))return O.resolve(null);let t=cw(s);return this.indexManager.getIndexType(i,t).next(e=>0===e?null:(null!==s.limit&&1===e&&(s=pw(s,null,"F"),t=cw(s)),this.indexManager.getDocumentsMatchingTarget(i,t).next(e=>{let n=V(...e);return this.ns.getDocuments(i,n).next(r=>this.indexManager.getMinOffset(i,t).next(e=>{var t=this.cs(s,r);return this.ls(s,t,n,e.readTime)?this.rs(i,pw(s,null,"F")):this.hs(i,t,s,e)}))})))}ss(r,n,i,s){return lw(n)||s.isEqual(P.min())?O.resolve(null):this.ns.getDocuments(r,i).next(e=>{var t=this.cs(n,e);return this.ls(n,t,i,s)?O.resolve(null):(Cm()<=c.DEBUG&&C("QueryEngine","Re-using previous result from %s to execute query: %s",s.toString(),mw(n)),this.hs(r,t,n,Zm(s,Gm)).next(e=>e))})}cs(r,e){let n=new M(yw(r));return e.forEach((e,t)=>{vw(r,t)&&(n=n.add(t))}),n}ls(e,t,r,n){var i;return null!==e.limit&&(r.size!==t.size||!!(i="F"===e.limitType?t.last():t.first())&&(i.hasPendingWrites||0<i.version.compareTo(n)))}_s(e,t,r){return Cm()<=c.DEBUG&&C("QueryEngine","Using full collection scan to execute query:",mw(t)),this.ns.getDocumentsMatchingQuery(e,t,tv.min(),r)}hs(e,r,t,n){return this.ns.getDocumentsMatchingQuery(e,t,n).next(t=>(r.forEach(e=>{t=t.insert(e.key,e)}),t))}}let YT="LocalStore",JT=3e8;class XT{constructor(e,t,r,n){this.persistence=e,this.Ps=t,this.serializer=n,this.Ts=new L(R),this.Is=new ww(e=>Zy(e),ew),this.Es=new Map,this.ds=e.getRemoteDocumentCache(),this.Hr=e.getTargetCache(),this.Yr=e.getBundleCache(),this.As(r)}As(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new CT(this.ds,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.ds.setIndexManager(this.indexManager),this.Ps.initialize(this.localDocuments,this.indexManager)}collectGarbage(t){return this.persistence.runTransaction("Collect garbage","readwrite-primary",e=>t.collect(e,this.Ts))}}function ZT(e,t,r,n){return new XT(e,t,r,n)}async function eE(e,t){let o=e;return o.persistence.runTransaction("Handle user change","readonly",s=>{let a;return o.mutationQueue.getAllMutationBatches(s).next(e=>(a=e,o.As(t),o.mutationQueue.getAllMutationBatches(s))).next(e=>{let t=[],r=[],n=V();for(let i of a){t.push(i.batchId);for(let e of i.mutations)n=n.add(e.key)}for(let i of e){r.push(i.batchId);for(let e of i.mutations)n=n.add(e.key)}return o.localDocuments.getDocuments(s,n).next(e=>({Rs:e,removedBatchIds:t,addedBatchIds:r}))})})}function tE(e,n){let i=e;return i.persistence.runTransaction("Acknowledge batch","readwrite-primary",e=>{let t=n.batch.keys(),r=i.ds.newChangeBuffer({trackRemovals:!0});return((e,t,n,i)=>{let s=n.batch,r=s.keys(),a=O.resolve();return r.forEach(r=>{a=a.next(()=>i.getEntry(t,r)).next(e=>{var t=n.docVersions.get(r);S(null!==t),e.version.compareTo(t)<0&&(s.applyToRemoteDocument(e,n),e.isValidDocument())&&(e.setReadTime(n.commitVersion),i.addEntry(e))})}),a.next(()=>e.mutationQueue.removeMutationBatch(t,s))})(i,e,n,r).next(()=>r.apply(e)).next(()=>i.mutationQueue.performConsistencyCheck(e)).next(()=>i.documentOverlayCache.removeOverlaysForBatchId(e,t,n.batch.batchId)).next(()=>i.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,(e=>{let t=V();for(let r=0;r<e.mutationResults.length;++r)0<e.mutationResults[r].transformResults.length&&(t=t.add(e.batch.mutations[r].key));return t})(n))).next(()=>i.localDocuments.getDocuments(e,t))})}function rE(e){let t=e;return t.persistence.runTransaction("Get last remote snapshot version","readonly",e=>t.Hr.getLastRemoteSnapshotVersion(e))}function nE(e,h){let u=e,c=h.snapshotVersion,d=u.Ts;return u.persistence.runTransaction("Apply remote event","readwrite-primary",o=>{let e=u.ds.newChangeBuffer({trackRemovals:!0}),l=(d=u.Ts,[]),t=(h.targetChanges.forEach((t,r)=>{var n,i,s,a=d.get(r);if(a){l.push(u.Hr.removeMatchingKeys(o,t.removedDocuments,r).next(()=>u.Hr.addMatchingKeys(o,t.addedDocuments,r)));let e=a.withSequenceNumber(o.currentSequenceNumber);null!==h.targetMismatches.get(r)?e=e.withResumeToken(K_.EMPTY_BYTE_STRING,P.min()).withLastLimboFreeSnapshotVersion(P.min()):0<t.resumeToken.approximateByteSize()&&(e=e.withResumeToken(t.resumeToken,c)),d=d.insert(r,e),n=a,i=e,s=t,(0===n.resumeToken.approximateByteSize()||i.snapshotVersion.toMicroseconds()-n.snapshotVersion.toMicroseconds()>=JT||0<s.addedDocuments.size+s.modifiedDocuments.size+s.removedDocuments.size)&&l.push(u.Hr.updateTargetData(o,e))}}),bw),r=V();if(h.documentUpdates.forEach(e=>{h.resolvedLimboDocuments.has(e)&&l.push(u.persistence.referenceDelegate.updateLimboDocument(o,e))}),l.push(iE(o,e,h.documentUpdates).next(e=>{t=e.Vs,r=e.fs})),!c.isEqual(P.min())){let e=u.Hr.getLastRemoteSnapshotVersion(o).next(e=>u.Hr.setTargetsMetadata(o,o.currentSequenceNumber,c));l.push(e)}return O.waitFor(l).next(()=>e.apply(o)).next(()=>u.localDocuments.getLocalViewOfDocuments(o,t,r)).next(()=>t)}).then(e=>(u.Ts=d,e))}function iE(e,s,t){let r=V(),a=V();return t.forEach(e=>r=r.add(e)),s.getEntries(e,r).next(n=>{let i=bw;return t.forEach((e,t)=>{var r=n.get(e);t.isFoundDocument()!==r.isFoundDocument()&&(a=a.add(e)),t.isNoDocument()&&t.version.isEqual(P.min())?(s.removeEntry(e,t.readTime),i=i.insert(e,t)):!r.isValidDocument()||0<t.version.compareTo(r.version)||0===t.version.compareTo(r.version)&&r.hasPendingWrites?(s.addEntry(t),i=i.insert(e,t)):C(YT,"Ignoring outdated watch update for ",e,". Current version:",r.version," Watch version:",t.version)}),{Vs:i,fs:a}})}function sE(e,n){let i=e;return i.persistence.runTransaction("Allocate target","readwrite",t=>{let r;return i.Hr.getTargetData(t,n).next(e=>e?(r=e,O.resolve(r)):i.Hr.allocateTargetId(t).next(e=>(r=new tI(n,e,"TargetPurposeListen",t.currentSequenceNumber),i.Hr.addTargetData(t,r).next(()=>r))))}).then(e=>{var t=i.Ts.get(e.targetId);return(null===t||0<e.snapshotVersion.compareTo(t.snapshotVersion))&&(i.Ts=i.Ts.insert(e.targetId,e),i.Is.set(n,e.targetId)),e})}async function aE(e,t,r){let n=e,i=n.Ts.get(t),s=r?"readwrite":"readwrite-primary";try{r||await n.persistence.runTransaction("Release target",s,e=>n.persistence.referenceDelegate.removeTarget(e,i))}catch(e){if(!dv(e))throw e;C(YT,`Failed to update sequence numbers for target ${t}: `+e)}n.Ts=n.Ts.remove(t),n.Is.delete(i.target)}function oE(e,a,o){let l=e,h=P.min(),u=V();return l.persistence.runTransaction("Execute query","readwrite",t=>{return e=l,r=t,n=cw(a),(void 0!==(s=(i=e).Is.get(n))?O.resolve(i.Ts.get(s)):i.Hr.getTargetData(r,n)).next(e=>{if(e)return h=e.lastLimboFreeSnapshotVersion,l.Hr.getMatchingKeysForTargetId(t,e.targetId).next(e=>{u=e})}).next(()=>l.Ps.getDocumentsMatchingQuery(t,a,o?h:P.min(),o?u:V())).next(e=>(uE(l,_w(a),e),{documents:e,gs:u}));var e,r,n,i,s})}function lE(e,t){let r=e,n=r.Hr,i=r.Ts.get(t);return i?Promise.resolve(i.target):r.persistence.runTransaction("Get target data","readonly",e=>n.lt(e,t).next(e=>e?e.target:null))}function hE(e,t){let r=e,n=r.Es.get(t)||P.min();return r.persistence.runTransaction("Get new document changes","readonly",e=>r.ds.getAllFromCollectionGroup(e,t,Zm(n,Gm),Number.MAX_SAFE_INTEGER)).then(e=>(uE(r,t,e),e))}function uE(e,t,r){let n=e.Es.get(t)||P.min();r.forEach((e,t)=>{0<t.readTime.compareTo(n)&&(n=t.readTime)}),e.Es.set(t,n)}let cE="firestore_clients";function dE(e,t){return cE+`_${e}_`+t}let pE="firestore_mutations";function fE(e,t,r){let n=pE+`_${e}_`+r;return t.isAuthenticated()&&(n+="_"+t.uid),n}let gE="firestore_targets";function mE(e,t){return gE+`_${e}_`+t}let vE="SharedClientState";class _E{constructor(e,t,r,n){this.user=e,this.batchId=t,this.state=r,this.error=n}static Ss(e,t,r){var n=JSON.parse(r);let i,s="object"==typeof n&&-1!==["pending","acknowledged","rejected"].indexOf(n.state)&&(void 0===n.error||"object"==typeof n.error);return s&&n.error&&(s="string"==typeof n.error.message&&"string"==typeof n.error.code)&&(i=new N(n.error.code,n.error.message)),s?new _E(e,t,n.state,i):(km(vE,`Failed to parse mutation state for ID '${t}': `+r),null)}bs(){var e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class yE{constructor(e,t,r){this.targetId=e,this.state=t,this.error=r}static Ss(e,t){var r=JSON.parse(t);let n,i="object"==typeof r&&-1!==["not-current","current","rejected"].indexOf(r.state)&&(void 0===r.error||"object"==typeof r.error);return i&&r.error&&(i="string"==typeof r.error.message&&"string"==typeof r.error.code)&&(n=new N(r.error.code,r.error.message)),i?new yE(e,r.state,n):(km(vE,`Failed to parse target state for ID '${e}': `+t),null)}bs(){var e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class wE{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static Ss(e,t){var r=JSON.parse(t);let n="object"==typeof r&&r.activeTargetIds instanceof Array,i=Aw;for(let s=0;n&&s<r.activeTargetIds.length;++s)n=Ev(r.activeTargetIds[s]),i=i.add(r.activeTargetIds[s]);return n?new wE(e,i):(km(vE,`Failed to parse client data for instance '${e}': `+t),null)}}class bE{constructor(e,t){this.clientId=e,this.onlineState=t}static Ss(e){var t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new bE(t.clientId,t.onlineState):(km(vE,"Failed to parse online state: "+e),null)}}class IE{constructor(){this.activeTargetIds=Aw}Ds(e){this.activeTargetIds=this.activeTargetIds.add(e)}vs(e){this.activeTargetIds=this.activeTargetIds.delete(e)}bs(){var e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class TE{constructor(e,t,r,n,i){this.window=e,this.Ti=t,this.persistenceKey=r,this.Cs=n,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.Fs=this.Ms.bind(this),this.xs=new L(R),this.started=!1,this.Os=[];var s=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=i,this.Ns=dE(this.persistenceKey,this.Cs),this.Bs="firestore_sequence_number_"+this.persistenceKey,this.xs=this.xs.insert(this.Cs,new IE),this.Ls=new RegExp(`^${cE}_${s}_([^_]*)$`),this.ks=new RegExp(`^${pE}_${s}_(\\d+)(?:_(.*))?$`),this.qs=new RegExp(`^${gE}_${s}_(\\d+)$`),this.Qs="firestore_online_state_"+this.persistenceKey,this.$s="firestore_bundle_loaded_v2_"+this.persistenceKey,this.window.addEventListener("storage",this.Fs)}static D(e){return!(!e||!e.localStorage)}async start(){let e=await this.syncEngine.zi();for(let r of e)if(r!==this.Cs){let e=this.getItem(dE(this.persistenceKey,r));var t;e&&(t=wE.Ss(r,e))&&(this.xs=this.xs.insert(t.clientId,t))}this.Ks();let r=this.storage.getItem(this.Qs);if(r){let e=this.Us(r);e&&this.Ws(e)}for(let e of this.Os)this.Ms(e);this.Os=[],this.window.addEventListener("pagehide",()=>this.shutdown()),this.started=!0}writeSequenceNumber(e){this.setItem(this.Bs,JSON.stringify(e))}getAllActiveQueryTargets(){return this.Gs(this.xs)}isActiveQueryTarget(r){let n=!1;return this.xs.forEach((e,t)=>{t.activeTargetIds.has(r)&&(n=!0)}),n}addPendingMutation(e){this.zs(e,"pending")}updateMutationState(e,t,r){this.zs(e,t,r),this.js(e)}addLocalQueryTarget(t,e=!0){let r="not-current";if(this.isActiveQueryTarget(t)){let e=this.storage.getItem(mE(this.persistenceKey,t));var n;e&&(n=yE.Ss(t,e))&&(r=n.state)}return e&&this.Hs.Ds(t),this.Ks(),r}removeLocalQueryTarget(e){this.Hs.vs(e),this.Ks()}isLocalQueryTarget(e){return this.Hs.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(mE(this.persistenceKey,e))}updateQueryState(e,t,r){this.Js(e,t,r)}handleUserChange(e,t,r){t.forEach(e=>{this.js(e)}),this.currentUser=e,r.forEach(e=>{this.addPendingMutation(e)})}setOnlineState(e){this.Ys(e)}notifyBundleLoaded(e){this.Zs(e)}shutdown(){this.started&&(this.window.removeEventListener("storage",this.Fs),this.removeItem(this.Ns),this.started=!1)}getItem(e){var t=this.storage.getItem(e);return C(vE,"READ",e,t),t}setItem(e,t){C(vE,"SET",e,t),this.storage.setItem(e,t)}removeItem(e){C(vE,"REMOVE",e),this.storage.removeItem(e)}Ms(e){let t=e;t.storageArea===this.storage&&(C(vE,"EVENT",t.key,t.newValue),t.key===this.Ns?km("Received WebStorage notification for local change. Another client might have garbage-collected our state"):this.Ti.enqueueRetryable(async()=>{if(this.started){if(null!==t.key){if(this.Ls.test(t.key))return null==t.newValue?(e=this.Xs(t.key),this.eo(e,null)):(e=this.no(t.key,t.newValue))?this.eo(e.clientId,e):void 0;if(this.ks.test(t.key)){if(null!==t.newValue){var e=this.ro(t.key,t.newValue);if(e)return this.io(e)}}else if(this.qs.test(t.key)){if(null!==t.newValue){var e=this.so(t.key,t.newValue);if(e)return this.oo(e)}}else if(t.key===this.Qs){if(null!==t.newValue){var e=this.Us(t.newValue);if(e)return this.Ws(e)}}else t.key===this.Bs?(e=(e=>{let t=wv.ae;if(null!=e)try{var r=JSON.parse(e);S("number"==typeof r),t=r}catch(e){km(vE,"Failed to read sequence number from WebStorage",e)}return t})(t.newValue))!==wv.ae&&this.sequenceNumberHandler(e):t.key===this.$s&&(e=this._o(t.newValue),await Promise.all(e.map(e=>this.syncEngine.ao(e))))}}else this.Os.push(t)}))}get Hs(){return this.xs.get(this.Cs)}Ks(){this.setItem(this.Ns,this.Hs.bs())}zs(e,t,r){var n=new _E(this.currentUser,e,t,r),i=fE(this.persistenceKey,this.currentUser,e);this.setItem(i,n.bs())}js(e){var t=fE(this.persistenceKey,this.currentUser,e);this.removeItem(t)}Ys(e){var t={clientId:this.Cs,onlineState:e};this.storage.setItem(this.Qs,JSON.stringify(t))}Js(e,t,r){var n=mE(this.persistenceKey,e),i=new yE(e,t,r);this.setItem(n,i.bs())}Zs(e){var t=JSON.stringify(Array.from(e));this.setItem(this.$s,t)}Xs(e){var t=this.Ls.exec(e);return t?t[1]:null}no(e,t){var r=this.Xs(e);return wE.Ss(r,t)}ro(e,t){var r=this.ks.exec(e),n=Number(r[1]),r=void 0!==r[2]?r[2]:null;return _E.Ss(new Im(r),n,t)}so(e,t){var r=this.qs.exec(e),r=Number(r[1]);return yE.Ss(r,t)}Us(e){return bE.Ss(e)}_o(e){return JSON.parse(e)}async io(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.uo(e.batchId,e.state,e.error);C(vE,"Ignoring mutation for non-active user "+e.user.uid)}oo(e){return this.syncEngine.co(e.targetId,e.state,e.error)}eo(e,t){let r=t?this.xs.insert(e,t):this.xs.remove(e),n=this.Gs(this.xs),i=this.Gs(r),s=[],a=[];return i.forEach(e=>{n.has(e)||s.push(e)}),n.forEach(e=>{i.has(e)||a.push(e)}),this.syncEngine.lo(s,a).then(()=>{this.xs=r})}Ws(e){this.xs.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}Gs(e){let r=Aw;return e.forEach((e,t)=>{r=r.unionWith(t.activeTargetIds)}),r}}class EE{constructor(){this.ho=new IE,this.Po={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,r){}addLocalQueryTarget(e,t=!0){return t&&this.ho.Ds(e),this.Po[e]||"not-current"}updateQueryState(e,t,r){this.Po[e]=t}removeLocalQueryTarget(e){this.ho.vs(e)}isLocalQueryTarget(e){return this.ho.activeTargetIds.has(e)}clearQueryState(e){delete this.Po[e]}getAllActiveQueryTargets(){return this.ho.activeTargetIds}isActiveQueryTarget(e){return this.ho.activeTargetIds.has(e)}start(){return this.ho=new IE,Promise.resolve()}handleUserChange(e,t,r){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class CE{To(e){}shutdown(){}}let kE="ConnectivityMonitor";class SE{constructor(){this.Io=()=>this.Eo(),this.Ao=()=>this.Ro(),this.Vo=[],this.mo()}To(e){this.Vo.push(e)}shutdown(){window.removeEventListener("online",this.Io),window.removeEventListener("offline",this.Ao)}mo(){window.addEventListener("online",this.Io),window.addEventListener("offline",this.Ao)}Eo(){C(kE,"Network connectivity changed: AVAILABLE");for(var e of this.Vo)e(0)}Ro(){C(kE,"Network connectivity changed: UNAVAILABLE");for(var e of this.Vo)e(1)}static D(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}let AE=null;function NE(){return null===AE?AE=268435456+Math.round(2147483648*Math.random()):AE++,"0x"+AE.toString(16)}let RE="RestConnection",PE={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"};class DE{constructor(e){this.Fo=e.Fo,this.Mo=e.Mo}xo(e){this.Oo=e}No(e){this.Bo=e}Lo(e){this.ko=e}onMessage(e){this.qo=e}close(){this.Mo()}send(e){this.Fo(e)}Qo(){this.Oo()}$o(){this.Bo()}Ko(e){this.ko(e)}Uo(e){this.qo(e)}}let xE="WebChannelConnection";class OE extends class{get fo(){return!1}constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;var t=e.ssl?"https":"http",r=encodeURIComponent(this.databaseId.projectId),n=encodeURIComponent(this.databaseId.database);this.po=t+"://"+e.host,this.yo=`projects/${r}/databases/`+n,this.wo=this.databaseId.database===ny?"project_id="+r:`project_id=${r}&database_id=`+n}So(t,e,r,n,i){let s=NE(),a=this.bo(t,e.toUriEncodedString());C(RE,`Sending RPC '${t}' ${s}:`,a,r);var o={"google-cloud-resource-prefix":this.yo,"x-goog-request-params":this.wo};return this.Do(o,n,i),this.vo(t,a,o,r).then(e=>(C(RE,`Received RPC '${t}' ${s}: `,e),e),e=>{throw Sm(RE,`RPC '${t}' ${s} failed with error: `,e,"url: ",a,"request:",r),e})}Co(e,t,r,n,i,s){return this.So(e,t,r,n,i)}Do(r,e,t){r["X-Goog-Api-Client"]="gl-js/ fire/"+Tm,r["Content-Type"]="text/plain",this.databaseInfo.appId&&(r["X-Firebase-GMPID"]=this.databaseInfo.appId),e&&e.headers.forEach((e,t)=>r[t]=e),t&&t.headers.forEach((e,t)=>r[t]=e)}bo(e,t){var r=PE[e];return this.po+`/v1/${t}:`+r}terminate(){}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}vo(l,t,r,n){let h=NE();return new Promise((s,a)=>{let o=new hm;o.setWithCredentials(!0),o.listenOnce(cm.COMPLETE,()=>{try{switch(o.getLastErrorCode()){case dm.NO_ERROR:var e=o.getResponseJson();C(xE,`XHR for RPC '${l}' ${h} received:`,JSON.stringify(e)),s(e);break;case dm.TIMEOUT:C(xE,`RPC '${l}' ${h} timed out`),a(new N(A.DEADLINE_EXCEEDED,"Request time out"));break;case dm.HTTP_ERROR:var t=o.getStatus();if(C(xE,`RPC '${l}' ${h} failed with status:`,t,"response text:",o.getResponseText()),0<t){let e=o.getResponseJson();var r=null==(e=Array.isArray(e)?e[0]:e)?void 0:e.error;if(r&&r.status&&r.message){n=r.status,i=n.toLowerCase().replace(/_/g,"-");let e=0<=Object.values(A).indexOf(i)?i:A.UNKNOWN;a(new N(e,r.message))}else a(new N(A.UNKNOWN,"Server responded with status "+o.getStatus()))}else a(new N(A.UNAVAILABLE,"Connection failed."));break;default:k()}}finally{C(xE,`RPC '${l}' ${h} completed.`)}var n,i});var e=JSON.stringify(n);C(xE,`RPC '${l}' ${h} sending request:`,n),o.send(t,"POST",e,r,15)})}Wo(i,e,t){let s=NE(),r=[this.po,"/","google.firestore.v1.Firestore","/",i,"/channel"],n=mm(),a=gm(),o={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/`+this.databaseId.database},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling},l=this.longPollingOptions.timeoutSeconds;void 0!==l&&(o.longPollingTimeout=Math.round(1e3*l)),this.useFetchStreams&&(o.useFetchStreams=!0),this.Do(o.initMessageHeaders,e,t),o.encodeInitMessageHeaders=!0;var h=r.join("");C(xE,`Creating RPC '${i}' stream ${s}: `+h,o);let u=n.createWebChannel(h,o),c=!1,d=!1,p=new DE({Fo:e=>{d?C(xE,`Not sending because RPC '${i}' stream ${s} is closed:`,e):(c||(C(xE,`Opening RPC '${i}' stream ${s} transport.`),u.open(),c=!0),C(xE,`RPC '${i}' stream ${s} sending:`,e),u.send(e))},Mo:()=>u.close()}),f=(e,t,r)=>{e.listen(t,e=>{try{r(e)}catch(e){setTimeout(()=>{throw e},0)}})};return f(u,um.EventType.OPEN,()=>{d||(C(xE,`RPC '${i}' stream ${s} transport opened.`),p.Qo())}),f(u,um.EventType.CLOSE,()=>{d||(d=!0,C(xE,`RPC '${i}' stream ${s} transport closed`),p.Ko())}),f(u,um.EventType.ERROR,e=>{d||(d=!0,Sm(xE,`RPC '${i}' stream ${s} transport errored:`,e),p.Ko(new N(A.UNAVAILABLE,"The operation could not be completed")))}),f(u,um.EventType.MESSAGE,e=>{if(!d){var t=e.data[0],n=(S(!!t),t),n=(null==n?void 0:n.error)||(null==(n=n[0])?void 0:n.error);if(n){C(xE,`RPC '${i}' stream ${s} received error:`,n);let e=n.status,t=(e=>{var t=vm[e];if(void 0!==t)return lb(t)})(e),r=n.message;void 0===t&&(t=A.INTERNAL,r="Unknown error status: "+e+" with message "+n.message),d=!0,p.Ko(new N(t,r)),u.close()}else C(xE,`RPC '${i}' stream ${s} received:`,t),p.Uo(t)}}),f(a,fm.STAT_EVENT,e=>{e.stat===pm.PROXY?C(xE,`RPC '${i}' stream ${s} detected buffering proxy`):e.stat===pm.NOPROXY&&C(xE,`RPC '${i}' stream ${s} detected no buffering proxy`)}),setTimeout(()=>{p.$o()},0),p}}function LE(){return"undefined"!=typeof window?window:null}function ME(){return"undefined"!=typeof document?document:null}function FE(e){return new Sb(e,!0)}class UE{constructor(e,t,r=1e3,n=1.5,i=6e4){this.Ti=e,this.timerId=t,this.Go=r,this.zo=n,this.jo=i,this.Ho=0,this.Jo=null,this.Yo=Date.now(),this.reset()}reset(){this.Ho=0}Zo(){this.Ho=this.jo}Xo(e){this.cancel();var t=Math.floor(this.Ho+this.e_()),r=Math.max(0,Date.now()-this.Yo),n=Math.max(0,t-r);0<n&&C("ExponentialBackoff",`Backing off for ${n} ms (base delay: ${this.Ho} ms, delay with jitter: ${t} ms, last attempt: ${r} ms ago)`),this.Jo=this.Ti.enqueueAfterDelay(this.timerId,n,()=>(this.Yo=Date.now(),e())),this.Ho*=this.zo,this.Ho<this.Go&&(this.Ho=this.Go),this.Ho>this.jo&&(this.Ho=this.jo)}t_(){null!==this.Jo&&(this.Jo.skipDelay(),this.Jo=null)}cancel(){null!==this.Jo&&(this.Jo.cancel(),this.Jo=null)}e_(){return(Math.random()-.5)*this.Ho}}let VE="PersistentStream";class qE{constructor(e,t,r,n,i,s,a,o){this.Ti=e,this.n_=r,this.r_=n,this.connection=i,this.authCredentialsProvider=s,this.appCheckCredentialsProvider=a,this.listener=o,this.state=0,this.i_=0,this.s_=null,this.o_=null,this.stream=null,this.__=0,this.a_=new UE(e,t)}u_(){return 1===this.state||5===this.state||this.c_()}c_(){return 2===this.state||3===this.state}start(){this.__=0,4!==this.state?this.auth():this.l_()}async stop(){this.u_()&&await this.close(0)}h_(){this.state=0,this.a_.reset()}P_(){this.c_()&&null===this.s_&&(this.s_=this.Ti.enqueueAfterDelay(this.n_,6e4,()=>this.T_()))}I_(e){this.E_(),this.stream.send(e)}async T_(){if(this.c_())return this.close(0)}E_(){this.s_&&(this.s_.cancel(),this.s_=null)}d_(){this.o_&&(this.o_.cancel(),this.o_=null)}async close(e,t){this.E_(),this.d_(),this.a_.cancel(),this.i_++,4!==e?this.a_.reset():t&&t.code===A.RESOURCE_EXHAUSTED?(km(t.toString()),km("Using maximum backoff delay to prevent overloading the backend."),this.a_.Zo()):t&&t.code===A.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.A_(),this.stream.close(),this.stream=null),this.state=e,await this.listener.Lo(t)}A_(){}auth(){this.state=1;let e=this.R_(this.i_),r=this.i_;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,t])=>{this.i_===r&&this.V_(e,t)},t=>{e(()=>{var e=new N(A.UNKNOWN,"Fetching auth token failed: "+t.message);return this.m_(e)})})}V_(e,t){let r=this.R_(this.i_);this.stream=this.f_(e,t),this.stream.xo(()=>{r(()=>this.listener.xo())}),this.stream.No(()=>{r(()=>(this.state=2,this.o_=this.Ti.enqueueAfterDelay(this.r_,1e4,()=>(this.c_()&&(this.state=3),Promise.resolve())),this.listener.No()))}),this.stream.Lo(e=>{r(()=>this.m_(e))}),this.stream.onMessage(e=>{r(()=>1==++this.__?this.g_(e):this.onNext(e))})}l_(){this.state=5,this.a_.Xo(async()=>{this.state=0,this.start()})}m_(e){return C(VE,"close with error: "+e),this.stream=null,this.close(4,e)}R_(t){return e=>{this.Ti.enqueueAndForget(()=>this.i_===t?e():(C(VE,"stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class jE extends qE{constructor(e,t,r,n,i,s){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,r,n,s),this.serializer=i}f_(e,t){return this.connection.Wo("Listen",e,t)}g_(e){return this.onNext(e)}onNext(e){this.a_.reset();var t=((e,t)=>{let r;if("targetChange"in t){t.targetChange;var n="NO_CHANGE"===(l=t.targetChange.targetChangeType||"NO_CHANGE")?0:"ADD"===l?1:"REMOVE"===l?2:"CURRENT"===l?3:"RESET"===l?4:k(),i=t.targetChange.targetIds||[],s=(l=t.targetChange.resumeToken,e.useProto3Json?(S(void 0===l||"string"==typeof l),K_.fromBase64String(l||"")):(S(void 0===l||l instanceof Buffer||l instanceof Uint8Array),K_.fromUint8Array(l||new Uint8Array))),a=t.targetChange.cause,a=a&&(a=void 0===(l=a).code?A.UNKNOWN:lb(l.code),new N(a,l.message||""));r=new yb(n,i,s,a||null)}else if("documentChange"in t){t.documentChange;var n=t.documentChange,i=(n.document,n.document.name,n.document.updateTime,Mb(e,n.document.name)),s=Pb(n.document.updateTime),a=n.document.createTime?Pb(n.document.createTime):P.min(),o=new Ry({mapValue:{fields:n.document.fields}}),i=Py.newFoundDocument(i,s,a,o),s=n.targetIds||[],o=n.removedTargetIds||[];r=new vb(s,o,i.key,i)}else if("documentDelete"in t){t.documentDelete;n=t.documentDelete,s=(n.document,Mb(e,n.document)),o=n.readTime?Pb(n.readTime):P.min(),i=Py.newNoDocument(s,o),s=n.removedTargetIds||[];r=new vb([],s,i.key,i)}else if("documentRemove"in t){t.documentRemove;o=t.documentRemove,n=(o.document,Mb(e,o.document)),s=o.removedTargetIds||[];r=new vb([],s,n,null)}else{if(!("filter"in t))return k();{t.filter;let e=t.filter;e.targetId;var{count:i=0,unchangedNames:o}=e,s=new ab(i,o),n=e.targetId;r=new _b(n,s)}}var l;return r})(this.serializer,e),r="targetChange"in(e=e)&&(!(r=e.targetChange).targetIds||!r.targetIds.length)&&r.readTime?Pb(r.readTime):P.min();return this.listener.p_(t,r)}y_(e){var t={},r=(t.database=Vb(this.serializer),t.addTarget=((t,r)=>{var n;let e=r.target;if((n=tw(e)?{documents:Hb(t,e)}:{query:Gb(t,e).ht}).targetId=r.targetId,0<r.resumeToken.approximateByteSize()){n.resumeToken=Rb(t,r.resumeToken);let e=Ab(t,r.expectedCount);null!==e&&(n.expectedCount=e)}else if(0<r.snapshotVersion.compareTo(P.min())){n.readTime=Nb(t,r.snapshotVersion.toTimestamp());let e=Ab(t,r.expectedCount);null!==e&&(n.expectedCount=e)}return n})(this.serializer,e),Qb(this.serializer,e));r&&(t.labels=r),this.I_(t)}w_(e){var t={};t.database=Vb(this.serializer),t.removeTarget=e,this.I_(t)}}class BE extends qE{constructor(e,t,r,n,i,s){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,r,n,s),this.serializer=i}get S_(){return 0<this.__}start(){this.lastStreamToken=void 0,super.start()}A_(){this.S_&&this.b_([])}f_(e,t){return this.connection.Wo("Write",e,t)}g_(e){return S(!!e.streamToken),this.lastStreamToken=e.streamToken,S(!e.writeResults||0===e.writeResults.length),this.listener.D_()}onNext(e){S(!!e.streamToken),this.lastStreamToken=e.streamToken,this.a_.reset();var t=Wb(e.writeResults,e.commitTime),r=Pb(e.commitTime);return this.listener.v_(r,t)}C_(){var e={};e.database=Vb(this.serializer),this.I_(e)}b_(e){var t={streamToken:this.lastStreamToken,writes:e.map(e=>zb(this.serializer,e))};this.I_(t)}}class zE extends class{}{constructor(e,t,r,n){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=r,this.serializer=n,this.F_=!1}M_(){if(this.F_)throw new N(A.FAILED_PRECONDITION,"The client has already been terminated.")}So(r,n,i,s){return this.M_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.connection.So(r,xb(n,i),s,e,t)).catch(e=>{throw"FirebaseError"===e.name?(e.code===A.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new N(A.UNKNOWN,e.toString())})}Co(r,n,i,s,a){return this.M_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.connection.Co(r,xb(n,i),s,e,t,a)).catch(e=>{throw"FirebaseError"===e.name?(e.code===A.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new N(A.UNKNOWN,e.toString())})}terminate(){this.F_=!0,this.connection.terminate()}}class KE{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.x_=0,this.O_=null,this.N_=!0}B_(){0===this.x_&&(this.L_("Unknown"),this.O_=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.O_=null,this.k_("Backend didn't respond within 10 seconds."),this.L_("Offline"),Promise.resolve())))}q_(e){"Online"===this.state?this.L_("Unknown"):(this.x_++,1<=this.x_&&(this.Q_(),this.k_("Connection failed 1 times. Most recent error: "+e.toString()),this.L_("Offline")))}set(e){this.Q_(),this.x_=0,"Online"===e&&(this.N_=!1),this.L_(e)}L_(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}k_(e){var t=`Could not reach Cloud Firestore backend. ${e}
|
|
15
|
+
This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;this.N_?(km(t),this.N_=!1):C("OnlineStateTracker",t)}Q_(){null!==this.O_&&(this.O_.cancel(),this.O_=null)}}let WE="RemoteStore";class HE{constructor(e,t,r,n,i){this.localStore=e,this.datastore=t,this.asyncQueue=r,this.remoteSyncer={},this.K_=[],this.U_=new Map,this.W_=new Set,this.G_=[],this.z_=i,this.z_.To(e=>{r.enqueueAndForget(async()=>{var e;t0(this)&&(C(WE,"Restarting streams for network reachability change."),(e=this).W_.add(4),await $E(e),e.j_.set("Unknown"),e.W_.delete(4),await GE(e))})}),this.j_=new KE(r,n)}}async function GE(e){if(t0(e))for(var t of e.G_)await t(!0)}async function $E(e){for(var t of e.G_)await t(!1)}function QE(e,t){var r=e;r.U_.has(t.targetId)||(r.U_.set(t.targetId,t),e0(r)?ZE(r):u0(r).c_()&&JE(r,t))}function YE(e,t){var r=e,n=u0(r);r.U_.delete(t),n.c_()&&XE(r,t),0===r.U_.size&&(n.c_()?n.P_():t0(r)&&r.j_.set("Unknown"))}function JE(e,t){var r;e.H_.Ne(t.targetId),(0<t.resumeToken.approximateByteSize()||0<t.snapshotVersion.compareTo(P.min()))&&(r=e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size,t=t.withExpectedCount(r)),u0(e).y_(t)}function XE(e,t){e.H_.Ne(t),u0(e).w_(t)}function ZE(t){t.H_=new bb({getRemoteKeysForTarget:e=>t.remoteSyncer.getRemoteKeysForTarget(e),lt:e=>t.U_.get(e)||null,it:()=>t.datastore.serializer.databaseId}),u0(t).start(),t.j_.B_()}function e0(e){return t0(e)&&!u0(e).u_()&&0<e.U_.size}function t0(e){return 0===e.W_.size}function r0(e){e.H_=void 0}async function n0(e,t,r){if(!dv(t))throw t;e.W_.add(1),await $E(e),e.j_.set("Offline"),r=r||(()=>rE(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{C(WE,"Retrying IndexedDB access"),await r(),e.W_.delete(1),await GE(e)})}function i0(t,r){return r().catch(e=>n0(t,e,r))}async function s0(e){var t,r,n,i,s=e,a=c0(s);let o=0<s.K_.length?s.K_[s.K_.length-1].batchId:bv;for(;t0(i=s)&&i.K_.length<10;)try{let e=await((e,t)=>{let r=e;return r.persistence.runTransaction("Get next mutation batch","readonly",e=>(void 0===t&&(t=bv),r.mutationQueue.getNextMutationBatchAfterBatchId(e,t)))})(s.localStore,o);if(null===e){0===s.K_.length&&a.P_();break}o=e.batchId,t=s,r=e,n=void 0,t.K_.push(r),(n=c0(t)).c_()&&n.S_&&n.b_(r.mutations)}catch(e){await n0(s,e)}a0(s)&&o0(s)}function a0(e){return t0(e)&&!c0(e).u_()&&0<e.K_.length}function o0(e){c0(e).start()}async function l0(e,t){var r=e,n=(r.asyncQueue.verifyOperationInProgress(),C(WE,"RemoteStore received new credentials"),t0(r));r.W_.add(3),await $E(r),n&&r.j_.set("Unknown"),await r.remoteSyncer.handleCredentialChange(t),r.W_.delete(3),await GE(r)}async function h0(e,t){var r=e;t?(r.W_.delete(2),await GE(r)):(r.W_.add(2),await $E(r),r.j_.set("Unknown"))}function u0(t){return t.J_||(t.J_=(e=t.datastore,r=t.asyncQueue,n={xo:(async function(e){e.j_.set("Online")}).bind(null,t),No:(async function(r){r.U_.forEach((e,t)=>{JE(r,e)})}).bind(null,t),Lo:(async function(e,t){r0(e),e0(e)?(e.j_.q_(t),ZE(e)):e.j_.set("Unknown")}).bind(null,t),p_:(async function(t,e,r){if(t.j_.set("Online"),e instanceof yb&&2===e.state&&e.cause)try{var n,i=t,s=e,a=s.cause;for(n of s.targetIds)i.U_.has(n)&&(await i.remoteSyncer.rejectListen(n,a),i.U_.delete(n),i.H_.removeTarget(n))}catch(r){C(WE,"Failed to remove targets %s: %s ",e.targetIds.join(","),r),await n0(t,r)}else if(e instanceof vb?t.H_.We(e):e instanceof _b?t.H_.Ze(e):t.H_.je(e),!r.isEqual(P.min()))try{let e=await rE(t.localStore);0<=r.compareTo(e)&&(l=r,(h=(o=t).H_.ot(l)).targetChanges.forEach((e,t)=>{var r;0<e.resumeToken.approximateByteSize()&&(r=o.U_.get(t))&&o.U_.set(t,r.withResumeToken(e.resumeToken,l))}),h.targetMismatches.forEach((e,t)=>{var r=o.U_.get(e);r&&(o.U_.set(e,r.withResumeToken(K_.EMPTY_BYTE_STRING,r.snapshotVersion)),XE(o,e),r=new tI(r.target,e,t,r.sequenceNumber),JE(o,r))}),await o.remoteSyncer.applyRemoteEvent(h))}catch(e){C(WE,"Failed to raise snapshot:",e),await n0(t,e)}var o,l,h}).bind(null,t)},(i=e).M_(),new jE(r,i.connection,i.authCredentials,i.appCheckCredentials,i.serializer,n)),t.G_.push(async e=>{e?(t.J_.h_(),e0(t)?ZE(t):t.j_.set("Unknown")):(await t.J_.stop(),r0(t))})),t.J_;var e,r,n,i}function c0(t){return t.Y_||(t.Y_=(e=t.datastore,r=t.asyncQueue,n={xo:()=>Promise.resolve(),No:(async function(e){c0(e).C_()}).bind(null,t),Lo:(async function(e,t){if(t&&c0(e).S_){var r=e,n=t;if(ob(t=n.code)&&t!==A.ABORTED){let e=r.K_.shift();c0(r).h_(),await i0(r,()=>r.remoteSyncer.rejectFailedWrite(e.batchId,n)),await s0(r)}await 0}a0(e)&&o0(e)}).bind(null,t),D_:(async function(e){var t,r=c0(e);for(t of e.K_)r.b_(t.mutations)}).bind(null,t),v_:(async function(e,t,r){let n=e.K_.shift(),i=ib.from(n,t,r);await i0(e,()=>e.remoteSyncer.applySuccessfulWrite(i)),await s0(e)}).bind(null,t)},(i=e).M_(),new BE(r,i.connection,i.authCredentials,i.appCheckCredentials,i.serializer,n)),t.G_.push(async e=>{e?(t.Y_.h_(),await s0(t)):(await t.Y_.stop(),0<t.K_.length&&(C(WE,`Stopping write stream with ${t.K_.length} pending writes`),t.K_=[]))})),t.Y_;var e,r,n,i}class d0{constructor(e,t,r,n,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=r,this.op=n,this.removalCallback=i,this.deferred=new Nm,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch(e=>{})}get promise(){return this.deferred.promise}static createAndSchedule(e,t,r,n,i){var s=Date.now()+r,s=new d0(e,t,s,n,i);return s.start(r),s}start(e){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new N(A.CANCELLED,"Operation cancelled"+(e?": "+e:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget(()=>null!==this.timerHandle?(this.clearTimeout(),this.op().then(e=>this.deferred.resolve(e))):Promise.resolve())}clearTimeout(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}}function p0(e,t){if(km("AsyncQueue",t+": "+e),dv(e))return new N(A.UNAVAILABLE,t+": "+e);throw e}class f0{static emptySet(e){return new f0(e.comparator)}constructor(r){this.comparator=r?(e,t)=>r(e,t)||x.comparator(e.key,t.key):(e,t)=>x.comparator(e.key,t.key),this.keyedMap=Tw(),this.sortedSet=new L(this.comparator)}has(e){return null!=this.keyedMap.get(e)}get(e){return this.keyedMap.get(e)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(e){var t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(r){this.sortedSet.inorderTraversal((e,t)=>(r(e),!1))}add(e){var t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))}delete(e){var t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof f0))return!1;if(this.size!==e.size)return!1;for(var r=this.sortedSet.getIterator(),n=e.sortedSet.getIterator();r.hasNext();){let e=r.getNext().key,t=n.getNext().key;if(!e.isEqual(t))return!1}return!0}toString(){let t=[];return this.forEach(e=>{t.push(e.toString())}),0===t.length?"DocumentSet ()":"DocumentSet (\n "+t.join(" \n")+"\n)"}copy(e,t){var r=new f0;return r.comparator=this.comparator,r.keyedMap=e,r.sortedSet=t,r}}class g0{constructor(){this.Z_=new L(x.comparator)}track(e){var t=e.doc.key,r=this.Z_.get(t);!r||0!==e.type&&3===r.type?this.Z_=this.Z_.insert(t,e):3===e.type&&1!==r.type?this.Z_=this.Z_.insert(t,{type:r.type,doc:e.doc}):2===e.type&&2===r.type?this.Z_=this.Z_.insert(t,{type:2,doc:e.doc}):2===e.type&&0===r.type?this.Z_=this.Z_.insert(t,{type:0,doc:e.doc}):1===e.type&&0===r.type?this.Z_=this.Z_.remove(t):1===e.type&&2===r.type?this.Z_=this.Z_.insert(t,{type:1,doc:r.doc}):0===e.type&&1===r.type?this.Z_=this.Z_.insert(t,{type:2,doc:e.doc}):k()}X_(){let r=[];return this.Z_.inorderTraversal((e,t)=>{r.push(t)}),r}}class m0{constructor(e,t,r,n,i,s,a,o,l){this.query=e,this.docs=t,this.oldDocs=r,this.docChanges=n,this.mutatedKeys=i,this.fromCache=s,this.syncStateChanged=a,this.excludesMetadataChanges=o,this.hasCachedResults=l}static fromInitialDocuments(e,t,r,n,i){let s=[];return t.forEach(e=>{s.push({type:0,doc:e})}),new m0(e,t,f0.emptySet(t),s,r,n,!0,!1,i)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.hasCachedResults===e.hasCachedResults&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&fw(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;var t=this.docChanges,r=e.docChanges;if(t.length!==r.length)return!1;for(let n=0;n<t.length;n++)if(t[n].type!==r[n].type||!t[n].doc.isEqual(r[n].doc))return!1;return!0}}class v0{constructor(){this.ea=void 0,this.ta=[]}na(){return this.ta.some(e=>e.ra())}}class _0{constructor(){this.queries=y0(),this.onlineState="Unknown",this.ia=new Set}terminate(){var e,r,t,n;e=this,r=new N(A.ABORTED,"Firestore shutting down"),n=(t=e).queries,t.queries=y0(),n.forEach((e,t)=>{for(let e of t.ta)e.onError(r)})}}function y0(){return new ww(e=>gw(e),fw)}async function w0(t,r){let e=t,n=3;var i=r.query;let s=e.queries.get(i);s?!s.na()&&r.ra()&&(n=2):(s=new v0,n=r.ra()?0:1);try{switch(n){case 0:s.ea=await e.onListen(i,!0);break;case 1:s.ea=await e.onListen(i,!1);break;case 2:await e.onFirstRemoteStoreListen(i)}}catch(t){let e=p0(t,`Initialization of query '${mw(r.query)}' failed`);return void r.onError(e)}e.queries.set(i,s),s.ta.push(r),r.sa(e.onlineState),s.ea&&r.oa(s.ea)&&I0(e)}async function b0(e,t){var r=e,n=t.query;let i=3;var s=r.queries.get(n);if(s){let e=s.ta.indexOf(t);0<=e&&(s.ta.splice(e,1),0===s.ta.length?i=t.ra()?0:1:!s.na()&&t.ra()&&(i=2))}switch(i){case 0:return r.queries.delete(n),r.onUnlisten(n,!0);case 1:return r.queries.delete(n),r.onUnlisten(n,!1);case 2:return r.onLastRemoteStoreUnlisten(n);default:return}}function I0(e){e.ia.forEach(e=>{e.next()})}(_m=_m||{})._a="default",_m.Cache="cache";class T0{constructor(e,t,r){this.query=e,this.aa=t,this.ua=!1,this.ca=null,this.onlineState="Unknown",this.options=r||{}}oa(t){if(!this.options.includeMetadataChanges){let e=[];for(var r of t.docChanges)3!==r.type&&e.push(r);t=new m0(t.query,t.docs,t.oldDocs,e,t.mutatedKeys,t.fromCache,t.syncStateChanged,!0,t.hasCachedResults)}let e=!1;return this.ua?this.la(t)&&(this.aa.next(t),e=!0):this.ha(t,this.onlineState)&&(this.Pa(t),e=!0),this.ca=t,e}onError(e){this.aa.error(e)}sa(e){this.onlineState=e;let t=!1;return this.ca&&!this.ua&&this.ha(this.ca,e)&&(this.Pa(this.ca),t=!0),t}ha(e,t){return!e.fromCache||!this.ra()||(!this.options.Ta||!("Offline"!==t))&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t)}la(e){var t;return 0<e.docChanges.length||(t=this.ca&&this.ca.hasPendingWrites!==e.hasPendingWrites,!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges)}Pa(e){e=m0.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.ua=!0,this.aa.next(e)}ra(){return this.options.source!==_m.Cache}}class E0{constructor(e,t){this.Ia=e,this.byteLength=t}Ea(){return"metadata"in this.Ia}}class C0{constructor(e){this.serializer=e}ps(e){return Mb(this.serializer,e)}ys(e){return e.metadata.exists?Bb(this.serializer,e.document,!1):Py.newNoDocument(this.ps(e.metadata.name),this.ws(e.metadata.readTime))}ws(e){return Pb(e)}}class k0{constructor(e,t,r){this.da=e,this.localStore=t,this.serializer=r,this.queries=[],this.documents=[],this.collectionGroups=new Set,this.progress=S0(e)}Aa(e){this.progress.bytesLoaded+=e.byteLength;let t=this.progress.documentsLoaded;var r;return e.Ia.namedQuery?this.queries.push(e.Ia.namedQuery):e.Ia.documentMetadata?(this.documents.push({metadata:e.Ia.documentMetadata}),e.Ia.documentMetadata.exists||++t,r=D.fromString(e.Ia.documentMetadata.name),this.collectionGroups.add(r.get(r.length-2))):e.Ia.document&&(this.documents[this.documents.length-1].document=e.Ia.document,++t),t!==this.progress.documentsLoaded?(this.progress.documentsLoaded=t,Object.assign({},this.progress)):null}Ra(e){let r=new Map,n=new C0(this.serializer);for(var i of e)if(i.metadata.queries){let e=n.ps(i.metadata.name);for(let t of i.metadata.queries){var s=(r.get(t)||V()).add(e);r.set(t,s)}}return r}async complete(){let e=await(async(r,n,e,t)=>{let i=r,s=V(),a=bw;for(let r of e){let e=n.ps(r.metadata.name),t=(r.document&&(s=s.add(e)),n.ys(r));t.setReadTime(n.ws(r.metadata.readTime)),a=a.insert(e,t)}let o=i.ds.newChangeBuffer({trackRemovals:!0}),l=await sE(i,(r=t,cw(ow(D.fromString("__bundle__/docs/"+r)))));return i.persistence.runTransaction("Apply bundle documents","readwrite",t=>iE(t,o,a).next(e=>(o.apply(t),e)).next(e=>i.Hr.removeMatchingKeysForTargetId(t,l.targetId).next(()=>i.Hr.addMatchingKeys(t,s,l.targetId)).next(()=>i.localDocuments.getLocalViewOfDocuments(t,e.Vs,e.fs)).next(()=>e.Vs)))})(this.localStore,new C0(this.serializer),this.documents,this.da.id),t=this.Ra(this.documents);for(let e of this.queries)await(async(e,r,n=V())=>{let i=await sE(e,cw(uI(r.bundledQuery))),s=e;return s.persistence.runTransaction("Save named query","readwrite",e=>{var t=Pb(r.readTime);return 0<=i.snapshotVersion.compareTo(t)?s.Yr.saveNamedQuery(e,r):(t=i.withResumeToken(K_.EMPTY_BYTE_STRING,t),s.Ts=s.Ts.insert(t.targetId,t),s.Hr.updateTargetData(e,t).next(()=>s.Hr.removeMatchingKeysForTargetId(e,i.targetId)).next(()=>s.Hr.addMatchingKeys(e,n,i.targetId)).next(()=>s.Yr.saveNamedQuery(e,r)))})})(this.localStore,e,t.get(e.name));return this.progress.taskState="Success",{progress:this.progress,Va:this.collectionGroups,ma:e}}}function S0(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class A0{constructor(e){this.key=e}}class N0{constructor(e){this.key=e}}class R0{constructor(e,t){this.query=e,this.fa=t,this.ga=null,this.hasCachedResults=!1,this.current=!1,this.pa=V(),this.mutatedKeys=V(),this.ya=yw(e),this.wa=new f0(this.ya)}get Sa(){return this.fa}ba(e,t){let o=t?t.Da:new g0,l=(t||this).wa,h=(t||this).mutatedKeys,u=l,c=!1,d="F"===this.query.limitType&&l.size===this.query.limit?l.last():null,p="L"===this.query.limitType&&l.size===this.query.limit?l.first():null;if(e.inorderTraversal((e,t)=>{var r=l.get(e),n=vw(this.query,t)?t:null,i=!!r&&this.mutatedKeys.has(r.key),s=!!n&&(n.hasLocalMutations||this.mutatedKeys.has(n.key)&&n.hasCommittedMutations);let a=!1;r&&n?r.data.isEqual(n.data)?i!==s&&(o.track({type:3,doc:n}),a=!0):!this.va(r,n)&&(o.track({type:2,doc:n}),a=!0,d&&0<this.ya(n,d)||p&&this.ya(n,p)<0)&&(c=!0):!r&&n?(o.track({type:0,doc:n}),a=!0):r&&!n&&(o.track({type:1,doc:r}),a=!0,d||p)&&(c=!0),a&&(h=n?(u=u.add(n),s?h.add(e):h.delete(e)):(u=u.delete(e),h.delete(e)))}),null!==this.query.limit)for(;u.size>this.query.limit;){let e="F"===this.query.limitType?u.last():u.first();u=u.delete(e.key),h=h.delete(e.key),o.track({type:1,doc:e})}return{wa:u,Da:o,ls:c,mutatedKeys:h}}va(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,r,n){var i=this.wa,s=(this.wa=e.wa,this.mutatedKeys=e.mutatedKeys,e.Da.X_()),a=(s.sort((e,t)=>{return r=e.type,n=t.type,(i=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return k()}})(r)-i(n)||this.ya(e.doc,t.doc);var r,n,i}),this.Ca(r),n=null!=n&&n,t&&!n?this.Fa():[]),o=0===this.pa.size&&this.current&&!n?1:0,l=o!==this.ga;return this.ga=o,0!==s.length||l?{snapshot:new m0(this.query,e.wa,i,s,e.mutatedKeys,0==o,l,!1,!!r&&0<r.resumeToken.approximateByteSize()),Ma:a}:{Ma:a}}sa(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({wa:this.wa,Da:new g0,mutatedKeys:this.mutatedKeys,ls:!1},!1)):{Ma:[]}}xa(e){return!this.fa.has(e)&&!!this.wa.has(e)&&!this.wa.get(e).hasLocalMutations}Ca(e){e&&(e.addedDocuments.forEach(e=>this.fa=this.fa.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.fa=this.fa.delete(e)),this.current=e.current)}Fa(){if(!this.current)return[];let t=this.pa,r=(this.pa=V(),this.wa.forEach(e=>{this.xa(e.key)&&(this.pa=this.pa.add(e.key))}),[]);return t.forEach(e=>{this.pa.has(e)||r.push(new N0(e))}),this.pa.forEach(e=>{t.has(e)||r.push(new A0(e))}),r}Oa(e){this.fa=e.gs,this.pa=V();var t=this.ba(e.documents);return this.applyChanges(t,!0)}Na(){return m0.fromInitialDocuments(this.query,this.wa,this.mutatedKeys,0===this.ga,this.hasCachedResults)}}let P0="SyncEngine";class D0{constructor(e,t,r){this.query=e,this.targetId=t,this.view=r}}class x0{constructor(e){this.key=e,this.Ba=!1}}class O0{constructor(e,t,r,n,i,s){this.localStore=e,this.remoteStore=t,this.eventManager=r,this.sharedClientState=n,this.currentUser=i,this.maxConcurrentLimboResolutions=s,this.La={},this.ka=new ww(e=>gw(e),fw),this.qa=new Map,this.Qa=new Set,this.$a=new L(x.comparator),this.Ka=new Map,this.Ua=new NT,this.Wa={},this.Ga=new Map,this.za=rT.Un(),this.onlineState="Unknown",this.ja=void 0}get isPrimaryClient(){return!0===this.ja}}async function L0(e,t,r,n){var i=await sE(e.localStore,cw(t)),s=i.targetId,a=e.sharedClientState.addLocalQueryTarget(s,r);let o;return n&&(o=await M0(e,t,s,"current"===a,i.resumeToken)),e.isPrimaryClient&&r&&QE(e.remoteStore,i),o}async function M0(n,e,t,r,i){n.Ha=(e,t,r)=>(async(e,t,r,n)=>{let i=t.view.ba(r);i.ls&&(i=await oE(e.localStore,t.query,!1).then(({documents:e})=>t.view.ba(e,i)));var s=n&&n.targetChanges.get(t.targetId),a=n&&null!=n.targetMismatches.get(t.targetId),s=t.view.applyChanges(i,e.isPrimaryClient,s,a);return H0(e,t.targetId,s.Ma),s.snapshot})(n,e,t,r);var s=await oE(n.localStore,e,!0),a=new R0(e,s.gs),s=a.ba(s.documents),o=mb.createSynthesizedTargetChangeForCurrentChange(t,r&&"Offline"!==n.onlineState,i),s=a.applyChanges(s,n.isPrimaryClient,o),o=(H0(n,t,s.Ma),new D0(e,t,a));return n.ka.set(e,o),n.qa.has(t)?n.qa.get(t).push(e):n.qa.set(t,[e]),s.snapshot}async function F0(t,e,r){var n=Z0(t);try{let t=await((e,i)=>{let s=e,a=Bm.now(),o=i.reduce((e,t)=>e.add(t.key),V()),l,h;return s.persistence.runTransaction("Locally write mutations","readwrite",n=>{let t=bw,r=V();return s.ds.getEntries(n,o).next(e=>{(t=e).forEach((e,t)=>{t.isValidDocument()||(r=r.add(e))})}).next(()=>s.localDocuments.getOverlayedDocuments(n,t)).next(e=>{l=e;var t=[];for(let r of i){let e=((e,r)=>{let n=null;for(var i of e.fieldTransforms){let e=r.data.field(i.field),t=xw(i.transform,e||null);null!=t&&(n=null===n?Ry.empty():n).set(i.field,t)}return n||null})(r,l.get(r.key).overlayedDocument);null!=e&&t.push(new Jw(r.key,e,function i(e){let s=[];return M_(e.fields,(e,r)=>{var n=new Hm([e]);if(Ty(r)){let t=i(r.mapValue).fields;if(0===t.length)s.push(n);else for(let e of t)s.push(n.child(e))}else s.push(n)}),new B_(s)}(e.value.mapValue),Kw.exists(!0)))}return s.mutationQueue.addMutationBatch(n,a,t,i)}).next(e=>{var t=(h=e).applyToLocalDocumentSet(l,r);return s.documentOverlayCache.saveOverlays(n,e.batchId,t)})}).then(()=>({batchId:h.batchId,changes:Ew(l)}))})(n.localStore,e);n.sharedClientState.addPendingMutation(t.batchId);{var i=n;var s=t.batchId;var a=r;let e=i.Wa[i.currentUser.toKey()];e=(e=e||new L(R)).insert(s,a),i.Wa[i.currentUser.toKey()]=e}await $0(n,t.changes),await s0(n.remoteStore)}catch(t){let e=p0(t,"Failed to persist write");r.reject(e)}}async function U0(e,t){let n=e;try{let e=await nE(n.localStore,t);t.targetChanges.forEach((e,t)=>{var r=n.Ka.get(t);r&&(S(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),0<e.addedDocuments.size?r.Ba=!0:0<e.modifiedDocuments.size?S(r.Ba):0<e.removedDocuments.size&&(S(r.Ba),r.Ba=!1))}),await $0(n,e,t)}catch(e){await sv(e)}}function V0(e,i,t){var s=e;if(s.isPrimaryClient&&0===t||!s.isPrimaryClient&&1===t){let n=[];s.ka.forEach((e,t)=>{var r=t.view.sa(i);r.snapshot&&n.push(r.snapshot)});{t=s.eventManager;var a=i;var o=t;o.onlineState=a;let r=!1;o.queries.forEach((e,t)=>{for(let e of t.ta)e.sa(a)&&(r=!0)}),r&&I0(o)}n.length&&s.La.p_(n),s.onlineState=i,s.isPrimaryClient&&s.sharedClientState.setOnlineState(i)}}async function q0(e,t,r){var n=e;try{let e=await((e,n)=>{let i=e;return i.persistence.runTransaction("Reject batch","readwrite-primary",t=>{let r;return i.mutationQueue.lookupMutationBatch(t,n).next(e=>(S(null!==e),r=e.keys(),i.mutationQueue.removeMutationBatch(t,e))).next(()=>i.mutationQueue.performConsistencyCheck(t)).next(()=>i.documentOverlayCache.removeOverlaysForBatchId(t,r,n)).next(()=>i.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t,r)).next(()=>i.localDocuments.getDocuments(t,r))})})(n.localStore,t);z0(n,t,r),B0(n,t),n.sharedClientState.updateMutationState(t,"rejected",r),await $0(n,e)}catch(r){await sv(r)}}async function j0(t,r){let n=t;t0(n.remoteStore)||C(P0,"The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");try{let e=await(e=>{let t=e;return t.persistence.runTransaction("Get highest unacknowledged batch id","readonly",e=>t.mutationQueue.getHighestUnacknowledgedBatchId(e))})(n.localStore);var i;e===bv?r.resolve():((i=n.Ga.get(e)||[]).push(r),n.Ga.set(e,i))}catch(t){let e=p0(t,"Initialization of waitForPendingWrites() operation failed");r.reject(e)}}function B0(e,t){(e.Ga.get(t)||[]).forEach(e=>{e.resolve()}),e.Ga.delete(t)}function z0(e,t,r){var n=e;let i=n.Wa[n.currentUser.toKey()];if(i){let e=i.get(t);e&&(r?e.reject(r):e.resolve(),i=i.remove(t)),n.Wa[n.currentUser.toKey()]=i}}function K0(t,e,r=null){t.sharedClientState.removeLocalQueryTarget(e);for(var n of t.qa.get(e))t.ka.delete(n),r&&t.La.Ja(n,r);t.qa.delete(e),t.isPrimaryClient&&t.Ua.br(e).forEach(e=>{t.Ua.containsKey(e)||W0(t,e)})}function W0(e,t){e.Qa.delete(t.path.canonicalString());var r=e.$a.get(t);null!==r&&(YE(e.remoteStore,r),e.$a=e.$a.remove(t),e.Ka.delete(r),G0(e))}function H0(e,t,r){for(var n of r)n instanceof A0?(e.Ua.addReference(n.key,t),i=e,s=n,o=a=void 0,a=s.key,o=a.path.canonicalString(),i.$a.get(a)||i.Qa.has(o)||(C(P0,"New document in limbo: "+a),i.Qa.add(o),G0(i))):n instanceof N0?(C(P0,"Document no longer in limbo: "+n.key),e.Ua.removeReference(n.key,t),e.Ua.containsKey(n.key)||W0(e,n.key)):k();var i,s,a,o}function G0(e){for(;0<e.Qa.size&&e.$a.size<e.maxConcurrentLimboResolutions;){var t=e.Qa.values().next().value,t=(e.Qa.delete(t),new x(D.fromString(t))),r=e.za.next();e.Ka.set(r,new x0(t)),e.$a=e.$a.insert(t,r),QE(e.remoteStore,new tI(cw(ow(t.path)),r,"TargetPurposeLimboResolution",wv.ae))}}async function $0(e,t,i){let s=e,a=[],o=[],r=[];if(!s.ka.isEmpty()){s.ka.forEach((e,n)=>{r.push(s.Ha(n,t,i).then(t=>{var r;if((t||i)&&s.isPrimaryClient){let e=t?!t.fromCache:null==(r=null==i?void 0:i.targetChanges.get(n.targetId))?void 0:r.current;s.sharedClientState.updateQueryState(n.targetId,e?"current":"not-current")}if(t){a.push(t);let e=GT.Yi(n.targetId,t);o.push(e)}}))}),await Promise.all(r),s.La.p_(a);{var n=s.localStore,l=o;let i=n;try{await i.persistence.runTransaction("notifyLocalViewChanges","readwrite",r=>O.forEach(l,t=>O.forEach(t.Hi,e=>i.persistence.referenceDelegate.addReference(r,t.targetId,e)).next(()=>O.forEach(t.Ji,e=>i.persistence.referenceDelegate.removeReference(r,t.targetId,e)))))}catch(n){if(!dv(n))throw n;C(YT,"Failed to update sequence numbers: "+n)}for(let e of l){let n=e.targetId;if(!e.fromCache){let e=i.Ts.get(n),t=e.snapshotVersion,r=e.withLastLimboFreeSnapshotVersion(t);i.Ts=i.Ts.insert(n,r)}}}}}async function Q0(e,t,r,n){var i=e,s=await((e,r)=>{let n=e,i=n.mutationQueue;return n.persistence.runTransaction("Lookup mutation documents","readonly",t=>i.Ln(t,r).next(e=>e?n.localDocuments.getDocuments(t,e):O.resolve(null)))})(i.localStore,t);null!==s?("pending"===r?await s0(i.remoteStore):"acknowledged"===r||"rejected"===r?(z0(i,t,n||null),B0(i,t),i.localStore.mutationQueue.qn(t)):k(),await $0(i,s)):C(P0,"Cannot apply mutation batch with id: "+t)}async function Y0(r,e){var n,i,s,a=r,o=[],l=[];for(let r of e){let t,e=a.qa.get(r);if(e&&0!==e.length){t=await sE(a.localStore,cw(e[0]));for(let r of e){let e=a.ka.get(r),t=(n=e,s=i=void 0,s=await oE((i=a).localStore,n.query,!0),s=n.view.Oa(s),i.isPrimaryClient&&H0(i,n.targetId,s.Ma),await s);t.snapshot&&l.push(t.snapshot)}}else{let e=await lE(a.localStore,r);t=await sE(a.localStore,e),await M0(a,J0(e),r,!1,t.resumeToken)}o.push(t)}return a.La.p_(l),o}function J0(e){return aw(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,"F",e.startAt,e.endAt)}function X0(e){var t=e;return t.remoteStore.remoteSyncer.applyRemoteEvent=U0.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=(function(e,t){let n=e,r=n.Ka.get(t);if(r&&r.Ba)return V().add(r.key);{let r=V(),e=n.qa.get(t);if(e)for(let t of e){let e=n.ka.get(t);r=r.unionWith(e.view.Sa)}return r}}).bind(null,t),t.remoteStore.remoteSyncer.rejectListen=(async function(e,n,t){let i=e,r=(i.sharedClientState.updateQueryState(n,"rejected",t),i.Ka.get(n)),s=r&&r.key;if(s){let e=new L(x.comparator),t=(e=e.insert(s,Py.newNoDocument(s,P.min())),V().add(s)),r=new gb(P.min(),new Map,new L(R),e,t);await U0(i,r),i.$a=i.$a.remove(s),i.Ka.delete(n),G0(i)}else await aE(i.localStore,n,!1).then(()=>K0(i,n,t)).catch(sv)}).bind(null,t),t.La.p_=(function(r,e){var n=r;let i=!1;for(let r of e){let e=r.query,t=n.queries.get(e);if(t){for(let e of t.ta)e.oa(r)&&(i=!0);t.ea=r}}i&&I0(n)}).bind(null,t.eventManager),t.La.Ja=(function(e,t,r){var n=e,i=n.queries.get(t);if(i)for(let e of i.ta)e.onError(r);n.queries.delete(t)}).bind(null,t.eventManager),t}function Z0(e){var t=e;return t.remoteStore.remoteSyncer.applySuccessfulWrite=(async function(e,t){var r=e,n=t.batch.batchId;try{let e=await tE(r.localStore,t);z0(r,n,null),B0(r,n),r.sharedClientState.updateMutationState(n,"acknowledged"),await $0(r,e)}catch(e){await sv(e)}}).bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=q0.bind(null,t),t}function eC(e,t,r){let n=e;(async(e,r,n)=>{try{var i=await r.getMetadata();if(await((e,t)=>{let r=e,n=Pb(t.createTime);return r.persistence.runTransaction("hasNewerBundle","readonly",e=>r.Yr.getBundleMetadata(e,t.id)).then(e=>!!e&&0<=e.createTime.compareTo(n))})(e.localStore,i))return await r.close(),n._completeWith({taskState:"Success",documentsLoaded:i.totalDocuments,bytesLoaded:i.totalBytes,totalDocuments:i.totalDocuments,totalBytes:i.totalBytes}),Promise.resolve(new Set);n._updateProgress(S0(i));var s=new k0(i,e.localStore,r.serializer);let t=await r.Ya();for(;t;){let e=await s.Aa(t);e&&n._updateProgress(e),t=await r.Ya()}var a=await s.complete();return await $0(e,a.ma,void 0),await((e,t)=>{let r=e;return r.persistence.runTransaction("Save bundle","readwrite",e=>r.Yr.saveBundleMetadata(e,t))})(e.localStore,i),n._completeWith(a.progress),Promise.resolve(a.Va)}catch(e){return Sm(P0,"Loading bundle failed with "+e),n._failWith(e),Promise.resolve(new Set)}})(n,t,r).then(e=>{n.sharedClientState.notifyBundleLoaded(e)})}class tC{constructor(){this.kind="memory",this.synchronizeTabs=!1}async initialize(e){this.serializer=FE(e.databaseInfo.databaseId),this.sharedClientState=this.Za(e),this.persistence=this.Xa(e),await this.persistence.start(),this.localStore=this.eu(e),this.gcScheduler=this.tu(e,this.localStore),this.indexBackfillerScheduler=this.nu(e,this.localStore)}tu(e,t){return null}nu(e,t){return null}eu(e){return ZT(this.persistence,new QT,e.initialUser,this.serializer)}Xa(e){return new LT(FT.ri,this.serializer)}Za(e){return new EE}async terminate(){var e;null!=(e=this.gcScheduler)&&e.stop(),null!=(e=this.indexBackfillerScheduler)&&e.stop(),this.sharedClientState.shutdown(),await this.persistence.shutdown()}}tC.provider={build:()=>new tC};class rC extends tC{constructor(e){super(),this.cacheSizeBytes=e}tu(e,t){S(this.persistence.referenceDelegate instanceof UT);var r=this.persistence.referenceDelegate.garbageCollector;return new uT(r,e.asyncQueue,t)}Xa(e){let t=void 0!==this.cacheSizeBytes?$I.withCacheSize(this.cacheSizeBytes):$I.DEFAULT;return new LT(e=>UT.ri(e,t),this.serializer)}}class nC extends tC{constructor(e,t,r){super(),this.ru=e,this.cacheSizeBytes=t,this.forceOwnership=r,this.kind="persistent",this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.ru.initialize(this,e),await Z0(this.ru.syncEngine),await s0(this.ru.remoteStore),await this.persistence.Ci(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve()))}eu(e){return ZT(this.persistence,new QT,e.initialUser,this.serializer)}tu(e,t){var r=this.persistence.referenceDelegate.garbageCollector;return new uT(r,e.asyncQueue,t)}nu(e,t){var r=new yv(t,this.persistence);return new _v(e.asyncQueue,r)}Xa(e){var t=HT(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),r=void 0!==this.cacheSizeBytes?$I.withCacheSize(this.cacheSizeBytes):$I.DEFAULT;return new zT(this.synchronizeTabs,t,e.clientId,r,e.asyncQueue,LE(),ME(),this.serializer,this.sharedClientState,!!this.forceOwnership)}Za(e){return new EE}}class iC extends nC{constructor(e,t){super(e,t,!1),this.ru=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);var t=this.ru.syncEngine;this.sharedClientState instanceof TE&&(this.sharedClientState.syncEngine={uo:Q0.bind(null,t),co:(async function(e,r,n,t){var i=e;if(i.ja)C(P0,"Ignoring unexpected query state notification.");else{var s=i.qa.get(r);if(s&&0<s.length)switch(n){case"current":case"not-current":{let e=await hE(i.localStore,_w(s[0])),t=gb.createSynthesizedRemoteEventForCurrentChange(r,"current"===n,K_.EMPTY_BYTE_STRING);await $0(i,e,t);break}case"rejected":await aE(i.localStore,r,!0),K0(i,r,t);break;default:k()}}}).bind(null,t),lo:(async function(e,t,n){let i=X0(e);if(i.ja){for(let r of t)if(i.qa.has(r)&&i.sharedClientState.isActiveQueryTarget(r))C(P0,"Adding an already active target "+r);else{let e=await lE(i.localStore,r),t=await sE(i.localStore,e);await M0(i,J0(e),t.targetId,!1,t.resumeToken),QE(i.remoteStore,t)}for(let r of n)i.qa.has(r)&&await aE(i.localStore,r,!1).then(()=>{YE(i.remoteStore,r),K0(i,r)}).catch(sv)}}).bind(null,t),zi:(function(e){return e.localStore.persistence.zi()}).bind(null,t),ao:(async function(e,t){let r=e;return hE(r.localStore,t).then(e=>$0(r,e))}).bind(null,t)},await this.sharedClientState.start()),await this.persistence.Ci(async e=>{{var t=this.ru.syncEngine,s=e;let i=t;if(X0(i),Z0(i),!0===s&&!0!==i.ja){let e=i.sharedClientState.getAllActiveQueryTargets(),t=await Y0(i,e.toArray());i.ja=!0,await h0(i.remoteStore,!0);for(let e of t)QE(i.remoteStore,e)}else if(!1===s&&!1!==i.ja){let r=[],n=Promise.resolve();i.qa.forEach((e,t)=>{i.sharedClientState.isLocalQueryTarget(t)?r.push(t):n=n.then(()=>(K0(i,t),aE(i.localStore,t,!0))),YE(i.remoteStore,t)}),await n,await Y0(i,r);{s=i;let r=s;r.Ka.forEach((e,t)=>{YE(r.remoteStore,t)}),r.Ua.Dr(),r.Ka=new Map,r.$a=new L(x.comparator)}i.ja=!1,await h0(i.remoteStore,!1)}}await 0,this.gcScheduler&&(e&&!this.gcScheduler.started?this.gcScheduler.start():e||this.gcScheduler.stop()),this.indexBackfillerScheduler&&(e&&!this.indexBackfillerScheduler.started?this.indexBackfillerScheduler.start():e||this.indexBackfillerScheduler.stop())})}Za(e){var t,r=LE();if(TE.D(r))return t=HT(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),new TE(r,e.asyncQueue,t,e.clientId,e.initialUser);throw new N(A.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.")}}class sC{async initialize(e,t){this.localStore||(this.localStore=e.localStore,this.sharedClientState=e.sharedClientState,this.datastore=this.createDatastore(t),this.remoteStore=this.createRemoteStore(t),this.eventManager=this.createEventManager(t),this.syncEngine=this.createSyncEngine(t,!e.synchronizeTabs),this.sharedClientState.onlineStateHandler=e=>V0(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=(async function(e,t){var r,n,i=e;if(!i.currentUser.isEqual(t)){C(P0,"User change. New user:",t.toKey());let e=await eE(i.localStore,t);i.currentUser=t,n="'waitForPendingWrites' promise is rejected due to a user change.",(r=i).Ga.forEach(e=>{e.forEach(e=>{e.reject(new N(A.CANCELLED,n))})}),r.Ga.clear(),i.sharedClientState.handleUserChange(t,e.removedBatchIds,e.addedBatchIds),await $0(i,e.Rs)}}).bind(null,this.syncEngine),await h0(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new _0}createDatastore(e){var t,r,n,i=FE(e.databaseInfo.databaseId),s=(t=e.databaseInfo,new OE(t));return t=e.authCredentials,e=e.appCheckCredentials,r=s,n=i,new zE(t,e,r,n)}createRemoteStore(e){return t=this.localStore,r=this.datastore,e=e.asyncQueue,n=e=>V0(this.syncEngine,e,0),i=new(SE.D()?SE:CE),new HE(t,r,e,n,i);var t,r,n,i}createSyncEngine(e,t){return r=this.localStore,n=this.remoteStore,i=this.eventManager,s=this.sharedClientState,a=e.initialUser,e=e.maxConcurrentLimboResolutions,t=t,o=new O0(r,n,i,s,a,e),t&&(o.ja=!0),o;var r,n,i,s,a,o}async terminate(){var e,t;e=this.remoteStore,t=e,C(WE,"RemoteStore shutting down."),t.W_.add(5),await $E(t),t.z_.shutdown(),await!t.j_.set("Unknown"),null!=(t=this.datastore)&&t.terminate(),null!=(t=this.eventManager)&&t.terminate()}}function aC(t,r=10240){let n=0;return{async read(){var e;return n<t.byteLength?(e={value:t.slice(n,n+r),done:!1},n+=r,e):{done:!0}},async cancel(){},releaseLock(){},closed:Promise.resolve()}}sC.provider={build:()=>new sC};class oC{constructor(e){this.observer=e,this.muted=!1}next(e){this.muted||this.observer.next&&this.iu(this.observer.next,e)}error(e){this.muted||(this.observer.error?this.iu(this.observer.error,e):km("Uncaught Error in snapshot listener:",e.toString()))}su(){this.muted=!0}iu(e,t){setTimeout(()=>{this.muted||e(t)},0)}}class lC{constructor(e,t){this.ou=e,this.serializer=t,this.metadata=new Nm,this.buffer=new Uint8Array,this._u=new TextDecoder("utf-8"),this.au().then(e=>{e&&e.Ea()?this.metadata.resolve(e.Ia.metadata):this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is
|
|
16
|
+
`+JSON.stringify(null==e?void 0:e.Ia)))},e=>this.metadata.reject(e))}close(){return this.ou.cancel()}async getMetadata(){return this.metadata.promise}async Ya(){return await this.getMetadata(),this.au()}async au(){var e,t,r=await this.uu();return null===r?null:(t=this._u.decode(r),e=Number(t),isNaN(e)&&this.cu(`length string (${t}) is not valid number`),t=await this.lu(e),new E0(JSON.parse(t),r.length+e))}hu(){return this.buffer.findIndex(e=>e==="{".charCodeAt(0))}async uu(){for(;this.hu()<0&&!await this.Pu(););var e,t;return 0===this.buffer.length?null:((e=this.hu())<0&&this.cu("Reached the end of bundle when a length string is expected."),t=this.buffer.slice(0,e),this.buffer=this.buffer.slice(e),t)}async lu(e){for(;this.buffer.length<e;)await this.Pu()&&this.cu("Reached the end of bundle when more is expected.");var t=this._u.decode(this.buffer.slice(0,e));return this.buffer=this.buffer.slice(e),t}cu(e){throw this.ou.cancel(),new Error("Invalid bundle format: "+e)}async Pu(){var e,t=await this.ou.read();return t.done||((e=new Uint8Array(this.buffer.length+t.value.length)).set(this.buffer),e.set(t.value,this.buffer.length),this.buffer=e),t.done}}class hC{constructor(e){this.datastore=e,this.readVersions=new Map,this.mutations=[],this.committed=!1,this.lastTransactionError=null,this.writtenDocs=new Set}async lookup(e){if(this.ensureCommitNotCalled(),0<this.mutations.length)throw this.lastTransactionError=new N(A.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes."),this.lastTransactionError;var t=await(async(e,t)=>{let l=e,r={documents:t.map(e=>Lb(l.serializer,e))},n=await l.Co("BatchGetDocuments",l.serializer.databaseId,D.emptyPath(),r,t.length),h=new Map,i=(n.forEach(e=>{t=l.serializer;var t,r,n,i,s,a,o="found"in(e=e)?(r=t,S(!!(n=e).found),n.found.name,n.found.updateTime,i=Mb(r,n.found.name),s=Pb(n.found.updateTime),o=n.found.createTime?Pb(n.found.createTime):P.min(),a=new Ry({mapValue:{fields:n.found.fields}}),Py.newFoundDocument(i,s,o,a)):"missing"in e?(r=t,S(!!(n=e).missing),S(!!n.readTime),i=Mb(r,n.missing),s=Pb(n.readTime),Py.newNoDocument(i,s)):k();h.set(o.key.toString(),o)}),[]);return t.forEach(e=>{var t=h.get(e.toString());S(!!t),i.push(t)}),i})(this.datastore,e);return t.forEach(e=>this.recordVersion(e)),t}set(e,t){this.write(t.toMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}update(e,t){try{this.write(t.toMutation(e,this.preconditionForUpdate(e)))}catch(e){this.lastTransactionError=e}this.writtenDocs.add(e.toString())}delete(e){this.write(new tb(e,this.precondition(e))),this.writtenDocs.add(e.toString())}async commit(){if(this.ensureCommitNotCalled(),this.lastTransactionError)throw this.lastTransactionError;let t=this.readVersions;this.mutations.forEach(e=>{t.delete(e.key.toString())}),t.forEach((e,t)=>{var r=x.fromPath(t);this.mutations.push(new rb(r,this.precondition(r)))});{var r=this.datastore,n=this.mutations;let t=r,e={writes:n.map(e=>zb(t.serializer,e))};await t.So("Commit",t.serializer.databaseId,D.emptyPath(),e)}await 0,this.committed=!0}recordVersion(e){let t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw k();t=P.min()}var r=this.readVersions.get(e.key.toString());if(r){if(!t.isEqual(r))throw new N(A.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),t)}precondition(e){var t=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&t?t.isEqual(P.min())?Kw.exists(!1):Kw.updateTime(t):Kw.none()}preconditionForUpdate(e){var t=this.readVersions.get(e.toString());if(this.writtenDocs.has(e.toString())||!t)return Kw.exists(!0);if(t.isEqual(P.min()))throw new N(A.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return Kw.updateTime(t)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}class uC{constructor(e,t,r,n,i){this.asyncQueue=e,this.datastore=t,this.options=r,this.updateFunction=n,this.deferred=i,this.Tu=r.maxAttempts,this.a_=new UE(this.asyncQueue,"transaction_retry")}Iu(){--this.Tu,this.Eu()}Eu(){this.a_.Xo(async()=>{let t=new hC(this.datastore),e=this.du(t);e&&e.then(e=>{this.asyncQueue.enqueueAndForget(()=>t.commit().then(()=>{this.deferred.resolve(e)}).catch(e=>{this.Au(e)}))}).catch(e=>{this.Au(e)})})}du(e){try{var t=this.updateFunction(e);return!Iv(t)&&t.catch&&t.then?t:(this.deferred.reject(Error("Transaction callback must return a Promise")),null)}catch(e){return this.deferred.reject(e),null}}Au(e){0<this.Tu&&this.Ru(e)?(--this.Tu,this.asyncQueue.enqueueAndForget(()=>(this.Eu(),Promise.resolve()))):this.deferred.reject(e)}Ru(e){var t;return"FirebaseError"===e.name&&("aborted"===(t=e.code)||"failed-precondition"===t||"already-exists"===t||!ob(t))}}let cC="FirestoreClient";class dC{constructor(e,t,r,n,i){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=r,this.databaseInfo=n,this.user=Im.UNAUTHENTICATED,this.clientId=Um.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=i,this.authCredentials.start(r,async e=>{C(cC,"Received user=",e.uid),await this.authCredentialListener(e),this.user=e}),this.appCheckCredentials.start(r,e=>(C(cC,"Received new app check token=",e),this.appCheckCredentialListener(e,this.user)))}get configuration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}terminate(){this.asyncQueue.enterRestrictedMode();let r=new Nm;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async()=>{try{this._onlineComponents&&await this._onlineComponents.terminate(),this._offlineComponents&&await this._offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),r.resolve()}catch(e){var t=p0(e,"Failed to shutdown persistence");r.reject(t)}}),r.promise}}async function pC(e,t){e.asyncQueue.verifyOperationInProgress(),C(cC,"Initializing OfflineComponentProvider");var r=e.configuration;await t.initialize(r);let n=r.initialUser;e.setCredentialChangeListener(async e=>{n.isEqual(e)||(await eE(t.localStore,e),n=e)}),t.persistence.setDatabaseDeletedListener(()=>e.terminate()),e._offlineComponents=t}async function fC(e,r){e.asyncQueue.verifyOperationInProgress();var t=await gC(e);C(cC,"Initializing OnlineComponentProvider"),await r.initialize(t,e.configuration),e.setCredentialChangeListener(e=>l0(r.remoteStore,e)),e.setAppCheckTokenChangeListener((e,t)=>l0(r.remoteStore,t)),e._onlineComponents=r}async function gC(t){if(!t._offlineComponents)if(t._uninitializedComponentsProvider){C(cC,"Using user provided OfflineComponentProvider");try{await pC(t,t._uninitializedComponentsProvider._offline)}catch(e){var r=e;if(!("FirebaseError"===(n=r).name?n.code===A.FAILED_PRECONDITION||n.code===A.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&n instanceof DOMException)||22===n.code||20===n.code||11===n.code))throw r;Sm("Error using user provided cache. Falling back to memory cache: "+r),await pC(t,new tC)}}else C(cC,"Using default OfflineComponentProvider"),await pC(t,new rC(void 0));var n;return t._offlineComponents}async function mC(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(C(cC,"Using user provided OnlineComponentProvider"),await fC(e,e._uninitializedComponentsProvider._online)):(C(cC,"Using default OnlineComponentProvider"),await fC(e,new sC))),e._onlineComponents}function vC(e){return gC(e).then(e=>e.persistence)}function _C(e){return gC(e).then(e=>e.localStore)}function yC(e){return mC(e).then(e=>e.remoteStore)}function wC(e){return mC(e).then(e=>e.syncEngine)}async function bC(e){var t=await mC(e),r=t.eventManager;return r.onListen=(async function(e,t,r=!0){var n=X0(e);let i;var s=n.ka.get(t);return i=s?(n.sharedClientState.addLocalQueryTarget(s.targetId),s.view.Na()):await L0(n,t,r,!0)}).bind(null,t.syncEngine),r.onUnlisten=(async function(e,t,r){let n=e,i=n.ka.get(t),s=n.qa.get(i.targetId);1<s.length?(n.qa.set(i.targetId,s.filter(e=>!fw(e,t))),n.ka.delete(t)):n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(i.targetId),n.sharedClientState.isActiveQueryTarget(i.targetId)||await aE(n.localStore,i.targetId,!1).then(()=>{n.sharedClientState.clearQueryState(i.targetId),r&&YE(n.remoteStore,i.targetId),K0(n,i.targetId)}).catch(sv)):(K0(n,i.targetId),await aE(n.localStore,i.targetId,!0))}).bind(null,t.syncEngine),r.onFirstRemoteStoreListen=(async function(e,t){await L0(X0(e),t,!0,!1)}).bind(null,t.syncEngine),r.onLastRemoteStoreUnlisten=(async function(e,t){var r=e,n=r.ka.get(t),i=r.qa.get(n.targetId);r.isPrimaryClient&&1===i.length&&(r.sharedClientState.removeLocalQueryTarget(n.targetId),YE(r.remoteStore,n.targetId))}).bind(null,t.syncEngine),r}function IC(r){return r.asyncQueue.enqueue(async()=>{var e=await vC(r),t=await yC(r);return e.setNetworkEnabled(!1),(async e=>{var t=e;t.W_.add(0),await $E(t),t.j_.set("Offline")})(t)})}function TC(e,t){let r=new Nm;return e.asyncQueue.enqueueAndForget(async()=>(async(e,t,r)=>{try{var n=await((e,t)=>{let r=e;return r.persistence.runTransaction("read document","readonly",e=>r.localDocuments.getDocument(e,t))})(e,t);n.isFoundDocument()?r.resolve(n):n.isNoDocument()?r.resolve(null):r.reject(new N(A.UNAVAILABLE,"Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)"))}catch(e){n=p0(e,`Failed to get document '${t} from cache`);r.reject(n)}})(await _C(e),t,r)),r.promise}function EC(e,t,h={}){let u=new Nm;return e.asyncQueue.enqueueAndForget(async()=>{{var i=await bC(e),s=e.asyncQueue,a=t,o=h,l=u;let r=new oC({next:e=>{r.su(),s.enqueueAndForget(()=>b0(i,n));var t=e.docs.has(a);!t&&e.fromCache?l.reject(new N(A.UNAVAILABLE,"Failed to get document because the client is offline.")):t&&e.fromCache&&o&&"server"===o.source?l.reject(new N(A.UNAVAILABLE,'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')):l.resolve(e)},error:e=>l.reject(e)}),n=new T0(ow(a.path),r,{includeMetadataChanges:!0,Ta:!0});return w0(i,n)}}),u.promise}function CC(e,t){let r=new Nm;return e.asyncQueue.enqueueAndForget(async()=>(async(e,t,r)=>{try{var n=await oE(e,t,!0),i=new R0(t,n.gs),s=i.ba(n.documents),a=i.applyChanges(s,!1);r.resolve(a.snapshot)}catch(e){n=p0(e,`Failed to execute query '${t} against cache`);r.reject(n)}})(await _C(e),t,r)),r.promise}function kC(o,l,h={}){let u=new Nm;return o.asyncQueue.enqueueAndForget(async()=>{{var n=await bC(o),i=o.asyncQueue,e=l,s=h,a=u;let t=new oC({next:e=>{t.su(),i.enqueueAndForget(()=>b0(n,r)),e.fromCache&&"server"===s.source?a.reject(new N(A.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')):a.resolve(e)},error:e=>a.reject(e)}),r=new T0(e,t,{includeMetadataChanges:!0,Ta:!0});return w0(n,r)}}),u.promise}function SC(r,e){let n=new oC(e);return r.asyncQueue.enqueueAndForget(async()=>{return e=await bC(r),t=n,e.ia.add(t),void t.next();var e,t}),()=>{n.su(),r.asyncQueue.enqueueAndForget(async()=>{var e,t;e=await bC(r),t=n,e.ia.delete(t)})}}function AC(e,t,r,n){r=r,t=FE(t),s="string"==typeof r?hb().encode(r):r,r=((e,t)=>{if(e instanceof Uint8Array)return aC(e,t);if(e instanceof ArrayBuffer)return aC(new Uint8Array(e),t);if(e instanceof ReadableStream)return e.getReader();throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream")})(s),t=t;let i=new lC(r,t);var s;e.asyncQueue.enqueueAndForget(async()=>{eC(await wC(e),i,n)})}function NC(n,i){return n.asyncQueue.enqueue(async()=>{{var e=await _C(n),r=i;let t=e;return t.persistence.runTransaction("Get named query","readonly",e=>t.Yr.getNamedQuery(e,r))}})}function RC(e){var t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t}let PC=new Map;function DC(e,t,r){if(!r)throw new N(A.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function xC(e,t,r,n){if(!0===t&&!0===n)throw new N(A.INVALID_ARGUMENT,e+` and ${r} cannot be used together.`)}function OC(e){if(!x.isDocumentKey(e))throw new N(A.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function LC(e){if(x.isDocumentKey(e))throw new N(A.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function MC(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":k()}function q(e,t){if((e="_delegate"in e?e._delegate:e)instanceof t)return e;if(t.name===e.constructor.name)throw new N(A.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");var r=MC(e);throw new N(A.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: `+r)}function FC(e,t){if(t<=0)throw new N(A.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}let UC="firestore.googleapis.com";class VC{constructor(e){var t;if(void 0===e.host){if(void 0!==e.ssl)throw new N(A.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=UC,this.ssl=!0}else this.host=e.host,this.ssl=null==(t=e.ssl)||t;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new N(A.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}xC("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:void 0===e.experimentalAutoDetectLongPolling?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=RC(null!=(t=e.experimentalLongPollingOptions)?t:{});var r=this.experimentalLongPollingOptions;if(void 0!==r.timeoutSeconds){if(isNaN(r.timeoutSeconds))throw new N(A.INVALID_ARGUMENT,`invalid long polling timeout: ${r.timeoutSeconds} (must not be NaN)`);if(r.timeoutSeconds<5)throw new N(A.INVALID_ARGUMENT,`invalid long polling timeout: ${r.timeoutSeconds} (minimum allowed value is 5)`);if(30<r.timeoutSeconds)throw new N(A.INVALID_ARGUMENT,`invalid long polling timeout: ${r.timeoutSeconds} (maximum allowed value is 30)`)}this.useFetchStreams=!!e.useFetchStreams}isEqual(e){return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&(t=this.experimentalLongPollingOptions,r=e.experimentalLongPollingOptions,t.timeoutSeconds===r.timeoutSeconds)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams;var t,r}}class qC{constructor(e,t,r,n){this._authCredentials=e,this._appCheckCredentials=t,this._databaseId=r,this._app=n,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new VC({}),this._settingsFrozen=!1,this._terminateTask="notTerminated"}get app(){if(this._app)return this._app;throw new N(A.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available")}get _initialized(){return this._settingsFrozen}get _terminated(){return"notTerminated"!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new N(A.FAILED_PRECONDITION,"Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");this._settings=new VC(e),void 0!==e.credentials&&(this._authCredentials=(e=>{if(!e)return new Pm;switch(e.type){case"firstParty":return new Lm(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new N(A.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}})(e.credentials))}_getSettings(){return this._settings}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return"notTerminated"===this._terminateTask&&(this._terminateTask=this._terminate()),this._terminateTask}async _restart(){"notTerminated"===this._terminateTask?await this._terminate():this._terminateTask="notTerminated"}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return e=this,(t=PC.get(e))&&(C("ComponentProvider","Removing Datastore"),PC.delete(e),t.terminate()),Promise.resolve();var e,t}}class jC{constructor(e,t,r){this.converter=t,this._query=r,this.type="query",this.firestore=e}withConverter(e){return new jC(this.firestore,e,this._query)}}class BC{constructor(e,t,r){this.converter=t,this._key=r,this.type="document",this.firestore=e}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new zC(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new BC(this.firestore,e,this._key)}}class zC extends jC{constructor(e,t,r){super(e,t,ow(r)),this._path=r,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){var e=this._path.popLast();return e.isEmpty()?null:new BC(this.firestore,null,new x(e))}withConverter(e){return new zC(this.firestore,e,this._path)}}function KC(e,t,...r){var n;if(e=w(e),DC("collection","path",t),e instanceof qC)return LC(n=D.fromString(t,...r)),new zC(e,null,n);if(e instanceof BC||e instanceof zC)return LC(n=e._path.child(D.fromString(t,...r))),new zC(e.firestore,null,n);throw new N(A.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore")}function WC(e,t,...r){var n;if(e=w(e),DC("doc","path",t=1===arguments.length?Um.newId():t),e instanceof qC)return OC(n=D.fromString(t,...r)),new BC(e,null,new x(n));if(e instanceof BC||e instanceof zC)return OC(n=e._path.child(D.fromString(t,...r))),new BC(e.firestore,e instanceof zC?e.converter:null,new x(n));throw new N(A.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore")}function HC(e,t){return e=w(e),t=w(t),(e instanceof BC||e instanceof zC)&&(t instanceof BC||t instanceof zC)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter}function GC(e,t){return e=w(e),t=w(t),e instanceof jC&&t instanceof jC&&e.firestore===t.firestore&&fw(e._query,t._query)&&e.converter===t.converter}let $C="AsyncQueue";class QC{constructor(e=Promise.resolve()){this.Vu=[],this.mu=!1,this.fu=[],this.gu=null,this.pu=!1,this.yu=!1,this.wu=[],this.a_=new UE(this,"async_queue_retry"),this.Su=()=>{var e=ME();e&&C($C,"Visibility state changed to "+e.visibilityState),this.a_.t_()},this.bu=e;var t=ME();t&&"function"==typeof t.addEventListener&&t.addEventListener("visibilitychange",this.Su)}get isShuttingDown(){return this.mu}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.Du(),this.vu(e)}enterRestrictedMode(e){var t;this.mu||(this.mu=!0,this.yu=e||!1,(t=ME())&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.Su))}enqueue(e){if(this.Du(),this.mu)return new Promise(()=>{});let t=new Nm;return this.vu(()=>this.mu&&this.yu?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.Vu.push(e),this.Cu()))}async Cu(){if(0!==this.Vu.length){try{await this.Vu[0](),this.Vu.shift(),this.a_.reset()}catch(e){if(!dv(e))throw e;C($C,"Operation failed with retryable error: "+e)}0<this.Vu.length&&this.a_.Xo(()=>this.Cu())}}vu(e){var t=this.bu.then(()=>(this.pu=!0,e().catch(e=>{throw this.gu=e,this.pu=!1,km("INTERNAL UNHANDLED ERROR: ",(e=>{let t=e.message||"";return t=e.stack?e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack:t})(e)),e}).then(e=>(this.pu=!1,e))));return this.bu=t}enqueueAfterDelay(e,t,r){this.Du(),-1<this.wu.indexOf(e)&&(t=0);var n=d0.createAndSchedule(this,e,t,r,e=>this.Fu(e));return this.fu.push(n),n}Du(){this.gu&&k()}verifyOperationInProgress(){}async Mu(){for(var e;await(e=this.bu),e!==this.bu;);}xu(e){for(var t of this.fu)if(t.timerId===e)return!0;return!1}Ou(t){return this.Mu().then(()=>{this.fu.sort((e,t)=>e.targetTimeMs-t.targetTimeMs);for(var e of this.fu)if(e.skipDelay(),"all"!==t&&e.timerId===t)break;return this.Mu()})}Nu(e){this.wu.push(e)}Fu(e){var t=this.fu.indexOf(e);this.fu.splice(t,1)}}function YC(t){var r=t,t=["next","error","complete"];if("object"==typeof r&&null!==r){var n=r;for(let e of t)if(e in n&&"function"==typeof n[e])return 1}}class JC{constructor(){this._progressObserver={},this._taskCompletionResolver=new Nm,this._lastProgress={taskState:"Running",totalBytes:0,totalDocuments:0,bytesLoaded:0,documentsLoaded:0}}onProgress(e,t,r){this._progressObserver={next:e,error:t,complete:r}}catch(e){return this._taskCompletionResolver.promise.catch(e)}then(e,t){return this._taskCompletionResolver.promise.then(e,t)}_completeWith(e){this._updateProgress(e),this._progressObserver.complete&&this._progressObserver.complete(),this._taskCompletionResolver.resolve(e)}_failWith(e){this._lastProgress.taskState="Error",this._progressObserver.next&&this._progressObserver.next(this._lastProgress),this._progressObserver.error&&this._progressObserver.error(e),this._taskCompletionResolver.reject(e)}_updateProgress(e){this._lastProgress=e,this._progressObserver.next&&this._progressObserver.next(e)}}var XC,ZC;class ek extends qC{constructor(e,t,r,n){super(e,t,r,n),this.type="firestore",this._queue=new QC,this._persistenceKey=(null==n?void 0:n.name)||"[DEFAULT]"}async _terminate(){var e;this._firestoreClient&&(e=this._firestoreClient.terminate(),this._queue=new QC(e),this._firestoreClient=void 0,await e)}}function tk(e){if(e._terminated)throw new N(A.FAILED_PRECONDITION,"The client has already been terminated.");return e._firestoreClient||rk(e),e._firestoreClient}function rk(e){var t,r,n,i,s,a=e._freezeSettings(),o=(i=e._databaseId,t=(null==(o=e._app)?void 0:o.options.appId)||"",r=e._persistenceKey,n=a,new ry(i,t,r,n.host,n.ssl,n.experimentalForceLongPolling,n.experimentalAutoDetectLongPolling,RC(n.experimentalLongPollingOptions),n.useFetchStreams));e._componentsProvider||null!=(s=a.localCache)&&s._offlineComponentProvider&&null!=(s=a.localCache)&&s._onlineComponentProvider&&(e._componentsProvider={_offline:a.localCache._offlineComponentProvider,_online:a.localCache._onlineComponentProvider}),e._firestoreClient=new dC(e._authCredentials,e._appCheckCredentials,e._queue,o,e._componentsProvider&&(i=e._componentsProvider,s=null==i?void 0:i._online.build(),{_offline:null==i?void 0:i._offline.build(s),_online:s}))}function nk(e,t,r){if((e=q(e,ek))._firestoreClient||e._terminated)throw new N(A.FAILED_PRECONDITION,"Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.");if(e._componentsProvider||e._getSettings().localCache)throw new N(A.FAILED_PRECONDITION,"SDK cache is already specified.");e._componentsProvider={_online:t,_offline:r},rk(e)}function ik(r){if(r._initialized&&!r._terminated)throw new N(A.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");let n=new Nm;return r._queue.enqueueAndForgetEvenWhileRestricted(async()=>{try{e=HT(r._databaseId,r._persistenceKey),await(lv.D()?(t=e+"main",void await lv.delete(t)):Promise.resolve()),n.resolve()}catch(e){n.reject(e)}var e,t}),n.promise}function sk(e){return(r=tk(e=q(e,ek))).asyncQueue.enqueue(async()=>{var e=await vC(r),t=await yC(r);return e.setNetworkEnabled(!0),(e=t).W_.delete(0),GE(e)});var r}class ak{constructor(e){this._byteString=e}static fromBase64String(e){try{return new ak(K_.fromBase64String(e))}catch(e){throw new N(A.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new ak(K_.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(e){return this._byteString.isEqual(e._byteString)}}class ok{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new N(A.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new Hm(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class lk{constructor(e){this._methodName=e}}class hk{constructor(e,t){if(!isFinite(e)||e<-90||90<e)throw new N(A.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||180<t)throw new N(A.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+t);this._lat=e,this._long=t}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}toJSON(){return{latitude:this._lat,longitude:this._long}}_compareTo(e){return R(this._lat,e._lat)||R(this._long,e._long)}}class uk{constructor(e){this._values=(e||[]).map(e=>e)}toArray(){return this._values.map(e=>e)}isEqual(e){var t=this._values,r=e._values;if(t.length!==r.length)return!1;for(let n=0;n<t.length;++n)if(t[n]!==r[n])return!1;return!0}}let ck=/^__.*__$/;class dk{constructor(e,t,r){this.data=e,this.fieldMask=t,this.fieldTransforms=r}toMutation(e,t){return null!==this.fieldMask?new Jw(e,this.data,this.fieldMask,t,this.fieldTransforms):new Yw(e,this.data,t,this.fieldTransforms)}}class pk{constructor(e,t,r){this.data=e,this.fieldMask=t,this.fieldTransforms=r}toMutation(e,t){return new Jw(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function fk(e){switch(e){case 0:case 2:case 1:return 1;case 3:case 4:return;default:throw k()}}class gk{constructor(e,t,r,n,i,s){this.settings=e,this.databaseId=t,this.serializer=r,this.ignoreUndefinedProperties=n,void 0===i&&this.Bu(),this.fieldTransforms=i||[],this.fieldMask=s||[]}get path(){return this.settings.path}get Lu(){return this.settings.Lu}ku(e){return new gk(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}qu(e){var t=null==(t=this.path)?void 0:t.child(e),t=this.ku({path:t,Qu:!1});return t.$u(e),t}Ku(e){var t=null==(t=this.path)?void 0:t.child(e),t=this.ku({path:t,Qu:!1});return t.Bu(),t}Uu(e){return this.ku({path:void 0,Qu:!0})}Wu(e){return Lk(e,this.settings.methodName,this.settings.Gu||!1,this.path,this.settings.zu)}contains(t){return void 0!==this.fieldMask.find(e=>t.isPrefixOf(e))||void 0!==this.fieldTransforms.find(e=>t.isPrefixOf(e.field))}Bu(){if(this.path)for(let e=0;e<this.path.length;e++)this.$u(this.path.get(e))}$u(e){if(0===e.length)throw this.Wu("Document fields must not be empty");if(fk(this.Lu)&&ck.test(e))throw this.Wu('Document fields cannot begin and end with "__"')}}class mk{constructor(e,t,r){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=r||FE(e)}ju(e,t,r,n=!1){return new gk({Lu:e,methodName:t,zu:r,path:Hm.emptyPath(),Qu:!1,Gu:n},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function vk(e){var t=e._freezeSettings(),r=FE(e._databaseId);return new mk(e._databaseId,!!t.ignoreUndefinedProperties,r)}function _k(e,n,i,t,r,s={}){var a=e.ju(s.merge||s.mergeFields?2:0,n,i,r),o=(Pk("Data must be an object, but it was:",a,t),Nk(t,a));let l,h;if(s.merge)l=new B_(a.fieldMask),h=a.fieldTransforms;else if(s.mergeFields){let t=[];for(let r of s.mergeFields){let e=Dk(n,r,i);if(!a.contains(e))throw new N(A.INVALID_ARGUMENT,`Field '${e}' is specified in your field mask but missing from your input data.`);Mk(t,e)||t.push(e)}l=new B_(t),h=a.fieldTransforms.filter(e=>l.covers(e.field))}else l=null,h=a.fieldTransforms;return new dk(new Ry(o),l,h)}class yk extends lk{_toFieldTransform(e){if(2!==e.Lu)throw 1===e.Lu?e.Wu(this._methodName+"() can only appear at the top level of your update data"):e.Wu(this._methodName+"() cannot be used with set() unless you pass {merge:true}");return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof yk}}function wk(e,t,r){return new gk({Lu:3,zu:t.settings.zu,methodName:e._methodName,Qu:r},t.databaseId,t.serializer,t.ignoreUndefinedProperties)}class bk extends lk{_toFieldTransform(e){return new Bw(e.path,new Ow)}isEqual(e){return e instanceof bk}}class Ik extends lk{constructor(e,t){super(e),this.Hu=t}_toFieldTransform(e){let t=wk(this,e,!0),r=this.Hu.map(e=>Ak(e,t)),n=new Lw(r);return new Bw(e.path,n)}isEqual(e){return e instanceof Ik&&Ie(this.Hu,e.Hu)}}class Tk extends lk{constructor(e,t){super(e),this.Hu=t}_toFieldTransform(e){let t=wk(this,e,!0),r=this.Hu.map(e=>Ak(e,t)),n=new Fw(r);return new Bw(e.path,n)}isEqual(e){return e instanceof Tk&&Ie(this.Hu,e.Hu)}}class Ek extends lk{constructor(e,t){super(e),this.Ju=t}_toFieldTransform(e){var t=new Vw(e.serializer,Pw(e.serializer,this.Ju));return new Bw(e.path,t)}isEqual(e){return e instanceof Ek&&this.Ju===e.Ju}}function Ck(e,i,s,t){let a=e.ju(1,i,s),o=(Pk("Data must be an object, but it was:",a,t),[]),l=Ry.empty();M_(t,(e,t)=>{var r=Ok(i,e,s),n=(t=w(t),a.Ku(r));if(t instanceof yk)o.push(r);else{let e=Ak(t,n);null!=e&&(o.push(r),l.set(r,e))}});var r=new B_(o);return new pk(l,r,a.fieldTransforms)}function kk(e,t,r,n,i,s){var a=e.ju(1,t,r),o=[Dk(t,n,r)],l=[i];if(s.length%2!=0)throw new N(A.INVALID_ARGUMENT,`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let p=0;p<s.length;p+=2)o.push(Dk(t,s[p])),l.push(s[p+1]);var h=[],u=Ry.empty();for(let f=o.length-1;0<=f;--f)if(!Mk(h,o[f])){let t=o[f];var c=w(l[f]);let r=a.Ku(t);if(c instanceof yk)h.push(t);else{let e=Ak(c,r);null!=e&&(h.push(t),u.set(t,e))}}var d=new B_(h);return new pk(u,d,a.fieldTransforms)}function Sk(e,t,r,n=!1){return Ak(r,e.ju(n?4:3,t))}function Ak(e,r){if(Rk(e=w(e)))return Pk("Unsupported field value:",r,e),Nk(e,r);if(e instanceof lk){{var t=e;var n=r;if(!fk(n.Lu))throw n.Wu(t._methodName+"() can only be used with update() and set()");if(!n.path)throw n.Wu(t._methodName+"() is not currently supported inside arrays");var i=t._toFieldTransform(n);i&&n.fieldTransforms.push(i)}return null}if(void 0===e&&r.ignoreUndefinedProperties)return null;if(r.path&&r.fieldMask.push(r.path),e instanceof Array){if(r.settings.Qu&&4!==r.Lu)throw r.Wu("Nested arrays are not supported");{var s,a=r,o=[];let t=0;for(s of e){let e=Ak(s,a.Uu(t));null==e&&(e={nullValue:"NULL_VALUE"}),o.push(e),t++}return{arrayValue:{values:o}}}}var l,t=e,n=r;if(null===(t=w(t)))return{nullValue:"NULL_VALUE"};if("number"==typeof t)return Pw(n.serializer,t);if("boolean"==typeof t)return{booleanValue:t};if("string"==typeof t)return{stringValue:t};if(t instanceof Date)return h=Bm.fromDate(t),{timestampValue:Nb(n.serializer,h)};if(t instanceof Bm)return h=new Bm(t.seconds,1e3*Math.floor(t.nanoseconds/1e3)),{timestampValue:Nb(n.serializer,h)};if(t instanceof hk)return{geoPointValue:{latitude:t.latitude,longitude:t.longitude}};if(t instanceof ak)return{bytesValue:Rb(n.serializer,t._byteString)};if(t instanceof BC){var h=n.databaseId,i=t.firestore._databaseId;if(i.isEqual(h))return{referenceValue:Db(t.firestore._databaseId||n.databaseId,t._key.path)};throw n.Wu(`Document reference is for database ${i.projectId}/${i.database} but should be for database ${h.projectId}/`+h.database)}if(t instanceof uk)return e=t,l=n,{mapValue:{fields:{[sy]:{stringValue:ly},[hy]:{arrayValue:{values:e.toArray().map(e=>{if("number"!=typeof e)throw l.Wu("VectorValues must only contain numeric values.");return Nw(l.serializer,e)})}}}}};throw n.Wu("Unsupported field value: "+MC(t))}function Nk(e,n){let i={};return F_(e)?n.path&&0<n.path.length&&n.fieldMask.push(n.path):M_(e,(e,t)=>{var r=Ak(t,n.qu(e));null!=r&&(i[e]=r)}),{mapValue:{fields:i}}}function Rk(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof Bm||e instanceof hk||e instanceof ak||e instanceof BC||e instanceof lk||e instanceof uk)}function Pk(e,t,r){var n,i;if(!Rk(r)||"object"!=typeof(i=r)||null===i||Object.getPrototypeOf(i)!==Object.prototype&&null!==Object.getPrototypeOf(i))throw"an object"===(n=MC(r))?t.Wu(e+" a custom object"):t.Wu(e+" "+n)}function Dk(e,t,r){if((t=w(t))instanceof ok)return t._internalPath;if("string"==typeof t)return Ok(e,t);throw Lk("Field path arguments must be of type string or ",e,!1,void 0,r)}let xk=new RegExp("[~\\*/\\[\\]]");function Ok(t,r,n){if(0<=r.search(xk))throw Lk(`Invalid field path (${r}). Paths must not contain '~', '*', '/', '[', or ']'`,t,!1,void 0,n);try{return new ok(...r.split("."))._internalPath}catch(e){throw Lk(`Invalid field path (${r}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,t,!1,void 0,n)}}function Lk(e,t,r,n,i){var s=n&&!n.isEmpty(),a=void 0!==i;let o=`Function ${t}() called with invalid data`,l=(r&&(o+=" (via `toFirestore()`)"),o+=". ","");return(s||a)&&(l+=" (found",s&&(l+=" in field "+n),a&&(l+=" in document "+i),l+=")"),new N(A.INVALID_ARGUMENT,o+e+l)}function Mk(e,t){return e.some(e=>e.isEqual(t))}class Fk{constructor(e,t,r,n,i){this._firestore=e,this._userDataWriter=t,this._key=r,this._document=n,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new BC(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){var e;if(this._document)return this._converter?(e=new Uk(this._firestore,this._userDataWriter,this._key,this._document,null),this._converter.fromFirestore(e)):this._userDataWriter.convertValue(this._document.data.value)}get(e){if(this._document){var t=this._document.data.field(Vk("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class Uk extends Fk{data(){return super.data()}}function Vk(e,t){return"string"==typeof t?Ok(e,t):(t instanceof ok?t:t._delegate)._internalPath}function qk(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new N(A.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class jk{}class Bk extends jk{}function zk(e,t,...r){let n=[];t instanceof jk&&n.push(t);var t=n=n.concat(r),i=t.filter(e=>!1).length,s=t.filter(e=>e instanceof Kk).length;if(1<i||0<i&&0<s)throw new N(A.INVALID_ARGUMENT,"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.");for(let t of n)e=t._apply(e);return e}class Kk extends Bk{constructor(e,t,r){super(),this._field=e,this._op=t,this._value=r,this.type="where"}static _create(e,t,r){return new Kk(e,t,r)}_apply(e){var t=this._parse(e);return Xk(e._query,t),new jC(e.firestore,e.converter,dw(e._query,t))}_parse(e){var t=vk(e.firestore);{var n=e._query,i="where",s=t,a=e.firestore._databaseId,o=(e=this._field,this._op),l=this._value;let r;if(e.isKeyField()){if("array-contains"===o||"array-contains-any"===o)throw new N(A.INVALID_ARGUMENT,`Invalid Query. You can't perform '${o}' queries on documentId().`);if("in"===o||"not-in"===o){Jk(l,o);let e=[];for(let t of l)e.push(Yk(a,n,t));r={arrayValue:{values:e}}}else r=Yk(a,n,l)}else"in"!==o&&"not-in"!==o&&"array-contains-any"!==o||Jk(l,o),r=Sk(s,i,l,"in"===o||"not-in"===o);return F.create(e,o,r)}}}(class extends jk{});class Wk extends Bk{constructor(e,t){super(),this._field=e,this._direction=t,this.type="orderBy"}static _create(e,t){return new Wk(e,t)}_apply(e){var t=((e,t,r)=>{if(null!==e.startAt)throw new N(A.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new N(A.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");return new Ly(t,r)})(e._query,this._field,this._direction);return new jC(e.firestore,e.converter,(t=(e=e._query).explicitOrderBy.concat([t]),new sw(e.path,e.collectionGroup,t,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)))}}class Hk extends Bk{constructor(e,t,r){super(),this.type=e,this._limit=t,this._limitType=r}static _create(e,t,r){return new Hk(e,t,r)}_apply(e){return new jC(e.firestore,e.converter,pw(e._query,this._limit,this._limitType))}}class Gk extends Bk{constructor(e,t,r){super(),this.type=e,this._docOrFields=t,this._inclusive=r}static _create(e,t,r){return new Gk(e,t,r)}_apply(e){var t,r=Qk(e,this.type,this._docOrFields,this._inclusive);return new jC(e.firestore,e.converter,(e=e._query,t=r,new sw(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,t,e.endAt)))}}class $k extends Bk{constructor(e,t,r){super(),this.type=e,this._docOrFields=t,this._inclusive=r}static _create(e,t,r){return new $k(e,t,r)}_apply(e){var t,r=Qk(e,this.type,this._docOrFields,this._inclusive);return new jC(e.firestore,e.converter,(e=e._query,t=r,new sw(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,t)))}}function Qk(e,r,n,i){if(n[0]=w(n[0]),n[0]instanceof Fk){var s=e._query,a=e.firestore._databaseId,o=r,l=n[0]._document,h=i;if(!l)throw new N(A.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${o}().`);var u=[];for(let t of uw(s))if(t.field.isKeyField())u.push(_y(a,l.key));else{let e=l.data.field(t.field);if(Z_(e))throw new N(A.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+t.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(null===e){let e=t.field.canonicalString();throw new N(A.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${e}' (used as the orderBy) does not exist.`)}u.push(e)}return new Dy(u,h)}var t=vk(e.firestore),c=e._query,d=e.firestore._databaseId,p=t,f=r,g=n,o=i,m=c.explicitOrderBy;if(g.length>m.length)throw new N(A.INVALID_ARGUMENT,`Too many arguments provided to ${f}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);var v=[];for(let y=0;y<g.length;y++){var _=g[y];if(m[y].field.isKeyField()){if("string"!=typeof _)throw new N(A.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${f}(), but got a `+typeof _);if(!hw(c)&&-1!==_.indexOf("/"))throw new N(A.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${f}() must be a plain document ID, but '${_}' contains a slash.`);let e=c.path.child(D.fromString(_));if(!x.isDocumentKey(e))throw new N(A.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${f}() must result in a valid document path, but '${e}' is not because it contains an odd number of segments.`);let t=new x(e);v.push(_y(d,t))}else{let e=Sk(p,f,_);v.push(e)}}return new Dy(v,o)}function Yk(e,t,r){if("string"==typeof(r=w(r))){if(""===r)throw new N(A.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!hw(t)&&-1!==r.indexOf("/"))throw new N(A.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${r}' contains a '/' character.`);var n=t.path.child(D.fromString(r));if(x.isDocumentKey(n))return _y(e,new x(n));throw new N(A.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${n}' is not because it has an odd number of segments (${n.length}).`)}if(r instanceof BC)return _y(e,r._key);throw new N(A.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${MC(r)}.`)}function Jk(e,t){if(!Array.isArray(e)||0===e.length)throw new N(A.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`)}function Xk(e,t){var r=((t,r)=>{for(var n of t)for(let e of n.getFlattenedFilters())if(0<=r.indexOf(e.op))return e.op;return null})(e.filters,(e=>{switch(e){case"!=":return["!=","not-in"];case"array-contains-any":case"in":return["not-in"];case"not-in":return["array-contains-any","in","not-in","!="];default:return[]}})(t.op));if(null!==r)throw r===t.op?new N(A.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new N(A.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${r.toString()}' filters.`)}class Zk{convertValue(e,t="none"){switch(cy(e)){case 0:return null;case 1:return e.booleanValue;case 2:return G_(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,t);case 5:return e.stringValue;case 6:return this.convertBytes($_(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,t);case 11:return this.convertObject(e.mapValue,t);case 10:return this.convertVectorValue(e.mapValue);default:throw k()}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,r="none"){let n={};return M_(e,(e,t)=>{n[e]=this.convertValue(t,r)}),n}convertVectorValue(e){var t=null==(t=null==(t=null==(t=e.fields)?void 0:t[hy].arrayValue)?void 0:t.values)?void 0:t.map(e=>G_(e.doubleValue));return new uk(t)}convertGeoPoint(e){return new hk(G_(e.latitude),G_(e.longitude))}convertArray(e,t){return(e.values||[]).map(e=>this.convertValue(e,t))}convertServerTimestamp(e,t){switch(t){case"previous":var r=ey(e);return null==r?null:this.convertValue(r,t);case"estimate":return this.convertTimestamp(ty(e));default:return null}}convertTimestamp(e){var t=H_(e);return new Bm(t.seconds,t.nanos)}convertDocumentKey(e,t){var r=D.fromString(e),n=(S(eI(r)),new iy(r.get(1),r.get(3))),r=new x(r.popFirst(5));return n.isEqual(t)||km(`Document ${r} contains a document reference within a different database (${n.projectId}/${n.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),r}}function eS(e,t,r){return e?r&&(r.merge||r.mergeFields)?e.toFirestore(t,r):e.toFirestore(t):t}class tS extends Zk{constructor(e){super(),this.firestore=e}convertBytes(e){return new ak(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new BC(this.firestore,null,t)}}class rS{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class nS extends Fk{constructor(e,t,r,n,i,s){super(e,t,r,n,s),this._firestore=e,this._firestoreImpl=e,this.metadata=i}exists(){return super.exists()}data(e={}){var t;if(this._document)return this._converter?(t=new iS(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null),this._converter.fromFirestore(t,e)):this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}get(e,t={}){if(this._document){var r=this._document.data.field(Vk("DocumentSnapshot.get",e));if(null!==r)return this._userDataWriter.convertValue(r,t.serverTimestamps)}}}class iS extends nS{data(e={}){return super.data(e)}}class sS{constructor(e,t,r,n){this._firestore=e,this._userDataWriter=t,this._snapshot=n,this.metadata=new rS(n.hasPendingWrites,n.fromCache),this.query=r}get docs(){let t=[];return this.forEach(e=>t.push(e)),t}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(t,r){this._snapshot.docs.forEach(e=>{t.call(r,new iS(this._firestore,this._userDataWriter,e.key,e,new rS(this._snapshot.mutatedKeys.has(e.key),this._snapshot.fromCache),this.query.converter))})}docChanges(e={}){var t=!!e.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new N(A.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===t||(this._cachedChanges=((s,t)=>{if(s._snapshot.oldDocs.isEmpty()){let r=0;return s._snapshot.docChanges.map(e=>{var t=new iS(s._firestore,s._userDataWriter,e.doc.key,e.doc,new rS(s._snapshot.mutatedKeys.has(e.doc.key),s._snapshot.fromCache),s.query.converter);return e.doc,{type:"added",doc:t,oldIndex:-1,newIndex:r++}})}{let i=s._snapshot.oldDocs;return s._snapshot.docChanges.filter(e=>t||3!==e.type).map(e=>{var t=new iS(s._firestore,s._userDataWriter,e.doc.key,e.doc,new rS(s._snapshot.mutatedKeys.has(e.doc.key),s._snapshot.fromCache),s.query.converter);let r=-1,n=-1;return 0!==e.type&&(r=i.indexOf(e.doc.key),i=i.delete(e.doc.key)),1!==e.type&&(i=i.add(e.doc),n=i.indexOf(e.doc.key)),{type:(e=>{switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return k()}})(e.type),doc:t,oldIndex:r,newIndex:n}})}})(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function aS(e,t){return e instanceof nS&&t instanceof nS?e._firestore===t._firestore&&e._key.isEqual(t._key)&&(null===e._document?null===t._document:e._document.isEqual(t._document))&&e._converter===t._converter:e instanceof sS&&t instanceof sS&&e._firestore===t._firestore&&GC(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)}class oS extends Zk{constructor(e){super(),this.firestore=e}convertBytes(e){return new ak(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new BC(this.firestore,null,t)}}function lS(e,t,r){e=q(e,BC);var n=q(e.firestore,ek),i=eS(e.converter,t,r);return cS(n,[_k(vk(n),"setDoc",e._key,i,null!==e.converter,r).toMutation(e._key,Kw.none())])}function hS(e,t,r,...n){e=q(e,BC);var i=q(e.firestore,ek),s=vk(i);return cS(i,[("string"==typeof(t=w(t))||t instanceof ok?kk(s,"updateDoc",e._key,t,r,n):Ck(s,"updateDoc",e._key,t)).toMutation(e._key,Kw.exists(!0))])}function uS(n,...i){var t,r;n=w(n);let e={includeMetadataChanges:!1,source:"default"},s=0;"object"!=typeof i[s]||YC(i[s])||(e=i[s],s++);var a={includeMetadataChanges:e.includeMetadataChanges,source:e.source};if(YC(i[s])){let e=i[s];i[s]=null==(r=e.next)?void 0:r.bind(e),i[s+1]=null==(t=e.error)?void 0:t.bind(e),i[s+2]=null==(r=e.complete)?void 0:r.bind(e)}let o,l,h;if(n instanceof BC)l=q(n.firestore,ek),h=ow(n._key.path),o={next:e=>{i[s]&&i[s](dS(l,n,e))},error:i[s+1],complete:i[s+2]};else{let t=q(n,jC),r=(l=q(t.firestore,ek),h=t._query,new oS(l));o={next:e=>{i[s]&&i[s](new sS(l,r,t,e))},error:i[s+1],complete:i[s+2]},qk(n._query)}{var u=tk(l),c=h,d=a,p=o;let e=new oC(p),t=new T0(c,e,d);return u.asyncQueue.enqueueAndForget(async()=>w0(await bC(u),t)),()=>{e.su(),u.asyncQueue.enqueueAndForget(async()=>b0(await bC(u),t))}}}function cS(t,r){{var n=tk(t),i=r;let e=new Nm;return n.asyncQueue.enqueueAndForget(async()=>F0(await wC(n),i,e)),e.promise}}function dS(e,t,r){var n=r.docs.get(t._key),i=new oS(e);return new nS(e,i,t._key,n,new rS(r.hasPendingWrites,r.fromCache),t.converter)}let pS={maxAttempts:5};class fS{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=vk(e)}set(e,t,r){this._verifyNotCommitted();var n=gS(e,this._firestore),i=eS(n.converter,t,r),i=_k(this._dataReader,"WriteBatch.set",n._key,i,null!==n.converter,r);return this._mutations.push(i.toMutation(n._key,Kw.none())),this}update(e,t,r,...n){this._verifyNotCommitted();var i=gS(e,this._firestore),s="string"==typeof(t=w(t))||t instanceof ok?kk(this._dataReader,"WriteBatch.update",i._key,t,r,n):Ck(this._dataReader,"WriteBatch.update",i._key,t);return this._mutations.push(s.toMutation(i._key,Kw.exists(!0))),this}delete(e){this._verifyNotCommitted();var t=gS(e,this._firestore);return this._mutations=this._mutations.concat(new tb(t._key,Kw.none())),this}commit(){return this._verifyNotCommitted(),this._committed=!0,0<this._mutations.length?this._commitHandler(this._mutations):Promise.resolve()}_verifyNotCommitted(){if(this._committed)throw new N(A.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function gS(e,t){if((e=w(e)).firestore!==t)throw new N(A.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}class mS extends class{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=vk(e)}get(e){let r=gS(e,this._firestore),n=new tS(this._firestore);return this._transaction.lookup([r._key]).then(e=>{if(!e||1!==e.length)return k();var t=e[0];if(t.isFoundDocument())return new Fk(this._firestore,n,t.key,t,r.converter);if(t.isNoDocument())return new Fk(this._firestore,n,r._key,null,r.converter);throw k()})}set(e,t,r){var n=gS(e,this._firestore),i=eS(n.converter,t,r),i=_k(this._dataReader,"Transaction.set",n._key,i,null!==n.converter,r);return this._transaction.set(n._key,i),this}update(e,t,r,...n){var i=gS(e,this._firestore),s="string"==typeof(t=w(t))||t instanceof ok?kk(this._dataReader,"Transaction.update",i._key,t,r,n):Ck(this._dataReader,"Transaction.update",i._key,t);return this._transaction.update(i._key,s),this}delete(e){var t=gS(e,this._firestore);return this._transaction.delete(t._key),this}}{constructor(e,t){super(e,t),this._firestore=e}get(e){let t=gS(e,this._firestore),r=new oS(this._firestore);return super.get(e).then(e=>new nS(this._firestore,r,t._key,e._document,new rS(!1,!1),t.converter))}}function vS(r,n,e){r=q(r,ek);var i=Object.assign(Object.assign({},pS),e);if(i.maxAttempts<1)throw new N(A.INVALID_ARGUMENT,"Max attempts must be at least 1");{var s=tk(r),a=e=>n(new mS(r,e)),o=i;let t=new Nm;return s.asyncQueue.enqueueAndForget(async()=>{var e=await mC(s).then(e=>e.datastore);new uC(s.asyncQueue,e,o,a,t).Iu()}),t.promise}}XC=!0,KD=Dt,Tm=KD,Ct(new u("firestore",(e,{instanceIdentifier:t,options:r})=>{var n=e.getProvider("app").getImmediate(),n=new ek(new xm(e.getProvider("auth-internal")),new Fm(n,e.getProvider("app-check-internal")),((e,t)=>{if(Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))return new iy(e.options.projectId,t);throw new N(A.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.')})(n,t),n);return r=Object.assign({useFetchStreams:XC},r),n._setSettings(r),n},"PUBLIC").setMultipleInstances(!0)),d(bm,"4.7.8",$N),d(bm,"4.7.8","esm2017");function _S(e,t){if(void 0===t)return{merge:!1};if(void 0!==t.mergeFields&&void 0!==t.merge)throw new N("invalid-argument",`Invalid options passed to function ${e}(): You cannot `+'specify both "merge" and "mergeFields".');return t}function yS(){if("undefined"==typeof Uint8Array)throw new N("unimplemented","Uint8Arrays are not available in this environment.")}function wS(){if("undefined"==typeof atob)throw new N("unimplemented","Blobs are unavailable in Firestore in this environment.")}class bS{constructor(e){this._delegate=e}static fromBase64String(e){return wS(),new bS(ak.fromBase64String(e))}static fromUint8Array(e){return yS(),new bS(ak.fromUint8Array(e))}toBase64(){return wS(),this._delegate.toBase64()}toUint8Array(){return yS(),this._delegate.toUint8Array()}isEqual(e){return this._delegate.isEqual(e._delegate)}toString(){return"Blob(base64: "+this.toBase64()+")"}}function IS(e){var t=["next","error","complete"];if("object"==typeof e&&null!==e){var r,n=e;for(r of t)if(r in n&&"function"==typeof n[r])return 1}}class TS{enableIndexedDbPersistence(e,r){{e=e._delegate;var n={forceOwnership:r};Sm("enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");let t=e._freezeSettings();return nk(e,sC.provider,{build:e=>new nC(e,t.cacheSizeBytes,null==n?void 0:n.forceOwnership)}),Promise.resolve()}}enableMultiTabIndexedDbPersistence(e){return(async e=>{Sm("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");let t=e._freezeSettings();nk(e,sC.provider,{build:e=>new iC(e,t.cacheSizeBytes)})})(e._delegate)}clearIndexedDbPersistence(e){return ik(e._delegate)}}class ES{constructor(e,t,r){this._delegate=t,this._persistenceProvider=r,this.INTERNAL={delete:()=>this.terminate()},e instanceof iy||(this._appCompat=e)}get _databaseId(){return this._delegate._databaseId}settings(e){var t=this._delegate._getSettings();e.merge||t.host===e.host||Sm("You are overriding the original host. If you did not intend to override your settings, use {merge: true}."),e.merge&&delete(e=Object.assign(Object.assign({},t),e)).merge,this._delegate._setSettings(e)}useEmulator(i,r,s={}){{var[i,r,s,a={}]=[this._delegate,i,r,s];let n,e=(i=q(i,qC))._getSettings(),t=r+":"+s;if(e.host!==UC&&e.host!==t&&Sm("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."),i._setSettings(Object.assign(Object.assign({},e),{host:t,ssl:!1})),a.mockUserToken){let t,r;if("string"==typeof a.mockUserToken)t=a.mockUserToken,r=Im.MOCK_USER;else{t=Z(a.mockUserToken,null==(n=i._app)?void 0:n.options.projectId);let e=a.mockUserToken.sub||a.mockUserToken.user_id;if(!e)throw new N(A.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");r=new Im(e)}i._authCredentials=new Dm(new Rm(t,r))}}}enableNetwork(){return sk(this._delegate)}disableNetwork(){return IC(tk(q(this._delegate,ek)))}enablePersistence(e){let t=!1,r=!1;return e&&(t=!!e.synchronizeTabs,r=!!e.experimentalForceOwningTab,xC("synchronizeTabs",t,"experimentalForceOwningTab",r)),t?this._persistenceProvider.enableMultiTabIndexedDbPersistence(this):this._persistenceProvider.enableIndexedDbPersistence(this,r)}clearPersistence(){return this._persistenceProvider.clearIndexedDbPersistence(this)}terminate(){return this._appCompat&&(this._appCompat._removeServiceInstance("firestore-compat"),this._appCompat._removeServiceInstance("firestore")),this._delegate._delete()}waitForPendingWrites(){var t=this._delegate;{var r=tk(t=q(t,ek));let e=new Nm;return r.asyncQueue.enqueueAndForget(async()=>j0(await wC(r),e)),e.promise}}onSnapshotsInSync(e){return t=this._delegate,e=e,SC(tk(t=q(t,ek)),YC(e)?e:{next:e});var t}get app(){if(this._appCompat)return this._appCompat;throw new N("failed-precondition","Firestore was not initialized using the Firebase SDK. 'app' is not available")}collection(e){try{return new US(this,KC(this._delegate,e))}catch(e){throw RS(e,"collection()","Firestore.collection()")}}doc(e){try{return new NS(this,WC(this._delegate,e))}catch(e){throw RS(e,"doc()","Firestore.doc()")}}collectionGroup(e){try{return new LS(this,((e,t)=>{if(e=q(e,qC),DC("collectionGroup","collection id",t),0<=t.indexOf("/"))throw new N(A.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new jC(e,null,(e=t,new sw(D.emptyPath(),e)))})(this._delegate,e))}catch(e){throw RS(e,"collectionGroup()","Firestore.collectionGroup()")}}runTransaction(t){return vS(this._delegate,e=>t(new kS(this,e)))}batch(){return tk(this._delegate),new SS(new fS(this._delegate,e=>cS(this._delegate,e)))}loadBundle(e){return t=this._delegate,e=e,r=tk(t=q(t,ek)),n=new JC,AC(r,t._databaseId,e,n),n;var t,r,n}namedQuery(e){return t=this._delegate,e=e,NC(tk(t=q(t,ek)),e).then(e=>e?new jC(t,null,e.query):null).then(e=>e?new LS(this,e):null);var t}}class CS extends Zk{constructor(e){super(),this.firestore=e}convertBytes(e){return new bS(new ak(e))}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return NS.forKey(t,this.firestore,null)}}class kS{constructor(e,t){this._firestore=e,this._delegate=t,this._userDataWriter=new CS(e)}get(e){let t=VS(e);return this._delegate.get(t).then(e=>new xS(this._firestore,new nS(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,t.converter)))}set(e,t,r){var n=VS(e);return r?(_S("Transaction.set",r),this._delegate.set(n,t,r)):this._delegate.set(n,t),this}update(e,t,r,...n){var i=VS(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,r,...n),this}delete(e){var t=VS(e);return this._delegate.delete(t),this}}class SS{constructor(e){this._delegate=e}set(e,t,r){var n=VS(e);return r?(_S("WriteBatch.set",r),this._delegate.set(n,t,r)):this._delegate.set(n,t),this}update(e,t,r,...n){var i=VS(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,r,...n),this}delete(e){var t=VS(e);return this._delegate.delete(t),this}commit(){return this._delegate.commit()}}class AS{constructor(e,t,r){this._firestore=e,this._userDataWriter=t,this._delegate=r}fromFirestore(e,t){var r=new iS(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,null);return this._delegate.fromFirestore(new OS(this._firestore,r),null!=t?t:{})}toFirestore(e,t){return t?this._delegate.toFirestore(e,t):this._delegate.toFirestore(e)}static getInstance(e,t){var r=AS.INSTANCES;let n=r.get(e),i=(n||(n=new WeakMap,r.set(e,n)),n.get(t));return i||(i=new AS(e,new CS(e),t),n.set(t,i)),i}}AS.INSTANCES=new WeakMap;class NS{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new CS(e)}static forPath(e,t,r){if(e.length%2!=0)throw new N("invalid-argument","Invalid document reference. Document references must have an even number of segments, but "+e.canonicalString()+" has "+e.length);return new NS(t,new BC(t._delegate,r,new x(e)))}static forKey(e,t,r){return new NS(t,new BC(t._delegate,r,e))}get id(){return this._delegate.id}get parent(){return new US(this.firestore,this._delegate.parent)}get path(){return this._delegate.path}collection(e){try{return new US(this.firestore,KC(this._delegate,e))}catch(e){throw RS(e,"collection()","DocumentReference.collection()")}}isEqual(e){return(e=w(e))instanceof BC&&HC(this._delegate,e)}set(e,t){t=_S("DocumentReference.set",t);try{return t?lS(this._delegate,e,t):lS(this._delegate,e)}catch(e){throw RS(e,"setDoc()","DocumentReference.set()")}}update(e,t,...r){try{return 1===arguments.length?hS(this._delegate,e):hS(this._delegate,e,t,...r)}catch(e){throw RS(e,"updateDoc()","DocumentReference.update()")}}delete(){return cS(q((e=this._delegate).firestore,ek),[new tb(e._key,Kw.none())]);var e}onSnapshot(...e){var t=PS(e),r=DS(e,e=>new xS(this.firestore,new nS(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)));return uS(this._delegate,t,r)}get(e){let t;return(t=("cache"===(null==e?void 0:e.source)?t=>{t=q(t,BC);let r=q(t.firestore,ek),e=tk(r),n=new oS(r);return TC(e,t._key).then(e=>new nS(r,n,t._key,e,new rS(null!==e&&e.hasLocalMutations,!0),t.converter))}:"server"===(null==e?void 0:e.source)?t=>{t=q(t,BC);let r=q(t.firestore,ek);return EC(tk(r),t._key,{source:"server"}).then(e=>dS(r,t,e))}:t=>{t=q(t,BC);let r=q(t.firestore,ek);return EC(tk(r),t._key).then(e=>dS(r,t,e))})(this._delegate)).then(e=>new xS(this.firestore,new nS(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)))}withConverter(e){return new NS(this.firestore,e?this._delegate.withConverter(AS.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function RS(e,t,r){return e.message=e.message.replace(t,r),e}function PS(e){for(var t of e)if("object"==typeof t&&!IS(t))return t;return{}}function DS(e,t){let r,n,i;return i=IS(e[0])?e[0]:IS(e[1])?e[1]:"function"==typeof e[0]?{next:e[0],error:e[1],complete:e[2]}:{next:e[1],error:e[2],complete:e[3]},{next:e=>{i.next&&i.next(t(e))},error:null==(r=i.error)?void 0:r.bind(i),complete:null==(n=i.complete)?void 0:n.bind(i)}}class xS{constructor(e,t){this._firestore=e,this._delegate=t}get ref(){return new NS(this._firestore,this._delegate.ref)}get id(){return this._delegate.id}get metadata(){return this._delegate.metadata}get exists(){return this._delegate.exists()}data(e){return this._delegate.data(e)}get(e,t){return this._delegate.get(e,t)}isEqual(e){return aS(this._delegate,e._delegate)}}class OS extends xS{data(e){var t=this._delegate.data(e);return this._delegate._converter||void 0!==t||k(),t}}class LS{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new CS(e)}where(e,t,r){try{return new LS(this.firestore,zk(this._delegate,(n=r,i=t,s=Vk("where",e),Kk._create(s,i,n))))}catch(e){throw RS(e,/(orderBy|where)\(\)/,"Query.$1()")}var n,i,s}orderBy(e,t){try{return new LS(this.firestore,zk(this._delegate,([r,n="asc"]=[e,t],i=n,s=Vk("orderBy",r),Wk._create(s,i))))}catch(e){throw RS(e,/(orderBy|where)\(\)/,"Query.$1()")}var r,n,i,s}limit(e){try{return new LS(this.firestore,zk(this._delegate,(FC("limit",t=e),Hk._create("limit",t,"F"))))}catch(e){throw RS(e,"limit()","Query.limit()")}var t}limitToLast(e){try{return new LS(this.firestore,zk(this._delegate,(FC("limitToLast",t=e),Hk._create("limitToLast",t,"L"))))}catch(e){throw RS(e,"limitToLast()","Query.limitToLast()")}var t}startAt(...e){try{return new LS(this.firestore,zk(this._delegate,([...t]=[...e],Gk._create("startAt",t,!0))))}catch(e){throw RS(e,"startAt()","Query.startAt()")}var t}startAfter(...e){try{return new LS(this.firestore,zk(this._delegate,([...t]=[...e],Gk._create("startAfter",t,!1))))}catch(e){throw RS(e,"startAfter()","Query.startAfter()")}var t}endBefore(...e){try{return new LS(this.firestore,zk(this._delegate,([...t]=[...e],$k._create("endBefore",t,!1))))}catch(e){throw RS(e,"endBefore()","Query.endBefore()")}var t}endAt(...e){try{return new LS(this.firestore,zk(this._delegate,([...t]=[...e],$k._create("endAt",t,!0))))}catch(e){throw RS(e,"endAt()","Query.endAt()")}var t}isEqual(e){return GC(this._delegate,e._delegate)}get(e){let t;return(t=("cache"===(null==e?void 0:e.source)?t=>{t=q(t,jC);let r=q(t.firestore,ek),e=tk(r),n=new oS(r);return CC(e,t._query).then(e=>new sS(r,n,t,e))}:"server"===(null==e?void 0:e.source)?t=>{t=q(t,jC);let r=q(t.firestore,ek),e=tk(r),n=new oS(r);return kC(e,t._query,{source:"server"}).then(e=>new sS(r,n,t,e))}:t=>{t=q(t,jC);let r=q(t.firestore,ek),e=tk(r),n=new oS(r);return qk(t._query),kC(e,t._query).then(e=>new sS(r,n,t,e))})(this._delegate)).then(e=>new FS(this.firestore,new sS(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)))}onSnapshot(...e){var t=PS(e),r=DS(e,e=>new FS(this.firestore,new sS(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)));return uS(this._delegate,t,r)}withConverter(e){return new LS(this.firestore,e?this._delegate.withConverter(AS.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}class MS{constructor(e,t){this._firestore=e,this._delegate=t}get type(){return this._delegate.type}get doc(){return new OS(this._firestore,this._delegate.doc)}get oldIndex(){return this._delegate.oldIndex}get newIndex(){return this._delegate.newIndex}}class FS{constructor(e,t){this._firestore=e,this._delegate=t}get query(){return new LS(this._firestore,this._delegate.query)}get metadata(){return this._delegate.metadata}get size(){return this._delegate.size}get empty(){return this._delegate.empty}get docs(){return this._delegate.docs.map(e=>new OS(this._firestore,e))}docChanges(e){return this._delegate.docChanges(e).map(e=>new MS(this._firestore,e))}forEach(t,r){this._delegate.forEach(e=>{t.call(r,new OS(this._firestore,e))})}isEqual(e){return aS(this._delegate,e._delegate)}}class US extends LS{constructor(e,t){super(e,t),this.firestore=e,this._delegate=t}get id(){return this._delegate.id}get path(){return this._delegate.path}get parent(){var e=this._delegate.parent;return e?new NS(this.firestore,e):null}doc(e){try{return void 0===e?new NS(this.firestore,WC(this._delegate)):new NS(this.firestore,WC(this._delegate,e))}catch(e){throw RS(e,"doc()","CollectionReference.doc()")}}add(e){return((e,t)=>{let r=q(e.firestore,ek),n=WC(e),i=eS(e.converter,t);return cS(r,[_k(vk(e.firestore),"addDoc",n._key,i,null!==e.converter,{}).toMutation(n._key,Kw.exists(!1))]).then(()=>n)})(this._delegate,e).then(e=>new NS(this.firestore,e))}isEqual(e){return HC(this._delegate,e._delegate)}withConverter(e){return new US(this.firestore,e?this._delegate.withConverter(AS.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function VS(e){return q(e,BC)}class qS{static serverTimestamp(){var e=new bk("serverTimestamp");return e._methodName="FieldValue.serverTimestamp",new qS(e)}static delete(){var e=new yk("deleteField");return e._methodName="FieldValue.delete",new qS(e)}static arrayUnion(...e){[...e]=[...e];var t=new Ik("arrayUnion",e);return t._methodName="FieldValue.arrayUnion",new qS(t)}static arrayRemove(...e){[...e]=[...e];var t=new Tk("arrayRemove",e);return t._methodName="FieldValue.arrayRemove",new qS(t)}static increment(e){e=e;var t=new Ek("increment",e);return t._methodName="FieldValue.increment",new qS(t)}constructor(e){this._delegate=e}isEqual(e){return this._delegate.isEqual(e._delegate)}}let jS={Firestore:ES,GeoPoint:hk,Timestamp:Bm,Blob:bS,Transaction:kS,WriteBatch:SS,DocumentReference:NS,DocumentSnapshot:xS,Query:LS,QueryDocumentSnapshot:OS,QuerySnapshot:FS,CollectionReference:US,FieldPath:class cx{constructor(...e){this._delegate=new ok(...e)}static documentId(){return new cx(Hm.keyField().canonicalString())}isEqual(e){return(e=w(e))instanceof ok&&this._delegate._internalPath.isEqual(e._internalPath)}},FieldValue:qS,setLogLevel:function(e){e=e,Em.setLogLevel(e)},CACHE_SIZE_UNLIMITED:-1};t=tr,ZC=(e,t)=>new ES(e,t,new TS),t.INTERNAL.registerComponent(new u("firestore-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),r=e.getProvider("firestore").getImmediate();return ZC(t,r)},"PUBLIC").setServiceProps(Object.assign({},jS))),t.registerVersion("@firebase/firestore-compat","0.3.43");let BS="type.googleapis.com/google.protobuf.Int64Value",zS="type.googleapis.com/google.protobuf.UInt64Value";function KS(e,t){var r,n={};for(r in e)e.hasOwnProperty(r)&&(n[r]=t(e[r]));return n}function WS(e){if(null==e)return null;if("number"==typeof(e=e instanceof Number?e.valueOf():e)&&isFinite(e))return e;if(!0===e||!1===e)return e;if("[object String]"===Object.prototype.toString.call(e))return e;if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(e=>WS(e));if("function"==typeof e||"object"==typeof e)return KS(e,e=>WS(e));throw new Error("Data cannot be encoded in JSON: "+e)}function HS(e){if(null==e)return e;if(e["@type"])switch(e["@type"]){case BS:case zS:var t=Number(e.value);if(isNaN(t))throw new Error("Data cannot be decoded from JSON: "+e);return t;default:throw new Error("Data cannot be decoded from JSON: "+e)}return Array.isArray(e)?e.map(e=>HS(e)):"function"==typeof e||"object"==typeof e?KS(e,e=>HS(e)):e}let GS="functions",$S={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 QS extends de{constructor(e,t,r){super(GS+"/"+e,t||""),this.details=r,Object.setPrototypeOf(this,QS.prototype)}}function YS(e,t){let r=(e=>{if(200<=e&&e<300)return"ok";switch(e){case 0:return"internal";case 400:return"invalid-argument";case 401:return"unauthenticated";case 403:return"permission-denied";case 404:return"not-found";case 409:return"aborted";case 429:return"resource-exhausted";case 499:return"cancelled";case 500:return"internal";case 501:return"unimplemented";case 503:return"unavailable";case 504:return"deadline-exceeded"}return"unknown"})(e),n=r,i=void 0;try{var s=t&&t.error;if(s){let e=s.status;if("string"==typeof e){if(!$S[e])return new QS("internal","internal");r=$S[e],n=e}var a=s.message;"string"==typeof a&&(n=a),void 0!==(i=s.details)&&(i=HS(i))}}catch(e){}return"ok"===r?null:new QS(r,n,i)}class JS{constructor(e,t,r,n){this.app=e,this.auth=null,this.messaging=null,this.appCheck=null,this.serverAppAppCheckToken=null,h(e)&&e.settings.appCheckToken&&(this.serverAppAppCheckToken=e.settings.appCheckToken),this.auth=t.getImmediate({optional:!0}),this.messaging=r.getImmediate({optional:!0}),this.auth||t.get().then(e=>this.auth=e,()=>{}),this.messaging||r.get().then(e=>this.messaging=e,()=>{}),this.appCheck||null!=n&&n.get().then(e=>this.appCheck=e,()=>{})}async getAuthToken(){if(this.auth)try{var e=await this.auth.getToken();return null==e?void 0:e.accessToken}catch(e){}}async getMessagingToken(){if(this.messaging&&"Notification"in self&&"granted"===Notification.permission)try{return await this.messaging.getToken()}catch(e){}}async getAppCheckToken(e){var t;return this.serverAppAppCheckToken||(!this.appCheck||(t=e?await this.appCheck.getLimitedUseToken():await this.appCheck.getToken()).error?null:t.token)}async getContext(e){return{authToken:await this.getAuthToken(),messagingToken:await this.getMessagingToken(),appCheckToken:await this.getAppCheckToken(e)}}}let XS="us-central1",ZS=/^data: (.*?)(?:\n|$)/;class eA{constructor(e,t,r,n,i=XS,s=(...e)=>fetch(...e)){this.app=e,this.fetchImpl=s,this.emulatorOrigin=null,this.contextProvider=new JS(e,t,r,n),this.cancelAllRequests=new Promise(e=>{this.deleteService=()=>Promise.resolve(e())});try{var a=new URL(i);this.customDomain=a.origin+("/"===a.pathname?"":a.pathname),this.region=XS}catch(e){this.customDomain=null,this.region=i}}_delete(){return this.deleteService()}_url(e){var t=this.app.options.projectId;return null!==this.emulatorOrigin?`${this.emulatorOrigin}/${t}/${this.region}/`+e:null!==this.customDomain?this.customDomain+"/"+e:`https://${this.region}-${t}.cloudfunctions.net/`+e}}function tA(i,s,a){var e=e=>{return e=e,r=a||{},n=(t=i)._url(s),nA(t,n,e,r);var t,r,n};return e.stream=(e,t)=>{return e=e,t=t,n=(r=i)._url(s),iA(r,n,e,t||{});var r,n},e}async function rA(e,t){var r={},n=await e.contextProvider.getContext(t.limitedUseAppCheckTokens);return n.authToken&&(r.Authorization="Bearer "+n.authToken),n.messagingToken&&(r["Firebase-Instance-ID-Token"]=n.messagingToken),null!==n.appCheckToken&&(r["X-Firebase-AppCheck"]=n.appCheckToken),r}async function nA(e,t,r,n){var i={data:r=WS(r)},s=await rA(e,n),a=(r=>{let n=null;return{promise:new Promise((e,t)=>{n=setTimeout(()=>{t(new QS("deadline-exceeded","deadline-exceeded"))},r)}),cancel:()=>{n&&clearTimeout(n)}}})(n.timeout||7e4),i=await Promise.race([(async(e,t,r,n)=>{r["Content-Type"]="application/json";let i;try{i=await n(e,{method:"POST",body:JSON.stringify(t),headers:r})}catch(e){return{status:0,json:null}}let s=null;try{s=await i.json()}catch(e){}return{status:i.status,json:s}})(t,i,s,e.fetchImpl),a.promise,e.cancelAllRequests]);if(a.cancel(),!i)throw new QS("cancelled","Firebase Functions instance was deleted.");s=YS(i.status,i.json);if(s)throw s;if(!i.json)throw new QS("internal","Response is not valid JSON object.");let o=i.json.data;if(void 0===(o=void 0===o?i.json.result:o))throw new QS("internal","Response is missing data field.");return{data:HS(o)}}async function iA(e,t,r,n){var i={data:r=WS(r)},s=await rA(e,n);s["Content-Type"]="application/json",s.Accept="text/event-stream";let a;try{a=await e.fetchImpl(t,{method:"POST",body:JSON.stringify(i),headers:s,signal:null==n?void 0:n.signal})}catch(e){if(e instanceof Error&&"AbortError"===e.name){let e=new QS("cancelled","Request was cancelled.");return{data:Promise.reject(e),stream:{[Symbol.asyncIterator](){return{next(){return Promise.reject(e)}}}}}}let t=YS(0,null);return{data:Promise.reject(t),stream:{[Symbol.asyncIterator](){return{next(){return Promise.reject(t)}}}}}}let o,l;i=new Promise((e,t)=>{o=e,l=t}),null!=(s=null==n?void 0:n.signal)&&s.addEventListener("abort",()=>{var e=new QS("cancelled","Request was cancelled.");l(e)}),s=a.body.getReader();let h=((a,s,o,l)=>{let h=(e,t)=>{var r=e.match(ZS);if(r){r=r[1];try{var n,i=JSON.parse(r);"result"in i?s(HS(i.result)):"message"in i?t.enqueue(HS(i.message)):"error"in i&&(n=YS(0,i),t.error(n),o(n))}catch(e){e instanceof QS&&(t.error(e),o(e))}}},u=new TextDecoder;return new ReadableStream({start(i){let s="";return async function r(){if(null!=l&&l.aborted){let e=new QS("cancelled","Request was cancelled");return i.error(e),o(e),Promise.resolve()}try{let{value:t,done:e}=await a.read();if(e)s.trim()&&h(s.trim(),i),i.close();else{if(null==l||!l.aborted){let e=(s+=u.decode(t,{stream:!0})).split("\n");s=e.pop()||"";for(var n of e)n.trim()&&h(n.trim(),i);return r()}{let e=new QS("cancelled","Request was cancelled");i.error(e),o(e),void await a.cancel()}}}catch(e){let t=e instanceof QS?e:YS(0,null);i.error(t),o(t)}}()},cancel(){return a.cancel()}})})(s,o,l,null==n?void 0:n.signal);return{stream:{[Symbol.asyncIterator](){let r=h.getReader();return{async next(){var{value:e,done:t}=await r.read();return{value:e,done:t}},async return(){return await r.cancel(),{done:!0,value:void 0}}}}},data:i}}let sA="@firebase/functions";function aA(e,t,r){w(e).emulatorOrigin=`http://${t}:`+r}function oA(e,t,r){return n=w(e),i=t,s=r,(a=e=>nA(n,i,e,s||{})).stream=(e,t)=>iA(n,i,e,t||{}),a;var n,i,s,a}Ct(new u(GS,(e,{instanceIdentifier:t})=>{var r=e.getProvider("app").getImmediate(),n=e.getProvider("auth-internal"),i=e.getProvider("messaging-internal"),s=e.getProvider("app-check-internal");return new eA(r,n,i,s,t)},"PUBLIC").setMultipleInstances(!0)),d(sA,"0.12.2",r),d(sA,"0.12.2","esm2017");var lA,hA,uA;class cA{constructor(e,t){this.app=e,this._delegate=t,this._region=this._delegate.region,this._customDomain=this._delegate.customDomain}httpsCallable(e,t){return tA(w(this._delegate),e,t)}httpsCallableFromURL(e,t){return oA(this._delegate,e,t)}useFunctionsEmulator(e){var t=e.match("[a-zA-Z]+://([a-zA-Z0-9.-]+)(?::([0-9]+))?");if(null==t)throw new de("functions","No origin provided to useFunctionsEmulator()");if(null==t[2])throw new de("functions","Port missing in origin provided to useFunctionsEmulator()");return aA(this._delegate,t[1],Number(t[2]))}useEmulator(e,t){return aA(this._delegate,e,t)}}let dA="us-central1",pA=(e,{instanceIdentifier:t})=>{var r=e.getProvider("app-compat").getImmediate(),n=e.getProvider("functions").getImmediate({identifier:null!=t?t:dA});return new cA(r,n)};Zt={Functions:cA},tr.INTERNAL.registerComponent(new u("functions-compat",pA,"PUBLIC").setServiceProps(Zt).setMultipleInstances(!0)),tr.registerVersion("@firebase/functions-compat","0.3.19");let fA="/firebase-messaging-sw.js",gA="/firebase-cloud-messaging-push-scope",mA="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4",vA="https://fcmregistrations.googleapis.com/v1",_A="google.c.a.c_id",yA="google.c.a.c_l",wA="google.c.a.ts",bA="google.c.a.e",IA=1e4;function TA(e){var t=new Uint8Array(e);return btoa(String.fromCharCode(...t)).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}(KD=lA=lA||{}).PUSH_RECEIVED="push-received",KD.NOTIFICATION_CLICKED="notification-clicked";let EA="fcm_token_details_db",CA=5,kA="fcm_token_object_Store";async function SA(o){if("databases"in indexedDB&&!(await indexedDB.databases()).map(e=>e.name).includes(EA))return null;let l=null;return(await lt(EA,CA,{upgrade:async(e,t,r,n)=>{var i,s,a;t<2||e.objectStoreNames.contains(kA)&&(i=await(a=n.objectStore(kA)).index("fcmSenderId").get(o),await a.clear(),i)&&(2===t?(a=i).auth&&a.p256dh&&a.endpoint&&(l={token:a.fcmToken,createTime:null!=(s=a.createTime)?s:Date.now(),subscriptionOptions:{auth:a.auth,p256dh:a.p256dh,endpoint:a.endpoint,swScope:a.swScope,vapidKey:"string"==typeof a.vapidKey?a.vapidKey:TA(a.vapidKey)}}):3===t?(s=i,l={token:s.fcmToken,createTime:s.createTime,subscriptionOptions:{auth:TA(s.auth),p256dh:TA(s.p256dh),endpoint:s.endpoint,swScope:s.swScope,vapidKey:TA(s.vapidKey)}}):4===t&&(a=i,l={token:a.fcmToken,createTime:a.createTime,subscriptionOptions:{auth:TA(a.auth),p256dh:TA(a.p256dh),endpoint:a.endpoint,swScope:a.swScope,vapidKey:TA(a.vapidKey)}}))}})).close(),await ht(EA),await ht("fcm_vapid_details_db"),await ht("undefined"),(e=>{var t;if(e&&e.subscriptionOptions)return t=e.subscriptionOptions,"number"==typeof e.createTime&&0<e.createTime&&"string"==typeof e.token&&0<e.token.length&&"string"==typeof t.auth&&0<t.auth.length&&"string"==typeof t.p256dh&&0<t.p256dh.length&&"string"==typeof t.endpoint&&0<t.endpoint.length&&"string"==typeof t.swScope&&0<t.swScope.length&&"string"==typeof t.vapidKey&&0<t.vapidKey.length})(l)?l:null}let AA="firebase-messaging-database",NA=1,RA="firebase-messaging-store",PA=null;function DA(){return PA=PA||lt(AA,NA,{upgrade:(e,t)=>{0===t&&e.createObjectStore(RA)}})}async function xA(e){var t=LA(e),t=await(await DA()).transaction(RA).objectStore(RA).get(t);return t||((t=await SA(e.appConfig.senderId))?(await OA(e,t),t):void 0)}async function OA(e,t){var r=LA(e),n=(await DA()).transaction(RA,"readwrite");return await n.objectStore(RA).put(t,r),await n.done,t}function LA({appConfig:e}){return e.appId}let MA=new pe("messaging","Messaging",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"only-available-in-window":"This method is available in a Window context.","only-available-in-sw":"This method is available in a service worker context.","permission-default":"The notification permission was not granted and dismissed instead.","permission-blocked":"The notification permission was not granted and blocked instead.","unsupported-browser":"This browser doesn't support the API's required to use the Firebase SDK.","indexed-db-unsupported":"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)","failed-service-worker-registration":"We are unable to register the default service worker. {$browserErrorMessage}","token-subscribe-failed":"A problem occurred while subscribing the user to FCM: {$errorInfo}","token-subscribe-no-token":"FCM returned no token when subscribing the user to push.","token-unsubscribe-failed":"A problem occurred while unsubscribing the user from FCM: {$errorInfo}","token-update-failed":"A problem occurred while updating the user from FCM: {$errorInfo}","token-update-no-token":"FCM returned no token when updating the user to push.","use-sw-after-get-token":"The useServiceWorker() method may only be called once and must be called before calling getToken() to ensure your service worker is used.","invalid-sw-registration":"The input to useServiceWorker() must be a ServiceWorkerRegistration.","invalid-bg-handler":"The input to setBackgroundMessageHandler() must be a function.","invalid-vapid-key":"The public VAPID key must be a string.","use-vapid-key-after-get-token":"The usePublicVapidKey() method may only be called once and must be called before calling getToken() to ensure your VAPID key is used."});async function FA(e,t){var r={method:"DELETE",headers:await VA(e)};try{var n,i=await(await fetch(UA(e.appConfig)+"/"+t,r)).json();if(i.error)throw n=i.error.message,MA.create("token-unsubscribe-failed",{errorInfo:n})}catch(e){throw MA.create("token-unsubscribe-failed",{errorInfo:null==e?void 0:e.toString()})}}function UA({projectId:e}){return vA+`/projects/${e}/registrations`}async function VA({appConfig:e,installations:t}){var r=await t.getToken();return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e.apiKey,"x-goog-firebase-installations-auth":"FIS "+r})}function qA({p256dh:e,auth:t,endpoint:r,vapidKey:n}){var i={web:{endpoint:r,auth:t,p256dh:e}};return n!==mA&&(i.web.applicationPubKey=n),i}let jA=6048e5;async function BA(e){var t,r,n,i,s,a=await(async(e,t)=>{var r=await e.pushManager.getSubscription();return r||e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:(e=>{var t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/"),r=atob(t),n=new Uint8Array(r.length);for(let i=0;i<r.length;++i)n[i]=r.charCodeAt(i);return n})(t)})})(e.swRegistration,e.vapidKey),a={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:a.endpoint,auth:TA(a.getKey("auth")),p256dh:TA(a.getKey("p256dh"))},o=await xA(e.firebaseDependencies);if(o){if(t=o.subscriptionOptions,r=a.vapidKey===t.vapidKey,n=a.endpoint===t.endpoint,i=a.auth===t.auth,s=a.p256dh===t.p256dh,r&&n&&i&&s)return Date.now()>=o.createTime+jA?(async(e,t)=>{try{var r=await(async(e,t)=>{var r=await VA(e),n=qA(t.subscriptionOptions),r={method:"PATCH",headers:r,body:JSON.stringify(n)};let i;try{var s=await fetch(UA(e.appConfig)+"/"+t.token,r);i=await s.json()}catch(e){throw MA.create("token-update-failed",{errorInfo:null==e?void 0:e.toString()})}if(i.error)throw n=i.error.message,MA.create("token-update-failed",{errorInfo:n});if(i.token)return i.token;throw MA.create("token-update-no-token")})(e.firebaseDependencies,t),n=Object.assign(Object.assign({},t),{token:r,createTime:Date.now()});return await OA(e.firebaseDependencies,n),r}catch(e){throw e}})(e,{token:o.token,createTime:Date.now(),subscriptionOptions:a}):o.token;try{await FA(e.firebaseDependencies,o.token)}catch(e){console.warn(e)}}return KA(e.firebaseDependencies,a)}async function zA(e){var t,r=await xA(e.firebaseDependencies),r=(r&&(await FA(e.firebaseDependencies,r.token),r=LA(e.firebaseDependencies),await(t=(await DA()).transaction(RA,"readwrite")).objectStore(RA).delete(r),await t.done),await e.swRegistration.pushManager.getSubscription());return!r||r.unsubscribe()}async function KA(e,t){var r={token:await(async(e,t)=>{var r=await VA(e),n=qA(t),r={method:"POST",headers:r,body:JSON.stringify(n)};let i;try{var s=await fetch(UA(e.appConfig),r);i=await s.json()}catch(e){throw MA.create("token-subscribe-failed",{errorInfo:null==e?void 0:e.toString()})}if(i.error)throw n=i.error.message,MA.create("token-subscribe-failed",{errorInfo:n});if(i.token)return i.token;throw MA.create("token-subscribe-no-token")})(e,t),createTime:Date.now(),subscriptionOptions:t};return await OA(e,r),r.token}function WA(e){var t,r,n,i,s={from:e.from,collapseKey:e.collapse_key,messageId:e.fcmMessageId};return n=s,(r=e).notification&&(n.notification={},(t=r.notification.title)&&(n.notification.title=t),(t=r.notification.body)&&(n.notification.body=t),(t=r.notification.image)&&(n.notification.image=t),t=r.notification.icon)&&(n.notification.icon=t),r=s,(n=e).data&&(r.data=n.data),r=s,((n=e).fcmOptions||null!=(i=n.notification)&&i.click_action)&&(r.fcmOptions={},(i=null!=(i=null==(i=n.fcmOptions)?void 0:i.link)?i:null==(i=n.notification)?void 0:i.click_action)&&(r.fcmOptions.link=i),i=null==(i=n.fcmOptions)?void 0:i.analytics_label)&&(r.fcmOptions.analyticsLabel=i),s}var HA="AzSCbw63g1R0nCw85jG8",GA="Iaya3yLKwmgvh7cF0q4",$A=[];for(let dx=0;dx<HA.length;dx++)$A.push(HA.charAt(dx)),dx<GA.length&&$A.push(GA.charAt(dx));function QA(e){return MA.create("missing-app-config-values",{valueName:e})}$A.join("");class YA{constructor(e,t,r){this.deliveryMetricsExportedToBigQueryEnabled=!1,this.onBackgroundMessageHandler=null,this.onMessageHandler=null,this.logEvents=[],this.isLogServiceStarted=!1;var n=(e=>{if(!e||!e.options)throw QA("App Configuration Object");if(!e.name)throw QA("App Name");var t,r=e.options;for(t of["projectId","apiKey","appId","messagingSenderId"])if(!r[t])throw QA(t);return{appName:e.name,projectId:r.projectId,apiKey:r.apiKey,appId:r.appId,senderId:r.messagingSenderId}})(e);this.firebaseDependencies={app:e,appConfig:n,installations:t,analyticsProvider:r}}_delete(){return Promise.resolve()}}async function JA(e){try{e.swRegistration=await navigator.serviceWorker.register(fA,{scope:gA}),e.swRegistration.update().catch(()=>{}),t=e.swRegistration,await new Promise((r,e)=>{let n=setTimeout(()=>e(new Error(`Service worker not registered after ${IA} ms`)),IA),i=t.installing||t.waiting;t.active?(clearTimeout(n),r()):i?i.onstatechange=e=>{var t;"activated"===(null==(t=e.target)?void 0:t.state)&&(i.onstatechange=null,clearTimeout(n),r())}:(clearTimeout(n),e(new Error("No incoming service worker found.")))})}catch(e){throw MA.create("failed-service-worker-registration",{browserErrorMessage:null==e?void 0:e.message})}var t}async function XA(e,t){if(!navigator)throw MA.create("only-available-in-window");if("default"===Notification.permission&&await Notification.requestPermission(),"granted"!==Notification.permission)throw MA.create("permission-blocked");n=e,await!((r=null==t?void 0:t.vapidKey)?n.vapidKey=r:n.vapidKey||(n.vapidKey=mA));var r=e,n=null==t?void 0:t.serviceWorkerRegistration;if(n||r.swRegistration||await JA(r),n||!r.swRegistration){if(!(n instanceof ServiceWorkerRegistration))throw MA.create("invalid-sw-registration");r.swRegistration=n}return await 0,BA(e)}async function ZA(e,t,r){var n=(e=>{switch(e){case lA.NOTIFICATION_CLICKED:return"notification_open";case lA.PUSH_RECEIVED:return"notification_foreground";default:throw new Error}})(t);(await e.firebaseDependencies.analyticsProvider.get()).logEvent(n,{message_id:r[_A],message_name:r[yA],message_time:r[wA],message_device_time:Math.floor(Date.now()/1e3)})}async function eN(e,t){var r,n=t.data;n.isFirebaseMessaging&&(e.onMessageHandler&&n.messageType===lA.PUSH_RECEIVED&&("function"==typeof e.onMessageHandler?e.onMessageHandler(WA(n)):e.onMessageHandler.next(WA(n))),"object"==typeof(t=r=n.data))&&t&&_A in t&&"1"===r[bA]&&await ZA(e,n.messageType,r)}let tN="@firebase/messaging",rN="0.12.16",nN=e=>{let t=new YA(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return navigator.serviceWorker.addEventListener("message",e=>eN(t,e)),t},iN=e=>{let t=e.getProvider("messaging").getImmediate();return{getToken:e=>XA(t,e)}};function sN(e){return(async e=>{if(navigator)return e.swRegistration||await JA(e),zA(e);throw MA.create("only-available-in-window")})(e=w(e))}function aN(e,t){var r=e=w(e),e=t;if(navigator)return r.onMessageHandler=e,()=>{r.onMessageHandler=null};throw MA.create("only-available-in-window")}Ct(new u("messaging",nN,"PUBLIC")),Ct(new u("messaging-internal",iN,"PRIVATE")),d(tN,rN),d(tN,rN,"esm2017");let oN="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4",lN="https://fcmregistrations.googleapis.com/v1",hN="FCM_MSG",uN="google.c.a.c_id",cN=3,dN=1;function pN(e){var t=new Uint8Array(e);return btoa(String.fromCharCode(...t)).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}($N=hA=hA||{})[$N.DATA_MESSAGE=1]="DATA_MESSAGE",$N[$N.DISPLAY_NOTIFICATION=3]="DISPLAY_NOTIFICATION",(t=uA=uA||{}).PUSH_RECEIVED="push-received",t.NOTIFICATION_CLICKED="notification-clicked";let fN="fcm_token_details_db",gN=5,mN="fcm_token_object_Store";async function vN(o){if("databases"in indexedDB&&!(await indexedDB.databases()).map(e=>e.name).includes(fN))return null;let l=null;return(await lt(fN,gN,{upgrade:async(e,t,r,n)=>{var i,s,a;t<2||e.objectStoreNames.contains(mN)&&(i=await(a=n.objectStore(mN)).index("fcmSenderId").get(o),await a.clear(),i)&&(2===t?(a=i).auth&&a.p256dh&&a.endpoint&&(l={token:a.fcmToken,createTime:null!=(s=a.createTime)?s:Date.now(),subscriptionOptions:{auth:a.auth,p256dh:a.p256dh,endpoint:a.endpoint,swScope:a.swScope,vapidKey:"string"==typeof a.vapidKey?a.vapidKey:pN(a.vapidKey)}}):3===t?(s=i,l={token:s.fcmToken,createTime:s.createTime,subscriptionOptions:{auth:pN(s.auth),p256dh:pN(s.p256dh),endpoint:s.endpoint,swScope:s.swScope,vapidKey:pN(s.vapidKey)}}):4===t&&(a=i,l={token:a.fcmToken,createTime:a.createTime,subscriptionOptions:{auth:pN(a.auth),p256dh:pN(a.p256dh),endpoint:a.endpoint,swScope:a.swScope,vapidKey:pN(a.vapidKey)}}))}})).close(),await ht(fN),await ht("fcm_vapid_details_db"),await ht("undefined"),(e=>{var t;if(e&&e.subscriptionOptions)return t=e.subscriptionOptions,"number"==typeof e.createTime&&0<e.createTime&&"string"==typeof e.token&&0<e.token.length&&"string"==typeof t.auth&&0<t.auth.length&&"string"==typeof t.p256dh&&0<t.p256dh.length&&"string"==typeof t.endpoint&&0<t.endpoint.length&&"string"==typeof t.swScope&&0<t.swScope.length&&"string"==typeof t.vapidKey&&0<t.vapidKey.length})(l)?l:null}let _N="firebase-messaging-database",yN=1,wN="firebase-messaging-store",bN=null;function IN(){return bN=bN||lt(_N,yN,{upgrade:(e,t)=>{0===t&&e.createObjectStore(wN)}})}async function TN(e){var t=CN(e),t=await(await IN()).transaction(wN).objectStore(wN).get(t);return t||((t=await vN(e.appConfig.senderId))?(await EN(e,t),t):void 0)}async function EN(e,t){var r=CN(e),n=(await IN()).transaction(wN,"readwrite");return await n.objectStore(wN).put(t,r),await n.done,t}function CN({appConfig:e}){return e.appId}let kN=new pe("messaging","Messaging",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"only-available-in-window":"This method is available in a Window context.","only-available-in-sw":"This method is available in a service worker context.","permission-default":"The notification permission was not granted and dismissed instead.","permission-blocked":"The notification permission was not granted and blocked instead.","unsupported-browser":"This browser doesn't support the API's required to use the Firebase SDK.","indexed-db-unsupported":"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)","failed-service-worker-registration":"We are unable to register the default service worker. {$browserErrorMessage}","token-subscribe-failed":"A problem occurred while subscribing the user to FCM: {$errorInfo}","token-subscribe-no-token":"FCM returned no token when subscribing the user to push.","token-unsubscribe-failed":"A problem occurred while unsubscribing the user from FCM: {$errorInfo}","token-update-failed":"A problem occurred while updating the user from FCM: {$errorInfo}","token-update-no-token":"FCM returned no token when updating the user to push.","use-sw-after-get-token":"The useServiceWorker() method may only be called once and must be called before calling getToken() to ensure your service worker is used.","invalid-sw-registration":"The input to useServiceWorker() must be a ServiceWorkerRegistration.","invalid-bg-handler":"The input to setBackgroundMessageHandler() must be a function.","invalid-vapid-key":"The public VAPID key must be a string.","use-vapid-key-after-get-token":"The usePublicVapidKey() method may only be called once and must be called before calling getToken() to ensure your VAPID key is used."});async function SN(e,t){var r={method:"DELETE",headers:await NN(e)};try{var n,i=await(await fetch(AN(e.appConfig)+"/"+t,r)).json();if(i.error)throw n=i.error.message,kN.create("token-unsubscribe-failed",{errorInfo:n})}catch(e){throw kN.create("token-unsubscribe-failed",{errorInfo:null==e?void 0:e.toString()})}}function AN({projectId:e}){return lN+`/projects/${e}/registrations`}async function NN({appConfig:e,installations:t}){var r=await t.getToken();return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e.apiKey,"x-goog-firebase-installations-auth":"FIS "+r})}function RN({p256dh:e,auth:t,endpoint:r,vapidKey:n}){var i={web:{endpoint:r,auth:t,p256dh:e}};return n!==oN&&(i.web.applicationPubKey=n),i}let PN=6048e5;async function DN(e){var t,r,n,i,s,a=await(async(e,t)=>{var r=await e.pushManager.getSubscription();return r||e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:(e=>{var t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/"),r=atob(t),n=new Uint8Array(r.length);for(let i=0;i<r.length;++i)n[i]=r.charCodeAt(i);return n})(t)})})(e.swRegistration,e.vapidKey),a={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:a.endpoint,auth:pN(a.getKey("auth")),p256dh:pN(a.getKey("p256dh"))},o=await TN(e.firebaseDependencies);if(o){if(t=o.subscriptionOptions,r=a.vapidKey===t.vapidKey,n=a.endpoint===t.endpoint,i=a.auth===t.auth,s=a.p256dh===t.p256dh,r&&n&&i&&s)return Date.now()>=o.createTime+PN?(async(e,t)=>{try{var r=await(async(e,t)=>{var r=await NN(e),n=RN(t.subscriptionOptions),r={method:"PATCH",headers:r,body:JSON.stringify(n)};let i;try{var s=await fetch(AN(e.appConfig)+"/"+t.token,r);i=await s.json()}catch(e){throw kN.create("token-update-failed",{errorInfo:null==e?void 0:e.toString()})}if(i.error)throw n=i.error.message,kN.create("token-update-failed",{errorInfo:n});if(i.token)return i.token;throw kN.create("token-update-no-token")})(e.firebaseDependencies,t),n=Object.assign(Object.assign({},t),{token:r,createTime:Date.now()});return await EN(e.firebaseDependencies,n),r}catch(e){throw e}})(e,{token:o.token,createTime:Date.now(),subscriptionOptions:a}):o.token;try{await SN(e.firebaseDependencies,o.token)}catch(e){console.warn(e)}}return ON(e.firebaseDependencies,a)}async function xN(e){var t,r=await TN(e.firebaseDependencies),r=(r&&(await SN(e.firebaseDependencies,r.token),r=CN(e.firebaseDependencies),await(t=(await IN()).transaction(wN,"readwrite")).objectStore(wN).delete(r),await t.done),await e.swRegistration.pushManager.getSubscription());return!r||r.unsubscribe()}async function ON(e,t){var r={token:await(async(e,t)=>{var r=await NN(e),n=RN(t),r={method:"POST",headers:r,body:JSON.stringify(n)};let i;try{var s=await fetch(AN(e.appConfig),r);i=await s.json()}catch(e){throw kN.create("token-subscribe-failed",{errorInfo:null==e?void 0:e.toString()})}if(i.error)throw n=i.error.message,kN.create("token-subscribe-failed",{errorInfo:n});if(i.token)return i.token;throw kN.create("token-subscribe-no-token")})(e,t),createTime:Date.now(),subscriptionOptions:t};return await EN(e,r),r.token}var LN="AzSCbw63g1R0nCw85jG8",MN="Iaya3yLKwmgvh7cF0q4",FN=[];for(let px=0;px<LN.length;px++)FN.push(LN.charAt(px)),px<MN.length&&FN.push(MN.charAt(px));async function UN(e,t){var r=((e,t)=>{var r,n={};return e.from&&(n.project_number=e.from),e.fcmMessageId&&(n.message_id=e.fcmMessageId),n.instance_id=t,n.message_type=(e.notification?hA.DISPLAY_NOTIFICATION:hA.DATA_MESSAGE).toString(),n.sdk_platform=cN.toString(),n.package_name=self.origin.replace(/(^\w+:|^)\/\//,""),e.collapse_key&&(n.collapse_key=e.collapse_key),n.event=dN.toString(),null!=(r=e.fcmOptions)&&r.analytics_label&&(n.analytics_label=null==(r=e.fcmOptions)?void 0:r.analytics_label),n})(t,await e.firebaseDependencies.installations.getId()),n=r,t=t.productId,r={};r.event_time_ms=Math.floor(Date.now()).toString(),r.source_extension_json_proto3=JSON.stringify({messaging_client_event:n}),t&&(r.compliance_data=(e=>({privacy_context:{prequest:{origin_associated_product_id:e}}}))(t)),e.logEvents.push(r)}async function VN(e,t){var r=(({data:e})=>{if(!e)return null;try{return e.json()}catch(e){return null}})(e);if(r){t.deliveryMetricsExportedToBigQueryEnabled&&await UN(t,r);var n,i,s,a=await jN();if(a.some(e=>"visible"===e.visibilityState&&!e.url.startsWith("chrome-extension://"))){var o,e=a,l=r;l.isFirebaseMessaging=!0,l.messageType=uA.PUSH_RECEIVED;for(o of e)o.postMessage(l)}else r.notification&&await(e=>{var t=e.actions,r=Notification.maxActions;return t&&r&&t.length>r&&console.warn(`This browser only supports ${r} actions. The remaining actions will not be displayed.`),self.registration.showNotification(null!=(t=e.title)?t:"",e)})((e=r,(a=Object.assign({},e.notification)).data={[hN]:e},a)),t&&t.onBackgroundMessageHandler&&(a={from:(e=r).from,collapseKey:e.collapse_key,messageId:e.fcmMessageId},i=a,(n=e).notification&&(i.notification={},(r=n.notification.title)&&(i.notification.title=r),(r=n.notification.body)&&(i.notification.body=r),(r=n.notification.image)&&(i.notification.image=r),r=n.notification.icon)&&(i.notification.icon=r),n=a,(i=e).data&&(n.data=i.data),n=a,((i=e).fcmOptions||null!=(s=i.notification)&&s.click_action)&&(n.fcmOptions={},(s=null!=(s=null==(s=i.fcmOptions)?void 0:s.link)?s:null==(s=i.notification)?void 0:s.click_action)&&(n.fcmOptions.link=s),s=null==(s=i.fcmOptions)?void 0:s.analytics_label)&&(n.fcmOptions.analyticsLabel=s),r=a,"function"==typeof t.onBackgroundMessageHandler?await t.onBackgroundMessageHandler(r):t.onBackgroundMessageHandler.next(r))}}async function qN(e){var t=null==(t=null==(t=e.notification)?void 0:t.data)?void 0:t[hN];if(t&&!e.action){e.stopImmediatePropagation(),e.notification.close();var r=(e=>{var t=null!=(t=null==(t=e.fcmOptions)?void 0:t.link)?t:null==(t=e.notification)?void 0:t.click_action;return t||((e=>"object"==typeof e&&e&&uN in e)(e.data)?self.location.origin:null)})(t);if(r){var n,i=new URL(r,self.location.href),s=new URL(self.location.origin);if(i.host===s.host){let e=await(async e=>{var t;for(t of await jN()){var r=new URL(t.url,self.location.href);if(e.host===r.host)return t}return null})(i);if(e?e=await e.focus():(e=await self.clients.openWindow(r),n=3e3,await new Promise(e=>{setTimeout(e,n)})),e)return t.messageType=uA.NOTIFICATION_CLICKED,t.isFirebaseMessaging=!0,e.postMessage(t)}}}}function jN(){return self.clients.matchAll({type:"window",includeUncontrolled:!0})}function BN(e){return kN.create("missing-app-config-values",{valueName:e})}FN.join("");class zN{constructor(e,t,r){this.deliveryMetricsExportedToBigQueryEnabled=!1,this.onBackgroundMessageHandler=null,this.onMessageHandler=null,this.logEvents=[],this.isLogServiceStarted=!1;var n=(e=>{if(!e||!e.options)throw BN("App Configuration Object");if(!e.name)throw BN("App Name");var t,r=e.options;for(t of["projectId","apiKey","appId","messagingSenderId"])if(!r[t])throw BN(t);return{appName:e.name,projectId:r.projectId,apiKey:r.apiKey,appId:r.appId,senderId:r.messagingSenderId}})(e);this.firebaseDependencies={app:e,appConfig:n,installations:t,analyticsProvider:r}}_delete(){return Promise.resolve()}}let KN=e=>{let t=new zN(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return self.addEventListener("push",e=>{e.waitUntil(VN(e,t))}),self.addEventListener("pushsubscriptionchange",e=>{e.waitUntil((async(e,t)=>{var r;(r=e.newSubscription)?(r=await TN(t.firebaseDependencies),await xN(t),t.vapidKey=null!=(r=null==(r=null==r?void 0:r.subscriptionOptions)?void 0:r.vapidKey)?r:oN,await DN(t)):await xN(t)})(e,t))}),self.addEventListener("notificationclick",e=>{e.waitUntil(qN(e))}),t};function WN(e,t){var r=e=w(e),e=t;if(void 0!==self.document)throw kN.create("only-available-in-sw");return r.onBackgroundMessageHandler=e,()=>{r.onBackgroundMessageHandler=null}}Ct(new u("messaging-sw",KN,"PUBLIC"));var HN,GN,$N;class QN{constructor(e,t){this.app=e,this._delegate=t,this.app=e,this._delegate=t}async getToken(e){return(async(e,t)=>XA(e=w(e),t))(this._delegate,e)}async deleteToken(){return sN(this._delegate)}onMessage(e){return aN(this._delegate,e)}onBackgroundMessage(e){return WN(this._delegate,e)}}let YN=e=>self&&"ServiceWorkerGlobalScope"in self?new QN(e.getProvider("app-compat").getImmediate(),e.getProvider("messaging-sw").getImmediate()):new QN(e.getProvider("app-compat").getImmediate(),e.getProvider("messaging").getImmediate()),JN={isSupported:function(){return self&&"ServiceWorkerGlobalScope"in self?he()&&"PushManager"in self&&"Notification"in self&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey"):"undefined"!=typeof window&&he()&&ce()&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window&&"fetch"in window&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey")}};tr.INTERNAL.registerComponent(new u("messaging-compat",YN,"PUBLIC").setServiceProps(JN)),tr.registerVersion("@firebase/messaging-compat","0.2.16");let XN="firebasestorage.googleapis.com",ZN="storageBucket";class eR extends de{constructor(e,t,r=0){super(tR(e),`Firebase Storage: ${t} (${tR(e)})`),this.status_=r,this.customData={serverResponse:null},this._baseMessage=this.message,Object.setPrototypeOf(this,eR.prototype)}get status(){return this.status_}set status(e){this.status_=e}_codeEquals(e){return tR(e)===this.code}get serverResponse(){return this.customData.serverResponse}set serverResponse(e){this.customData.serverResponse=e,this.customData.serverResponse?this.message=this._baseMessage+`
|
|
17
|
+
`+this.customData.serverResponse:this.message=this._baseMessage}}function tR(e){return"storage/"+e}function rR(){return new eR(HN.UNKNOWN,"An unknown error occurred, please check the error payload for server response.")}function nR(){return new eR(HN.RETRY_LIMIT_EXCEEDED,"Max retry time for operation exceeded, please try again.")}function iR(){return new eR(HN.CANCELED,"User canceled the upload/download.")}function sR(){return new eR(HN.CANNOT_SLICE_BLOB,"Cannot slice blob for upload. Please retry the upload.")}function aR(e){return new eR(HN.INVALID_ARGUMENT,e)}function oR(){return new eR(HN.APP_DELETED,"The Firebase app was deleted.")}function lR(e){return new eR(HN.INVALID_ROOT_OPERATION,"The operation '"+e+"' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').")}function hR(e,t){return new eR(HN.INVALID_FORMAT,"String does not match format '"+e+"': "+t)}function uR(e){throw new eR(HN.INTERNAL_ERROR,"Internal error: "+e)}(r=HN=HN||{}).UNKNOWN="unknown",r.OBJECT_NOT_FOUND="object-not-found",r.BUCKET_NOT_FOUND="bucket-not-found",r.PROJECT_NOT_FOUND="project-not-found",r.QUOTA_EXCEEDED="quota-exceeded",r.UNAUTHENTICATED="unauthenticated",r.UNAUTHORIZED="unauthorized",r.UNAUTHORIZED_APP="unauthorized-app",r.RETRY_LIMIT_EXCEEDED="retry-limit-exceeded",r.INVALID_CHECKSUM="invalid-checksum",r.CANCELED="canceled",r.INVALID_EVENT_NAME="invalid-event-name",r.INVALID_URL="invalid-url",r.INVALID_DEFAULT_BUCKET="invalid-default-bucket",r.NO_DEFAULT_BUCKET="no-default-bucket",r.CANNOT_SLICE_BLOB="cannot-slice-blob",r.SERVER_FILE_WRONG_SIZE="server-file-wrong-size",r.NO_DOWNLOAD_URL="no-download-url",r.INVALID_ARGUMENT="invalid-argument",r.INVALID_ARGUMENT_COUNT="invalid-argument-count",r.APP_DELETED="app-deleted",r.INVALID_ROOT_OPERATION="invalid-root-operation",r.INVALID_FORMAT="invalid-format",r.INTERNAL_ERROR="internal-error",r.UNSUPPORTED_ENVIRONMENT="unsupported-environment";class cR{constructor(e,t){this.bucket=e,this.path_=t}get path(){return this.path_}get isRoot(){return 0===this.path.length}fullServerUrl(){var e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o/"+e(this.path)}bucketOnlyServerUrl(){return"/b/"+encodeURIComponent(this.bucket)+"/o"}static makeFromBucketSpec(t,e){let r;try{r=cR.makeFromUrl(t,e)}catch(e){return new cR(t,"")}if(""===r.path)return r;throw e=t,new eR(HN.INVALID_DEFAULT_BUCKET,"Invalid default bucket '"+e+"'.")}static makeFromUrl(e,t){let r=null;var n="([A-Za-z0-9.\\-_]+)";var i=new RegExp("^gs://"+n+"(/(.*))?$","i");function s(e){e.path_=decodeURIComponent(e.path)}var a=t.replace(/[.]/g,"\\."),a=new RegExp(`^https?://${a}/v[A-Za-z0-9_]+/b/${n}/o(/([^?#]*).*)?$`,"i"),o=t===XN?"(?:storage.googleapis.com|storage.cloud.google.com)":t,l=[{regex:i,indices:{bucket:1,path:3},postModify:function(e){"/"===e.path.charAt(e.path.length-1)&&(e.path_=e.path_.slice(0,-1))}},{regex:a,indices:{bucket:1,path:3},postModify:s},{regex:new RegExp(`^https?://${o}/${n}/([^?#]*)`,"i"),indices:{bucket:1,path:2},postModify:s}];for(let d=0;d<l.length;d++){var h=l[d],u=h.regex.exec(e);if(u){var c=u[h.indices.bucket];let e=u[h.indices.path];e=e||"",r=new cR(c,e),h.postModify(r);break}}if(null==r)throw t=e,new eR(HN.INVALID_URL,"Invalid URL '"+t+"'.");return r}}class dR{constructor(e){this.promise_=Promise.reject(e)}getPromise(){return this.promise_}cancel(e=0){}}function pR(e){return"string"==typeof e||e instanceof String}function fR(e){return gR()&&e instanceof Blob}function gR(){return"undefined"!=typeof Blob}function mR(e,t,r,n){if(n<t)throw aR(`Invalid value for '${e}'. Expected ${t} or greater.`);if(r<n)throw aR(`Invalid value for '${e}'. Expected ${r} or less.`)}function vR(e,t,r){let n=null==r?"https://"+t:t;return`${r}://${n}/v0`+e}function _R(e){var t,r,n=encodeURIComponent;let i="?";for(t in e)e.hasOwnProperty(t)&&(r=n(t)+"="+n(e[t]),i=i+r+"&");return i=i.slice(0,-1)}function yR(e,t){var r=500<=e&&e<600,n=-1!==[408,429].indexOf(e),i=-1!==t.indexOf(e);return r||n||i}(KD=GN=GN||{})[KD.NO_ERROR=0]="NO_ERROR",KD[KD.NETWORK_ERROR=1]="NETWORK_ERROR",KD[KD.ABORT=2]="ABORT";class wR{constructor(e,t,r,n,i,s,a,o,l,h,u,c=!0){this.url_=e,this.method_=t,this.headers_=r,this.body_=n,this.successCodes_=i,this.additionalRetryCodes_=s,this.callback_=a,this.errorCallback_=o,this.timeout_=l,this.progressCallback_=h,this.connectionFactory_=u,this.retry=c,this.pendingConnection_=null,this.backoffId_=null,this.canceled_=!1,this.appDelete_=!1,this.promise_=new Promise((e,t)=>{this.resolve_=e,this.reject_=t,this.start_()})}start_(){var e=(i,e)=>{if(e)i(!1,new bR(!1,null,!0));else{let r=this.connectionFactory_(),n=(this.pendingConnection_=r,e=>{var t=e.loaded,r=e.lengthComputable?e.total:-1;null!==this.progressCallback_&&this.progressCallback_(t,r)});null!==this.progressCallback_&&r.addUploadProgressListener(n),r.send(this.url_,this.method_,this.body_,this.headers_).then(()=>{null!==this.progressCallback_&&r.removeUploadProgressListener(n),this.pendingConnection_=null;var e=r.getErrorCode()===GN.NO_ERROR,t=r.getStatus();!e||yR(t,this.additionalRetryCodes_)&&this.retry?(e=r.getErrorCode()===GN.ABORT,i(!1,new bR(!1,null,e))):(e=-1!==this.successCodes_.indexOf(t),i(!0,new bR(e,r)))})}},t=(e,t)=>{var r=this.resolve_,n=this.reject_,i=t.connection;if(t.wasSuccessCode)try{var s=this.callback_(i,i.getResponse());void 0!==s?r(s):r()}catch(e){n(e)}else null!==i?((s=rR()).serverResponse=i.getErrorText(),this.errorCallback_?n(this.errorCallback_(i,s)):n(s)):t.canceled?n((this.appDelete_?oR:iR)()):n(nR())};this.canceled_?t(0,new bR(!1,null,!0)):this.backoffId_=((t,r,e)=>{let n=1,i=null,s=null,a=!1,o=0;function l(){return 2===o}let h=!1;function u(...e){h||(h=!0,r.apply(null,e))}function c(e){i=setTimeout(()=>{i=null,t(p,l())},e)}function d(){s&&clearTimeout(s)}function p(e,...t){if(h)d();else if(e)d(),u.call(null,e,...t);else if(l()||a)d(),u.call(null,e,...t);else{n<64&&(n*=2);let e;c(e=1===o?(o=2,0):1e3*(n+Math.random()))}}let f=!1;function g(e){f||(f=!0,d(),h)||(null!==i?(e||(o=2),clearTimeout(i),c(0)):e||(o=1))}return c(0),s=setTimeout(()=>{g(a=!0)},e),g})(e,t,this.timeout_)}getPromise(){return this.promise_}cancel(e){this.canceled_=!0,this.appDelete_=e||!1,null!==this.backoffId_&&(0,this.backoffId_)(!1),null!==this.pendingConnection_&&this.pendingConnection_.abort()}}class bR{constructor(e,t,r){this.wasSuccessCode=e,this.connection=t,this.canceled=!!r}}function IR(...t){var r="undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:void 0;if(void 0!==r){var n=new r;for(let e=0;e<t.length;e++)n.append(t[e]);return n.getBlob()}if(gR())return new Blob(t);throw new eR(HN.UNSUPPORTED_ENVIRONMENT,"This browser doesn't seem to support creating Blobs")}function TR(e){if("undefined"==typeof atob)throw new eR(HN.UNSUPPORTED_ENVIRONMENT,"base-64 is missing. Make sure to install the required polyfills. See https://firebase.google.com/docs/web/environments-js-sdk#polyfills for more information.");return atob(e)}let ER={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"};class CR{constructor(e,t){this.data=e,this.contentType=t||null}}function kR(e,t){switch(e){case ER.RAW:return new CR(SR(t));case ER.BASE64:case ER.BASE64URL:return new CR(AR(e,t));case ER.DATA_URL:return new CR((r=t,(n=new NR(r)).base64?AR(ER.BASE64,n.rest):(e=>{let t;try{t=decodeURIComponent(e)}catch(e){throw hR(ER.DATA_URL,"Malformed data URL.")}return SR(t)})(n.rest)),(r=t,new NR(r).contentType))}var r,n;throw rR()}function SR(t){var r,n,i=[];for(let s=0;s<t.length;s++){let e=t.charCodeAt(s);e<=127?i.push(e):e<=2047?i.push(192|e>>6,128|63&e):55296==(64512&e)?s<t.length-1&&56320==(64512&t.charCodeAt(s+1))?(r=e,n=t.charCodeAt(++s),e=65536|(1023&r)<<10|1023&n,i.push(240|e>>18,128|e>>12&63,128|e>>6&63,128|63&e)):i.push(239,191,189):56320==(64512&e)?i.push(239,191,189):i.push(224|e>>12,128|e>>6&63,128|63&e)}return new Uint8Array(i)}function AR(t,e){switch(t){case ER.BASE64:var r=-1!==e.indexOf("-"),n=-1!==e.indexOf("_");if(r||n)throw hR(t,"Invalid character '"+(r?"-":"_")+"' found: is it base64url encoded?");break;case ER.BASE64URL:n=-1!==e.indexOf("+"),r=-1!==e.indexOf("/");if(n||r)throw hR(t,"Invalid character '"+(n?"+":"/")+"' found: is it base64 encoded?");e=e.replace(/-/g,"+").replace(/_/g,"/")}let i;try{i=TR(e)}catch(e){if(e.message.includes("polyfill"))throw e;throw hR(t,"Invalid character found")}var s=new Uint8Array(i.length);for(let a=0;a<i.length;a++)s[a]=i.charCodeAt(a);return s}class NR{constructor(e){this.base64=!1,this.contentType=null;var t=e.match(/^data:([^,]+)?,/);if(null===t)throw hR(ER.DATA_URL,"Must be formatted 'data:[<mediatype>][;base64],<data>");var r,n,t=t[1]||null;null!=t&&(this.base64=(n=";base64",(r=t).length>=n.length&&r.substring(r.length-n.length)===n),this.contentType=this.base64?t.substring(0,t.length-";base64".length):t),this.rest=e.substring(e.indexOf(",")+1)}}class RR{constructor(e,t){let r=0,n="";fR(e)?(this.data_=e,r=e.size,n=e.type):e instanceof ArrayBuffer?(t?this.data_=new Uint8Array(e):(this.data_=new Uint8Array(e.byteLength),this.data_.set(new Uint8Array(e))),r=this.data_.length):e instanceof Uint8Array&&(t?this.data_=e:(this.data_=new Uint8Array(e.length),this.data_.set(e)),r=e.length),this.size_=r,this.type_=n}size(){return this.size_}type(){return this.type_}slice(e,t){var r,n,i,s;return fR(this.data_)?(r=this.data_,i=e,s=t,null===(r=(n=r).webkitSlice?n.webkitSlice(i,s):n.mozSlice?n.mozSlice(i,s):n.slice?n.slice(i,s):null)?null:new RR(r)):(r=new Uint8Array(this.data_.buffer,e,t-e),new RR(r,!0))}static getBlob(...e){if(gR())return i=e.map(e=>e instanceof RR?e.data_:e),new RR(IR.apply(null,i));{var i=e.map(e=>pR(e)?kR(ER.RAW,e).data:e.data_);let t=0,r=(i.forEach(e=>{t+=e.byteLength}),new Uint8Array(t)),n=0;return i.forEach(e=>{for(let t=0;t<e.length;t++)r[n++]=e[t]}),new RR(r,!0)}}uploadData(){return this.data_}}function PR(e){let t;try{t=JSON.parse(e)}catch(e){return null}return"object"!=typeof(e=t)||Array.isArray(e)?null:t}function DR(e){var t=e.lastIndexOf("/",e.length-2);return-1===t?e:e.slice(t+1)}function xR(e,t){return t}class OR{constructor(e,t,r,n){this.server=e,this.local=t||e,this.writable=!!r,this.xform=n||xR}}let LR=null;function MR(){var e,t;return LR||((e=[]).push(new OR("bucket")),e.push(new OR("generation")),e.push(new OR("metageneration")),e.push(new OR("name","fullPath",!0)),(t=new OR("name")).xform=function(e,t){return!pR(t=t)||t.length<2?t:DR(t)},e.push(t),(t=new OR("size")).xform=function(e,t){return void 0!==t?Number(t):t},e.push(t),e.push(new OR("timeCreated")),e.push(new OR("updated")),e.push(new OR("md5Hash",null,!0)),e.push(new OR("cacheControl",null,!0)),e.push(new OR("contentDisposition",null,!0)),e.push(new OR("contentEncoding",null,!0)),e.push(new OR("contentLanguage",null,!0)),e.push(new OR("contentType",null,!0)),e.push(new OR("metadata","customMetadata",!0)),LR=e),LR}function FR(r,n){Object.defineProperty(r,"ref",{get:function(){var e=r.bucket,t=r.fullPath,e=new cR(e,t);return n._makeStorageReference(e)}})}function UR(e,t,r){var n=PR(t);if(null===n)return null;var t=e,i=n,s=r,a={type:"file"},o=s.length;for(let h=0;h<o;h++){var l=s[h];a[l.local]=l.xform(a,i[l.server])}return FR(a,t),a}function VR(e,t){var r={},n=t.length;for(let s=0;s<n;s++){var i=t[s];i.writable&&(r[i.server]=e[i.local])}return JSON.stringify(r)}let qR="prefixes",jR="items";function BR(e,t,r){var n=PR(r);if(null===n)return null;var i=e,s=t,r=n,a={prefixes:[],items:[],nextPageToken:r.nextPageToken};if(r[qR])for(var o of r[qR]){o=o.replace(/\/$/,""),o=i._makeStorageReference(new cR(s,o));a.prefixes.push(o)}if(r[jR])for(var l of r[jR]){l=i._makeStorageReference(new cR(s,l.name));a.items.push(l)}return a}class zR{constructor(e,t,r,n){this.url=e,this.method=t,this.handler=r,this.timeout=n,this.urlParams={},this.headers={},this.body=null,this.errorHandler=null,this.progressCallback=null,this.successCodes=[200],this.additionalRetryCodes=[]}}function KR(e){if(!e)throw rR()}function WR(n,i){return function(e,t){var r=UR(n,t,i);return KR(null!==r),r}}function HR(n,i){return function(e,t){var r=BR(n,i,t);return KR(null!==r),r}}function GR(o,n){return function(e,t){var r=UR(o,t,n);KR(null!==r);{var i=r,s=o.host,a=o._protocol;if(null===(r=PR(t)))return null;if(!pR(r.downloadTokens))return null;if(0===(r=r.downloadTokens).length)return null;let n=encodeURIComponent;return r.split(",").map(e=>{var t=i.bucket,r=i.fullPath;return vR("/b/"+n(t)+"/o/"+n(r),s,a)+_R({alt:"media",token:e})})[0]}}}function $R(i){return function(e,t){let r;var n;return(r=401===e.getStatus()?e.getErrorText().includes("Firebase App Check token is invalid")?new eR(HN.UNAUTHORIZED_APP,"This app does not have permission to access Firebase Storage on this project."):new eR(HN.UNAUTHENTICATED,"User is not authenticated, please authenticate using Firebase Authentication and try again."):402===e.getStatus()?(n=i.bucket,new eR(HN.QUOTA_EXCEEDED,"Quota for bucket '"+n+"' exceeded, please view quota on https://firebase.google.com/pricing/.")):403===e.getStatus()?(n=i.path,new eR(HN.UNAUTHORIZED,"User does not have permission to access '"+n+"'.")):t).status=e.getStatus(),r.serverResponse=t.serverResponse,r}}function QR(n){let i=$R(n);return function(e,t){let r=i(e,t);return(r=404===e.getStatus()?(e=n.path,new eR(HN.OBJECT_NOT_FOUND,"Object '"+e+"' does not exist.")):r).serverResponse=t.serverResponse,r}}function YR(e,t,r){var n=vR(t.fullServerUrl(),e.host,e._protocol),i=e.maxOperationRetryTime,n=new zR(n,"GET",WR(e,r),i);return n.errorHandler=QR(t),n}function JR(e,t,r){var n=Object.assign({},r);return n.fullPath=e.path,n.size=t.size(),n.contentType||(n.contentType=(r=t,(e=null)&&e.contentType||r&&r.type()||"application/octet-stream")),n}function XR(e,t,r,n,i){var s=t.bucketOnlyServerUrl(),a={"X-Goog-Upload-Protocol":"multipart"};var o=(()=>{let e="";for(let t=0;t<2;t++)e+=Math.random().toString().slice(2);return e})(),l=(a["Content-Type"]="multipart/related; boundary="+o,JR(t,n,i)),h="--"+o+"\r\nContent-Type: application/json; charset=utf-8\r\n\r\n"+VR(l,r)+"\r\n--"+o+"\r\nContent-Type: "+l.contentType+"\r\n\r\n",o="\r\n--"+o+"--",h=RR.getBlob(h,n,o);if(null===h)throw sR();o={name:l.fullPath},l=vR(s,e.host,e._protocol),s=e.maxUploadRetryTime,l=new zR(l,"POST",WR(e,r),s);return l.urlParams=o,l.headers=a,l.body=h.uploadData(),l.errorHandler=$R(t),l}class ZR{constructor(e,t,r,n){this.current=e,this.total=t,this.finalized=!!r,this.metadata=n||null}}function eP(e,t){let r=null;try{r=e.getResponseHeader("X-Goog-Upload-Status")}catch(e){KR(!1)}return KR(!!r&&-1!==(t||["active"]).indexOf(r)),r}function tP(e,t,r,n,i){var s=t.bucketOnlyServerUrl(),a=JR(t,n,i),o={name:a.fullPath},s=vR(s,e.host,e._protocol),l={"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":""+n.size(),"X-Goog-Upload-Header-Content-Type":a.contentType,"Content-Type":"application/json; charset=utf-8"},a=VR(a,r),h=e.maxUploadRetryTime;s=new zR(s,"POST",function(e){eP(e);let t;try{t=e.getResponseHeader("X-Goog-Upload-URL")}catch(e){KR(!1)}return KR(pR(t)),t},h);return s.urlParams=o,s.headers=l,s.body=a,s.errorHandler=$R(t),s}function rP(e,t,r,i){var n=e.maxUploadRetryTime,n=new zR(r,"POST",function(e){var t=eP(e,["active","final"]);let r=null;try{r=e.getResponseHeader("X-Goog-Upload-Size-Received")}catch(e){KR(!1)}r||KR(!1);var n=Number(r);return KR(!isNaN(n)),new ZR(n,i.size(),"final"===t)},n);return n.headers={"X-Goog-Upload-Command":"query"},n.errorHandler=$R(t),n}function nP(e,a,t,o,r,l,n,i){let h=new ZR(0,0);if(n?(h.current=n.current,h.total=n.total):(h.current=0,h.total=o.size()),o.size()!==h.total)throw new eR(HN.SERVER_FILE_WRONG_SIZE,"Server recorded incorrect upload file size, please retry the upload.");var s=h.total-h.current;let u=s;0<r&&(u=Math.min(u,r));var c=h.current,d=c+u;let p="";s={"X-Goog-Upload-Command":p=0===u?"finalize":s===u?"upload, finalize":"upload","X-Goog-Upload-Offset":""+h.current},c=o.slice(c,d);if(null===c)throw sR();d=a.maxUploadRetryTime,d=new zR(t,"POST",function(e,t){var r=eP(e,["active","final"]),n=h.current+u,i=o.size();let s;return s="final"===r?WR(a,l)(e,t):null,new ZR(n,i,"final"===r,s)},d);return d.headers=s,d.body=c.uploadData(),d.progressCallback=i||null,d.errorHandler=$R(e),d}let iP={STATE_CHANGED:"state_changed"},sP={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function aP(e){switch(e){case"running":case"pausing":case"canceling":return sP.RUNNING;case"paused":return sP.PAUSED;case"success":return sP.SUCCESS;case"canceled":return sP.CANCELED;default:return sP.ERROR}}class oP{constructor(e,t,r){var n;"function"==typeof e||null!=t||null!=r?(this.next=e,this.error=null!=t?t:void 0,this.complete=null!=r?r:void 0):(this.next=(n=e).next,this.error=n.error,this.complete=n.complete)}}function lP(t){return(...e)=>{Promise.resolve().then(()=>t(...e))}}class hP extends class{constructor(){this.sent_=!1,this.xhr_=new XMLHttpRequest,this.initXhr(),this.errorCode_=GN.NO_ERROR,this.sendPromise_=new Promise(e=>{this.xhr_.addEventListener("abort",()=>{this.errorCode_=GN.ABORT,e()}),this.xhr_.addEventListener("error",()=>{this.errorCode_=GN.NETWORK_ERROR,e()}),this.xhr_.addEventListener("load",()=>{e()})})}send(e,t,r,n){if(this.sent_)throw uR("cannot .send() more than once");if(this.sent_=!0,this.xhr_.open(t,e,!0),void 0!==n)for(var i in n)n.hasOwnProperty(i)&&this.xhr_.setRequestHeader(i,n[i].toString());return void 0!==r?this.xhr_.send(r):this.xhr_.send(),this.sendPromise_}getErrorCode(){if(this.sent_)return this.errorCode_;throw uR("cannot .getErrorCode() before sending")}getStatus(){if(!this.sent_)throw uR("cannot .getStatus() before sending");try{return this.xhr_.status}catch(e){return-1}}getResponse(){if(this.sent_)return this.xhr_.response;throw uR("cannot .getResponse() before sending")}getErrorText(){if(this.sent_)return this.xhr_.statusText;throw uR("cannot .getErrorText() before sending")}abort(){this.xhr_.abort()}getResponseHeader(e){return this.xhr_.getResponseHeader(e)}addUploadProgressListener(e){null!=this.xhr_.upload&&this.xhr_.upload.addEventListener("progress",e)}removeUploadProgressListener(e){null!=this.xhr_.upload&&this.xhr_.upload.removeEventListener("progress",e)}}{initXhr(){this.xhr_.responseType="text"}}function uP(){return new hP}class cP{isExponentialBackoffExpired(){return this.sleepTime>this.maxSleepTime}constructor(e,t,r=null){this._transferred=0,this._needToFetchStatus=!1,this._needToFetchMetadata=!1,this._observers=[],this._error=void 0,this._uploadUrl=void 0,this._request=void 0,this._chunkMultiplier=1,this._resolve=void 0,this._reject=void 0,this._ref=e,this._blob=t,this._metadata=r,this._mappings=MR(),this._resumable=this._shouldDoResumable(this._blob),this._state="running",this._errorHandler=e=>{if(this._request=void 0,this._chunkMultiplier=1,e._codeEquals(HN.CANCELED))this._needToFetchStatus=!0,this.completeTransitions_();else{var t=this.isExponentialBackoffExpired();if(yR(e.status,[])){if(!t)return this.sleepTime=Math.max(2*this.sleepTime,1e3),this._needToFetchStatus=!0,void this.completeTransitions_();e=nR()}this._error=e,this._transition("error")}},this._metadataErrorHandler=e=>{this._request=void 0,e._codeEquals(HN.CANCELED)?this.completeTransitions_():(this._error=e,this._transition("error"))},this.sleepTime=0,this.maxSleepTime=this._ref.storage.maxUploadRetryTime,this._promise=new Promise((e,t)=>{this._resolve=e,this._reject=t,this._start()}),this._promise.then(null,()=>{})}_makeProgressCallback(){let t=this._transferred;return e=>this._updateProgress(t+e)}_shouldDoResumable(e){return 262144<e.size()}_start(){"running"===this._state&&void 0===this._request&&(this._resumable?void 0===this._uploadUrl?this._createResumable():this._needToFetchStatus?this._fetchStatus():this._needToFetchMetadata?this._fetchMetadata():this.pendingTimeout=setTimeout(()=>{this.pendingTimeout=void 0,this._continueUpload()},this.sleepTime):this._oneShotUpload())}_resolveToken(r){Promise.all([this._ref.storage._getAuthToken(),this._ref.storage._getAppCheckToken()]).then(([e,t])=>{switch(this._state){case"running":r(e,t);break;case"canceling":this._transition("canceled");break;case"pausing":this._transition("paused")}})}_createResumable(){this._resolveToken((e,t)=>{var r=tP(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),r=this._ref.storage._makeRequest(r,uP,e,t);(this._request=r).getPromise().then(e=>{this._request=void 0,this._uploadUrl=e,this._needToFetchStatus=!1,this.completeTransitions_()},this._errorHandler)})}_fetchStatus(){let n=this._uploadUrl;this._resolveToken((e,t)=>{var r=rP(this._ref.storage,this._ref._location,n,this._blob),r=this._ref.storage._makeRequest(r,uP,e,t);(this._request=r).getPromise().then(e=>{this._request=void 0,this._updateProgress(e.current),this._needToFetchStatus=!1,e.finalized&&(this._needToFetchMetadata=!0),this.completeTransitions_()},this._errorHandler)})}_continueUpload(){let i=262144*this._chunkMultiplier,s=new ZR(this._transferred,this._blob.size()),a=this._uploadUrl;this._resolveToken((e,t)=>{let r;try{r=nP(this._ref._location,this._ref.storage,a,this._blob,i,this._mappings,s,this._makeProgressCallback())}catch(e){return this._error=e,void this._transition("error")}var n=this._ref.storage._makeRequest(r,uP,e,t,!1);(this._request=n).getPromise().then(e=>{this._increaseMultiplier(),this._request=void 0,this._updateProgress(e.current),e.finalized?(this._metadata=e.metadata,this._transition("success")):this.completeTransitions_()},this._errorHandler)})}_increaseMultiplier(){2*(262144*this._chunkMultiplier)<33554432&&(this._chunkMultiplier*=2)}_fetchMetadata(){this._resolveToken((e,t)=>{var r=YR(this._ref.storage,this._ref._location,this._mappings),r=this._ref.storage._makeRequest(r,uP,e,t);(this._request=r).getPromise().then(e=>{this._request=void 0,this._metadata=e,this._transition("success")},this._metadataErrorHandler)})}_oneShotUpload(){this._resolveToken((e,t)=>{var r=XR(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),r=this._ref.storage._makeRequest(r,uP,e,t);(this._request=r).getPromise().then(e=>{this._request=void 0,this._metadata=e,this._updateProgress(this._blob.size()),this._transition("success")},this._errorHandler)})}_updateProgress(e){var t=this._transferred;this._transferred=e,this._transferred!==t&&this._notifyObservers()}_transition(e){if(this._state!==e)switch(e){case"canceling":case"pausing":this._state=e,void 0!==this._request?this._request.cancel():this.pendingTimeout&&(clearTimeout(this.pendingTimeout),this.pendingTimeout=void 0,this.completeTransitions_());break;case"running":var t="paused"===this._state;this._state=e,t&&(this._notifyObservers(),this._start());break;case"paused":this._state=e,this._notifyObservers();break;case"canceled":this._error=iR(),this._state=e,this._notifyObservers();break;case"error":case"success":this._state=e,this._notifyObservers()}}completeTransitions_(){switch(this._state){case"pausing":this._transition("paused");break;case"canceling":this._transition("canceled");break;case"running":this._start()}}get snapshot(){var e=aP(this._state);return{bytesTransferred:this._transferred,totalBytes:this._blob.size(),state:e,metadata:this._metadata,task:this,ref:this._ref}}on(e,t,r,n){let i=new oP(t||void 0,r||void 0,n||void 0);return this._addObserver(i),()=>{this._removeObserver(i)}}then(e,t){return this._promise.then(e,t)}catch(e){return this.then(null,e)}_addObserver(e){this._observers.push(e),this._notifyObserver(e)}_removeObserver(e){var t=this._observers.indexOf(e);-1!==t&&this._observers.splice(t,1)}_notifyObservers(){this._finishPromise(),this._observers.slice().forEach(e=>{this._notifyObserver(e)})}_finishPromise(){if(void 0!==this._resolve){let e=!0;switch(aP(this._state)){case sP.SUCCESS:lP(this._resolve.bind(null,this.snapshot))();break;case sP.CANCELED:case sP.ERROR:lP(this._reject.bind(null,this._error))();break;default:e=!1}e&&(this._resolve=void 0,this._reject=void 0)}}_notifyObserver(e){switch(aP(this._state)){case sP.RUNNING:case sP.PAUSED:e.next&&lP(e.next.bind(e,this.snapshot))();break;case sP.SUCCESS:e.complete&&lP(e.complete.bind(e))();break;case sP.CANCELED:case sP.ERROR:default:e.error&&lP(e.error.bind(e,this._error))()}}resume(){var e="paused"===this._state||"pausing"===this._state;return e&&this._transition("running"),e}pause(){var e="running"===this._state;return e&&this._transition("pausing"),e}cancel(){var e="running"===this._state||"pausing"===this._state;return e&&this._transition("canceling"),e}}class dP{constructor(e,t){this._service=e,t instanceof cR?this._location=t:this._location=cR.makeFromUrl(t,e.host)}toString(){return"gs://"+this._location.bucket+"/"+this._location.path}_newRef(e,t){return new dP(e,t)}get root(){var e=new cR(this._location.bucket,"");return this._newRef(this._service,e)}get bucket(){return this._location.bucket}get fullPath(){return this._location.path}get name(){return DR(this._location.path)}get storage(){return this._service}get parent(){var e,t,r=0===(e=this._location.path).length?null:-1===(r=e.lastIndexOf("/"))?"":e.slice(0,r);return null===r?null:(t=new cR(this._location.bucket,r),new dP(this._service,t))}_throwIfRoot(e){if(""===this._location.path)throw lR(e)}}function pP(e){let t={prefixes:[],items:[]};return async function e(t,r,n){let i={pageToken:n};let s=await fP(t,i);r.prefixes.push(...s.prefixes);r.items.push(...s.items);null!=s.nextPageToken&&await e(t,r,s.nextPageToken)}(e,t).then(()=>t)}function fP(e,t){null!=t&&"number"==typeof t.maxResults&&mR("options.maxResults",1,1e3,t.maxResults);var r,n,i,s,a,o=t||{},l=(t=e.storage,r=e._location,n="/",i=o.pageToken,s=o.maxResults,o={},r.isRoot?o.prefix="":o.prefix=r.path+"/",n&&0<n.length&&(o.delimiter=n),i&&(o.pageToken=i),s&&(o.maxResults=s),a=vR(a=r.bucketOnlyServerUrl(),t.host,t._protocol),l=t.maxOperationRetryTime,(a=new zR(a,"GET",HR(t,r.bucket),l)).urlParams=o,a.errorHandler=$R(r),a);return e.storage.makeRequestWithTokens(l,uP)}function gP(e,t){e._throwIfRoot("updateMetadata");r=e.storage,n=e._location,t=t,i=MR(),s=vR(n.fullServerUrl(),r.host,r._protocol),a=VR(t,i),o=r.maxOperationRetryTime,(s=new zR(s,"PATCH",WR(r,i),o)).headers={"Content-Type":"application/json; charset=utf-8"},s.body=a,s.errorHandler=QR(n);var r,n,i,s,a,o=s;return e.storage.makeRequestWithTokens(o,uP)}function mP(e){e._throwIfRoot("getDownloadURL");t=e.storage,r=e._location,n=MR(),i=vR(r.fullServerUrl(),t.host,t._protocol),s=t.maxOperationRetryTime,(i=new zR(i,"GET",GR(t,n),s)).errorHandler=QR(r);var t,r,n,i,s=i;return e.storage.makeRequestWithTokens(s,uP).then(e=>{if(null===e)throw new eR(HN.NO_DOWNLOAD_URL,"The given file does not have any download URLs.");return e})}function vP(e){e._throwIfRoot("deleteObject");t=e.storage,n=vR((r=e._location).fullServerUrl(),t.host,t._protocol),i=t.maxOperationRetryTime,(n=new zR(n,"DELETE",function(e,t){},i)).successCodes=[200,204],n.errorHandler=QR(r);var t,r,n,i=n;return e.storage.makeRequestWithTokens(i,uP)}function _P(e,t){r=e._location.path,n=t.split("/").filter(e=>0<e.length).join("/");var r,n=0===r.length?n:r+"/"+n,n=new cR(e._location.bucket,n);return new dP(e.storage,n)}function yP(e,t){if(e instanceof IP){var r=e;if(null==r._bucket)throw new eR(HN.NO_DEFAULT_BUCKET,"No default bucket found. Did you set the '"+ZN+"' property when initializing the app?");r=new dP(r,r._bucket);return null!=t?yP(r,t):r}return void 0!==t?_P(e,t):e}function wP(e,t){if(t&&/^[A-Za-z]+:\/\//.test(t)){if(e instanceof IP)return r=e,n=t,new dP(r,n);throw aR("To use ref(service, url), the first argument must be a Storage instance.")}return yP(e,t);var r,n}function bP(e,t){var r=null==t?void 0:t[ZN];return null==r?null:cR.makeFromBucketSpec(r,e)}class IP{constructor(e,t,r,n,i){this.app=e,this._authProvider=t,this._appCheckProvider=r,this._url=n,this._firebaseVersion=i,this._bucket=null,this._host=XN,this._protocol="https",this._appId=null,this._deleted=!1,this._maxOperationRetryTime=12e4,this._maxUploadRetryTime=6e5,this._requests=new Set,this._bucket=null!=n?cR.makeFromBucketSpec(n,this._host):bP(this._host,this.app.options)}get host(){return this._host}set host(e){this._host=e,null!=this._url?this._bucket=cR.makeFromBucketSpec(this._url,e):this._bucket=bP(e,this.app.options)}get maxUploadRetryTime(){return this._maxUploadRetryTime}set maxUploadRetryTime(e){mR("time",0,Number.POSITIVE_INFINITY,e),this._maxUploadRetryTime=e}get maxOperationRetryTime(){return this._maxOperationRetryTime}set maxOperationRetryTime(e){mR("time",0,Number.POSITIVE_INFINITY,e),this._maxOperationRetryTime=e}async _getAuthToken(){if(this._overrideAuthToken)return this._overrideAuthToken;var e=this._authProvider.getImmediate({optional:!0});if(e){e=await e.getToken();if(null!==e)return e.accessToken}return null}async _getAppCheckToken(){var e;return h(this.app)&&this.app.settings.appCheckToken?this.app.settings.appCheckToken:(e=this._appCheckProvider.getImmediate({optional:!0}))?(await e.getToken()).token:null}_delete(){return this._deleted||(this._deleted=!0,this._requests.forEach(e=>e.cancel()),this._requests.clear()),Promise.resolve()}_makeStorageReference(e){return new dP(this,e)}_makeRequest(t,r,n,i,s=!0){if(this._deleted)return new dR(oR());{[t,n,i,r,s,a,o=!0]=[t,this._appId,n,i,r,this._firebaseVersion,s],h=_R(t.urlParams),h=t.url+h,u=Object.assign({},t.headers),l=u,(n=n)&&(l["X-Firebase-GMPID"]=n),l=u,null!==(n=i)&&0<n.length&&(l.Authorization="Firebase "+n),i=a,u["X-Firebase-Storage-Version"]="webjs/"+(null!=i?i:"AppManager"),l=u,null!==(n=r)&&(l["X-Firebase-AppCheck"]=n);let e=new wR(h,t.method,u,t.body,t.successCodes,t.additionalRetryCodes,t.handler,t.errorHandler,t.timeout,t.progressCallback,s,o);return this._requests.add(e),e.getPromise().then(()=>this._requests.delete(e),()=>this._requests.delete(e)),e}var a,o,l,h,u}async makeRequestWithTokens(e,t){var[r,n]=await Promise.all([this._getAuthToken(),this._getAppCheckToken()]);return this._makeRequest(e,t,r,n).getPromise()}}let TP="@firebase/storage";function EP(e,t,r){return e=w(e),t=t,r=r,(e=e)._throwIfRoot("uploadBytesResumable"),new cP(e,new RR(t),r)}function CP(e){return e=w(e),(e=e)._throwIfRoot("getMetadata"),t=YR(e.storage,e._location,MR()),e.storage.makeRequestWithTokens(t,uP);var t}function kP(e,t){return wP(e=w(e),t)}function SP(e,t,r,n={}){var i;[e,t,r,n={}]=[e,t,r,n],e.host=t+":"+r,e._protocol="http",(i=n.mockUserToken)&&(e._overrideAuthToken="string"==typeof i?i:Z(i,e.app.options.projectId))}function AP(e,{instanceIdentifier:t}){var r=e.getProvider("app").getImmediate(),n=e.getProvider("auth-internal"),i=e.getProvider("app-check-internal");return new IP(r,n,i,t,Dt)}Ct(new u("storage",AP,"PUBLIC").setMultipleInstances(!0)),d(TP,"0.13.6",""),d(TP,"0.13.6","esm2017");class NP{constructor(e,t,r){this._delegate=e,this.task=t,this.ref=r}get bytesTransferred(){return this._delegate.bytesTransferred}get metadata(){return this._delegate.metadata}get state(){return this._delegate.state}get totalBytes(){return this._delegate.totalBytes}}class RP{constructor(e,t){this._delegate=e,this._ref=t,this.cancel=this._delegate.cancel.bind(this._delegate),this.catch=this._delegate.catch.bind(this._delegate),this.pause=this._delegate.pause.bind(this._delegate),this.resume=this._delegate.resume.bind(this._delegate)}get snapshot(){return new NP(this._delegate.snapshot,this,this._ref)}then(t,e){return this._delegate.then(e=>{if(t)return t(new NP(e,this,this._ref))},e)}on(e,t,r,n){let i=void 0;return t&&(i="function"==typeof t?e=>t(new NP(e,this,this._ref)):{next:t.next?e=>t.next(new NP(e,this,this._ref)):void 0,complete:t.complete||void 0,error:t.error||void 0}),this._delegate.on(e,i,r||void 0,n||void 0)}}class PP{constructor(e,t){this._delegate=e,this._service=t}get prefixes(){return this._delegate.prefixes.map(e=>new DP(e,this._service))}get items(){return this._delegate.items.map(e=>new DP(e,this._service))}get nextPageToken(){return this._delegate.nextPageToken||null}}class DP{constructor(e,t){this._delegate=e,this.storage=t}get name(){return this._delegate.name}get bucket(){return this._delegate.bucket}get fullPath(){return this._delegate.fullPath}toString(){return this._delegate.toString()}child(e){var t=_P(this._delegate,e);return new DP(t,this.storage)}get root(){return new DP(this._delegate.root,this.storage)}get parent(){var e=this._delegate.parent;return null==e?null:new DP(e,this.storage)}put(e,t){return this._throwIfRoot("put"),new RP(EP(this._delegate,e,t),this)}putString(e,t=ER.RAW,r){this._throwIfRoot("putString");var n=kR(t,e),i=Object.assign({},r);return null==i.contentType&&null!=n.contentType&&(i.contentType=n.contentType),new RP(new cP(this._delegate,new RR(n.data,!0),i),this)}listAll(){return pP(w(this._delegate)).then(e=>new PP(e,this.storage))}list(e){return t=this._delegate,e=e||void 0,fP(t=w(t),e).then(e=>new PP(e,this.storage));var t}getMetadata(){return CP(this._delegate)}updateMetadata(e){return gP(w(this._delegate),e)}getDownloadURL(){return mP(w(this._delegate))}delete(){return this._throwIfRoot("delete"),vP(w(this._delegate))}_throwIfRoot(e){if(""===this._delegate._location.path)throw lR(e)}}class xP{constructor(e,t){this.app=e,this._delegate=t}get maxOperationRetryTime(){return this._delegate.maxOperationRetryTime}get maxUploadRetryTime(){return this._delegate.maxUploadRetryTime}ref(e){if(OP(e))throw aR("ref() expected a child path but got a URL, use refFromURL instead.");return new DP(kP(this._delegate,e),this)}refFromURL(e){if(!OP(e))throw aR("refFromURL() expected a full URL but got a child path, use ref() instead.");try{cR.makeFromUrl(e,this._delegate.host)}catch(e){throw aR("refFromUrl() expected a valid full URL but got an invalid one.")}return new DP(kP(this._delegate,e),this)}setMaxUploadRetryTime(e){this._delegate.maxUploadRetryTime=e}setMaxOperationRetryTime(e){this._delegate.maxOperationRetryTime=e}useEmulator(e,t,r={}){SP(this._delegate,e,t,r)}}function OP(e){return/^[A-Za-z]+:\/\//.test(e)}function LP(e,{instanceIdentifier:t}){var r=e.getProvider("app-compat").getImmediate(),n=e.getProvider("storage").getImmediate({identifier:t});return new xP(r,n)}$N=tr,ym={TaskState:sP,TaskEvent:iP,StringFormat:ER,Storage:xP,Reference:DP},$N.INTERNAL.registerComponent(new u("storage-compat",LP,"PUBLIC").setServiceProps(ym).setMultipleInstances(!0)),$N.registerVersion("@firebase/storage-compat","0.3.16");function MP(e){if("loading"===document.readyState)return"loading";var t=HP();if(t){if(e<t.domInteractive)return"loading";if(0===t.domContentLoadedEventStart||e<t.domContentLoadedEventStart)return"dom-interactive";if(0===t.domComplete||e<t.domComplete)return"dom-content-loaded"}return"complete"}function FP(e,t){var r="";try{for(;e&&9!==e.nodeType;){var n=e,i=n.id?"#"+n.id:GP(n)+(n.classList&&n.classList.value&&n.classList.value.trim()&&n.classList.value.trim().length?"."+n.classList.value.trim().replace(/\s+/g,"."):"");if(r.length+i.length>(t||100)-1)return r||i;if(r=r?i+">"+r:i,n.id)break;e=n.parentNode}}catch(e){}return r}function UP(i,e){var a,o,s,l;a=function(e){r={},(e=e).entries.length&&(t=e.entries.reduce(function(e,t){return e&&e.value>t.value?e:t}))&&t.sources&&t.sources.length&&(n=(n=t.sources).find(function(e){return e.node&&1===e.node.nodeType})||n[0])&&(r={largestShiftTarget:FP(n.node),largestShiftTime:t.startTime,largestShiftValue:t.value,largestShiftSource:n,largestShiftEntry:t,loadState:MP(t.startTime)});var t,r,n=Object.assign(e,{attribution:r});i(n)},o=e||{},s=nD(function(){function e(e){e.forEach(function(e){var t,r;e.hadRecentInput||(t=i[0],r=i[i.length-1],n&&e.startTime-r.startTime<1e3&&e.startTime-t.startTime<5e3?(n+=e.value,i.push(e)):(n=e.value,i=[e]))}),n>r.value&&(r.value=n,r.entries=i,t())}var t,r=XP("CLS",0),n=0,i=[],s=ZP("layout-shift",e);s&&(t=eD(a,r,dD,o.reportAllChanges),rD(function(){e(s.takeRecords()),t(!0)}),YP(function(){r=XP("CLS",n=0),t=eD(a,r,dD,o.reportAllChanges),tD(function(){return t()})}),setTimeout(t,0))}),l=l||{},uD(function(){var t,r=hD(),n=XP("FCP"),i=ZP("paint",function(e){e.forEach(function(e){"first-contentful-paint"===e.name&&(i.disconnect(),e.startTime<r.firstHiddenTime)&&(n.value=Math.max(e.startTime-JP(),0),n.entries.push(e),t(!0))})});i&&(t=eD(s,n,cD,l.reportAllChanges),YP(function(e){n=XP("FCP"),t=eD(s,n,cD,l.reportAllChanges),tD(function(){n.value=performance.now()-e.timeStamp,t(!0)})}))})}function VP(s,a){"PerformanceEventTiming"in self&&"interactionId"in PerformanceEventTiming.prototype&&(a=a||{},uD(function(){var e;_D();function t(t){CD(function(){t.forEach(ED);var e=ID();e&&e.latency!==r.value&&(r.value=e.latency,r.entries=e.entries,i())})}var r=XP("INP"),n=ZP("event",t,{durationThreshold:null!=(e=a.durationThreshold)?e:40}),i=eD(s,r,kD,a.reportAllChanges);n&&(n.observe({type:"first-input",buffered:!0}),rD(function(){t(n.takeRecords()),i(!0)}),YP(function(){bD=vD(),yD.length=0,wD.clear(),r=XP("INP"),i=eD(s,r,kD,a.reportAllChanges)}))}))}function qP(e){SD=SD.concat(e),xD()}function jP(){10<PD.size&&PD.forEach(function(e,t){wD.has(t)||PD.delete(t)});var r=yD.map(function(e){return RD.get(e.entries[0])}),n=AD.length-50;AD=AD.filter(function(e,t){return n<=t||r.includes(e)});for(var i=new Set,e=0;e<AD.length;e++){var t=AD[e];OD(t.startTime,t.processingEnd).forEach(function(e){i.add(e)})}var s=SD.length-1-50;SD=SD.filter(function(e,t){return e.startTime>ND&&s<t||i.has(e)}),DD=-1}function BP(l,e){WP=WP||ZP("long-animation-frame",qP),VP(function(e){t=(e=e).entries[0],o=RD.get(t),r=t.processingStart,n=o.processingEnd,o=o.entries.sort(function(e,t){return e.processingStart-t.processingStart}),i=OD(t.startTime,n),s=(s=e.entries.find(function(e){return e.target}))&&s.target||PD.get(t.interactionId),a=[t.startTime+t.duration,n].concat(i.map(function(e){return e.startTime+e.duration})),a=Math.max.apply(Math,a),s={interactionTarget:FP(s),interactionTargetElement:s,interactionType:t.name.startsWith("key")?"keyboard":"pointer",interactionTime:t.startTime,nextPaintTime:a,processedEventEntries:o,longAnimationFrameEntries:i,inputDelay:r-t.startTime,processingDuration:n-r,presentationDelay:Math.max(a-n,0),loadState:MP(t.startTime)};var t,r,n,i,s,a,o=Object.assign(e,{attribution:s});l(o)},e)}function zP(h,e){var a,o;a=function(e){o={timeToFirstByte:0,resourceLoadDelay:0,resourceLoadDuration:0,elementRenderDelay:(e=e).value},e.entries.length&&(t=HP())&&(a=t.activationStart||0,n=(r=e.entries[e.entries.length-1]).url&&performance.getEntriesByType("resource").filter(function(e){return e.name===r.url})[0],l=Math.max(0,t.responseStart-a),i=Math.max(l,n?(n.requestStart||n.startTime)-a:0),s=Math.max(i,n?n.responseEnd-a:0),a=Math.max(s,r.startTime-a),o={element:FP(r.element),timeToFirstByte:l,resourceLoadDelay:i-l,resourceLoadDuration:s-i,elementRenderDelay:a-s,navigationEntry:t,lcpEntry:r},r.url&&(o.url=r.url),n)&&(o.lcpResourceEntry=n);var t,r,n,i,s,a,o,l=Object.assign(e,{attribution:o});h(l)},o=e||{},uD(function(){function e(e){(e=o.reportAllChanges?e:e.slice(-1)).forEach(function(e){e.startTime<n.firstHiddenTime&&(i.value=Math.max(e.startTime-JP(),0),i.entries=[e],t())})}var t,r,n=hD(),i=XP("LCP"),s=ZP("largest-contentful-paint",e);s&&(t=eD(a,i,LD,o.reportAllChanges),r=nD(function(){MD[i.id]||(e(s.takeRecords()),s.disconnect(),MD[i.id]=!0,t(!0))}),["keydown","click"].forEach(function(e){addEventListener(e,function(){return CD(r)},{once:!0,capture:!0})}),rD(r),YP(function(e){i=XP("LCP"),t=eD(a,i,LD,o.reportAllChanges),tD(function(){i.value=performance.now()-e.timeStamp,MD[i.id]=!0,t(!0)})}))})}var KP,WP,HP=function(){var e=self.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0];if(e&&0<e.responseStart&&e.responseStart<performance.now())return e},GP=function(e){var t=e.nodeName;return 1===e.nodeType?t.toLowerCase():t.toUpperCase().replace(/^#/,"")},$P=-1,QP=function(){return $P},YP=function(t){addEventListener("pageshow",function(e){e.persisted&&($P=e.timeStamp,t(e))},!0)},JP=function(){var e=HP();return e&&e.activationStart||0},XP=function(e,t){var r=HP(),n="navigate";return 0<=QP()?n="back-forward-cache":r&&(document.prerendering||0<JP()?n="prerender":document.wasDiscarded?n="restore":r.type&&(n=r.type.replace(/_/g,"-"))),{name:e,value:void 0===t?-1:t,rating:"good",delta:0,entries:[],id:"v4-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:n}},ZP=function(e,t,r){try{var n;if(PerformanceObserver.supportedEntryTypes.includes(e))return(n=new PerformanceObserver(function(e){Promise.resolve().then(function(){t(e.getEntries())})})).observe(Object.assign({type:e,buffered:!0},r||{})),n}catch(e){}},eD=function(t,r,n,i){var s,a;return function(e){0<=r.value&&(e||i)&&((a=r.value-(s||0))||void 0===s)&&(s=r.value,r.delta=a,r.rating=(e=r.value)>n[1]?"poor":e>n[0]?"needs-improvement":"good",t(r))}},tD=function(e){requestAnimationFrame(function(){return requestAnimationFrame(function(){return e()})})},rD=function(e){document.addEventListener("visibilitychange",function(){"hidden"===document.visibilityState&&e()})},nD=function(e){var t=!1;return function(){t||(e(),t=!0)}},iD=-1,sD=function(){return"hidden"!==document.visibilityState||document.prerendering?1/0:0},aD=function(e){"hidden"===document.visibilityState&&-1<iD&&(iD="visibilitychange"===e.type?e.timeStamp:0,lD())},oD=function(){addEventListener("visibilitychange",aD,!0),addEventListener("prerenderingchange",aD,!0)},lD=function(){removeEventListener("visibilitychange",aD,!0),removeEventListener("prerenderingchange",aD,!0)},hD=function(){return iD<0&&(iD=sD(),oD(),YP(function(){setTimeout(function(){iD=sD(),oD()},0)})),{get firstHiddenTime(){return iD}}},uD=function(e){document.prerendering?addEventListener("prerenderingchange",function(){return e()},!0):e()},cD=[1800,3e3],dD=[.1,.25],pD=0,fD=1/0,gD=0,mD=function(e){e.forEach(function(e){e.interactionId&&(fD=Math.min(fD,e.interactionId),gD=Math.max(gD,e.interactionId),pD=gD?(gD-fD)/7+1:0)})},vD=function(){return KP?pD:performance.interactionCount||0},_D=function(){"interactionCount"in performance||(KP=KP||ZP("event",mD,{type:"event",buffered:!0,durationThreshold:0}))},yD=[],wD=new Map,bD=0,ID=function(){var e=Math.min(yD.length-1,Math.floor((vD()-bD)/50));return yD[e]},TD=[],ED=function(t){var e,r;TD.forEach(function(e){return e(t)}),!t.interactionId&&"first-input"!==t.entryType||(r=yD[yD.length-1],((e=wD.get(t.interactionId))||yD.length<10||t.duration>r.latency)&&(e?t.duration>e.latency?(e.entries=[t],e.latency=t.duration):t.duration===e.latency&&t.startTime===e.entries[0].startTime&&e.entries.push(t):(r={id:t.interactionId,latency:t.duration,entries:[t]},wD.set(r.id,r),yD.push(r)),yD.sort(function(e,t){return t.latency-e.latency}),10<yD.length)&&yD.splice(10).forEach(function(e){return wD.delete(e.id)}))},CD=function(e){var t=self.requestIdleCallback||self.setTimeout,r=-1;return e=nD(e),"hidden"===document.visibilityState?e():(r=t(e),rD(e)),r},kD=[200,500],SD=[],AD=[],ND=0,RD=new WeakMap,PD=new Map,DD=-1,xD=function(){DD<0&&(DD=CD(jP))},OD=(TD.push(function(e){e.interactionId&&e.target&&!PD.has(e.interactionId)&&PD.set(e.interactionId,e.target)},function(e){var t,r=e.startTime+e.duration;ND=Math.max(ND,e.processingEnd);for(var n=AD.length-1;0<=n;n--){var i=AD[n];if(Math.abs(r-i.renderTime)<=8){(t=i).startTime=Math.min(e.startTime,t.startTime),t.processingStart=Math.min(e.processingStart,t.processingStart),t.processingEnd=Math.max(e.processingEnd,t.processingEnd),t.entries.push(e);break}}t||(t={startTime:e.startTime,processingStart:e.processingStart,processingEnd:e.processingEnd,renderTime:r,entries:[e]},AD.push(t)),!e.interactionId&&"first-input"!==e.entryType||RD.set(e,t),xD()}),function(e,t){for(var r,n=[],i=0;r=SD[i];i++)if(!(r.startTime+r.duration<e)){if(r.startTime>t)break;n.push(r)}return n}),LD=[2500,4e3],MD={};let FD="@firebase/performance",UD="0.7.0",VD=UD,qD="FB-PERF-TRACE-MEASURE",jD="@firebase/performance/config",BD="@firebase/performance/configexpire";var zD,t,r,KD,e="Performance";let WD=new pe("performance",e,{"trace started":"Trace {$traceName} was started before.","trace stopped":"Trace {$traceName} is not running.","nonpositive trace startTime":"Trace {$traceName} startTime should be positive.","nonpositive trace duration":"Trace {$traceName} duration should be positive.","no window":"Window is not available.","no app id":"App id is not available.","no project id":"Project id is not available.","no api key":"Api key is not available.","invalid cc log":"Attempted to queue invalid cc event","FB not default":"Performance can only start when Firebase app instance is the default one.","RC response not ok":"RC response is not ok","invalid attribute name":"Attribute name {$attributeName} is invalid.","invalid attribute value":"Attribute value {$attributeValue} is invalid.","invalid custom metric name":"Custom metric name {$customMetricName} is invalid","invalid String merger input":"Input for String merger is invalid, contact support team to resolve.","already initialized":"initializePerformance() has already been called with different options. To avoid this error, call initializePerformance() with the same options as when it was originally called, or call getPerformance() to return the already initialized instance."}),HD=new $e(e);HD.logLevel=c.INFO;let GD,$D;class QD{constructor(e){if(!(this.window=e))throw WD.create("no window");this.performance=e.performance,this.PerformanceObserver=e.PerformanceObserver,this.windowLocation=e.location,this.navigator=e.navigator,this.document=e.document,this.navigator&&this.navigator.cookieEnabled&&(this.localStorage=e.localStorage),e.perfMetrics&&e.perfMetrics.onFirstInputDelay&&(this.onFirstInputDelay=e.perfMetrics.onFirstInputDelay),this.onLCP=zP,this.onINP=BP,this.onCLS=UP}getUrl(){return this.windowLocation.href.split("?")[0]}mark(e){this.performance&&this.performance.mark&&this.performance.mark(e)}measure(e,t,r){this.performance&&this.performance.measure&&this.performance.measure(e,t,r)}getEntriesByType(e){return this.performance&&this.performance.getEntriesByType?this.performance.getEntriesByType(e):[]}getEntriesByName(e){return this.performance&&this.performance.getEntriesByName?this.performance.getEntriesByName(e):[]}getTimeOrigin(){return this.performance&&(this.performance.timeOrigin||this.performance.timing.navigationStart)}requiredApisAvailable(){return fetch&&Promise&&ce()?!!he()||(HD.info("IndexedDB is not supported by current browser"),!1):(HD.info("Firebase Performance cannot start if browser does not support fetch and Promise or cookie is disabled."),!1)}setupObserver(e,r){this.PerformanceObserver&&new this.PerformanceObserver(e=>{for(var t of e.getEntries())r(t)}).observe({entryTypes:[e]})}static getInstance(){return GD=void 0===GD?new QD($D):GD}}let YD;function JD(e,t){var r=e.length-t.length;if(r<0||1<r)throw WD.create("invalid String merger input");var n=[];for(let i=0;i<e.length;i++)n.push(e.charAt(i)),t.length>i&&n.push(t.charAt(i));return n.join("")}let XD;class ZD{constructor(){this.instrumentationEnabled=!0,this.dataCollectionEnabled=!0,this.loggingEnabled=!1,this.tracesSamplingRate=1,this.networkRequestsSamplingRate=1,this.logEndPointUrl="https://firebaselogging.googleapis.com/v0cc/log?format=json_proto",this.flTransportEndpointUrl=JD("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),this.transportKey=JD("AzSC8r6ReiGqFMyfvgow","Iayx0u-XT3vksVM-pIV"),this.logSource=462,this.logTraceAfterSampling=!1,this.logNetworkAfterSampling=!1,this.configTimeToLive=12}getFlTransportFullUrl(){return this.flTransportEndpointUrl.concat("?key=",this.transportKey)}static getInstance(){return XD=void 0===XD?new ZD:XD}}(t=zD=zD||{})[t.UNKNOWN=0]="UNKNOWN",t[t.VISIBLE=1]="VISIBLE",t[t.HIDDEN=2]="HIDDEN";let e1=["firebase_","google_","ga_"],t1=new RegExp("^[a-zA-Z]\\w*$");function r1(e){var t=null==(t=e.options)?void 0:t.appId;if(t)return t;throw WD.create("no app id")}let n1="0.0.1",i1={loggingEnabled:!0},s1="FIREBASE_INSTALLATIONS_AUTH";function a1(e,t){var n,i,r=(()=>{var e=QD.getInstance().localStorage;if(e){var t=e.getItem(BD);if(t&&(e=>Number(e)>Date.now())(t)){t=e.getItem(jD);if(t)try{return JSON.parse(t)}catch(e){}}}})();return r?(l1(r),Promise.resolve()):(i=t,(e=>{var t=e.getToken();return t.then(e=>{}),t})((n=e).installations).then(e=>{var t=(e=>{var t=null==(t=e.options)?void 0:t.projectId;if(t)return t;throw WD.create("no project id")})(n.app),r=(e=>{var t=null==(t=e.options)?void 0:t.apiKey;if(t)return t;throw WD.create("no api key")})(n.app),t=new Request(`https://firebaseremoteconfig.googleapis.com/v1/projects/${t}/namespaces/fireperf:fetch?key=`+r,{method:"POST",headers:{Authorization:s1+" "+e},body:JSON.stringify({app_instance_id:i,app_instance_id_token:e,app_id:r1(n.app),app_version:VD,sdk_version:n1})});return fetch(t).then(e=>{if(e.ok)return e.json();throw WD.create("RC response not ok")})}).catch(()=>{HD.info(o1)}).then(l1).then(e=>{var t;e=e,t=QD.getInstance().localStorage,e&&t&&(t.setItem(jD,JSON.stringify(e)),t.setItem(BD,String(Date.now()+60*ZD.getInstance().configTimeToLive*60*1e3)))},()=>{}))}let o1="Could not fetch config, will use default configs";function l1(e){var t,r;return e&&(t=ZD.getInstance(),void 0!==(r=e.entries||{}).fpr_enabled?t.loggingEnabled="true"===String(r.fpr_enabled):t.loggingEnabled=i1.loggingEnabled,r.fpr_log_source?t.logSource=Number(r.fpr_log_source):i1.logSource&&(t.logSource=i1.logSource),r.fpr_log_endpoint_url?t.logEndPointUrl=r.fpr_log_endpoint_url:i1.logEndPointUrl&&(t.logEndPointUrl=i1.logEndPointUrl),r.fpr_log_transport_key?t.transportKey=r.fpr_log_transport_key:i1.transportKey&&(t.transportKey=i1.transportKey),void 0!==r.fpr_vc_network_request_sampling_rate?t.networkRequestsSamplingRate=Number(r.fpr_vc_network_request_sampling_rate):void 0!==i1.networkRequestsSamplingRate&&(t.networkRequestsSamplingRate=i1.networkRequestsSamplingRate),void 0!==r.fpr_vc_trace_sampling_rate?t.tracesSamplingRate=Number(r.fpr_vc_trace_sampling_rate):void 0!==i1.tracesSamplingRate&&(t.tracesSamplingRate=i1.tracesSamplingRate),t.logTraceAfterSampling=h1(t.tracesSamplingRate),t.logNetworkAfterSampling=h1(t.networkRequestsSamplingRate)),e}function h1(e){return Math.random()<=e}let u1=1,c1;function d1(e){var r;return u1=2,c1=c1||(r=e,(()=>{let r=QD.getInstance().document;return new Promise(t=>{if(r&&"complete"!==r.readyState){let e=()=>{"complete"===r.readyState&&(r.removeEventListener("readystatechange",e),t())};r.addEventListener("readystatechange",e)}else t()})})().then(()=>{return e=r.installations,(t=e.getId()).then(e=>{YD=e}),t;var e,t}).then(e=>a1(r,e)).then(()=>p1(),()=>p1()))}function p1(){u1=3}let f1=1e4,g1=1e3,m1=3,v1=m1,_1=[],y1=!1;function w1(e){setTimeout(()=>{0!==v1&&(0<_1.length&&b1(),w1(f1))},e)}function b1(){let e=_1.splice(0,g1);var t,r,n=e.map(e=>({source_extension_json_proto3:e.message,event_time_ms:String(e.eventTime)})),n={request_time_ms:String(Date.now()),client_info:{client_type:1,js_client_info:{}},log_source:ZD.getInstance().logSource,log_event:n};t=n,n=ZD.getInstance().getFlTransportFullUrl(),r=JSON.stringify(t),(navigator.sendBeacon&&navigator.sendBeacon(n,r)?Promise.resolve():fetch(n,{method:"POST",body:r,keepalive:!0}).then()).then(()=>{v1=m1}).catch(()=>{_1=[...e,..._1],v1--,HD.info(`Tries left: ${v1}.`),w1(f1)})}function I1(t){return(...e)=>{e={message:t(...e),eventTime:Date.now()};if(!e.eventTime||!e.message)throw WD.create("invalid cc log");_1=[..._1,e]}}function T1(){for(;0<_1.length;)b1()}let E1;function C1(e,t){(E1=E1||{send:I1(A1),flush:T1}).send(e,t)}function k1(e){var t=ZD.getInstance();!t.instrumentationEnabled&&e.isAuto||(t.dataCollectionEnabled||e.isAuto)&&QD.getInstance().requiredApisAvailable()&&(3===u1?S1(e):d1(e.performanceController).then(()=>S1(e),()=>S1(e)))}function S1(e){var t;YD&&(t=ZD.getInstance()).loggingEnabled&&t.logTraceAfterSampling&&C1(e,1)}function A1(e,t){var r,n;return 0===t?(r={url:e.url,http_method:e.httpMethod||0,http_response_code:200,response_payload_bytes:e.responsePayloadBytes,client_start_time_us:e.startTimeUs,time_to_response_initiated_us:e.timeToResponseInitiatedUs,time_to_response_completed_us:e.timeToResponseCompletedUs},r={application_info:N1(e.performanceController.app),network_request_metric:r},JSON.stringify(r)):(r={name:(t=e).name,is_auto:t.isAuto,client_start_time_us:t.startTimeUs,duration_us:t.durationUs},0!==Object.keys(t.counters).length&&(r.counters=t.counters),n=t.getAttributes(),0!==Object.keys(n).length&&(r.custom_attributes=n),n={application_info:N1(t.performanceController.app),trace_metric:r},JSON.stringify(n))}function N1(e){return{google_app_id:r1(e),app_instance_id:YD,web_app_info:{sdk_version:VD,page_url:QD.getInstance().getUrl(),service_worker_status:null!=(t=QD.getInstance().navigator)&&t.serviceWorker?t.serviceWorker.controller?2:3:1,visibility_state:(()=>{switch(QD.getInstance().document.visibilityState){case"visible":return zD.VISIBLE;case"hidden":return zD.HIDDEN;default:return zD.UNKNOWN}})(),effective_connection_type:(()=>{var e=QD.getInstance().navigator.connection;switch(e&&e.effectiveType){case"slow-2g":return 1;case"2g":return 2;case"3g":return 3;case"4g":return 4;default:return 0}})()},application_process_state:0};var t}function R1(e,t){var r,n,i,s=t;s&&void 0!==s.responseStart&&(i=QD.getInstance().getTimeOrigin(),i=Math.floor(1e3*(s.startTime+i)),r=s.responseStart?Math.floor(1e3*(s.responseStart-s.startTime)):void 0,n=Math.floor(1e3*(s.responseEnd-s.startTime)),s={performanceController:e,url:s.name&&s.name.split("?")[0],responsePayloadBytes:s.transferSize,startTimeUs:i,timeToResponseInitiatedUs:r,timeToResponseCompletedUs:n},t=s,(i=ZD.getInstance()).instrumentationEnabled)&&(r=t.url,n=i.logEndPointUrl.split("?")[0],s=i.flTransportEndpointUrl.split("?")[0],r!==n)&&r!==s&&i.loggingEnabled&&i.logNetworkAfterSampling&&C1(t,0)}let P1=["_fp","_fcp","_fid","_lcp","_cls","_inp"];class D1{constructor(e,t,r=!1,n){this.performanceController=e,this.name=t,this.isAuto=r,this.state=1,this.customAttributes={},this.counters={},this.api=QD.getInstance(),this.randomId=Math.floor(1e6*Math.random()),this.isAuto||(this.traceStartMark=`FB-PERF-TRACE-START-${this.randomId}-`+this.name,this.traceStopMark=`FB-PERF-TRACE-STOP-${this.randomId}-`+this.name,this.traceMeasure=n||`${qD}-${this.randomId}-`+this.name,n&&this.calculateTraceMetrics())}start(){if(1!==this.state)throw WD.create("trace started",{traceName:this.name});this.api.mark(this.traceStartMark),this.state=2}stop(){if(2!==this.state)throw WD.create("trace stopped",{traceName:this.name});this.state=3,this.api.mark(this.traceStopMark),this.api.measure(this.traceMeasure,this.traceStartMark,this.traceStopMark),this.calculateTraceMetrics(),k1(this)}record(e,t,r){if(e<=0)throw WD.create("nonpositive trace startTime",{traceName:this.name});if(t<=0)throw WD.create("nonpositive trace duration",{traceName:this.name});if(this.durationUs=Math.floor(1e3*t),this.startTimeUs=Math.floor(1e3*e),r&&r.attributes&&(this.customAttributes=Object.assign({},r.attributes)),r&&r.metrics)for(var n of Object.keys(r.metrics))isNaN(Number(r.metrics[n]))||(this.counters[n]=Math.floor(Number(r.metrics[n])));k1(this)}incrementMetric(e,t=1){void 0===this.counters[e]?this.putMetric(e,t):this.putMetric(e,this.counters[e]+t)}putMetric(e,t){if(n=e,i=this.name,0===n.length||100<n.length||!(i&&i.startsWith("_wt_")&&-1<P1.indexOf(n))&&n.startsWith("_"))throw WD.create("invalid custom metric name",{customMetricName:e});var r,n,i;this.counters[e]=(i=null!=t?t:0,(r=Math.floor(i))<i&&HD.info(`Metric value should be an Integer, setting the value as : ${r}.`),r)}getMetric(e){return this.counters[e]||0}putAttribute(e,t){var r,n,i=!(0===(r=e).length||40<r.length||e1.some(e=>r.startsWith(e))||!r.match(t1)),s=0!==(n=t).length&&n.length<=100;if(i&&s)this.customAttributes[e]=t;else{if(!i)throw WD.create("invalid attribute name",{attributeName:e});if(!s)throw WD.create("invalid attribute value",{attributeValue:t})}}getAttribute(e){return this.customAttributes[e]}removeAttribute(e){void 0!==this.customAttributes[e]&&delete this.customAttributes[e]}getAttributes(){return Object.assign({},this.customAttributes)}setStartTime(e){this.startTimeUs=e}setDuration(e){this.durationUs=e}calculateTraceMetrics(){var e=this.api.getEntriesByName(this.traceMeasure),e=e&&e[0];e&&(this.durationUs=Math.floor(1e3*e.duration),this.startTimeUs=Math.floor(1e3*(e.startTime+this.api.getTimeOrigin())))}static createOobTrace(e,t,r,n,i){var s=QD.getInstance().getUrl();if(s){var s=new D1(e,"_wt_"+s,!0),a=Math.floor(1e3*QD.getInstance().getTimeOrigin());s.setStartTime(a),t&&t[0]&&(s.setDuration(Math.floor(1e3*t[0].duration)),s.putMetric("domInteractive",Math.floor(1e3*t[0].domInteractive)),s.putMetric("domContentLoadedEventEnd",Math.floor(1e3*t[0].domContentLoadedEventEnd)),s.putMetric("loadEventEnd",Math.floor(1e3*t[0].loadEventEnd)));r&&((a=r.find(e=>"first-paint"===e.name))&&a.startTime&&s.putMetric("_fp",Math.floor(1e3*a.startTime)),(a=r.find(e=>"first-contentful-paint"===e.name))&&a.startTime&&s.putMetric("_fcp",Math.floor(1e3*a.startTime)),i)&&s.putMetric("_fid",Math.floor(1e3*i)),this.addWebVitalMetric(s,"_lcp","lcp_element",n.lcp),this.addWebVitalMetric(s,"_cls","cls_largestShiftTarget",n.cls),this.addWebVitalMetric(s,"_inp","inp_interactionTarget",n.inp),k1(s),E1&&E1.flush()}}static addWebVitalMetric(e,t,r,n){n&&(e.putMetric(t,Math.floor(1e3*n.value)),n.elementAttribution)&&e.putAttribute(r,n.elementAttribution)}static createUserTimingTrace(e,t){k1(new D1(e,t,!1,t))}}let x1={},O1=!1,L1;function M1(n){YD&&(setTimeout(()=>{{var t=n;let e=QD.getInstance();"onpagehide"in window?e.document.addEventListener("pagehide",()=>U1(t)):e.document.addEventListener("unload",()=>U1(t)),e.document.addEventListener("visibilitychange",()=>{"hidden"===e.document.visibilityState&&U1(t)}),e.onFirstInputDelay&&e.onFirstInputDelay(e=>{L1=e}),e.onLCP(e=>{var t;x1.lcp={value:e.value,elementAttribution:null==(t=e.attribution)?void 0:t.element}}),e.onCLS(e=>{var t;x1.cls={value:e.value,elementAttribution:null==(t=e.attribution)?void 0:t.largestShiftTarget}}),e.onINP(e=>{var t;x1.inp={value:e.value,elementAttribution:null==(t=e.attribution)?void 0:t.interactionTarget}})}},0),setTimeout(()=>{var e,t=n,r=QD.getInstance();for(e of r.getEntriesByType("resource"))R1(t,e);r.setupObserver("resource",e=>R1(t,e))},0),setTimeout(()=>{var e,t=n,r=QD.getInstance();for(e of r.getEntriesByType("measure"))F1(t,e);r.setupObserver("measure",e=>F1(t,e))},0))}function F1(e,t){var r=t.name;r.substring(0,qD.length)!==qD&&D1.createUserTimingTrace(e,r)}function U1(r){if(!O1){O1=!0;var n=QD.getInstance();let e=n.getEntriesByType("navigation"),t=n.getEntriesByType("paint");setTimeout(()=>{D1.createOobTrace(r,e,t,x1,L1)},0)}}class V1{constructor(e,t){this.app=e,this.installations=t,this.initialized=!1}_init(e){this.initialized||(void 0!==(null==e?void 0:e.dataCollectionEnabled)&&(this.dataCollectionEnabled=e.dataCollectionEnabled),void 0!==(null==e?void 0:e.instrumentationEnabled)&&(this.instrumentationEnabled=e.instrumentationEnabled),QD.getInstance().requiredApisAvailable()?ue().then(e=>{e&&(y1||(w1(5500),y1=!0),d1(this).then(()=>M1(this),()=>M1(this)),this.initialized=!0)}).catch(e=>{HD.info("Environment doesn't support IndexedDB: "+e)}):HD.info('Firebase Performance cannot start if the browser does not support "Fetch" and "Promise", or cookies are disabled.'))}set instrumentationEnabled(e){ZD.getInstance().instrumentationEnabled=e}get instrumentationEnabled(){return ZD.getInstance().instrumentationEnabled}set dataCollectionEnabled(e){ZD.getInstance().dataCollectionEnabled=e}get dataCollectionEnabled(){return ZD.getInstance().dataCollectionEnabled}}let q1="[DEFAULT]";let j1=(e,{options:t})=>{var r=e.getProvider("app").getImmediate(),n=e.getProvider("installations-internal").getImmediate();if(r.name!==q1)throw WD.create("FB not default");if("undefined"==typeof window)throw WD.create("no window");e=window,$D=e;r=new V1(r,n);return r._init(t),r};Ct(new u("performance",j1,"PUBLIC")),d(FD,UD),d(FD,UD,"esm2017");class B1{constructor(e,t){this.app=e,this._delegate=t}get instrumentationEnabled(){return this._delegate.instrumentationEnabled}set instrumentationEnabled(e){this._delegate.instrumentationEnabled=e}get dataCollectionEnabled(){return this._delegate.dataCollectionEnabled}set dataCollectionEnabled(e){this._delegate.dataCollectionEnabled=e}trace(e){return t=this._delegate,e=e,t=w(t),new D1(t,e);var t}}function z1(e){var t=e.getProvider("app-compat").getImmediate(),r=e.getProvider("performance").getImmediate();return new B1(t,r)}(r=tr).INTERNAL.registerComponent(new u("performance-compat",z1,"PUBLIC")),r.registerVersion("@firebase/performance-compat","0.2.13");let K1="@firebase/remote-config";class W1{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach(e=>e())}}let H1=new pe("remoteconfig","Remote Config",{"registration-window":"Undefined window object. This SDK only supports usage in a browser environment.","registration-project-id":"Undefined project identifier. Check Firebase app initialization.","registration-api-key":"Undefined API key. Check Firebase app initialization.","registration-app-id":"Undefined app identifier. Check Firebase app initialization.","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}.","storage-delete":"Error thrown when deleting from storage. Original error: {$originalErrorMessage}.","fetch-client-network":"Fetch client failed to connect to a network. Check Internet connection. Original error: {$originalErrorMessage}.","fetch-timeout":'The config fetch request timed out. Configure timeout using "fetchTimeoutMillis" SDK setting.',"fetch-throttle":'The config fetch request timed out while in an exponential backoff state. Configure timeout using "fetchTimeoutMillis" SDK setting. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',"fetch-client-parse":"Fetch client could not parse response. Original error: {$originalErrorMessage}.","fetch-status":"Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.","indexed-db-unavailable":"Indexed DB is not supported by current browser","custom-signal-max-allowed-signals":"Setting more than {$maxSignals} custom signals is not supported."});let G1=["1","true","t","yes","y","on"];class $1{constructor(e,t=""){this._source=e,this._value=t}asString(){return this._value}asBoolean(){return"static"!==this._source&&0<=G1.indexOf(this._value.toLowerCase())}asNumber(){if("static"===this._source)return 0;let e=Number(this._value);return e=isNaN(e)?0:e}getSource(){return this._source}}async function Q1(e){var t=w(e),[r,n]=await Promise.all([t._storage.getLastSuccessfulFetchResponse(),t._storage.getActiveConfigEtag()]);return!!(r&&r.config&&r.eTag&&r.eTag!==n)&&(await Promise.all([t._storageCache.setActiveConfig(r.config),t._storage.setActiveConfigEtag(r.eTag)]),!0)}function Y1(e){let t=w(e);return t._initializePromise||(t._initializePromise=t._storageCache.loadFromStorage().then(()=>{t._isInitializationComplete=!0})),t._initializePromise}async function J1(t){var r=w(t);let e=new W1;setTimeout(async()=>{e.abort()},r.settings.fetchTimeoutMillis);var n,i=r._storageCache.getCustomSignals();i&&r._logger.debug("Fetching config with custom signals: "+JSON.stringify(i));try{await r._client.fetch({cacheMaxAgeMillis:r.settings.minimumFetchIntervalMillis,signal:e,customSignals:i}),await r._storageCache.setLastFetchStatus("success")}catch(e){t="fetch-throttle";i=(n=e)instanceof de&&-1!==n.code.indexOf(t)?"throttle":"failure";throw await r._storageCache.setLastFetchStatus(i),e}}function X1(r){var e,t,n=w(r);return[e={},t={}]=[n._storageCache.getActiveConfig(),n.defaultConfig],Object.keys(Object.assign(Object.assign({},e),t)).reduce((e,t)=>(e[t]=Z1(r,t),e),{})}function Z1(e,t){var r=w(e),n=(r._isInitializationComplete||r._logger.debug(`A value was requested for key "${t}" before SDK initialization completed.`+" Await on ensureInitialized if the intent was to get a previously activated value."),r._storageCache.getActiveConfig());return n&&void 0!==n[t]?new $1("remote",n[t]):r.defaultConfig&&void 0!==r.defaultConfig[t]?new $1("default",String(r.defaultConfig[t])):(r._logger.debug(`Returning static value for key "${t}".`+" Define a default or remote value if this is unintentional."),new $1("static"))}class ex{constructor(e,t,r,n){this.client=e,this.storage=t,this.storageCache=r,this.logger=n}isCachedDataFresh(e,t){var r;return t?(r=Date.now()-t,this.logger.debug("Config fetch cache check."+` Cache age millis: ${r}.`+` Cache max age millis (minimumFetchIntervalMillis setting): ${e}.`+` Is cache hit: ${r=r<=e}.`),r):(this.logger.debug("Config fetch cache check. Cache unpopulated."),!1)}async fetch(e){var[t,r]=await Promise.all([this.storage.getLastSuccessfulFetchTimestampMillis(),this.storage.getLastSuccessfulFetchResponse()]);if(r&&this.isCachedDataFresh(e.cacheMaxAgeMillis,t))return r;e.eTag=r&&r.eTag;t=await this.client.fetch(e),r=[this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now())];return 200===t.status&&r.push(this.storage.setLastSuccessfulFetchResponse(t)),await Promise.all(r),t}}class tx{constructor(e,t,r,n,i,s){this.firebaseInstallations=e,this.sdkVersion=t,this.namespace=r,this.projectId=n,this.apiKey=i,this.appId=s}async fetch(r){var e,[t,n]=await Promise.all([this.firebaseInstallations.getId(),this.firebaseInstallations.getToken()]),i=`${window.FIREBASE_REMOTE_CONFIG_URL_BASE||"https://firebaseremoteconfig.googleapis.com"}/v1/projects/${this.projectId}/namespaces/${this.namespace}:fetch?key=`+this.apiKey,s={"Content-Type":"application/json","Content-Encoding":"gzip","If-None-Match":r.eTag||"*"},t={sdk_version:this.sdkVersion,app_instance_id:t,app_instance_id_token:n,app_id:this.appId,language_code:(e=navigator).languages&&e.languages[0]||e.language,custom_signals:r.customSignals},n={method:"POST",headers:s,body:JSON.stringify(t)},s=fetch(i,n),t=new Promise((e,t)=>{r.signal.addEventListener(()=>{var e=new Error("The operation was aborted.");e.name="AbortError",t(e)})});let a;try{await Promise.race([s,t]),a=await s}catch(e){let t="fetch-client-network";throw"AbortError"===(null==e?void 0:e.name)&&(t="fetch-timeout"),H1.create(t,{originalErrorMessage:null==e?void 0:e.message})}let o=a.status;i=a.headers.get("ETag")||void 0;let l,h;if(200===a.status){let e;try{e=await a.json()}catch(e){throw H1.create("fetch-client-parse",{originalErrorMessage:null==e?void 0:e.message})}l=e.entries,h=e.state}if("INSTANCE_STATE_UNSPECIFIED"===h?o=500:"NO_CHANGE"===h?o=304:"NO_TEMPLATE"!==h&&"EMPTY_CONFIG"!==h||(l={}),304!==o&&200!==o)throw H1.create("fetch-status",{httpStatus:o});return{status:o,eTag:i,config:l}}}class rx{constructor(e,t){this.client=e,this.storage=t}async fetch(e){var t=await this.storage.getThrottleMetadata()||{backoffCount:0,throttleEndTimeMillis:Date.now()};return this.attemptFetch(e,t)}async attemptFetch(t,{throttleEndTimeMillis:e,backoffCount:r}){var i,s;i=t.signal,s=e,await new Promise((e,t)=>{var r=Math.max(s-Date.now(),0);let n=setTimeout(e,r);i.addEventListener(()=>{clearTimeout(n),t(H1.create("fetch-throttle",{throttleEndTimeMillis:s}))})});try{var n=await this.client.fetch(t);return await this.storage.deleteThrottleMetadata(),n}catch(e){if((e=>{var t;return e instanceof de&&e.customData&&(429===(t=Number(e.customData.httpStatus))||500===t||503===t||504===t)})(e))return n={throttleEndTimeMillis:Date.now()+Ve(r),backoffCount:r+1},await this.storage.setThrottleMetadata(n),this.attemptFetch(t,n);throw e}}}class nx{get fetchTimeMillis(){return this._storageCache.getLastSuccessfulFetchTimestampMillis()||-1}get lastFetchStatus(){return this._storageCache.getLastFetchStatus()||"no-fetch-yet"}constructor(e,t,r,n,i){this.app=e,this._client=t,this._storageCache=r,this._storage=n,this._logger=i,this._isInitializationComplete=!1,this.settings={fetchTimeoutMillis:6e4,minimumFetchIntervalMillis:432e5},this.defaultConfig={}}}function ix(e,t){var r=e.target.error||void 0;return H1.create(t,{originalErrorMessage:r&&(null==r?void 0:r.message)})}let sx="app_namespace_store";class ax{constructor(e,t,r,n=(()=>new Promise((t,r)=>{try{var e=indexedDB.open("firebase_remote_config",1);e.onerror=e=>{r(ix(e,"storage-open"))},e.onsuccess=e=>{t(e.target.result)},e.onupgradeneeded=e=>{var t=e.target.result;0===e.oldVersion&&t.createObjectStore(sx,{keyPath:"compositeKey"})}}catch(e){r(H1.create("storage-open",{originalErrorMessage:null==e?void 0:e.message}))}}))()){this.appId=e,this.appName=t,this.namespace=r,this.openDbPromise=n}getLastFetchStatus(){return this.get("last_fetch_status")}setLastFetchStatus(e){return this.set("last_fetch_status",e)}getLastSuccessfulFetchTimestampMillis(){return this.get("last_successful_fetch_timestamp_millis")}setLastSuccessfulFetchTimestampMillis(e){return this.set("last_successful_fetch_timestamp_millis",e)}getLastSuccessfulFetchResponse(){return this.get("last_successful_fetch_response")}setLastSuccessfulFetchResponse(e){return this.set("last_successful_fetch_response",e)}getActiveConfig(){return this.get("active_config")}setActiveConfig(e){return this.set("active_config",e)}getActiveConfigEtag(){return this.get("active_config_etag")}setActiveConfigEtag(e){return this.set("active_config_etag",e)}getThrottleMetadata(){return this.get("throttle_metadata")}setThrottleMetadata(e){return this.set("throttle_metadata",e)}deleteThrottleMetadata(){return this.delete("throttle_metadata")}getCustomSignals(){return this.get("custom_signals")}async setCustomSignals(e){var t=(await this.openDbPromise).transaction([sx],"readwrite"),r=await this.getWithTransaction("custom_signals",t),r=Object.assign(Object.assign({},r),e),r=Object.fromEntries(Object.entries(r).filter(([,e])=>null!==e).map(([e,t])=>"number"==typeof t?[e,t.toString()]:[e,t]));if(100<Object.keys(r).length)throw H1.create("custom-signal-max-allowed-signals",{maxSignals:100});return await this.setWithTransaction("custom_signals",r,t),r}async getWithTransaction(s,a){return new Promise((r,t)=>{var e=a.objectStore(sx),n=this.createCompositeKey(s);try{var i=e.get(n);i.onerror=e=>{t(ix(e,"storage-get"))},i.onsuccess=e=>{var t=e.target.result;r(t?t.value:void 0)}}catch(e){t(H1.create("storage-get",{originalErrorMessage:null==e?void 0:e.message}))}})}async setWithTransaction(s,a,o){return new Promise((e,t)=>{var r=o.objectStore(sx),n=this.createCompositeKey(s);try{var i=r.put({compositeKey:n,value:a});i.onerror=e=>{t(ix(e,"storage-set"))},i.onsuccess=()=>{e()}}catch(e){t(H1.create("storage-set",{originalErrorMessage:null==e?void 0:e.message}))}})}async get(e){var t=(await this.openDbPromise).transaction([sx],"readonly");return this.getWithTransaction(e,t)}async set(e,t){var r=(await this.openDbPromise).transaction([sx],"readwrite");return this.setWithTransaction(e,t,r)}async delete(s){let a=await this.openDbPromise;return new Promise((e,t)=>{var r=a.transaction([sx],"readwrite").objectStore(sx),n=this.createCompositeKey(s);try{var i=r.delete(n);i.onerror=e=>{t(ix(e,"storage-delete"))},i.onsuccess=()=>{e()}}catch(e){t(H1.create("storage-delete",{originalErrorMessage:null==e?void 0:e.message}))}})}createCompositeKey(e){return[this.appId,this.appName,this.namespace,e].join()}}class ox{constructor(e){this.storage=e}getLastFetchStatus(){return this.lastFetchStatus}getLastSuccessfulFetchTimestampMillis(){return this.lastSuccessfulFetchTimestampMillis}getActiveConfig(){return this.activeConfig}getCustomSignals(){return this.customSignals}async loadFromStorage(){var e=this.storage.getLastFetchStatus(),t=this.storage.getLastSuccessfulFetchTimestampMillis(),r=this.storage.getActiveConfig(),n=this.storage.getCustomSignals(),e=await e,e=(e&&(this.lastFetchStatus=e),await t),t=(e&&(this.lastSuccessfulFetchTimestampMillis=e),await r),e=(t&&(this.activeConfig=t),await n);e&&(this.customSignals=e)}setLastFetchStatus(e){return this.lastFetchStatus=e,this.storage.setLastFetchStatus(e)}setLastSuccessfulFetchTimestampMillis(e){return this.lastSuccessfulFetchTimestampMillis=e,this.storage.setLastSuccessfulFetchTimestampMillis(e)}setActiveConfig(e){return this.activeConfig=e,this.storage.setActiveConfig(e)}async setCustomSignals(e){this.customSignals=await this.storage.setCustomSignals(e)}}async function lx(){if(!he())return!1;try{return await ue()}catch(e){return!1}}Ct(new u("remote-config",function(e,{instanceIdentifier:t}){var r=e.getProvider("app").getImmediate(),n=e.getProvider("installations-internal").getImmediate();if("undefined"==typeof window)throw H1.create("registration-window");if(!he())throw H1.create("indexed-db-unavailable");var{projectId:i,apiKey:s,appId:a}=r.options;if(!i)throw H1.create("registration-project-id");if(!s)throw H1.create("registration-api-key");if(!a)throw H1.create("registration-app-id");t=t||"firebase";var o=new ax(a,r.name,t),l=new ox(o),h=new $e(K1),n=(h.logLevel=c.ERROR,new tx(n,Dt,t,i,s,a)),i=new rx(n,o),s=new ex(i,o,l,h),a=new nx(r,s,l,o,h);return Y1(a),a},"PUBLIC").setMultipleInstances(!0)),d(K1,"0.5.0"),d(K1,"0.5.0","esm2017");class hx{constructor(e,t){this.app=e,this._delegate=t}get defaultConfig(){return this._delegate.defaultConfig}set defaultConfig(e){this._delegate.defaultConfig=e}get fetchTimeMillis(){return this._delegate.fetchTimeMillis}get lastFetchStatus(){return this._delegate.lastFetchStatus}get settings(){return this._delegate.settings}set settings(e){this._delegate.settings=e}activate(){return Q1(this._delegate)}ensureInitialized(){return Y1(this._delegate)}fetch(){return J1(this._delegate)}fetchAndActivate(){return(async e=>(await J1(e=w(e)),Q1(e)))(this._delegate)}getAll(){return X1(this._delegate)}getBoolean(e){return Z1(w(this._delegate),e).asBoolean()}getNumber(e){return Z1(w(this._delegate),e).asNumber()}getString(e){return Z1(w(this._delegate),e).asString()}getValue(e){return Z1(this._delegate,e)}setLogLevel(e){var t=this._delegate,r=w(t);switch(e){case"debug":r._logger.logLevel=c.DEBUG;break;case"silent":r._logger.logLevel=c.SILENT;break;default:r._logger.logLevel=c.ERROR}}}function ux(e,{instanceIdentifier:t}){var r=e.getProvider("app-compat").getImmediate(),n=e.getProvider("remote-config").getImmediate({identifier:t});return new hx(r,n)}return(KD=tr).INTERNAL.registerComponent(new u("remoteConfig-compat",ux,"PUBLIC").setMultipleInstances(!0).setServiceProps({isSupported:lx})),KD.registerVersion("@firebase/remote-config-compat","0.2.12"),console.warn(`
|
|
18
18
|
It looks like you're using the development build of the Firebase JS SDK.
|
|
19
19
|
When deploying Firebase apps to production, it is advisable to only import
|
|
20
20
|
the individual SDK components you intend to use.
|
|
@@ -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
|
-
`),tr.registerVersion("firebase","11.3.
|
|
26
|
+
`),tr.registerVersion("firebase","11.3.1","compat-cdn"),tr});
|
|
27
27
|
//# sourceMappingURL=firebase-compat.js.map
|